</>EmbeddedInterview

Which compiler optimisations can change how your C code behaves?

HardEmbedded C

An optimiser may transform code in any way that keeps the observable behaviour defined by the C standard. Code that relies on undefined behaviour, or that forgets to tell the compiler about hardware, can change behaviour between -O0 and -O2. The common ones:

  • Caching values in registers / removing loads: a polled flag or register read once and never again. Fix with volatile.
  • Dead-store elimination: writes the compiler thinks nobody reads are removed, such as clearing a key buffer before free or writing a register twice. Fix with volatile or explicit_bzero/memset_s.
  • Reordering: independent loads and stores may be moved, including across a write to a "data ready" flag. Fix with barriers or atomics.
  • Assuming no undefined behaviour: signed overflow cannot happen (so x + 1 > x becomes true), a dereferenced pointer cannot be NULL (so a later NULL check is deleted), shifts are smaller than the type width.
  • Strict aliasing: the compiler assumes an int * and a float * never point to the same memory, so type-punning through pointer casts can read stale values.
  • Loop transformations: empty delay loops are removed entirely; loops become memcpy/memset calls (a problem inside your own memcpy or before .data is initialised).
  • Inlining and constant folding: can change timing and stack usage, and hide functions from the debugger.

The interview point is that the optimiser is not buggy; the code relied on something the language does not promise. Use volatile for hardware, atomics and barriers for concurrency, memcpy for type punning, and compiler warnings and sanitizers (-Wall -Wextra, UBSan) to find undefined behaviour.