Search code examples
c++compiler-constructionllvm

Writing a compiler backend using LLVM: return value for statements


I'm writing a basic compiler for the a subset of the C language, and I'm using the LLVM C++ api to write the backend. I'm following this tutorial mostly. I understand that each node in the AST must return an llvm::Value, that works for expressions, but what do I return for C statements?

For example, for an if-else block, I am required to create a phi node. The constructor Builder.CreatePHI takes the type of the value this if-else block is supposed to evaluate to, but what's that type supposed to be?


Solution

  • Phi nodes represent the operation of getting a value from the union of several predecessor blocks. You will need one phi node for each value determined within the if/else, e.g. a register variable which is assigned conditionally.

    If you aren't using register variables or carrying them between basic blocks, then you won't need any phi nodes.

    You shouldn't have any need for a phi node just to implement an if/else which isn't doing anything, precisely because non-expression statements don't have values. As @arnt mentions, you probably want to use the void type.