GATE / CS ARCHIVE

GATE CSE 2013 / QUESTION 48

Minimum register spills with code motion

Compiler Design · Code Generation & Register Allocation · Full GATE CSE 2013 paper

GATE 2013, Q48 2 marks · MCQ
Not in GATE 2027 syllabusReport issue

Code Generation & Register Allocation

Question 48, GATE 2013: Register-only processor allows at most 2 source operands and 1destination. Code: 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;}. All variables dead after segment. With only 2 registers and code motion as the only optimization, minimum spills to memory: A0, B1, C2, D3.
Question 48, GATE 2013: Register-only processor allows at most 2 source operands and 1destination. Code: 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;}. All variables dead after segment. With only 2 registers and code motion as the only optimization, minimum spills to memory: A0, B1, C2, D3.
Tap to enlarge
Your answer
Answer & solution

Official answer: B

One spill store suffices. With registers R1, R2, start with a in R1 and b in R2. Compute R2←R1+R2 (c), store c once in spill slot S, and compute R2←R2×R2 (x). Compare R2 with R1. On the true branch compute y as R1←R1×R1. On the false branch execute: load R2←S; R2←R2×R1 (d); R2←R2×R2 (d²); load R2←S; R2←R2+R1 (e); R2←R2×R2 (e²). The computations d=c*a and e=c+a have been sunk into the false branch, where they are used, and arranged just before their respective squarings. Their former values are unused on the true branch, and all variables are dead after the segment, so this code motion preserves the required values. It performs one spill store and two reloads on the false path; reloads are not additional spills to memory. For the lower bound, after forming c the independent live values a and c already occupy both registers. Before the branch can be decided, at least one of d=c*a, e=c+a or x=c*c must be computed. If d or e is first, its result is needed for its later square while both a and c remain necessary for the other operations. If x is first, x and a are needed for the test while c is still needed on the false path. Thus the first such result forces three simultaneously needed values in a no-spill schedule, regardless of permitted reordering. A live value must be saved. Since recomputation and dead-code elimination are not allowed, zero spills is impossible and the minimum is one, option B.

The spill count in this question counts stores of live register values to memory. It does not count initial operand loads or each subsequent reload as another spill. The construction saves c once, reuses its register for x, then reloads c separately for the two false-branch calculations. Its one-store bound and the three-live-values argument together establish an exact minimum, not just an example. If arbitrary recomputation or elimination of dead code were allowed, the optimization problem would change, which is why the stated restriction matters.

Original paper, page 11 · Answer key