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

前端 未结 2 1477
攒了一身酷
攒了一身酷 2021-01-30 01:25

LLVM has phi instruction with quite weird explanation:

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

2条回答
  •  深忆病人
    2021-01-30 02:11

    You don't need to use phi at all. Just create bunch of temporary variables. LLVM optimization passes will take care of optimizing temporary variables away and will use phi node for that automatically.

    For example, if you want to do this:

    x = 4;
    if (something) x = x + 2;
    print(x);
    

    You can use phi node for that (in pseudocode):

    1. assign 4 to x1
    2. if (!something) branch to 4
    3. calculate x2 from x1 by adding 2
    4. assign x3 phi from x1 and x2
    5. call print with x3

    But you can do without phi node (in pseudocode):

    1. allocate local variable on stack called x
    2. load into temp x1 value 4
    3. store x1 to x
    4. if (!something) branch to 8
    5. load x to temp x2
    6. add x2 with 4 to temp x3
    7. store x3 to x
    8. load x to temp x4
    9. call print with x4

    By running optimization passes with llvm this second code will get optimized to first code.

提交回复
热议问题