cancel
Showing results for 
Search instead for 
Did you mean: 

Are HAL registers defined volatile, and will this prevent optimization?

Lars Beiderbecke
Senior III

Suppose I have the following code snippet:

void some_func() {
  int data = GPIOA->IDR;
  if (data == 0x01)
    func1();
  else if (data == 0x02)
    func2();
}

If optimization is turned on, I would expect the compiler to remove variable data and replace both occurrences of data with GPIOA->IDR -- which is clearly different from the original code.

Hence my question if GPIOA->IDR is defined as volatile. And if it is, is this sufficient to prevent this "optimization", or does variable data need to be volatile as well?

(My IDE would not jump to the declaration of GPIOA->IDR.)

12 REPLIES 12
Pavel A.
Evangelist III

There's also ARM specific reordering, See this PDF page 7 for example. It is from Broadcom, Does STM32 have similar quirks?

-- pa

Data structure element definitions that access peripheral registers typically look like:

  __IO uint32_t IDR;         /*!< GPIO port input data register,         Address offset: 0x10      */

where __IO is #defined as volatile.

Thanks!