11,966 views
21 21 votes

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.

  1. 3
  2. 4
  3. 5
  4. 6

3 Answers

Best answer
31 31 votes

Here, we are told not to do code motion. So, we start with 3 registers

c = a + b; //a, c in register
d = c * a; //a, c, d in register
e = c + a; //a, c, e in register, d spilled. 

So, now we try with 4 registers

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

No spilling. So, 4 is the minimum number of registers needed for avoiding spilling. (If code motion was allowed, we need only 3 registers for avoiding spilling).

• selected by
8 8 votes

BOLD lines describe Live variable just before entering the next statement 


{ a,b }
c = a + b;
{ a,c }
d = c * a;
{ a,c,d }
e = c + a;
{ a,c,d,e }
x = c * c;
{ a,d,x,e }
if (x > a)
Either IF condition passes
{ a }
{ y = a * a; }
or when IF condition fails
{ d,e }
else 
{d = d * d;
e = e * e; }

So as we can see that at max only 4 variables are live, therefore we need 4 registers to avoid register spilling.

@ sir, is this method correct?

Because everyone draws a graph and then finds its chromatic number, i don’t understand why do we need a graph?

For example, https://gateoverflow.in/78311/how-to-draw-register-allocation-interference-graph

• edited by
Answer:
Position:
Show:

Related questions

0 0 votes
1 1 answer
1.8k
1.8k views
Tridhara Chakrabarti asked Jan 23, 2017
1,831 views
Please can anyone list the topics to study in this part. The syllabus only states basics of code generation and optimization. Anyone who had prepared gate earlier. What d...
1 1 vote
1 answers 1 answer
14.5k
14.5k views
LavTheRawkstar asked Nov 10, 2016
14,548 views
What is the difference between Cross Compiler and Bootstrapping ?
0 0 votes
2 2 answers
4.8k
4.8k views
LavTheRawkstar asked Nov 8, 2016
4,823 views
Please explain what is Global Data Flow Analyis in Code optimization ?