Device Family: Excalibur

Type: Answers

Area: Embedded

Area: Tools



Why do multiple reads to my peripheral get optimized away by the Nios GCC compiler?

Description

Reads from peripherals are often accomplished through the use of pointers. For example, the following code reads the value stored at peripheral_base_address and places it in the read_value variable.

int *pointer_to_peripheral = (int *)(peripheral_base_address);read_value = *pointer_to_peripheral;

However, multiple reads from the same address can be optmized away. For example, for the code below, the Nios CPU will read the data value from the peipheral_base_address and copy it into both read_value and read_value2. However, the data value at the peripheral_base_address may have changed between reads and the new data value would not be read.

int *pointer_to_peripheral = (int *)(peripheral_base_address);;
read_value = *pointer_to_peripheral;
read_value2 = *pointer_to_peripheral;

All pointers should be declared as volatile types to prevent subsequent reads from being optimized away by the gcc compiler. The pointers used above should be declared as follows:

volatile int *pointer_to_peripheral = (int *)(peripheral_base_address);