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
movinstructions.”
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:
/* 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.cThe 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
retpush rbpandmov rbp, rspconstruct 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], rdiand... -32[rbp], rsispill the arguments to the stack so thatrdiandrsiare free to be reused. mov QWORD PTR -8[rbp], 0appears twice: first for the declarationi = 0, then for thefor-loop initializer.lea rdx, 0[0+rax*4](a quirk of GAS Intel syntax where0[0+rax*4]is equivalent to[rax*4]) scales the index by the element size, andcdqesign-extends the 32-biteaxinto 64-bitrax—in GDB, this same instruction is disassembled ascltq.- The accumulator
add QWORD PTR -16[rbp], raxalso 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
rettest rsi, rsiandje .L4short-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 separatecdqe.add rdi, 4advances the pointer to the next element, eliminating the dedicated index register altogether..p2align 4aligns the next label to a 16-byte boundary; the assembler pads the gap withnopbytes, 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 registersThe 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:
; 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 progbitsThe 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: okIn 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:28rdiholds the address ofdata, andrsiholds the length8: the harness called the function through its prototype, so the compiler placed the arguments accordingly.- The
.1suffix 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 functioncheck_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_sumLowercase 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
retWith -O2, the entire function shrinks to a single jump:
"calc_copy":
jmp "memcpy"@PLTThis 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
retmov rcx, rdxmoves the byte count intorcx, whererepexpects it.rsiandrdialready hold the source and destination pointers—matching the exact ABI argument registers.- The compiler chooses
rep movsbwhen 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 OKCommon Failure Modes
-
Treating the
-O0listing as the canonical ABI.
Symptom: Under-O0, arguments sit at[rbp-0x18]and[rbp-0x20], whereas under-O2those same values stay inrdiandrsi.
Cause:-O0disables optimizations and builds a frame pointer, even thoughrbpframing 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. -
Thinking
-O2deletedmemcpybecausecallis gone.
Symptom: The listing only containsjmp "memcpy"@PLT.
Cause: The compiler foldedcall+retinto a tail call because nothing runs after the library function returns.
Fix: Look for bothcallandjmpinstructions carrying anR_X86_64_PLT32relocation inobjdump -drorreadelf -r. -
Reading AT&T syntax backwards.
Symptom:mov %rdi,%raxlooks likerdi = raxwhen it actually meansrax = rdi.
Cause: AT&T syntax places the source operand first and the destination second; Intel syntax flips them.
Fix: Pass-masm=intelwhen generating assembly so operand order matches NASM andobjdump -M intel. -
Assuming
rep movsbalways copies forward.
Symptom: Buffers get overwritten backwards.
Cause: The copy direction is controlled byDF, not the instruction itself. ExecutingstdsetsDF = 1(lesson 07), causing string instructions to decrement pointers from high addresses to low.
Fix: Never return from a function withDFset; if you usestd, clear it withcldbeforerep movsband beforeret.
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, andecx; the return value goes inrax. - When
len == 0, return0; you may assumelo <= 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.
make -s testexits with0and printssum_clamped: ok.- For
{-3, 0, 7, -20, 10}withlo = 0,hi = 10, the result is17; for an empty array,0. objdump -d -M intel build/funcs.oshows nocallinstruction insideasm_sum_clamped.- Fuzzing 1,000 random arrays against the C99 reference produces zero mismatches, and running under
-fsanitize=address,undefinedreports 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
3517 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
-O0disables optimizations and spills arguments, loop counters, and accumulators to the stack.-O2keeps hot values in registers and replaces array indexing with a stepping pointer.- The
rbpframe pointer and[rbp-0x18]stack layout are-O0artifacts, not System V ABI requirements. -O2collapsescall+retinto a tailjmpwhen nothing follows the call.-Osinlines memory copies asrep movsb, which expects the count inrcxand pointers inrsi/rdi.- C99 and NASM object files link into a single binary: GDB inspects both seamlessly, while
nmdistinguishes global entry points (T) from local labels (t).