This document discusses intermediate code generation. It begins by defining intermediate representations that span the gap between source and target languages. It describes two types of intermediate languages: high-level representations like syntax trees that are closer to the source language, and low-level representations like 3-address code that are closer to the target machine. The document then provides examples and explanations of constructing syntax trees and generating 3-address code for expressions, statements, and functions. It discusses handling various language constructs in the intermediate code.
I am Moffat K. I am a C++ Programming Homework Expert at cpphomeworkhelp.com. I hold a Masters in Programming from London, UK. I have been helping students with their homework for the past 6 years. I solve homework related to C++ Programming.
Visit cpphomeworkhelp.com or email info@cpphomeworkhelp.com. You can also call on +1 678 648 4277 for any assistance with C++ Programming Homework.
Code is not text! How graph technologies can help us to understand our code b...Andreas Dewes
Today, we almost exclusively think of code in software projects as a collection of text files. The tools that we use (version control systems, IDEs, code analyzers) also use text as the primary storage format for code. In fact, the belief that “code is text” is so deeply ingrained in our heads that we never question its validity or even become aware of the fact that there are other ways to look at code.
In my talk I will explain why treating code as text is a very bad idea which actively holds back our understanding and creates a range of problems in large software projects. I will then show how we can overcome (some of) these problems by treating and storing code as data, and more specifically as a graph. I will show specific examples of how we can use this approach to improve our understanding of large code bases, increase code quality and automate certain aspects of software development.
Finally, I will outline my personal vision of the future of programming, which is a future where we no longer primarily interact with code bases using simple text editors. I will also give some ideas on how we might get to that future.
talk at Virginia Bioinformatics Institute, December 5, 2013ericupnorth
Extensible domain-specific programming for the sciences
The notion of scientists as programmers begs the question of what sort of programming language would be a good fit. The common answer seems to be both none of them and all of them. Many scientific applications are a combination of general-purpose and domain-specific languages: R for statistical elements, MATLAB for matrix-based computations, Perl-based regular expressions for string matching, C or FORTRAN for high performance parallel computations, and scripting languages such as Python to glue them all together. This clumsy situation demonstrates the need for different domain-specific language features.
Our hypothesis is that programming could be made easier, less error-prone and result in higher-quality code if languages could be easily extended, by the programmer, with the domain-specific features that a programmer or scientists needs for their particular task at hand. This talk demonstrates the meta-language processing tools that support this composition of programmer-selected language features, with several extensions chosen from the previously mentioned list of features.
The Morse code (see Table 6.10 in book) is a common code that is use.pdfbhim1213
The Morse code (see Table 6.10 in book) is a common code that is used to encode messages
consisted of letters and digits. Each letter consists of a series of dots and dashes; for example, the
code for the letter a is *- and the code for the letter b is -***. Store each letter of the alphabet in a
node of a binary tree of level 5. The root node is at level 1 and stores no letter. The left node at
level 2 stores the letter e (code is *), and the right node stores letter t (code is -). The 4 nodes at
level 3 store the letters with codes (**, *-, -*, --). To build the tree (see Figure 6.38 in book),
read a file in which each line consists of a letter followed by its code. The letters should be
ordered by tree level. To find the position for a letter in the tree, scan the code and branch left for
a dot and branch right for a dash. Encode a message by replacing each letter by its code symbol.
Then decode the message using the Morse code tree. Make sure you use a delimiter symbol
between coded letters.
Implementation Notes: You will need to complete the generic implementation of the BinaryTree
data structure first (see slides). Once it is complete, solve the problem above (note that the book
uses dots and dashes, we will use the asterisk (*) as the dot, hyphen (-) as a dash, and space ( ) as
the delimiter symbol between coded letters). Provide a menu program that asks the user to 1) test
output for all morse code letters with their respective translated alphabet letters (make sure you
are using the binary tree to do the actual translation, output as a nicely formatted table), 2) enter
an input file name to decode morse code and output the translated text to the screen, or 3) enter
in a line of morse code through the console to decode morse code and output the translated text
to the screen
relevenat picture of both the tree diagram and the table of morse code
Solution
JAVA CODE:
import java.io.*;
import java.util.*;
public class MorseCoder implements MorseCodeInterface {
private MorseNode root;
/**
* constructor to build the tree
*/
public MorseCoder() {
root = new MorseNode();
readTreeInfo();
}
/**
* reads in the tree info from the text file (helper method)
*/
private void readTreeInfo() {
Scanner input = null;
try {
input = new Scanner(new File(\"encodings.txt\"));
} catch (FileNotFoundException exception) {
System.out.println(\"File not found!\");
}
while (input.hasNextLine()) {
String data = input.nextLine().trim();
if (data.length() > 0) {
add(data.substring(1).trim(), data.charAt(0));
}
}
input.close();
}
/**
* adds the letter to the tree based on the mcode string (helper method)
* @param mcode the string being fed in
* @param ltr the letter being added at the node
*/
private void add(String mcode, char ltr) {
MorseNode current = root;
String signal = \" \";
for (int i = 0; i < mcode.length(); i++) {
signal = mcode.substring(i, i + 1);
if (signal.equals(\".\")) {
if (current.getLeft() != null) {
current = current.getLeft();
} else {
current.set.
Cosmetic shop management system project report.pdfKamal Acharya
Buying new cosmetic products is difficult. It can even be scary for those who have sensitive skin and are prone to skin trouble. The information needed to alleviate this problem is on the back of each product, but it's thought to interpret those ingredient lists unless you have a background in chemistry.
Instead of buying and hoping for the best, we can use data science to help us predict which products may be good fits for us. It includes various function programs to do the above mentioned tasks.
Data file handling has been effectively used in the program.
The automated cosmetic shop management system should deal with the automation of general workflow and administration process of the shop. The main processes of the system focus on customer's request where the system is able to search the most appropriate products and deliver it to the customers. It should help the employees to quickly identify the list of cosmetic product that have reached the minimum quantity and also keep a track of expired date for each cosmetic product. It should help the employees to find the rack number in which the product is placed.It is also Faster and more efficient way.
Water scarcity is the lack of fresh water resources to meet the standard water demand. There are two type of water scarcity. One is physical. The other is economic water scarcity.
I am Moffat K. I am a C++ Programming Homework Expert at cpphomeworkhelp.com. I hold a Masters in Programming from London, UK. I have been helping students with their homework for the past 6 years. I solve homework related to C++ Programming.
Visit cpphomeworkhelp.com or email info@cpphomeworkhelp.com. You can also call on +1 678 648 4277 for any assistance with C++ Programming Homework.
Code is not text! How graph technologies can help us to understand our code b...Andreas Dewes
Today, we almost exclusively think of code in software projects as a collection of text files. The tools that we use (version control systems, IDEs, code analyzers) also use text as the primary storage format for code. In fact, the belief that “code is text” is so deeply ingrained in our heads that we never question its validity or even become aware of the fact that there are other ways to look at code.
In my talk I will explain why treating code as text is a very bad idea which actively holds back our understanding and creates a range of problems in large software projects. I will then show how we can overcome (some of) these problems by treating and storing code as data, and more specifically as a graph. I will show specific examples of how we can use this approach to improve our understanding of large code bases, increase code quality and automate certain aspects of software development.
Finally, I will outline my personal vision of the future of programming, which is a future where we no longer primarily interact with code bases using simple text editors. I will also give some ideas on how we might get to that future.
talk at Virginia Bioinformatics Institute, December 5, 2013ericupnorth
Extensible domain-specific programming for the sciences
The notion of scientists as programmers begs the question of what sort of programming language would be a good fit. The common answer seems to be both none of them and all of them. Many scientific applications are a combination of general-purpose and domain-specific languages: R for statistical elements, MATLAB for matrix-based computations, Perl-based regular expressions for string matching, C or FORTRAN for high performance parallel computations, and scripting languages such as Python to glue them all together. This clumsy situation demonstrates the need for different domain-specific language features.
Our hypothesis is that programming could be made easier, less error-prone and result in higher-quality code if languages could be easily extended, by the programmer, with the domain-specific features that a programmer or scientists needs for their particular task at hand. This talk demonstrates the meta-language processing tools that support this composition of programmer-selected language features, with several extensions chosen from the previously mentioned list of features.
The Morse code (see Table 6.10 in book) is a common code that is use.pdfbhim1213
The Morse code (see Table 6.10 in book) is a common code that is used to encode messages
consisted of letters and digits. Each letter consists of a series of dots and dashes; for example, the
code for the letter a is *- and the code for the letter b is -***. Store each letter of the alphabet in a
node of a binary tree of level 5. The root node is at level 1 and stores no letter. The left node at
level 2 stores the letter e (code is *), and the right node stores letter t (code is -). The 4 nodes at
level 3 store the letters with codes (**, *-, -*, --). To build the tree (see Figure 6.38 in book),
read a file in which each line consists of a letter followed by its code. The letters should be
ordered by tree level. To find the position for a letter in the tree, scan the code and branch left for
a dot and branch right for a dash. Encode a message by replacing each letter by its code symbol.
Then decode the message using the Morse code tree. Make sure you use a delimiter symbol
between coded letters.
Implementation Notes: You will need to complete the generic implementation of the BinaryTree
data structure first (see slides). Once it is complete, solve the problem above (note that the book
uses dots and dashes, we will use the asterisk (*) as the dot, hyphen (-) as a dash, and space ( ) as
the delimiter symbol between coded letters). Provide a menu program that asks the user to 1) test
output for all morse code letters with their respective translated alphabet letters (make sure you
are using the binary tree to do the actual translation, output as a nicely formatted table), 2) enter
an input file name to decode morse code and output the translated text to the screen, or 3) enter
in a line of morse code through the console to decode morse code and output the translated text
to the screen
relevenat picture of both the tree diagram and the table of morse code
Solution
JAVA CODE:
import java.io.*;
import java.util.*;
public class MorseCoder implements MorseCodeInterface {
private MorseNode root;
/**
* constructor to build the tree
*/
public MorseCoder() {
root = new MorseNode();
readTreeInfo();
}
/**
* reads in the tree info from the text file (helper method)
*/
private void readTreeInfo() {
Scanner input = null;
try {
input = new Scanner(new File(\"encodings.txt\"));
} catch (FileNotFoundException exception) {
System.out.println(\"File not found!\");
}
while (input.hasNextLine()) {
String data = input.nextLine().trim();
if (data.length() > 0) {
add(data.substring(1).trim(), data.charAt(0));
}
}
input.close();
}
/**
* adds the letter to the tree based on the mcode string (helper method)
* @param mcode the string being fed in
* @param ltr the letter being added at the node
*/
private void add(String mcode, char ltr) {
MorseNode current = root;
String signal = \" \";
for (int i = 0; i < mcode.length(); i++) {
signal = mcode.substring(i, i + 1);
if (signal.equals(\".\")) {
if (current.getLeft() != null) {
current = current.getLeft();
} else {
current.set.
Cosmetic shop management system project report.pdfKamal Acharya
Buying new cosmetic products is difficult. It can even be scary for those who have sensitive skin and are prone to skin trouble. The information needed to alleviate this problem is on the back of each product, but it's thought to interpret those ingredient lists unless you have a background in chemistry.
Instead of buying and hoping for the best, we can use data science to help us predict which products may be good fits for us. It includes various function programs to do the above mentioned tasks.
Data file handling has been effectively used in the program.
The automated cosmetic shop management system should deal with the automation of general workflow and administration process of the shop. The main processes of the system focus on customer's request where the system is able to search the most appropriate products and deliver it to the customers. It should help the employees to quickly identify the list of cosmetic product that have reached the minimum quantity and also keep a track of expired date for each cosmetic product. It should help the employees to find the rack number in which the product is placed.It is also Faster and more efficient way.
Water scarcity is the lack of fresh water resources to meet the standard water demand. There are two type of water scarcity. One is physical. The other is economic water scarcity.
Courier management system project report.pdfKamal Acharya
It is now-a-days very important for the people to send or receive articles like imported furniture, electronic items, gifts, business goods and the like. People depend vastly on different transport systems which mostly use the manual way of receiving and delivering the articles. There is no way to track the articles till they are received and there is no way to let the customer know what happened in transit, once he booked some articles. In such a situation, we need a system which completely computerizes the cargo activities including time to time tracking of the articles sent. This need is fulfilled by Courier Management System software which is online software for the cargo management people that enables them to receive the goods from a source and send them to a required destination and track their status from time to time.
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...Amil Baba Dawood bangali
Contact with Dawood Bhai Just call on +92322-6382012 and we'll help you. We'll solve all your problems within 12 to 24 hours and with 101% guarantee and with astrology systematic. If you want to take any personal or professional advice then also you can call us on +92322-6382012 , ONLINE LOVE PROBLEM & Other all types of Daily Life Problem's.Then CALL or WHATSAPP us on +92322-6382012 and Get all these problems solutions here by Amil Baba DAWOOD BANGALI
#vashikaranspecialist #astrologer #palmistry #amliyaat #taweez #manpasandshadi #horoscope #spiritual #lovelife #lovespell #marriagespell#aamilbabainpakistan #amilbabainkarachi #powerfullblackmagicspell #kalajadumantarspecialist #realamilbaba #AmilbabainPakistan #astrologerincanada #astrologerindubai #lovespellsmaster #kalajaduspecialist #lovespellsthatwork #aamilbabainlahore#blackmagicformarriage #aamilbaba #kalajadu #kalailam #taweez #wazifaexpert #jadumantar #vashikaranspecialist #astrologer #palmistry #amliyaat #taweez #manpasandshadi #horoscope #spiritual #lovelife #lovespell #marriagespell#aamilbabainpakistan #amilbabainkarachi #powerfullblackmagicspell #kalajadumantarspecialist #realamilbaba #AmilbabainPakistan #astrologerincanada #astrologerindubai #lovespellsmaster #kalajaduspecialist #lovespellsthatwork #aamilbabainlahore #blackmagicforlove #blackmagicformarriage #aamilbaba #kalajadu #kalailam #taweez #wazifaexpert #jadumantar #vashikaranspecialist #astrologer #palmistry #amliyaat #taweez #manpasandshadi #horoscope #spiritual #lovelife #lovespell #marriagespell#aamilbabainpakistan #amilbabainkarachi #powerfullblackmagicspell #kalajadumantarspecialist #realamilbaba #AmilbabainPakistan #astrologerincanada #astrologerindubai #lovespellsmaster #kalajaduspecialist #lovespellsthatwork #aamilbabainlahore #Amilbabainuk #amilbabainspain #amilbabaindubai #Amilbabainnorway #amilbabainkrachi #amilbabainlahore #amilbabaingujranwalan #amilbabainislamabad
TECHNICAL TRAINING MANUAL GENERAL FAMILIARIZATION COURSEDuvanRamosGarzon1
AIRCRAFT GENERAL
The Single Aisle is the most advanced family aircraft in service today, with fly-by-wire flight controls.
The A318, A319, A320 and A321 are twin-engine subsonic medium range aircraft.
The family offers a choice of engines
Welcome to WIPAC Monthly the magazine brought to you by the LinkedIn Group Water Industry Process Automation & Control.
In this month's edition, along with this month's industry news to celebrate the 13 years since the group was created we have articles including
A case study of the used of Advanced Process Control at the Wastewater Treatment works at Lleida in Spain
A look back on an article on smart wastewater networks in order to see how the industry has measured up in the interim around the adoption of Digital Transformation in the Water Industry.
2. CSc 453: Intermediate Code Generation 2
Overview
Intermediate representations span the gap between
the source and target languages:
closer to target language;
(more or less) machine independent;
allows many optimizations to be done in a machine-independent way.
Implementable via syntax directed translation, so
can be folded into the parsing process.
3. CSc 453: Intermediate Code Generation 3
Types of Intermediate Languages
High Level Representations (e.g., syntax trees):
closer to the source language
easy to generate from an input program
code optimizations may not be straightforward.
Low Level Representations (e.g., 3-address
code, RTL):
closer to the target machine;
easier for optimizations, final code generation;
4. CSc 453: Intermediate Code Generation 4
Syntax Trees
A syntax tree shows the structure of a program by abstracting
away irrelevant details from a parse tree.
Each node represents a computation to be performed;
The children of the node represents what that computation is
performed on.
Syntax trees decouple parsing from subsequent processing.
5. CSc 453: Intermediate Code Generation 5
Syntax Trees: Example
Grammar :
E E + T | T
T T * F | F
F ( E ) | id
Input: id + id * id
Parse tree:
Syntax tree:
6. CSc 453: Intermediate Code Generation 6
Syntax Trees: Structure
Expressions:
leaves: identifiers or constants;
internal nodes are labeled with operators;
the children of a node are its operands.
Statements:
a node’s label indicates what kind of
statement it is;
the children correspond to the components
of the statement.
7. CSc 453: Intermediate Code Generation 7
Constructing Syntax Trees
General Idea: construct bottom-up using
synthesized attributes.
E → E + E { $$ = mkTree(PLUS, $1, $3); }
S → if ‘(‘ E ‘)’ S OptElse { $$ = mkTree(IF, $3, $5, $6); }
OptElse → else S { $$ = $2; }
| /* epsilon */ { $$ = NULL; }
S → while ‘(‘ E ‘)’ S { $$ = mkTree(WHILE, $3, $5); }
mkTree(NodeType, Child1, Child2, …) allocates space for the tree node and fills in its node
type as well as its children.
8. CSc 453: Intermediate Code Generation 8
Three Address Code
Low-level IR
instructions are of the form ‘x = y op z,’ where x,
y, z are variables, constants, or “temporaries”.
At most one operator allowed on RHS, so no
‘built-up” expressions.
Instead, expressions are computed using temporaries
(compiler-generated variables).
9. CSc 453: Intermediate Code Generation 9
Three Address Code: Example
Source:
if ( x + y*z > x*y + z)
a = 0;
Three Address Code:
tmp1 = y*z
tmp2 = x+tmp1 // x + y*z
tmp3 = x*y
tmp4 = tmp3+z // x*y + z
if (tmp2 <= tmp4) goto L
a = 0
L:
10. CSc 453: Intermediate Code Generation 10
An Intermediate Instruction Set
Assignment:
x = y op z (op binary)
x = op y (op unary);
x = y
Jumps:
if ( x op y ) goto L (L a label);
goto L
Pointer and indexed
assignments:
x = y[ z ]
y[ z ] = x
x = &y
x = *y
*y = x.
Procedure call/return:
param x, k (x is the kth param)
retval x
call p
enter p
leave p
return
retrieve x
Type Conversion:
x = cvt_A_to_B y (A, B base types)
e.g.: cvt_int_to_float
Miscellaneous
label L
11. CSc 453: Intermediate Code Generation 11
Three Address Code: Representation
Each instruction represented as a structure called a
quadruple (or “quad”):
contains info about the operation, up to 3 operands.
for operands: use a bit to indicate whether constant or ST pointer.
E.g.:
x = y + z if ( x y ) goto L
12. CSc 453: Intermediate Code Generation 12
Code Generation: Approach
function prototypes, global declarations:
save information in the global symbol table.
function definitions:
function name, return type, argument type and number saved
in global table (if not already there);
process formals, local declarations into local symbol table;
process body:
construct syntax tree;
traverse syntax tree and generate code for the function;
deallocate syntax tree and local symbol table.
13. CSc 453: Intermediate Code Generation 13
Code Generation: Approach
codeGen_stmt(synTree_node S)
{
switch (S.nodetype) {
case FOR: … ; break;
case WHILE : … ; break;
case IF: … ; break;
case ‘=‘ : … ; break;
…
}
codeGen_expr(synTree_node E)
{
switch (E.nodetype) {
case ‘+’: … ; break;
case ‘*’ : … ; break;
case ‘–’: … ; break;
case ‘/’ : … ; break;
…
}
Recursively traverse syntax tree:
Node type determines action at each node;
Code for each node is a (doubly linked) list of three-address instructions;
Generate code for each node after processing its children
recursively process the children,
then generate code for this node
and glue it all together.
14. CSc 453: Intermediate Code Generation 14
Intermediate Code Generation
Auxiliary Routines:
struct symtab_entry *newtemp(typename t)
creates a symbol table entry for new temporary variable each
time it is called, and returns a pointer to this ST entry.
struct instr *newlabel()
returns a new label instruction each time it is called.
struct instr *newinstr(arg1, arg2, …)
creates a new instruction, fills it in with the arguments supplied,
and returns a pointer to the result.
16. CSc 453: Intermediate Code Generation 16
Intermediate Code for a Function
Code generated for a function f:
begin with ‘enter f ’, where f is a pointer to the function’s
symbol table entry:
this allocates the function’s activation record;
activation record size obtained from f ’s symbol table information;
this is followed by code for the function body;
generated using codeGen_stmt(…) [to be discussed soon]
each return in the body (incl. any implicit return at the end of
the function body) are translated to the code
leave f /* clean up: f a pointer to the function’s symbol table entry */
return /* + associated return value, if any */
17. CSc 453: Intermediate Code Generation 17
Simple Expressions
Syntax tree node for expressions augmented with the
following fields:
type: the type of the expression (or “error”);
code: a list of intermediate code instructions for evaluating the expression.
place: the location where the value of the expression will be kept at runtime:
18. CSc 453: Intermediate Code Generation 18
Simple Expressions
Syntax tree node for expressions augmented with the
following fields:
type: the type of the expression (or “error”);
code: a list of intermediate code instructions for evaluating the expression.
place: the location where the value of the expression will be kept at runtime:
When generating intermediate code, this just refers to a symbol table entry for a
variable or temporary that will hold that value;
The variable/temporary is mapped to an actual memory location when going from
intermediate to final code.
19. CSc 453: Intermediate Code Generation 19
Simple Expressions 1
Syntax tree node E Action during intermediate code generation
codeGen_expr(E)
{ /* E.nodetype == INTCON; */
E.place = newtemp(E.type);
E.code = ‘E.place = intcon.val’;
}
codeGen_expr(E)
{ /* E.nodetype == ID; */
/* E.place is just the location of id (nothing more to do) */
E.code = NULL;
}
id
E
intcon
E
20. CSc 453: Intermediate Code Generation 20
Simple Expressions 2
Syntax tree node E Action during intermediate code generation
codeGen_expr(E)
{
/* E.nodetype == UNARY_MINUS */
codeGen_expr(E1); /* recursively traverse E1, generate code for it */
E.place = newtemp( E.type ); /* allocate space to hold E’s value */
E.code = E1.code newinstr(UMINUS, E1.place, NULL, E.place);
}
codeGen_expr(E)
{
/* E.nodetype == ‘+’ … other binary operators are similar */
codeGen_expr(E1);
codeGen_expr(E2); /* generate code for E1 and E2 */
E.place = newtemp( E.type ); /* allocate space to hold E’s value */
E.code = E1.code E2.code newinstr(PLUS, E1.place, E2.place, E.place );
}
–
E1
+
E1 E2
E
E
21. CSc 453: Intermediate Code Generation 21
Accessing Array Elements 1
Given:
an array A[lo…hi] that starts at address b;
suppose we want to access A[ i ].
We can use indexed addressing in the
intermediate code for this:
A[ i ] is the (i + lo)th array element starting from address b.
Code generated for A[ i ] is:
t1 = i + lo
t2 = A[ t1 ] /* A being treated as a 0-based array at this level. */
22. CSc 453: Intermediate Code Generation 22
Accessing Array Elements 2
In general, address computations can’t be
avoided, due to pointer and record types.
Accessing A[ i ] for an array A[lo…hi] starting at
address b, where each element is w bytes wide:
Address of A[ i ] is b + ( i – lo ) w
= (b – lo w) + i w
= kA + i w.
kA depends only on A, and is known at compile time.
Code generated:
t1 = i w
t2 = kA + t1 /* address of A[ i ] */
t3 = t2
23. CSc 453: Intermediate Code Generation 23
Accessing Structure Fields
Use the symbol table to store information about the
order and type of each field within the structure.
Hence determine the distance from the start of a struct to each field.
For code generation, add the displacement to the base address of the
structure to get the address of the field.
Example: Given
struct s { … } *p;
…
x = pa; /* a is at displacement a within struct s */
The generated code has the form:
t1 = p + a /* address of pa */
x = t1
25. CSc 453: Intermediate Code Generation 25
Logical Expressions 1
Syntax tree node:
Naïve but Simple Code (TRUE=1, FALSE=0):
t1 = { evaluate E1
t2 = { evaluate E2
t3 = 1 /* TRUE */
if ( t1 relop t2 ) goto L
t3 = 0 /* FALSE */
L: …
Disadvantage: lots of unnecessary memory references.
relop
E2
E1
26. CSc 453: Intermediate Code Generation 26
Logical Expressions 2
Observation: Logical expressions are used
mainly to direct flow of control.
Intuition: “tell” the logical expression where to
branch based on its truth value.
When generating code for B, use two inherited attributes,
trueDst and falseDst. Each is (a pointer to) a label
instruction.
E.g.: for a statement if ( B ) S1 else S2 :
B.trueDst = start of S1
B.falseDst = start of S2
The code generated for B jumps to the appropriate label.
31. CSc 453: Intermediate Code Generation 31
Loops 2
Code Structure:
goto Leval
Ltop :
code for S1
Leval: code to evaluate B
if ( B ) goto Ltop
Lafter:
This code executes fewer branch ops.
codeGen_stmt(S):
/* S.nodetype = ‘WHILE’ */
Ltop = newlabel();
Leval = newlabel();
Lafter = newlabel();
codeGen_bool(B, Ltop, Lafter);
codeGen_stmt(S1);
S.code =
newinstr(GOTO, Leval)
Ltop
S1.code
Leval
B.code
Lafter ;
while
B S1
S:
32. CSc 453: Intermediate Code Generation 32
Multi-way Branches: switch statements
Goal:
generate code to (efficiently) choose amongst a fixed set of alternatives
based on the value of an expression.
Implementation Choices:
linear search
best for a small number of case labels ( 3 or 4)
cost increases with no. of case labels; later cases more expensive.
binary search
best for a moderate number of case labels ( 4 – 8)
cost increases with no. of case labels.
jump tables
best for large no. of case labels ( 8)
may take a large amount of space if the labels are not well-clustered.
33. CSc 453: Intermediate Code Generation 33
Background: Jump Tables
A jump table is an array of code addresses:
Tbl[ i ] is the address of the code to execute if the expression evaluates
to i.
if the set of case labels have “holes”, the correspond jump table entries
point to the default case.
Bounds checks:
Before indexing into a jump table, we must check that the expression
value is within the proper bounds (if not, jump to the default case).
The check
lower_bound exp_value upper bound
can be implemented using a single unsigned comparison.
34. CSc 453: Intermediate Code Generation 34
Jump Tables: cont’d
Given a switch with max. and min. case labels cmax
and cmin, the jump table is accessed as follows:
Instruction
t0 value of expression
t0 = t0 – cmin
if (t0 u cmax – cmin) goto DefaultCase
t1 = JmpTbl_BaseAddr
t1 += 4*t0
jmp *t1
Cost (cycles)
…
1
4 to 6
1
1
3 to 5
: 10 to 14
35. CSc 453: Intermediate Code Generation 35
Jump Tables: Space Costs
A jump table with max. and min. case labels
cmax and cmin needs cmax – cmin entries.
This can be wasteful if the entries aren’t “dense enough”, e.g.:
switch (x) {
case 1: …
case 1000: …
case 1000000: …
}
Define the density of a set of case labels as
density = no. of case labels / (cmax – cmin )
Compilers will not generate a jump table if
density below some threshold (typically, 0.5).
36. CSc 453: Intermediate Code Generation 36
Switch Statements: Overall Algorithm
if no. of case labels is small ( ~ 8), use
linear or binary search.
use no. of case labels to decide between the two.
if density threshold (~ 0.5) :
generate a jump table;
else :
divide the set of case labels into sub-ranges s.t. each sub-range
has density threshold;
generate code to use binary search to choose amongst the sub-
ranges;
handle each sub-range recursively.
37. CSc 453: Intermediate Code Generation 37
Function Calls
Caller:
evaluate actual parameters, place them where the callee
expects them:
param x, k /* x is the kth actual parameter of the call */
save appropriate machine state (e.g., return address) and
transfer control to the callee:
call p
Callee:
allocate space for activation record, save callee-saved
registers as needed, update stack/frame pointers:
enter p
38. CSc 453: Intermediate Code Generation 38
Function Returns
Callee:
restore callee-saved registers; place return value (if any)
where caller can find it; update stack/frame pointers:
retval x;
leave p
transfer control back to caller:
return
Caller:
save value returned by callee (if any) into x:
retrieve x
39. CSc 453: Intermediate Code Generation 39
Function Call/Return: Example
Source: x = f(0, y+1) + 1;
Intermediate Code: Caller:
t1 = y+1
param t1, 2
param 0, 1
call f
retrieve t2
x = t2+1
Intermediate Code: Callee:
enter f /* set up activation record */
… /* code for f’s body */
retval t27 /* return the value of t27 */
leave f /* clean up activation record */
return
40. CSc 453: Intermediate Code Generation 40
Intermediate Code for Function Calls
non-void return type: codeGen_expr(E):
/* E.nodetype = FUNCALL */
codeGen_expr_list(arguments);
E.place = newtemp( f.returnType );
E.code = …code to evaluate the arguments…
param xk
…
param x1
call f, k
retrieve E.place;
Code Structure:
… evaluate actuals …
param xk
…
param x1
call f
retrieve t0 /* t0 a temporary var */
call
f (sym. tbl. ptr)
arguments
(list of expressions)
E
R-to-L
41. CSc 453: Intermediate Code Generation 41
Intermediate Code for Function Calls
void return type: codeGen_stmt(S):
/* S.nodetype = FUNCALL */
codeGen_expr_list(arguments);
E.place = newtemp( f.returnType );
S.code = …code to evaluate the arguments…
param xk
…
param x1
call f, k
retrieve E.place;
Code Structure:
… evaluate actuals …
param xk
…
param x1
call f
retrieve t0 /* t0 a temporary var */
call
f (sym. tbl. ptr)
arguments
(list of expressions)
S
R-to-L
void return type f has no return value
no need to allocate space for one, or
to retrieve any return value.
42. CSc 453: Intermediate Code Generation 42
Reusing Temporaries
Storage usage can be reduced considerably by
reusing space for temporaries:
For each type T, keep a “free list” of temporaries of type T;
newtemp(T) first checks the appropriate free list to see if it
can reuse any temps; allocates new storage if not.
putting temps on the free list:
distinguish between user variables (not freed) and compiler-
generated temps (freed);
free a temp after the point of its last use (i.e., when its value is no
longer needed).