TExcelTAD
Home › Build Fundamentals: From Source to Binary › Compilation to Assembly (-S)

Compilation to Assembly (-S)

The second stage, the compiler proper, turns preprocessed C into assembly language for one CPU. This is where types are checked, warnings are produced, and optimisation happens. gcc -S stops right after it and writes a .s file you can read.

Reading assembly in depth is the subject of Reading Compiler Output in the x86-64 Assembly course. Here we care about what a build engineer needs: what this stage consumes, what it produces, and which flags change its output.

Your first .s file

-fno-asynchronous-unwind-tables removes the .cfi_* unwinding directives that otherwise fill half the file; -masm=intel picks Intel syntax (GCC's default is AT&T). The sed prints only the lines from the function's label to its .size directive; the rest of the file is bookkeeping (file name, compiler version, a note section describing security features):

bash · try it yourself
mkdir -p cc && cd cc
cat > square.c <<'SRC'
int square(int x) {
    return x * x;
}
SRC
gcc -S -O0 -masm=intel -fno-asynchronous-unwind-tables square.c -o square-O0.s
sed -n '/^square:/,/\.size/p' square-O0.s
square:
	endbr64
	push	rbp
	mov	rbp, rsp
	mov	DWORD PTR -4[rbp], edi
	mov	eax, DWORD PTR -4[rbp]
	imul	eax, eax
	pop	rbp
	ret
	.size	square, .-square

endbr64 is a marker for Intel's control-flow protection, added because Ubuntu's GCC enables -fcf-protection by default. After it, at -O0 GCC does exactly what the source says, step by step: store the argument on the stack (DWORD PTR -4[rbp]), load it twice, multiply, return. That is slow but easy to debug, because every variable has a home in memory.

Optimisation changes the output, not the meaning

Now the same file at -O2, plus a function that loops:

bash · try it yourself
mkdir -p cc && cd cc
cat > sum.c <<'SRC'
int square(int x) {
    return x * x;
}

int sum_to(int n) {
    int total = 0;
    for (int i = 1; i <= n; i++)
        total += i;
    return total;
}
SRC
gcc -S -O2 -masm=intel -fno-asynchronous-unwind-tables sum.c -o sum-O2.s
sed -n '/^square:/,/\.size\tsum_to/p' sum-O2.s | grep -v p2align
echo "--- lines at -O0 vs -O2"
gcc -S -O0 -fno-asynchronous-unwind-tables sum.c -o sum-O0.s
wc -l sum-O0.s sum-O2.s
square:
	endbr64
	imul	edi, edi
	mov	eax, edi
	ret
	.size	square, .-square
	.globl	sum_to
	.type	sum_to, @function
sum_to:
	endbr64
	test	edi, edi
	jle	.L6
	lea	ecx, 1[rdi]
	xor	edx, edx
	and	edi, 1
	mov	eax, 1
	je	.L5
	mov	eax, 2
	mov	edx, 1
	cmp	eax, ecx
	je	.L3
.L5:
	lea	edx, 1[rdx+rax*2]
	add	eax, 2
	cmp	eax, ecx
	jne	.L5
.L3:
	mov	eax, edx
	ret
.L6:
	xor	edx, edx
	mov	eax, edx
	ret
	.size	sum_to, .-sum_to
--- lines at -O0 vs -O2
  54 sum-O0.s
  63 sum-O2.s
 117 total

square shrank to two instructions (imul edi, edi multiplies the argument register by itself). The loop in sum_to is still a loop at -O2, but it lives entirely in registers and adds two numbers per pass (lea edx, 1[rdx+rax*2] adds i and i + 1 at once, with a little set-up code for odd n). That is why the optimised file is actually longer: faster code is not always smaller code. If size matters more than speed, -Os asks for the smallest code instead. Different flags, different assembly: so -O, -march, -g, -f… flags are inputs of the compile step just like the source file. A build tool that ignores a flag change will happily keep a stale -O0 object inside your "release" build.

Clang compiles the same C differently

Different compilers produce different (equally valid) code. Clang 18 at -O2 turns sum_to into a closed formula (essentially n(n+1)/2), with no loop at all:

bash · try it yourself
mkdir -p cc && cd cc
cat > sum.c <<'SRC'
int sum_to(int n) {
    int total = 0;
    for (int i = 1; i <= n; i++)
        total += i;
    return total;
}
SRC
clang -S -O2 -masm=intel -fno-asynchronous-unwind-tables sum.c -o sum-clang.s
grep -cE '^\s+j' sum-clang.s || true
grep -E '^\s+(imul|lea|shr|add|mul)' sum-clang.s
1
	lea	eax, [rdi - 1]
	lea	ecx, [rdi - 2]
	imul	rcx, rax
	shr	rcx
	lea	eax, [rcx + 2*rdi]

The grep -c counts jump instructions: the only one left is the early exit for n < 1. The second grep shows the arithmetic Clang uses for the sum. Because outputs differ between compilers and even between compiler versions, the compiler's identity and version are part of what a build depends on. Caches and lockfiles for toolchains (later in this course) exist because of this.

Warnings are produced here

Type checking happens in this stage, so this is where warnings and errors come from. -Wall -Wextra turns on the common warnings; -Werror makes them fatal, which is popular in CI:

bash · try it yourself
mkdir -p cc && cd cc
cat > warn.c <<'SRC'
int scale(int value, int factor) {
    int unused;
    return value * 2;
}
SRC
gcc -S -Wall -Wextra warn.c -o warn.s
echo "exit status: $?"
gcc -S -Wall -Wextra -Werror warn.c -o warn.s
echo "exit status: $?"
warn.c: In function ‘scale’:
warn.c:2:9: warning: unused variable ‘unused’ [-Wunused-variable]
    2 |     int unused;
      |         ^~~~~~
warn.c:1:26: warning: unused parameter ‘factor’ [-Wunused-parameter]
    1 | int scale(int value, int factor) {
      |                      ~~~~^~~~~~
exit status: 0
warn.c: In function ‘scale’:
warn.c:2:9: error: unused variable ‘unused’ [-Werror=unused-variable]
    2 |     int unused;
      |         ^~~~~~
warn.c:1:26: error: unused parameter ‘factor’ [-Werror=unused-parameter]
    1 | int scale(int value, int factor) {
      |                      ~~~~^~~~~~
cc1: all warnings being treated as errors
exit status: 1

Model: a tiny code generator

A compiler walks a syntax tree and emits instructions. This model compiles arithmetic expressions for a simple stack machine, the same idea used by the JVM, WebAssembly and CPython bytecode:

js · try it yourself
// x * x + 3 * y, as a syntax tree
const tree = ["+", ["*", "x", "x"], ["*", 3, "y"]];

function compile(node, out = []) {
  if (typeof node === "number") out.push(`push ${node}`);
  else if (typeof node === "string") out.push(`load ${node}`);
  else {
    const [op, left, right] = node;
    compile(left, out);
    compile(right, out);
    out.push(op === "+" ? "add" : "mul");
  }
  return out;
}

function run(code, vars) {
  const stack = [];
  for (const ins of code) {
    const [op, arg] = ins.split(" ");
    if (op === "push") stack.push(Number(arg));
    else if (op === "load") stack.push(vars[arg]);
    else { const b = stack.pop(), a = stack.pop(); stack.push(op === "add" ? a + b : a * b); }
  }
  return stack.pop();
}

const code = compile(tree);
console.log(code.join("; "));
console.log("x=4, y=5 ->", run(code, { x: 4, y: 5 }));
load x; load x; mul; push 3; load y; mul; add
x=4, y=5 -> 31

Test yourself

Why should a build system rebuild objects when you switch from -O0 to -O2?

  1. It shouldn't, the code is the same
  2. Optimisation flags change the generated code, so they are inputs of the compile step
  3. Because -O2 objects are larger
  4. Only the linker uses -O2

Which flag turns all warnings into errors?

  1. -Wall
  2. -Wextra
  3. -Werror
  4. -pedantic

What does gcc -S produce?

  1. An object file
  2. An assembly file (.s)
  3. A preprocessed file (.i)
  4. An executable