Three-Address Code
If there is at most one operator on the right side of the instruction, then the instruction will be the three-address code so that no arithmetic expressions are permitted. It is a kind of intermediate code that can be easily generated and converted into machine code.
The expression a+b*c can be translated into three-address instructions:
1
2
3
4
|
t1 = b * c
t2 = a + t1
|
Here, t1 and t2 are the temporary names, which are generated by the compiler.
Example:
Consider the following expression:
1
2
3
|
a + a * (b – c) + (b – c) * d
|
Three-address code for the given example is shown below:
t1 = b – c
t2 = a * t1
t3 = a + t2
t4 = t1 * d
t5 = t3 + t4
For the construction of a three-address code, two concepts are required: addresses and instructions. Three-address code can be performed using records called quadruples and triples, which are described below in detail.
The address can be any of the following: a name, a constant, or a compiler-generated temporary name.
Quadruples
A quadruples consists of four fields such as op, arg1, arg2, and result. The internal code for the operator is stored in the op field. For instance, the three-address instruction a = b + c is depicted by putting + in the op, b in arg1, c in arg2, and a in the result.
This rule has some anomaly, which is given below:
- Operations with unary operators do not use arg2.
- Arg2 and result don’t use by the PARAM operator.
- Conditional and unconditional operators put the target label in the result.
Example
See the below expression:
a = b * – c + b * – c;
Here, we have used the special operator minus to distinguish the unary minus operator from the binary minus operator.
Three address code for the given statements are:
t1 = minus c
t2 = b * t1
t3 = minus c
t4 = b * t3
t5 = t2 + t1
a = t5
Quadruple representation for given expression:
op | arg1 | arg2 | result | |
0 | minus | c | t1 | |
1 | * | b | t1 | t2 |
2 | minus | c | t3 | |
3 | * | b | t3 | t4 |
4 | + | t2 | t4 | t5 |
5 | = | t5 | a |
Triples
A triple has only three fields, which are known as op, arg1, and arg2. Result fields in quadruple are used for temporary names. Triples using the position of an operation to store results rather than temporary names. So triple using position (0) rather than temporary t1.
Example
Consider the following expression:
1
2
3
|
a = b * – c + b * – c ;
|
The three-address code and quadruple of this expression are shown above. The syntax tree and triple of this expression are shown below.
op | arg1 | arg2 | |
0 | minus | c | |
1 | * | b | (0) |
2 | minus | c | |
3 | * | b | (2) |
4 | + | (1) | (3) |
5 | = | a | (4) |
Here, forthecopy statement, a=t5 is replaced by a in agr1 and by 4 in arg2.