Function Calls and Stack Allocation

Similar documents
Function Calls and Stack Allocation

Stack. Stack. Function Calls and Stack Allocation. Stack Popping Popping. Stack Pushing Pushing. Page 1

Systems I. Machine-Level Programming V: Procedures

(Extract from the slides by Terrance E. Boult

CS558 Programming Languages

CS558 Programming Languages Winter 2018 Lecture 4a. Andrew Tolmach Portland State University

Stacks and Function Calls

IA32 Stack. Lecture 5 Machine-Level Programming III: Procedures. IA32 Stack Popping. IA32 Stack Pushing. Topics. Pushing. Popping

IA32 Stack The course that gives CMU its Zip! Machine-Level Programming III: Procedures Sept. 17, IA32 Stack Popping. IA32 Stack Pushing

Short Notes of CS201

Giving credit where credit is due

CS201 - Introduction to Programming Glossary By

Assembly III: Procedures. Jin-Soo Kim Computer Systems Laboratory Sungkyunkwan University

Implementing Procedure Calls

MIPS Functions and the Runtime Stack

ASSEMBLY III: PROCEDURES. Jo, Heeseung

Assembly III: Procedures. Jo, Heeseung

Run-time Environments - 2

Implementing Subroutines. Outline [1]

Run Time Environment

Operating Systems CMPSCI 377, Lec 2 Intro to C/C++ Prashant Shenoy University of Massachusetts Amherst

CS213. Machine-Level Programming III: Procedures

Programming Studio #9 ECE 190

Topic 7: Activation Records

Programs in memory. The layout of memory is roughly:

Q1: /8 Q2: /30 Q3: /30 Q4: /32. Total: /100

Run-time Environment

Do-While Example. In C++ In assembly language. do { z--; while (a == b); z = b; loop: addi $s2, $s2, -1 beq $s0, $s1, loop or $s2, $s1, $zero

Data Transfer Instructions

Computer Programming

The course that gives CMU its Zip! Machine-Level Programming III: Procedures Sept. 17, 2002

Fundamentals of Programming

QUIZ. What are 3 differences between C and C++ const variables?

Course Administration

Scope: Global and Local. Concept of Scope of Variable

Informatica e Sistemi in Tempo Reale

CSE Lecture In Class Example Handout

Q1: /20 Q2: /30 Q3: /24 Q4: /26. Total: /100

A Simplistic Program Translation Scheme

University of Washington

X86 Assembly -Procedure II:1

Lectures 5-6: Introduction to C

CSC 2400: Computer Systems. Using the Stack for Function Calls

In Java we have the keyword null, which is the value of an uninitialized reference type

Memory Usage 0x7fffffff. stack. dynamic data. static data 0x Code Reserved 0x x A software convention

Chapter 6: User-Defined Functions. Objectives (cont d.) Objectives. Introduction. Predefined Functions 12/2/2016

Procedure Calls Main Procedure. MIPS Calling Convention. MIPS-specific info. Procedure Calls. MIPS-specific info who cares? Chapter 2.7 Appendix A.

Cpt S 122 Data Structures. Data Structures

Separate compilation. Topic 6: Runtime Environments p.1/21. CS 526 Topic 6: Runtime Environments The linkage convention

Code Generation. Lecture 12

Today's Topics. CISC 458 Winter J.R. Cordy

Page 1. IA32 Stack CISC 360. Machine-Level Programming III: Procedures Sept. 22, IA32 Stack Popping Stack Bottom. IA32 Stack Pushing

CPSC 213. Introduction to Computer Systems. Procedures and the Stack. Unit 1e Feb 11, 13, 15, and 25. Winter Session 2018, Term 2

System Software Assignment 1 Runtime Support for Procedures

MPATE-GE 2618: C Programming for Music Technology. Unit 4.1

Stacks and Frames Demystified. CSCI 3753 Operating Systems Spring 2005 Prof. Rick Han

Lecture 7: Procedures and Program Execution Preview

Lectures 5. Announcements: Today: Oops in Strings/pointers (example from last time) Functions in MIPS

CIT Week13 Lecture

Project Compiler. CS031 TA Help Session November 28, 2011

Generating Programs and Linking. Professor Rick Han Department of Computer Science University of Colorado at Boulder

Functions in MIPS. Functions in MIPS 1

CSE2421 Systems1 Introduction to Low-Level Programming and Computer Organization

Calling Conventions. Hakim Weatherspoon CS 3410, Spring 2012 Computer Science Cornell University. See P&H 2.8 and 2.12

Implementing Subprograms

CPS311 Lecture: Procedures Last revised 9/9/13. Objectives:

ECE232: Hardware Organization and Design

Mechanisms in Procedures. CS429: Computer Organization and Architecture. x86-64 Stack. x86-64 Stack Pushing

Understand Execution of a Program

o Code, executable, and process o Main memory vs. virtual memory

Machine-level Programming (3)

An Experience Like No Other. Stack Discipline Aug. 30, 2006

Programming in C. main. Level 2. Level 2 Level 2. Level 3 Level 3

Assembly Programming (III)

Stack Discipline Jan. 19, 2018

Arguments and Return Values. EE 109 Unit 16 Stack Frames. Assembly & HLL s. Arguments and Return Values

Procedure Call. Procedure Call CS 217. Involves following actions

Compilers and computer architecture: A realistic compiler to MIPS

Interview Questions of C++

QUIZ. Source:

CSE Lecture In Class Example Handout

Region of memory managed with stack discipline Grows toward lower addresses. Register %esp contains lowest stack address = address of top element

Code Generation. Lecture 19

Machine Programming 3: Procedures

The Procedure Abstraction Part I: Basics

Object Reference and Memory Allocation. Questions:

Scope, Functions, and Storage Management

MIPS R-format Instructions. Representing Instructions. Hexadecimal. R-format Example. MIPS I-format Example. MIPS I-format Instructions

Chapter 9 :: Subroutines and Control Abstraction

Midterm Review. PIC 10B Spring 2018

Assembly III: Procedures. Jin-Soo Kim Computer Systems Laboratory Sungkyunkwan University

COMP3221: Microprocessors and. and Embedded Systems. Overview. Variable Types and Memory Sections. Types of Variables in C

COMP 303 Computer Architecture Lecture 3. Comp 303 Computer Architecture

Sungkyunkwan University

ECE331: Hardware Organization and Design

CSC 1600 Memory Layout for Unix Processes"

6.096 Introduction to C++ January (IAP) 2009

the gamedesigninitiative at cornell university Lecture 7 C++ Overview

Stack Frames. September 2, Indiana University. Geoffrey Brown, Bryce Himebaugh 2015 September 2, / 15

CS201 Some Important Definitions

Transcription:

Function Calls and Allocation Topics Pushing and Popping Role of in (Automatic) Allocation Parameter Passing Region of memory managed with stack discipline Grows toward lower addresses pointer indicates lowest stack address Bottom Increasing Addresses Grows Down Top Page 1

Pushing Pushing Add something at the top of the stack Bottom Increasing Addresses Grows Down Top Popping Popping Throw away element at the top of the stack Bottom Increasing Addresses Grows Down Top Page 2

Procedure Control Flow Use stack to support procedure call and return Allocated in Frames state for single procedure instantiation Local variables Arguments Other (e.g., for return) all state goes away when procedure returns Example Code Structure ( ) (); ( ) (); (); Procedure recursive (calls itself) ( ) (); Page 3

Frames Contents Local variables Return information Temporary ace Management Space allocated when enter procedure Deallocated (freed) when return proc Top Operation ( ) (); Page 4

Operation ( ) (); (); Operation ( ) (); Page 5

Operation ( ) (); Operation ( ) (); Page 6

Operation ( ) (); Operation ( ) (); Page 7

Operation ( ) (); (); Operation ( ) Page 8

Operation ( ) (); (); Operation ( ) (); Page 9

Function Parameters Function arguments are passed by value. What is pass by value? The called function is given a copy of the arguments. What does this imply? The called function can t alter a variable in the caller function, but its private copy. An example Example 1: swap_1 void swap_1(int a, int b) int temp; temp = a; a = b; b = temp; Q: Let x=3, y=4, after swap_1(x,y); x =? y=? A1: x=4; y=3; A2: x=3; y=4; Page 10

Process Memory Image Automatic variables are allocated memory on the stack. grows downwards (automatic allocations) Dynamic Memory Allocator requests memory from the heap. Heap grows upwards run-time heap (via new) data program code 0 Dynamic (Heap) Memory Allocator Recap Operator new is still a high-level request such as I d like an instance of class String Try to think about it low level You ask for n bytes (the sizeof that type/class) You get a pointer (memory address) to the allocated object This allocation is on the heap You need to free all memory blocks you allocated A delete for each correonding new Page 11

Automatic Allocator Internals Automatic allocation of variables occurs on the stack We ll learn how the stack works next Passing Arguments by Value Upon function call, the argument values are copied (byte-by by-byte) byte) onto stack Push args on stack for the function you are about to call Caller () Local Variables Copy Args for Space for local variables is allocated on stack Local variables allocated automatically in new frame Disappear when frame pops off the stack Callee () Local Variables Copy Args for Page 12

Pass Args by Value () int y1,y2; (y1,y2); (int a, int b) int w1,w2; (); (); Frame fp y1 y2 Pass Args by Value (Copy) () int y1,y2; (y1,y2); y1 y2 a b w1 w2 (int a, int b) int w1,w2; (a); (b); Page 13

Pass Args by Value on Call (int a, int b) int w1,w2; (a); (b); (int i) (i); y1 y2 a b w1 w2 i Pass Args by Value on Call (int i) (i); y1 y2 a b w1 w2 i i Page 14

Pass Args by Value on Call (int i) (i); y1 y2 a b w1 w2 i i i Pop on Return (int i) (i); y1 y2 a b w1 w2 i i Page 15

Pop on Return (int i) (i); y1 y2 a b w1 w2 i Pop on Return (int a, int b) int w1,w2; (a); (b); y1 y2 a b w1 w2 Page 16

Pass Args by Value on Call (int a, int b) int w1,w2; (a); (b); (int i) (i); y1 y2 a b w1 w2 i Pop on Return (int a, int b) int w1,w2; (a); (b); y1 y2 a b w1 w2 Page 17

Pop on Return () int y1,y2; (y1,y2); y1 y2 Summary The Makes Function Calls Work Private storage for each instance of procedure call locals + arguments are allocated on stack Can be managed by stack discipline Procedures return in inverse order of calls That s how automatic allocation works Local vars allocated on new frame upon entering function call Vars (including arg copies) freed automatically upon return Do you see now why you cannot delete an automatically allocated object? Page 18

Summary (contd.) Do you see now why you cannot delete an automatically allocated object? (e.g. int i; int * pi = &i; delete pi is WRONG!) Because automatically allocated objects live temporarily on the stack. You cannot control lifetime. You can only free objects that you allocated with new (on the heap). The two allocators (dynamic & automatic) are different. Function Parameters Passing (contd) The only mechanism in C++ is to pass arguments by value (push/copy args on stack)!!! So how can we make swap work? A: The called function is passed a pointer (address) of a var. What does this imply? The called function can alter that variable var through its pointer This fakes a mechanism called pass args by reference present in other languages (e.g., Pascal). An example Page 19

Example 2: swap_2 void swap_2(int *a, int *b) int temp; temp = *a; *a = *b; *b = temp; Q: Let x=3, y=4, after swap_2(&x,&y); x =? y=? A1: x=3; y=4; A2: x=4; y=3; Parameters Passing by Reference 1. The stack mechanism works unchanged 2. The pointer (arg( arg) ) is still copied (byte by byte) on stack as usual! 3. So the pointer itself is still passed by value 4. However, the callee can directly access that memory address thus can change the var through its pointer 5. If arg is large object (e.g., struct student_data) should pass its address (to avoid large copies) Page 20

Compilation and Linking Topics Separation of function code into.cc and.h A preface to Encapsulation Preprocessor Compiling Object files Linking different files Encapsulation Introduction Class implementation Interface User Implementation details hidden from User Page 21

Encapsulation Introduction Class1 implementation (by Bahlul) Class2 implementation (by Salam) Function call Interface User Interface Implementation details hidden from User Programmers collaborate (use each other s code thru func calls) Encapsulation Class implementation (e.g., Set.cc) int sort() Interface (Set.h) User Implementation details (in Set.cc) hidden from User Interface (in Set.h) is public - given to User Page 22

How to Encapsulate (first step)? Interface = ec (how to use) put in a header file We ll see more of this with classes (e.g., private/public) Class implementation Function bodies (.cc file) Interface (header file) User Public function headers Public type definitions (e.g., class definition, struct definition, typedefs) +/- of Encapsulation? + User code remains same if class implem changes - User code might run slower without apparent reason Class implementation (in Set.cc) #include Set.h int sort(..) //changed from //quick to bubble sort Interface in Set.h User code (inventory.cc) #include <iostream> #include Set.h int main () sort( ); Bottom Line: Code is read out over several.cc and.h files. How do we deal with compiling that? Page 23

A Simplistic Program Translation Scheme (seen up to now) m.cc ASCII (text) source file Translator (compiler) g++ -o p m.cc p Binary executable object file (memory image on disk) Problems: Efficiency: small change requires complete recompilation Modularity: hard to share common functions (e.g., cout, sort) Solution: Use separate files for different functionalities (code is modular ) Linker Example C Program m.cc int e=7; int main()... z = squared(y); cout << e; sq.cc extern int e; int squared(int y) return y*y; return 0; Page 24

A Better Scheme Using a Linker m.cc sq.cc Translators Translators m.o sq.o Separately compiled object files Linker (ld) p Executable object file (contains code and data for all functions defined in m.cc and sq.cc) Translating the Example Program g++ coordinates all steps in the translation and linking process. Invokes preprocessor, compiler, assembler (as), and linker (ld). Passes command line arguments to appropriate phases Example: create executable p from m.cc and sq.cc: g++ -c m.cc g++ -c a.cc g++ m.o a.o o p This creates m.o This creates a.o Links m.o and a.o Page 25

Translating the Example Program g++ coordinates all steps in the translation and linking process. Invokes preprocessor, compiler, assembler (as), and linker (ld). Passes command line arguments to appropriate phases Example: create executable p from m.cc and a.cc: g++ -c m.cc g++ -c a.cc g++ m.o a.o o p This creates m.o This creates a.o Links m.o and a.o Can do it like this too: g++ m.cc a.cc o p But: If one file changes,all need to be recompiled,long compile time What Does a Linker Do? Merges object files Merges multiple (.o) object files into a single executable object file that can be loaded and executed. Resolves external references As part of the merging process, resolves external references. External reference: reference to a symbol defined in another object file. External references can be to either code or data» code: a(); /* reference to symbol a */» data: extern int x; /* reference to symbol x */ Page 26

Why Linkers? Modularity Program can be written as a collection of smaller source files, rather than one monolithic mass. Can build libraries of common functions (more on this later) e.g., Math library, iostream library Efficiency Time: Change one source file, recompile that one!, and then relink. No need to recompile other source files» e.g., if Bahlul changes sort, then only his Set.cc will be recompiled to produce a new Set.o, not our own So what goes in.cc and in.h? int main() Listnode *head;... z = squared(y); head = free_list(head); return 0; main.cc squared.cc int squared(int y) return y*y; typedef struct list_node... Listnode; list.cc Listnode *free_list(listnode *l)..//ex5 use no aux pointers //ex4&5 prize Visual C++ free Page 27

Example C++ Program int main() Listnode *head;//listnode??... z = squared(y); head = free_list(head); return 0; main.cc squared.cc int squared(int y) return y*y; typedef struct list_node... Listnode; //move to list.h list.cc Listnode *free_list(listnode *l).. //ex5 use no aux pointers Example Program main.cc #include squared.h squared.h int squared(int y); int e=7; int main() Listnode *head;... z = squared(y); head = free_list(head); squared.cc #include squared.h int squared(int y) return y*y; return 0; Page 28

Example Program #include squared.h #include List.h int e=7; int main() Listnode *head;... z = squared(y); head = free_list(head); return 0; main.cc List.h typedef struct list_node... Listnode; Listnode *free_list(listnode *l); list.cc #include List.h Listnode *free_list(listnode *l).. //ex5 use no aux pointers How It Works #include List.h #include squared.h int e=7; int main() Listnode *head;... z = squared(y); head = free_list(head); return 0; main.cc List.h typedef struct list_node... Listnode; Listnode *free_list(listnode *l); squared.h int squared(int y); Preprocessor includes all text in List.h and squared.h in main.cc. We just separate declarations out for use by others. Page 29