1

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
webchatowner
  • 145
  • 1
  • 1
  • 10
  • You need to break `j < 10 || j < 20` down into three address code before the if instruction and then test if the result is false in it. – Johan Dec 14 '18 at 13:00
  • Thanks for your reply! You can't have this for example, `mt1 = j < 10` because `x op y` where op can only be `(+,-,\,*,&&, or ||)` @Johan – webchatowner Dec 14 '18 at 13:02
  • 1
    @webchatowner Then you can use something like `jlt10 = true; if j < 10 goto L1; jlt10 = false; L1:` to implement `jlt10 = j < 10`. – Johan Dec 14 '18 at 13:43

1 Answers1

5

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.

rici
  • 234,347
  • 28
  • 237
  • 341