parsingcompiler-constructiontacit-programming

How to represent binary logical in Three Address Code


In three address code a branch can only have a binary relational operator,

e.g.

if x relop y goto L1, where relop is (!=,==,>,>=,<,<=)

How would the following be represented as three address code format:

j = 0
while(j < 10 || j < 20)
{
    System.out.println(i);
    j++;
}

Here is my solution which is obviously incorrect:

main:
        j = 1
        sum = 0
L2:
        if j < 10 || j < 20 goto L3
        goto L4
L3:
        mt2 = sum + 1
        sum = mt2
        mt3 = j + 1
        j = mt3
        goto L2
L4:
        sum = 2

Solution

  • You break it down into two tests:

    L2:
            if j < 10 goto L3
            if j < 20 goto L3
            goto L4
    L3:
    

    (Did you mean j < 10 || j > 20? As written, the first test is redundant.)

    In general, || and && are control flow operators and translate into individual branch instructions. Note that boolean not is often implemented by flipping labels.

    Boolean operators are usually "short-circuiting" -- that is, the right-hand operation is not evaluated unless necessary -- precisely because of this translation style. Had the second computation been more complicated, it would have been done after the first if, which would lead to short-circuit behaviour.