
Your firmware passes every test at -O0. You flip the switch to -O2 for the release build and suddenly the device hangs, corrupts data, or lands in HardFault_Handler. The compiler did not break your code: it exposed a bug that was already there.
The most frequent culprit is a variable shared between an ISR and the main loop that is missing volatile. At -O0, the compiler keeps variables in their home memory locations between statements, so the main loop reloads the ISR’s write. At -O2, the compiler hoists that load out of the loop into a register, and your code spins forever on a stale value.
This article explains why that happens, how to spot it in Cortex-M disassembly, and the exact fixes — including when volatile alone is not enough.
Engineers often blame the compiler: “It worked in debug, -O2 broke it.” When undefined behavior (UB) is present, the C standard places no requirements on the program at the point of violation. Optimization makes the consequences visible because the compiler uses language guarantees when folding expressions, eliminating checks, or reordering permitted operations.
A debug build is not a reference implementation of code with UB. Before concluding UB is the cause, also check:
volatile on MMIO and ISR-shared variables+------------------------------------------------------------------+| OPTIMIZATION EXPOSES BUGS |+------------------------------------------------------------------+| || -O0 (Debug) -O2 (Release) || ----------- ------------- || Reloaded from memory Hoisted/cached in registers || Minimal reordering Loads/stores reordered || Checks preserved Dead/redundant code removed || Minimal inlining Aggressive inlining || || Result: ISR write observed Result: ISR write MISSED || Loop re-reads flag Loop spins on cached register || || The bug existed at -O0. Optimization revealed it. || |+------------------------------------------------------------------+
Unless instructed otherwise via volatile or _Atomic, a C compiler optimizes each function assuming objects are modified only along visible control-flow paths without unmodeled asynchronous updates or data races. The compiler has no visibility into hardware interrupt vectors: it sees an ISR (EXTI0_IRQHandler) that is never called from main(). When a polling loop such as while (!flag) { } contains no opaque external calls, compiler barriers, or volatile accesses, the optimizer concludes flag cannot legitimately change between iterations.
#include <stdbool.h>void process_data(void);/* BUG: missing volatile -- works at -O0, fails at -O2 */bool flag = false; // NOT volatile!void EXTI0_IRQHandler(void) {flag = true; // ISR writes to memory}int main(void) {while (!flag) { } // Compiler: "flag never changes in this loop"process_data(); // Unreachable at -O2 if flag was false on entry}
At -O2, GCC targeting ARM Cortex-M loads the 1-byte bool (ldrb, assuming r4 holds &flag) once before the loop instead of on every iteration:
/* Without volatile -- load hoisted out of loop (r4 = &flag) */ldrb r3, [r4] @ Load 1-byte bool flag ONCE into r3cmp r3, #0bne .proceed @ If already non-zero on entry, continue.loop_forever:b .loop_forever @ Spin forever without re-reading memory.proceed:bl process_data
The load is hoisted out of the loop. Even after the ISR writes 1 to flag in SRAM, main() never reads memory again and spins forever in .loop_forever.
With volatile, every iteration is forced to perform a fresh byte load from memory:
/* With volatile -- fresh load every iteration (r4 = &flag) */.loop:ldrb r3, [r4] @ Load flag from memory EACH iterationcmp r3, #0beq .loop @ Re-check memory on next iterationbl process_data
This optimization is not a compiler bug — it is valid behavior under the C abstract machine. Qualifying flag as volatile tells the compiler that accesses to that object have observable side effects outside normal control flow.
In embedded C troubleshooting across Cortex-M families (such as STM32, NXP, and TI devices), these five patterns account for most “works at -O0, fails at -O2” reports.
Symptom: Main loop never exits, a flag set by an ISR is never observed, or adding a printf / function call inside the loop makes the bug disappear (an opaque call forces the compiler to reload non-local globals).
Fix: Qualify bare flags and scalars shared between an ISR and main context as volatile (unless accessed through C11 _Atomic or inside a critical section / compiler barrier). This applies in both directions: if main() writes a non-volatile flag that an ISR reads, -O2 may optimize away the write via dead-store elimination.
#include <stdbool.h>void process_rx_data(void);/* CORRECT: volatile forces re-read every iteration */volatile bool data_ready = false;void UART_IRQHandler(void) {data_ready = true; // ISR writes}int main(void) {while (!data_ready) { // Compiler must reload each iteration/* wait */}process_rx_data();}
Rule: Any bare shared variable polled or modified across main/ISR contexts without _Atomic or barriers must be volatile.
Signed arithmetic overflow is undefined behavior in C17 (6.5/5). At -O0, hardware multiply/add instructions may appear to wrap in two’s complement. At -O2, GCC assumes signed operations in a defined program do not overflow and folds comparisons or eliminates overflow checks based on that assumption.
#include <stdbool.h>#include <stddef.h>#include <stdint.h>/* DANGEROUS: signed multiplication overflows if out of range */int32_t scale_sensor(int32_t raw, int32_t factor) {return raw * factor; // UB if mathematical product overflows int32_t}/* SAFE: widen to int64_t and clamp (int32_t * int32_t always fits in int64_t) */int32_t scale_sensor_safe(int32_t raw, int32_t factor) {int64_t prod = (int64_t)raw * (int64_t)factor;if (prod > INT32_MAX) return INT32_MAX;if (prod < INT32_MIN) return INT32_MIN;return (int32_t)prod;}/* SAFE for GCC/Clang: checked builtin.* Callers must ignore *out when the function returns false. */bool scale_sensor_checked(int32_t raw, int32_t factor, int32_t *out) {if (out == NULL) return false;return !__builtin_mul_overflow(raw, factor, out);}
The builtin evaluates the exact mathematical product in infinite signed precision, casts that result to int32_t (storing the wrapped representation in *out), and returns true if the value could not be represented in int32_t — never invoking UB.
Accessing an object through a pointer to an incompatible effective type violates C’s strict aliasing rules (C17 6.5/7). At -O2 (-fstrict-aliasing is enabled by default), GCC assumes pointers of incompatible types do not alias the same object and may reorder, cache, or eliminate loads and stores.
#include <stdint.h>#include <string.h>/* DANGEROUS: strict aliasing violation on a float object */uint32_t float_bits_unsafe(float f) {return *(const uint32_t *)&f; // UB: incompatible effective type}/* SAFE: memcpy transfers object representation without aliasing UB */uint32_t float_bits_safe(float f) {uint32_t bits;_Static_assert(sizeof(float) == sizeof(uint32_t), "Assumes 32-bit float");memcpy(&bits, &f, sizeof(bits)); // GCC compiles this to a register movereturn bits;}
Character types (char *, unsigned char *, signed char *; on 8-bit-byte platforms uint8_t is typically unsigned char) are exempt from strict aliasing. C unions also permit reading another member for representation inspection under C17 (6.5.2.3), though inactive-member reads are not portable in C++ (use std::bit_cast in C++20). Never use memcpy on volatile memory-mapped peripheral registers, because memcpy drops volatile and may emit unaligned or byte-width accesses unsupported by Device memory.
Reading an uninitialized automatic variable whose value is indeterminate produces undefined behavior in C17 (6.3.2.1p2, notably for automatic variables whose address is never taken). A debug build does not zero-initialize stack slots; apparent zero values are accidental stack residue. Optimization can change register allocation and expose garbage values or trigger dead-code elimination along branches that rely on uninitialized state.
#include <stdbool.h>#include <stdint.h>/* BAD: flags is indeterminate when enable is false */void configure_peripheral_bad(volatile uint32_t *control_reg,bool enable, uint32_t enable_bit) {uint32_t flags;if (enable) flags = enable_bit;*control_reg = flags; // UB if enable == false}/* SAFE: initialized on all paths before MMIO write */void configure_peripheral_safe(volatile uint32_t *control_reg,bool enable, uint32_t enable_bit) {uint32_t flags = 0; // Initialized at declarationif (enable) flags = enable_bit;*control_reg = flags;}
Enable -Wall (which activates -Wuninitialized and, when optimizing, -Wmaybe-uninitialized). These static checks are valuable but not exhaustive, and UBSan does not generally detect reads of uninitialized stack memory.
Accesses outside an array object’s bounds (including dereferencing one-past-the-end) are UB. Off-by-one loop bounds (<= instead of <) and unvalidated length arguments commonly corrupt neighboring stack variables or fault only when -O2 alters stack layout or removes redundant guards.
#include <stdbool.h>#include <stddef.h>#include <stdint.h>void do_something(uint8_t byte);/* DANGEROUS: off-by-one (i == len is OOB) and no capacity check */void process_buffer(const uint8_t *buf, size_t len) {for (size_t i = 0; i <= len; i++) { // Reads 1 byte past buf[len - 1]do_something(buf[i]);}}/* SAFE: validate pointer and length against actual buffer capacity */bool process_buffer_safe(const uint8_t *buf, size_t capacity, size_t len) {if (buf == NULL || len > capacity) return false;for (size_t i = 0; i < len; i++) {do_something(buf[i]);}return true;}
Enable -Warray-bounds=2 at -O2 or higher (value-range propagation is required for full bounds diagnostics).
A volatile peripheral-register update such as REG |= BIT is a read-modify-write (RMW) sequence, not a single indivisible transaction. If main code and an ISR both update the same read/write register, an interrupt between the load and the store causes a lost update (for ordinary non-atomic RAM shared across C threads, concurrent conflicting accesses are also a C data race). Note also that write-1-to-clear (W1C) interrupt status registers must never be updated with |= at all, because writing back 1 to other set bits clears unrelated pending flags.
+----------------------------------+----------------------------------+| MAIN CONTEXT | ISR CONTEXT |+----------------------------------+----------------------------------+| T0: LOAD REG (0x00) | || T1: OR 0x00 | 0x01 -> 0x01 | || <-- interrupted before store | || | T2: LOAD REG (0x00) || | T3: OR 0x00 | 0x08 -> 0x08 || | T4: STORE REG (0x08) || <-- ISR returns | || T5: STORE REG (0x01) | || BIT 3 (0x08) LOST! | |+----------------------------------+----------------------------------+| volatile preserves every load/store, but cannot make RMW atomic. |+---------------------------------------------------------------------+
#include <stdint.h>/* RP2040 Datasheet Section 2.1.2:* Supported peripheral blocks expose +0x1000 (XOR), +0x2000 (SET), +0x3000 (CLR).* Note: SIO does NOT use these bus aliases (SIO GPIO has dedicated _SET/_CLR regs). */static inline void rp2040_reg_set(uintptr_t reg_addr, uint32_t bits) {*(volatile uint32_t *)(reg_addr + UINT32_C(0x2000)) = bits;}static inline void rp2040_reg_clr(uintptr_t reg_addr, uint32_t bits) {*(volatile uint32_t *)(reg_addr + UINT32_C(0x3000)) = bits;}
BSRR)#include <stdint.h>/* Requires the device STM32 CMSIS header (for example, "stm32f4xx.h"). *//* STM32F4 RM0090 Section 8.4.7: GPIOx_BSRR is write-only and atomic.* Bits [15:0] set ODR bits; bits [31:16] reset (clear) ODR bits.* (STM32F4 has no separate BRR register; some other STM32 families also provide BRR.) */static inline void set_pa5(void) {GPIOA->BSRR = (UINT32_C(1) << 5); // Set PA5 atomically}static inline void clear_pa5(void) {GPIOA->BSRR = (UINT32_C(1) << (5 + 16)); // Clear PA5 atomically}
Using UINT32_C(1) instead of signed 1 avoids signed left-shift undefined behavior if a caller resets pin 15 (1 << 31).
PRIMASK)#include <stdint.h>#include "cmsis_compiler.h" // Provides __get_PRIMASK, __disable_irq, __set_PRIMASK/* Save PRIMASK, disable configurable interrupts, update, restore PRIMASK.* Protects against preempting IRQs on this core (not NMI, HardFault, DMA, or other cores). */static inline void critical_section_update(volatile uint32_t *reg, uint32_t bits) {uint32_t primask = __get_PRIMASK();__disable_irq(); // Includes compiler "memory" clobber in CMSIS*reg |= bits;__set_PRIMASK(primask); // Restore previous state (safe when nested)}
Always save and restore PRIMASK rather than unconditionally calling __enable_irq() — nested critical sections must not re-enable interrupts prematurely. In an RTOS (such as FreeRTOS using BASEPRI), use the kernel’s critical-section macros around RTOS-managed data.
_Atomic for Shared RAM (GCC 4.9+, Clang 3.8+)#include <stdatomic.h>#include <stdint.h>#define EVENT_BIT (UINT32_C(1) << 0)_Atomic uint32_t shared_flags = 0;/* Verify lock-free support before calling from an ISR */_Static_assert(ATOMIC_INT_LOCK_FREE == 2 && ATOMIC_LONG_LOCK_FREE == 2,"Requires lock-free 32-bit atomics");/* ISR: atomic fetch-or */void set_event_from_isr(void) {atomic_fetch_or_explicit(&shared_flags, EVENT_BIT, memory_order_relaxed);}/* Main: atomic fetch-and */uint32_t clear_event_from_main(void) {return atomic_fetch_and_explicit(&shared_flags, ~EVENT_BIT, memory_order_relaxed);}
On ARMv7-M (Cortex-M3/M4/M7) and ARMv8-M Mainline (Cortex-M33), GCC compiles lock-free 32-bit _Atomic RMW operations to LDREX/STREX loops that are ISR-safe. However, Cortex-M0/M0+ (ARMv6-M) lacks LDREX/STREX, so _Atomic RMW calls libatomic locking helpers that are unsuitable for ISRs or fail to link in bare metal — check atomic_is_lock_free(&shared_flags) and use PRIMASK critical sections on ARMv6-M. Never use C11 _Atomic on peripheral MMIO registers (LDREX/STREX on Device memory is unsupported/unpredictable), and remember memory_order_relaxed does not order unrelated payload buffers (use memory_order_release/memory_order_acquire for producer-consumer handoff).
When -O2 breaks previously working code, follow this systematic workflow:
Rebuild the same source and configuration with only the optimization level changed. If that reproduces the issue, selectively compile translation units at -O2 to locate the sensitive file.
# Build suspect translation unit at -O2 while keeping others at -O0arm-none-eabi-gcc -O2 -c sensitive.c -o sensitive_O2.oarm-none-eabi-gcc -O0 -c other.c -o other_O0.o# Link and test
Check for differing NDEBUG, LTO (-flto), linker scripts, and compiler versions as separate variables. You can temporarily bisect down to a single function using __attribute__((optimize("O0"))), but never ship that as a substitute for fixing the root bug.
Compile both builds with -g and inspect interleaved C/disassembly via objdump:
arm-none-eabi-objdump -dS firmware_O0.elf > asm_O0.txtarm-none-eabi-objdump -dS firmware_O2.elf > asm_O2.txtdiff -u asm_O0.txt asm_O2.txt | less
Look for:
These differences are clues, not proof of UB.
Run host unit tests with UBSan and AddressSanitizer:
gcc -Og -g -fsanitize=undefined,address -fno-sanitize-recover=all test.c -o test
For Cortex-M target diagnostics without libubsan, use trap-mode UBSan (-fsanitize-trap=undefined in modern GCC, or -fsanitize-undefined-trap-on-error on older GCC):
arm-none-eabi-gcc -mcpu=cortex-m4 -mthumb -Og -g \-fsanitize=signed-integer-overflow,shift,bounds,null,integer-divide-by-zero \-fsanitize-trap=undefined \-c firmware.c -o firmware_ubsan.o
On ARMv7-M/ARMv8-M Mainline, a trap compiles to an undefined instruction (UDF), raising UsageFault (if enabled via SCB->SHCSR) or escalating to HardFault; on Cortex-M0/M0+ (ARMv6-M), UDF enters HardFault directly. Inspect the disassembly and capture the stacked PC.
Add a naked HardFault_Handler stub so the compiler does not emit a stack-pushing prologue that corrupts MSP before reading the exception frame (for ARMv7-M/ARMv8-M Mainline such as Cortex-M3/M4/M7/M33; Cortex-M0/M0+ lacks ite and CFSR/HFSR/MMFAR/BFAR):
#include <stdint.h>/* Requires the device CMSIS core header (providing SCB and SCB_CFSR_*_Msk). */__attribute__((used))void hard_fault_c(const uint32_t *stack) {uint32_t r0 = stack[0];uint32_t r1 = stack[1];uint32_t r2 = stack[2];uint32_t r3 = stack[3];uint32_t r12 = stack[4];uint32_t lr = stack[5];uint32_t pc = stack[6];uint32_t xpsr = stack[7];uint32_t cfsr = SCB->CFSR; // Configurable Fault Status Registeruint32_t hfsr = SCB->HFSR; // HardFault Status Registeruint32_t mmfar = (cfsr & SCB_CFSR_MMARVALID_Msk) ? SCB->MMFAR : 0U;uint32_t bfar = (cfsr & SCB_CFSR_BFARVALID_Msk) ? SCB->BFAR : 0U;(void)r0; (void)r1; (void)r2; (void)r3;(void)r12; (void)lr; (void)pc; (void)xpsr;(void)hfsr; (void)mmfar; (void)bfar;// Log cfsr, hfsr, mmfar, bfar, pc, lr to UART/RTT/flash, then haltwhile (1) { __asm volatile("bkpt #0"); }}__attribute__((naked))void HardFault_Handler(void) {__asm volatile ("tst lr, #4\n" // Check EXC_RETURN bit 2 (0 = MSP, 1 = PSP)"ite eq\n""mrseq r0, msp\n" // MSP was active"mrsne r0, psp\n" // PSP was active"b hard_fault_c\n");}
Correlate the stacked pc and lr with the .map file and disassembly. Check ISR/task interactions, volatile qualifiers, DMA cache coherence, and timing assumptions.
Match the symptom to the likely cause:
Symptom at -O2 | Likely Cause | Fix |
|---|---|---|
| Arithmetic gives wrong result | Signed overflow | Widen/clamp, __builtin_mul_overflow, or unsigned |
| Bit mask evaluates to 0 | Invalid shift count / signed shift | Use UINT32_C(1) << n and check n < 32 |
| Type-punned value corrupted | Strict aliasing violation | memcpy (RAM only) or C union |
| Variable holds garbage | Uninitialized read | Initialize at declaration |
| Loop skips/extra iterations | OOB array access | Validate bounds, enable -Warray-bounds=2 |
| ISR register update lost | Peripheral RMW race | Atomic alias, BSRR, or PRIMASK critical section |
| Flag never observed | Missing volatile on ISR-shared | Add volatile (or _Atomic for lock-free RAM) |
Once the codebase is warning-clean, consider -Werror in CI:
arm-none-eabi-gcc -std=c17 -mcpu=cortex-m4 -mthumb -O2 \-Wall -Wextra \-Wshift-overflow=2 \-Wconversion -Wsign-conversion -Wnull-dereference \-Warray-bounds=2 -Wstrict-aliasing=2 \-Werror=implicit-function-declaration \-c firmware.c -o firmware.o
-Wall enables -Wuninitialized and (with optimization on) -Wmaybe-uninitialized-Wshift-overflow=2 additionally diagnoses left-shifting 1 into the sign bit (such as 1 << 31 on 32-bit int) in C11/C17 mode-Warray-bounds=2 requires -O2 or higher (VRP analysis), and -Wstrict-aliasing=2 requires -fstrict-aliasing (enabled at -O2)volatile Is Not Enoughvolatile prevents the compiler from omitting or caching memory accesses, but does not guarantee atomicity or hardware bus ordering.
#include <stdint.h>/* DANGEROUS: non-atomic 64-bit access on a 32-bit Cortex-M core */volatile uint64_t system_timestamp;void SysTick_Handler(void) {system_timestamp++; // Multi-instruction 32-bit load/add/store}uint64_t get_timestamp(void) {return system_timestamp; // Two 32-bit LDRs (or LDRD); can tear if interrupted}
On ARMv7-M, neither a pair of LDR instructions nor LDRD is single-copy atomic across all 64 bits. If SysTick_Handler preempts get_timestamp() between the low-word and high-word reads (for instance across a 0x00000000FFFFFFFF to 0x0000000100000000 carry), get_timestamp() returns a torn 64-bit value.
Option 1: Disable Interrupts (Simple, Guaranteed on Single Core)
#include <stdint.h>#include "cmsis_compiler.h"extern volatile uint64_t system_timestamp;uint64_t get_timestamp(void) {uint32_t primask = __get_PRIMASK();__disable_irq();uint64_t ts = system_timestamp;__set_PRIMASK(primask);return ts;}
Option 2: Double-Read Consistency (No Interrupt Disable, Sole Monotonic ISR Writer)
#include <stdint.h>extern volatile uint64_t system_timestamp;uint64_t get_timestamp(void) {uint64_t a, b;do {a = system_timestamp;b = system_timestamp;} while (a != b);return a;}
Option 2 requires that the ISR is the sole monotonic writer, that updates occur much less frequently than the read loop (otherwise it can spin indefinitely under pathological IRQ rates), and that the read sequence is not preempted for 2^32 ticks between reads.
Two volatile accesses are sequenced relative to each other by the compiler, but a volatile access and a non-volatile access have no such ordering guarantee:
#include <stdint.h>volatile uint8_t flag;uint8_t buffer[64];/* COMPILER MAY REORDER: flag = 1 emitted before buffer[0] is written */void publish_bad(uint8_t received_byte) {buffer[0] = received_byte; // Non-volatile writeflag = 1; // Volatile write}
Place a compiler barrier (__asm volatile("" ::: "memory") or CMSIS __COMPILER_BARRIER()) between the non-volatile payload and the volatile flag on both producer and consumer sides (so the consumer cannot speculatively read buffer[0] before checking flag), or prefer C11 _Atomic with memory_order_release / memory_order_acquire:
void publish_good(uint8_t received_byte) {buffer[0] = received_byte;__asm volatile("" ::: "memory"); // Compiler barrier: prevents compile-time reorderingflag = 1;}uint8_t consume_good(uint8_t fallback) {if (flag == 0U) {return fallback;}__asm volatile("" ::: "memory"); // Prevent speculative load before flag checkreturn buffer[0];}
On a single-core CPU communicating with its own ISR, a compiler barrier suffices because exception entry/return preserves single-core program-order visibility. However, if DMA or a second core reads buffer and flag in Normal SRAM, a compiler barrier alone is not enough: insert __DMB() (hardware Data Memory Barrier) and, on D-cache cores like Cortex-M7, perform cache maintenance (SCB_CleanDCache_by_Addr() / SCB_InvalidateDCache_by_Addr()).
| Problem | Detection | Fix |
|---|---|---|
Missing volatile on ISR flag | Loop never exits at -O2 | Add volatile (or lock-free _Atomic in RAM) |
| Signed integer overflow | Wrong result at -O2 | Widen, clamp, or __builtin_mul_overflow |
| Strict aliasing violation | Corrupted type-punned value | memcpy (RAM only) or C union |
| Uninitialized variable | Garbage value, non-deterministic | Initialize at declaration |
| OOB array access | Crash / corruption at -O2 | Check pointer/capacity, enable -Warray-bounds=2 |
| Peripheral RMW race | Lost bit updates | Atomic alias, BSRR, or PRIMASK critical section |
| 64-bit torn read | Impossible timestamp values | PRIMASK critical section or double-read check |
| Compiler reordering | Flag set before payload ready | Compiler barrier (plus __DMB() for DMA/multicore) |
Key takeaways:
-O2 is evidence to investigate, not a compiler bug; optimization exposes latent UB, missing volatile, concurrency races, or stack/timing assumptionsvolatile prevents load hoisting and dead-store elimination, but does not provide atomicity or hardware bus orderingBSRR set/reset registers (STM32), short PRIMASK critical sections, or verified lock-free C11 _Atomic (ARMv7-M/v8-M Mainline RAM only) for concurrent updates-Wall -Wextra -Wshift-overflow=2 -Warray-bounds=2 -Wstrict-aliasing=2 with -O2 in CI-fsanitize-trap=undefined) on target builds, and always validate the optimized production configuration before deploymentQuick Links
Legal Stuff





