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

Nicola Gigante nicola.gigante at gmail.com
Sun Sep 29 10:04:36 PDT 2013


Hello.

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

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

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?

Trivial example:

void func() {
    Class *obj = new Class(args);
    obj->stuff();
    delete obj;
}

Trying to compile something simple like this, I see the couple of operator calls are elided, but in more complex cases in 
my code this does not happen, and I would like to know why (is the effect of a tradeoff with the size of the allocated memory?)

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.

Thank you very much.

Nicola



More information about the cfe-dev mailing list