COSC121: Computer Systems: Runtime Stack

Similar documents
Chapter 12 Variables and Operators

Chapter 12 Variables and Operators

Lecture 5: C programming

Chapter 11 Introduction to Programming in C

Chapter 12 Variables and Operators

Introduction to C Part 1 HLL s and the Basic Syntax. (Ch11 & 12)

Chapter 11 Introduction to Programming in C

Chapter 11 Introduction to Programming in C

Chapter 11 Introduction to Programming in C

Chapter 11 Introduction to Programming in C

Chapter 11 Introduction to Programming in C

Chapter 11 Introduction to Programming in C

Chapter 12 Variables and Operators

Problem Solving in C. Stepwise Refinement. ...but can stop refining at a higher level of abstraction. Same basic constructs. as covered in Chapter 6

Fundamental of Programming (C)

1 Lexical Considerations

UNIT- 3 Introduction to C++

Lexical Considerations

Scope: Global and Local. Concept of Scope of Variable

Lecture 2. Examples of Software. Programming and Data Structure. Programming Languages. Operating Systems. Sudeshna Sarkar

printf( Please enter another number: ); scanf( %d, &num2);

Lexical Considerations

Full file at

Course Outline Introduction to C-Programming

9/5/2018. Overview. The C Programming Language. Transitioning to C from Python. Why C? Hello, world! Programming in C

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program

The C Programming Language. (with material from Dr. Bin Ren, William & Mary Computer Science)

Chapter 2: Basic Elements of C++

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction

Unit 3. Operators. School of Science and Technology INTRODUCTION

C: How to Program. Week /Mar/05

Lecture 3. More About C

Chapter 2. Lexical Elements & Operators

Programming for Engineers Introduction to C

COSC121: Computer Systems: Review

Features of C. Portable Procedural / Modular Structured Language Statically typed Middle level language

Maciej Sobieraj. Lecture 1

COSC121: Computer Systems: Review

Fundamentals of Programming

About the Tutorial. Audience. Prerequisites. Copyright & Disclaimer. Compiler Design

BITG 1233: Introduction to C++

Objectives. In this chapter, you will:

Fundamentals of Programming Session 4

Chapter 4: Expressions. Chapter 4. Expressions. Copyright 2008 W. W. Norton & Company. All rights reserved.

Language Reference Manual simplicity

A complex expression to evaluate we need to reduce it to a series of simple expressions. E.g * 7 =>2+ 35 => 37. E.g.

Work relative to other classes

Informatica e Sistemi in Tempo Reale

Preview from Notesale.co.uk Page 6 of 52

Fundamentals of Programming

Computers Programming Course 5. Iulian Năstac

Language Translation. Compilation vs. interpretation. Compilation diagram. Step 1: compile. Step 2: run. compiler. Compiled program. program.

Chapter 2 Elementary Programming

Have examined process Creating program Have developed program Written in C Source code

Overview of C, Part 2. CSE 130: Introduction to Programming in C Stony Brook University

Running a C program Compilation Python and C Variables and types Data and addresses Functions Performance. John Edgar 2

Fundamentals of Programming. Lecture 3: Introduction to C Programming

Computer Components. Software{ User Programs. Operating System. Hardware

LESSON 1. A C program is constructed as a sequence of characters. Among the characters that can be used in a program are:

DaMPL. Language Reference Manual. Henrique Grando

C Language Part 1 Digital Computer Concept and Practice Copyright 2012 by Jaejin Lee

Full file at C How to Program, 6/e Multiple Choice Test Bank

Arithmetic Expressions in C

Chapter 13 Control Structures

COP4020 Programming Languages. Compilers and Interpreters Robert van Engelen & Chris Lacher

Computer Components. Software{ User Programs. Operating System. Hardware

CS113: Lecture 3. Topics: Variables. Data types. Arithmetic and Bitwise Operators. Order of Evaluation

C++ Basic Elements of COMPUTER PROGRAMMING. Special symbols include: Word symbols. Objectives. Programming. Symbols. Symbols.

The Compiler So Far. CSC 4181 Compiler Construction. Semantic Analysis. Beyond Syntax. Goals of a Semantic Analyzer.

Chapter 2 - Introduction to C Programming

C OVERVIEW. C Overview. Goals speed portability allow access to features of the architecture speed

flex is not a bad tool to use for doing modest text transformations and for programs that collect statistics on input.

WEEK 4 OPERATORS, EXPRESSIONS AND STATEMENTS

Chapter 2 Basic Elements of C++

UNIT - I. Introduction to C Programming. BY A. Vijay Bharath

Decaf Language Reference

BASIC ELEMENTS OF A COMPUTER PROGRAM

INTRODUCTION 1 AND REVIEW

Variables and literals

Operators. Java operators are classified into three categories:

PRINCIPLES OF COMPILER DESIGN UNIT I INTRODUCTION TO COMPILERS

CSCI 2132 Software Development. Lecture 8: Introduction to C

Declaration and Memory

Basic Types and Formatted I/O

Lecture 3 Tao Wang 1

C OVERVIEW BASIC C PROGRAM STRUCTURE. C Overview. Basic C Program Structure

M4.1-R3: PROGRAMMING AND PROBLEM SOLVING THROUGH C LANGUAGE

Compiler Design. Computer Science & Information Technology (CS) Rank under AIR 100

C++ Programming: From Problem Analysis to Program Design, Third Edition

Slide Set 2. for ENCM 335 in Fall Steve Norman, PhD, PEng

Computers Programming Course 6. Iulian Năstac

Programming Languages Third Edition. Chapter 7 Basic Semantics

\n is used in a string to indicate the newline character. An expression produces data. The simplest expression

CS102: Variables and Expressions

The C++ Language. Arizona State University 1

CP FAQS Q-1) Define flowchart and explain Various symbols of flowchart Q-2) Explain basic structure of c language Documentation section :

9/5/17. The Design and Implementation of Programming Languages. Compilation. Interpretation. Compilation vs. Interpretation. Hybrid Implementation

CS2900 Introductory Programming with Python and C++ Kevin Squire LtCol Joel Young Fall 2007

Fundamental of C programming. - Ompal Singh

CSc 10200! Introduction to Computing. Lecture 2-3 Edgardo Molina Fall 2013 City College of New York

Transcription:

COSC121: Computer Systems: Runtime Stack Jeremy Bolton, PhD Assistant Teaching Professor Constructed using materials: - Patt and Patel Introduction to Computing Systems (2nd) - Patterson and Hennessy Computer Organization and Design (4th) **A special thanks to Rich Squier and Robert van Engelen

Read PP.11 PP.12 Notes

Outline Overview of Compilers Translation

This week our journey takes us COSC 121: Computer Systems Application (Browser) Operating System Compiler (Win, Linux) COSC 255: Operating Systems Software Hardware Assembler Processor Memory Drivers I/O system Instruction Set Architecture Datapath & Control Digital Design Circuit Design transistors COSC 120: Computer Hardware

PP.11: Compiler Introduction

Compilers Compilation Translation of a program written in a source language into a semantically equivalent program written in a target language Source Program Compiler Target (assembly or binary) Error messages

Communication with Computers Compilation Programs are translated into machine language; Use: Large commercial applications Pure Interpretation Programs are interpreted by another program known as an interpreter Use: Small programs or when efficiency is not an issue Hybrid Implementation Systems A compromise between compilers and pure interpreters Use: Small and medium systems when efficiency is not the first concern 1-7

Preprocessors, Compilers, Assemblers, and Linkers Skeletal Source Program Preprocessor Source Program Target Assembly Program Relocatable Object Code Compiler Assembler Linker Try for example: gcc -v myprog.c Libraries and Relocatable Object Files Absolute Machine Code

1-9 The Compilation Process (detailed view)

The Phases of a Compiler Phase Output Sample Programmer (source code producer) Source string A=B+C; Scanner (performs lexical analysis) Token string A, =, B, +, C, ; And symbol table with names Parser (performs syntax analysis based on the grammar of the programming language) Semantic analyzer (type checking, etc) Intermediate code generator Optimizer Parse tree or abstract syntax tree ; = / \ A + Annotated parse tree or abstract syntax tree / \ B C Code generator Assembly code LDR R2,R5, #1 LDR R2,R5, #2 ADD R1,R2, R3

Compilation Translate high-level program (source language) into machine code (machine language) Slow translation, fast execution Compilation process has several phases: lexical analysis: converts characters in the source program into lexical units syntax analysis: transforms lexical units into parse trees which represent the syntactic structure of program Semantics analysis: generate intermediate code code generation: machine code is generated 1-11

C: A High-Level Language Gives symbolic names to values don t need to know which register or memory location Provides abstraction of underlying hardware operations do not depend on instruction set example: can write a = b * c, even though LC-3 doesn t have a multiply instruction Provides expressiveness use meaningful symbols that convey meaning simple expressions for common control patterns (if-then-else) Enhances code readability Safeguards against bugs can enforce rules or conditions at compile-time or run-time 11-12

11-13 Compilation vs. Interpretation Different ways of translating high-level language Interpretation interpreter = program that executes program statements generally one line/command at a time/ interactive limited processing easy to debug, make changes, view intermediate results languages: BASIC, LISP, Perl, Java, Matlab, C-shell Compilation translates statements into machine language does not execute, but creates executable program performs optimization over multiple statements change requires recompilation can be harder to debug, since executed code may be different languages: C, C++, Fortran, Pascal

Compilation vs. Interpretation Consider the following algorithm: Get W from the keyboard. X = W + W Y = X + X Z = Y + Y Print Z to screen. If interpreting, how many arithmetic operations occur? If compiling, we can analyze the entire program and possibly reduce the number of operations. Can we simplify the above algorithm to use a single arithmetic operation? 11-14

11-15 Compiling a C Program Entire mechanism is usually called the compiler Preprocessor macro substitution conditional compilation source-level transformations output is still C Compiler generates object file machine instructions Linker combine object files (including libraries) into executable image Library Object Files Source Code Analysis Target Code Synthesis C Source and Header Files C Preprocessor Compiler Linker Executable Image Symbol Table

A Simple C Program #include <stdio.h> #define STOP 0 /* Function: main */ /* Description: counts down from user input to STOP */ main() { /* variable declarations */ int counter; /* an integer to hold count values */ int startpoint; /* starting point for countdown */ /* prompt user for input */ printf("enter a positive number: "); scanf("%d", &startpoint); /* read into startpoint */ /* count down and print count */ for (counter=startpoint; counter >= STOP; counter--) printf("%d\n", counter); } 11-16

Preprocessor Directives #include <stdio.h> Before compiling, copy contents of header file (stdio.h) into source code. Header files typically contain descriptions of functions and variables needed by the program. no restrictions -- could be any C source code #define STOP 0 Before compiling, replace all instances of the string "STOP" with the string "0" Called a macro Used for values that won't change during execution, but might change if the program is reused. (Must recompile.) 11-17

Comments Begins with /* and ends with */ Can span multiple lines Cannot have a comment within a comment Comments are not recognized within a string example: "my/*don't print this*/string" would be printed as: my/*don't print this*/string As before, use comments to help reader, not to confuse or to restate the obvious 11-18

main Function Every C program must have a function called main(). This is the code that is executed when the program is run. The code for the function lives within brackets: main() { /* code goes here */ } 11-19

Variable Declarations Variables are used as names for data items. Each variable has a type, which tells the compiler how the data is to be interpreted (and how much space it needs, etc.). int counter; int startpoint; int is a predefined integer type in C. 11-20

Input and Output Variety of I/O functions in C Standard Library. Must include <stdio.h> to use them. printf("%d\n", counter); String contains characters to print and formatting directions for variables. This call says to print the variable counter as a decimal integer, followed by a linefeed (\n). scanf("%d", &startpoint); String contains formatting directions for looking at input. This call says to read a decimal integer and assign it to the variable startpoint. (Don't worry about the & yet.) 11-21

More About Output Can print arbitrary expressions, not just variables printf("%d\n", startpoint - counter); Print multiple expressions with a single statement printf("%d %d\n", counter, startpoint - counter); Different formatting options: %d decimal integer %x hexadecimal integer %c ASCII character %f floating-point number 11-22

Examples This code: printf("%d is a prime number.\n", 43); printf("43 plus 59 in decimal is %d.\n", 43+59); printf("43 plus 59 in hex is %x.\n", 43+59); printf("43 plus 59 as a character is %c.\n", 43+59); produces this output: 43 is a prime number. 43 + 59 in decimal is 102. 43 + 59 in hex is 66. 43 + 59 as a character is f. 11-23

Examples of Input Many of the same formatting characters are available for user input. scanf("%c", &nextchar); reads a single character and stores it in nextchar scanf("%f", &radius); reads a floating point number and stores it in radius scanf("%d %d", &length, &width); reads two decimal integers (separated by whitespace), stores the first one in length and the second in width Must use ampersand (&) for variables being modified. (Explained in Chapter 16.) 11-24

Compiling and Linking Various compilers available cc, gcc includes preprocessor, compiler, and linker Lots and lots of options! level of optimization, debugging preprocessor, linker options intermediate files -- object (.o), assembler (.s), preprocessor (.i), etc. 11-25

PP.12 Translation of Variables and Operators

Basic C Elements Variables named, typed data items Operators predefined actions performed on data items combined with variables to form expressions, statements Rules and usage Implementation using LC-3 12-27

Data Types C has three basic data types int integer (at least 16 bits) double floating point (at least 32 bits) char character (at least 8 bits) Exact size can vary, depending on processor int is supposed to be "natural" integer size; for LC-3, that's 16 bits -- 32 bits for most modern processors 12-28

Variable Names Any combination of letters, numbers, and underscore (_) Case matters "sum" is different than "Sum" Cannot begin with a number usually, variables beginning with underscore are used only in special library routines Only first 31 characters are used 12-29

Examples Legal i wordspersecond words_per_second _green areally_longname_morethan31chars areally_longname_morethan31characters same identifier Illegal 10sdigit ten'sdigit done? double reserved keyword 12-30

Literals 12-31 Integer 123 /* decimal */ -123 0x123 /* hexadecimal */ Floating point 6.023 6.023e23 /* 6.023 x 10 23 */ 5E12 /* 5.0 x 10 12 */ Character 'c' '\n' /* newline */ '\xa' /* ASCII 10 (0xA) */

Scope: Global and Local Where is the variable accessible? Global: accessed anywhere in program Local: only accessible in a particular region Compiler infers scope from where variable is declared programmer doesn't have to explicitly state Variable is local to the block in which it is declared block defined by open and closed braces { } can access variable declared in any "containing" block Global variable is declared outside all blocks 12-32

Example #include <stdio.h> int itsglobal = 0; main() { int itslocal = 1; /* local to main */ printf("global %d Local %d\n", itsglobal, itslocal); { int itslocal = 2; /* local to this block */ itsglobal = 4; /* change global variable */ printf("global %d Local %d\n", itsglobal, itslocal); } printf("global %d Local %d\n", itsglobal, itslocal); } Output Global 0 Local 1 Global 4 Local 2 Global 4 Local 1 12-33

Operators Programmers manipulate variables using the operators provided by the high-level language. Variables and operators combine to form expressions and statements which denote the work to be done by the program. Each operator may correspond to many machine instructions. Example: The multiply operator (*) typically requires multiple LC-3 ADD instructions. 12-34

Expression Any combination of variables, constants, operators, and function calls every expression has a type, derived from the types of its components (according to C typing rules) Examples: counter >= STOP x + sqrt(y) x & z + 3 9 - w-- % 6 12-35

Statement Expresses a complete unit of work executed in sequential order Simple statement ends with semicolon z = x * y; /* assign product to z */ y = y + 1; /* after multiplication */ ; /* null statement */ Compound statement groups simple statements using braces. syntactically equivalent to a simple statement { z = x * y; y = y + 1; } 12-36

Operators Three things to know about each operator (1) Function what does it do? (2) Precedence in which order are operators combined? Example: "a * b + c * d" is the same as "(a * b) + (c * d)" because multiply (*) has a higher precedence than addition (+) (3) Associativity in which order are operators of the same precedence combined? Example: "a - b - c" is the same as "(a - b) - c" because add/sub associate left-to-right 12-37

Assignment Operator All expressions evaluate to a value, even ones with the assignment operator. For assignment, the result is the value assigned. usually (but not always) the value of the right-hand side type conversion might make assigned value different than computed value Assignment associates right to left. y = x = 3; y gets the value 3, because (x = 3) evaluates to the value 3. 12-38

Arithmetic Operators Symbol Operation Usage Precedence Assoc * multiply x * y 6 l-to-r / divide x / y 6 l-to-r % modulo x % y 6 l-to-r + addition x + y 7 l-to-r - subtraction x - y 7 l-to-r All associate left to right. * / % have higher precedence than + -. 12-39

Arithmetic Expressions If mixed types, smaller type is "promoted" to larger. x + 4.3 if x is int, converted to double and result is double Integer division -- fraction is dropped. x / 3 if x is int and x=5, result is 1 (not 1.666666...) Modulo -- result is remainder. x % 3 if x is int and x=5, result is 2. 12-40

Bitwise Operators Symbol Operation Usage Precedence Assoc ~ bitwise NOT ~x 4 r-to-l << left shift x << y 8 l-to-r >> right shift x >> y 8 l-to-r & bitwise AND x & y 11 l-to-r ^ bitwise XOR x ^ y 12 l-to-r bitwise OR x y 13 l-to-r Operate on variables bit-by-bit. Like LC-3 AND and NOT instructions. Shift operations are logical (not arithmetic). Operate on values -- neither operand is changed. 12-41

Logical Operators Symbol Operation Usage Precedence Assoc! logical NOT!x 4 r-to-l && logical AND x && y 14 l-to-r logical OR x y 15 l-to-r Treats entire variable (or value) as TRUE (non-zero) or FALSE (zero). Result is 1 (TRUE) or 0 (FALSE). 12-42

Relational Operators Symbol Operation Usage Precedence Assoc > greater than x > y 9 l-to-r >= greater than or equal x >= y 9 l-to-r < less than x < y 9 l-to-r <= less than or equal x <= y 9 l-to-r == equal x == y 10 l-to-r!= not equal x!= y 10 l-to-r Result is 1 (TRUE) or 0 (FALSE). Note: Don't confuse equality (==) with assignment (=). 12-43

Special Operators: ++ and -- Changes value of variable before (or after) its value is used in an expression. Symbol Operation Usage Precedence Assoc ++ postincrement x++ 2 r-to-l -- postdecrement x-- 2 r-to-l ++ preincrement ++x 3 r-to-l <= predecrement --x 3 r-to-l Pre: Increment/decrement variable before using its value. Post: Increment/decrement variable after using its value. 12-44

Using ++ and -- x = 4; y = x++; Results: x = 5, y = 4 (because x is incremented after assignment) x = 4; y = ++x; Results: x = 5, y = 5 (because x is incremented before assignment) 12-45

Practice with Precedence Assume a=1, b=2, c=3, d=4. x = a * b + c * d / 2; /* x = 8 */ same as: x = (a * b) + ((c * d) / 2); For long or confusing expressions, use parentheses, because reader might not have memorized precedence table. Note: Assignment operator has lowest precedence, so all the arithmetic operations on the right-hand side are evaluated first. 12-46

Symbol Table Like assembler, compiler needs to know information associated with identifiers in assembler, all identifiers were labels and information is address Compiler keeps more information Name (identifier) Type Location in memory Scope Name Type Offset Scope amount hours minutes rate seconds time int int int int int int 0-3 -4-1 -5-2 main main main main main main 12-47

Local Variable Storage Local variables are stored in an activation record, also known as a stack frame. Symbol table offset gives the distance from the base of the frame. R5 is the frame pointer holds address of the base of the current frame. A new frame is pushed on the run-time stack each time a block is entered. Because stack grows downward, base is the highest address of the frame, and variable offsets are <= 0. R5 seconds minutes hours time rate amount 12-48

12-49 Allocating Space for Variables Global data section 0x0000 All global variables stored here (actually all static variables) R4 points to beginning Run-time stack Used for local variables R6 points to top of stack R5 points to top frame on stack New frame for each block (goes away when block exited) Offset = distance from beginning of storage area 0xFFFF Global: LDR R1, R4, #4 Local: LDR R2, R5, #-3 instructions global data run-time stack PC R4 R6 R5

Variables and Memory Locations In our examples, a variable is always stored in memory. When assigning to a variable, must store to memory location. A real compiler would perform code optimizations that try to keep variables allocated in registers. Why? 12-50

Example: Compiling to LC-3 #include <stdio.h> int inglobal; main() { int inlocal; /* local to main */ int outlocala; int outlocalb; /* initialize */ inlocal = 5; inglobal = 3; /* perform calculations */ outlocala = inlocal++ & ~inglobal; outlocalb = (inlocal + inglobal) - (inlocal - inglobal); /* print results */ printf("the results are: outlocala = %d, outlocalb = %d\n", outlocala, outlocalb); } 12-51

Example: Symbol Table Name Type Offset Scope inglobal int 0 global inlocal int 0 main outlocala int -1 main outlocalb int -2 main 12-52

Example: Code Generation ; main ; initialize variables AND R0, R0, #0 ADD R0, R0, #5 ; inlocal = 5 STR R0, R5, #0 ; (offset = 0) AND R0, R0, #0 ADD R0, R0, #3 ; inglobal = 3 STR R0, R4, #0 ; (offset = 0) 12-53

Example (continued) ; first statement: ; outlocala = inlocal++ & ~inglobal; LDR R0, R5, #0 ; get inlocal ADD R1, R0, #1 ; increment STR R1, R5, #0 ; store LDR R1, R4, #0 ; get inglobal NOT R1, R1 ; ~inglobal AND R2, R0, R1 ; inlocal & ~inglobal STR R2, R5, #-1 ; store in outlocala ; (offset = -1) 12-54

12-55 Example (continued) ; next statement: ; outlocalb = (inlocal + inglobal) ; - (inlocal - inglobal); LDR R0, R5, #0 ; inlocal LDR R1, R4, #0 ; inglobal ADD R0, R0, R1 ; R0 is sum LDR R2, R5, #0 ; inlocal LDR R3, R5, #0 ; inglobal NOT R3, R3 ADD R3, R3, #1 ADD R2, R2, R3 ; R2 is difference NOT R2, R2 ; negate ADD R2, R2, #1 ADD R0, R0, R2 ; R0 = R0 - R2 STR R0, R5, #-2 ; outlocalb (offset = -2)