Skip to content
Tutorials Center
My learning

Topics

Lesson 4 of 40 ยท First Steps

Reading Real Assembly from a C Compiler

Learn to read real x86-64 and ARM64 assembly produced by a C compiler: gcc -S, optimization levels, Intel versus AT&T syntax and line-by-line annotation.

The fastest way to get comfortable with real assembly is to look at what a compiler produces for code you already understand. You write a small C function, ask the compiler for its assembly, and read the result next to the source. No guessing about what the programmer meant: the C tells you the intention, the assembly tells you what the machine does.

This lesson shows how to get compiler output, how optimization levels change it, how to tell the two x86 syntax styles apart, and how to read a function one line at a time. The listings in this lesson are read-only: they are typical output of GCC for x86-64 Linux and ARM64, written out for you. Exact instruction order and label numbers vary between compiler versions, so treat them as representative rather than as the only correct answer.

Getting assembly out of a compiler

On your own machine, GCC and Clang can stop after the compile step and write the assembly instead of an object file:

Terminal
gcc -S -O2 -masm=intel -fno-asynchronous-unwind-tables -o square.s square.c
  • -S stops after producing assembly text (square.s).
  • -O2 chooses the optimization level.
  • -masm=intel prints x86 in Intel syntax instead of the default AT&T syntax.
  • -fno-asynchronous-unwind-tables removes the .cfi_* bookkeeping lines that clutter the output. (Clang spells the Intel option -mllvm --x86-asm-syntax=intel.)

If you do not want to install anything, use an online Compiler Explorer (the Godbolt site): paste C, pick a compiler and flags, and it highlights which assembly lines belong to which source line. The same technique works for Rust, C++ and Go. The main skill is the same everywhere: find the function label, find the ret, and trace values between them.

flowchart TD
    A["Find the function label<br/>for example square:"] --> B["Find the ret instruction<br/>the end of the function"]
    B --> C["Identify the inputs<br/>argument registers or stack slots"]
    C --> D["Follow the data<br/>which instruction changes which register"]
    D --> E["Match jumps and labels<br/>to the C if and loop structure"]

A routine that works for any compiler output: from the label, to the end, to the data flow.

A first function, three ways

Here is the smallest useful function, in C:

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

On x86-64 Linux the first integer argument arrives in the register edi (the 32-bit part of rdi), and an integer result is returned in eax. That agreement is the calling convention, covered in Calling Conventions. With -O2 and Intel syntax GCC produces:

NASM
square:
        mov     eax, edi        ; eax = x
        imul    eax, edi        ; eax = eax * x
        ret                     ; return, the result is in eax

Three instructions, no memory access at all. The same function in AT&T syntax, which is the default output of GCC and Clang on Linux and macOS, looks like this:

ASM
square:
        movl    %edi, %eax
        imull   %edi, %eax
        ret

The two listings are the same program. You can recognize AT&T by its % before register names, a size suffix on the mnemonic (movl means a 32-bit move), and a reversed operand order: the source comes first and the destination last. In Intel syntax the destination comes first, as in the toy CPU. This tutorial uses Intel syntax for x86; Assemblers, Syntax Flavors and Object Files covers the details.

For comparison, ARM64's AAPCS64 convention passes the first argument in w0 and returns in w0 as well:

ASM
square:
        mul     w0, w0, w0      ; w0 = w0 * w0
        ret

ARM64 instructions have three operands (destination, then two sources), so no copying is needed.

What optimization levels change

The same C function compiled with -O0 (no optimization, the default) looks very different:

NASM
square:
        push    rbp                     ; save the caller's frame pointer
        mov     rbp, rsp                ; set up this function's frame
        mov     DWORD PTR [rbp-4], edi  ; spill the argument into memory
        mov     eax, DWORD PTR [rbp-4]  ; load it back
        imul    eax, eax
        pop     rbp                     ; restore the frame pointer
        ret

At -O0 the compiler gives every variable a home in memory (a slot on the stack, addressed relative to rbp) so that a debugger can show it at every step. DWORD PTR [rbp-4] means "the 4-byte value at the address rbp minus 4". The instructions that store edi and reload it do nothing useful, but they keep the program easy to debug. At -O1 and above the compiler keeps x in a register and the function shrinks to the three-line version.

Flag What you usually see
-O0 Variables in memory, a frame set up for every function, one C line becomes a visible block of instructions
-O1 Values in registers, simple loops, no inlining of larger functions
-O2 The normal release setting: inlining, loop restructuring, cmov, strength reduction
-O3 Everything in -O2 plus aggressive loop unrolling and vectorization (SIMD)
-Os Optimize for size

For learning, read -O0 output when you want to see the plain translation of C statements, and -O1 or -O2 output when you want to see what the machine really runs.

Annotating a function with a branch

Branches show how the compiler translates if. Take this function:

C
int max_of(int a, int b) {
    return a > b ? a : b;
}

A typical -O0 translation, annotated line by line:

NASM
max_of:
        push    rbp
        mov     rbp, rsp
        mov     DWORD PTR [rbp-4], edi   ; a lives at [rbp-4]
        mov     DWORD PTR [rbp-8], esi   ; b lives at [rbp-8]
        mov     eax, DWORD PTR [rbp-4]   ; eax = a
        cmp     eax, DWORD PTR [rbp-8]   ; compare a with b (sets flags)
        jle     .L2                      ; if a <= b, jump to the else part
        mov     eax, DWORD PTR [rbp-4]   ; then part: result = a
        jmp     .L3                      ; skip the else part
.L2:
        mov     eax, DWORD PTR [rbp-8]   ; else part: result = b
.L3:
        pop     rbp
        ret

Read this like a story. The compiler tests the opposite condition (jle, "jump if less or equal") so that the common path falls through. The labels .L2 and .L3 are names the compiler invented; the leading dot marks them as local to the file. The ternary operator became compare, conditional jump, two result assignments and an unconditional jump.

At -O2 GCC can avoid the branch completely, using a conditional move:

NASM
max_of:
        cmp     edi, esi        ; compare a with b
        mov     eax, esi        ; assume the result is b
        cmovge  eax, edi        ; if a >= b, replace it with a
        ret

cmovge copies edi into eax only when the flags say "greater or equal". Because there is no jump, the processor never has to guess a branch (see Performance). Note that a >= b gives the same answer as a > b here, because when they are equal both choices are identical.

A loop in compiler output

Loops are compare-and-jump patterns that go backwards. Here is a function that adds up an array:

C
long sum_array(const int *a, int n) {
    long total = 0;
    for (int i = 0; i < n; i++) {
        total += a[i];
    }
    return total;
}

A shape very close to what GCC produces at -O1 is:

NASM
sum_array:
        test    esi, esi                 ; is n <= 0 ?
        jle     .L4                      ; yes: return 0
        mov     esi, esi                 ; zero-extend n into rsi
        lea     rdx, [rdi+rsi*4]         ; rdx = end address of the array
        mov     eax, 0                   ; total = 0
.L3:
        movsx   rcx, DWORD PTR [rdi]     ; read one int, widen it to 64 bits
        add     rax, rcx                 ; total += element
        add     rdi, 4                   ; advance the pointer by 4 bytes
        cmp     rdi, rdx                 ; reached the end?
        jne     .L3                      ; no: loop again
        ret
.L4:
        mov     eax, 0
        ret

Look at what the compiler did with the source. The index i has vanished. The compiler replaced a[i] with a pointer that moves forward 4 bytes at a time and compares it with a precomputed end address. This kind of rewriting is why optimized assembly can look very different from the C even when the behavior is identical. The first argument a is in rdi (a full 64-bit pointer) and n in esi; the result is in rax because long is 64 bits on Linux.

The next program shows the source side on a real compiler. It contains the three functions from this lesson, plus the pointer-walking version of the loop. Run it to confirm that both loop styles give the same answer.

C The C source behind the listings

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The two sums agree, and sizeof(long) is 8 on this 64-bit Linux runner, which is why the compiler used the 64-bit register rax for total.

The same idea in the toy CPU

A compiler is a translator from a tree of operations into instructions. To see that without a real compiler, the editor below contains a miniature one for arithmetic expressions. It parses text like (a + b) * c - 4 into a tree, then generates toy assembly in which each subexpression's result lives in a register. Then it runs the generated code on the toy CPU from the previous lesson. The variables a, b and c are preloaded with 2, 3 and 4.

The second expression is compiled twice: once as written, and once with constant folding, one of the simplest optimizations. The compiler multiplies 2 * 8 itself, at compile time, so the program does not have to.

JS A miniature compiler for expressions

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Compare the two compilations of 2 * 8 + a. The folded program is two instructions shorter and still prints the same answer, which is exactly what an optimizer is allowed to do: change the instructions, never the result.

Tips for reading unfamiliar output

  • Start with the arguments. On Linux x86-64 look for edi, esi, edx, ecx (integers) or rdi, rsi, rdx, rcx (pointers and 64-bit values); on ARM64 look for w0 to w7 or x0 to x7.
  • Look at the end. The value in eax (x86-64) or w0/x0 (ARM64) just before ret is the return value.
  • Ignore directives at first. Lines starting with a dot such as .text, .globl or .size talk to the assembler, not the CPU.
  • Match jumps to C. A backwards jump is a loop; a forward conditional jump is an if. Switches may become a table of addresses (How if, switch and Ternaries Compile).
  • Do not expect one line per line. Optimized output reorders and merges source lines.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does gcc -S do?

    -S makes the compiler stop after the compile step and output assembly (a .s file) instead of an object file.
  2. 2. How can you tell that an x86 listing is in AT&T syntax?

    AT&T syntax writes %eax, adds size suffixes like movl, and puts the source before the destination. Intel syntax puts the destination first.
  3. 3. Why does -O0 output store arguments to [rbp-4] and read them back?

    Without optimization the compiler keeps each variable in a stack slot. This is slow but makes debugging predictable; higher optimization levels keep values in registers.
  4. 4. On x86-64 Linux, where is the return value of an int function before ret?

    The System V convention returns integer values in rax; for an int, the 32-bit part eax holds the result.
  5. 5. What did the compiler replace the index i with in the optimized sum_array loop?

    Optimizers often turn a[i] indexing into pointer walking, which needs one add and one compare per element.

Summary

  • gcc -S -O2 -masm=intel file.c (or an online Compiler Explorer) shows what the compiler generated for your C.
  • Intel syntax puts the destination first; AT&T uses % register prefixes, size suffixes and source-first order.
  • -O0 keeps variables in stack slots ([rbp-4]); -O1 and above use registers, cmov and pointer walking.
  • On x86-64 Linux the first integer arguments are in edi, esi, edx, ecx and the result is in eax; ARM64 uses w0 to w7.
  • A backwards jump is a loop, a forward conditional jump is an if, and the instructions before ret compute the result.
  • Optimizers such as constant folding change the instructions but never the result.
  • The listings here are representative: instruction order and labels vary with the compiler version.

Next: Binary, Hex and Two's Complement, the number formats behind every register.