CS-603-C AD-604-C SD-603-C
+1 moreCD-801
Compiler Design

Compiler Design Important Questions

RGPV · B.Tech · CSE · Semester 6 · Current scheme · 14 papers (2020 to 2026)

  1. Read the answers

    Start with the topics that come every year.

  2. Revise unit notes

    Go through each unit once to score more.

Paperwala Imp Topics - Compiler Design important questions

Download Paperwala Imp Question & Answer (PDF)

Counted from the questions in the past papers listed on this site. Repeated = how many times the topic came in those papers.

Compiler Design important questions with answers

Each answer starts with the short answer. Then come the points to write, a diagram and an exam tip. The questions under each topic are copied from the RGPV papers.

Q1. Code optimization: sources of optimization, function preserving transformations, common subexpression, copy propagation, dead code

Asked 15 times in 2013, 2014, 2016, 2017, 2018, 2019, 2020, 2022, 2023, 2024, 2025, 2026 · Unit 5

From the papers

  • “Explain the common sub expression elimination, copy propagation, and transformation for moving loop invariant computations in detail.” (Dec 2017, Dec 2024)
  • “Explain the concept of dead code elimination.” (Nov 2019, Dec 2020)
  • “Explain the following with example: i) Strength reduction ii) Variable propagation iii) Common sub expression elimination” (Dec 2014, Dec 2020)
  • “Discuss various sources of optimization in basic blocks and analyse their impact with examples.” (May 2026)

The short answer

Code optimization changes the intermediate code so the program runs faster or uses less memory, without changing what it computes. The main sources of optimization are common subexpression elimination, copy propagation, dead code elimination and constant folding. These are called function preserving transformations.

Write these points

Criteria for a code improving transformation

  • It must keep the meaning of the program exactly the same.
  • It must speed up the program by a measurable amount on average.
  • It must be worth the effort it takes inside the compiler.

Function preserving transformations

TransformationWhat it doesBefore → after
Common subexpression eliminationReuses a value already computedd = b * c + e → d = a + e
Copy propagationAfter f = a, uses a in place of fg = f + 2 → g = a + 2
Dead code eliminationRemoves code whose result is never usedf = a (f unused) → removed
Constant foldingWorks out constant expressions at compile timeh = 3 * 4 → h = 12

Areas of optimization

  • Local: inside one basic block.
  • Global: across basic blocks, using data flow analysis.
  • Loop: code motion, strength reduction, induction variables (see the loop answer).
  • Peephole: a small window over the target code.

Optimizing a block of five statements.

Before: a = b * c; d = b * c + e; f = a; g = f + 2; h = 3 * 4.

Common subexpression: b * c is already in a, so d = a + e.

Copy propagation: g = a + 2. Now f is never used, so f = a is dead and removed.

Constant folding: h = 12. After: a = b * c; d = a + e; g = a + 2; h = 12. Two multiplications are saved.

Real-life example

A shopkeeper who has already added up a customer's bill does not add it again when the customer asks for the total a second time. He reuses the first answer. Common subexpression elimination does the same with computed values.

Figure: where the optimizer sits
Figure: where the optimizer sits

Same or opposite: local and global optimization

PointLocalGlobalSame or opposite
ScopeOne basic blockWhole flow graphOpposite
Needs data flow analysisNoYesOpposite
Keeps program meaningYesYesSame
ExampleCSE inside a blockCSE across blocksOpposite

Exam tip. Give the three criteria, then the four transformation table with a before and after for each. One small block worked through earns full marks.

Back to the topic list

Q2. DAG for a basic block: construction, algorithm and uses

Asked 15 times in 2014, 2015, 2016, 2017, 2018, 2019, 2020, 2022, 2023, 2024, 2025, 2026 · Unit 4

From the papers

  • “Construct DAG for the basic blocks: D := B*C; E := A+B; B := B+C; A := E-D” (Dec 2016, Dec 2017, Nov 2018, May 2023, May 2024)
  • “Construct DAG for the following expression.” (Dec 2014, Nov 2019, Dec 2020)
  • “Construct a DAG for the given expressions and optimize the code.” (May 2026)
  • “Explain DAG Representation of Basic Blocks and Peephole Optimization.” (Jun 2026)

The short answer

A DAG (directed acyclic graph) for a basic block has a leaf for each starting value of a variable or constant and an interior node for each operator. A value computed twice is one node with two parents, so the DAG shows common subexpressions directly.

Write these points

Algorithm to construct a DAG

  1. For each statement x = y op z, find the node for y and for z. If none exists, make a leaf.
  2. Look for an existing node with label op whose children are those two nodes. If found, reuse it.
  3. Otherwise make a new node op with those children.
  4. Attach x to that node and remove x from any older node.

Applications of a DAG

  • Finds common subexpressions automatically.
  • Shows which names are used inside the block but set outside it.
  • Shows which values computed in the block are used outside it.
  • Helps remove dead code and reorder code for fewer registers.

DAG for D := B*C; E := A+B; B := B+C; A := E−D (May 2023).

D := B*C: node n1 = * (B0, C0), label D.

E := A+B: node n2 = + (A0, B0), label E.

B := B+C: node n3 = + (B0, C0), label B. It is a new node, because + is a different operator from *.

A := E−D: node n4 = − (n2, n1), label A. No subexpression repeats here, so the block keeps 4 operations.

DAG for a = (a*b+c) − (a*b+c) (May 2024).

n1 = * (a, b). n2 = + (n1, c).

The second (a*b+c) finds n1 and n2 again, so no new nodes.

n3 = − (n2, n2), label a.

Code from the DAG: t1 = a * b; t2 = t1 + c; a = t2 − t2. Five operations become three.

Real-life example

A family tree where a grandparent appears once with lines to every grandchild is cleaner than writing the grandparent's name again under each child. A DAG keeps one node for a shared value in the same way.

Figure: DAG with the common subexpression (b − c)
Figure: DAG with the common subexpression (b − c)

Same or opposite: syntax tree and DAG

PointSyntax treeDAGSame or opposite
Repeated subexpressionDrawn againShared nodeOpposite
Nodes are operators and operandsYesYesSame
Node can have two parentsNoYesOpposite
Main useParsing outputOptimizing a blockOpposite

Exam tip. Write the four step algorithm, then draw the DAG and mark the shared node. Finish by writing the optimized code from the DAG.

Back to the topic list

Q3. Syntax directed definitions: synthesized and inherited attributes, S-attributed and L-attributed, SDT for infix to postfix

Asked 15 times in 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020, 2023, 2024, 2025, 2026 · Unit 2

From the papers

  • “Write the differences between synthesized attributes and inherited attributes.” (Nov 2019, Dec 2024, Jun 2025)
  • “Assuming suitable syntax directed definition, construct a syntax tree for the expression a - 4 + c.” (Dec 2013, Dec 2017)
  • “Compare S-attributed and L-attributed Syntax Directed Definitions with examples.” (May 2026)
  • “Explain Syntax Directed Definitions and Top-Down Translation.” (Jun 2026)

The short answer

A syntax directed definition (SDD) is a grammar with attributes attached to symbols and semantic rules attached to productions. A synthesized attribute gets its value from the node's children. An inherited attribute gets its value from the parent or siblings. A syntax directed translation scheme (SDT) puts the actions inside the right side of productions, so the order of execution is fixed.

Write these points

Synthesized and inherited attributes

PointSynthesizedInherited
Value comes fromChildrenParent and left siblings
Flow in the treeUpwardDownward or sideways
ExampleE.val = E1.val + T.valL.type = T.type in int a, b

S-attributed and L-attributed definitions

  • S-attributed: uses only synthesized attributes. It is evaluated bottom up, during LR parsing.
  • L-attributed: an inherited attribute may use only the parent and siblings to its left. It is evaluated in one depth first, left to right pass.
  • Every S-attributed definition is also L-attributed.

Terms

  • Annotated parse tree: a parse tree showing the value of each attribute.
  • Dependency graph: an edge from each attribute to the attributes that need it. Its topological order is a valid evaluation order.

SDT that converts infix to postfix

  • E → E + T { print('+') }
  • E → E − T { print('−') }
  • E → T
  • T → 0 | 1 | ... | 9 { print(digit) }
  • Input 9 − 5 + 2 prints 9 5 − 2 +.

E.value for the December 2024 grammar.

Rules: E → E1 # T { E.value = E1.value * T.value }, T → T1 & F { T.value = T1.value + F.value }, F → num.

So # means multiply and & means add. & sits lower in the grammar, so it is done first.

For 2 # 3 & 4: T.value = 3 + 4 = 7, then E.value = 2 * 7 = 14.

For 3 & 2 # 4 & 1: (3 + 2) * (4 + 1) = 5 * 5 = 25 at the root.

Real-life example

In a school, each class teacher adds up the marks of their own students and passes the total up to the principal. That is a synthesized attribute. The principal sends the exam date down to every class. That is an inherited attribute.

Figure: annotated parse tree for 3 * 5 + 4
Figure: annotated parse tree for 3 * 5 + 4

Same or opposite: S-attributed and L-attributed definitions

PointS-attributedL-attributedSame or opposite
Attributes usedSynthesized onlySynthesized and restricted inheritedOpposite
EvaluationBottom upDepth first, left to rightOpposite
Has semantic rulesYesYesSame
FitsLR parserLL parserOpposite

Exam tip. Define both attribute kinds with one example each. Draw the annotated parse tree. For SDT questions, write the rules and trace one input.

Back to the topic list

Q4. Phases of a compiler with an example; analysis-synthesis model

Asked 14 times in 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020, 2022, 2023, 2024, 2025, 2026 · Unit 1

From the papers

  • “Explain the various phases of a compiler with a neat diagram.” (Dec 2015, Dec 2020, May 2022, Jun 2025)
  • “Describe the synthesis-analysis model of compiler?” (Dec 2013, Dec 2020)
  • “Explain how the Analysis-Synthesis model of compilation processes the expression y = a * x + b through each compiler phase.” (May 2026)
  • “Show the output generated by each phase for the given expression.” (Jun 2025)

The short answer

A compiler works in two parts. The analysis part (front end) breaks the source into pieces and builds a meaning of it. The synthesis part (back end) builds the target program from that meaning. There are six phases: lexical analysis, syntax analysis, semantic analysis, intermediate code generation, code optimization and code generation. A symbol table and an error handler serve all of them.

Write these points

What each phase does

PhaseInputOutput
Lexical analysisCharactersTokens
Syntax analysisTokensParse tree or syntax tree
Semantic analysisSyntax treeType checked tree
Intermediate code generationChecked treeThree address code
Code optimizationThree address codeBetter three address code
Code generationOptimized codeMachine or assembly code

Helpers used by every phase

  • Symbol table: names, types, scope and addresses of identifiers.
  • Error handler: reports an error and lets the compiler continue.
  • Phases are grouped into passes. One pass reads the input once and may do several phases.
  • Lexical, syntax and semantic analysis form the analysis part; the rest form the synthesis part.

a = (b + c) * (b + c) * 2 through the phases (May 2024).

Lexical: id1 = ( id2 + id3 ) * ( id2 + id3 ) * 2.

Intermediate code: t1 = b + c; t2 = b + c; t3 = t1 * t2; t4 = t3 * 2; a = t4.

Optimized: t1 = b + c; t2 = t1 * t1; a = t2 * 2.

Target code: MOV b, R0; ADD c, R0; MUL R0, R0; MUL #2, R0; MOV R0, a.

Real-life example

Translating a Hindi letter into English goes in steps too. First you read the words, then check the grammar of each sentence, then the meaning. Next you write a rough English draft, polish it and write the final copy. A compiler follows the same steps.

Figure: the phases of a compiler for position = initial + rate * 60
Figure: the phases of a compiler for position = initial + rate * 60

Same or opposite: analysis and synthesis parts

PointAnalysis (front end)Synthesis (back end)Same or opposite
PhasesLexical, syntax, semanticOptimization, code generationOpposite
Depends onSource languageTarget machineOpposite
Uses the symbol tableYesYesSame
OutputIntermediate codeTarget codeOpposite

Exam tip. Draw the six phase diagram with the symbol table and error handler at the side. Then take the statement from the question through every phase.

Back to the topic list

Q5. Three address code, quadruples, triples and intermediate code generation

Asked 14 times in 2013, 2014, 2015, 2016, 2017, 2018, 2020, 2022, 2023, 2024, 2026 · Unit 4

From the papers

  • “Generate the three address code for the following code segment: While (a < c and b < d) do If a = 1 then c = c + 1 Else While (a <= 0) do ...” (Jun 2020, Dec 2024)
  • “Write Three Address Code for the following code fragment: ... while (i <= n) ...” (May 2026)
  • “Explain Intermediate Code Generation for declarations, procedure calls, and case statements.” (Jun 2026)
  • “Write the three address code sequence for the assignment statement.” (May 2024)

The short answer

Three address code (TAC) is an intermediate code in which each statement has at most one operator on the right side, such as x = y op z. It is stored as quadruples (op, arg1, arg2, result), triples (op, arg1, arg2, using statement numbers for results) or indirect triples (a list of pointers to triples).

Write these points

Forms of three address statements

  • Assignment: x = y op z, x = op y, x = y.
  • Jumps: goto L, if x relop y goto L.
  • Procedure calls: param x, call p, n.
  • Indexed and pointer: x = y[i], x = *p.

Benefits of intermediate code

  • A new target machine needs only a new back end.
  • Machine independent optimization can run on it.
  • It is simpler to generate than machine code.

Quadruples, triples and indirect triples

PointQuadruplesTriplesIndirect triples
Result fieldYes, a temporary nameNo, the statement numberNo
Moving statementsEasyHard, numbers changeEasy, move pointers
SpaceMostLeastMiddle

Quadruples are preferred in an optimizing compiler because statements can be moved without renumbering every reference.

(a + b) * (c + d) − (a + b + c) (December 2014).

TAC: t1 = a + b; t2 = c + d; t3 = t1 * t2; t4 = t1 + c; t5 = t3 − t4.

Quadruples: (+, a, b, t1), (+, c, d, t2), (*, t1, t2, t3), (+, t1, c, t4), (−, t3, t4, t5).

Triples: (0) + a b; (1) + c d; (2) * (0) (1); (3) + (0) c; (4) − (2) (3).

a + b is computed once and reused, because a + b + c means (a + b) + c.

TAC for while (a < c and b < d) do if a = 1 then c = c + 1 else while (a <= d) do a = a + 3.

100: if a < c goto 102. 101: goto 114. 102: if b < d goto 104. 103: goto 114.

104: if a = 1 goto 106. 105: goto 109. 106: t1 = c + 1. 107: c = t1. 108: goto 100.

109: if a <= d goto 111. 110: goto 100. 111: t2 = a + 3. 112: a = t2. 113: goto 109.

114: next statement. The inner loop body a = a + 3 is the usual textbook form; the paper's own body goes in its place.

Real-life example

A recipe that says "mix flour and water, then knead, then add salt" gives one action per line. Three address code gives the computer one operation per line in the same way.

Figure: ways to store three address code
Figure: ways to store three address code

Same or opposite: quadruples and triples

PointQuadruplesTriplesSame or opposite
FieldsFourThreeOpposite
Represent three address codeYesYesSame
Temporaries namedYesNoOpposite
Easy to reorderYesNoOpposite

Exam tip. Write the TAC first, then the quadruple table and the triple table under it. Say in one line why quadruples suit optimizers.

Back to the topic list

Q6. Lexical analysis: role, input buffering, tokens, patterns and lexemes, recognition of tokens

Asked 12 times in 2013, 2014, 2016, 2017, 2019, 2020, 2022, 2024, 2025, 2026 · Unit 1

From the papers

  • “Explain in detail: Input Buffering” (Dec 2013, Jun 2025)
  • “Explain Input Buffering and Token Recognition in Lexical Analysis.” (Jun 2026)
  • “Discuss the functionality of pre-processing and Input buffering.” (Jun 2025)
  • “Explain how identifiers and key words are recognized by a lexical analysis with an example.” (Jun 2025)

The short answer

The lexical analyzer is the first phase. It reads the source characters, groups them into lexemes and gives the parser one token at a time. A pattern is the rule that describes the lexemes of a token. Input buffering with two halves and sentinels lets it read fast.

Write these points

Role of the lexical analyzer

  • Groups characters into tokens and passes them to the parser on request.
  • Removes white space and comments.
  • Enters identifiers into the symbol table.
  • Keeps line numbers for error messages.
  • Reports lexical errors such as an illegal character.

Token, pattern and lexeme

TokenPatternSample lexeme
idletter followed by letters or digitsmax, rate
numone or more digits10, 60
relop< or <= or = or <> or > or >=<=
ifthe characters i fif

Why lexical analysis is separate from parsing

  • Simpler design: the parser does not deal with spaces and comments.
  • Speed: special buffering for reading characters.
  • Portability: input quirks stay in one place.

Recognition of tokens

Tokens are specified by regular expressions and recognized by transition diagrams (finite automata). Keywords are first read as identifiers, then looked up in a keyword table.

Tokens in int max = a + 10;.

Lexemes: int, max, =, a, +, 10, ;

Tokens: keyword int, id, assign, id, plus, num, semicolon.

That is 7 tokens. max and a go into the symbol table.

If the line were int max = a @ 10; the lexical analyzer would report @ as an illegal character.

Real-life example

When you read a sentence, your eyes first group letters into words before you think about grammar. The lexical analyzer is the compiler's eye that turns letters into words.

Figure: input buffering with sentinels
Figure: input buffering with sentinels

Same or opposite: token and lexeme

PointTokenLexemeSame or opposite
What it isA categoryThe actual charactersOpposite
ExampleidmaxOpposite
Used by the parserYesThrough its tokenOpposite
Linked to a patternYesYesSame

Exam tip. List the roles, then the token, pattern, lexeme table. Draw the two half buffer for input buffering questions and say what a sentinel saves.

Back to the topic list

Q7. LR parsers: SLR, CLR and LALR parsing tables

Asked 12 times in 2013, 2015, 2017, 2018, 2020, 2022, 2023, 2024, 2025, 2026 · Unit 2

From the papers

  • “Consider the following grammar. Construct the SLR Parsing table for this grammar.” (Nov 2018, Dec 2020, Dec 2024)
  • “Construct a LALR parsing table for the given grammar.” (Jun 2020, Jun 2025)
  • “Compute LR(0) items for the following grammar and construct SLR Parser table: S -> L = R | R” (May 2023, May 2024)
  • “Prove that Grammar is CLR but not LALR: S -> Aa / bAc / Bc / bBa” (Dec 2017, Jun 2020)

The short answer

LR parsers are bottom up parsers that read input Left to right and build a Rightmost derivation in reverse. SLR uses LR(0) items and FOLLOW sets. Canonical LR (CLR) uses LR(1) items with a lookahead symbol. LALR merges CLR states with the same core, so it has as few states as SLR but almost the power of CLR.

Write these points

Steps to build an SLR table

  1. Add S' → S to the grammar.
  2. Build the LR(0) item sets with closure and goto.
  3. For A → α . a β in state i with goto to j: action[i, a] = shift j.
  4. For A → α . in state i: action[i, a] = reduce for every a in FOLLOW(A).
  5. For S' → S . : action = accept. Goto entries come from goto on non-terminals.

SLR, CLR and LALR compared

PointSLRCLRLALR
ItemsLR(0)LR(1)LR(1) merged
Reduce onFOLLOW setExact lookaheadMerged lookahead
StatesFewManySame as SLR
PowerLeastMostMiddle
Used byTeachingRarelyYACC

Merits and demerits of LR parsers

  • Merits: handle almost all programming language grammars, find errors early, no backtracking.
  • Demerit: tables are too big to build by hand; tools such as YACC are needed.

S → L = R | R, L → * R | id, R → L (May 2023).

Items: I0 = {S' → .S, S → .L=R, S → .R, L → .*R, L → .id, R → .L}. I2 = {S → L.=R, R → L.}.

FOLLOW(R) = {=, $}, because R → L passes FOLLOW(L) and L appears before = in S → L = R.

In I2 on '=': shift (S → L.=R) and reduce R → L both apply. This is a shift reduce conflict, so the grammar is not SLR(1).

In CLR and LALR the item R → L. in I2 has lookahead $ only, so on '=' the parser only shifts. The grammar is LALR(1).

Real-life example

SLR is like a guard who stops everyone wearing a red shirt because some thieves wore red. CLR checks each person's exact ticket. LALR groups tickets of the same type to save time but still checks enough to be right almost always.

Figure: building an LR parsing table
Figure: building an LR parsing table

Same or opposite: SLR and LALR

PointSLRLALRSame or opposite
Lookahead sourceFOLLOW setLR(1) items mergedOpposite
Number of statesSameSameSame
ConflictsMoreFewerOpposite
ToolBy handYACCOpposite

Exam tip. Write the item sets neatly, compute FOLLOW, then fill the table. If a cell has two entries, say it is a conflict and name its type.

Back to the topic list

Q8. Peephole optimization

Asked 12 times in 2013, 2015, 2016, 2017, 2018, 2020, 2023, 2024, 2025, 2026 · Unit 4

From the papers

  • “Write brief notes: Peephole Optimization” (Dec 2016, Dec 2017, Jun 2020, May 2024)
  • “Explain in detail: Peephole optimization” (Dec 2015, May 2024, Jun 2025)
  • “Describe Peephole optimization briefly.” (Dec 2013, Dec 2020)
  • “Explain different peephole optimization strategies and evaluate their role in improving code efficiency.” (May 2026)

The short answer

Peephole optimization looks at a small window (the peephole) of a few target instructions and replaces it with a shorter or faster sequence. It is applied again and again, because one change can open the way for another.

Write these points

Peephole optimization strategies

StrategyBeforeAfter
Redundant load and storeMOV R0, a; MOV a, R0MOV R0, a
Unreachable codegoto L2; x = 1 (no label)goto L2
Flow of controlgoto L1 ... L1: goto L2goto L2
Algebraic simplificationx = x + 0; x = x * 1removed
Strength reductionx = y * 2x = y + y
Machine idiomsi = i + 1INC i

Features

  • Works on target code or intermediate code.
  • Needs no global analysis, so it is fast.
  • The window can slide over the whole program in one pass.
  • Repeated passes give the best result.

Improving five instructions.

Code: MOV b, R0; ADD c, R0; MOV R0, a; MOV a, R0; MUL #1, R0.

MOV a, R0 right after MOV R0, a is a redundant load. Remove it.

MUL #1, R0 multiplies by one. Remove it.

Result: MOV b, R0; ADD c, R0; MOV R0, a. Five instructions become three.

Real-life example

A teacher checking an answer sheet with a small magnifying glass fixes small mistakes line by line, without reading the whole book again. A peephole optimizer polishes code the same way.

Figure: peephole pass
Figure: peephole pass

Same or opposite: peephole optimization and global optimization

PointPeepholeGlobalSame or opposite
WindowA few instructionsWhole flow graphOpposite
Needs data flow analysisNoYesOpposite
Improves the codeYesYesSame
Speed of compilerFastSlowerOpposite

Exam tip. Define the peephole, then make the six row table with a before and after for each. One worked window ends the answer well.

Back to the topic list

Q9. Left recursion, left factoring, FIRST and FOLLOW, LL(1) grammar and predictive parsing

Asked 12 times in 2014, 2016, 2017, 2019, 2020, 2022, 2024, 2025, 2026 · Unit 2

From the papers

  • “Why is it necessary to eliminate left recursion in top down parsing? Consider predictive parsing table for the grammar.” (Nov 2019, Dec 2020)
  • “Check whether the given grammar is LL(1) or not.” (Dec 2014, Dec 2020)
  • “Explain Context-Free Grammar (CFG) and grammar transformations for Predictive Parsing.” (Jun 2026)
  • “Construct the predictive parser for the following grammar.” (Jun 2025)

The short answer

A grammar is LL(1) when a top down parser can always choose the right production by looking at one input symbol. To get there we remove ambiguity, eliminate left recursion and apply left factoring, then build the predictive parsing table from FIRST and FOLLOW sets.

Write these points

Left recursion and left factoring

  • Left recursion A → A α | β makes a top down parser loop forever. Replace it with A → β A', A' → α A' | ε.
  • Left factoring A → α β1 | α β2 is rewritten as A → α A', A' → β1 | β2, so the choice waits until the common part is read.
  • Ambiguity: a grammar is ambiguous if one string has two parse trees, such as E → E + E | E * E | id for id + id * id.

Rules for FIRST and FOLLOW

  • FIRST(a) = {a} for a terminal. If X → ε, ε is in FIRST(X).
  • FOLLOW(start) contains $.
  • For A → α B β: FIRST(β) without ε goes into FOLLOW(B).
  • If β can be ε, FOLLOW(A) goes into FOLLOW(B).

Conditions for LL(1)

  • For A → α | β: FIRST(α) and FIRST(β) share no symbol.
  • If β can derive ε, FIRST(α) and FOLLOW(A) share no symbol.
  • Equivalently, no cell of the predictive table has two entries.

E → E + T | T, T → T * F | F, F → (E) | id.

Remove left recursion: E → T E', E' → + T E' | ε, T → F T', T' → * F T' | ε, F → (E) | id.

FIRST(E) = FIRST(T) = FIRST(F) = {(, id}. FIRST(E') = {+, ε}. FIRST(T') = {*, ε}.

FOLLOW(E) = FOLLOW(E') = {), $}. FOLLOW(T) = FOLLOW(T') = {+, ), $}. FOLLOW(F) = {*, +, ), $}.

Table: E' on + is E' → +TE', on ) and $ is E' → ε. T' on * is T' → *FT', on +, ), $ is T' → ε. No cell has two entries, so the grammar is LL(1).

Real-life example

At a railway junction a signalman looks at just the next train's board to decide the track. If two tracks could fit the same board, he would get stuck. An LL(1) grammar makes sure one look is always enough.

Figure: making a grammar LL(1)
Figure: making a grammar LL(1)

Same or opposite: left recursion and left factoring

PointLeft recursionLeft factoringSame or opposite
ProblemParser loops foreverParser cannot chooseOpposite
Fixed by rewriting the grammarYesYesSame
New symbol A'YesYesSame
Form fixedA → A αA → α β1 or α β2Opposite

Exam tip. Remove left recursion first, then write FIRST and FOLLOW in a small table, then the parsing table. End with one line on whether any cell has two entries.

Back to the topic list

Q10. Code generator: design issues, register allocation and assignment, code generation algorithm

Asked 12 times in 2013, 2014, 2015, 2016, 2018, 2020, 2023, 2024, 2025, 2026 · Unit 4

From the papers

  • “Explain different issues in the design of code generator.” (Dec 2013, Dec 2014, Dec 2016, Nov 2018, Dec 2020, Jun 2020)
  • “Explain register allocation and assignment in compiler design with examples.” (May 2024, May 2026)
  • “Explain Flow Graph Construction, Register Allocation, and Register Assignment.” (Jun 2026)
  • “Discuss about the register allocation and assignment with examples.” (Jun 2025)

The short answer

The code generator turns optimized intermediate code into target code. Its main design issues are the input, the target program, memory management, instruction selection, register allocation and the evaluation order. Good register use matters most, because registers are much faster than memory.

Write these points

Issues in the design of a code generator

IssueWhat must be decided
InputForm of intermediate code; assumed free of errors
Target programAbsolute, relocatable or assembly code
Memory managementMapping names to addresses using the symbol table
Instruction selectionWhich machine instructions; e.g. INC for x = x + 1
Register allocationWhich values stay in registers
Evaluation orderOrder of computing, which changes registers needed

Register allocation and assignment

  • Allocation: choose which variables live in registers at each point.
  • Assignment: choose the exact register for each one.
  • Keep often used values and loop variables in registers.
  • Graph colouring: variables alive together get different colours (registers).

Simple code generation algorithm

  • For x = y op z: get a register L for the result.
  • If y is not already in L, load it: MOV y, L.
  • Emit OP z, L.
  • Update the register and address descriptors to show x is now in L.

X = (A − B) + (A − C) + (A − C) (December 2013).

TAC: t1 = A − B; t2 = A − C; t3 = t1 + t2; t4 = t3 + t2; X = t4.

MOV A, R0; SUB B, R0 (R0 = A − B). MOV A, R1; SUB C, R1 (R1 = A − C).

ADD R1, R0; ADD R1, R0 (R1 is reused, so A − C is not computed again).

MOV R0, X. Total 7 instructions with 2 registers.

Real-life example

A cook keeps salt, oil and chilli on the counter, while rare spices stay in the store room. Fetching from the store room is slow. Register allocation keeps the most used values on the counter.

Figure: issues in code generator design
Figure: issues in code generator design

Same or opposite: register allocation and register assignment

PointAllocationAssignmentSame or opposite
DecidesWhich values get registersWhich register each getsOpposite
Aims to cut memory accessYesYesSame
OrderFirstSecondOpposite
ToolLive variable analysisGraph colouringOpposite

Exam tip. Make the six issue table, then two lines on register allocation. Generate code for the given statement and count instructions.

Back to the topic list

Q11. Storage allocation strategies: static, stack, heap and dynamic allocation

Asked 11 times in 2013, 2015, 2016, 2018, 2019, 2020, 2023, 2024, 2025, 2026 · Unit 3

From the papers

  • “Describe about various storage allocation strategies.” (Dec 2015, May 2024, Jun 2025)
  • “Explain different dynamic allocation strategies.” (Dec 2013, Dec 2020, May 2024)
  • “Differentiate stack allocation from heap allocation with reference to activation records and dynamic memory.” (May 2026)
  • “Explain Parameter Passing Methods and Dynamic Storage Allocation.” (Jun 2026)

The short answer

Storage allocation decides where data lives while a program runs. Static allocation fixes addresses at compile time. Stack allocation pushes an activation record for each call and pops it on return. Heap allocation gives and takes back memory in any order, as needed by new and malloc.

Write these points

The three strategies

PointStaticStackHeap
When fixedCompile timeAt each callAny time at run time
RecursionNot allowedAllowedAllowed
Size knownAt compile timeAt call timeAny size
FreedNeverOn returnExplicitly or by garbage collection
ExampleGlobal variables, FORTRANLocal variables in Cmalloc, new

Merits and demerits

  • Static: fast, simple, but no recursion and no dynamic data.
  • Stack: supports recursion, automatic freeing, but data dies on return.
  • Heap: flexible lifetime, but slower and can cause fragmentation and memory leaks.

Dynamic storage allocation in the heap

  • First fit, best fit and worst fit choose a free block.
  • Freed blocks are joined with free neighbours (coalescing).
  • Garbage collection finds blocks no longer reachable.

fact(3) with stack allocation.

main calls fact(3): the record for fact(3) is pushed with n = 3.

fact(3) calls fact(2), which calls fact(1). Now 4 records are on the stack.

fact(1) returns 1 and its record is popped. fact(2) returns 2, fact(3) returns 6.

Static allocation could not do this, because each call needs its own n at the same time.

Real-life example

A hostel gives some students fixed rooms for the whole year (static). Guests get a room for one night and leave in order (stack). The library lends books to anyone at any time and takes them back whenever they return (heap).

Figure: run time memory and activation records
Figure: run time memory and activation records

Same or opposite: stack allocation and heap allocation

PointStackHeapSame or opposite
Order of freeingLast in, first outAny orderOpposite
Done at run timeYesYesSame
SpeedFastSlowerOpposite
ProblemStack overflowFragmentation, leaksOpposite

Exam tip. Draw the run time memory picture first. Then give the three column table with merits and demerits. A recursion example shows why the stack is needed.

Back to the topic list

Q12. Loop optimization: code motion, induction variables, strength reduction, loop unrolling

Asked 11 times in 2013, 2014, 2015, 2016, 2018, 2019, 2020, 2022, 2024, 2025 · Unit 5

From the papers

  • “Give a detailed note on loop optimization techniques.” (Jun 2025)
  • “What is loop optimization?” (Dec 2015)
  • “What are induction variables? How does the strength reduction on induction variable help in improving loop optimization? Illustrate with an example.” (Dec 2015)
  • “Explain loop optimization with example. Define the following: i) Dominators ii) Natural loops iii) Inner loop iv) Preheader” (Dec 2014)

The short answer

Loop optimization improves the code inside loops, where a program spends most of its time. The main techniques are code motion (moving loop invariant code out), induction variable elimination, strength reduction, loop unrolling and loop jamming.

Write these points

Techniques

TechniqueWhat it does
Code motionMoves a computation whose value does not change into the preheader
Induction variable eliminationKeeps one of several variables that change in step
Strength reductionReplaces a costly operation by a cheaper one, such as * by +
Loop unrollingRepeats the body to cut the number of tests and jumps
Loop jamming (fusion)Joins two loops over the same range into one

Terms used with loops in flow graphs

  • Dominator: d dominates n if every path from the start to n goes through d.
  • Back edge: an edge n → d where d dominates n.
  • Natural loop: d plus all nodes that can reach n without going through d.
  • Inner loop: a loop that contains no other loop.
  • Preheader: a new block placed just before the loop header to hold moved code.

Code motion and strength reduction.

Before: i = 0; L: if i >= n goto exit; x = y + z; t = 4 * i; a[t] = x; i = i + 1; goto L.

y and z do not change in the loop, so x = y + z moves to the preheader.

t = 4 * i grows by 4 each time i grows by 1, so set t = 0 before the loop and use t = t + 4 inside.

For n = 100 this saves 100 multiplications and 99 additions of y + z.

Real-life example

If you buy a metro card once instead of a token at every trip, you save time on every journey. Code motion does that for a loop: work that gives the same answer is done once, before the loop starts.

Figure: a loop flow graph with a preheader and back edge
Figure: a loop flow graph with a preheader and back edge

Same or opposite: code motion and strength reduction

PointCode motionStrength reductionSame or opposite
ChangesWhere code runsWhich operation is usedOpposite
Applied inside loopsYesYesSame
Examplex = y + z moved out4 * i to t + 4Opposite
NeedsLoop invariant testInduction variableOpposite

Exam tip. Make the technique table, then define dominator, natural loop and preheader. Show one loop before and after. Then count what was saved.

Back to the topic list

Q13. Compiler basics: types of compilers, front end and back end, compiler and interpreter, bootstrapping, cross compiler

Asked 10 times in 2013, 2015, 2016, 2018, 2020, 2022, 2024, 2025, 2026 · Unit 1

From the papers

  • “Illustrate the bootstrapping process of a compiler and analyse its advantages in compiler design.” (May 2026)
  • “Explain the types of Compilers. Differentiate between the Front-end and Back-end of a compiler.” (Jun 2026)
  • “List and explain the advantages and disadvantages of frontend and backend model of compiler.” (Jun 2025)
  • “What is a translator? Compare compiler and interpreter in terms of translation method, memory requirement and ...” (Dec 2024)

The short answer

A translator turns a program in one language into another. A compiler translates the whole program into target code before it runs. An interpreter runs it statement by statement. The front end depends on the source language. The back end depends on the target machine. Bootstrapping uses a compiler to compile itself. A cross compiler runs on one machine but makes code for another.

Write these points

Compiler and interpreter

PointCompilerInterpreter
TranslationWhole program at onceOne statement at a time
MemoryMore, makes object codeLess, no object code
Speed of runningFastSlow
ErrorsShown after compilingShown line by line
ExampleC, C++Python, BASIC

Types of compilers

  • Single pass and multipass.
  • Cross compiler.
  • Source to source compiler.
  • Just in time (JIT) compiler.
  • Incremental compiler.

Front end and back end

  • Front end: lexical, syntax and semantic analysis, intermediate code.
  • Back end: optimization and code generation.
  • Advantages: reuse one front end with many back ends; machine independent optimization on intermediate code.
  • Disadvantage: the extra intermediate step can make the compiler slightly slower.

Bootstrapping

  1. Write a small compiler for a subset of language C in assembly language.
  2. Write the full C compiler in that subset.
  3. Compile it with the small compiler. Now the full compiler runs on the machine.
  4. From then on the compiler can compile its own new versions.

A multipass compiler needs less memory per pass and can optimize better than a single pass compiler.

Why split the compiler.

Suppose 3 languages (C, Java, Pascal) must run on 4 machines.

Without a split: 3 × 4 = 12 complete compilers.

With front ends and back ends meeting at one intermediate code: 3 + 4 = 7 parts.

A fifth machine then needs only 1 new back end, not 3 new compilers.

Real-life example

A compiler is like a translator who translates a whole book before it is printed. An interpreter is like a live translator at a speech who speaks each sentence as soon as it is said.

Figure: front ends and back ends sharing one intermediate code
Figure: front ends and back ends sharing one intermediate code

Same or opposite: compiler and cross compiler

PointCompilerCross compilerSame or opposite
Runs onMachine AMachine ASame
Makes code forMachine AMachine BOpposite
Translates a whole programYesYesSame
Examplegcc on a laptopCompiling for an ArduinoOpposite

Exam tip. Start with the compiler and interpreter table. Draw the front end and back end picture, then write the bootstrapping steps.

Back to the topic list

Q14. Symbol table: entries, organisation, data structures and management

Asked 9 times in 2014, 2015, 2016, 2017, 2018, 2020, 2024, 2026 · Unit 3

From the papers

  • “Explain the symbol table management system.” (Nov 2018, Dec 2020)
  • “Explain the organization and role of the Symbol Table.” (Jun 2026)
  • “What are the features and capabilities of the symbol table?” (Jun 2020)
  • “What are the typical entries in a symbol table, what are the various data structures used to implement the table?” (Jun 2020)

The short answer

A symbol table is the data structure where a compiler stores every identifier with its attributes, such as type, scope, size and address. Every phase uses it. It must support fast insert and lookup.

Write these points

Typical entries

  • Name of the identifier.
  • Type (int, float, array, function).
  • Size and memory address (offset).
  • Scope or block level.
  • For functions: number and types of parameters, return type.

Data structures used

StructureLookup timeNote
Linear listO(n)Simple, slow for many names
Binary search treeO(log n) on averageKept in sorted order
Hash tableO(1) on averageMost used; collisions handled by chaining

Management

  • Insert when a declaration is seen.
  • Lookup at each use, to check type and scope.
  • For block structured languages, keep one table per scope or a scope number with each entry.
  • Delete or hide entries when a block ends.

Hash table with chaining, h(name) = sum of ASCII codes mod 7.

a = 97, so h = 97 mod 7 = 6. b = 98, so h = 0. c = 99, so h = 1.

ab = 97 + 98 = 195, so h = 195 mod 7 = 6. This collides with a.

Chaining: bucket 6 holds a list a → ab.

Looking up ab checks bucket 6, then at most 2 entries, instead of all 4 names.

Real-life example

A school register lists every student with roll number, class and address. Teachers look up a name whenever they need details. A symbol table is the compiler's register of names.

Figure: what a symbol table stores
Figure: what a symbol table stores

Same or opposite: hash table and binary search tree for a symbol table

PointHash tableBinary search treeSame or opposite
Average lookupO(1)O(log n)Opposite
Stores names with attributesYesYesSame
Sorted outputNoYesOpposite
Worst caseO(n) with bad hashingO(n) if unbalancedSame

Exam tip. List the entries, then the three data structure table. A small hashing example with a collision shows you understand it.

Back to the topic list

Q15. LEX and compiler construction tools

Asked 9 times in 2014, 2015, 2017, 2020, 2023, 2024, 2025 · Unit 1

From the papers

  • “Explain the various Compiler Construction Tools.” (Dec 2014, May 2024)
  • “What do you mean by LEX? Explain in detail.” (Dec 2020, Jun 2020)
  • “What are the various components of lexical specification file? Illustrate with an example.” (Dec 2015, Dec 2020)
  • “Write a simple Lex program to recognize identifiers.” (Jun 2025)

The short answer

LEX is a tool that generates a lexical analyzer from a list of patterns (regular expressions) and actions. It turns a lex.l file into a C program lex.yy.c with a function yylex(). Compiler construction tools like LEX and YACC build parts of a compiler automatically.

Write these points

Structure of a LEX specification file

  1. Definitions: C declarations in %{ %} and named patterns (auxiliary definitions), such as digit [0-9].
  2. %% then translation rules: pattern { action }.
  3. %% then user subroutines: C functions such as main().

How LEX is used

  • lex lex.l makes lex.yy.c.
  • cc lex.yy.c makes a.out, the scanner.
  • a.out reads input and runs the action of the longest matching pattern.
  • If two patterns match the same length, the one listed first wins.

Compiler construction tools

ToolBuilds
Scanner generator (LEX)Lexical analyzer
Parser generator (YACC)Syntax analyzer
Syntax directed translation engineIntermediate code from the parse tree
Automatic code generatorTarget code from rules
Data flow analysis engineInformation for optimization
Compiler construction toolkitA set of the above

LEX program to print identifiers with line numbers.

%option yylineno and %{ int n = 0; %} in the definitions part.

Rule 1: int|float|if|while { printf("keyword %s\n", yytext); }

Rule 2: [a-zA-Z_][a-zA-Z0-9_]* { n++; printf("%s at line %d\n", yytext, yylineno); }. Rule 3: .|\n ;

Input int x = y1 + 2; prints keyword int, then x at line 1 and y1 at line 1. n = 2.

Real-life example

A mobile app builder lets you drag buttons and set what each does, then it writes the app code for you. LEX does the same for a scanner: you give patterns and actions, it writes the C code.

Figure: building a scanner with LEX
Figure: building a scanner with LEX

Same or opposite: LEX and YACC

PointLEXYACCSame or opposite
BuildsLexical analyzerParserOpposite
InputRegular expressionsGrammar rulesOpposite
Generates C codeYesYesSame
Main functionyylex()yyparse()Opposite

Exam tip. Show the three part file layout, then a small working program. For tools questions, list the six tools in a table.

Back to the topic list

How we picked these questions

RGPV teaches Compiler Design to 4 branches under one syllabus. Each branch prints its own code on the paper, but the units are the same. So one page and one PDF serve all of them.

We counted every question in the Compiler Design papers on this site by topic, from 2013 to 2026. A topic that keeps coming back is a topic RGPV likes, so it sits higher in the table. One branch alone has only a few papers. Counting them together gives a surer list.

Compiler Design important questions by branch

CS-603-C Compiler Design important questions for CSE, Semester 6

CS-603-C follows the same RGPV syllabus as the other codes on this page. The 15 topics and answers above are the CS-603-C important questions too.

See all 14 CS-603-C previous year papers

AD-604-C Compiler Design important questions for AI & Data Science, Semester 6

AD-604-C follows the same RGPV syllabus as the other codes on this page. The 15 topics and answers above are the AD-604-C important questions too.

See all 1 AD-604-C previous year paper

SD-603-C Compiler Design important questions, Semester 6

SD-603-C follows the same RGPV syllabus as the other codes on this page. The 15 topics and answers above are the SD-603-C important questions too.

See all 2 SD-603-C previous year papers

CD-801 Compiler Design important questions for CSE-DS, Semester 8

CD-801 follows the same RGPV syllabus as the other codes on this page. The 15 topics and answers above are the CD-801 important questions too.

See all 2 CD-801 previous year papers

About Compiler Design

Compiler Design (CS-603 C) shows how a program in a language like C is turned into machine code. It is an elective in Semester 6 of RGPV B.Tech CSE with five units that follow the compiler's phases: lexical analysis, parsing, type checking and runtime, code generation, and optimisation. Trace each phase on one small program.

Compiler Design unit-wise brief

Unit 1: Introduction and lexical analysis

This unit introduces the compiler, its types, the analysis-synthesis model and its phases, then lexical analysis: input buffering, specifying and recognising tokens, and building a lexical analyser with LEX. Name the phases in order and what each produces.

Unit 2: Syntax analysis and syntax directed translation

Here you learn parsing: top down parsing, recursive descent, predictive parsing, bottom up parsing, operator precedence and the LR family (SLR, LALR and LR). Then syntax directed definitions with S-attributed and L-attributed forms. Build a parsing table for a small grammar.

Unit 3: Type checking and runtime environment

The unit covers type systems, type checking and conversion, overloading and polymorphic functions, and the runtime environment: storage organisation and allocation, parameter passing, the symbol table, and error detection and recovery. Compare the parameter passing methods with a short example.

Unit 4: Intermediate code and code generation

This unit covers intermediate code for declarations, assignments, Boolean expressions and case statements, backpatching, and procedure calls. It then covers code generator design, basic blocks and flow graphs, register allocation, DAG representation, peephole optimisation and generating code from a DAG. Draw the DAG of a basic block.

Unit 5: Code optimisation

The last unit covers sources of optimisation, optimising basic blocks and loops, dead code elimination, global data flow analysis, code improving transformations, and debugging optimised code. Apply three optimisations by hand to a short loop.

Units follow the RGPV scheme and syllabus, B.Tech Computer Science and Engineering, Semester 6 (AICTE flexible curriculum, w.e.f. Jan 2020). For the full topic list of each unit, open the Compiler Design notes.

Start with the latest papers

Compiler Design - Jun 2026

Compiler Design - Dec 2024

Compiler Design - May 2024

See all 14 papers →

Compiler Design (CS-603-C) FAQs

What are the most important topics in Compiler Design?

By how often they were asked in the papers on this site: Code optimization: sources of optimization, function preserving transformations, common subexpression, copy propagation, dead code (15 times); DAG for a basic block: construction, algorithm and uses (15 times); Syntax directed definitions: synthesized and inherited attributes, S-attributed and L-attributed, SDT for infix to postfix (15 times); Phases of a compiler with an example; analysis-synthesis model (14 times); Three address code, quadruples, triples and intermediate code generation (14 times).

How were these Compiler Design important questions chosen?

Each topic was counted from the questions in the past papers listed on this site (2013-2026). Repeated is the number of times the topic came. The counts come from keyword matching and the answers are not teacher-reviewed, so use them together with your syllabus.

Is there a PDF of Compiler Design important questions with answers?

Yes. The Paperwala Imp Question & Answer PDF for Compiler Design is free to download from this page.

The 15 most repeated topics of Compiler Design (CS-603-C) for RGPV B.Tech CSE semester 6, counted from the previous year papers on this site. The same syllabus is taught under 4 codes: CS-603-C, AD-604-C, SD-603-C, CD-801. Compiler Design is also searched for as AL-703-A, IO-702-B, IS-702-B and CS-7002.

Also known as AL-703-A, IO-702-B, IS-702-B, CS-7002