[llvm-dev] alloca behavior in llvm IR

Tim Northover via llvm-dev llvm-dev at lists.llvm.org
Wed Dec 16 23:43:58 PST 2020


On Wed, 16 Dec 2020 at 13:52, 林政宗 <jackie_linzz at 126.com> wrote:
> When there are dynamic allocas, is it always that the compiler will insert @llvm.stacksave() and @llvm.stackrestore()?

Clang always emits them for variable length arrays as far as I know
(e.g. "int arr[n]"), but C's actual "alloca" function
(https://www.man7.org/linux/man-pages/man3/alloca.3.html) makes the
memory available until the function returns so Clang can't use
stackrestore anywhere there.

> When there is a need to insert @llvm.stacksave() and @llvm.stackrestore(), how does the compiler decide where it should insert them?

The stacksave should go just before the alloca you want to reclaim
later, which is usually pretty easy to do.

The stackrestore ideally goes just after the last instruction that
uses the memory involved. That's difficult to determine though (and
impossible to implement if it happens in another function). So in
practice source languages have scoping rules that say when a variable
is *allowed* to be accessed, and compilers put the stackrestore at the
end of the scope.

In C and C++ that's at the '}' of the block the variable is declared

Cheers.

Tim.


More information about the llvm-dev mailing list