Optimized code debugging

Problems that only surface during optimization are often an indication of logic errors or compile errors that are exposed by optimization, for example using a variable that has not been initialized. If you encounter an error in your program that only occurs in the optimized version, you can usually find the cause of the error using a binary search technique to find the failing module:

  1. Begin by optimizing half the modules and see if the error persists.
  2. After each change in the number of optimized modules, if the error persists, optimize fewer modules; if the error goes away, optimize more modules. Eventually you will have narrowed the error down to a single module or a small number of modules.
  3. Debug the failing module. If possible, turn off the instruction scheduling optimizations for that module. Look for problems such as reading from a variable before it has been written to, and pointers or array indices exceeding the bounds of storage allocated for the pointer or array.

When you debug optimized code, information in debugger panes may lead you to suspect logic problems that do not actually exist. You should bear in mind the points below:

Local variables are not always current

Do not rely on the Local variables monitor to show the current values of variables. Numeric values, character values and pointers may be kept in processor registers. In the optimized program, these values and pointers are not always written out to memory; in some cases, they may be discarded because they are not needed.

Static and external variables are not always current

Within an optimized function, the values of static or external variables are not always written out to memory.

Registers and Storage monitors are always current

The Registers and Storage monitors are correct. Unlike a monitor that shows actual variables, such as the Locals Variables monitor, the Registers and Storage monitors are always up-to-date as of the last time execution stopped.

Source statements may be optimized away

Using the disassembly view or mixed view to see the machine code for your program, you may find, for example, that an assignment to a variable in your source code does not result in any disassembly code being produced; this may indicate that the variable's value is never used after the assignment.