Pointer aliasing refers to the situation where the same memory location can be
accessed using different pointer names. The strict aliasing rule in C/C++ means that
pointers are assumed not to alias if they point to fundamentally different types.
Aliasing introduces strong constraints on program execution order. The following shows
the aliasing of p
and q
.
The following is an example of pointer aliasing, in which both the pointers
p
and q
point to
the same address. The assembly language code produced by the compiler is shown in the
middle column, and the operations and clock cycles are shown on the right.
By adding the restrict keyword into this code example, the compiler can optimize the resulting assembly language to increase parallelization of the operations in hardware. The following example shows that using the restrict keyword to prevent aliasing uses fewer clock cycles to complete the same operation.
Memory Dependencies
Memory dependencies in the code can limit the kinds of optimizations
attempted by the compiler. For example in the following code, xyz
and pointers p
and q
might be unrelated. However, within the
function code both pointer p
and pointer q
point to same global variable xyz
. The compiler must guarantee the correct execution
under both these conditions. Due to these kinds of memory dependencies the compiler
needs to be conservative and limit optimizations.