On this page

The compiler renders the same C99 source in three completely different ways, and each one reflects a distinct engineering trade-off—not just “the same code with fewer mov instructions.”

After covering the ABI, the link between C99 and assembly is no longer an informal handshake. What remains is reading what the compiler actually produces from source: where it places variables, how a loop looks before and after optimization, and why a library call sometimes collapses into a single jump. In this testbed, calc.c is compiled with -O0, -O2, and -Os, and linked alongside a hand-written funcs.asm.

Mental Model: What Optimization Actually Changes

Intuition What appears in the listing
-O0 shows the “real” code and the true ABI -O0 simply disables optimizations and spills everything to the stack
-O2 is the same code minus redundant movs -O2 restructures the loop: the index disappears and a pointer advances instead
A call to memcpy always stays a call -O2 folds it into a tail jmp, while -Os inlines rep movsb
C99 and assembly live in separate worlds Object files link into a single binary, bound together by the ABI

-O0: Every Step Through Memory

Our benchmark function sums an int32_t array into an int64_t accumulator:

calc.c
/* SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0 */

/* calc.c — C99 sum and copy routines: a single source file for -O0, -O2, and -Os. */

#include <stddef.h>
#include <stdint.h>
#include <string.h>

int64_t calc_sum(const int32_t *arr, size_t len)
{
    int64_t total = 0;
    size_t i = 0;

    for (i = 0; i < len; i++) {
        total += arr[i];
    }

    return total;
}

void calc_copy(uint8_t *dst, const uint8_t *src, size_t len)
{
    memcpy(dst, src, len);
}

We generate the assembly listing without debug info so we don’t have to wade through hundreds of .loc directives:

$ gcc -std=c99 -D_POSIX_C_SOURCE=200809L -Wall -Wextra -Werror -pedantic \
    -O0 -S -masm=intel -fno-asynchronous-unwind-tables -g0 calc.c

The listing comes from gcc -S -masm=intel, so its syntax differs slightly from NASM: function names and labels are quoted ("calc_sum":), and local labels start with a dot (.L2:).

Memory operands are written as DWORD PTR -4[rbp]; following that pattern, the listing below uses forms like QWORD PTR -24[rbp] and DWORD PTR [rax].

The file still includes boilerplate .file, .intel_syntax, and .globl directives; here is the body of calc_sum:

"calc_sum":
    push    rbp
    mov     rbp, rsp
    mov     QWORD PTR -24[rbp], rdi
    mov     QWORD PTR -32[rbp], rsi
    mov     QWORD PTR -16[rbp], 0
    mov     QWORD PTR -8[rbp], 0
    mov     QWORD PTR -8[rbp], 0
    jmp     .L2
.L3:
    mov     rax, QWORD PTR -8[rbp]
    lea     rdx, 0[0+rax*4]
    mov     rax, QWORD PTR -24[rbp]
    add     rax, rdx
    mov     eax, DWORD PTR [rax]
    cdqe
    add     QWORD PTR -16[rbp], rax
    add     QWORD PTR -8[rbp], 1
.L2:
    mov     rax, QWORD PTR -8[rbp]
    cmp     rax, QWORD PTR -32[rbp]
    jb      .L3
    mov     rax, QWORD PTR -16[rbp]
    pop     rbp
    ret
  • push rbp and mov rbp, rsp construct a stack frame; the frame pointer itself is not mandated by the System V ABI and exists solely for the unoptimized compiler.
  • The two instructions mov QWORD PTR -24[rbp], rdi and ... -32[rbp], rsi spill the arguments to the stack so that rdi and rsi are free to be reused.
  • mov QWORD PTR -8[rbp], 0 appears twice: first for the declaration i = 0, then for the for-loop initializer.
  • lea rdx, 0[0+rax*4] (a quirk of GAS Intel syntax where 0[0+rax*4] is equivalent to [rax*4]) scales the index by the element size, and cdqe sign-extends the 32-bit eax into 64-bit rax—in GDB, this same instruction is disassembled as cltq.
  • The accumulator add QWORD PTR -16[rbp], rax also lives in memory: every loop iteration reads and writes it back to the stack.

-O2: Registers and a Pointer Instead of an Index

Compiling the exact same source with -O2 yields a completely different loop:

"calc_sum":
    test    rsi, rsi
    je      .L4
    lea     rcx, [rdi+rsi*4]
    xor     eax, eax
    .p2align 4
    .p2align 4
    .p2align 3
.L3:
    movsxd  rdx, DWORD PTR [rdi]
    add     rdi, 4
    add     rax, rdx
    cmp     rdi, rcx
    jne     .L3
    ret
    .p2align 4,,10
    .p2align 3
.L4:
    xor     eax, eax
    ret
  • test rsi, rsi and je .L4 short-circuit an empty array before entering the loop.
  • lea rcx, [rdi+rsi*4] computes the one-past-the-end pointer: the loop compares two pointers rather than an index against a length.
  • movsxd rdx, DWORD PTR [rdi] loads the 32-bit element and sign-extends it to 64 bits directly—no stack spill and no separate cdqe.
  • add rdi, 4 advances the pointer to the next element, eliminating the dedicated index register altogether.
  • .p2align 4 aligns the next label to a 16-byte boundary; the assembler pads the gap with nop bytes, and the repeated directives are harmless artifacts from two compiler passes.
-O0: [rbp-24](arr), [rbp-32](len), [rbp-8](i), [rbp-16](total) — memory traffic on every step
-O2: rdi (current ptr) ──► rcx = rdi + rsi*4 (end), rax (sum) — everything in registers

The hand-written asm_sum_array in funcs.asm solves the same task differently: it keeps the index in rcx and addresses each element as [rdi + rcx * 4]. Both versions are valid, though the -O2 form is closer to what actually executes inside a hot loop.

Mixing C99 and Assembly

The assembly core of this lesson implements clamp and array summation:

funcs.asm
; SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0

; funcs.asm — hand-written clamp and array sum routines to compare against gcc output.

default rel

section .text
    global asm_clamp
    global asm_sum_array

; ------------------------------------------------------------------------------
; int32_t asm_clamp(int32_t v, int32_t lo, int32_t hi)
; Input:     edi = v, esi = lo, edx = hi
; Output:    eax = min(max(v, lo), hi)
; Clobbers:  rax, flags (caller-saved)
; ------------------------------------------------------------------------------
asm_clamp:
    mov eax, edi

    cmp edi, esi
    jl .below
    cmp edi, edx
    jg .above

    ret

.below:
    mov eax, esi

    ret

.above:
    mov eax, edx

    ret

; ------------------------------------------------------------------------------
; int64_t asm_sum_array(const int32_t *arr, size_t len)
; Input:     rdi = arr, rsi = len
; Output:    rax = sum of elements as int64_t
; Clobbers:  rax, rcx, rdx, flags (caller-saved)
; ------------------------------------------------------------------------------
asm_sum_array:
    xor eax, eax
    xor ecx, ecx
    test rsi, rsi
    jz .done

.loop:
    movsxd rdx, dword [rdi + rcx * 4]
    add rax, rdx
    inc rcx
    cmp rcx, rsi
    jb .loop

.done:
    ret

section .note.GNU-stack noalloc noexec nowrite progbits

The test harness main.c declares both assembly functions and invokes the C99 version alongside them:

int32_t asm_clamp(int32_t v, int32_t lo, int32_t hi);
int64_t asm_sum_array(const int32_t *arr, size_t len);
int64_t calc_sum(const int32_t *arr, size_t len);

ok = check_clamp("-5, 0, 10", -5, 0, 10, 0) && ok;
ok = check_sum(data, 8, 36) && ok;

Linking requires nothing beyond passing the assembled object file to gcc:

$ nasm -f elf64 -g -F dwarf -o build/funcs.o funcs.asm
$ gcc -std=c99 -D_POSIX_C_SOURCE=200809L -Wall -Wextra -Werror -pedantic \
    -g -O0 -o build/mixed main.c calc.c build/funcs.o
$ ./build/mixed
clamp(-5, 0, 10) = 0
clamp(15, 0, 10) = 10
clamp(7, 0, 10) = 7
sum asm: 36
sum c:   36
sum asm: -6
sum c:   -6
copy: ok
mixed: ok

In GDB, both implementations appear as ordinary functions, and upon entering the assembly routine, the arguments are already laid out according to the ABI:

$ gdb -q --nx -batch -ex 'break asm_sum_array' -ex run \
    -ex 'info registers rdi rsi' -ex 'x/4dw $rdi' -ex 'bt 2' ./build/mixed
Breakpoint 1, asm_sum_array () at funcs.asm:44
44          xor eax, eax
rdi            0x5555555560a0      93824992239776
rsi            0x8                 8
0x5555555560a0 <data.1>:       1       2       3       4
#0  asm_sum_array () at funcs.asm:44
#1  0x0000555555555207 in check_sum (arr=0x5555555560a0 <data>, len=8, want=36) at main.c:28
  • rdi holds the address of data, and rsi holds the length 8: the harness called the function through its prototype, so the compiler placed the arguments accordingly.
  • The .1 suffix in <data.1> is added by GDB to disambiguate a static array from a symbol of the same name elsewhere.
  • bt 2 (lesson 05) shows the top two stack frames: the return address points back into the C99 function check_sum, not _start.

In the symbol table, local labels appear right alongside the global entry points:

$ nm build/mixed | grep -E 'asm_clamp|asm_sum_array|calc_sum|calc_copy'
00000000000015a0 T asm_clamp
00000000000015ae t asm_clamp.above
00000000000015ab t asm_clamp.below
00000000000015b1 T asm_sum_array
00000000000015c9 t asm_sum_array.done
00000000000015ba t asm_sum_array.loop
000000000000156d T calc_copy
0000000000001517 T calc_sum

Lowercase t marks a local symbol: NASM scopes .above and .loop by prefixing them with the enclosing global label, avoiding collisions across functions while keeping T asm_clamp as the single exported entry point.

One memcpy, Three Compiler Decisions

memcpy is the libc function that copies len bytes from src to dst. calc_copy doesn’t change at all—only the compiler flags do. With -O0, the compiler dutifully emits a call to libc:

"calc_copy":
    push    rbp
    mov     rbp, rsp
    sub     rsp, 32
    mov     QWORD PTR -8[rbp], rdi
    mov     QWORD PTR -16[rbp], rsi
    mov     QWORD PTR -24[rbp], rdx
    mov     rdx, QWORD PTR -24[rbp]
    mov     rcx, QWORD PTR -16[rbp]
    mov     rax, QWORD PTR -8[rbp]
    mov     rsi, rcx
    mov     rdi, rax
    call    "memcpy"@PLT
    nop
    leave
    ret

With -O2, the entire function shrinks to a single jump:

"calc_copy":
    jmp     "memcpy"@PLT

This is a tail call (lesson 10): since calc_copy has nothing left to do after memcpy returns, call followed by ret is replaced by jmp. The caller’s return address is already sitting on the stack, so memcpy will return directly to calc_copy’s caller.

With -Os, the compiler emits rep movsb:

"calc_copy":
    mov     rcx, rdx
    rep movsb
    ret
  • mov rcx, rdx moves the byte count into rcx, where rep expects it.
  • rsi and rdi already hold the source and destination pointers—matching the exact ABI argument registers.
  • The compiler chooses rep movsb when code size matters more than peak throughput on short copies.
Optimization level Instruction in calc_copy Rationale
-O0 call memcpy@PLT Literal call to the library function
-O2 jmp memcpy@PLT Tail call with no extra stack frame
-Os mov rcx, rdx; rep movsb Minimal machine-code footprint

Terminal Verification

All three compiler strategies are checked by make test, which scans the listings for call, jmp, and rep movsb, and verifies the assembly and C99 sums against each other:

$ make -s test
19-c-to-asm: gcc -O0/-O2 output and C99/asm mix OK

Common Failure Modes

  1. Treating the -O0 listing as the canonical ABI.
    Symptom: Under -O0, arguments sit at [rbp-0x18] and [rbp-0x20], whereas under -O2 those same values stay in rdi and rsi.
    Cause: -O0 disables optimizations and builds a frame pointer, even though rbp framing is not part of the System V ABI.
    Fix: Inspect registers on function entry in GDB rather than inferring calling conventions from unoptimized stack slots.

  2. Thinking -O2 deleted memcpy because call is gone.
    Symptom: The listing only contains jmp "memcpy"@PLT.
    Cause: The compiler folded call + ret into a tail call because nothing runs after the library function returns.
    Fix: Look for both call and jmp instructions carrying an R_X86_64_PLT32 relocation in objdump -dr or readelf -r.

  3. Reading AT&T syntax backwards.
    Symptom: mov %rdi,%rax looks like rdi = rax when it actually means rax = rdi.
    Cause: AT&T syntax places the source operand first and the destination second; Intel syntax flips them.
    Fix: Pass -masm=intel when generating assembly so operand order matches NASM and objdump -M intel.

  4. Assuming rep movsb always copies forward.
    Symptom: Buffers get overwritten backwards.
    Cause: The copy direction is controlled by DF, not the instruction itself. Executing std sets DF = 1 (lesson 07), causing string instructions to decrement pointers from high addresses to low.
    Fix: Never return from a function with DF set; if you use std, clear it with cld before rep movsb and before ret.

Lab

Goal. Add asm_sum_clamped to funcs.asm to sum an array’s elements after clamping each value to [lo, hi], and validate it against a C99 reference implementation.

Contract and constraints.

  • Prototype: int64_t asm_sum_clamped(const int32_t *arr, size_t len, int32_t lo, int32_t hi);
  • Arguments arrive via System V ABI in rdi, rsi, edx, and ecx; the return value goes in rax.
  • When len == 0, return 0; you may assume lo <= hi.
  • Do not call libc inside the function: use only arithmetic, comparisons, and branches.
  • The C99 test harness builds with -std=c99 -D_POSIX_C_SOURCE=200809L -Wall -Wextra -Werror -pedantic.

Acceptance criteria.

  1. make -s test exits with 0 and prints sum_clamped: ok.
  2. For {-3, 0, 7, -20, 10} with lo = 0, hi = 10, the result is 17; for an empty array, 0.
  3. objdump -d -M intel build/funcs.o shows no call instruction inside asm_sum_clamped.
  4. Fuzzing 1,000 random arrays against the C99 reference produces zero mismatches, and running under -fsanitize=address,undefined reports no errors.
Hints, expected output, and walkthrough

Sign-extend each element to 64 bits first (or clamp in 32 bits and sign-extend before accumulating) so negative values don’t corrupt the 64-bit sum. Clamping takes two signed comparisons: one against lo and one against hi. Once clamped, add the 64-bit value to the accumulator.

You cannot use rcx as your loop counter because ecx holds the upper bound hi, so place the loop index in another free caller-saved register.

Expected output for three sample calls:

17
0
35

17 comes from 0 + 0 + 7 + 0 + 10, and 35 from 7 * 5 when both bounds are 7.

Testbed sources, Makefile, and automated tests for this lesson: lessons/19-c-to-asm.

Summary

  1. -O0 disables optimizations and spills arguments, loop counters, and accumulators to the stack.
  2. -O2 keeps hot values in registers and replaces array indexing with a stepping pointer.
  3. The rbp frame pointer and [rbp-0x18] stack layout are -O0 artifacts, not System V ABI requirements.
  4. -O2 collapses call + ret into a tail jmp when nothing follows the call.
  5. -Os inlines memory copies as rep movsb, which expects the count in rcx and pointers in rsi/rdi.
  6. C99 and NASM object files link into a single binary: GDB inspects both seamlessly, while nm distinguishes global entry points (T) from local labels (t).
Bridge to the next lesson
We’ve seen the choices the compiler makes on your behalf. In lesson 20, we measure what those choices cost in cycles: how expensive a branch is, why branch prediction matters more than instruction count, and when the compiler replaces a branch with branchless selection.