Skip to content
Official PYQ · 2013

GATE CS 2013 Q49 — Local Optimization

Explain with AI

The following code segment is executed on a processor which allows only register operands in its instructions. Each instruction can have atmost two source operands and one destination operand. Assume that all variables are dead after this code segment.

c = a + b; 
d = c * a; 
e = c + a; 
x = c * c; 
if (x > a) { 
 y = a * a; 
} 
else { 
 d = d * d; 
 e = e * e; 
}

What is the minimum number of registers needed in the instruction set architecture of the processor to compile this code segment without any spill to memory? Do not apply any optimization other than optimizing register allocation.

Choose one option
View worked solution

Answer: B

To find the minimum number of registers required without any memory spill, we analyze the liveness of variables at each step of the code segment:

  1. Initially: aa and bb must be in registers. Let R1=aR_1 = a and R2=bR_2 = b.
  2. c = a + b;
    Since bb is dead after this instruction, we can reuse its register for cc.
    Live variables: a,ca, c  →  Register assignment: R1=aR_1 = a, R2=cR_2 = c.
  3. d = c * a;
    We need a new register for dd because dd is used later in the else block.
    Live variables: a,c,da, c, d  →  Register assignment: R1=aR_1 = a, R2=cR_2 = c, R3=dR_3 = d.
  4. e = c + a;
    We need a new register for ee because ee is used later in the else block.
    Live variables: a,c,d,ea, c, d, e  →  Register assignment: R1=aR_1 = a, R2=cR_2 = c, R3=dR_3 = d, R4=eR_4 = e.
  5. x = c * c;
    Since cc is dead after this instruction, we can reuse its register for xx.
    Live variables: a,d,e,xa, d, e, x  →  Register assignment: R1=aR_1 = a, R2=xR_2 = x, R3=dR_3 = d, R4=eR_4 = e.

At the point right before x = c * c, the four variables a,c,d,a, c, d, and ee are simultaneously live, which requires at least 4 registers. As shown in the step-by-step allocation, 4 registers are also sufficient to complete the execution of both branches without any spill.

Free practice · Your answers on this page are not saved.

Published
Report a correction
Keep exploringMore Local Optimization questions