Common data questions

Common Data for Questions 48 and 49:
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;
}

Shared with question 49.

Question

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
Official answer and solution
Official answer
B
From
Official GATE 2013 answer key

Solution

Apply code motion to move computations of variables that are only used conditionally into their respective branches and determine the minimum memory spills with two registers.

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

Notice that the variables d and e are only used inside the else branch. Since code motion is permitted, we can defer the computations of d and e until inside the else block:

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

Let us evaluate register requirements with 2 registers R1,R2R_1, R_2:

  1. To compute c = a + b, registers hold aa and bb, computing c.
  2. To compute x = c * c, registers hold cc, producing x.
  3. In the condition if (x > a), we compare x and a. Both xx and aa must be in registers.
  4. But notice: for the else branch, variable cc must be preserved across the comparison to compute d = c * a and e = c + a! At the point of x > a, the variables needed subsequently in the else branch are aa and cc, plus xx is needed for the test. This requires 3 active values (x,a,cx, a, c), while only 2 registers are available.
  5. Therefore, at least one value (specifically cc) must be spilled to memory before the branch and reloaded in the else branch.

Thus, the minimum number of spills to memory is 1, which corresponds to option (B).

Final answer

B

The answer is the one in the official GATE answer key. The solution is this site's own explanation.

Source

Paper
GATE 2013 Computer Science and Information Technology (CS)
Question
48 of 65, printed as CS Q.48
Section
Computer Science and Information Technology

Report an error in this question

GATE questions are the work of the organising institutes. This site is independent and is not affiliated with them.