Skip to content
Official PYQ · 2013

GATE CS 2013 Q48 — Runtime Environments

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; 
} 

Q.48 Suppose the instruction set architecture of the processor has only two registers. The only allowed compiler optimization is code motion, which moves statements from one place to another while preserving correctness. What is the minimum number of spills to memory in the compiled code?

Choose one option
View worked solution

Answer: B

Using the only allowed optimization, code motion, we can move the computations of d and e into the else block because they are only used there and their operands a and c are not modified before the branch. This minimizes their live ranges.

The optimized code becomes:

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

Let us allocate the two available registers, R1R_1 and R2R_2:

  1. Load aa into R1R_1 and bb into R2R_2.
  2. Compute c=a+bc = a + b and store it in R2R_2 (since bb is now dead). Currently: R1=aR_1 = a, R2=cR_2 = c.
  3. To evaluate the condition x > a, both xx and aa must reside in registers. Thus, we must compute x=c∗cx = c * c and store xx in R2R_2.
  4. Since cc is still needed in the else block, we must spill cc to memory before overwriting R2R_2. This counts as 1 spill.
  5. Now, R1=aR_1 = a and R2=xR_2 = x. We perform the comparison x > a.
  6. If the else branch is taken, we reload cc from memory into R2R_2 (as xx is now dead) and complete the remaining calculations without any further spills.

Thus, the minimum number of spills to memory is 1.

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

Published
Report a correction
Keep exploringMore Runtime Environments questions