Compiler Construction, Past Papers, UOS Main Campus

Compiler Construction Past Paper 2015 – MSc IT 4th Term UOS (IT-696)

ProgramMSc IT
Term4th
Year2015
Course codeIT-696
AnswersSolved ✓

University of Sargodha M.Sc. IT 4th term Compiler Construction (IT-696) paper, 2015 exam (80 marks, 2:30 hours). The paper is retyped below, followed by solved answers for all 16 short questions and all five long questions: the structure of a compiler, parse trees, the lexical analysis phase, three-address code, and step-by-step optimization of the given code.

Solved answers

Q1 – Short answers (16 × 2)

1. When do we use a cross compiler? When the program must run on a machine different from the one used for compiling, e.g. writing software for embedded systems, mobile phones or microcontrollers that cannot run a compiler themselves, or building a compiler for a new machine (bootstrapping).

2. Benefit of the syntax tree in the analysis–synthesis model. The syntax tree is the link between analysis and synthesis: it shows the hierarchical structure of the program with operators as interior nodes, so semantic checks and code generation can be done by simply walking the tree, independent of the source text.

3. Properties of intermediate code. It should be easy to produce from the source, easy to translate into target code, machine independent, and suitable for optimization (e.g. three-address code with temporaries).

4. Phases of a compiler in sequence. Lexical analysis → Syntax analysis → Semantic analysis → Intermediate code generation → Code optimization → Code generation (with the symbol table and error handler used by all).

5. Semantic analysis. The phase that checks the meaning of the program using the syntax tree and symbol table: type checking, matching of operands with operators, declared-before-use, correct number of function arguments, and inserting type conversions.

6. Top-down parsing vs predictive parsing. Top-down parsing builds the parse tree from the root and may need backtracking (recursive descent with backtracking). Predictive parsing is a special top-down parser that never backtracks: one lookahead symbol selects the production (LL(1) grammars only).

7. NFA vs DFA. In a DFA each state has exactly one move for each input symbol and no ε-moves; an NFA can have several moves for the same symbol and ε-moves. Example for (a|b)*ab: NFA – state 0 loops on a,b and goes to 1 on a, 1 goes to 2 on b (3 states). DFA – A (a→B, b→A), B (a→B, b→C), C (a→B, b→A), accepting C.

8. Compiler vs interpreter. A compiler translates the whole program into target code once, then the code runs fast and errors are reported together. An interpreter translates and executes the program statement by statement; it is slower but easier for debugging (e.g. Python).

9. Lexeme vs pattern. A pattern is the rule that describes the form of a token (e.g. letter (letter|digit)* for identifiers). A lexeme is the actual character sequence in the source that matches it, e.g. count or x1.

10. Function of static checkers. Static checking is done at compile time without running the program: type checks, flow-of-control checks (break outside a loop), uniqueness checks (a variable declared twice) and name-related checks.

11. Dead code elimination. Removing statements that compute values never used, or that can never execute, e.g. if (false) {…} or an assignment to a variable that is overwritten before use.

12. Left recursion. A grammar is left recursive if a non-terminal A derives a string beginning with A (A ⇒+ Aα), e.g. E → E + T | T. Top-down parsers loop forever on it, so it is removed: E → T E′, E′ → + T E′ | ε.

13. Lexical analysis vs parsing. Lexical analysis works on characters and produces tokens using regular expressions/finite automata; parsing works on tokens and checks the grammatical structure using a context-free grammar, producing a parse tree.

14. Transition diagram. A flowchart-like graph of states and edges labelled with characters, used to recognise tokens; it has a start state and accepting states (often with * for retracting one character). E.g. the diagram for relational operators <, <=, <>, =, >, >=.

15. Syntax directed translation. Attaching attributes to grammar symbols and semantic rules/actions to productions, so the translation (e.g. code or a value) is computed while parsing, e.g. E → E1 + T { E.val = E1.val + T.val }.

16. Why the symbol table? It stores each identifier with its type, scope, size and memory location, so that all phases can look up names quickly, check declarations and types, and generate correct addresses.

Q2 – Structure of a compiler with diagram

A compiler translates a program in a source language into an equivalent program in a target language and reports errors. It works in two parts: the analysis (front end) breaks the source into pieces, checks it and builds an intermediate representation; the synthesis (back end) builds the target program from that representation.

 source program
      |
 [ Lexical analyzer ]        -> tokens
      |
 [ Syntax analyzer ]         -> parse / syntax tree
      |
 [ Semantic analyzer ]       -> annotated tree (type checked)
      |
 [ Intermediate code gen ]   -> three-address code
      |
 [ Code optimizer ]          -> improved intermediate code
      |
 [ Code generator ]          -> target (machine / assembly) code

 Symbol table manager and error handler are used by all phases.
 Front end (analysis) = first 4 phases; back end (synthesis) = last 2.
  • Lexical analysis (scanning): groups characters into lexemes and produces tokens such as <id,1> <=> <id,2> <+> <num,60>; removes blanks and comments.
  • Syntax analysis (parsing): checks the token stream against the grammar and builds a parse tree / syntax tree.
  • Semantic analysis: type checking, declarations before use, type conversions (e.g. inttofloat).
  • Intermediate code generation: machine-independent code such as three-address code.
  • Code optimization: makes the intermediate code faster/smaller (constant folding, common subexpressions, dead code removal).
  • Code generation: chooses instructions and registers for the target machine.
  • Symbol table: stores each identifier with its type, scope and location; error handler reports and recovers from errors in every phase.

Example: position = initial + rate * 60 → tokens <id,1> = <id,2> + <id,3> * <60> → t1 = inttofloat(60); t2 = id3 * t1; t3 = id2 + t2; id1 = t3 → optimized: t1 = id3 * 60.0; id1 = id2 + t1 → target: LDF R2, id3 / MULF R2, R2, #60.0 / LDF R1, id2 / ADDF R1, R1, R2 / STF id1, R1.

Q3 – Parse tree with examples

A parse tree shows how the start symbol of a grammar derives a string. Properties: the root is the start symbol, every leaf is a terminal (or ε), every interior node is a non-terminal, and if A has children X1 … Xn then A → X1 … Xn is a production. Reading the leaves from left to right gives the yield (the input string).

Example 1 – grammar E → E + T | T, T → T * F | F, F → id. Parse tree for id + id * id:

          E
        / | \
       E  +  T
       |   / | \
       T  T  *  F
       |  |     |
       F  F     id
       |  |
       id id

The tree shows that * binds tighter than + because it is lower in the tree.

Example 2 – ambiguity: with E → E + E | E * E | id the same string has two parse trees, one grouping (id + id) * id and one grouping id + (id * id). A grammar with two parse trees for one string is ambiguous; this is why the first grammar uses levels E, T, F.

Example 3 – leftmost derivation for 9 − 5 + 2 with list → list + digit | list − digit | digit: list ⇒ list + digit ⇒ list − digit + digit ⇒ digit − digit + digit ⇒ 9 − 5 + 2; the parse tree is left-branching, which shows left associativity.

Q4 – Lexical analysis phase

The lexical analyzer (scanner) is the first phase. It reads the input characters, groups them into lexemes and produces a sequence of tokens <token-name, attribute> for the parser.

  • Interaction with the parser: the parser calls getNextToken(); the scanner returns the next token.
  • Tokens, patterns, lexemes: token id, pattern letter(letter|digit)*, lexeme rate; token number, pattern digit+(.digit+)?, lexeme 60.
  • Other jobs: removing comments and white space, counting line numbers for error messages, entering identifiers in the symbol table, expanding macros in some compilers.
  • Input buffering: two buffer halves with sentinels and two pointers (lexemeBegin, forward) so characters are read in blocks.
  • Specification and recognition: tokens are specified with regular expressions and recognised with transition diagrams / finite automata (tools such as Lex/Flex generate the scanner).
  • Error handling: panic mode – delete characters until a valid token can be formed; or insert/replace/transpose one character.

Example: position = initial + rate * 60 → <id,1> <=> <id,2> <+> <id,3> <*> <number,60>.

Q5 – Three-address code

Three-address code (TAC) is an intermediate representation in which each instruction has at most three addresses (two operands and a result) and at most one operator on the right side. Complex expressions are broken up using compiler-generated temporaries.

FormInstruction
Assignment (binary)x = y op z
Assignment (unary)x = op y (minus, not, inttofloat)
Copyx = y
Unconditional jumpgoto L
Conditional jumpif x relop y goto L / ifFalse x goto L
Procedure callparam x1 … param xn; call p, n; return y
Indexedx = y[i]; x[i] = y
Address/pointerx = &y; x = *y; *x = y

Example: a = b * −c + b * −c → t1 = minus c; t2 = b * t1; t3 = minus c; t4 = b * t3; t5 = t2 + t4; a = t5.

Example with control flow: while (i < 10) i = i + 1; → L1: if i < 10 goto L2; goto L3; L2: t1 = i + 1; i = t1; goto L1; L3: …

Implementations: quadruples (op, arg1, arg2, result), triples (op, arg1, arg2, results referenced by position) and indirect triples (list of pointers to triples, easy to reorder during optimization).

Q6 – Optimize the code

x = 1
y = a * b + 3
z = a * b + x + z + 2
x = 3
  • Constant propagation: x is 1 when z is computed, so x in the third statement is replaced by 1.
  • Common subexpression elimination: a * b is computed twice; compute it once in t.
  • Constant folding: t + 1 + z + 2 = t + z + 3 (integers, + is associative and commutative).
  • Dead code elimination: after propagation, the value 1 stored in x is never used (x is overwritten by x = 3), so x = 1 is removed.
t = a * b
y = t + 3
z = t + z + 3
x = 3

The block now has one multiplication instead of two and one addition fewer, and the useless store to x is gone.

Save this paper for offline studyDownload the question paper, or save the paper together with all solved answers as a PDF.
↓ Download Paper (JPG)

About Saif R

An educator and technology enthusiast passionate about empowering students through quality education and digital learning. Dedicated to making academic resources and opportunities accessible to everyone.