## Related Articles

• Write an Interview Experience

# Compiler Design | Detection of a Loop in Three Address Code

• Difficulty Level : Easy
• Last Updated : 16 Feb, 2023

Prerequisite – Three address code in Compiler

Loop optimization is the phase after the Intermediate Code Generation. The main intention of this phase is to reduce the number of lines in a program. In any program majority of the time is spent actually inside the loop for an iterative program. In the case of the recursive program a block will be there and the majority of the time will present inside the block.

Loop Optimization –

1. To apply loop optimization we must first detect loops.
2. For detecting loops we use Control Flow Analysis(CFA) using Program Flow Graph(PFG).
3. To find program flow graph we need to find Basic Block

Basic Block – A basic block is a sequence of three address statements where control enters at the beginning and leaves only at the end without any jumps or halts.

Finding the Basic Block – In order to find the basic blocks, we need to find the leaders in the program. Then a basic block will start from one leader to the next leader but not include the next leader. This means if you find out that line no 1 is a leader and line no 15 is the next leader, then the line from 1 to 14 is a basic block, but not including line no 15.

Identifying leader in a Basic Block –

1. First statement is always a leader
2. Statement that is target of conditional or un-conditional statement is a leader
3. Statement that follows immediately a conditional or un-conditional statement is a leader

## CPP

 `fact(x)``{``    ``int` `f = 1;``    ``for` `(i = 2; i <= x; i++)``        ``f = f * i;``    ``return` `f;``}`

Three Address Code of the above C code:

1. f = 1;
2. i = 2;
3. if (i > x) goto 9
4. t1 = f * i;
5. f = t1;
6. t2 = i + 1;
7. i = t2;
8. goto(3)
9. goto calling program