Algorithm
Label (Expression Node)
1. Node is a left-most leaf: Label = 1
2. Node is a right-most leaf: Label = 0
3. (Otherwise)
3(a)Label (Left(Node)
3(b)Label (Right(Node)
3(c)Label# (Node) = Max(Left Label# , Right Label#)
or Left Label# + 1 if Left Label# = RightLabel#.
The algorithm is called with Label(root)Using the tree labelled as above, we can write an effiecient code generation algorithm:
Algorithm
GenerateCode (Node)
CASE Node is:
A leaf labeled 1 and a left leaf:
(a) R = GetReg
(b) Generate "Load Node, R"
Labeled with a number greater than available registers:
(a) Generate code for right child
(b) Store the result in a temp
(c) Generate code for the left child
(d) Apply node's operator to (a) and (c)
Has a right child that is a leaf:
(a) Evaluate the left child
(b) Apply node's operator to left child
result and leaf.
Otherwise:
(a) GenerateCode(Node with larger label). (Use either if
labels are the same) Leave result in a register
(b) GenerateCode (Other Node)
(c )Apply node's operation to registers holding
the two results.
Send questions and comments to: Karen Lemone