Assignment 11: functions, calling conventions, and the stack
|
|
- Nigel Warner
- 6 years ago
- Views:
Transcription
1 Assignment 11: functions, calling conventions, and the stack ECEN 4553 & 5013, CSCI 4555 & 5525 Prof. Jeremy G. Siek December 5, 2008 The goal of this week s assignment is to remove function definitions and function calls, replacing them with operations that manipulate a stack, where each element of the stack is a chunk of data about a function invocation. These chunks are called activation records (or frames). They contain the arguments to a function, its local variables, the return address, and other information needed to execute the function. With the removal of function definitions, our IR (intermediate representation) will nearly be at the same abstraction-level as x86 assembly, so we will be able to emit assembly code to test this pass. After this week, the structure of the compiler will match what is shown in Figure 1. 1 Background Before diving into the details of how a stack is used to implement functions, let us recall why a stack is needed in the first place and why it is the right data-structure for the job. Consider the following recursive function that computes the nth Fibonacci number. int fib(int n) { if (n == 0 n == 1) return n; else return fib(n - 2) + fib(n - 1); } The calls made to the fib function can be visualized as a tree. Figure 2 shows the tree that results from calling fib(6). The execution of fib(6) can be thought of as a depth-first search through this tree that visits the subtree on the left before visiting the subtree on the right. So fib(6) invokes fib(4), which invokes fib(2), which calls fib(0). Once execution reaches 1
2 Python Text Lex & Parse Python AST Class and Object Lowering Variable Heapification Closure Conversion Convert to C-level AST Type Analysis & insert casts Insert Variable Declarations Convert to SSA Form C-level AST Remove Complex Opera* Remove Structured Control Remove 3-operand Instructions Remove Functions Emit x86 Lower Complex Assignments x86 Assembly Figure 1: Structure of the compiler. fib(0) fib(1) fib(0) fib(1) fib(0) fib(1) fib(0) fib(1) fib(1) fib(2) fib(0) fib(1) fib(1) fib(2) fib(1) fib(2) fib(2) fib(3) fib(2) fib(3) fib(3) fib(4) fib(4) fib(5) fib(6) Figure 2: The call tree for fib(6). 2
3 a leaf in the tree, it backtracks to the previous node and continues with the subtree on the right, so from fib(0) we backtrack to fib(2) and invoke fib(1). Once that is complete we again backtrack, but this time fib(2) is complete so we backtrack further to fib(4). Now, consider what is needed to implement this backtracking. We need to keep track of where we came from, that is, the sequence of nodes that led to the current node. Furthermore, for each node in the sequence, we need to keep track of what remains to be done and the values of the intermediate results. For example, when we return to fib(4) after computing fib(3), we need to remember the result of fib(2) so that we can add it to the result of fib(3). Also, note that as execution proceeds, we only add and remove nodes from the front of this sequence. Therefore, a stack data-structure is the appropriate choice, where each item in the stack contains information about intermediate results and what is left to be done. When the program is about to be run, the operating system creates a process and dedicates a chunk of memory to it. In Linux, this memory is laid out as shown The Stack in Figure 3. Memory addresses increase from bottom to Free Memory top. So the heap, which is the memory dedicated to object allocated with malloc, grows up, and the stack, used The Heap Static Data Program Code Figure 3: Memory Layout for a Linux Process. for activation frames, grows down. Having an upsidedown stack is confusing because tradition refers to the top of the stack as the place where items are pushed and popped. However, because this stack is upside-down, the top is lower than the bottom. To avoid further confusion, we refer to the front of the stack as the place where items are pushed and popped. The machine code for the program itself is stored at the bottom. Static data, such as string constants, is stored directly above the program code. The way in which a function should manipulate the stack is governed by calling conventions. By following an agreed-to set of conventions, different functions can work together, even if they are compiled by different compilers (so long as the compilers all follow the same calling convention). Figure 4 is a diagram of the stack focusing on the current activation record at the front of the stack. The %esp register is the stack pointer and it should always point to the front of the stack. The instruction pushes the contents of a 32-bit (double-word or 4-byte) register onto the stack, e.g., %eax pushes the value of the %eax register. The instruction does this by decrementing the %esp by 4 bytes so that it 3
4 points to an empty memory location and then writes the contents of the register to the address in %esp. The instruction %eax is equivalent to the following. subl $4, %esp movl %eax, (%esp) The popl instruction does just the opposite. It removes an item from the front of the stack. The popl instruction accomplishes this by loading the value at the %esp address into a register and then incrementing the stack pointer by 4 bytes. The instruction popl %eax is equivalent to the following. movl (%esp), %eax addl $4, %esp Previous Activation Records { The Current Activation Record{ The Stack arg 2 arg 1 arg 0 old instr. pointer old base pointer callee-save 0 callee-save 1 local 0 local 1 local 2 Free Memory higher addresses %ebp %esp lower addresses Figure 4: An activation record following the Linux x86 calling conventions. To call a function, you push the arguments for the function on the stack in reverse order and invoke the call instruction. Once the function is complete, control will be returned to the instruction following the call, which should pop the arguments from the stack by incrementing the stack pointer the appropriate number of bytes. For example, the call fib(6) corresponds to the following assembly code. $6 call fib addl $4, %esp The call instruction does two things: it pushes return address on the top of the stack and it jumps to the address indicated by the label, in this case fib. In Figure 4, the return address is in the slot labeled old instr. pointer. Figure 5 shows the assembly code produced by the GNU C compiler for the fib function. The base pointer (register %ebp) is used to keep track of where the function arguments and local variables are located on the stack. The arguments start at eight bytes above the base pointer and continue up. 4
5 For example, 8(%ebp) refers to argument 0 of the function and 12(%ebp) refers to argument 1 (assuming that argument 0 takes up 4 bytes). The base pointer is also used by the leave instruction (more about this later). The first thing a function needs to do is save the base pointer and then change it to point to the same place as the current stack pointer. fib: %ebp movl %esp, %ebp %ebx subl $4, %esp cmpl $0, 8(%ebp) je.l3 cmpl $1, 8(%ebp) je.l3 jmp.l2.l3: movl 8(%ebp), %eax movl %eax, -8(%ebp) jmp.l1.l2: movl 8(%ebp), %eax subl $2, %eax %eax call fib addl $4, %esp movl %eax, %ebx movl 8(%ebp), %eax decl %eax %eax call fib addl $4, %esp addl %eax, %ebx movl %ebx, -8(%ebp).L1: movl -8(%ebp), %eax movl -4(%ebp), %ebx leave ret Figure 5: x86 assembly code for the fib function. The next thing a function needs to do is to save the values of any callee-save registers that the function plans to use. The GNU C convention is that %ebx, %esi, %edi, and %ebp are designated as callee-save. The rest of the register are caller-save: %eax, %ecx, and %edx. In Figure 5 we see the %ebx register being pushed onto the stack just after the base pointer. The value for %ebx is retrieved from the stack at the very end of the fib function. After the callee-save registers are saved, the function makes room for any local variables that need to be stored on the stack. For the fib function, there is just one local variable stored on the stack; it is used to store the result of the function. To make room for this variable, 4 bytes are subtracted from the stack pointer. Later in the function, this variable is referred to as -8(%ebp). Scanning towards the middle of the fib function we see two calls to fib. In each case the argument is pushed on the stack, the call to fib is made, and then the argument is removed by adding 4 to the stack pointer. At the end of the function are two instructions: leave followed by ret. The leave instruction copies the contents of the %ebp register into the %esp register, so %esp points to the old base pointer. It then pops the old base pointer into the %ebp register. The ret instruction pops the return address from the stack and jumps back to the calling function. Exercise 1.1. Read chapter 6 through of the Intel 64 and IA-32 Architectures Software Developer s Manual Volume 5
6 1. The advice given in this chapter is quite general, whereas the above description is specific to GNU C calling conventions. Passing Large Objects If your pyobj type is larger than 32 bits, then special care is needed for passing pyobjs as function arguments and returning then from a function. Let s see how the GNU C compiler handles the following program. #include <stdio.h> struct pyobj { int tag; union { int i; double f; } u; }; struct pyobj add(struct pyobj a, struct pyobj b) { struct pyobj r; r.tag = 0; r.u.i = a.u.i + b.u.i; return r; } int main() { struct pyobj x, y, z; y.tag = 0; y.u.i = 40; z.tag = 0; z.u.i = 2; x = add(y, z); printf("%d\n", x.u.i); return 0; } Here s the interesting portion of the assembly code for the main function. The object x is stored at -16(%ebp) through -24(%ebp), y is stored at -32(%ebp) through -40(%ebp), and z is stored at -48(%ebp) through -56(%ebp). The sequences of pushes leading up to call to the add function push z, then y, then the address of x. The leal instruction put the address in the eax register and the final before the call put the address onto the stack. main:... leal -24(%ebp), %eax -48(%ebp) -52(%ebp) -56(%ebp) -32(%ebp) -36(%ebp) -40(%ebp) 6
7 call addl subl call... %eax add $28, %esp $8, %esp -20(%ebp) $.LC0 printf The assembly code for the add function is shown below. add: %ebp movl %esp, %ebp subl $24, %esp movl 8(%ebp), %edx movl $0, -24(%ebp) movl 28(%ebp), %eax addl 16(%ebp), %eax movl %eax, -20(%ebp) movl -24(%ebp), %eax movl %eax, (%edx) movl -20(%ebp), %eax movl %eax, 4(%edx) movl -16(%ebp), %eax movl %eax, 8(%edx) movl %edx, %eax leave ret $4 The parameter b is stored in 24(%ebp) through 32(%ebp) and a is stored in 12(%ebp) through 20(%ebp) (which is where main put them when it pushed the arguments z and y). The address for the return value is in 8(%ebp). The local variable r is store in -24(%ebp) through -16(%ebp). Starting with the instruction movl -24(%ebp), %eax, the assembly code is copying r into the return value. This is a memory-to-memory copy and x86 does not have a general purpose instruction that copies memory to memory. Instead one 32-bit chunk at a time of r is copied into the %eax register and then copied into the return value, where the %edx register holds the address of the return value. The instruction movl %edx,%eax moves the address of the return value into the eax register. This move seems to be unnecessary and is not generated when optimization is turned on in gcc. 7
8 2 Remove Functions In this pass we remove the CallFunc and Return AST nodes and add the following new kinds of nodes. class Call: def init (self, label): self.label = label class Push: def init (self, arg): self.arg = arg class FPush: def init (self, arg): self.arg = arg class FPop: def init (self, arg): self.arg = arg class Register: def init (self, name): self.name = name class Address: def init (self, arg): self.arg = arg class Deref: def init (self, arg): self.arg = arg class Offset: def init (self, arg, offset): self.arg = arg self.offset = offset class Leave: pass class Ret: pass The Push AST node corresponds to the x86 instruction that pushes an item on the stack. The Call AST node corresponds to the x86 call instruction. 8
9 2.1 Translating CallFunc For the simple case when all of the arguments and the return value are small (32 bits), the CallFunc node is translated as follows, where m is the sum of the sizes of the arguments. CallFunc(Name(f), [arg 1,..., arg n ]) Push(arg n )... Push(arg 1 ) Call(f) Register( esp ) += m If an argument is large, then instead of a single Push you ll take the address of the argument and then use several Pushs. Suppose that arg i is 12 bytes. Then you ll need three Pushs to copy it onto the stack. Push(Offset(Name(arg i ), 8)) Push(Offset(Name(arg i ), 4)) Push(Offset(Name(arg i ), 0)) If the return type of the function is larger than 32 bits, then you need to push the address of the return value onto the stack just before the Call. Assign([AssName(x, OP_ASSIGN )], CallFunc(Name(f), [arg 1,..., arg n ])) Push(arg n )... Push(arg 1 ) tmp = Address(x) Push(tmp) Call(f) Register( esp ) += m If the CallFunc did not appear on the RHS of an assignment, then you must first create a new temporary variable and an assignment statement where the temporary is the LHS and the CallFunc is on the RHS. Then proceed as shown above. The temporary variable will need a VarDecl at the beginning of the function. If the return value of the function is a floating point number, then it is returned on the floating point stack. The FPop AST node corresponds to the fstpl instruction. Assign([AssName(x, OP_ASSIGN )], CallFunc(Name(f), [arg 1,..., arg n ])) Push(arg n )... Push(arg 1 ) 9
10 Call(f) Register( esp ) += m FPop(x) 2.2 Translating Return If the argument to return is small, then simple assign the argument to the %eax register and then issue the Leave and Ret instructions. Return(e) Register( eax ) = e Leave() Ret() If the argument is large, then copy the value into the return value. We ll introduce a special variable named ret to represent the address of the return value. Return(x) Deref( ret) = x Leave() Ret() If the argument is a floating point number, then load into onto the floating point stack. The FPush AST node corresponds to the fldl instruction. Return(x) FPush(x) Leave() Ret() 2.3 Assign Stack Locations to Parameters and Locals We assign a location on the stack to each parameter and local variable of a function. The location will be specified by an offset relative to the base pointer. The parameters get positive offsets and the local variables get negative offsets. The first parameter gets offset 8. Each parameter after the first gets an offset that is equal to the offset for the previous parameter plus the size of the previous parameter. So if the first parameter is 4 bytes, the second parameter gets offset 12. The first local variable is at offset -4 and each local variable after the first gets an even lower offset according to the size of the preceding local. 10
11 If the return type of a function is large, then the special variable ret has been introduced and it should be assigned an offset of 8, which bumps the first parameter up to offset 12. When we emit the x86 code, we ll need to access the assigned stack location when we come upon a Name AST node. There are several ways one could accomplish this. One way is to attached a dictionary to every function that maps variable names to their assigned location. When you emit the assembly code, pass the dictionary as a parameter to the emit function. 3 Lower Complex Assignments If an assignment statement is between large objects (greater than 32 bits, but not including floating point numbers) then you have to expand the assignment into a sequence of assignments. Suppose that x and y are 12 bytes. Then an assignment of x to y translates to three assignments statements. y = x; Offset(y, 0) = Offset(x, 0) Offset(y, 4) = Offset(x, 4) Offset(y, 8) = Offset(x, 8) If there is a Deref on the right or left-hand side of the assignment, some special handling is needed. The Offset nodes need to be inserted inside the Deref nodes (not on the outside). Deref(y) = x; Deref(Offset(y, 0)) = Offset(x, 0) Deref(Offset(y, 4)) = Offset(x, 4) Deref(Offset(y, 8)) = Offset(x, 8) 4 Emit x86 Assembly Code To emit x86 assembly from the AST, we write a recursive function that traverses the AST and produces a string containing the x86 instructions. Several cases are discussed below. Assignment x = e; Recursively apply the emit function to get x and e. Then emit two movl instructions as shown below. 11
12 x = e; movl e, %eax movl %eax, x For floating point numbers, use the movsd instructions and the xmm0 register instead. x = e; movsd e, %xmm0 movsd %xmm0, x However, the case where e is a floating point constant requires some special treatment. You need to represent e as two 32-bit integers. The easiest way to do this (in C) is to cast your double to an array of two integers. Call the two integers i 0 and i 1. Then you can use two movl instructions to write the two integers into the 8-bytes of memory at x. x = e; movl $i 0, 0(x ) movl $i 1, 4(x ) There s also some special cases for assignments concerning pointers. If there s a dereference on the left-hand side, then the address must be moved into a register before it can be used as the target of a move. We can then move e into the location pointed to by the register. The parenthesis around %eax in the second movl is the assembly language way to say dereference. Deref(x) = e movl x, %eax movl e, (%eax) If there s an Offset node inside the Deref node, then use the offset amount to adjust the dereference. Deref(Offset(x, n)) = e movl x, %eax movl e, n(%eax) If there s a dereference on the right-hand side, then we move the value of the right-hand side (which is an address) into a register, then move the value pointed to by the register into the register, and finally move the result to x. x = Deref(e) 12
13 movl e, %eax movl (%eax), %eax movl %eax, x The case where there s a dereference on both sides of the assignment is left to the reader to figure out. If the assignment has an Address node on the right-hand side, use the leal instruction to put the address of the argument in a register and then move the address to its destination. x = Address(e) leal e, %eax movl %eax, x Add x += e; Recursively apply the emit function to get x and e. For integer addition, emit a movl instruction to load e into a register then emit an addl instruction. x += e movl e, %eax addl %eax, x For floating point addition, we recommend using the SSE2 instructions. The SSE2 instructions use a special set of 8 registers for floating point, called the XMM registers. For now we ll only use one of these registers: xmm0. The instruction sequence for floating point is a bit more complicated than for integers because the SSE2 arithmetic instruction require the destination to be a register. Thus a second move is necessary to move the result back to the appropriate memory location. So in the following, we first move x to the xmm0 register, using the movsd instruction. The s stands for scalar (as opposed to vector, i.e. we re only dealing with a single floating point number) and the d stands for double precision. We then add e to the contents of xmm0 using the addsd instruction, and finally move the result back to x. x += e movsd x, %xmm0 addsd e, %xmm0 movsd %xmm0, x 13
14 Conditional Goto if (x == 0) goto label; Recursively apply the emit function to get x. Then emit a cmp instruction followed by a jne instruction. if (x == 0) goto label; cmpl $0, x je label Variable x Look up the offset n that you ve assigned to x and then emit n(%ebp) Constant c If the constant is an integer (or Boolean represented as 0 or 1) then emit $c Offset (x, m) Look up the offset n that you ve assigned to x and let n = n + m. Emit n (%ebp) Exercise 4.1. Add the three passes described above so that your compiler outputs x86 assembly code. 14
Procedure Calls. Young W. Lim Sat. Young W. Lim Procedure Calls Sat 1 / 27
Procedure Calls Young W. Lim 2016-11-05 Sat Young W. Lim Procedure Calls 2016-11-05 Sat 1 / 27 Outline 1 Introduction References Stack Background Transferring Control Register Usage Conventions Procedure
More informationEECE.3170: Microprocessor Systems Design I Summer 2017 Homework 4 Solution
1. (40 points) Write the following subroutine in x86 assembly: Recall that: int f(int v1, int v2, int v3) { int x = v1 + v2; urn (x + v3) * (x v3); Subroutine arguments are passed on the stack, and can
More informationAssembly Language: Function Calls
Assembly Language: Function Calls 1 Goals of this Lecture Help you learn: Function call problems: Calling and returning Passing parameters Storing local variables Handling registers without interference
More informationAssembly Language: Function Calls" Goals of this Lecture"
Assembly Language: Function Calls" 1 Goals of this Lecture" Help you learn:" Function call problems:" Calling and returning" Passing parameters" Storing local variables" Handling registers without interference"
More informationQuestion 4.2 2: (Solution, p 5) Suppose that the HYMN CPU begins with the following in memory. addr data (translation) LOAD 11110
Questions 1 Question 4.1 1: (Solution, p 5) Define the fetch-execute cycle as it relates to a computer processing a program. Your definition should describe the primary purpose of each phase. Question
More informationAssembly Language: Function Calls" Goals of this Lecture"
Assembly Language: Function Calls" 1 Goals of this Lecture" Help you learn:" Function call problems:" Calling and urning" Passing parameters" Storing local variables" Handling registers without interference"
More informationProcedure Calls. Young W. Lim Mon. Young W. Lim Procedure Calls Mon 1 / 29
Procedure Calls Young W. Lim 2017-08-21 Mon Young W. Lim Procedure Calls 2017-08-21 Mon 1 / 29 Outline 1 Introduction Based on Stack Background Transferring Control Register Usage Conventions Procedure
More informationAssembly Language: Function Calls. Goals of this Lecture. Function Call Problems
Assembly Language: Function Calls 1 Goals of this Lecture Help you learn: Function call problems: Calling and urning Passing parameters Storing local variables Handling registers without interference Returning
More informationCS61 Section Solutions 3
CS61 Section Solutions 3 (Week of 10/1-10/5) 1. Assembly Operand Specifiers 2. Condition Codes 3. Jumps 4. Control Flow Loops 5. Procedure Calls 1. Assembly Operand Specifiers Q1 Operand Value %eax 0x104
More informationFunction Calls COS 217. Reading: Chapter 4 of Programming From the Ground Up (available online from the course Web site)
Function Calls COS 217 Reading: Chapter 4 of Programming From the Ground Up (available online from the course Web site) 1 Goals of Today s Lecture Finishing introduction to assembly language o EFLAGS register
More informationAS08-C++ and Assembly Calling and Returning. CS220 Logic Design AS08-C++ and Assembly. AS08-C++ and Assembly Calling Conventions
CS220 Logic Design Outline Calling Conventions Multi-module Programs 1 Calling and Returning We have already seen how the call instruction is used to execute a subprogram. call pushes the address of the
More informationadministrivia today start assembly probably won t finish all these slides Assignment 4 due tomorrow any questions?
administrivia today start assembly probably won t finish all these slides Assignment 4 due tomorrow any questions? exam on Wednesday today s material not on the exam 1 Assembly Assembly is programming
More informationx86 assembly CS449 Fall 2017
x86 assembly CS449 Fall 2017 x86 is a CISC CISC (Complex Instruction Set Computer) e.g. x86 Hundreds of (complex) instructions Only a handful of registers RISC (Reduced Instruction Set Computer) e.g. MIPS
More informationCIT Week13 Lecture
CIT 3136 - Week13 Lecture Runtime Environments During execution, allocation must be maintained by the generated code that is compatible with the scope and lifetime rules of the language. Typically there
More informationLecture #16: Introduction to Runtime Organization. Last modified: Fri Mar 19 00:17: CS164: Lecture #16 1
Lecture #16: Introduction to Runtime Organization Last modified: Fri Mar 19 00:17:19 2010 CS164: Lecture #16 1 Status Lexical analysis Produces tokens Detects & eliminates illegal tokens Parsing Produces
More informationIntroduction to Compilers Professor Jeremy Siek
Professor Jeremy Siek This exam has 12 questions, for a total of 100 points. 1. 10 points Draw a parse tree and an abstract syntax tree for the following program given the grammar below. In the case of
More informationCompiler Construction D7011E
Compiler Construction D7011E Lecture 8: Introduction to code generation Viktor Leijon Slides largely by Johan Nordlander with material generously provided by Mark P. Jones. 1 What is a Compiler? Compilers
More informationCSC 2400: Computing Systems. X86 Assembly: Function Calls"
CSC 24: Computing Systems X86 Assembly: Function Calls" 1 Lecture Goals! Challenges of supporting functions" Providing information for the called function" Function arguments and local variables" Allowing
More informationCS 31: Intro to Systems Functions and the Stack. Martin Gagne Swarthmore College February 23, 2016
CS 31: Intro to Systems Functions and the Stack Martin Gagne Swarthmore College February 23, 2016 Reminders Late policy: you do not have to send me an email to inform me of a late submission before the
More informationDigital Forensics Lecture 3 - Reverse Engineering
Digital Forensics Lecture 3 - Reverse Engineering Low-Level Software Akbar S. Namin Texas Tech University Spring 2017 Reverse Engineering High-Level Software Low-level aspects of software are often the
More informationASSEMBLY III: PROCEDURES. Jo, Heeseung
ASSEMBLY III: PROCEDURES Jo, Heeseung IA-32 STACK (1) Characteristics Region of memory managed with stack discipline Grows toward lower addresses Register indicates lowest stack address - address of top
More informationIntegers and variables
CHAPTER 1 Integers and variables The main concepts in this chapter are abstract syntax trees: Inside the compiler we represent programs with a data-structure called an abstract syntax tree (AST). recursive
More informationAssembly III: Procedures. Jo, Heeseung
Assembly III: Procedures Jo, Heeseung IA-32 Stack (1) Characteristics Region of memory managed with stack discipline Grows toward lower addresses Register indicates lowest stack address - address of top
More informationIntegers and variables
CHAPTER 1 Integers and variables The main concepts in this chapter are abstract syntax trees: Inside the compiler, we represent programs with a data-structure called an abstract syntax tree, which is abbreviated
More informationCMSC 313 Lecture 12. Project 3 Questions. How C functions pass parameters. UMBC, CMSC313, Richard Chang
Project 3 Questions CMSC 313 Lecture 12 How C functions pass parameters UMBC, CMSC313, Richard Chang Last Time Stack Instructions: PUSH, POP PUSH adds an item to the top of the stack POP
More informationWhat is a Compiler? Compiler Construction SMD163. Why Translation is Needed: Know your Target: Lecture 8: Introduction to code generation
Compiler Construction SMD163 Lecture 8: Introduction to code generation Viktor Leijon & Peter Jonsson with slides by Johan Nordlander Contains material generously provided by Mark P. Jones What is a Compiler?
More informationCSE351 Autumn 2012 Midterm Exam (5 Nov 2012)
CSE351 Autumn 2012 Midterm Exam (5 Nov 2012) Please read through the entire examination first! We designed this exam so that it can be completed in 50 minutes and, hopefully, this estimate will prove to
More informationAssembly III: Procedures. Jin-Soo Kim Computer Systems Laboratory Sungkyunkwan University
Assembly III: Procedures Jin-Soo Kim (jinsookim@skku.edu) Computer Systems Laboratory Sungkyunkwan University http://csl.skku.edu IA-32 (1) Characteristics Region of memory managed with stack discipline
More informationSystem Programming and Computer Architecture (Fall 2009)
System Programming and Computer Architecture (Fall 2009) Recitation 2 October 8 th, 2009 Zaheer Chothia Email: zchothia@student.ethz.ch Web: http://n.ethz.ch/~zchothia/ Topics for Today Classroom Exercise
More informationCOMP 210 Example Question Exam 2 (Solutions at the bottom)
_ Problem 1. COMP 210 Example Question Exam 2 (Solutions at the bottom) This question will test your ability to reconstruct C code from the assembled output. On the opposing page, there is asm code for
More informationCode Generation. Lecture 30
Code Generation Lecture 30 (based on slides by R. Bodik) 11/14/06 Prof. Hilfinger CS164 Lecture 30 1 Lecture Outline Stack machines The MIPS assembly language The x86 assembly language A simple source
More information4) C = 96 * B 5) 1 and 3 only 6) 2 and 4 only
Instructions: The following questions use the AT&T (GNU) syntax for x86-32 assembly code, as in the course notes. Submit your answers to these questions to the Curator as OQ05 by the posted due date and
More informationMachine-level Programming (3)
Machine-level Programming (3) Procedures A: call A call A return Two issues How to return to the correct position? How to pass arguments and return values between callee to caller? 2 Procedure Control
More informationMachine Programming 3: Procedures
Machine Programming 3: Procedures CS61, Lecture 5 Prof. Stephen Chong September 15, 2011 Announcements Assignment 2 (Binary bomb) due next week If you haven t yet please create a VM to make sure the infrastructure
More informationSecond Part of the Course
CSC 2400: Computer Systems Towards the Hardware 1 Second Part of the Course Toward the hardware High-level language (C) assembly language machine language (IA-32) 2 High-Level Language g Make programming
More informationCSC 2400: Computing Systems. X86 Assembly: Function Calls
CSC 24: Computing Systems X86 Assembly: Function Calls 1 Lecture Goals Challenges of supporting functions Providing information for the called function Function arguments and local variables Allowing the
More informationCS 33: Week 3 Discussion. x86 Assembly (v1.0) Section 1G
CS 33: Week 3 Discussion x86 Assembly (v1.0) Section 1G Announcements - HW2 due Sunday - MT1 this Thursday! - Lab2 out Info Name: Eric Kim (Section 1G, 2-4 PM, BH 5419) Office Hours (Boelter 2432) - Wed
More informationCPSC W Term 2 Problem Set #3 - Solution
1. (a) int gcd(int a, int b) { if (a == b) urn a; else if (a > b) urn gcd(a - b, b); else urn gcd(a, b - a); CPSC 313 06W Term 2 Problem Set #3 - Solution.file "gcdrec.c".globl gcd.type gcd, @function
More informationLab 10: Introduction to x86 Assembly
CS342 Computer Security Handout # 8 Prof. Lyn Turbak Wednesday, Nov. 07, 2012 Wellesley College Revised Nov. 09, 2012 Lab 10: Introduction to x86 Assembly Revisions: Nov. 9 The sos O3.s file on p. 10 was
More informationThe course that gives CMU its Zip! Machine-Level Programming III: Procedures Sept. 17, 2002
15-213 The course that gives CMU its Zip! Machine-Level Programming III: Procedures Sept. 17, 2002 Topics IA32 stack discipline Register saving conventions Creating pointers to local variables class07.ppt
More informationCPEG421/621 Tutorial
CPEG421/621 Tutorial Compiler data representation system call interface calling convention Assembler object file format object code model Linker program initialization exception handling relocation model
More informationMachine Program: Procedure. Zhaoguo Wang
Machine Program: Procedure Zhaoguo Wang Requirements of procedure calls? P() { y = Q(x); y++; 1. Passing control int Q(int i) { int t, z; return z; Requirements of procedure calls? P() { y = Q(x); y++;
More informationCS241 Computer Organization Spring Loops & Arrays
CS241 Computer Organization Spring 2015 Loops & Arrays 2-26 2015 Outline! Loops C loops: while, for, do-while Translation to jump to middle! Arrays Read: CS:APP2 Chapter 3, sections 3.6 3.7 IA32 Overview
More informationCS213. Machine-Level Programming III: Procedures
CS213 Machine-Level Programming III: Procedures Topics IA32 stack discipline Register saving conventions Creating pointers to local variables IA32 Region of memory managed with stack discipline Grows toward
More informationCS241 Computer Organization Spring 2015 IA
CS241 Computer Organization Spring 2015 IA-32 2-10 2015 Outline! Review HW#3 and Quiz#1! More on Assembly (IA32) move instruction (mov) memory address computation arithmetic & logic instructions (add,
More informationWinter Compiler Construction T11 Activation records + Introduction to x86 assembly. Today. Tips for PA4. Today:
Winter 2006-2007 Compiler Construction T11 Activation records + Introduction to x86 assembly Mooly Sagiv and Roman Manevich School of Computer Science Tel-Aviv University Today ic IC Language Lexical Analysis
More informationIntel assembly language using gcc
QOTD Intel assembly language using gcc Assembly language programming is difficult. Make no mistake about that. It is not for wimps and weaklings. - Tanenbaum s 6th, page 519 These notes are a supplement
More informationStacks and Frames Demystified. CSCI 3753 Operating Systems Spring 2005 Prof. Rick Han
s and Frames Demystified CSCI 3753 Operating Systems Spring 2005 Prof. Rick Han Announcements Homework Set #2 due Friday at 11 am - extension Program Assignment #1 due Tuesday Feb. 15 at 11 am - note extension
More informationLecture Outline. Code Generation. Lecture 30. Example of a Stack Machine Program. Stack Machines
Lecture Outline Code Generation Lecture 30 (based on slides by R. Bodik) Stack machines The MIPS assembly language The x86 assembly language A simple source language Stack-machine implementation of the
More informationAssembly Language: IA-32 Instructions
Assembly Language: IA-32 Instructions 1 Goals of this Lecture Help you learn how to: Manipulate data of various sizes Leverage more sophisticated addressing modes Use condition codes and jumps to change
More informationCPS104 Recitation: Assembly Programming
CPS104 Recitation: Assembly Programming Alexandru Duțu 1 Facts OS kernel and embedded software engineers use assembly for some parts of their code some OSes had their entire GUIs written in assembly in
More informationLow-Level Essentials for Understanding Security Problems Aurélien Francillon
Low-Level Essentials for Understanding Security Problems Aurélien Francillon francill@eurecom.fr Computer Architecture The modern computer architecture is based on Von Neumann Two main parts: CPU (Central
More informationSungkyunkwan University
Switch statements IA 32 Procedures Stack Structure Calling Conventions Illustrations of Recursion & Pointers long switch_eg (long x, long y, long z) { long w = 1; switch(x) { case 1: w = y*z; break; case
More informationCS24: INTRODUCTION TO COMPUTING SYSTEMS. Spring 2016 Lecture 12
CS24: INTRODUCTION TO COMPUTING SYSTEMS Spring 2016 Lecture 12 CS24 MIDTERM Midterm format: 6 hour overall time limit, multiple sittings (If you are focused on midterm, clock should be running.) Open book
More informationInstructor: Alvin R. Lebeck
X86 Assembly Programming with GNU assembler Lecture 7 Instructor: Alvin R. Lebeck Some Slides based on those from Randy Bryant and Dave O Hallaron Admin Reading: Chapter 3 Note about pointers: You must
More informationInstruction Set Architecture
CS:APP Chapter 4 Computer Architecture Instruction Set Architecture Randal E. Bryant Carnegie Mellon University http://csapp.cs.cmu.edu CS:APP Instruction Set Architecture Assembly Language View! Processor
More informationInstruction Set Architecture
CS:APP Chapter 4 Computer Architecture Instruction Set Architecture Randal E. Bryant Carnegie Mellon University http://csapp.cs.cmu.edu CS:APP Instruction Set Architecture Assembly Language View Processor
More informationImplementing Threads. Operating Systems In Depth II 1 Copyright 2018 Thomas W. Doeppner. All rights reserved.
Implementing Threads Operating Systems In Depth II 1 Copyright 2018 Thomas W Doeppner All rights reserved The Unix Address Space stack dynamic bss data text Operating Systems In Depth II 2 Copyright 2018
More informationMachine-Level Programming II: Control and Arithmetic
Machine-Level Programming II: Control and Arithmetic CSCI 2400: Computer Architecture Instructor: David Ferry Slides adapted from Bryant & O Hallaron s slides 1 Today Complete addressing mode, address
More informationCMSC 313 Lecture 12 [draft] How C functions pass parameters
CMSC 313 Lecture 12 [draft] How C functions pass parameters UMBC, CMSC313, Richard Chang Last Time Stack Instructions: PUSH, POP PUSH adds an item to the top of the stack POP removes an
More informationCS 31: Intro to Systems ISAs and Assembly. Kevin Webb Swarthmore College February 9, 2016
CS 31: Intro to Systems ISAs and Assembly Kevin Webb Swarthmore College February 9, 2016 Reading Quiz Overview How to directly interact with hardware Instruction set architecture (ISA) Interface between
More informationCS 31: Intro to Systems ISAs and Assembly. Kevin Webb Swarthmore College September 25, 2018
CS 31: Intro to Systems ISAs and Assembly Kevin Webb Swarthmore College September 25, 2018 Overview How to directly interact with hardware Instruction set architecture (ISA) Interface between programmer
More informationInstruction Set Architecture
CS:APP Chapter 4 Computer Architecture Instruction Set Architecture Randal E. Bryant adapted by Jason Fritts http://csapp.cs.cmu.edu CS:APP2e Hardware Architecture - using Y86 ISA For learning aspects
More informationSummary: Direct Code Generation
Summary: Direct Code Generation 1 Direct Code Generation Code generation involves the generation of the target representation (object code) from the annotated parse tree (or Abstract Syntactic Tree, AST)
More informationProcess Layout, Function Calls, and the Heap
Process Layout, Function Calls, and the Heap CS 6 Spring 20 Prof. Vern Paxson TAs: Devdatta Akhawe, Mobin Javed, Matthias Vallentin January 9, 20 / 5 2 / 5 Outline Process Layout Function Calls The Heap
More informationX86 Assembly -Procedure II:1
X86 Assembly -Procedure II:1 IA32 Object Code Setup Label.L61 becomes address 0x8048630 Label.L62 becomes address 0x80488dc Assembly Code switch_eg:... ja.l61 # if > goto default jmp *.L62(,%edx,4) # goto
More informationAssembly Programmer s View Lecture 4A Machine-Level Programming I: Introduction
Assembly Programmer s View Lecture 4A Machine-Level Programming I: Introduction E I P CPU isters Condition Codes Addresses Data Instructions Memory Object Code Program Data OS Data Topics Assembly Programmer
More informationUniversity of Washington
Roadmap C: car *c = malloc(sizeof(car)); c->miles = 100; c->gals = 17; float mpg = get_mpg(c); free(c); Assembly language: Machine code: Computer system: get_mpg: pushq %rbp movq %rsp, %rbp... popq %rbp
More informationInstruction Set Architecture
CISC 360 Instruction Set Architecture Michela Taufer October 9, 2008 Powerpoint Lecture Notes for Computer Systems: A Programmer's Perspective, R. Bryant and D. O'Hallaron, Prentice Hall, 2003 Chapter
More informationCISC 360 Instruction Set Architecture
CISC 360 Instruction Set Architecture Michela Taufer October 9, 2008 Powerpoint Lecture Notes for Computer Systems: A Programmer's Perspective, R. Bryant and D. O'Hallaron, Prentice Hall, 2003 Chapter
More informationX86 Review Process Layout, ISA, etc. CS642: Computer Security. Drew Davidson
X86 Review Process Layout, ISA, etc. CS642: Computer Security Drew Davidson davidson@cs.wisc.edu From Last Time ACL-based permissions (UNIX style) Read, Write, execute can be restricted on users and groups
More informationYou may work with a partner on this quiz; both of you must submit your answers.
Instructions: Choose the best answer for each of the following questions. It is possible that several answers are partially correct, but one answer is best. It is also possible that several answers are
More informationAn Elegant Weapon for a More Civilized Age
An Elegant Weapon for a More Civilized Age Solving an Easy Problem What are the input types? What is the output type? Give example input/output pairs Which input represents the domain of the recursion,
More informationAssignment 7: functions and closure conversion (part 1)
Assignment 7: functions and closure conversion (part 1) ECEN 4553 & 5013, CSCI 4555 & 5525 Prof. Jeremy G. Siek November 12, 2008 The main ideas for this week are: first-class functions lexical scoping
More informationCSE2421 FINAL EXAM SPRING Name KEY. Instructions: Signature
CSE2421 FINAL EXAM SPRING 2013 Name KEY Instructions: This is a closed-book, closed-notes, closed-neighbor exam. Only a writing utensil is needed for this exam. No calculators allowed. If you need to go
More informationThe Hardware/Software Interface CSE351 Spring 2013
The Hardware/Software Interface CSE351 Spring 2013 x86 Programming II 2 Today s Topics: control flow Condition codes Conditional and unconditional branches Loops 3 Conditionals and Control Flow A conditional
More informationMachine-Level Programming III: Procedures
Machine-Level Programming III: Procedures IA32 Region of memory managed with stack discipline Grows toward lower addresses Register indicates lowest stack address address of top element Bottom Increasing
More informationRegister Allocation, iii. Bringing in functions & using spilling & coalescing
Register Allocation, iii Bringing in functions & using spilling & coalescing 1 Function Calls ;; f(x) = let y = g(x) ;; in h(y+x) + y*5 (:f (x
More informationY86 Processor State. Instruction Example. Encoding Registers. Lecture 7A. Computer Architecture I Instruction Set Architecture Assembly Language View
Computer Architecture I Instruction Set Architecture Assembly Language View Processor state Registers, memory, Instructions addl, movl, andl, How instructions are encoded as bytes Layer of Abstraction
More informationx86 assembly CS449 Spring 2016
x86 assembly CS449 Spring 2016 CISC vs. RISC CISC [Complex instruction set Computing] - larger, more feature-rich instruction set (more operations, addressing modes, etc.). slower clock speeds. fewer general
More informationCSE 351: Week 4. Tom Bergan, TA
CSE 35 Week 4 Tom Bergan, TA Does this code look okay? int binarysearch(int a[], int length, int key) { int low = 0; int high = length - ; while (low
More informationProcess Layout and Function Calls
Process Layout and Function Calls CS 6 Spring 07 / 8 Process Layout in Memory Stack grows towards decreasing addresses. is initialized at run-time. Heap grow towards increasing addresses. is initialized
More informationIntroduction to Computer Systems. Exam 1. February 22, Model Solution fp
15-213 Introduction to Computer Systems Exam 1 February 22, 2005 Name: Andrew User ID: Recitation Section: Model Solution fp This is an open-book exam. Notes are permitted, but not computers. Write your
More informationX86 Stack Calling Function POV
X86 Stack Calling Function POV Computer Systems Section 3.7 Stack Frame Reg Value ebp xffff FFF0 esp xffff FFE0 eax x0000 000E Memory Address Value xffff FFF8 xffff FFF4 x0000 0004 xffff FFF4 x0000 0003
More informationCS412/CS413. Introduction to Compilers Tim Teitelbaum. Lecture 21: Generating Pentium Code 10 March 08
CS412/CS413 Introduction to Compilers Tim Teitelbaum Lecture 21: Generating Pentium Code 10 March 08 CS 412/413 Spring 2008 Introduction to Compilers 1 Simple Code Generation Three-address code makes it
More informationCode Generation. The Main Idea of Today s Lecture. We can emit stack-machine-style code for expressions via recursion. Lecture Outline.
The Main Idea of Today s Lecture Code Generation We can emit stack-machine-style code for expressions via recursion (We will use MIPS assembly as our target language) 2 Lecture Outline What are stack machines?
More informationWe can emit stack-machine-style code for expressions via recursion
Code Generation The Main Idea of Today s Lecture We can emit stack-machine-style code for expressions via recursion (We will use MIPS assembly as our target language) 2 Lecture Outline What are stack machines?
More informationWhat the CPU Sees Basic Flow Control Conditional Flow Control Structured Flow Control Functions and Scope. C Flow Control.
C Flow Control David Chisnall February 1, 2011 Outline What the CPU Sees Basic Flow Control Conditional Flow Control Structured Flow Control Functions and Scope Disclaimer! These slides contain a lot of
More informationCSC 8400: Computer Systems. Using the Stack for Function Calls
CSC 84: Computer Systems Using the Stack for Function Calls Lecture Goals Challenges of supporting functions! Providing information for the called function Function arguments and local variables! Allowing
More informationCode Generation. Lecture 12
Code Generation Lecture 12 1 Lecture Outline Topic 1: Basic Code Generation The MIPS assembly language A simple source language Stack-machine implementation of the simple language Topic 2: Code Generation
More informationIA32 Stack. Stack BoDom. Region of memory managed with stack discipline Grows toward lower addresses. Register %esp contains lowest stack address
IA32 Procedures 1 IA32 Stack Region of memory managed with stack discipline Grows toward lower addresses Stack BoDom Increasing Addresses Register contains lowest stack address address of top element Stack
More informationCS24: INTRODUCTION TO COMPUTING SYSTEMS. Spring 2018 Lecture 6
CS24: INTRODUCTION TO COMPUTING SYSTEMS Spring 2018 Lecture 6 LAST TIME: SYSTEM V AMD64 ABI How to implement basic C abstractions in x86-64? C subroutines with arguments, and local/global variables Began
More informationLecture 15 Intel Manual, Vol. 1, Chapter 3. Fri, Mar 6, Hampden-Sydney College. The x86 Architecture. Robb T. Koether. Overview of the x86
Lecture 15 Intel Manual, Vol. 1, Chapter 3 Hampden-Sydney College Fri, Mar 6, 2009 Outline 1 2 Overview See the reference IA-32 Intel Software Developer s Manual Volume 1: Basic, Chapter 3. Instructions
More informationAssignment 7: functions and closure conversion
Assignment 7: functions and closure conversion ECEN 4553 & 5013, CSCI 4555 & 5525 Prof. Jeremy G. Siek October 20, 2007 The main ideas for this week are: first-class functions lexical scoping of variables
More informationCSE351 Autumn 2014 Midterm Exam (29 October 2014)
CSE351 Autumn 2014 Midterm Exam (29 October 2014) (Version A) Please read through the entire examination first! We designed this exam so that it can be completed in 50 minutes and, hopefully, this estimate
More informationCS 31: Intro to Systems ISAs and Assembly. Martin Gagné Swarthmore College February 7, 2017
CS 31: Intro to Systems ISAs and Assembly Martin Gagné Swarthmore College February 7, 2017 ANNOUNCEMENT All labs will meet in SCI 252 (the robot lab) tomorrow. Overview How to directly interact with hardware
More informationObject-oriented features
Chapter 1 Object-oriented features The compiler s job for a procedural language like C is relatively straightforward, because C and most other compiled procedural languages have been designed to approximate
More informationThe x86 Architecture
The x86 Architecture Lecture 24 Intel Manual, Vol. 1, Chapter 3 Robb T. Koether Hampden-Sydney College Fri, Mar 20, 2015 Robb T. Koether (Hampden-Sydney College) The x86 Architecture Fri, Mar 20, 2015
More informationUW CSE 351, Winter 2013 Midterm Exam
Full Name: Student ID: UW CSE 351, Winter 2013 Midterm Exam February 15, 2013 Instructions: Make sure that your exam is not missing any of the 9 pages, then write your full name and UW student ID on the
More informationCSE351 Autumn 2014 Midterm Exam (29 October 2014)
CSE351 Autumn 2014 Midterm Exam (29 October 2014) Please read through the entire examination first! We designed this exam so that it can be completed in 50 minutes and, hopefully, this estimate will prove
More information