Bug 21046 - move memory allocation out of a loop
Summary: move memory allocation out of a loop
Status: ASSIGNED
Alias: None
Product: gcc
Classification: Unclassified
Component: tree-optimization (show other bugs)
Version: 4.1.0
: P2 enhancement
Target Milestone: ---
Assignee: Richard Biener
URL:
Keywords: missed-optimization
Depends on: 42958
Blocks: 30409 38318
  Show dependency treegraph
 
Reported: 2005-04-15 12:41 UTC by Thomas Koenig
Modified: 2023-10-23 05:50 UTC (History)
5 users (show)

See Also:
Host:
Target:
Build:
Known to work:
Known to fail:
Last reconfirmed: 2020-11-11 00:00:00


Attachments

Note You need to log in before you can comment on or make changes to this bug.
Description Thomas Koenig 2005-04-15 12:41:56 UTC
Consider the following program fragment:

  char *p;
  int i;

  for (i=0; i<10; i++)
    {
      p = malloc(20);
      foo(p,i);
      free(p);
    }
}

The loop could be simplified into

  p = malloc(20);
  for (i=0; i<10; i++)
    foo(p,i);

  free(p);

This would reduce the overhead for memory allocation
considerably.

A more challenging case is to change

  for (i=0; i<10; i++)
    {
      p = malloc(2*i+2);
      foo(p,i);
      free(p);
    }

into

  p = malloc(20);
  for (i=0; i<10; i++)
      foo(p,i);

  free(p);

because the amount of memory allocated has an upper bound.

This is probably not a big win for straight C code.  For languages
which generate temporary arrays at runtime, such as Fortran, it
could mean a significant reduction in memory management overhead.
Comment 1 Giovanni Bajo 2005-04-15 13:04:33 UTC
I would think this is much more easily done in the frontend itself, which has a 
higher level representation so that it is much easier to hoist and reuse 
allocations.
Comment 2 Andrew Pinski 2005-04-15 13:37:13 UTC
(In reply to comment #1)
> I would think this is much more easily done in the frontend itself, which has a 
> higher level representation so that it is much easier to hoist and reuse 
> allocations.
Not really true anymore.

Confirmed, related to PR 19831.
Comment 3 Richard Biener 2010-04-29 09:33:08 UTC
I am working on this one (well, the first testcase kind).
Comment 4 xiaoyuanbo 2012-02-22 12:42:13 UTC
you know stack one
Comment 5 Thomas Koenig 2014-12-25 12:16:31 UTC
Any work being done on this?
Comment 6 Thomas Koenig 2020-11-11 09:22:54 UTC
Just thought to see if this has been fixed in the meantime;
it's not optimized with current trunk.