Summary
Lecture 14 delves into how function calls are implemented in assembly language. It explains the crucial role of the stack in managing function calls, including parameter passing, local variable storage, and return addresses. The lecture also covers the mechanics of the %rip register (instruction pointer) and how it’s affected by function calls and returns. Key instructions like push, pop, callq, and retq are discussed in detail. The concept of register saving and restoring is introduced to ensure proper function execution.
1. Recap: Control Flow
- C control flow statements (if/else, while, for) are implemented in assembly using condition codes and conditional jumps.
- Condition codes (CF, ZF, SF, OF) store results of arithmetic/logic operations.
setinstructions, conditionalmovinstructions, and conditionaljmpinstructions use condition codes.jmpinstruction:jmp Label: Direct jump.jmp *Operand: Indirect jump.
2. The Instruction Pointer (%rip)
%ripregister stores the address of the currently executing instruction.- Instructions are just bytes in memory.
- Hardware increments
%ripto the next instruction. jmpinstructions modify%ripto change the flow of execution.- Relative jumps use offsets (e.g.,
jmp 0x40057a).
3. Calling Functions
- Calling a function involves:
- Passing control to the callee and resuming caller execution later.
- Passing data (parameters, return values).
- Managing memory (stack).
4. The Stack
%rspregister stores the address of the top of the stack.- Stack grows downwards in memory.
- Stack frames are used to store function data.
%rspmust be the same before and after a function call.push S:- Decrements
%rspby 8. - Stores the value of S at the new top of the stack.
- Decrements
pushq Sis equivalent tosubq $8, %rsp; movq S, (%rsp).pop D:- Reads the value from the top of the stack.
- Stores it in D.
- Increments
%rspby 8.
popq Dis equivalent tomovq (%rsp), D; addq $8, %rsp.
5. Passing Control
callq Label:- Pushes the return address (address of the next instruction in the caller) onto the stack.
- Jumps to the callee’s code (modifies
%rip).
retq:- Pops the return address from the stack.
- Jumps to the return address (modifies
%rip).
6. Passing Data
- Registers are used to pass parameters.
%rdi: 1st parameter%rsi: 2nd parameter%rdx: 3rd parameter%rcx: 4th parameter%r8: 5th parameter%r9: 6th parameter%raxis used to return the return value.
7. Local Storage
- The stack is used for local variables that don’t fit in registers.
- Callees can push data onto the stack.
8. Register Restrictions
- Callee-saved registers:
%rbp,%rbx,%r12-%r15Callees must preserve their original values. - If a callee modifies a callee-saved register, it must:
- Push the original value onto the stack before modifying it.
- Pop the original value from the stack before returning.
- Caller-saved registers: All other registers. The caller must save these if it wants to preserve their values across function calls.