Skip to content
binshelf/ cpp

Search lessons

Type a C++ term, like vector, reference, unique_ptr or use-after-free.

    Lessons

    On this page

    1. Key terms
    2. In 30 seconds
    3. Seeing what the compiler made
    4. Registers and the calling convention
    5. Branches and loops
    6. Optimization levels
    7. What the optimizer does
    8. Inlining, constant folding and dead code
    9. Loop unrolling and vectorization
    10. Undefined behavior lets the optimizer delete code
    11. [[likely]] and [[unlikely]]
    12. Which one should I use?
    13. Under the hood
    14. Common pitfalls
    15. Timing code that the optimizer removed
    16. Judging speed from an -O0 build
    17. Try it yourself

    Module 9 · Performance

    9.3Optimization levels and reading assembly

    See what the compiler makes of your code. Learn what -O0 to -O3 change, read short x86-64 assembly listings, and watch the optimizer fold constants, inline calls, unroll loops and delete code that relies on undefined behavior.

    About 35 minutesIntermediate

    On this page
    1. Key terms
    2. In 30 seconds
    3. Seeing what the compiler made
    4. Registers and the calling convention
    5. Branches and loops
    6. Optimization levels
    7. What the optimizer does
    8. Inlining, constant folding and dead code
    9. Loop unrolling and vectorization
    10. Undefined behavior lets the optimizer delete code
    11. [[likely]] and [[unlikely]]
    12. Which one should I use?
    13. Under the hood
    14. Common pitfalls
    15. Timing code that the optimizer removed
    16. Judging speed from an -O0 build
    17. Try it yourself

    Key terms

    assembly
    The text form of machine code: one CPU instruction per line, such as add eax, esi. g++ -S writes it to a .s file.
    register
    A small, very fast storage slot inside the CPU, such as eax or rdi. Most instructions read and write registers.
    calling convention
    The rules for where a function finds its arguments and leaves its result. On 64-bit Linux, the first integer arguments arrive in rdi, rsi, rdx, rcx, r8, r9, and an integer result goes in eax or rax.
    optimization level (-O0 to -O3, -Os, -Og)
    How hard the optimizer works. -O0 translates line by line, -O2 is the usual release level, -O3 tries harder on loops, -Os prefers small code and -Og keeps debugging easy.
    inlining
    Replacing a function call with a copy of the function's body. It saves the call and lets the optimizer simplify the body with the caller's values.
    constant folding
    Working out an expression while compiling, when its values are known, so the program holds only the answer.
    loop unrolling
    Repeating a loop's body several times per pass, so the loop checks its condition less often. A short loop with a fixed count can disappear entirely.
    link-time optimization (LTO)
    Optimizing the whole program while linking (-flto), so a function in one source file can be inlined into another.

    The compiler doesn’t translate your code line by line. With optimization on, it rewrites the program into something faster that gives the same results, as long as the program has no undefined behavior. Reading the assembly it produces is how you find out what really runs: whether a call was inlined, whether a loop uses the CPU’s wide instructions, or whether a check you wrote is still there.

    In 30 seconds

    • -O0 (the default) barely optimizes. -O2 is the usual level for release builds; -O3 works harder on loops, -Os keeps code small and -Og keeps debugging easy.
    • Assembly is one CPU instruction per line. On 64-bit Linux, a function finds its first arguments in rdi, rsi, rdx… and returns an integer in eax.
    • The optimizer folds constants, inlines calls, deletes unused work, unrolls loops and processes several values at once.
    • It also assumes undefined behavior never happens, so it can delete a check that comes too late.

    Seeing what the compiler made

    g++ -S stops after compiling and writes assembly to a .s file instead of an object file. -masm=intel picks the Intel spelling of the instructions, which most documentation uses:

    g++ -std=c++23 -O2 -S -masm=intel square.cpp   # writes square.s
    objdump -d -M intel --no-show-raw-insn app     # the same, from a built program
    

    The raw .s file is full of lines for the assembler, starting with .. The listings on this page drop those, the way Compiler Explorer (godbolt.org) does: each example on this site has a button that opens it there, with the same compiler and flags, and you can change the code and watch the assembly change.

    Here is one function at -O0, the default:

    int square(int x) {
        return x * x;
    }

    Assembly (GCC 15, -O0)

    square(int):
        push    rbp
        mov     rbp, rsp
        mov     DWORD PTR -4[rbp], edi
        mov     eax, DWORD PTR -4[rbp]
        imul    eax, eax
        pop     rbp
        ret

    Each line is an instruction followed by its operands. With Intel syntax, the destination comes first: mov eax, edi copies edi into eax.

    • square(int): is a label: the address where the function’s code starts. push rbp, mov rbp, rsp and pop rbp set up and tear down its stack frame (Stack, heap and lifetime).
    • mov DWORD PTR -4[rbp], edi stores the argument x into the stack frame. DWORD PTR means “4 bytes of memory”, and -4[rbp] means “the address in rbp, minus 4”. Other tools write it [rbp-4].
    • mov eax, DWORD PTR -4[rbp] loads it straight back. imul eax, eax multiplies eax by itself. ret returns to the caller, which finds the result in eax.

    At -O0, every variable lives in memory, so a debugger can show and change it at any line. That’s why -O0 code is slow. The same function at -O2:

    int square(int x) {
        return x * x;
    }

    Assembly (GCC 15, -O2)

    square(int):
        imul    edi, edi
        mov     eax, edi
        ret

    Three instructions, and no memory at all.

    Registers and the calling convention

    x86-64 CPUs have 16 general-purpose 64-bit registers. Each has names for its parts: rax is the whole 64 bits and eax its lower 32, which is why an int shows up as eax or edi. Floating-point values use separate registers, xmm0 to xmm15.

    A function and its callers must agree on where arguments and results go. That agreement is the calling convention. Linux and macOS use the System V convention; 64-bit Windows uses a different one.

    WhatWhere (System V, x86-64)
    Integer and pointer arguments 1 to 6rdi, rsi, rdx, rcx, r8, r9 (edi, esi, … for 32-bit values)
    float and double arguments 1 to 8xmm0 to xmm7
    Integer or pointer resultrax (eax for 32 bits)
    float or double resultxmm0

    With that table, short functions read almost like the C++:

    int add(int a, int b) {
        return a + b;
    }
    
    int third(const int* values) {
        return values[2];
    }
    
    long offset_of(long row, long column) {
        return row * 4 + column + 7;
    }
    
    double scale(double x, double factor) {
        return x * factor;
    }

    Assembly (GCC 15, -O2)

    add(int, int):
        lea     eax, [rdi+rsi]
        ret
    third(int const*):
        mov     eax, DWORD PTR 8[rdi]
        ret
    offset_of(long, long):
        lea     rax, 7[rsi+rdi*4]
        ret
    scale(double, double):
        mulsd   xmm0, xmm1
        ret
    • add uses lea (“load effective address”). It was made for computing addresses, but it adds a register, another register times 1, 2, 4 or 8, and a constant in one instruction, without touching memory. Compilers use it as a fast adder: eax = rdi + rsi.
    • third gets the pointer in rdi. values[2] is 8 bytes past it, because each int is 4 bytes, so mov loads 4 bytes from rdi + 8.
    • offset_of does a multiply and two additions with one lea: rax = rsi + rdi * 4 + 7.
    • scale gets its two doubles in xmm0 and xmm1. mulsd (“multiply scalar double”) multiplies them and leaves the result in xmm0, where the caller expects it.

    Branches and loops

    An if or a loop becomes a comparison followed by a jump. This function returns the position of the first unknown base, N, in a read:

    int find_n(const char* read, int length) {
        for (int i = 0; i < length; ++i) {
            if (read[i] == 'N') {
                return i;
            }
        }
        return -1;
    }

    Assembly (GCC 15, -O2)

    find_n(char const*, int):
        test    esi, esi
        jle     .L5
        movsxd  rsi, esi
        xor     eax, eax
        jmp     .L4
    .L8:
        add     rax, 1
        cmp     rsi, rax
        je      .L5
    .L4:
        cmp     BYTE PTR [rdi+rax], 78
        jne     .L8
        ret
    .L5:
        mov     eax, -1
        ret
    • cmp a, b compares two values and sets the CPU’s flags; test esi, esi does the same for “is esi zero or negative?”. The jump after it reads the flags: jle jumps if less or equal, je if equal, jne if not equal. jmp always jumps. .L4, .L5 and .L8 are labels the compiler made up for jump targets.
    • If length is 0 or less, the function jumps straight to .L5 and returns -1. Otherwise movsxd widens length to 64 bits and xor eax, eax sets the counter to 0 (XOR of a value with itself is 0, in a short instruction).
    • The loop is .L4 and .L8: compare one byte at rdi + rax with 78, the code for 'N'. If it matches, return; rax already holds i. If not, add 1, and stop when the counter reaches length.

    The compiler moved the loop’s test to the bottom and the 'N' check to the top, so each pass costs one compare-and-jump for the base and one for the count. Reading a loop’s assembly mostly means finding that backward jump.

    Optimization levels

    LevelWhat it does
    -O0Almost nothing. Every variable is in memory and every line has its own instructions. Fast to compile, easy to debug, slow to run.
    -OgOptimizations that don’t get in the way of a debugger. A good level for day-to-day debugging.
    -O1The cheap, safe optimizations: keeping values in registers, removing unused work, simple inlining.
    -O2Nearly everything that doesn’t trade code size for speed. The usual level for release builds. GCC 15 also vectorizes simple loops at this level, when it’s sure that pays.
    -O3-O2 plus more aggressive inlining, unrolling and vectorization. Often faster for loops over numbers; sometimes slower, because the code grows.
    -OsLike -O2, but avoids anything that makes the code bigger.

    Each level is a bundle of individual optimizations that you can also turn on or off one at a time (-funroll-loops, -fno-inline, …). Try find_n with -Os in Compiler Explorer: the loop gets shorter but checks the count at the top of every pass, with an extra jump.

    What the optimizer does

    Inlining, constant folding and dead code

    static int sum_to(int n) {
        int total = 0;
        for (int i = 1; i <= n; ++i) {
            total += i;
        }
        return total;
    }
    
    int sum_to_ten() {
        return sum_to(10);
    }

    Assembly (GCC 15, -O2)

    sum_to_ten():
        mov     eax, 55
        ret

    Three things happened. Inlining copied the body of sum_to into sum_to_ten, where n is known to be 10. Constant folding then ran the loop while compiling and kept only the answer, 55. Finally, sum_to itself is gone: it’s static, so no other file can call it (Headers and the one-definition rule), and no call is left in this one. Removing code or work whose result nobody uses is dead code elimination. A function that isn’t static keeps its own copy even when every call to it was inlined, because another file might call it.

    Loop unrolling and vectorization

    A loop with a short, fixed count often disappears. Loop unrolling copies the body once per pass, so there’s no counter and no jump left. At -O2, GCC 15 then goes one step further with this loop:

    int sum4(const int* values) {
        int total = 0;
        for (int i = 0; i < 4; ++i) {
            total += values[i];
        }
        return total;
    }

    Assembly (GCC 15, -O2)

    sum4(int const*):
        movdqu  xmm0, XMMWORD PTR [rdi]
        movdqa  xmm1, xmm0
        psrldq  xmm1, 8
        paddd   xmm0, xmm1
        movdqa  xmm1, xmm0
        psrldq  xmm1, 4
        paddd   xmm0, xmm1
        movd    eax, xmm0
        ret

    There’s no loop. movdqu loads all four ints (16 bytes, an XMMWORD) into one xmm register at once. psrldq shifts a copy of the register right by 8 bytes, so paddd, which adds four pairs of ints in one instruction, adds the top two values to the bottom two. A second shift and add combine the last two, and movd moves the total into eax. Using one instruction on several values is vectorization. The next lesson, SIMD, shows when the compiler does it, what stops it, and how to write it yourself.

    Undefined behavior lets the optimizer delete code

    The optimizer is allowed to assume your program has no undefined behavior (Undefined behavior, assertions and sanitizers). Here are two functions whose checks rely on it:

    bool add_overflows(int count, int extra) {
        int total = count + extra;
        return total < count;
    }
    
    int first_or_zero(const int* values) {
        int first = *values;
        if (values == nullptr) {
            return 0;
        }
        return first;
    }

    Assembly (GCC 15, -O2)

    add_overflows(int, int):
        shr     esi, 31
        mov     eax, esi
        ret
    first_or_zero(int const*):
        mov     eax, DWORD PTR [rdi]
        ret
    • add_overflows never adds. Signed overflow can’t happen in a valid program, so count + extra < count is true exactly when extra is negative. shr esi, 31 shifts extra right by 31 bits, which leaves only its sign bit: 1 if it’s negative, 0 if not. A real overflow goes unnoticed.
    • first_or_zero reads *values first. Reading through a null pointer is undefined, so after that line values can’t be null, and the check is gone. Only the load is left.

    Neither is a compiler bug. The checks come after the undefined behavior they were meant to catch, so the compiler treats them as always false. The sanitizers catch the null read at run time:

    #include <print>
    
    int first_or_zero(const int* values) {
        int first = *values;
        if (values == nullptr) {
            return 0;
        }
        return first;
    }
    
    int main() {
        std::println("{}", first_or_zero(nullptr));
    }

    This fails when it runs

    main.cpp:4:9: runtime error: load of null pointer of type 'const int'

    The fix in both cases is to check before the operation that could be undefined: test the pointer before reading through it, and compare count with std::numeric_limits<int>::max() - extra before adding, as 5.3 showed.

    [[likely]] and [[unlikely]]

    C++20’s [[likely]] and [[unlikely]] attributes tell the compiler which way a branch usually goes. They don’t change what the program does, only how the code is laid out:

    void report_bad_quality(int quality);
    
    int scaled_quality(int quality) {
        if (quality < 0) [[unlikely]] {
            report_bad_quality(quality);
            return 0;
        }
        return quality * 2;
    }

    Assembly (GCC 15, -O2)

    scaled_quality(int):
        test    edi, edi
        js      .L10
        lea     eax, [rdi+rdi]
        ret
    .L10:
        sub     rsp, 8
        call    report_bad_quality(int)@PLT
        xor     eax, eax
        add     rsp, 8
        ret

    The usual path runs straight through: test, a jump that isn’t taken (js jumps if the sign is negative), lea to double the value, ret. The rare path sits after the ret, out of the way. call runs another function; @PLT means it’s found when the program starts, because it’s defined somewhere else, and sub rsp, 8 keeps the stack aligned for that call. With [[likely]] on the same branch, GCC lays it out the other way round, with the call first.

    CPUs predict branches well on their own, and compilers already guess that error paths are rare. Use these attributes only on hot code, after measuring, where you know better than the compiler.

    Which one should I use?

    WhatWhenWhyHow
    -O0 -g or -Og -gWhile writing and debugging.Every variable is visible in the debugger; builds are fast.CMake’s Debug build type
    -O2Release builds, by default.Most of the speed, without bloating the code.CMake’s Release build type uses -O3; set -O2 if you prefer
    -O3Hot loops over numbers, after measuring.More unrolling and vectorization; not always faster.-O3 on the whole build or one file
    -OsSmall devices, or code where size matters more than speed.Smaller code fits in caches and in flash memory.-Os
    -march=native, -fltoPrograms you build for one known machine; whole-program speed.Newer instructions; inlining across files.Under the hood, below

    Rule of thumb: debug at -O0 or -Og with the sanitizers, ship at -O2, and reach for -O3 or anything else only when a measurement says it helps.

    Under the hood

    The pipeline. GCC turns your code into its own internal form, runs hundreds of passes over it (each one an optimization like inlining or constant folding, many run several times), and only then picks x86-64 instructions and registers. That’s why the assembly can look so different from the source, and why GCC and Clang, another GCC version or another CPU give different but equally correct listings. Use assembly to understand what one compiler did with one piece of code, not as a promise.

    -march=native. By default, GCC targets the first 64-bit x86 CPUs from 2003, so the program runs on any x86-64 machine. -march=native lets it use every instruction the CPU you’re compiling on has, such as AVX2 (SIMD). The result can crash with “illegal instruction” on an older CPU. Use it for programs you build and run on the same machine; for programs you hand out, pick a level on purpose, such as -march=x86-64-v3 (it adds AVX2, which most x86-64 CPUs from the last ten years have), or check the CPU at run time.

    Link-time optimization. The compiler sees one .cpp file at a time, so it can’t inline a function defined in another file. With -flto on both the compiling and the linking command (g++ -O2 -flto -c dna.cpp main.cpp, then g++ -O2 -flto dna.o main.o -o app), it saves its internal form in the object files, and the linker runs the optimizer again over the whole program. In CMake, set(CMAKE_INTERPROCEDURAL_OPTIMIZATION ON) does the same. Builds get slower; programs whose hot code is spread over many files get faster.

    Common pitfalls

    Timing code that the optimizer removed

    This function tries to time a loop:

    #include <chrono>
    
    long long time_sum() {
        auto start = std::chrono::steady_clock::now();
        long long total = 0;
        for (int i = 0; i < 100'000'000; ++i) {
            total += i;
        }
        auto stop = std::chrono::steady_clock::now();
        return (stop - start).count();
    }

    Assembly (GCC 15, -O2)

    time_sum():
        push    rbx
        call    std::chrono::_V2::steady_clock::now()@PLT
        mov     rbx, rax
        call    std::chrono::_V2::steady_clock::now()@PLT
        sub     rax, rbx
        pop     rbx
        ret

    The two calls to now() are back to back: nothing uses total, so the loop was dead code. The function measures nothing. Use the result of the work you time (print it, or return it), and check the assembly or the numbers when a timing looks too good. Caches and data-oriented design shows a complete timing setup.

    Judging speed from an -O0 build

    -O0 code keeps every variable in memory and calls every function, so it’s often several times slower than -O2, and not evenly: code with many small functions suffers most. Measure the build you ship. The reverse problem: in an -O2 build, the debugger may say a variable was “optimized out”, or jump around between lines. Debug with -Og or -O0.

    Try it yourself

    Try it yourself

    count_or_zero is meant to return 0 for a null pointer, but it reads through the pointer before checking it. Fix it, and add a call with nullptr that prints 0.

    #include <cstddef>
    #include <print>
    #include <vector>
    
    std::size_t count_or_zero(const std::vector<int>* scores) {
        std::size_t count = scores->size();
        if (scores == nullptr) {
            return 0;
        }
        return count;
    }
    
    int main() {
        std::vector<int> scores = {30, 38, 12};
        std::println("{}", count_or_zero(&scores));
    }

    Expected output

    3
    0
    Show a hint

    Move the null check above the line that reads through scores, and return 0 from there. Then call count_or_zero(nullptr) in main and print the result.

    Show a solution
    #include <cstddef>
    #include <print>
    #include <vector>
    
    std::size_t count_or_zero(const std::vector<int>* scores) {
        if (scores == nullptr) {
            return 0;
        }
        return scores->size();
    }
    
    int main() {
        std::vector<int> scores = {30, 38, 12};
        std::println("{}", count_or_zero(&scores));
        std::println("{}", count_or_zero(nullptr));
    }

    In the starter, scores->size() reads through the pointer before the check, so at -O2 the compiler may assume scores isn't null and delete the check, and a null pointer is undefined behavior. Checking first makes the null case defined, so the optimizer has to keep the test: open the fixed version in Compiler Explorer with -O2 and you'll see test rdi, rdi at the start.

    Saved in this browser only.