[llvm-dev] why is llvm.stacksave() necessary?

David Chisnall via llvm-dev llvm-dev at lists.llvm.org
Wed Jul 26 00:14:22 PDT 2017

On 25 Jul 2017, at 17:26, alex via llvm-dev <llvm-dev at lists.llvm.org> wrote:
> Another good example, thanks.
> I had a look at the ll and found that the restore is in the if.end block.
> I think it could also go into the for.inc block (just before jumping
> back to cond).

Either would work, but the part of clang that generates the IR for the if statement doesn’t know that the variable goes out of scope after the if statement.  The variable goes out of scope at the end of the loop and so that’s where the stack restore gets generated. Various optimisation passes may move it later (if you give the loop a small fixed trip count, you’ll see that at -O2 it gets unrolled and a single alloca used for all iterations).

> Is there any way (from AST in C++) to easily identify 'the block that
> unifies flow control at the end of the scope'? does it have any special
> attribute one could search for?

The C++ AST directly maps to scopes, because the structure of C/C++ source code is a tree[1].  Clang’s CodeGen (really IRGen) layer generates new basic blocks for each branch in a divergent flow control situation and generates code for them independently.  On exit from generating the divergent flow path, it generates a new block to unify the flow.  There isn’t a direct correspondence between IR blocks and AST nodes (for an example of why there can’t be, consider exceptions and C++ destructors).  


[1] This is common across the vast majority of programming languages and unfortunately is one of the things that makes programming difficult to learn for most people.  Only about 10% of people naturally think in terms of this kind of hierarchical structure (which is also why programmers tend to hate iTunes).

More information about the llvm-dev mailing list