What is Backpatching of Boolean Expressions and Control Statements in compiler design?

The simplest way to execute syntax-directed translation is to use two passes. First, construct a syntax tree for the input and then walk the tree in depth-first order, completing the translations given in definition.

The major issue with generating code for Boolean expression and flow of control statements in a single pass is that during a single pass we cannot understand the labels for which the control should goto at the time the jump statements are generated. It can get around this issue by making a sequence of branching statements with the targets of the jumps temporarily left undefined.

Each such statement would be put on a record of goto statements where labels will be filled in when the proper label is decided. It can call this subsequent filling of the label backpatching.

Backpatching for Boolean Expressions

It can construct a translation scheme suitable for generating code for Boolean expressions during bottom-up parsing. A non-terminal marker M in the grammar causes a semantic action to pickup, at suitable times, the index of the next instruction to be created. The grammar is as follows−

B → B1| | MB2|B1&& MB2|! B1|(B1)|E1rel E2|True|False

M → ϵ

The translation scheme is as follows−

B → B1|| MB2{backpatch (B1. falselist, M. instr);
B.truelist = merge (B1.truelist, B2.truelist);
B.falselist =B2.falselist;}
B → B1&& MB2{backpatch (B1. truelist, M. instr);
B.truelist = B2.truelist;
B.falselist = merge (B1. falselist, B2.falselist);}
B → ! B1{ B.truelist = B1.falselist;
B.falselist = B1.truelist;}
B → (B1){ B.truelist = B1.truelist;
B.falselist = B1.falselist;}
B → E1 rel E2{ B.truelist = makelist(nextinstr);
B.falselist = makelist(nextinstr + 1);
append ('if' E1. addr relop E2. addr 'goto-');
append ('goto-');}
B → True{ B.truelist = makelist(nextinstr);
append ('goto-');}
𝐁 → 𝐅𝐚𝐥𝐬𝐞{ B.falselist = makelist(nextinstr);
append ('goto-');}
𝐌 →∈{M.instr = nextinstr;}

Flow of Control Statements

Now it can use backpatching to translate the flow of control statements in one pass. Consider the statement generated by the following grammar −

S → if (B)then S | if (B)then S else S |while (B)then do

S| begin L end |A;

L → L; S | S

Here S denotes a statement, L a statement list, A an assignment statement, and B a Boolean Expression. There should be other productions, including

  • After backpatching 104 into instruction 102.

100− if x < 100 goto -

101− goto -

102− if x > 200 goto 104

103− goto -

104− if x! = y goto-

105− goto-

  • After backpatching 102 into instruction 101

100− if x < 100 goto -

101− goto 102

102− if y > 200 goto 104

103− goto -

104− if x! = y goto-

105− goto-

The production is given, however, is sufficient to illustrate the technique used to translate the flow of control statements.