[cfe-dev] Question about optimization of new and delete

Chandler Carruth chandlerc at google.com
Sun Sep 29 15:28:06 PDT 2013


On Sun, Sep 29, 2013 at 12:04 PM, Nicola Gigante
<nicola.gigante at gmail.com>wrote:

> Hello.
>
> Probably this is an old enough question, sorry in this case.
>

Heh, not really. We're just now getting the C++ standard fixed:
http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2013/n3664.html


>
> I was wondering which optimizations clang/llvm does (or can do, given
> restrictions from the standard)
> about the use of default new/delete operators.
>

See the paper for the high level theory of what the standard allows (once
it goes in). The current plan in Clang is to follow that paper's strategy
of optimization even in older standard modes unless there is significant
existing code broken by it.


>
> In particular, I'm wondering about a couple of interesting cases:
>
> 1) Can clang convert a call to default operator new to stack allocation,
> if it can prove that
> the lifetime of the allocated memory is the same as the enclosing scope?
> Would it be someway contrary to the standard or somewhat undesirable?
>

We can do this, but it may cause an unacceptable growth in stack usage. Hal
Finkel has recently started work on an optimization pass to do precisely
this, and I'm helping review and get it into the tree. I would expect Clang
to start doing this soon for small, constant size allocations.

Currently, Clang only really does this when it can delete the allocation
entirely, which is probably why you see confusing results from your testing.


2) Can clang/llvm identify as a dead store a write to a piece of memory
> that will be delete?
>
> void func(Class *obj) {
>     obj->member = 42; // Is this store removed?
>     delete obj;
> }
>
> Compiling this exact code with -O3, I see the store still there.
>

Huh. No, I bet we miss this. This is almost certainly just a missed
optimization that we should get.


However, note that all of Clang's optimizations of this form are mostly
conducted by the LLVM optimization libraries Clang is built on, and so the
fix to this missed optimization will likely involve mostly a change to LLVM.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.llvm.org/pipermail/cfe-dev/attachments/20130929/eceaded8/attachment.html>


More information about the cfe-dev mailing list