Optimizing of explicit temporary storage

Mark Mitchell mark@codesourcery.com
Tue Oct 12 07:38:00 GMT 2004


Richard Guenther wrote:

> Mike Stump wrote:
>
>> On Sunday, October 10, 2004, at 07:48  AM, Richard Guenther wrote:
>>
>>> Is it legal for a conforming C++ compiler to optimize away storage 
>>> allocation / deallocation?  Like in
>>>
>>> #include <new>
>>>
>>> void foo(void)
>>> {
>>>         int *x = new(std::nothrow) int;
>>>         delete x;
>>> }
>>>
>>> is it allowed to kill the new and delete statements?  Would it be 
>>> allowed to do this for the throwing version of new, too?
>>
>>
>> The as if rule is fairly powerful...  If the resulting program 
>> behaves as if it had it, then the optimization is allowed.  I don't 
>> think memory consumption is an externally visible effect.  Now, we 
>> might need to do full program analysis to know which new is run, and 
>> to know its semantics; I don't recall if the user is prohibited from 
>> adding semantics to a new replacement function.
>
>
> Well, I was thinking of the traditional
>
> struct Vector {
>    Vector(int size);
>    Vector operator*(const Vector&);
>    Vector& operator=(const Vector&);
>    double *storage;
> };
>
> and doing expressions like
>
> Vector a,b,c;
> a = b*c;
>
> where one usually considers using expression templates because of the 
> temporaries.  With loop fusion one could get the speed of the 
> expression template code, but are you allowed to get rid of the 
> temporaries (and their allocated memory), too?

As Mike says, if you can prove that there are no side-effects, then, 
yes, you can.  But, that's in general impossible; even with 
whole-program analysis, you see that "::operator new" calls 
"std::malloc" and "std::malloc" eventually makes a syscall.  I don't 
think any compiler has ever attempted to turn:

  free (malloc (16));

into a no-op, which would be a simpler case.

So, I think that for practical purposes, you're not going to find that 
compilers get rid of these kinds of calls.

-- 
Mark Mitchell
CodeSourcery, LLC
(916) 791-8304
mark@codesourcery.com



More information about the Gcc mailing list