Question
Consider the following ANSI C 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 y points to a struct (allocated on the heap) containing two fields f1 and f2, and the local variables x, y, z, p, q, and i are allotted registers. Common sub-expression elimination (CSE) optimization is applied on the code. The number of addition and dereference operations (of the form y->f1 or y->f2) in the optimized code, respectively, are:
Official answer and solution
- Official answer
- D
- From
- Official GATE 2021 answer key
Solution
Apply common subexpression elimination (CSE) to hoist loop-invariant expressions and reuse precomputed results, then count total additions and pointer dereferences.
Variables x, y, z, p, q, and i are in registers. The pointer y is not modified inside the loop, nor is x. Therefore, the expressions , , and are loop-invariant common subexpressions.
Before the loop, the compiler precomputes these subexpressions into registers:
- (1 addition)
- (1 dereference)
- (1 dereference)
- (2 additions)
Operations executed before the loop:
The loop header is for (i = 0; i < 200; i = i + 2). It executes for , which is exactly iterations.
In each iteration, the loop increment i = i + 2 performs 1 addition:
Inside each iteration of the loop, exactly one branch of the if-else is executed:
- If : (1 addition) and (1 addition), totaling 2 additions.
- Else: (1 addition) and (1 addition), totaling 2 additions.
No dereferences occur inside the loop because the precomputed register values and are used directly.
Summing all operations:
This matches option D (303 and 2).
D
The answer is the one in the official GATE answer key. The solution is this site's own explanation.
Source
- Paper
- GATE 2021 Computer Science and Information Technology - Session 2 (CS2)
- Question
- 40 of 65, printed as CS Q.30
- 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.