Is it allowed for a compiler to optimize away a local volatile variable?

后端 未结 6 1132
天命终不由人
天命终不由人 2020-12-05 09:25

Is the compiler allowed to optimize this (according to the C++17 standard):

int fn() {
    volatile int x = 0;
    return x;
}

to this?

6条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-05 10:00

    This loop can be optimised away by the as-if rule because it has no observable behaviour:

    for (unsigned i = 0; i < n; ++i) { bool looped = true; }
    

    This one cannot:

    for (unsigned i = 0; i < n; ++i) { volatile bool looped = true; }
    

    The second loop does something on every iteration, which means the loop takes O(n) time. I have no idea what the constant is, but I can measure it and then I have a way of busy looping for a (more or less) known amount of time.

    I can do that because the standard says that access to volatiles must happen, in order. If a compiler were to decide that in this case the standard didn't apply, I think I would have the right to file a bug report.

    If the compiler chooses to put looped into a register, I suppose I have no good argument against that. But it still must set the value of that register to 1 for every loop iteration.

提交回复
热议问题