Compiler construction

Size: px
Start display at page:

Download "Compiler construction"

Transcription

1 This lecture Compiler construction Lecture 5: Project etensions Magnus Mreen Spring 2018 Chalmers Universit o Technolog Gothenburg Universit Some project etensions: Arras Pointers and structures Object-oriented languages Module sstem (etension proposal) Warm-up: Boolean epressions and control low Warm-up: Boolean epressions and control low Possible code generation or one-armed i stmt cgstmt (Cond epr stmt) = do then_ <- newlabel k <- newlabel cgboolepr then_ k epr label then_ cgstmt stmt branch k label k Warm-up: Boolean epressions and control low Possible code generation or one-armed i stmt cgstmt (Cond epr stmt) = do then_ <- newlabel k <- newlabel cgboolepr then_ k epr label then_ cgstmt stmt branch k label k Arras Possible code or conjunction in condition epression cgboolepr then_ k (EAnd ) = do mid <- newlabel cgboolepr mid k label mid cgboolepr then_ k

2 Memor structure Memor organisation JavaLette restrictions Onl local variables and parameters no global variables or other non-local declarations Onl simple data tpes (int, double, boolean) with ied-size values Onl call-b-value parameter passing As a consequence, all data at runtime can be stored in the activation records on a stack. More general language eatures Global variables, nested procedures, linked structures and pointers, classes,, have other requirements: a stack is not suicient or runtime memor management. Tpical memor organisation Stack Heap Static data Code area Addr. 0 Comments Static area or global variables Stack and heap grow rom opposite ends to avoid predetermined size decisions Stack managed b LLVM Management o heap much more complicated than stack Arras in JavaLette Two etensions (each one credit) Java-like arras Arras in the JavaLette etensions are similar to Java arras: A variable o tpe e.g. int[] contains a reerence to a block o memor on the heap, where arra elements are stored. Arras must be eplicitl created as in int[] v = new int[20]; Lower bound o arra inde is alwas 0 Arra elements are initialized to 0/0.0/alse Arras have a length attribute, with dot-notation Arras can be both unction arguments and results First etension One-dimensional arras and oreach statement, as in int sum = 0; or (int : v) sum = sum + ; The ordinar or statement is not required. Two etensions (each one credit) Sample LLVM code Indeing in two-dimensional arra First etension One-dimensional arras and oreach statement, as in int sum = 0; or (int : v) sum = sum + ; The ordinar or statement is not required. Second etension Multidimensional arras: All indices must get upper bounds when an arra is created For n > 1, an n-dimensional arra is a one-dimensional arra, each o whose elements is an n 1-dimensional arra %arr1 = tpe %struct1* %arr2 = tpe %struct2* %struct1 = tpe {i32, [0 i32] %struct2 = tpe {i32, [0 %arr1] deine (%arr2 %m, i32 %i, i32 %j) { %p1 = getelementptr %struct2, %arr2 %m, i32 0, i32 1, i32 %i %p2 = load %arr1, %arr1* %p1 %p3 = getelementptr %struct1, %arr1 %p2, i32 0, i32 1, i32 %j %p4 = load i32, i32* %p3 ret i32 %p4 Your generated code ma well look dierent.

3 Hints or arra etension Hints or arra etension First etension LLVM tpe o arra hinted at in previous slide, use size 0 Use C unction calloc to allocate 0-initialized memor New orms o epression: arra indeing and new epression Indeed epressions also as L-values in assignments Not required to generate bounds-checking code Second etension First etension LLVM tpe o arra hinted at in previous slide, use size 0 Use C unction calloc to allocate 0-initialized memor New orms o epression: arra indeing and new epression Indeed epressions also as L-values in assignments Not required to generate bounds-checking code Second etension new epression with several indices involves generating code with loops and repeated calloc s Indeing requires several getelementptr instructions Structures and pointers etension Structures and pointers In addition to unction deinitions, a Javalette ile ma contain deinitions o structures and pointer tpes Structure objects are allocated on the heap, using new Pointer variable (on stack) ma reer to memor structure on the heap Static data Addr. 0 Code area Structures and pointers eamples Adding structures and pointers to JavaLette Code eamples in JavaLette. tpede struct Node *list; struct Node { int elem; list net; list cons(int, list s) { list res; res = new Node; res->elem = ; res->net = s; return res; int length(list s) { i (s == (list)null) return 0; else return 1 + length(s->net); list romto(int m, int n) { i (m > n) return (list)null; else return cons(m, romto(m + 1, n)); New toplevel deinitions Structure deinitions, eampliied b Node Pointer tpe deinitions, eampliied b list New epression orms New statement orms

4 Adding structures and pointers to JavaLette New toplevel deinitions Structure deinitions, eampliied b Node Pointer tpe deinitions, eampliied b list New epression orms Heap object creation, eampliied b new Node Pointer dereerencing, eampliied b s->net Null pointers, eampliied b (list)null New statement orms Adding structures and pointers to JavaLette New toplevel deinitions Structure deinitions, eampliied b Node Pointer tpe deinitions, eampliied b list New epression orms Heap object creation, eampliied b new Node Pointer dereerencing, eampliied b s->net Null pointers, eampliied b (list)null New statement orms Pointer dereerencing allowed in let hand sides o assignments, as in s->elem = 3; In absense o garbage collection, ou should have a ree statement Implementing structures and pointers in LLVM backend Implementing structures and pointers in LLVM backend Some hints Structure and pointer tpe deinitions translate to LLVM tpe deinitions Again, use calloc or allocating heap memor getelementptr and load will be used or pointer dereerencing Ino about struct laout ma be needed in the state o code generator Some hints Structure and pointer tpe deinitions translate to LLVM tpe deinitions Again, use calloc or allocating heap memor getelementptr and load will be used or pointer dereerencing Ino about struct laout ma be needed in the state o code generator From previous lecture: Computing the size o a tpe We use the getelementptr instruction: %p = getelementptr %T, %T* null, i32 1 %s = ptrtoint %T* %p to i32 Now, %s holds the size o %T. Other uses o pointers (not part o etension) Other uses o pointers (not part o etension) Code eample (in C) void swap (int *, int *) { int tmp = *; * = *; * = tmp; Code eample (in C) void swap (int *, int *) { int tmp = *; * = *; * = tmp; Parameter passing b reerence To make it possible to return results in parameters, one ma use pointer parameters Actual arguments are addresses Problem: makes code optimization much more diicult int main () { int a = 1; int b = 3; swap(&a, &b); print("a=%d\n", a); int main () { int a = 1; int b = 3; swap(&a, &b); print("a=%d\n", a); AR main AR swap a b

5 Call b reerence and aliasing Call b reerence and aliasing Code eamples void swap (int *, int *) { int tmp = *; * = *; * = tmp; swap (, ); Code eamples void swap (int *, int *) { int tmp = *; * = *; * = tmp; swap (, ); Comments With call b reerence and pointers, two dierent variables ma reer to the same location; aliasing Aliasing complicates code optimization: := 2 := 5 a := + 3 Here we might want to replace last instr b a := 5; but what i is an alias or? Deallocating heap memor Garbage collection The problem In contrast to stack memor, there is no simple wa to sa when heap allocated memor is not needed anmore. Two main approaches 1. Eplicit deallocation Programmer deallocates memor when no longer needed (using ree) Potentiall most eicient Ver eas to get wrong (memor leakage or premature returns) 2. Garbage collection Programmer does nothing; runtime sstem reclaims unneeded memor Secure but runtime penalt Acceptable in most situations Used in Java, Haskell, C#, General approach Runtime sstem keeps list(s) o ree heap memor, malloc returns a chunk rom suitable ree list. Man variations. Some approaches: 1. Reerence counting: each chunk keeps a reerence count o incoming pointers, when count becomes zero, chunk is returned to ree list; problem: cclic structures 2. When ree list is empt, collect in two phases: Mark Follow pointers rom global and local variables, marking reachable chunks Sweep Traverse heap and return unmarked chunks to ree list Object-oriented languages Class-based languages We consider onl languages where objects are created as instances o classes. A class describes: Object-orientation a collection o instance variables; each object gets its own cop o this collection a collection o methods to access and update the instance variables Each object contains, in addition to the instance variables, a pointer to a class descriptor. This descriptor contains addresses o the code o methods. Without inheritance, all this is straightorward; classes are just structures. We propose a little bit more: single inheritance without method override.

6 JavaLette classes, code eample 1 JavaLette classes, code eample 2 class Counter { int val; void incr () { val++; return; int value () { return val; int main () { Counter c; c = new Counter; c.incr(); c.incr(); c.incr(); int = c.value(); printint(); return 0; class Point2 { int ; int ; void move(int d, int d) { = + d; = + d; int getx() { return ; int gety() { return ; class Point3 etends Point2 { int z; void movez(int dz) { z = z + dz; int getz() { return z; int main() { Point2 p; Point3 q = new Point3; q.move(2, 4); q.movez(7); p = q; Adding classes to basic JavaLette (etension 1) New toplevel deinitions Class deinitions, consisting o a number o instance variable declarations and a number o method deinitions Instance variables are onl visible within methods o the class All methods are public All classes have one deault constructor, which initializes instance variables to deault values (0, alse, null) A class ma etend another one, adding more instance variables and methods, but without overriding Classes are tpes; variables can be declared to be reerences to objects o a class We have subtping; i S etends C, then S is a subtpe o C; whenever an object o tpe C is epected, we ma suppl an object o tpe S. Hints or object etension 1 New orms o epressions Object creation, eampliied b new Point2, which allocates a new object on the heap with deault values or instance variables Method calls, eampliied b p.move(3,5) Null reerences, eampliied b (Point)null Sel reerence. Within a class, sel reers to the current object; all calls to sibling methods within a class must use method calls to sel Implementation hints Much o ideas (and code) rom the pointers/structures etension can be reused. Method calls will be translated to unction call with receiving object as etra, irst parameter. Overriding / dnamic dispatch (etension 2) Objects at runtime Eample with overriding We consider the ollowing classes: A obja = new A(); B objb = new B(); C objc = new C(); class A { int ; void (int z) { = z; class B etends A { int ; int g() {return 0; g g class C etends B { void (int z) { = z; = 0; code entr A_ code entr B_g code entr C_ Each object includes instance variables and pointer to class descriptor.

7 Objects at runtime, variant Dnamic dispatch A obja = new A(); B objb = new B(); C objc = new C(); null g Code eample A obj = obja; obj.(5); obj = objc; obj.(3); code entr A_ code entr B_g code entr C_ Class descriptors linked into list. List searched at runtime. Dnamic dispatch What code is run? Code eample A obj = obja; obj.(5); obj = objc; obj.(3); The method to eecute is determined at runtime b ollowing the link to the class descriptor Static tpe checking guarantees that there is a method with proper signature in the descriptor There is an eicienc penalt in dnamic dispatch (so optimization tries to remove it) Modules Module sstems Module sstems Programmer s perspective: Modularit Reusabilit Inormation hiding Name space control Programmer s perspective: Modularit Reusabilit Inormation hiding Name space control Compiler s perspective: Separate compilation Smaller compilation units Recompilation onl o changed units Librar modules released as binaries

8 Some approaches A possible module sstem or basic JavaLette Increasing levels o sophistication Inclusion mechanism: concatenate all iles beore compilation Include with header iles: headers with tpe inormation included or compilation and separate linking Import mechanism: Compilation requires interace ino rom imported iles Compilation generates interace and object iles Oten in OO languages, module = class Etension proposal One module per ile All modules in same director (urther etension: deine search path mechanism) Observations Mainl sstem or name space control and libraries I ou want to implement it, ou ma get credits Diicult: not much support in LLVM Import in JavaLette Import and dependenc New snta I M is a module name, then import M is a new orm o declaration M.(e 1,, e n ) is a new orm o epression Unqualiied use A unction in an imported module ma be used without the module qualiication i the name is unique. Name clashes are resolved as ollows: I two imported modules deine a unction, we must use the qualiied orm I the current module and an imported module both deine, the unqualiied name reers to the local unction Import To use unctions deined in M, another module must eplicitl import M. Hence, import is not transitive, i.e, i M imports L and L imports K, it does not ollow that M imports K. Dependenc I M imports L, then M depends on L I M imports L and L depends on K, then M depends on K; dependenc is transitive We assume that dependenc is non-cclic: i M depends on N, then N ma not depend on M. Compiling a module, 1 Compiling a module, 2 Compiler s tasks When called b jlc M.jl, the compiler must 1. Read the import statements o M to get list o imported modules 2. Recursivel, read the import statements o these modules (and report an error i some module not ound) 3. Build dependenc graph o involved modules 4. Sort modules topologicall (and report error i cclic import ound) 5. Go through modules in topological order (M last) and check timestamps to see i recompilation is necessar Hint: It is OK to require that import statements are in the beginning o the ile and with one import per line to avoid need o complete parsing. Smbol table You need a smbol table with tpes o unctions rom all imported modules. This ino is readil available in LLVM iles, but needs to be collected (and parsed). Build the smbol table so that unqualiied names will ind the correct tpe signature (i.e., ou must check or name clashes). Note 1 It is a good idea to replace unqualiied names b qualiied (or code generation) Note 2 Tpe declaration or all imported unctions must be added to LLVM ile

Compiler construction 2009

Compiler construction 2009 Compiler construction 2009 Lecture 6 Some project extensions. Pointers and heap allocation. Object-oriented languages. Module systems. Memory structure Javalette restrictions Only local variables and parameters

More information

Classes. Compiling Methods. Code Generation for Objects. Implementing Objects. Methods. Fields

Classes. Compiling Methods. Code Generation for Objects. Implementing Objects. Methods. Fields Classes Implementing Objects Components fields/instance variables values differ from to usuall mutable methods values shared b all s of a class usuall immutable component visibilit: public/private/protected

More information

Pre-defined class JFrame. Object & Class an analogy

Pre-defined class JFrame. Object & Class an analogy CS1M Lecture 17 Mar 29, 25 1 Announcements: Project 4 due Sunda 4/3 at 6pm Use Keboard class or reading input Section in classrooms this week Previous Lecture: Selection statement Reading input using Keboard

More information

Classes. Code Generation for Objects. Compiling Methods. Dynamic Dispatch. The Need for Dispatching CS412/CS413

Classes. Code Generation for Objects. Compiling Methods. Dynamic Dispatch. The Need for Dispatching CS412/CS413 Classes CS4/CS43 Introduction to Comilers Tim Teitelbaum Lecture : Imlementing Objects 8 March 5 Comonents ields/instance variables values ma dier rom object to object usuall mutable methods values shared

More information

Announcements. CSCI 334: Principles of Programming Languages. Lecture 19: C++

Announcements. CSCI 334: Principles of Programming Languages. Lecture 19: C++ Announcements CSCI 4: Principles of Programming Languages Lecture 19: C++ HW8 pro tip: the HW7 solutions have a complete, correct implementation of the CPS version of bubble sort in SML. All ou need to

More information

CS 403 Compiler Construction Lecture 8 Syntax Tree and Intermediate Code Generation [Based on Chapter 6 of Aho2] This Lecture

CS 403 Compiler Construction Lecture 8 Syntax Tree and Intermediate Code Generation [Based on Chapter 6 of Aho2] This Lecture CS 403 Compiler Construction Lecture 8 Snta Tree and Intermediate Code Generation [Based on Chapter 6 of Aho2] 1 This Lecture 2 1 Remember: Phases of a Compiler This lecture: Intermediate Code This lecture:

More information

Typical Compiler. Ahead- of- time compiler. Compilers... that target interpreters. Interpreter 12/9/15. compile time. run time

Typical Compiler. Ahead- of- time compiler. Compilers... that target interpreters. Interpreter 12/9/15. compile time. run time Ahead- of- time Tpical Compiler compile time C source C 86 assembl 86 assembler 86 machine Source Leical Analzer Snta Analzer Semantic Analzer Analsis Intermediate Code Generator Snthesis run time 86 machine

More information

Object Oriented Languages. Hwansoo Han

Object Oriented Languages. Hwansoo Han Object Oriented Languages Hwansoo Han Object-Oriented Languages An object is an abstract data tpe Encapsulates data, operations and internal state behind a simple, consistent interface. z Data Code Data

More information

The code generator must statically assign a location in the AR for each temporary add $a0 $t1 $a0 ; $a0 = e 1 + e 2 addiu $sp $sp 4 ; adjust $sp (!

The code generator must statically assign a location in the AR for each temporary add $a0 $t1 $a0 ; $a0 = e 1 + e 2 addiu $sp $sp 4 ; adjust $sp (! Lecture Outline Code Generation (II) Adapted from Lectures b Profs. Ale Aiken and George Necula (UCB) Allocating temporaries in the Activation Record Let s optimie cgen a little Code generation for OO

More information

Winter Compiler Construction T9 IR part 2 + Runtime organization. Announcements. Today. Know thy group s code

Winter Compiler Construction T9 IR part 2 + Runtime organization. Announcements. Today. Know thy group s code Winter 26-27 Compiler Construction T9 IR part 2 + Runtime organization Mool Sagiv and Roman Manevich School of Computer Science Tel-Aviv Universit Announcements What is epected in PA3 documentation (5

More information

Module Mechanisms CS412/413. Modules + abstract types. Abstract types. Multiple Implementations. How to type-check?

Module Mechanisms CS412/413. Modules + abstract types. Abstract types. Multiple Implementations. How to type-check? CS412/413 Introduction to Compilers and Translators Andrew Mers Cornell Universit Lecture 19: ADT mechanisms 10 March 00 Module Mechanisms Last time: modules, was to implement ADTs Module collection of

More information

CS S-11 Memory Management 1

CS S-11 Memory Management 1 CS414-2017S-11 Management 1 11-0: Three places in memor that a program can store variables Call stack Heap Code segment 11-1: Eecutable Code Code Segment Static Storage Stack Heap 11-2: Three places in

More information

Simple example. Analysis of programs with pointers. Program model. Points-to relation

Simple example. Analysis of programs with pointers. Program model. Points-to relation Simple eample Analsis of programs with pointers := 5 ptr := & *ptr := 9 := program S1 S2 S3 S4 What are the defs and uses of in this program? Problem: just looking at variable names will not give ou the

More information

Connecting Definition and Use? Tiger Semantic Analysis. Symbol Tables. Symbol Tables (cont d)

Connecting Definition and Use? Tiger Semantic Analysis. Symbol Tables. Symbol Tables (cont d) Tiger source program Tiger Semantic Analysis lexical analyzer report all lexical errors token get next token parser construct variable deinitions to their uses report all syntactic errors absyn checks

More information

Introduction to Programming Using Java (98-388)

Introduction to Programming Using Java (98-388) Introduction to Programming Using Java (98-388) Understand Java fundamentals Describe the use of main in a Java application Signature of main, why it is static; how to consume an instance of your own class;

More information

Introduction to Shape and Pointer Analysis

Introduction to Shape and Pointer Analysis Introduction to Shape and Pointer Analsis CS 502 Lecture 11 10/30/08 Some slides adapted from Nielson, Nielson, Hankin Principles of Program Analsis Analsis of the Heap Thus far, we have focussed on control

More information

Implementing Object-Oriented Languages. Implementing instance variable access. Implementing dynamic dispatching (virtual functions)

Implementing Object-Oriented Languages. Implementing instance variable access. Implementing dynamic dispatching (virtual functions) Implementing Object-Oriented Languages Implementing instance variable access Ke features: inheritance (possibl multiple) subtping & subtpe polmorphism message passing, dnamic binding, run-time tpe testing

More information

Building up a language SICP Variations on a Scheme. Meval. The Core Evaluator. Eval. Apply. 2. syntax procedures. 1.

Building up a language SICP Variations on a Scheme. Meval. The Core Evaluator. Eval. Apply. 2. syntax procedures. 1. 6.001 SICP Variations on a Scheme Scheme Evaluator A Grand Tour Techniques for language design: Interpretation: eval/appl Semantics vs. snta Sntactic transformations Building up a language... 3. 1. eval/appl

More information

Semantics (cont.) Symbol Table. Static Scope. Static Scope. Static Scope. CSE 3302 Programming Languages. Static vs. Dynamic Scope

Semantics (cont.) Symbol Table. Static Scope. Static Scope. Static Scope. CSE 3302 Programming Languages. Static vs. Dynamic Scope -2-1 CSE 3302 Programming Languages Semantics (cont.) Smbol Table Smbol Table: maintain bindings. Can be viewed as functions that map names to their attributes. Names SmbolTable Attributes Chengkai Li,

More information

EECS1022 Winter 2018 Additional Notes Tracing Point, PointCollector, and PointCollectorTester

EECS1022 Winter 2018 Additional Notes Tracing Point, PointCollector, and PointCollectorTester EECS1022 Winter 2018 Additional Notes Tracing, Collector, and CollectorTester Chen-Wei Wang Contents 1 Class 1 2 Class Collector 2 Class CollectorTester 7 1 Class 1 class { 2 double ; double ; 4 (double

More information

9.8 Graphing Rational Functions

9.8 Graphing Rational Functions 9. Graphing Rational Functions Lets begin with a deinition. Deinition: Rational Function A rational unction is a unction o the orm P where P and Q are polynomials. Q An eample o a simple rational unction

More information

Short Notes of CS201

Short Notes of CS201 #includes: Short Notes of CS201 The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with < and > if the file is a system

More information

CS201 - Introduction to Programming Glossary By

CS201 - Introduction to Programming Glossary By CS201 - Introduction to Programming Glossary By #include : The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with

More information

CS 536 Introduction to Programming Languages and Compilers Charles N. Fischer Lecture 11

CS 536 Introduction to Programming Languages and Compilers Charles N. Fischer Lecture 11 CS 536 Introduction to Programming Languages and Compilers Charles N. Fischer Lecture 11 CS 536 Spring 2015 1 Handling Overloaded Declarations Two approaches are popular: 1. Create a single symbol table

More information

Definition. Pointers. Outline. Why pointers? Definition. Memory Organization Overview. by Ziad Kobti. Definition. Pointers enable programmers to:

Definition. Pointers. Outline. Why pointers? Definition. Memory Organization Overview. by Ziad Kobti. Definition. Pointers enable programmers to: Pointers by Ziad Kobti Deinition When you declare a variable o any tye, say: int = ; The system will automatically allocated the required memory sace in a seciic location (tained by the system) to store

More information

Optional: Building a processor from scratch

Optional: Building a processor from scratch Optional: Building a processor from scratch In this assignment we are going build a computer processor from the ground up, starting with transistors, and ending with a small but powerful processor. The

More information

foldr CS 5010 Program Design Paradigms Lesson 5.4

foldr CS 5010 Program Design Paradigms Lesson 5.4 oldr CS 5010 Program Design Paradigms Lesson 5.4 Mitchell Wand, 2012-2014 This work is licensed under a Creative Commons Attribution-NonCommercial 4.0 International License. 1 Introduction In this lesson,

More information

Compiler Construction Project

Compiler Construction Project Compiler Construction Project Josef Svenningsson / Alex Gerdes Spring 2016 v1.2 Contents 1 Change Log 3 1.1 v1.2 April 11............................ 3 1.2 v1.1 March 18............................ 3 2

More information

Building Interpreters

Building Interpreters Building Interpreters Mool Sagiv html://www.cs.tau.ac.il/~msagiv/courses/wcc13.html Chapter 4 1 Structure of a simple compiler/interpreter Leical analsis Snta analsis Runtime Sstem Design Intermediate

More information

Common Misunderstandings from Exam 1 Material

Common Misunderstandings from Exam 1 Material Common Misunderstandings from Exam 1 Material Kyle Dewey Stack and Heap Allocation with Pointers char c = c ; char* p1 = malloc(sizeof(char)); char** p2 = &p1; Where is c allocated? Where is p1 itself

More information

Declaring Pointers. Declaration of pointers <type> *variable <type> *variable = initial-value Examples:

Declaring Pointers. Declaration of pointers <type> *variable <type> *variable = initial-value Examples: 1 Programming in C Pointer Variable A variable that stores a memory address Allows C programs to simulate call-by-reference Allows a programmer to create and manipulate dynamic data structures Must be

More information

Three-Dimensional Object Representations Chapter 8

Three-Dimensional Object Representations Chapter 8 Three-Dimensional Object Representations Chapter 8 3D Object Representation A surace can be analticall generated using its unction involving the coordinates. An object can be represented in terms o its

More information

Run-time Environments

Run-time Environments Run-time Environments Status We have so far covered the front-end phases Lexical analysis Parsing Semantic analysis Next come the back-end phases Code generation Optimization Register allocation Instruction

More information

Sample Problems for Quiz # 3

Sample Problems for Quiz # 3 EE 1301 UMN Introduction to Computing Sstems Spring 2013 Sample Problems for Quiz # 3 1. Implementing XOR with AND gates Recall that the Eclusive-OR (XOR) function is 1 if an odd number of the inputs are

More information

Run-time Environments

Run-time Environments Run-time Environments Status We have so far covered the front-end phases Lexical analysis Parsing Semantic analysis Next come the back-end phases Code generation Optimization Register allocation Instruction

More information

Data, memory. Pointers and Dynamic Variables. Example. Pointers Variables (or Pointers) Fall 2018, CS2

Data, memory. Pointers and Dynamic Variables. Example. Pointers Variables (or Pointers) Fall 2018, CS2 Data, memor Pointers and Dnamic Variables Fall 2018, CS2 memor address: ever bte is identified b a numeric address in the memor. a data value requiring multiple btes are stored consecutivel in memor cells

More information

Variables and Bindings

Variables and Bindings Net: Variables Variables and Bindings Q: How to use variables in ML? Q: How to assign to a variable? # let = 2+2;; val : int = 4 let = e;; Bind the value of epression e to the variable Variables and Bindings

More information

Lecture 2: C Programm

Lecture 2: C Programm 0 3 E CS 1 Lecture 2: C Programm ing C Programming Procedural thought process No built in object abstractions data separate from methods/functions Low memory overhead compared to Java No overhead of classes

More information

Semantics. Names. Binding Time

Semantics. Names. Binding Time /24/ CSE 3302 Programming Languages Semantics Chengkai Li, Weimin He Spring Names Names: identif language entities variables, procedures, functions, constants, data tpes, Attributes: properties of names

More information

Design Issues. Subroutines and Control Abstraction. Subroutines and Control Abstraction. CSC 4101: Programming Languages 1. Textbook, Chapter 8

Design Issues. Subroutines and Control Abstraction. Subroutines and Control Abstraction. CSC 4101: Programming Languages 1. Textbook, Chapter 8 Subroutines and Control Abstraction Textbook, Chapter 8 1 Subroutines and Control Abstraction Mechanisms for process abstraction Single entry (except FORTRAN, PL/I) Caller is suspended Control returns

More information

Object Oriented Programming. Solved MCQs - Part 2

Object Oriented Programming. Solved MCQs - Part 2 Object Oriented Programming Solved MCQs - Part 2 Object Oriented Programming Solved MCQs - Part 2 It is possible to declare as a friend A member function A global function A class All of the above What

More information

An Introduction to C++

An Introduction to C++ An Introduction to C++ Introduction to C++ C++ classes C++ class details To create a complex type in C In the.h file Define structs to store data Declare function prototypes The.h file serves as the interface

More information

Programming Language Dilemma Fall 2002 Lecture 1 Introduction to Compilation. Compilation As Translation. Starting Point

Programming Language Dilemma Fall 2002 Lecture 1 Introduction to Compilation. Compilation As Translation. Starting Point Programming Language Dilemma 6.035 Fall 2002 Lecture 1 Introduction to Compilation Martin Rinard Laborator for Computer Science Massachusetts Institute of Technolog Stored program computer How to instruct

More information

Lecture 3: C Programm

Lecture 3: C Programm 0 3 E CS 1 Lecture 3: C Programm ing Reading Quiz Note the intimidating red border! 2 A variable is: A. an area in memory that is reserved at run time to hold a value of particular type B. an area in memory

More information

CS201 Some Important Definitions

CS201 Some Important Definitions CS201 Some Important Definitions For Viva Preparation 1. What is a program? A program is a precise sequence of steps to solve a particular problem. 2. What is a class? We write a C++ program using data

More information

Names, Scope, and Bindings

Names, Scope, and Bindings Names, Scope, and Bindings COMS W4115 Prof. Stephen A. Edwards Spring 2007 Columbia University Department of Computer Science What s In a Name? Name: way to refer to something else variables, functions,

More information

CS 430 Spring Mike Lam, Professor. Data Types and Type Checking

CS 430 Spring Mike Lam, Professor. Data Types and Type Checking CS 430 Spring 2015 Mike Lam, Professor Data Types and Type Checking Type Systems Type system Rules about valid types, type compatibility, and how data values can be used Benefits of a robust type system

More information

POINTERS - Pointer is a variable that holds a memory address of another variable of same type. - It supports dynamic allocation routines. - It can improve the efficiency of certain routines. C++ Memory

More information

CPSC 3740 Programming Languages University of Lethbridge. Data Types

CPSC 3740 Programming Languages University of Lethbridge. Data Types Data Types A data type defines a collection of data values and a set of predefined operations on those values Some languages allow user to define additional types Useful for error detection through type

More information

G Programming Languages - Fall 2012

G Programming Languages - Fall 2012 G22.2110-003 Programming Languages - Fall 2012 Lecture 2 Thomas Wies New York University Review Last week Programming Languages Overview Syntax and Semantics Grammars and Regular Expressions High-level

More information

Motivation was to facilitate development of systems software, especially OS development.

Motivation was to facilitate development of systems software, especially OS development. A History Lesson C Basics 1 Development of language by Dennis Ritchie at Bell Labs culminated in the C language in 1972. Motivation was to facilitate development of systems software, especially OS development.

More information

Background Functions (1C) Young Won Lim 12/6/17

Background Functions (1C) Young Won Lim 12/6/17 Background Functions (1C) Copright (c) 2016-2017 Young W. Lim. Permission is granted to cop, distribute and/or modi this document under the terms o the GNU Free Documentation License, Version 1.2 or an

More information

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

CS558 Programming Languages Winter 2018 Lecture 4a. Andrew Tolmach Portland State University CS558 Programming Languages Winter 2018 Lecture 4a Andrew Tolmach Portland State University 1994-2018 Pragmatics of Large Values Real machines are very efficient at handling word-size chunks of data (e.g.

More information

Compiler Construction D7011E

Compiler Construction D7011E Compiler Construction D7011E Lecture 14: Memory Management Viktor Leijon Slides largely by Johan Nordlander with material generously provided by Mark P. Jones. 1 First: Run-time Systems 2 The Final Component:

More information

arxiv: v5 [cs.pl] 13 May 2015

arxiv: v5 [cs.pl] 13 May 2015 Heap Abstractions or Static Analsis Vini Kanvar and Uda P. Khedker Department o Computer Science and Engineering Indian Institute o Technolog Bomba Email: {vini,uda}@cse.iitb.ac.in arxiv:1403.4910v5 [cs.pl]

More information

CS 267: Automated Verification. Lecture 6: Binary Decision Diagrams. Instructor: Tevfik Bultan

CS 267: Automated Verification. Lecture 6: Binary Decision Diagrams. Instructor: Tevfik Bultan CS 267: Automated Verification Lecture 6: Binar Decision Diagrams Instructor: evfik Bultan Binar Decision Diagrams (BDDs) [Brant 86] Reduced Ordered Binar Decision Diagrams (BDDs) An efficient data structure

More information

Status. We ll do code generation first... Outline

Status. We ll do code generation first... Outline Status Run-time Environments Lecture 11 We have covered the ront-end phases Lexical analysis Parsin Semantic analysis Next are the back-end phases Optimization Code eneration We ll do code eneration irst...

More information

CSE 303: Concepts and Tools for Software Development

CSE 303: Concepts and Tools for Software Development CSE 303: Concepts and Tools for Software Development Hal Perkins Autumn 2008 Lecture 24 Introduction to C++ CSE303 Autumn 2008, Lecture 24 1 C++ C++ is an enormous language: All of C Classes and objects

More information

Visual Programming with Interaction Nets

Visual Programming with Interaction Nets Visual Programming with Interaction Nets Abubakar Hassan, Ian Mackie, and Jorge Sousa Pinto 1 Department of Informatics, Universit of Susse, Falmer, Brighton BN1 9QJ, UK 2 LIX, École Poltechnique, 91128

More information

1B1b Implementing Data Structures Lists, Hash Tables and Trees

1B1b Implementing Data Structures Lists, Hash Tables and Trees 1B1b Implementing Data Structures Lists, Hash Tables and Trees Agenda Classes and abstract data types. Containers. Iteration. Lists Hash Tables Trees Note here we only deal with the implementation of data

More information

Cpt S 122 Data Structures. Course Review Midterm Exam # 1

Cpt S 122 Data Structures. Course Review Midterm Exam # 1 Cpt S 122 Data Structures Course Review Midterm Exam # 1 Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Midterm Exam 1 When: Friday (09/28) 12:10-1pm Where:

More information

10. SOPC Builder Component Development Walkthrough

10. SOPC Builder Component Development Walkthrough 10. SOPC Builder Component Development Walkthrough QII54007-9.0.0 Introduction This chapter describes the parts o a custom SOPC Builder component and guides you through the process o creating an example

More information

Neighbourhood Operations

Neighbourhood Operations Neighbourhood Operations Neighbourhood operations simply operate on a larger neighbourhood o piels than point operations Origin Neighbourhoods are mostly a rectangle around a central piel Any size rectangle

More information

CS 132 Compiler Construction, Fall 2011 Instructor: Jens Palsberg Multiple Choice Exam, Dec 6, 2011

CS 132 Compiler Construction, Fall 2011 Instructor: Jens Palsberg Multiple Choice Exam, Dec 6, 2011 CS 132 Compiler Construction, Fall 2011 Instructor: Jens Palsberg Multiple Choice Eam, Dec 6, 2011 ID Name This eam consists of 22 questions. Each question has four options, eactl one of which is correct,

More information

C: Pointers. C: Pointers. Department of Computer Science College of Engineering Boise State University. September 11, /21

C: Pointers. C: Pointers. Department of Computer Science College of Engineering Boise State University. September 11, /21 Department of Computer Science College of Engineering Boise State University September 11, 2017 1/21 Pointers A pointer is a variable that stores the address of another variable. Pointers are similar to

More information

Outline. Java Models for variables Types and type checking, type safety Interpretation vs. compilation. Reasoning about code. CSCI 2600 Spring

Outline. Java Models for variables Types and type checking, type safety Interpretation vs. compilation. Reasoning about code. CSCI 2600 Spring Java Outline Java Models for variables Types and type checking, type safety Interpretation vs. compilation Reasoning about code CSCI 2600 Spring 2017 2 Java Java is a successor to a number of languages,

More information

NOTE: Answer ANY FOUR of the following 6 sections:

NOTE: Answer ANY FOUR of the following 6 sections: A-PDF MERGER DEMO Philadelphia University Lecturer: Dr. Nadia Y. Yousif Coordinator: Dr. Nadia Y. Yousif Internal Examiner: Dr. Raad Fadhel Examination Paper... Programming Languages Paradigms (750321)

More information

2. Getting Started with the Graphical User Interface

2. Getting Started with the Graphical User Interface February 2011 NII52017-10.1.0 2. Getting Started with the Graphical User Interace NII52017-10.1.0 The Nios II Sotware Build Tools (SBT) or Eclipse is a set o plugins based on the popular Eclipse ramework

More information

Compilers. Cool Semantics II. Alex Aiken

Compilers. Cool Semantics II. Alex Aiken Compilers Informal semantics of new T Allocate locations to hold all attributes of an object of class T Essentially, allocate a new object Set attributes with their default values Evaluate the initializers

More information

CE221 Programming in C++ Part 2 References and Pointers, Arrays and Strings

CE221 Programming in C++ Part 2 References and Pointers, Arrays and Strings CE221 Programming in C++ Part 2 References and Pointers, Arrays and Strings 19/10/2017 CE221 Part 2 1 Variables and References 1 In Java a variable of primitive type is associated with a memory location

More information

EE 264: Image Processing and Reconstruction. Image Motion Estimation II. EE 264: Image Processing and Reconstruction. Outline

EE 264: Image Processing and Reconstruction. Image Motion Estimation II. EE 264: Image Processing and Reconstruction. Outline Peman Milanar Image Motion Estimation II Peman Milanar Outline. Introduction to Motion. Wh Estimate Motion? 3. Global s. Local Motion 4. Block Motion Estimation 5. Optical Flow Estimation Basics 6. Optical

More information

COMS W4705, Spring 2015: Problem Set 2 Total points: 140

COMS W4705, Spring 2015: Problem Set 2 Total points: 140 COM W4705, pring 2015: Problem et 2 Total points: 140 Analytic Problems (due March 2nd) Question 1 (20 points) A probabilistic context-ree grammar G = (N, Σ, R,, q) in Chomsky Normal Form is deined as

More information

Credits and Disclaimers

Credits and Disclaimers Credits and Disclaimers 1 The eamples and discussion in the following slides have been adapted from a variet of sources, including: Chapter 3 of Computer Sstems 3 nd Edition b Brant and O'Hallaron 86 Assembl/GAS

More information

Module 27 Switch-case statements and Run-time storage management

Module 27 Switch-case statements and Run-time storage management Module 27 Switch-case statements and Run-time storage management In this module we will discuss the pending constructs in generating three-address code namely switch-case statements. We will also discuss

More information

Fractals and the Collage Theorem

Fractals and the Collage Theorem Universit o Nebraska - Lincoln DigitalCommons@Universit o Nebraska - Lincoln MAT Eam Epositor Papers Math in the Middle Institute Partnership 7-2006 Fractals and the Collage Theorem Sandra S. Snder Universit

More information

Bidirectional Object Layout for Separate Compilation

Bidirectional Object Layout for Separate Compilation Proceedings of the 1995 AM onference on Object-Oriented Programming Sstems, Languages, and Applications (OOPSLA) Bidirectional Object Laout for Separate ompilation Andrew. Mers MI Laborator for omputer

More information

CSE 401/M501 Compilers

CSE 401/M501 Compilers CSE 401/M501 Compilers Code Shape II Objects & Classes Hal Perkins Autumn 2018 UW CSE 401/M501 Autumn 2018 L-1 Administrivia Semantics/type check due next Thur. 11/15 How s it going? Reminder: if you want

More information

CSE 374 Programming Concepts & Tools. Hal Perkins Spring 2010

CSE 374 Programming Concepts & Tools. Hal Perkins Spring 2010 CSE 374 Programming Concepts & Tools Hal Perkins Spring 2010 Lecture 19 Introduction ti to C++ C++ C++ is an enormous language: g All of C Classes and objects (kind of like Java, some crucial differences)

More information

Binary recursion. Unate functions. If a cover C(f) is unate in xj, x, then f is unate in xj. x

Binary recursion. Unate functions. If a cover C(f) is unate in xj, x, then f is unate in xj. x Binary recursion Unate unctions! Theorem I a cover C() is unate in,, then is unate in.! Theorem I is unate in,, then every prime implicant o is unate in. Why are unate unctions so special?! Special Boolean

More information

Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur

Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur Lecture - 43 Dynamic Binding (Polymorphism): Part III Welcome to Module

More information

Effective Static Race Detection for Java. Part I. Chord. Chord. Chord. Chord - Overview. Problems addressed

Effective Static Race Detection for Java. Part I. Chord. Chord. Chord. Chord - Overview. Problems addressed Eective Static Race Detection or Java Mayer Naik, Alex Aiken, John Whaley Part I Introduction to Chord and Preliminaries presented by Matt McGill Chord Chord Chord is a static (data) race detection tool

More information

Lectures 5-6: Introduction to C

Lectures 5-6: Introduction to C Lectures 5-6: Introduction to C Motivation: C is both a high and a low-level language Very useful for systems programming Faster than Java This intro assumes knowledge of Java Focus is on differences Most

More information

Section III. Advanced Programming Topics

Section III. Advanced Programming Topics Section III. Advanced Programming Topics This section provides inormation about several advanced embedded programming topics. It includes the ollowing chapters: Chapter 8, Exception Handling Chapter 9,

More information

CIS 341 Final Examination 3 May 2011

CIS 341 Final Examination 3 May 2011 CIS 341 Final Examination 3 May 2011 1 /16 2 /20 3 /40 4 /28 5 /16 Total /120 Do not begin the exam until you are told to do so. You have 120 minutes to complete the exam. There are 12 pages in this exam.

More information

Dynamic memory allocation (malloc)

Dynamic memory allocation (malloc) 1 Plan for today Quick review of previous lecture Array of pointers Command line arguments Dynamic memory allocation (malloc) Structures (Ch 6) Input and Output (Ch 7) 1 Pointers K&R Ch 5 Basics: Declaration

More information

Dynamic Dispatch and Duck Typing. L25: Modern Compiler Design

Dynamic Dispatch and Duck Typing. L25: Modern Compiler Design Dynamic Dispatch and Duck Typing L25: Modern Compiler Design Late Binding Static dispatch (e.g. C function calls) are jumps to specific addresses Object-oriented languages decouple method name from method

More information

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

Q1: /8 Q2: /30 Q3: /30 Q4: /32. Total: /100 ECE 2035(A) Programming for Hardware/Software Systems Fall 2013 Exam Three November 20 th 2013 Name: Q1: /8 Q2: /30 Q3: /30 Q4: /32 Total: /100 1/10 For functional call related questions, let s assume

More information

Dynamic Data Structures. CSCI 112: Programming in C

Dynamic Data Structures. CSCI 112: Programming in C Dynamic Data Structures CSCI 112: Programming in C 1 It s all about flexibility In the programs we ve made so far, the compiler knows at compile time exactly how much memory to allocate for each variable

More information

Derived and abstract data types. TDT4205 Lecture 15

Derived and abstract data types. TDT4205 Lecture 15 1 Derived and abstract data types TDT4205 Lecture 15 2 Where we were We ve looked at static semantics for primitive types and how it relates to type checking We ve hinted at derived types using a multidimensional

More information

Data Structure. Recitation III

Data Structure. Recitation III Data Structure Recitation III Topic Binary Search Abstract Data types Java Interface Linked List Binary search Searching a sorted collection is a common task. A dictionary is a sorted list of word definitions.

More information

Names, Scope, and Bindings

Names, Scope, and Bindings Names, Scope, and Bindings COMS W4115 Prof. Stephen A. Edwards Fall 2007 Columbia University Department of Computer Science What s In a Name? Name: way to refer to something else variables, functions,

More information

2. Reachability in garbage collection is just an approximation of garbage.

2. Reachability in garbage collection is just an approximation of garbage. symbol tables were on the first exam of this particular year's exam. We did not discuss register allocation in this This exam has questions from previous CISC 471/672. particular year. Not all questions

More information

Midterm Review. PIC 10B Spring 2018

Midterm Review. PIC 10B Spring 2018 Midterm Review PIC 10B Spring 2018 Q1 What is size t and when should it be used? A1 size t is an unsigned integer type used for indexing containers and holding the size of a container. It is guarenteed

More information

Programs in memory. The layout of memory is roughly:

Programs in memory. The layout of memory is roughly: Memory 1 Programs in memory 2 The layout of memory is roughly: Virtual memory means that memory is allocated in pages or segments, accessed as if adjacent - the platform looks after this, so your program

More information

ITEC1620 Object-Based Programming. Lecture 13

ITEC1620 Object-Based Programming. Lecture 13 ITEC1620 Object-Based Programming Lecture 13 References A Simple Class AnInt objecta = new AnInt(); AnInt objectb = new AnInt(); objecta objectb AnInt AnInt value value Value Assignments objecta.value

More information

VIRTUAL FUNCTIONS Chapter 10

VIRTUAL FUNCTIONS Chapter 10 1 VIRTUAL FUNCTIONS Chapter 10 OBJECTIVES Polymorphism in C++ Pointers to derived classes Important point on inheritance Introduction to virtual functions Virtual destructors More about virtual functions

More information

8. An example row consists of constants and example elements which are really domain variables.

8. An example row consists of constants and example elements which are really domain variables. CMPT-354-98.2 Lecture Notes June 9, 1998 Chapter 4 Other Relational Languages 4.1 Quer-b-Eample èqbeè 1. QBE is both a quer language and the name of a DB sstem including it. The sstem is no longer in use,

More information

Course Text. Course Description. Course Objectives. StraighterLine Introduction to Programming in C++

Course Text. Course Description. Course Objectives. StraighterLine Introduction to Programming in C++ Introduction to Programming in C++ Course Text Programming in C++, Zyante, Fall 2013 edition. Course book provided along with the course. Course Description This course introduces programming in C++ and

More information

Homework I - Solution

Homework I - Solution CS 426 Fall 2017 1 Homework I - Solution Homework I - Solution CS 426 Compiler Construction Fall Semester 2017 1. (50 points) Intermediate representations: (a) (25 points) Construct a Control-Flow Graph

More information

Lecture 4: Outline. Arrays. I. Pointers II. III. Pointer arithmetic IV. Strings

Lecture 4: Outline. Arrays. I. Pointers II. III. Pointer arithmetic IV. Strings Lecture 4: Outline I. Pointers A. Accessing data objects using pointers B. Type casting with pointers C. Difference with Java references D. Pointer pitfalls E. Use case II. Arrays A. Representation in

More information