Content deleted Content added
No edit summary |
Algebraist (talk | contribs) m hyphens to endashs, per WP:DASH |
||
Line 1:
When [[Code generation|generating code]] for arithmetic expressions, the [[compiler]] has to decide which is the best way to translate the expression in terms of number of instructions used as well as number of registers needed to evaluate a certain subtree (especially if free registers are scarce). The '''
==Simple
The '''simple
# Traverse the [[abstract syntax tree]] in pre- or postorder
## For every non-constant leaf node, assign a 1 (i.e. 1 register is needed to hold the variable/field/etc.). For every constant leaf node (RHS of an operation
## For every non-leaf node ''n'', assign the number of registers needed to evaluate the respective subtrees of ''n''. If the number of registers needed in the left subtree (''l'') are not equal to the number of registers needed in the right subtree (''r''), the number of registers needed for the current node ''n'' is max(l, r). If ''l == r'', then the number of registers needed for the current node is l + 1.
# Code emission
Line 48:
From this tree it can be seen that we need 2 registers to compute the left subtree of the '*', but only 1 register to compute the right subtree.The reason of 'c' and 'g' do not need register is:If T is a tree leaf, then the number of registers to evaluate T is either 1 or 0 depending whether T is a left or a right subtree(since an operation such as add R1, A can handle the right component A directly without storing it into a register). Therefore we shall start to emit code for the left subtree first, because we might run into the situation that we only have 2 registers left to compute the whole expression. If we now computed the right subtree first (which needs only 1 register), we would then need a register to hold the result of the right subtree while computing the left subtree (which would still need 2 registers), therefore needing 3 registers concurrently. Computing the left subtree first needs 2 registers, but the result can be stored in 1, and since the right subtree needs only 1 register to compute, the evaluation of the expression can do with only 2 registers left.
==Advanced
In an advanced version of the '''
==External links==
*[http://portal.acm.org/citation.cfm?doid=321607.321620 The Generation of Optimal Code for Arithmetic Expressions] [[Ravi Sethi]], [[Jeffrey D. Ullman|J. D. Ullman]], Journal of the [[Association for Computing Machinery|ACM]], Vol. 17, No. 4, October 1970, pp.
*[http://lambda.uta.edu/cse5317/fall02/notes/node40.html Code Generation for Trees]
|