The grand plan for code-generation is
independent of any particular machine;
it depends largely on a set of tables.
But this fact does not necessarily make it very easy
to modify the compiler to produce code for other machines,
both because there is a good deal of machine-dependent structure
in the tables, and because in any event such tables are non-trivial to
The arguments to the basic code generation routine
are a pointer to a tree representing an expression,
the name of a code-generation table,
and the number of a register in which the value of the
expression should be placed.
returns the number of the register in which the value actually
instruction if the value really needs to be in the given register.
There are four code generation tables.
is the basic one, which actually does the job described
compile code which places the value represented by the expression
is used when the value of the expression is not actually needed,
but instead the value of the condition codes resulting from
evaluation of the expression.
This table is used, for example, to evaluate the expression after
calculate the value (0 or 1) of the expression
`a==b' in the context `if (a==b) ... '
table is used when the value of an expression is to be pushed on the stack,
for example when it is an actual argument.
For example in the function call `f(a)' it is a bad idea to
into a register which is then pushed on the stack,
when there is a single instruction which does the job.
table is used when an expression is to be evaluated for its side effects,
This occurs mostly for expressions which are statements, which have no
Thus the code for the statement
need produce only the approoriate
instruction, and need not leave the value of
while in the expression `a + (b = c)'
the value of `b = c' will appear in a register.
All of the tables besides
are rather small, and handle only a relatively few special cases.
If one of these subsidiary tables does not contain
an entry applicable to the given expression tree,
to put the value of the expression into a register
and then fixes things up;
nothing need be done when the table
instruction is produced when the table called for was
pushing the register on the stack,
routine itself picks off some special
tries to find an entry applicable
to the given tree in the given table, and returns \-1 if
no such entry is found, letting
try again with a different table.
A successful match yields a string
containing both literal characters
which are written out and pseudo-operations, or macros, which are expanded.
Before studying the contents
of these strings we will consider how table entries are matched
Recall that most non-leaf nodes in an expression tree
contain the name of the operator,
the type of the value represented, and pointers to the subtrees (operands).
They also contain an estimate of the number of registers required to evaluate
the expression, placed there by the expression-optimizer routines.
The register counts are used to guide the code generation process,
which is based on the Sethi-Ullman algorithm.
tables consist of entries
each containing an operator number and a pointer
to a subtable for the corresponding operator.
A subtable consists of a sequence
of entries, each with a key describing certain properties of the
operands of the operator involved; associated with the key is a code string.
Once the subtable corresponding to the operator is found, the subtable
is searched linearly until a key is found such that the properties demanded
by the key are compatible with the operands of the tree node.
A successful match returns the code string;
an unsuccessful search, either for the operator in the main table
or a compatble key in the subtable,
returns a failure indication.
The tables are all contained in a file
which must be processed to obtain an assembly language program.
Thus they are written in a special-purpose language.
To provided definiteness to the following discussion, here is an
example of a subtable entry.
The `%' indicates the key;
the information following (up to a blank line) specifies the code string.
Very briefly, this entry is in the subtable
the key specifies that the left operand is any integer, character, or pointer
and the right operand is any word quantity which is directly addressible
(e.g. a variable or constant).
The code string calls for the generation of the code
to compile the left (first) operand into the
and then to produce an `add' instruction which adds the
second operand (`A2') to the register (`R').
All of the notation will be explained below.
Only three features of the operands are used in deciding
whether a match has occurred.
Is the type of the operand compatible with that demanded?
Is the `degree of difficulty' (in a sense described below) compatible?
The table may demand that the operand have a `*'
(indirection operator) as its highest operator.
As suggested above, the key for a subtable entry
is indicated by a `%,' and a comma-separated pair
of specifications for the operands.
(The second specification is ignored for unary operators).
A specification indicates
a type requirement by including one of the following letters.
If no type letter is present, any integer, character,
or pointer operand will satisfy the requirement (not float, double, or long).
A byte (character) operand is required.
A word (integer or pointer) operand is required.
A float or double operand is required.
A double operand is required.
A long (32-bit integer) operand is required.
Before discussing the `degree of difficulty' specification,
the algorithm has to be explained more completely.
are called with a register number in which to place their result.
Registers 0, 1, ... are used during evaluation of expressions;
the maximum register which can be used in this way depends on the
number of register variables, but in any event only registers
0 through 4 are available since r5 is used as a stack frame
header and r6 (sp) and r7 (pc) have special
The code generation routines assume that when called with register
as argument, they may use
(up to the first register variable)
Consider the expression `X+Y', where both
As a first approximation, there are three ways of compiling
code to put this expression in register
If Y is an addressible cell,
(recursively) put X into register
If Y is an expression that can be calculated in
smaller than the number of registers available,
Otherwise, compile Y into register
save the result in a temporary (actually, on the stack)
then add in the temporary.
The distinction between cases 2 and 3 therefore depends
on whether the right operand can be compiled in fewer than
is the number of free registers left after registers 0 through
are presumed to contain already computed temporary results;
contain the value of the left operand while the right
These considerations should make clear
the specification codes for the degree of difficulty,
bearing in mind that a number of special cases are also present:
is satisfied when the operand is zero, so that special code
can be produced for expressions like `x = 0'.
is satisfied when the operand is the constant 1, to optimize
cases like left and right shift by 1, which can be done
efficiently on the PDP-11.
is satisfied when the operand is a positive (16-bit)
constant; this takes care of some special cases in long arithmetic.
is satisfied when the operand is addressible;
this occurs not only for variables and constants, but also for
some more complicated constructions, such as indirection through
a simple variable, `*p++' where
is a register variable (because of the PDP-11's auto-increment address
mode), and `*(p+c)' where
Precisely, the requirement is that the operand refers to a cell
whose address can be written as a source or destination of a PDP-11
is satisfied by an operand whose value can be generated in a register
is the number of registers left (not counting the current register).
The `e' stands for `easy.'
is satisfied by any operand.
The `n' stands for `anything.'
These degrees of difficulty are considered to lie in a linear ordering
and any operand which satisfies an earlier-mentioned requirement
will satisfy a later one.
Since the subtables are searched linearly,
if a `1' specification is included, almost certainly
a `z' must be written first to prevent
expressions containing the constant 0 to be compiled
a key specification may contain a `*' which
requires the operand to have an indirection as its leading operator.
Examples below should clarify the utility of this specification.
Now let us consider the contents of the code string
associated with each subtable entry.
Conventionally, lower-case letters in this string
represent literal information which is copied directly
Upper-case letters generally introduce specific
macro-operations, some of which may be followed
by modifying information.
The code strings in the tables are written with tabs and
new-lines used freely to suggest instructions which will be generated;
the table-compiling program compresses tabs (using the 0200 bit of the
next character) and throws away some of the new-lines.
For example the macro `F' is ordinarily written on a line by itself;
but since its expansion will end with a new-line, the new-line
after `F' itself is dispensable.
This is all to reduce the size of the stored tables.
The first set of macro-operations is concerned with
Recall that this is done by the
In the following discussion the `current register'
is generally the argument register to
that is, the place where the result is desired.
The `next register' is numbered one
than the current register.
(This explanation isn't fully true
because of complications, described below, involving
operations which require even-odd register pairs.)
causes a recursive call to
routine to compile code which places the value of the first (left)
operand of the operator in the current register.
generates code which places the value of the first operand in the
It is incorrectly used if there might be no next register;
that is, if the degree of difficulty of the first operand is not `easy;'
if not, another register might not be available.
generates code which pushes the value of the first operand on the stack,
compile the second (right) operand
into the current register, the next register, or onto the stack.
To deal with registers, there are
which expands into the name of the current register.
which expands into the name of the next register.
which expands into the the name of the current register plus 1.
It was suggested above that this is the same as the next register,
except for complications; here is one of them.
Long integer variables have
32 bits and require 2 registers; in such cases the next register
is the current register plus 2.
The code would like to talk about both halves of the
long quantity, so R refers to the register with the high-order part
and R+ to the low-order part.
This is another complication, involving division and mod.
These operations involve a pair of registers of which the odd-numbered
contains the left operand.
arranges that the current register is odd;
the R\- notation allows the code to refer to the next lower,
To refer to addressible quantities, there are the notations:
causes generation of the address specified by the first operand.
For this to be legal, the operand must be addressible; its
or a more restrictive specification.
correspondingly generates the address of the second operand
We now have enough mechanism to show a complete, if suboptimal,
table for the + operator on word or byte operands.
The first two sequences handle some special cases.
Actually it turns out that handling a right operand of 0
is unnecessary since the expression-optimizer
Adding 1 by using the `increment' instruction is done next,
and then the case where the right operand is addressible.
It must be a word quantity, since the PDP-11 lacks an `add byte' instruction.
Finally the cases where the right operand either can, or cannot,
be done in the available registers are treated.
The next macro-instructions are conveniently
introduced by noticing that the above table is suitable
for subtraction as well as addition, since no use is made of the
commutativity of addition.
All that is needed is substitution of `sub' for `add'
Considerable saving of space is achieved by factoring out
several similar operations.
is replaced by a string from another table indexed by the operator
in the node being expanded.
This secondary table actually contains two strings per operator.
is replaced by the second string in the side table
entry for the current operator.
Thus, given that the entries for `+' and `\-' in the side table
are `add' and `inc,' `sub' and `dec'
the middle of of the above addition table can be written
and it will be suitable for subtraction,
and several other operators, as well.
Next, there is the question of character and floating-point operations.
generates the letter `b' if the first operand is a character,
`f' if it is float or double, and nothing otherwise.
It is used in a context like `movB1'
which generates a `mov', `movb', or `movf'
instruction according to the type of the operand.
is just like B1 but applies to the second operand.
generates `b' if either operand is a character
generates `f' if the type of the operator node itself is float or double,
For example, there is an entry in
Note first that two key specifications
can be applied to the same code string.
Next, observe that when a word is assigned to a byte or to a word,
or a word is assigned to a byte,
as appropriate, does the job.
However, when a byte is assigned to a word,
it must pass through a register to implement the sign-extension rules:
Next, there is the question of handling indirection properly.
Consider the expression `X + *Y', where X and Y are expressions,
Assuming that Y is more complicated than just a variable,
but on the other hand qualifies as `easy' in the context,
the expression would be compiled by placing the value of X in a register,
that of *Y in the next register, and adding the registers.
It is easy to see that a better job can be done
by compiling X, then Y (into the next register),
instruction symbolized by `add (R1),R'.
This scheme avoids generating
the instruction `mov (R1),R1'
required actually to place the value of *Y in a register.
A related situation occurs
with the expression `X + *(p+6)', which
exemplifies a construction
frequent in structure and array references.
The addition table shown above would produce
As we said above, a key specification for a code table entry
may require an operand to have an indirection as its highest operator.
To make use of the requirement,
the following macros are provided.
the first operand must have the form *X.
If in particular it has the form *(Y + c), for some constant
then code is produced which places the value of Y in
Otherwise, code is produced which loads X into the current register.
resembles F* except that the next register is loaded.
resembles F* except that the second operand is loaded.
resembles S* except that the next register is loaded.
The first operand must have the form `*X'.
Push the value of X on the stack.
resembles FS* except that it applies to the second operand.
To capture the constant that may have been skipped over
in the above macros, there are
The first operand must have the form *X;
if in particular it has the form *(Y + c) for
a constant, then the constant is written out,
is the same as #1 except that the second operand is used.
Now we can improve the addition table above.
Just before the `%n,e' entry, put
and just before the `%n,n' put
When using the stacking macros there is no place to use
as an index word, so that particular special case doesn't occur.
The constant mentioned above can actually be more
Any quantity acceptable to the assembler as an expression will do,
in particular the address of a static cell, perhaps with a numeric offset.
is an external character array,
the expression `x[i+5] = 0' will generate
via the table entry (in the `=' part of
Some machine operations place restrictions on the registers
The divide instruction, used to implement the divide and mod
operations, requires the dividend to be placed in the odd member
of multiplication make it simplest to put the multiplicand
in an odd-numbered register.
There is no theory which optimally accounts for
this kind of requirement.
handles it by checking for a multiply, divide, or mod operation;
in these cases, its argument register number is incremented by
one or two so that it is odd, and if the operation was divide or mod,
so that it is a member of a free even-odd pair.
The routine which determines the number of registers required
estimates, conservatively, that
at least two registers are required for a multiplication
and three for the other peculiar operators.
After the expression is compiled,
the register where the result actually ended up is returned.
(Divide and mod are actually the same operation except for the
These operations are the ones which cause results to end up in
and this possibility adds a further level of complexity.
The simplest way of handling the problem is always to move the
result to the place where the caller expected it,
but this will produce unnecessary register moves in many
simple cases; `a = b*c' would generate
The next thought is used the passed-back
information as to where the result landed to change the notion of the current
While compiling the `=' operation above, which comes from a
it is sufficient to redefine the meaning of `R'
after processing the `S' which does the multiply.
This technique is in fact used; the tables are written in such a way
that correct code is produced.
The trouble is that the technique cannot be used in general,
because it invalidates the count of the number of registers
required for an expression.
Consider just `a*b + X' where X is some expression.
The algorithm assumes that the value of a*b,
once computed, requires just one register.
If there are three registers available, and X requires two registers to
compute, then this expression will match a key specifying
If a*b is computed and left in register 1, then there are, contrary
to expectations, no longer two registers available to compute X,
but only one, and bad code will be produced.
To guard against this possibility,
checks the result returned by recursive calls which implement
F, S and their relatives.
If the result is not in the expected register, then the number of
registers required by the other operand is checked;
if it can be done using those registers which remain even
after making unavailable the unexpectedly-occupied
the notions of the `next register' and possibly the `current
Otherwise a register-copy instruction is produced.
A register-copy is also always produced
when the current operator is one of those which have odd-even requirements.
Finally, there are a few loose-end macro operations
and facts about the tables.
is used for long operations.
It is written with an address like a machine instruction;
it expands into `adc' (add carry) if the operation
`sbc' (subtract carry) if the operation is a subtractive
operator, and disappears, along with the rest of the line, otherwise.
Its purpose is to allow common treatment of logical
operations, which have no carries, and additive and subtractive
operations, which generate carries.
generates a `tst' instruction if the first operand
of the tree does not set the condition codes correctly.
It is used with divide and mod operations,
which require a sign-extended 32-bit operand.
The code table for the operations contains an `sxt'
(sign-extend) instruction to generate the high-order part of the
is analogous to the `F' and `S' macros,
except that it calls for the generation of code for
(not one of its operands)
for all the operators which, when executed normally,
set the condition codes properly according to the result.
It prevents a `tst' instruction from being generated for
constructions like `if (a+b) ...'
since after calculation of the value of
`a+b' a conditional branch can be written immediately.
All of the discussion above is in terms of operators with operands.
Leaves of the expression tree (variables and constants), however,
are peculiar in that they have no operands.
In order to regularize the matching process,
examines its operand to determine if it is a leaf;
if so, it creates a special `load' operator whose operand
is the leaf, and substitutes it for the argument tree;
this allows the table entry for the created operator
to use the `A1' notation to load the leaf into a register.
Purely to save space in the tables,
pieces of subtables can be labelled and referred to later.
It turns out, for example,
that rather large portions of the
table for the `=' and `=+' operators are identical.
while part of the `=+' table is
Labels are written as `%[ ... : ]',
before the key specifications;
Peculiarities in the implementation
make it necessary that labels appear before references to them.
The example illustrates the utility
of allowing separate keys
to point to the same code string.
works properly if either the right operand is a word, or the left operand
but since there is no `add byte' instruction the addition code
has to be restricted to word operands.