Maps to: CMU 15-213/15-513/14-513 Fall 2026, Lecture 5 (Sep 8), slide deck
05-machine-gamma. Reading: CS:APP3e §3.7–3.8 (the schedule lists 3.7–3.9; structures, §3.9, are covered in Lecture 6, whose deck repeats them). Lab: L1 (datalab) is due. Sources: the public Fall 2026 slides and CS:APP. The code is original to these notes. It runs clang’s real x86-64 output (-Ogand-O1) in Lecture 3’s simulatorx86sim.py, and runs the slides’ gcc listings forcall_incr/incrandpcount_ras text, so both compilers appear. Every simulated function was checked against the real x86-64 machine code (Rosetta 2 on an Apple M4 Pro): 0 disagreements in 547 tests at each optimization level. Two native C demos measure real frames and real array layouts on the same machine. Code:code/lecture05/. Reading time: ~100 minutes; ~40 more for the demos.
0. How to read this lecture
0.1 Learning goals
After this lecture you should be able to:
- Say where each argument of a call travels (six registers, then the stack), where the return value goes, and where the callee finds argument 7.
- Draw the stack frame of a function from its assembly: return address, saved registers, local variables, padding and the argument build area. Explain the 16-byte alignment rule.
- State the caller-saved / callee-saved division of the x86-64 registers, and explain why both kinds exist.
- Explain why recursion needs no special machinery, and estimate how much stack a recursion uses.
- Compute the address of
A[i],A[i][j](nested array) andA[i][j](multi-level array), and recognize each in assembly. - Explain why a fixed-size matrix index is a shift and a variable-size one a multiply.
0.2 Prerequisites and scope
- Lecture 4 §5: the stack,
push/pop,call/ret. This lecture builds directly on that picture. - Lecture 3: the operand form
D(Rb,Ri,S)andlea. Array code is mostly these two. - In scope: the slides of Lecture 5, CS:APP §3.7.1–3.7.6 (procedures) and §3.8 (arrays). The slides end with structures “as time permits”; Lecture 6’s slides repeat them, so these notes treat structures there.
- Floating-point arguments (passed in
%xmm0–%xmm7) are mentioned once; CS:APP §3.11 has the details.
0.3 Section → code map
| Section | Idea | Demo in code/lecture05/ |
|---|---|---|
| §1–2 | passing control and data; arguments 7+ on the stack | 01_passing_data.py |
| §3 | stack frames; locals whose address is taken; alignment | 02_stack_frames.py |
| §4 | caller-saved vs callee-saved registers | 03_register_conventions.py |
| §5 | recursion; tail calls; the stack limit | 04_recursion.py, 05_frames_in_real_memory.c |
| §6–8 | 1-D, nested and multi-level arrays | 06_arrays.c, 07_array_code.py |
| §9 | fixed vs variable-size matrices | 07_array_code.py |
| §10 | the simulator vs real hardware | 08_crosscheck.py |
1. Procedures: three mechanisms
1.1 What a procedure call must do
A procedure (function, method, subroutine) is the most important abstraction in programming: you name a computation and use it without thinking about its insides. The slides list what the machine must do to implement a call y = Q(x) inside P:
- Passing control: jump to the start of
Q’s code, and later back to the point inPright after the call. - Passing data: deliver the arguments to
Q, and the return value back toP. - Managing local data: give
Qmemory for its local variables while it runs, and release it whenQreturns.
All three are done with ordinary machine instructions; there is no “function” hardware. And the x86-64 implementation uses only the mechanisms a given call needs. A small function that keeps everything in registers allocates no memory at all, and the compiler emits no code for the unused mechanisms.
Why care? Every bug class in Lecture 6 (buffer overflows), every crash backtrace you will read in gdb, and every bomblab phase lives in these mechanisms. They are also where the C abstraction leaks most: “local variables disappear when the function returns” is really “%rsp moved, and the bytes are still there”.
1.2 Passing control (recap of Lecture 4)
The slides’ example:
long mult2(long a, long b) { long s = a * b; return s; }
void multstore(long x, long y, long *dest) { long t = mult2(x, y); *dest = t; }
0000000000400540 <multstore>:
400540: push %rbx # save %rbx
400541: mov %rdx,%rbx # save dest
400544: call 400550 <mult2> # mult2(x, y)
400549: mov %rax,(%rbx) # save at dest
40054c: pop %rbx # restore %rbx
40054d: ret
0000000000400550 <mult2>:
400550: mov %rdi,%rax # a
400553: imul %rsi,%rax # a * b
400557: ret
call 400550 pushes 0x400549, the address of the next instruction, and sets %rip = 0x400550. mult2’s ret pops 0x400549 back into %rip. Lecture 4’s demo 06 traced exactly this with the simulator. (The disassembler sometimes prints callq/retq; the q only reminds you that this is 64-bit code.)
The rest of this lecture is about mechanisms 2 and 3.
2. Passing data
2.1 Six registers, then the stack
argument: 1 2 3 4 5 6 7, 8, ... return value
location: %rdi %rsi %rdx %rcx %r8 %r9 the stack %rax
This assignment is part of the System V AMD64 ABI (Application Binary Interface), the rulebook that Linux, macOS and the BSDs follow on x86-64. Windows uses a different one. An ABI is what lets a function compiled by clang call a library compiled by gcc years earlier: both sides agree on where everything goes.
Why registers? A register is read in a fraction of a cycle; memory, even the L1 cache, takes several cycles. Old 32-bit x86 code (IA32) passed every argument on the stack, so every call wrote arguments to memory and the callee read them back. x86-64 has 16 registers instead of 8, so the ABI spends six of them on arguments. Six is enough for the vast majority of real functions, so most calls never touch memory for their arguments.
(Floating-point arguments use a separate set, %xmm0–%xmm7, and a double result comes back in %xmm0. These notes, like the slides, stick to integers and pointers.)
2.2 An example with eight arguments
CS:APP’s Figure 3.29 has a function with eight arguments of four sizes:
void proc(long a1, long *a1p, int a2, int *a2p,
short a3, short *a3p, char a4, char *a4p)
{ *a1p += a1; *a2p += a2; *a3p += a3; *a4p += a4; }
clang’s code (01_passing_data.py PART A):
addq %rdi, (%rsi) # *a1p += a1 (8 bytes)
addl %edx, (%rcx) # *a2p += a2 (4 bytes)
movzbl 8(%rsp), %eax # a4, argument 7, from the stack
addw %r8w, (%r9) # *a3p += a3 (2 bytes)
movq 16(%rsp), %r10 # a4p, argument 8, from the stack
addb %al, (%r10) # *a4p += a4 (1 byte)
retq
Two lessons:
- Each argument is used at its own size.
a2is anint, so the code uses%edx, the low 4 bytes of%rdx.a3is ashort:%r8w. The instruction suffixes follow:addq,addl,addw,addb. - Arguments 7 and 8 are on the stack, at
8(%rsp)and16(%rsp). On entry,0(%rsp)holds the return address thatcalljust pushed, so the first stack argument is right above it. Every stack argument gets its own 8-byte slot, even the 1-bytechar a4.
2.3 The caller’s side: the argument build area
CS:APP’s Figure 3.32 calls proc:
long call_proc() {
long x1 = 1; int x2 = 2; short x3 = 3; char x4 = 4;
proc(x1, &x1, x2, &x2, x3, &x3, x4, &x4);
return (x1 + x2) * (x3 - x4);
}
Demo 01 PART B runs it and stops at the call _proc instruction:
...dff8 RET return address -> caller
...dff0 1 x1 (long, 8 bytes) at byte 0
...dfe8 0x200030400 x4 (char, 1 byte) at byte 1; x3 (short, 2 bytes) at byte 2; x2 (int, 4 bytes) at byte 4
...dfe0 0 unused: padding so that %rsp is a multiple of 16 at the call
...dfd8 0x7fffffffdfe9 argument 8: a4p = &x4
...dfd0 4 argument 7: a4 = 4 (a char, in a full 8-byte slot) <- %rsp
Read it from the bottom:
- The two slots at the bottom are the argument build area. The caller places arguments 7+ at the very top of its frame (the lowest addresses), with argument 7 at
(%rsp). Whencallpushes the return address, they appear to the callee at8(%rsp)and16(%rsp). - Above them is one slot of padding (§3.4 explains why).
- Then come the four local variables. They must live in memory because their addresses are passed: a register has no address. clang packs them by size:
x1takes a whole slot, andx2,x3,x4share the next one. The value0x200030400is that slot read as one number: byte 0 unused, byte 1 = 4 (x4), bytes 2–3 = 3 (x3), bytes 4–7 = 2 (x2), little-endian. - The argument registers hold
%rdi = 1,%rsi = &x1,%edx = 2,%rcx = &x2,%r8w = 3,%r9 = &x3.
The function returns −12 = (2 + 4) × (6 − 8).
(The slides’ gcc code reserves the whole frame with one subq and stores the stack arguments with movs. clang -Og pushes them right before the call: pushq %rax; pushq $4. Both produce the same layout at the moment of the call.)
2.4 What about the bytes an argument does not use?
A char argument occupies a full register or 8-byte slot. What is in the other 7 bytes? The ABI does not promise anything, so a correct callee only reads the bytes its type needs. PART C of the demo checks this: the simulator passes full 64-bit values, “garbage” upper bytes included, while the real program passes them through C’s conversion. The results agree:
a1, a2, a3, a4 passed simulator real x86-64
5, 70000, 70000, 300 1005 72000 7464 84 1005 72000 7464 84 same
7, 2147483648, 32768, 128 1007 -2147481648 -29768 -88 1007 -2147481648 -29768 -88 same
a4 = 300 contributes only its low byte, 300 mod 256 = 44, so 40 + 44 = 84. a3 = 70000 becomes 70000 − 65536 = 4464 as a short. This is Lecture 2’s truncation, enforced by the instruction sizes addb and addw.
3. Managing local data: the stack frame
3.1 Why a stack?
Languages like C, Java and Python allow recursion, so one function can have many instantiations active at once (amI calling amI calling amI…). Each instantiation needs its own copy of its arguments, local variables and return point. The code must be reentrant: a second activation must not destroy the first one’s state.
Where should that state go? Observe the stack discipline: the state of an activation is needed only from its call to its return, and a callee always returns before its caller. Last in, first out. So the state goes on a stack, in a block per activation called a stack frame. The slides animate a call chain yoo → who → amI → amI → amI, then who → amI again: frames are pushed and popped exactly as calls start and end, and only the frame at the top (lowest address) is active.
3.2 The x86-64 frame layout
higher addresses
+---------------------------+
| arguments 7+ | caller's frame
| return address | (pushed by call)
+===========================+ <- the callee's frame starts here
| old %rbp (optional) |
| saved registers |
| local variables | current frame
| argument build area | (for the calls this function makes)
+---------------------------+ <- %rsp (stack "top")
lower addresses
- Set-up code at the start of a function allocates the frame: it moves
%rspdown withsubq $n, %rspor a fewpushes. Thecallinstruction’s push of the return address counts too. - Finish code before
retreleases it:addq $n, %rsporpops, so that%rsppoints at the return address whenretexecutes. - Only what is needed is allocated. A function whose data fits in registers gets no frame at all.
- The frame pointer
%rbpis optional. Old code (and gcc-O0) set%rbpto a fixed point in the frame and addressed locals relative to it. Optimized x86-64 code addresses everything relative to%rsp, which frees%rbpas a general register.%rbpis still used when the frame’s size is only known at run time (a variable-length array), and some profilers want it kept (-fno-omit-frame-pointer).
The convention also says that the return address belongs to the caller’s frame. frames.py draws a dashed line just below each return address for that reason.
3.3 The incr example
long incr(long *p, long val) { // add val to *p, return the OLD value
long x = *p;
long y = x + val;
*p = y;
return x;
}
long call_incr() {
long v1 = 15213;
long v2 = incr(&v1, 3000);
return v1 + v2;
}
incr is a leaf (it calls nothing) and needs no frame: movq (%rdi),%rax; addq %rax,%rsi; movq %rsi,(%rdi); ret. call_incr is different. It passes &v1, so v1 needs an address, so it must live in memory, in call_incr’s frame. 02_stack_frames.py runs the slides’ gcc code and prints the stack after each instruction:
instruction %rsp %rdi %rax stack from the return address down to %rsp
(entry) ...dff8 RET
subq $16, %rsp ...dfe8 0 0 RET | 0 | 0
movq $15213, 8(%rsp) ...dfe8 0 0 RET | 15213 | 0
movl $3000, %esi ...dfe8 0 0 RET | 15213 | 0
leaq 8(%rsp), %rdi ...dfe8 ...dff0 0 RET | 15213 | 0
call incr ...dfe0 ...dff0 0 RET | 15213 | 0 | ret->call_incr
movq (%rdi), %rax ...dfe0 ...dff0 15213 RET | 15213 | 0 | ret->call_incr
addq %rax, %rsi ...dfe0 ...dff0 15213 RET | 15213 | 0 | ret->call_incr
movq %rsi, (%rdi) ...dfe0 ...dff0 15213 RET | 18213 | 0 | ret->call_incr
ret ...dfe8 ...dff0 15213 RET | 18213 | 0
addq 8(%rsp), %rax ...dfe8 ...dff0 33426 RET | 18213 | 0
addq $16, %rsp ...dff8 ...dff0 33426 RET
ret (returned to the caller with %rax = 33426)
These are the slides’ pictures “Before Calling incr” through “Returning From call_incr”, one row per instruction:
subq $16, %rspallocates 16 bytes.v1goes at8(%rsp);0(%rsp)is unused.leaq 8(%rsp), %rdicomputes&v1as the first argument. This isleadoing what its designers intended, computing an address; elsewhere it is mostly used for arithmetic.movl $3000, %esisets the second argument. A 32-bitmovalso zeroes the upper half of%rsi(Lecture 3), and it is shorter. The slide says “1 byte shorter”. The assembler here actually encodesmovlin 5 bytes andmovqin 7, a difference of 2; the slide’s 1-byte figure compares against a 6-bytemovlencoding that assemblers do not pick.- Inside
incr, the storemovq %rsi, (%rdi)changes call_incr’s local variable: 15213 → 18213. This is the whole point of passing a pointer. - Back in
call_incr,addq 8(%rsp), %raxcomputes v1 + v2 = 18213 + 15213 = 33426. addq $16, %rspdeallocates the frame. The return address is back on top, andretuses it.
clang does the same job differently (PART B): pushq %rax allocates 8 bytes (the value pushed is irrelevant and is overwritten at once), v1 lives at 0(%rsp), and popq %rcx releases it. A push is 1 byte of code; subq $8, %rsp is 4. The result is the same, 33426. The convention fixes the interface (arguments, return value, which registers survive). The inside of a frame is each compiler’s business.
3.4 The 16-byte alignment rule
Why did gcc allocate 16 bytes for one 8-byte variable? The ABI requires %rsp to be a multiple of 16 at every call instruction. On entry to a function, %rsp ≡ 8 (mod 16), because the caller’s call just pushed 8 bytes onto an aligned stack. A function that calls others must therefore move %rsp by 8, 24, 40, … bytes, an odd multiple of 8. That is why call_incr uses 16 (gcc: 8 for v1, plus 8 to restore alignment once the frame and return address are counted) and clang uses exactly 8. The rule exists because some vector instructions (SSE movaps) require 16-byte-aligned memory operands, and a callee can only align its stack data if it knows how its frame starts.
Demo 02 PART D measures every function’s frame:
function frame what is in it
mult2 0 leaf, registers only
multstore 8 saved %rbx
incr 0 leaf, registers only
call_incr 8 v1 (these 8 bytes also restore 16-byte alignment)
call_incr2 24 saved %rbx, v1, 8 bytes padding
proc 0 leaf; reads its stack arguments from the CALLER's frame
call_proc 40 locals x1..x4, padding, 16-byte argument build area
pcount_r 24 saved %r14, %rbx + 8 bytes padding (per recursive call!)
rfact 8 saved %rbx (per recursive call)
popcount_t 0 a tail call: `jmp`, not `call`, so no new frame
Every non-leaf frame + 8 is a multiple of 16. Demo 03’s checker confirms that %rsp % 16 == 0 at every executed call, in every function, at both optimization levels.
4. Register saving conventions
4.1 The problem
All functions share the 16 registers. The slides’ example:
yoo: movq $15213, %rdx who: ...
call who subq $18213, %rdx
addq %rdx, %rax ...
ret ret
yoo keeps 15213 in %rdx across the call. who, compiled separately and with no knowledge of yoo, uses %rdx as scratch. 03_register_conventions.py runs it:
broken: who clobbers %rdx yoo() = -3000 WRONG
fix 1: CALLER saves %rdx around the call yoo() = 15213 (correct: 0 + 15213)
fix 2: keep it in %rbx; every CALLEE saves %rbx yoo() = 15213 (correct: 0 + 15213)
There are two ways to cooperate:
- Caller-saved (also “call-clobbered”): the callee may overwrite the register freely. A caller that needs the value after the call saves it in its own frame before the call, and restores it after.
- Callee-saved (also “call-preserved”): the callee must leave the register as it found it. If it wants to use the register, it saves the old value in its frame first and restores it before returning.
Either works, but both sides must agree, and that is what the convention is for.
4.2 The x86-64 rules
| Registers | Role | Kind |
|---|---|---|
%rax | return value | caller-saved |
%rdi %rsi %rdx %rcx %r8 %r9 | arguments 1–6 | caller-saved |
%r10 %r11 | temporaries | caller-saved |
%rbx %r12 %r13 %r14 %r15 | temporaries | callee-saved |
%rbp | temporary, or the frame pointer | callee-saved |
%rsp | stack pointer | special: restored to its entry value on return |
(The slide’s diagram lists %r12–%r14; %r15 is callee-saved as well.)
Why have both kinds? It is a cost trade-off. A short leaf function wants scratch registers it can use without saving anything: the caller-saved ones. A function that makes calls wants registers whose values survive those calls without saving and restoring around each one: the callee-saved ones. It pays one push/pop pair per function, not per call. With both kinds available, each function picks what is cheapest for it. You saw both in Lecture 4’s multstore: it parks dest in callee-saved %rbx, so it must push %rbx / pop %rbx around its body.
4.3 A checker for the contract
Can we check from the outside that compiled code obeys these rules? PART B of demo 03 runs every function of procs.c with random garbage in all 16 registers and checks three things: callee-saved registers come back unchanged, %rsp comes back unchanged, and %rsp is a multiple of 16 at every call. An excerpt:
clang -Og
function calls aligned? callee-saved it used caller-saved it changed (allowed)
multstore 1 yes %rbx -
call_incr2 1 yes %rbx %rcx %rsi %rdi
call_proc 1 yes - %rcx %rdx %rsi %rdi %r8 %r9 %r10
pcount_r 16 yes %rbx %r14 %rdi
rfact 9 yes %rbx %rdi
fix_prod_ele 0 - - %r8 %r9 %r10 %r11
...
36 function runs checked, 0 violations.
The compiler obeys the contract. Hand-written assembly need not. PART C feeds the checker bad_sum3, which computes a + b + c in %rbx without saving it:
checker on bad_sum3(1, 2, 3): callee-saved registers not restored: %rbx
caller() = 12, but C says bad_sum3(1,2,3) + 100 = 106.
Notice where the symptom appears. bad_sum3 returns the correct sum, 6. The wrong answer shows up in its caller, which kept k = 100 in %rbx and found 6 there instead. Testing bad_sum3 on its own would never find this bug. It is “action at a distance”, the theme of Lecture 1’s memory bug.
5. Recursion
5.1 Recursion needs nothing new
long pcount_r(unsigned long x) { // number of 1 bits, recursively
if (x == 0) return 0;
else return (x & 1) + pcount_r(x >> 1);
}
The slides’ gcc code:
pcount_r:
movl $0, %eax
testq %rdi, %rdi
je .L6 # x == 0: return 0, nothing saved
pushq %rbx # save the caller's %rbx
movq %rdi, %rbx
andl $1, %ebx # %rbx = x & 1, must survive the call
shrq %rdi # argument x >> 1
call pcount_r
addq %rbx, %rax # (x & 1) + pcount_r(x >> 1)
popq %rbx
.L6:
rep; ret
Each activation keeps its own x & 1 in callee-saved %rbx. Before reusing %rbx, it saves its caller’s value on the stack. So the values of all active calls are stacked in their frames. 04_recursion.py stops clang’s version of pcount_r(13) at its deepest point, 13 = 0b1101:
...dff8 RET return address -> caller
--------------------------------------------------
...dff0 43690 pcount_r(13)'s frame: saved %r14 = 0xaaaa (outside caller's value)
...dfe8 48059 saved %rbx = 0xbbbb (outside caller's value)
...dfe0 0 padding
...dfd8 0x40015c return address -> pcount_r
--------------------------------------------------
...dfd0 1 pcount_r(6)'s frame: saved %r14 = 1 = x&1 of its caller, pcount_r(13)
...dfc8 13 saved %rbx = 13 = x of its caller
...dfc0 0 padding
...dfb8 0x40015c return address -> pcount_r
--------------------------------------------------
...dfb0 0 pcount_r(3)'s frame: saved %r14 = 0 = x&1 of its caller, pcount_r(6)
... (and so on for pcount_r(1); pcount_r(0) has just been called)
The slides’ “Observations about recursion”, seen in this picture:
- Each call has private storage. Its frame holds saved registers, locals and its return address.
- The register convention protects each call’s data. An inner call saves the outer call’s
%rbx/%r14before reusing them, and restores them on the way out. - The stack discipline matches the call pattern. If P calls Q, Q returns before P: last in, first out.
- Mutual recursion works the same way. If P calls Q and Q calls P, each activation simply gets a frame.
The one thing that can corrupt another activation’s data is C code that writes outside its own variables, a buffer overflow, which is Lecture 6’s topic.
(clang -Og saves two registers, %r14 for x & 1 and %rbx for x itself, because at -Og it keeps variables alive for the debugger. Its frames are therefore 32 bytes, against 16 for gcc’s.)
5.2 What recursion costs
x result real x86 calls stack bytes
0x0 0 0 1 24
0xd 3 3 5 152
0xff 8 8 9 280
0xffffffffffffffff 64 64 65 2072
Stack use = frame size × depth. Here that is 32 bytes × (1 + the position of the highest 1 bit); the slides’ gcc version needs 16 bytes per call (PART C). That is harmless for pcount_r, whose depth is at most 65, but a recursion whose depth grows with the input size, such as a naive recursive list traversal, uses stack in proportion to the input.
How much stack is there? 05_frames_in_real_memory.c asks the OS and then runs the slides’ “runaway stack” example: a recursion with a 128 KiB local array per call, in a forked copy of the program so that the demo survives:
stack size limit (RLIMIT_STACK, soft) = 8176 KiB
x = 1000000. a at 0x16f346458
x = 999999. a at 0x16f3263a8
. . .
last report: depth 63, a at 0x16eb839b8
the child was killed by signal 11 (Segmentation fault: 11) -- a "segmentation fault"
frame size = 131248 bytes (128 KiB array + 176 bytes of other frame data)
predicted maximum depth = limit / frame size = 63
The main thread’s stack is a fixed region, 8 MiB on Linux and 8,176 KiB on this Mac. Below it lies an unmapped guard region. A recursion that walks past the limit touches it and is killed with SIGSEGV; C never gives an error message. The same program built for x86-64 dies at the same depth. Its PART A shows real frames of depth_probe exactly 32 bytes apart on both architectures, the same “one block per call” picture as the simulator’s.
5.3 Tail calls, and recursion removed by the compiler
The slides’ bonus: a tail-recursive popcount passes the running sum down, so nothing remains to be done after the recursive call:
long popcount_t(unsigned long x, long s) {
if (x == 0) return s;
long b = x & 1UL;
return popcount_t(x >> 1, s + b);
}
clang -Og compiles the recursive call as jmp _popcount_t instead of call. The callee reuses the current frame and return address, and when it finally returns, it returns straight to the original caller. Stack use: 0 bytes for any x (PART D). The slides’ gcc code goes one step further and turns it into a loop.
PART E shows a surprise: at -O1 clang removes the recursion from all three functions, including pcount_r and rfact, which are not tail recursive (their + and * happen after the call). Because + and * are associative, the compiler can introduce an accumulator, effectively rewriting pcount_r into popcount_t, and then the tail call becomes a loop:
pcount_r 0xffffffffffffffff 64 calls 1 stack bytes 0
rfact 20 2432902008176640000 1 0
C does not promise this optimization (unlike Scheme, which requires tail calls to use no stack), and it disappears at -O0 and in many slightly different functions. Never rely on it to make deep recursion safe.
6. Arrays
6.1 Memory has no types
The slides start with a reminder. Memory locations do not have data types. A byte at address 0x4004 is just a byte. It is part of an int only because some instruction reads 4 bytes starting at 0x4000. Types live in the instructions (movl vs movq, movzbl) and in the address arithmetic, which the compiler derives from the C types. The address of a multi-byte object is the address of its first byte, and successive objects of a type are sizeof apart.
6.2 Allocation and access
T A[L]; is an array of L elements of type T: one contiguous block of L * sizeof(T) bytes. Element i starts at x + i * sizeof(T), where x is the array’s address. 06_arrays.c PART A checks the slides’ four examples:
declaration bytes element offsets from x
char string[12] 12 0 1 2 3 4 5 6 7 8 9 10 11
int val[5] 20 0 4 8 12 16
double a[3] 24 0 8 16
char *p[3] 24 0 8 16
The identifier A, used as a value, acts like a pointer to element 0 (type T *). Pointer arithmetic is scaled: A + i means x + i * sizeof(T) bytes. The slides’ access table for int val[5] = {1, 5, 2, 1, 3} (PART B):
| Expression | Type | Value |
|---|---|---|
val[4] | int | 3 |
val[5] | int | ?? — one past the end: undefined (C never checks bounds) |
*(val+3) | int | 1 (same as val[3]) |
val | int * | x |
val+1 | int * | x + 4 |
&val[2] | int * | x + 8 (same as val+2) |
val + i | int * | x + 4i (same as &val[i]) |
In C, A[i] is defined as *(A + i). That is why the two forms are interchangeable, and why (strangely but legally) i[A] also works.
6.3 The machine code
The slides’ zip-code arrays: typedef int zip_dig[5]; zip_dig cmu = {1, 5, 2, 1, 3};. Accessing one digit is one instruction (07_array_code.py PART A):
int get_digit(zip_dig z, int digit) { return z[digit]; }
movslq %esi, %rcx # 64-bit copy of the int index (sign-extended)
movl (%rdi,%rcx,4), %eax # z[digit] = M[z + 4*digit]
The addressing mode (%rdi,%rcx,4) is array indexing: base + 4 × index. Because digit is an int, the 64-bit address calculation first needs it sign-extended (movslq). The slide’s listing leaves that step out.
A loop over an array, the slides’ zincr:
void zincr(zip_dig z) { size_t i; for (i = 0; i < ZLEN; i++) z[i]++; }
The slides’ gcc code uses Lecture 4’s jump-to-middle shape: jmp .L3 to the test cmpq $4,%rax; jbe .L4, with jbe because i is unsigned. clang uses one read-modify-write instruction per element, incl (%rdi,%rax,4), and a cmpq $5, %rax; jne at the bottom of the loop.
6.4 Arrays vs pointers
An array variable is its storage; a pointer variable is 8 bytes that may or may not point at storage. sizeof tells them apart (PART F):
declaration sizeof An sizeof *An sizeof **An
int A1[3] 12 4 -
int *A2 8 4 -
int A3[3][5] 60 20 4
int *A4[3] 24 8 4
int (*A5)[3] 8 12 4
Declaring int *A2 allocates no ints at all, so *A2 reads through an uninitialized pointer: a bad reference. int (*A5)[3] is a pointer to an array of 3 ints (the parentheses matter). int *A4[3] is an array of 3 pointers. When reading declarations like these, start at the name and work outward: [] and () bind tighter than *.
7. Multidimensional (nested) arrays
7.1 Row-major order
T A[R][C]; is an array of R rows, each an array of C elements, in one block of R * C * sizeof(T) bytes, stored row by row (row-major order): A[0][0] … A[0][C-1], then A[1][0] …. With K = sizeof(T):
The slides’ example: zip_dig pgh[4] is the same as int pgh[4][5], four zip codes in 80 bytes. Demo 06 PART D checks the formula on all 20 elements:
pgh[0] starts at pgh + 0 : 1 5 2 0 6
pgh[1] starts at pgh + 20 : 1 5 2 1 3
pgh[2] starts at pgh + 40 : 1 5 2 1 7
pgh[3] starts at pgh + 60 : 1 5 2 2 1
&pgh[i][j] == pgh + 4*(5*i + j): 20 of 20 elements agree
Because the block is contiguous, a 2-D array can also be walked as one long 1-D array. The slides’ quiz (PART C): pgh[0][0] + linear_zip[7] + *(linear_zip + 8) + zip2[1] with linear_zip = (int *)pgh and zip2 = (int *)pgh[2] gives 1 + 2 + 1 + 5 = 9. linear_zip[7] is row 1, column 2; zip2[1] is pgh[2][1].
7.2 The machine code
A row (pgh[index], an array of 5 ints, which decays to a pointer) is at pgh + 20*index. The slides’ gcc code computes 20 × index as 4 × (index + 4 × index) with two leas:
leaq (%rdi,%rdi,4), %rax # 5 * index
leaq pgh(,%rax,4), %rax # pgh + 20 * index
An element is one memory read after the address arithmetic. clang’s get_pgh_digit:
leaq (%rdi,%rdi,4), %rax # 5 * index
leaq _pgh(%rip), %rcx # &pgh
leaq (%rcx,%rax,4), %rax # pgh + 20 * index
movl (%rax,%rsi,4), %eax # M[pgh + 20*index + 4*dig]
Why the extra leaq _pgh(%rip)? The slides’ code was built as a fixed-address (non-PIE) Linux program, so pgh is a 32-bit constant that fits in the displacement of pgh(,%rax,4). On macOS, and in modern Linux PIE programs, code must work at any load address, so global addresses are computed relative to %rip first. Lecture 7 explains why.
8. Multi-level arrays
The slides’ alternative representation: three separate zip-code arrays and an array of pointers to them:
zip_dig cmu = {1, 5, 2, 1, 3}, mit = {0, 2, 1, 3, 9}, ucb = {9, 4, 7, 2, 0};
int *univ[3] = {mit, cmu, ucb};
int get_univ_digit(size_t index, size_t digit) { return univ[index][digit]; }
univ is 24 bytes: three 8-byte pointers. The rows are elsewhere, wherever the compiler and linker put them. The element access is
two memory reads, the first producing the address used by the second. The slides’ gcc code:
salq $2, %rsi # 4*digit
addq univ(,%rdi,8), %rsi # p = univ[index] + 4*digit (read 1)
movl (%rsi), %eax # return *p (read 2)
Demo 07 PART C counts the reads on clang’s code:
call sim real memory reads (in order) count
get_pgh_digit(1, 2) 2 2 pgh+28 (4 bytes) 1
get_univ_digit(1, 2) 2 2 univ+8 (8 bytes), cmu+8 (4 bytes) 2
Same C syntax x[i][j], different machine work. Which representation is better?
Nested int A[R][C] | Multi-level int *A[R] | |
|---|---|---|
| memory | one block, R·C·K bytes | R pointers + R separate rows |
| element access | arithmetic + 1 read | 2 dependent reads |
| row lengths | all equal, fixed | may differ (“ragged” arrays, like char *argv[]) |
| swapping two rows | copy C elements | swap two pointers |
| locality (Lecture 9) | excellent: one contiguous block | rows may be scattered |
9. N×N matrices: fixed vs variable size
9.1 Two ways to declare the same thing
#define N 16
typedef int fix_matrix[N][N];
int fix_ele(fix_matrix A, size_t i, size_t j) { return A[i][j]; }
int var_ele(size_t n, int A[n][n], size_t i, size_t j) { return A[i][j]; } // C99
fix_ele: var_ele:
shlq $6, %rsi # 64*i imulq %rdi, %rdx # n*i
addq %rdi, %rsi # A + 64*i leaq (%rsi,%rdx,4), %rax # A + 4*n*i
movl (%rsi,%rdx,4), %eax movl (%rax,%rcx,4), %eax # M[A + 4*n*i + 4*j]
When the row length C·K = 16 × 4 = 64 is a compile-time constant, i * 64 is a shift. When n is only known at run time, the compiler must emit a real multiply. Before C99 added variable-length array parameters, you had to write the index arithmetic yourself, A[i*n + j] on an int *A, and get it right. Demo 07 PART D checks both functions on every element (256 for fix_ele; 84 over n = 1, 3, 5, 7 for var_ele) against the hardware: all agree.
9.2 Loops over matrices: strength reduction
CS:APP’s Figure 3.37 computes one element of a matrix product:
int fix_prod_ele(fix_matrix A, fix_matrix B, size_t i, size_t k) {
int result = 0;
for (size_t j = 0; j < N; j++) result += A[i][j] * B[j][k];
return result;
}
Evaluated naively, each iteration would compute B + 64*j + 4*k. The compiler does better (PART E, clang -O1):
shlq $6, %rdx # A + 64*i: start of row i
addq %rdi, %rdx
leaq (%rsi,%rcx,4), %rcx # &B[0][k]: top of column k
...
LBB17_1:
movl (%rcx), %edi # B[j][k]
imull (%rdx,%rsi,4), %edi # * A[i][j]
addl %edi, %eax
incq %rsi # j++
addq $64, %rcx # down one row of B
cmpq $16, %rsi
jne LBB17_1
The column pointer starts at &B[0][k] and moves 64 bytes (one row) per iteration. A multiplication inside the loop has become an addition: the classic optimization strength reduction, which Lecture 15 revisits. Note also how the access pattern differs: row i of A is walked 4 bytes at a time, but column k of B jumps 64 bytes per step. In Lectures 9–10 that difference decides how fast matrix code runs.
10. Is the simulator right?
08_crosscheck.py runs 547 tests through the simulator on clang’s -Og and -O1 code and compares them with the real x86-64 build and the native arm64 build. The tests cover every function, including pointer arguments, stack arguments, recursion depths up to 65 and all matrix elements. 0 disagreements at both levels.
To check that the test can fail, the demo temporarily plants a bug in the simulator: arguments 7 and 8 pushed in the wrong order. Result: 76 disagreements, all in proc, the only function with stack arguments. This shows both that the check has teeth and that a check is only as good as the cases it exercises. Had proc not been in the test set, the bug would have gone unnoticed.
To support this lecture the simulator gained calls with more than six arguments, a “start a call but do not run it” mode used to stop at interesting moments, and a log of memory reads. All Lecture 3 and 4 demos were re-run after each change, and their output was byte-for-byte identical to before.
Summary
- Procedures need three mechanisms: passing control (
call/ret), passing data and managing local data. x86-64 implements each with ordinary instructions, and only when needed. - Arguments 1–6 go in
%rdi %rsi %rdx %rcx %r8 %r9, each used at its own size. Arguments 7+ go on the stack in 8-byte slots: the caller builds them at the top of its frame, and the callee finds them at8(%rsp),16(%rsp), …. The return value goes in%rax. - A stack frame holds what cannot stay in registers: locals whose address is taken, saved callee-saved registers, the argument build area and alignment padding. Set-up code moves
%rspdown, finish code moves it back.%rspis a multiple of 16 at every call. Leaf functions often need no frame. - Caller-saved (
%rax %rcx %rdx %rsi %rdi %r8–%r11): the callee may clobber them. Callee-saved (%rbx %rbp %r12–%r15): the callee must restore them. Breaking the contract corrupts the caller. - Recursion works because every activation has a frame and every callee saves its caller’s callee-saved registers. Stack use = frame × depth, and the stack is limited (8 MiB; the runaway demo died at depth 63). Tail calls (
jmp) use no stack. Compilers sometimes remove recursion, but C does not promise it. - Arrays:
&A[i] = A + i·K. NestedT A[R][C]: one block, row-major,&A[i][j] = A + (i·C + j)·K, one memory read. Multi-levelT *A[R]: two dependent reads. Fixed sizes allow shifts; variable sizes needimul. Loops step pointers by the element or row size.
Common pitfalls
- Forgetting that argument registers are caller-saved. After a call,
%rdiand friends hold garbage, so an argument needed later must be saved first (in%rbxor on the stack). - Expecting argument 7 at
0(%rsp)in the callee.0(%rsp)is the return address; argument 7 is at8(%rsp). - Returning a pointer to a local variable. The frame is released by
ret; the pointer then aims at stack space that the next call will overwrite (Lecture 4: “pop does not erase”, so it may even seem to work). - Assuming recursion is free. Each level costs a frame; deep recursion is a crash waiting for a big input. Prefer loops, or an explicit stack on the heap.
- Confusing
int *a[3]withint (*a)[3]. The first is an array of 3 pointers (24 bytes); the second is one pointer to an array of 3 ints (8 bytes). - Treating a nested array and a multi-level array as interchangeable.
int **p = pgh;does not work:pghhas no row pointers stored anywhere. - Reading
x[i][j]in assembly without knowing which kind of array it is. Look for one read (nested) or two dependent reads (multi-level).
Exercises
-
Where do they go? For
long f(char a, long *b, int c, short d, long e, long *g, int h, char k), where is each argument on entry tof(register name at the right size, or stack offset)?Answer
a: `%dil`; b: `%rsi`; c: `%edx`; d: `%cx`; e: `%r8`; g: `%r9`; h: `8(%rsp)` (low 4 bytes of the slot); k: `16(%rsp)` (low byte of the slot). -
Frame size. A function calls another function, saves
%rbxand%r12, and has onelonglocal whose address is taken. What is the smallest frame (excluding the return address) that satisfies the alignment rule?Answer
Needed: 16 bytes of saved registers + 8 for the local = 24. On entry %rsp ≡ 8 (mod 16); after moving down 24 bytes, %rsp ≡ 8 − 24 ≡ 0 (mod 16). So 24 bytes works with no padding (24 + 8 = 32 is a multiple of 16). -
Read a frame. Explain each instruction:
f: pushq %rbx subq $16, %rsp movq %rdi, %rbx movq %rsi, 8(%rsp) leaq 8(%rsp), %rdi call g addq %rbx, %rax addq $16, %rsp popq %rbx retAnswer
`f(x, y)` saves the caller's %rbx (callee-saved), allocates 16 bytes (8 for a local + 8 of padding: 8 + 8 + 16 = 32), keeps x in %rbx so it survives the call, stores y in a stack local at 8(%rsp), passes its address to g, and returns x + g(&y). A C version: `long f(long x, long y) { return x + g(&y); }`. -
Which convention? Why does a recursive function like
pcount_ruse a callee-saved register forx & 1rather than a caller-saved one?Answer
The value must survive the recursive call. Both choices are correct. With a caller-saved register, `pcount_r` would store it in its frame before the call and reload it after. With callee-saved `%rbx`, it pays one push and one pop per activation, saving its *caller's* `%rbx`. For one call site the costs are similar. The callee-saved form wins as soon as a function has several call sites: it saves once per function instead of around every call. Callees that never touch `%rbx`, such as most leaf functions, pay nothing. So compilers keep values that live across calls in callee-saved registers. -
Stack depth. A recursive function has a 48-byte frame (plus 8 for the return address). Roughly how deep can it recurse in an 8 MiB stack?
Answer
8 × 220 / 56 ≈ 149,796 levels, minus whatever main and the runtime already use. A linked list longer than that, processed recursively, crashes. -
Address arithmetic.
short S[7][9];starts at addressxs. What is the address ofS[3][5]? Write the address calculation as an assembly expression giveniin%rdi,jin%rsi, andxsin%rdx.Answer
`xs + 2·(9·3 + 5) = xs + 64`. In general `xs + 2·(9i + j)`: `leaq (%rdi,%rdi,8), %rax` (9i); `addq %rsi, %rax` (9i + j); `movw (%rdx,%rax,2), %ax`. -
Reverse-engineer the dimensions.
int A[R][C];and the code forreturn A[i][j];isleaq (%rdi,%rdi,2),%rax; leaq (%rsi,%rax,4),%rax; movl A(,%rax,4),%eax(i in %rdi, j in %rsi). What is C?Answer
%rax = 3i, then j + 4·3i = 12i + j, so the element index is 12i + j and C = 12. R cannot be determined from this code, because the compiler does no bounds checks. -
Nested or multi-level? A function compiles to
movq (%rdi,%rsi,8), %rax; movl (%rax,%rdx,4), %eax. Is its first argument a nested array, or a multi-level one? What are the element types?Answer
Multi-level: the first instruction reads an 8-byte pointer from a table (A[i]), and the second reads a 4-byte int at that pointer + 4j. So the argument has type `int **` (or `int *A[]`): `int f(int **A, long i, long j) { return A[i][j]; }`.
The related lab: L1 (datalab) due today, and L2 (bomblab)
Datalab is due tonight; it uses only Lecture 2. Bomblab, released at Lecture 4, now needs this lecture. Most phases call helper functions, so read each call in terms of the convention. Which registers carry the arguments (often a pointer to your input string, or an array filled by a parsing function)? Which value is checked in %rax after the call? Which callee-saved registers does the phase use to keep values across calls? Some phases loop over an array with a scaled index, or follow pointers through a linked structure. Others call a recursive helper: draw its frames as in §5.1 and work out what one activation computes from its arguments, before guessing inputs. In gdb, bt shows the frames, info frame shows a frame’s saved registers, and x/6dw $rsp+8 dumps an array on the stack. These notes contain no bomb solutions.
Further reading
- CS:APP3e §3.7 (procedures) and §3.8 (arrays), practice problems 3.32–3.41; §3.10.5 for variable-size stack frames and
%rbp. - The System V AMD64 ABI document (chapter 3: “Function Calling Sequence”). It is the authority on registers, alignment and the red zone (128 bytes below
%rspthat leaf functions may use without moving%rsp, a detail the slides skip). - Compiler Explorer (godbolt.org): compile
pcount_randrfactwith gcc and clang at -O0, -O1 and -O2 and watch the recursion disappear. - The optional machine-programming “activities” linked from the course schedule.
Preview of Lecture 6: Machine-level programming IV, data and security
Arrays group values of one type; structures group values of different types, and the compiler inserts padding to keep each field aligned, so field order can change a struct’s size. Lecture 6 then looks at the whole memory layout of a running process (stack, heap, data, code, shared libraries). It also covers what happens when a write runs past the end of a stack array: the buffer overflow. You now know exactly what lies above a local array in a frame: saved registers and the return address. Lecture 6 shows why overwriting them is dangerous, and the three standard defenses (stack canaries, non-executable stacks, address-space randomization) that make it hard to exploit. It ends with unions.
术语表 (Glossary, English → 中文)
| English | 中文 |
|---|---|
| procedure / function | 过程 / 函数 |
| passing control / passing data | 传递控制 / 传递数据 |
| argument / parameter | 实参 / 形参 |
| return value | 返回值 |
| calling convention | 调用约定 |
| application binary interface (ABI) | 应用程序二进制接口 |
| System V AMD64 ABI | System V AMD64 应用二进制接口 |
| argument build area | 参数构造区 |
| stack frame | 栈帧 |
| set-up code / finish code | 建立代码(序言)/ 收尾代码(尾声) |
| prologue / epilogue | 函数序言 / 函数尾声 |
| frame pointer (%rbp) | 帧指针 |
| stack pointer (%rsp) | 栈指针 |
| stack alignment (16-byte) | 栈对齐(16 字节) |
| leaf function | 叶函数(不调用其他函数的函数) |
| local variable | 局部变量 |
| reentrant | 可重入 |
| stack discipline | 栈规则(后进先出的调用纪律) |
| instantiation / activation | 实例 / 活动记录(一次调用) |
| caller / callee | 调用者 / 被调用者 |
| caller-saved (call-clobbered) | 调用者保存(调用会破坏) |
| callee-saved (call-preserved) | 被调用者保存(调用会保留) |
| register spilling | 寄存器溢出到栈(溢写) |
| recursion / mutual recursion | 递归 / 相互递归 |
| tail call / tail recursion | 尾调用 / 尾递归 |
| accumulator | 累加器 |
| stack overflow (too-deep recursion) | 栈溢出(递归过深) |
| guard page | 保护页 |
| resource limit (RLIMIT_STACK) | 资源限制(栈大小上限) |
| segmentation fault (SIGSEGV) | 段错误 |
| backtrace | 调用栈回溯 |
| array / element | 数组 / 元素 |
| pointer arithmetic | 指针运算 |
| bounds checking | 边界检查 |
| nested (multidimensional) array | 嵌套(多维)数组 |
| multi-level array (array of pointers) | 多级数组(指针数组) |
| row-major order | 行优先顺序 |
| ragged array | 锯齿数组(各行长度不同) |
| variable-length array (VLA) | 变长数组 |
| strength reduction | 强度削减 |
| position-independent executable (PIE) | 位置无关可执行文件 |
| sign extension (movslq) | 符号扩展 |