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

David Chisnall via llvm-dev llvm-dev at lists.llvm.org
Tue Jul 25 02:13:59 PDT 2017

> On 25 Jul 2017, at 10:04, alex via llvm-dev <llvm-dev at lists.llvm.org> wrote:
> Hi all,
> the language reference for the alloca instruction states:
> The ‘alloca‘ instruction allocates memory on the stack frame of the
> currently executing function, to be automatically released when this
> function returns to its caller.
> when using come c code like
> void myfunc(void){
> int i=4;
> double d[i];
> }
> the ir shows enclosing llvm.stackSave & restore constructs, enclosing
> the alloca related to 'd’.

Clang does this because clang intentionally generates IR naïvely and relies on LLVM optimisation passes to clean it up.

In the case of C VLAs, the size of the alloca changes whenever the declaration goes into scope.  By emitting a stack save and restore for d, clang doesn’t need to have different IR generating code for your example and for this one:

void myfunc(void
	for (int i=0 ; i<4; i++)
		double d[i];

In this case, each time that the loop is entered you will get a new d with a different size.  Clang emits code that handles this case, and an early optimisation pass will remove the stack save and stack restore intrinsics if they’re not actually needed.


More information about the llvm-dev mailing list