What exactly PHI instruction does and how to use it in LLVM

Viewed 42104

LLVM has phi instruction with quite weird explanation:

The 'phi' instruction is used to implement the φ node in the SSA graph representing the function.

Typically it is used to implement branching. If I understood correctly, it is needed to make dependency analysis possible and in some cases it could help to avoid unnecessary loading. However it's still hard to understand what it does exactly.

Kaleidoscope example explains it fairly nicely for if case. However it's not that clear how to implement logical operations like && and ||. If I type the following to online llvm compiler:

void main1(bool r, bool y) {
    bool l = y || r;
}

Last several lines completely confuse me:

; <label>:10                                      ; preds = %7, %0
%11 = phi i1 [ true, %0 ], [ %9, %7 ]
%12 = zext i1 %11 to i8

Looks like phi node produces a result which can be used. And I was under impression that phi node just defines from which paths values coming.

Could someone explain what is a Phi node, and how to implement || with it?

3 Answers

The existing answers are good. But, I want to make it even simpler and shorter.

block3:
    %result = phi i32 [%a, %block1], [%b, %block2]

This means that if the previous block was block1, choose value a. If the previous block was block2, choose value b.

Why do we write like this? This is to prevent assignign result in two different blocks such as if block and else block. Because, we do not want to violate SSA principle. SSA helps compilers to apply variety of optimizations and it is a de-facto standard for the intermediate codes. For more information, refer to this reference.

Related