Calling Procedures C calling conventions. Outline Procedures Procedure call mechanism Passing parameters Local variable storage C-Style procedures Recursion.

Slides:



Advertisements
Similar presentations
Assembly Language for x86 Processors 6th Edition Chapter 5: Procedures (c) Pearson Education, All rights reserved. You may modify and copy this slide.
Advertisements

There are two types of addressing schemes:
Procedures in more detail. CMPE12cGabriel Hugh Elkaim 2 Why use procedures? –Code reuse –More readable code –Less code Microprocessors (and assembly languages)
Computer Architecture CSCE 350
The University of Adelaide, School of Computer Science
C Programming and Assembly Language Janakiraman V – NITK Surathkal 2 nd August 2014.
Procedures and Stacks. Outline Stack organization PUSH and POP instructions Defining and Calling procedures.
Subroutines: Passing Arguments Using the Stack. Passing Arguments via the Stack Arguments to a subroutine are pushed onto the stack. The subroutine accesses.
Assembly Language for Intel-Based Computers Chapter 8: Advanced Procedures Kip R. Irvine.
Procedures in more detail. CMPE12cCyrus Bazeghi 2 Procedures Why use procedures? Reuse of code More readable Less code Microprocessors (and assembly languages)
1 Lecture 5: Procedures Assembly Language for Intel-Based Computers, 4th edition Kip R. Irvine.
1 Function Calls Professor Jennifer Rexford COS 217 Reading: Chapter 4 of “Programming From the Ground Up” (available online from the course Web site)
Accessing parameters from the stack and calling functions.
Honors Compilers Addressing of Local Variables Mar 19 th, 2002.
Chapter 12: High-Level Language Interface. Chapter Overview Introduction Inline Assembly Code C calls assembly procedures Assembly calls C procedures.
1 Homework Reading –PAL, pp , Machine Projects –Finish mp2warmup Questions? –Start mp2 as soon as possible Labs –Continue labs with your.
Semantics of Calls and Returns
Assembly תרגול 8 פונקציות והתקפת buffer.. Procedures (Functions) A procedure call involves passing both data and control from one part of the code to.
INVOKE Directive The INVOKE directive is a powerful replacement for Intel’s CALL instruction that lets you pass multiple arguments Syntax: INVOKE procedureName.
ICS312 Set 11 Introduction to Subroutines. All the combinations in which a subroutine can be written 1. The subroutine may be: a. Internal or b. External.
Universal Concepts of Programming Creating and Initializing local variables on the stack Variable Scope and Lifetime Stack Parameters Stack Frames Passing.
CS-2710 Dr. Mark L. Hornick 1 Defining and calling procedures (subroutines) in assembly And using the Stack.
Introduction to Subroutines. All the combinations in which a subroutine can be written 1. The subroutine may be: a. Internal or b. External 2. The type.
Today’s topics Parameter passing on the system stack Parameter passing on the system stack Register indirect and base-indexed addressing modes Register.
The x86 Architecture Lecture 15 Fri, Mar 4, 2005.
Procedures. Why use procedures? ? Microprocessors (and assembly languages) provide only minimal support for procedures Must build a standard form for.
Richard P. Paul, SPARC Architecture, Assembly Language Programming, and C Chapter 7 – Subroutines These are lecture notes to accompany the book SPARC Architecture,
Strings, Procedures and Macros
Lecture 7 A closer look at procedures Dr. Dimitrios S. Nikolopoulos CSL/UIUC.
Module R3 Process Scheduling. Module R3 involves the creation of a simple “Round Robin” dispatcher. The successful completion of this module will require.
Microprocessors The ia32 User Instruction Set Jan 31st, 2002.
ECE291 Lecture 6 Procedures and macros. ECE 291 Lecture 6Page 2 of 36 Lecture outline Procedures Procedure call mechanism Passing parameters Local variable.
ITCS 3181 Logic and Computer Systems 2015 B. Wilkinson Slides4-2.ppt Modification date: March 23, Procedures Essential ingredient of high level.
Subroutines: Passing Arguments Using the Stack. Passing Arguments via the Stack Arguments to a subroutine are pushed onto the stack. The subroutine accesses.
Functions/Methods in Assembly
Lecture 9 (The Stack and Procedures). 1 Lecture Outline Introduction The Stack The PUSH Instruction The POP Instruction Terminology of Procedures INDEC.
Compiler Construction Code Generation Activation Records
ARM-7 Assembly: Example Programs 1 CSE 2312 Computer Organization and Assembly Language Programming Vassilis Athitsos University of Texas at Arlington.
ECE291 Computer Engineering II Lecture 8 Josh Potts University of Illinois at Urbana- Champaign.
Function Calling. Mips Assembly Call and Return Steps for procedure calling –Save the return address –Jump to the procedure (function) –Execute the procedure.
ICS312 Set 12 Subroutines: Passing Arguments Using the Stack.
Preocedures A closer look at procedures. Outline Procedures Procedure call mechanism Passing parameters Local variable storage C-Style procedures Recursion.
LECTURE 19 Subroutines and Parameter Passing. ABSTRACTION Recall: Abstraction is the process by which we can hide larger or more complex code fragments.
Microprocessors CSE- 341 Dr. Jia Uddin Assistant Professor, CSE, BRAC University Dr. Jia Uddin, CSE, BRAC University.
Assembly Language Addressing Modes. Introduction CISC processors usually supports more addressing modes than RISC processors. –RISC processors use the.
7-Nov Fall 2001: copyright ©T. Pearce, D. Hutchinson, L. Marshall Oct lecture23-24-hll-interrupts 1 High Level Language vs. Assembly.
Chapter 14 Functions.
Storage Classes There are three places in memory where data may be placed: In Data section declared with .data in assembly language in C - Static) On the.
Instruction set Architecture
Format of Assembly language
143A: Principles of Operating Systems Lecture 4: Calling conventions
Microprocessor and Assembly Language
Introduction to Compilers Tim Teitelbaum
(The Stack and Procedures)
BIC 10503: COMPUTER ARCHITECTURE
Programming 8086 – Part IV Stacks, Macros
Stack Frames and Advanced Procedures
Procedures – Overview Lecture 19 Mon, Mar 28, 2005.
Assembly Language Programming II: C Compiler Calling Sequences
MIPS Instructions.
MIPS Procedure Calls CSE 378 – Section 3.
Practical Session 4.
(The Stack and Procedures)
by Richard P. Paul, 2nd edition, 2000.
Multi-modules programming
X86 Assembly Review.
Where is all the knowledge we lost with information? T. S. Eliot
(The Stack and Procedures)
Presentation transcript:

Calling Procedures C calling conventions

Outline Procedures Procedure call mechanism Passing parameters Local variable storage C-Style procedures Recursion

Procedures defined Procedures perform specific frequently used tasks They can be repeatedly called from different places in your program These are essentially the same thing as functions and subroutines in high-level languages Procedures may have inputs/outputs, both, either, neither Essentially just labeled blocks of assembly language instructions with a special return instruction

Procedures prime directive Procedures should never alter the contents of any register that the procedure isn’t explicitly expected to modify If for example, if a proc is expected to return a value in EAX, it is required for it to modify EAX All other registers should appear unchanged Push them at the beginning and pop them at the end

Call Call does two things –It pushes the address of the instruction immediately following the call statement onto the stack –It loads the instruction pointer with the value of the label marking the beginning of the procedure you’re calling (this is essentially an unconditional jump to the beginning of the procedure

Passing parameters Using registers –Registers are the ultimate global variables –Your procedure can simply access information placed in specific registers –Also a simple way for your procedure to send data back to the caller –The procedure and any code that calls it must agree on where it will find its inputs and where it will put its output –This agreement is termed a “calling convention” –Many calling conventions are possible…

Passing parameters Using global memory locations –Memory locations declared at the beginning of your program are global and can be accessed from any procedure Using a parameter block –You may pass a pointer to an array or other type of memory block instead of an individual data value When calling (or being called by) code compiled from another language, your assembly code must conform to that language’s calling conventions!

Passing parameters in “C” Using the stack –Caller pushes all arguments expected by the proc onto the stack (in reverse order, push last argument first) –Proc can access these arguments directly from the stack by setting up the stack frame. push ebp ; save previous value of ebp mov ebp, esp ; mark start of stack frame arg1 is at [ebp+8] assuming call has pushed IP onto stack

Example ;call proc to calculate area of right triangle. ;proc expects two word sized args to be on the stack push 3 push 4 call TriangleArea ;now we must remove the variables from the stack ;every push must be popped. add esp, 4 ; ax now contains 6 (the result returned by TriangleArea)

Example continued y equ ebp+8;define [ebp+8] = y x equ ebp+12;define [ebp+12] = x TriangleArea: push ebp; save caller’s stack frame mov ebp, esp; start our own stack frame push edx; save edx so we can use it mov eax, [y]; fetch y mul double [x]; multiple by x shr eax, 1; divide by two pop edx; restore edx movesp, ebp; collapse the stack pop ebp; restore caller’s stk frame ret; return to caller

What just happened… 1C C ESP 3 Saved EBP 4 Return IP pushd 3 pushd 4 call TriangleArea TriangleArea push ebp mov ebp, esp push edx mov eax, [ebp+8] mul double [ebp+12] shr eax, 1 pop edx movesp, ebp pop ebp ret add esp, 4 Saved EDXESP Stack frame EBP

Local variable storage You may allocate stack space for use as local variables within procedures Subtract from the stack pointer the number of bytes you need to allocate after setting up the stack frame At the end of your procedure, just add the same amount you subtracted to free the memory you allocated just before you pop bp In the procedure, use the stack frame to address local variable storage

Local variable storage MyProc ;setup stack frame push ebp mov ebp, esp ;allocate space for two words sub esp, 4;access words at [ebp-4] and [ebp-8] … add esp, 4;destroy local variables (not needed) mov esp, ebp; restore caller’s stack pointer pop ebp;restore original ebp ret

Things to remember Always make sure that your stack is consistent (a proc doesn’t leave information on the stack that wasn’t there before the procedure executed) Always remember to save registers you modify that don’t contain return values

C-style procedures Assembly procedures that can be called by C programs Must follow the same calling procedure that C compilers use when building C programs You can also call C functions from assembly programs using the same protocol

C style procedures Suppose a C program calls an assembly procedure as follows –Proc1(a, b, c) Assume each argument is word-sized Further, assume the C compiler generates code to push a, b, and c onto the stack The assembly language procedure must be assembled with the correct ret (near or far) and stack handling of its procedures matching the corresponding values in the high-level module

C style procedures C compilers push arguments in reverse order, from right to left. –C is pushed first, then B, then A –Lowest index from EBP corresponds to first argument EBP+20 EBP+16 EBP+12 EBP+8 EBP+4 EBP a c b Return IP Saved EBP Proc1(a, b, c)

C style procedures If the returned value needs four or fewer bytes, it is by default returned in registers –one or two bytes - returned in AX –three or four bytes – returned in EAX (in 32-bit mode) More than four bytes –the called procedure stores data at some address and returns the address in EAX

C style procedures Caller is responsible for clearing the arguments from the stack as soon as it regains control after the call –this done by the compiler which generates an add to the ESP register to pop the arguments without moving any data –a far procedure called from C should end with RETF instead of RET

Example Calling an ASM proc from a C program – the proc lets you display a string at a given row and column #include extern void placeStr(char * s, unsigned int row, unsigned int col); void main(void) { intn; for (n = 10; n < 20; ++n) placeStr (“This is the string”, n, 45); }

Example (note: this is in 16 bit mode) global placeStr section.text placeStr: ; setup stack frame and save state PUSHBP MOVBP, SP PUSHAX PUSHBX PUSHDX ; get current page - returns in BH MOVAH, 0fh INT10h ; read unsigned args 2 and 3 MOVDL, [BP+10] MOVDH, [BP+8] ;set cursor position MOV AH, 02h INT 10h ;point to string MOV BX, [BP+6] ;call outAsc to disp string call outAsc ;restore state POP DX POP BX POP AX MOV SP, BP POP BP RETF

Putting the two together The C module must be compiled The assembly language module assembled The pair must be linked together into an executable Extern in C is exactly the same as Extern in assembly programs

Recursion Recursion: procedure calls itself RecursiveProc: DECAX JZQuitRecursion CALLRecursiveProc QuitRecursion: RET Requires a termination condition in order to stop infinite recursion Many recursively implemented algorithms are more efficient than their iterative counterparts

Recursion example Factorial: ; Input AX = CX = Value ; Output AX = Value ! DEC CX ;Test for base case CMP CX,0 JE FactDone IMUL CX ; Recurs Call Factorial FactDone: RET Stack contents Assume: AX = CX = 4 Return IP Iteration 1 CX = 4; AX = 4 Return Iteration IP 2 CX = 3; AX = 12 Return Iteration IP 3 CX = 2; AX = 24 Return Iteration IP 4 CX = 1; AX = 24

Recursion Recursion must maintain separate copies of all pertinent information (parameter value, return address, local variables) for each active call, all on the stack Recursive routines can consume a considerable amount of stack space In general, you will not know the depth to which recursion will take you