117

Consider the following function:

void func(bool& flag)
{
    if(!flag) flag=true;
}

It seems to me that if flag has a valid boolean value, this would be equivalent to unconditional setting it to true, like this:

void func(bool& flag)
{
    flag=true;
}

Yet neither gcc nor clang optimize it this way — both generate the following at -O3 optimization level:

_Z4funcRb:
.LFB0:
    .cfi_startproc
    cmp BYTE PTR [rdi], 0
    jne .L1
    mov BYTE PTR [rdi], 1
.L1:
    rep ret

My question is: is it just that the code is too special-case to care to optimize, or are there any good reasons why such optimization would be undesired, given that flag is not a reference to volatile? It seems the only reason which might be is that flag could somehow have a non-true-or-false value without undefined behavior at the point of reading it, but I'm not sure whether this is possible.

4
  • 8
    Do you have any evidence that it's an "optimization"? Oct 28, 2016 at 20:51
  • 1
    @200_success I don't think that putting a line of code with non-working markup as a title is a good thing. If you want a more specific title, fine but choose an English sentence, and try to avoid code in it (e.g. why don't compilers optimize conditional writes to unconditional writes when they can prove them to be equivalent? or similar). Also since backticks aren't rendered don't use them in the title even if you use code.
    – Bakuriu
    Oct 28, 2016 at 22:08
  • 2
    @Ruslan, while it doesn't seem to do this optimization for the function itself, when it can inline the code, it does seem to do so for the inlined version. Often just resulting in a compile time constant of 1 being used. godbolt.org/g/swe0tc
    – Evan Teran
    Oct 29, 2016 at 20:41
  • I closed this as a duplicate of a newer question (Why do none of the major compilers optimize this conditional store that checks if the value is already set?) because I think my answer there covers the same points brought up by the answers here (and other things they didn't), but in more detail and citing references that it's not UB to cast away const, thus compilers must respect the possibility. Perhaps the questions should be merged. May 19 at 9:30

3 Answers 3

104

This may negatively impact the performance of the program due to cache coherence considerations. Writing to flag each time func() is called would dirty the containing cache line. This will happen regardless of the fact that the value being written exactly matches the bits found at the destination address before the write.


EDIT

hvd has provided another good reason that prevents such an optimization. It is a more compelling argument against the proposed optimization, since it may result in undefined behavior, whereas my (original) answer only addressed performance aspects.

After a little more reflection, I can propose one more example why compilers should be strongly banned - unless they can prove that the transformation is safe for a particular context - from introducing the unconditional write. Consider this code:

const bool foo = true;

int main()
{
    func(const_cast<bool&>(foo));
}

With an unconditional write in func() this definitely triggers undefined behavior (writing to read-only memory will terminate the program, even if the effect of the write would otherwise be a no-op).

18
  • 10
    It may also impact positively on performance since you get rid of a branch. So I don't think this particular case is meaningful to discuss without a very specific system in mind.
    – Lundin
    Oct 28, 2016 at 10:46
  • 3
    @Yakk behavior definedness is not affected by the target platform. Saying that it will terminate the program is incorrect, but the UB itself can have far-reaching consequences, including nasal demons. Oct 28, 2016 at 14:13
  • 18
    @Yakk That depends on what one means by "read-only memory". No, it's not in a ROM chip, but it is very often in a section loaded to a page that does not have write access enabled, and you will get e.g. a SIGSEGV signal or STATUS_ACCESS_VIOLATION exception when you try to write to it.
    – Random832
    Oct 28, 2016 at 14:19
  • 6
    "this definitely triggers undefined behavior". No. Undefined behavior is a property of the abstract machine. It is what the code says that determines whether UB is present. Compilers cannot cause it (though if buggy a compiler can cause programs to behave incorrectly). Oct 28, 2016 at 17:36
  • 8
    It is the casting-away of const to pass into a function that may modify the data that is the source of the undefined behavior, not the unconditional write. Doctor, it hurts when I do this....
    – Spencer
    Oct 29, 2016 at 2:02
49

Aside from Leon's answer on performance:

Suppose flag is true. Suppose two threads are constantly calling func(flag). The function as written, in that case, does not store anything to flag, so this should be thread-safe. Two threads do access the same memory, but only to read it. Unconditionally setting flag to true means two different threads would be writing to the same memory. This is not safe, this is unsafe even if the data being written is identical to the data that's already there.

23
  • 10
    I think this is a result of applying [intro.races]/21.
    – Griwes
    Oct 28, 2016 at 11:08
  • 10
    Very interesting. So I read this as: The compiler is never allowed to "optimize in" a write operation where the abstract machine wouldn't have one.
    – Martin Ba
    Oct 28, 2016 at 11:24
  • 3
    @MartinBa Mostly so. But if the compiler can prove that it doesn't matter, for example because it can prove that no other thread could possibly have access to that particular variable, then it may be okay.
    – user743382
    Oct 28, 2016 at 11:38
  • 14
    This is only unsafe if the system the compiler is targeting makes it unsafe. I have never developed on a system where writing 0x01 to a byte that is already 0x01 causes "unsafe" behavior. On a system with word or dword memory access it would; but the optimizer should be aware of this. On a modern PC or phone OS, no problem occurs. So this isn't a valid reason. Oct 28, 2016 at 13:31
  • 4
    @Yakk Actually, thinking even more, I think this is right after all, even for common processors. I think you're right when the CPU can write to the memory directly, but suppose flag is in a copy-on-write page. Now, at the CPU level, the behaviour might be defined (page fault, let the OS handle it), but at the OS level, it may still be undefined, right?
    – user743382
    Oct 28, 2016 at 15:44
14

I am not sure about the behaviour of C++ here, but in C the memory might change because if the memory contains a non-zero value other than 1, it would remain unchanged with the check, but changed to 1 with the check.

But as I am not very fluent in C++, I don't know if this situation is even possible.

8
  • Would this still be true about _Bool?
    – Ruslan
    Oct 28, 2016 at 12:42
  • 6
    In C, if the memory contains a value that the ABI doesn't say is valid for its type, then it's a trap representation, and reading a trap representation is undefined behaviour. In C++, this could only happen when reading an uninitialised object, and it's reading an uninitialised object that's UB. But if you can find an ABI that says any non-zero value is valid for type bool/_Bool and means true, then in that particular ABI, you're probably right.
    – user743382
    Oct 28, 2016 at 13:07
  • 1
    @Ruslan With compilers that use the Itanium ABI, and on ARM processors, C _Bool and C++ bool are either the same type, or compatible types that follow the same rules. With MSVC, they have the same size and alignment, but there's no official statement about whether they use the same rules. Oct 28, 2016 at 16:37
  • 1
    @JustinTime: C's <stdbool.h> includes a typedef _Bool bool; And yes, on x86 (at least in the System V ABI), bool/_Bool are required to be either 0 or 1, with the upper bits of the byte cleared. I don't think this explanation is plausible. Nov 1, 2016 at 14:07
  • 1
    @JustinTime: That's true, I should have just pointed out that it definitely does have the same semantics in the all the x86 flavours of the System V ABI, which is what this question was about. (I can tell because the first arg to func was passed in RDI, while Windows would use RDX). Nov 2, 2016 at 0:10

Not the answer you're looking for? Browse other questions tagged or ask your own question.