Question

Consider the following C code segment:

a = b + c;
e = a + 1;
d = b + c;
f = d + 1;
g = e + f;

In a compiler, this code segment is represented internally as a directed acyclic graph (DAG). The number of nodes in the DAG is __________

Official answer and solution
Official answer
6
From
Official GATE 2021 answer key

Solution

Construct the Directed Acyclic Graph (DAG) for the basic block by reusing identical subexpression nodes.

Let us trace the DAG construction statement by statement:

  1. Initial leaves: Variables b and c are live upon entry. Create leaf node N1(b)N_1(\text{b}) and leaf node N2(c)N_2(\text{c}).
  2. Statement a = b + c: Create interior operator node N3(+)N_3(+) with left child N1N_1 and right child N2N_2. Attach label a to N3N_3.
  3. Create constant leaf node N4(1)N_4(1).
  4. Statement e = a + 1: Create interior operator node N5(+)N_5(+) with left child N3N_3 and right child N4N_4. Attach label e to N5N_5.
  1. Statement d = b + c: The subexpression b + c already corresponds to existing node N3N_3. Attach label d to N3N_3 without creating a new node.
  2. Statement f = d + 1: Since d refers to N3N_3, d + 1 is N3+N4N_3 + N_4, which already corresponds to node N5N_5. Attach label f to N5N_5 without creating a new node.
  3. Statement g = e + f: Both e and f refer to node N5N_5. Create interior operator node N6(+)N_6(+) with left child N5N_5 and right child N5N_5. Attach label g to N6N_6.

Count total nodes in the DAG:

  • Leaf nodes: N1(b),N2(c),N4(1)N_1(\text{b}), N_2(\text{c}), N_4(1) (3 leaf nodes)
  • Operator nodes: N3(+),N5(+),N6(+)N_3(+), N_5(+), N_6(+) (3 interior nodes)
    Total number of nodes =3+3=6= 3 + 3 = 6.
Final answer

6

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 (CS, Set-1)
Question
60 of 65, printed as CS Q.50
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.