Consider the following 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 . The number of nodes in the is _____________
View worked solution
Answer: 6 : 6
To find the number of nodes in the Directed Acyclic Graph (DAG) for the given basic block, we construct the DAG step-by-step by identifying common subexpressions and reusing existing nodes.
a = b + c:- Create leaf nodes for variables
bandc. - Create an operator node
+with childrenbandc. Label this node witha. - Nodes created:
{b, c, +a}(3 nodes)
- Create leaf nodes for variables
e = a + 1:- Create a leaf node for constant
1. - Create an operator node
+with children+aand1. Label this node withe. - Nodes created:
{1, +e}(2 new nodes, total 5)
- Create a leaf node for constant
d = b + c:- The expression
b + cis already represented by the node+a. - We simply add the label
dto this existing node. - Nodes created: 0 (total 5)
- The expression
f = d + 1:- Since
dandarefer to the same node,d + 1is equivalent toa + 1, which is already represented by the node+e. - We add the label
fto the node+e. - Nodes created: 0 (total 5)
- Since
g = e + f:- Create an operator node
+where both the left and right children point to the node labelede, f. Label this node withg. - Nodes created:
{+g}(1 new node, total 6)
- Create an operator node
The final DAG consists of the following 6 nodes:
- Leaf node
b - Leaf node
c - Operator node
+(labeleda, d) - Leaf node
1 - Operator node
+(labelede, f) - Operator node
+(labeledg)
Free practice · Your answers on this page are not saved.
