Destroy temporaries at the end of expression statements. (#7513)

Instead of tracking the cleanup scope depth on entry to each scope,
track an "ambient" cleanup scope depth that's *after* the destructors of
local variables in that scope. This gets increased to include the
destructors of local variables when we create a name-binding
declaration. Then, when we reach a point where temporaries should be
destroyed, run cleanups that are after the ambient cleanup scope depth
on the stack. This happens:

* At the `;` of a statement expression.
* At the `)` of an `if` or `while` statement.
* After performing the implied `HasValue()` call in a `for` statement.

Per informal agreement with leads, this means we lifetime-extend all
temporaries created in the initializer of a name-binding declaration to
the full scope of that declaration, but that temporaries created in an
expression statement are destroyed at the `;`.
This commit is contained in:
Richard Smith
2026-07-16 15:12:39 +00:00
committed by GitHub
parent 81e495ee53
commit 703529fc55
37 changed files with 844 additions and 384 deletions
@@ -82,8 +82,8 @@ fn M() -> i32 {
// CHECK:STDOUT: call void @llvm.lifetime.start.p0(ptr %.loc25_6.3.temp), !dbg !32
// CHECK:STDOUT: %H.call = call i32 @_CH.Main.5bd8d5767580997a(i32 %x), !dbg !32
// CHECK:STDOUT: store i32 %H.call, ptr %.loc25_6.3.temp, align 4, !dbg !32
// CHECK:STDOUT: call void @_CF.Main.84588f41d61dafba(i32 %x), !dbg !33
// CHECK:STDOUT: call void @"_COp.5e27612b9dd31a14:core.Destroy.Core"(ptr %.loc25_6.3.temp), !dbg !32
// CHECK:STDOUT: call void @_CF.Main.84588f41d61dafba(i32 %x), !dbg !33
// CHECK:STDOUT: ret i32 %x, !dbg !34
// CHECK:STDOUT: }
// CHECK:STDOUT: