Before optimizing embedded systems software, it is necessary to have a good understanding of how the AVR® microcontroller (MCU) core is structured and what strategies the AVR GNU Compiler Collection (GCC) uses to generate efficient code for the processor.
Optimization Overview
Atmel AVR 8-bit architecture
AVR uses the Harvard architecture – with separate memories and buses for program and data. It has a fast-access register file of 32 x 8 general purpose working registers with a single clock cycle access time. The 32 working registers are one of the keys to efficient C coding. These registers have the same function as the traditional accumulator, except that there are 32 of them. The AVR arithmetic and logical instructions work on these registers, hence they take up less instruction space. In one clock cycle, AVR can feed two arbitrary registers from the register file to the ALU, perform an operation, and write back the result to the register file.
Instructions in the program memory are executed with a single level pipelining. While one instruction is being executed, the next instruction is pre-fetched from the program memory. This concept enables instructions to be executed in every clock cycle. Most AVR instructions have a single 16-bit word format. Every program memory address contains a 16- or 32-bit instruction.
AVR GCC
AVR GCC provides several optimization levels. They are -O0, -O1, -O2, -O3 and -Os. In each level, there are different optimization options enabled, except for -O0 which means no optimization. Besides the options enabled in optimization levels, you can also enable separate optimization options to get specific optimization. The GNU Compiler Collection manual has a complete list of optimization options and levels.
Aside from the AVR GCC, it takes many other tools working together to produce the final executable application for the AVR microcontroller. The group of tools is called a toolchain. Within the AVR toolchain, AVR Libc Library which provides many of the same functions found in a standard C library and many additional library functions specific to an AVR. In addition, the library provides the basic startup code needed by most applications. Please check the AVR Libc Reference Manual for more details.