[llvm-dev] Another tail call optimization question

Haoran Xu via llvm-dev llvm-dev at lists.llvm.org
Sat Oct 3 13:10:12 PDT 2020


Hi Alexey,

Thanks for the explanation! That's really a tricky case, I understand it
now.

Best,
Haoran

Alexey <avl.lapshin at gmail.com> 于2020年10月3日周六 上午3:35写道:

> Hi Haoran,
> On 03.10.2020 12:02, Haoran Xu via llvm-dev wrote:
>
> Hello,
>
> Could anyone kindly explain to me why the 'g()' in the following function
> cannot have tail call optimization?
>
>> void f(int* x);
>> void g();
>> void h(int v) {
>>    f(&v);
>>    g();
>> }
>>
> A while ago I was taught that tail call optimization cannot apply if local
> variables needs to be kept alive, but 'g()' doesn't seem to require
> anything to be alive on the stack.
> I tried to manually add 'tail' to the emitted LLVM IR and it appears to
> work.
>
> Any idea how I could fix this and let clang automatically generate tail
> call?
>
>
> In that test case the pointer to "v" could escape through call to f();
> That prevents from doing tail call for g().
> If it is already known that f() does not capture its parameter
> then it could be declared with attribute noescape :
>
> https://clang.llvm.org/docs/AttributeReference.html#noescape
>
> In this case tailcall happens:
>
> cat test.cpp
>     void f(__attribute__((noescape)) int* x);
>     void g();
>     void h(int v) {
>        f(&v);
>        g();
>     }
>
> clang++ -O3 -S test.cpp
>
> grep _Z1gv test.s
>
> jmp    _Z1gv                           # TAILCALL
>
>
>
> Thanks!
>
> Best,
> Haoran
>
> _______________________________________________
> LLVM Developers mailing listllvm-dev at lists.llvm.orghttps://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-dev
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.llvm.org/pipermail/llvm-dev/attachments/20201003/cfcb4d06/attachment.html>


More information about the llvm-dev mailing list