[clang] [CIR] Emit lifetime markers for automatic variables (PR #206695)

Jiahao Guo via cfe-commits cfe-commits at lists.llvm.org
Wed Jul 8 00:00:49 PDT 2026


================
@@ -0,0 +1,112 @@
+// RUN: %clang_cc1 -triple x86_64-unknown-linux-gnu -O2 -fclangir -emit-cir %s -o %t.cir
----------------
E00N777 wrote:

Hey andy, I fond some problems when I tried to add tests for a variable declared in the condition of a while loop and for loop.

Adding the requested test for a variable declared in a while/for condition uncovered two distinct problems, one of which pre-dates this PR:

-  A LifetimeMarker cleanup is pushed while the loop's cond region is being emitted. Since pushCleanup eagerly creates a cir.cleanup.scope and moves the insertion point into its body region, the subsequently emitted cir.condition ends up nested inside the cleanup scope, and the verifier rejects it ("condition must be within a conditional region"). So while (int x = g()) at -O2 would fail to compile.
- A pre-existing structural issue on main (not addressed here). The same shape already fails on current main without this PR when the condition variable has a non-trivial destructor, e.g. while (Guard g = Guard()), because the destructor cleanup takes the same eager-cir.cleanup.scope path.

The underlying problem is semantic: per C++ [stmt.while] a loop condition variable is destroyed and re-created on every iteration, so its cleanup must run on both the back edge and the exit edge. Classic CodeGen expresses this naturally on its flat CFG (both edges branch through a shared cleanup block). The structured cond region has no way to express a cleanup on two edges.  a cir.cleanup.scope wrapping the condition would trap the cir.condition terminator.

For this PR I suppress lifetime markers for while/for condition variables (suppressLoopCondVarLifetime, save/restored around the condition variable's emitDecl). The destructor case is anorthogonal pre-existing issue; If you have any suggestions for this issue, please let me know.  

https://github.com/llvm/llvm-project/pull/206695


More information about the cfe-commits mailing list