Consider the following code segment:
z=x + 3 + y->f1 + y->f2;
for (i = 0; i < 200; i = i + 2)
{
if (z > i)
{
p = p + x + 3;
q = q + y->f1;
} else
{
p = p + y->f2;
q = q + x + 3;
}
}
Assume that the variable points to a (allocated on the heap) containing two fields and , and the local variables and are allotted registers. Common sub-expression elimination optimization is applied on the code. The number of addition and the dereference operations (of the form or ) in the optimized code, respectively, are:
View worked solution
Answer: D
To optimize the code using Common Sub-expression Elimination (CSE), we identify expressions that are computed multiple times without their operands being modified:
x + 3is computed in the initialization ofzand inside both branches of theif-elsestatement. Sincexis not modified, we can compute it once:t1 = x + 3.- The dereferences
y->f1andy->f2are accessed in the initialization ofzand inside the loop. Sinceyand its fields are not modified, they can be evaluated once and stored in registers:t2 = y->f1andt3 = y->f2.
The optimized code becomes:
t1 = x + 3; // 1 addition, 0 dereferences
t2 = y->f1; // 0 additions, 1 dereference
t3 = y->f2; // 0 additions, 1 dereference
z = t1 + t2 + t3; // 2 additions
for (i = 0; i < 200; i = i + 2) { // 1 addition per iteration (i = i + 2)
if (z > i) {
p = p + t1; // 1 addition
q = q + t2; // 1 addition
} else {
p = p + t3; // 1 addition
q = q + t1; // 1 addition
}
}
Now, let us count the operations:
- Dereference Operations:
- Only dereferences are performed outside the loop (one for
y->f1and one fory->f2).
- Only dereferences are performed outside the loop (one for
- Addition Operations:
- Outside the loop: (for
t1) + (forz) = additions. - Inside the loop: The loop runs for , which is exactly iterations.
- In each iteration, the increment
i = i + 2takes addition. - Regardless of the branch taken in the
if-elseblock, exactly additions are executed. - Additions per iteration = additions.
- In each iteration, the increment
- Total additions: additions.
- Outside the loop: (for
Thus, the number of additions is and the number of dereferences is .
Free practice · Your answers on this page are not saved.
