https://gcc.gnu.org/bugzilla/show_bug.cgi?id=124660

            Bug ID: 124660
           Summary: Missed optimization for reusing stack space of
                    temporary objects in C
           Product: gcc
           Version: 15.2.0
            Status: UNCONFIRMED
          Severity: normal
          Priority: P3
         Component: c
          Assignee: unassigned at gcc dot gnu.org
          Reporter: star-code at tuta dot com
  Target Milestone: ---

It seems that, in C, GCC currently does not reuse stack space for temporary
objects when their lifetimes do not overlap [1]. GCC does perform this
optimization for named variables, though. For example [2]:

    // -O2
    struct S {
      char a[256];
    };
    struct S f();
    void g(char *);
    void test1() {
      g(f().a);
      g(f().a);
    }
    void test2() {
      {
        struct S s = f();
        g(s.a);
      }
      {
        struct S s = f();
        g(s.a);
      }
    }

GCC compiles this code into:

    test1:
      sub rsp, 520
      mov rdi, rsp
      call f
      mov rdi, rsp
      call g
      lea rdi, [rsp+256]
      call f
      lea rdi, [rsp+256]
      call g
      add rsp, 520
      ret
    test2:
      sub rsp, 264
      mov rdi, rsp
      call f
      mov rdi, rsp
      call g
      mov rdi, rsp
      call f
      mov rdi, rsp
      call g
      add rsp, 264
      ret

Observe that the stack usage in `test1` is not optimized. However, when
compiling in C++ mode, this optimization does occur:

    test1():
      sub rsp, 264
      mov rdi, rsp
      call f()
      mov rdi, rsp
      call g(char*)
      mov rdi, rsp
      call f()
      mov rdi, rsp
      call g(char*)
      add rsp, 264
      ret
    test2():
      jmp test1()

So I think this optimization should be implemented for C as well, and the
option `-fstack-reuse` [3] could be used to enable or disable the behavior.
Currently, the values `all` and `named_vars` for that option appear to make no
difference in C mode.

[1] https://www.reddit.com/r/C_Programming/comments/1s3cohq/comment/ocfjnuk/
[2] https://godbolt.org/z/87vqqeTTd
[3]
https://gcc.gnu.org/onlinedocs/gcc-15.2.0/gcc/Code-Gen-Options.html#index-fstack_005freuse

Reply via email to