[clang] [LifetimeSafety] Add origin tracking for lambda captures (PR #185216)

Utkarsh Saxena via cfe-commits cfe-commits at lists.llvm.org
Mon Mar 9 14:48:29 PDT 2026


================
@@ -431,6 +445,26 @@ void FactsGenerator::VisitMaterializeTemporaryExpr(
   }
 }
 
+void FactsGenerator::VisitLambdaExpr(const LambdaExpr *LE) {
+  // The lambda gets a single merged origin that aggregates all captured
----------------
usx95 wrote:

This has been less relevant until now but now the diagnostics are very obscure due to implicit loans.

```cpp
 auto return_copied_lambda() {
    int local = 1, local2 = 2;
    auto lambda = [&]() { return local + local2; };
    auto lambda_copy = lambda;
    return lambda_copy;
  }
```

The diagnostics are:

```
/usr/local/google/home/usx/tmp/a.cpp:294:20: warning: address of stack memory is returned later [-Wlifetime-safety-return-stack-addr]
  294 |     auto lambda = [&]() { return local + local2; };
      |                    ^
/usr/local/google/home/usx/tmp/a.cpp:296:12: note: returned here
  296 |     return lambda_copy;
      |            ^~~~~~~~~~~
/usr/local/google/home/usx/tmp/a.cpp:294:20: warning: address of stack memory is returned later [-Wlifetime-safety-return-stack-addr]
  294 |     auto lambda = [&]() { return local + local2; };
      |                    ^
/usr/local/google/home/usx/tmp/a.cpp:296:12: note: returned here
  296 |     return lambda_copy;
```

We need to now start improving the diagnostics, like including variable names (where it resides, temporary or not).

Please add a TODO to include variable names to make this helpful.

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


More information about the cfe-commits mailing list