[cfe-dev] Memory allocation in current function stack using __builtin_alloca

Rahul Jain 1989.rahuljain at gmail.com
Sat Jul 13 08:29:04 PDT 2013


Thanks Tim, that really helped in understanding the difference!

Thanks,
Rahul


On Sat, Jul 13, 2013 at 6:30 PM, Tim Northover <t.p.northover at gmail.com>wrote:

> > clang version- clang version 3.4 (trunk 186087)
> > On compiling it with clang the output is:
> > sp1 points at 0xbf87d30f
> > sp2 points at 0xbf87d30e
>
> Interestingly, it doesn't if -O3 is used.
>
> There's potential interactions with C++'s rule that each object has a
> unique pointer, though since C++11 doesn't mention alloca at all (it's
> POSIX) that's a bit of a shaky connection.
>
> > Would be really helpful if someone could throw some light on how stack
> > allocation and alignment takes place in clang?
>
> Well, Clang just produces one of LLVM's "alloca" instructions for the
> code. The LLVM language reference at
> http://llvm.org/docs/LangRef.html#alloca-instruction says: "allocating
> zero bytes is legal, but the result is undefined".
>
> More generally, all local variables get an LLVM "alloca" instruction,
> which can specify size and alignment. Various LLVM passes know how to
> optimise these (hence the difference between -O0 and -O3), and then
> they eventually get assigned to stack slots with the appropriate size
> and alignment during CodeGen.
>
> To understand what Clang does to your code, it's very helpful to give
> it the "-emit-llvm" option (I usually use "-S -o-" as well to actually
> see it). At "-O0" that'll be directly what Clang itself creates; at
> "-O3" it'll be the code after the LLVM passes have gone to work.
>
> What's happening here (at -O3) is that some pass ("InstCombine" by the
> looks of it) is combining the two "alloca 0" instructions into just
> one.
>
> Tim.
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.llvm.org/pipermail/cfe-dev/attachments/20130713/0239a45a/attachment.html>


More information about the cfe-dev mailing list