Optimization, global variables and memory-barriers

94 Views Asked by At

In the following example the variable v is not accessible from outside this TU. So the compiler can optimize the loop in main() to an empty loop. This is done with -O3, but with -Os it remains a loop with the load of v outside the loop, so that it is effectively an endless loop without effect.

The function isr() could be optimized away, but is not since it should resemble an ISR and therefore hast the used attribute.

If one changes v to an external visible global, the assemble code remains the same!

How can the compiler reason, that v remains unmodified in this case?

Inserting a memory-barrier sure fixes that in both cases. But why isn't it suffcient to make v external visible?

#include <avr/cpufunc.h>

//int v; 
namespace {
    int v; 
    void isr() 
        __asm__("__vector_5") 
        __attribute__ ((__signal__, 
        __used__
        )); 
    void isr() { 
        v += 1; 
    }
}

int main() {
    while(true) {
//        _MemoryBarrier();
        if (v == 42) { 
            v += 1; 
        }
    }    
}

https://godbolt.org/z/4j7En41sE

0

There are 0 best solutions below