[clang] [LifetimeSafety] Catch intra-method lifetime_capture_by(this) dangles (PR #204630)

Gábor Horváth via cfe-commits cfe-commits at lists.llvm.org
Tue Sep 29 06:52:56 PDT 2026


https://github.com/Xazax-hun updated https://github.com/llvm/llvm-project/pull/204630

>From 7e7c7d0b93c53515151e898b734ea61ab44fff61 Mon Sep 17 00:00:00 2001
From: Gabor Horvath <gaborh at apple.com>
Date: Thu, 18 Jun 2026 17:28:18 +0100
Subject: [PATCH] [LifetimeSafety] Catch intra-method lifetime_capture_by(this)
 dangles

A borrow captured into the object via [[clang::lifetime_capture_by(this)]]
flows into the never-expiring `this` origin, so when the capture and the
captured local's expiry both happen inside one method, `this` is not otherwise
live at the expiry and the dangle was missed. Add a CaptureEscapeFact, emitted
for `this` at function exit, so checkExpiry sees the captured local going out of
scope while still held by the object and reports it as use-after-scope.

Assisted-by: Claude Opus 4.8
---
 .../Analysis/Analyses/LifetimeSafety/Facts.h  | 24 +++++++++++++++++
 .../Analyses/LifetimeSafety/LifetimeSafety.h  |  6 +++++
 clang/lib/Analysis/LifetimeSafety/Checker.cpp | 11 +++++++-
 clang/lib/Analysis/LifetimeSafety/Facts.cpp   |  8 ++++++
 .../LifetimeSafety/FactsGenerator.cpp         |  7 +++++
 .../Analysis/LifetimeSafety/LiveOrigins.cpp   |  2 ++
 clang/lib/Sema/SemaLifetimeSafety.h           | 19 +++++++++++++
 .../LifetimeSafety/noescape-violation.cpp     | 12 +++++++++
 clang/test/Sema/LifetimeSafety/safety.cpp     | 27 +++++++++++++++++++
 9 files changed, 115 insertions(+), 1 deletion(-)

diff --git a/clang/include/clang/Analysis/Analyses/LifetimeSafety/Facts.h b/clang/include/clang/Analysis/Analyses/LifetimeSafety/Facts.h
index 16fe31a577fa1..a78d22a80b527 100644
--- a/clang/include/clang/Analysis/Analyses/LifetimeSafety/Facts.h
+++ b/clang/include/clang/Analysis/Analyses/LifetimeSafety/Facts.h
@@ -174,6 +174,8 @@ class OriginEscapesFact : public Fact {
     Return, /// Escapes via return statement.
     Field,  /// Escapes via assignment to a field.
     Global, /// Escapes via assignment to global storage.
+    This,   /// Escapes via the enclosing object `this`, which outlives the
+            /// method.
   } EscKind;
 
   static bool classof(const Fact *F) {
@@ -243,6 +245,28 @@ class GlobalEscapeFact : public OriginEscapesFact {
             const LoanPropagationAnalysis *LPA = nullptr) const override;
 };
 
+/// Represents an origin escaping through the enclosing object `this`, which
+/// outlives the current method. Emitted for `this` at function exit so a borrow
+/// still held by the object there is seen as escaping -- e.g. a borrow captured
+/// via [[clang::lifetime_capture_by_this]] that outlived the captured local is
+/// reported as a use-after-scope.
+class ThisEscapeFact : public OriginEscapesFact {
+  SourceLocation Loc;
+
+public:
+  ThisEscapeFact(OriginID OID, SourceLocation Loc)
+      : OriginEscapesFact(OID, EscapeKind::This), Loc(Loc) {}
+
+  static bool classof(const Fact *F) {
+    return F->getKind() == Kind::OriginEscapes &&
+           static_cast<const OriginEscapesFact *>(F)->getEscapeKind() ==
+               EscapeKind::This;
+  }
+  SourceLocation getLoc() const { return Loc; }
+  void dump(llvm::raw_ostream &OS, const LoanManager &, const OriginManager &OM,
+            const LoanPropagationAnalysis *LPA = nullptr) const override;
+};
+
 class UseFact : public Fact {
   const Expr *UseExpr;
   const OriginList *OList;
diff --git a/clang/include/clang/Analysis/Analyses/LifetimeSafety/LifetimeSafety.h b/clang/include/clang/Analysis/Analyses/LifetimeSafety/LifetimeSafety.h
index 18e5e8473e414..ec00b60bc3ece 100644
--- a/clang/include/clang/Analysis/Analyses/LifetimeSafety/LifetimeSafety.h
+++ b/clang/include/clang/Analysis/Analyses/LifetimeSafety/LifetimeSafety.h
@@ -74,6 +74,12 @@ class LifetimeSafetySemaHelper {
                                    SourceLocation FreeLoc,
                                    llvm::ArrayRef<const Expr *> ExprChain) {}
 
+  // Overload for a use with only a location and no expression (e.g. a borrow
+  // captured into the object and still held at the capturing method's exit).
+  virtual void reportUseAfterScope(const Expr *IssueExpr, SourceLocation UseLoc,
+                                   const Expr *MovedExpr,
+                                   SourceLocation FreeLoc) {}
+
   // TODO: Pass the expiry location and aliasing chain like
   // reportUseAfterScope.
   virtual void reportUseAfterReturn(const Expr *IssueExpr,
diff --git a/clang/lib/Analysis/LifetimeSafety/Checker.cpp b/clang/lib/Analysis/LifetimeSafety/Checker.cpp
index c4cc872dcd568..e7969cdaf812a 100644
--- a/clang/lib/Analysis/LifetimeSafety/Checker.cpp
+++ b/clang/lib/Analysis/LifetimeSafety/Checker.cpp
@@ -328,6 +328,8 @@ class LifetimeChecker {
                                                   Warning.InvalidatedByExpr);
           } else if (isa<ReturnEscapeFact>(OEF)) {
             // FIXME: Diagnose invalidated return escapes separately.
+          } else if (isa<ThisEscapeFact>(OEF)) {
+            // FIXME: Diagnose a `this`-held loan invalidated through `this`.
           } else
             llvm_unreachable("Unhandled OriginEscapesFact type");
         } else if (const auto *RetEscape = dyn_cast<ReturnEscapeFact>(OEF))
@@ -348,7 +350,14 @@ class LifetimeChecker {
             IsMain = Func->isMain();
           SemaHelper->reportDanglingGlobal(IssueExpr, GlobalEscape->getGlobal(),
                                            MovedExpr, ExpiryLoc, IsMain);
-        } else
+        } else if (const auto *ThisEscape = dyn_cast<ThisEscapeFact>(OEF))
+          // A borrow is still held by the object (e.g. captured via
+          // lifetime_capture_by_this) when the captured local goes out of
+          // scope; reuse the use-after-scope diagnostic at the capturing
+          // method.
+          SemaHelper->reportUseAfterScope(IssueExpr, ThisEscape->getLoc(),
+                                          MovedExpr, ExpiryLoc);
+        else
           llvm_unreachable("Unhandled OriginEscapesFact type");
       } else
         llvm_unreachable("Unhandled CausingFact type");
diff --git a/clang/lib/Analysis/LifetimeSafety/Facts.cpp b/clang/lib/Analysis/LifetimeSafety/Facts.cpp
index 2d3c161ae8f11..9d3428b59b769 100644
--- a/clang/lib/Analysis/LifetimeSafety/Facts.cpp
+++ b/clang/lib/Analysis/LifetimeSafety/Facts.cpp
@@ -155,6 +155,14 @@ void GlobalEscapeFact::dump(llvm::raw_ostream &OS, const LoanManager &,
   OS << ", via Global)\n";
 }
 
+void ThisEscapeFact::dump(llvm::raw_ostream &OS, const LoanManager &,
+                          const OriginManager &OM,
+                          const LoanPropagationAnalysis *) const {
+  OS << "OriginEscapes (";
+  OM.dump(getEscapedOriginID(), OS);
+  OS << ", via This)\n";
+}
+
 void UseFact::dump(llvm::raw_ostream &OS, const LoanManager &,
                    const OriginManager &OM,
                    const LoanPropagationAnalysis *) const {
diff --git a/clang/lib/Analysis/LifetimeSafety/FactsGenerator.cpp b/clang/lib/Analysis/LifetimeSafety/FactsGenerator.cpp
index 2457b8270cb80..113f52e612f5b 100644
--- a/clang/lib/Analysis/LifetimeSafety/FactsGenerator.cpp
+++ b/clang/lib/Analysis/LifetimeSafety/FactsGenerator.cpp
@@ -855,6 +855,13 @@ void FactsGenerator::handleExitBlock() {
             FactMgr.createFact<GlobalEscapeFact>(O.ID, VD));
       }
     }
+
+  // A borrow captured via [[clang::lifetime_capture_by_this]] flows into the
+  // never-expiring `this` origin, so it is not otherwise live at the captured
+  // local's expiry. Keep `this` live at exit so the dangle is caught.
+  if (auto ThisOrigins = FactMgr.getOriginMgr().getThisOrigins())
+    EscapesInCurrentBlock.push_back(FactMgr.createFact<ThisEscapeFact>(
+        (*ThisOrigins)->getOuterOriginID(), AC.getDecl()->getEndLoc()));
 }
 
 void FactsGenerator::handleGSLPointerConstruction(const CXXConstructExpr *CCE) {
diff --git a/clang/lib/Analysis/LifetimeSafety/LiveOrigins.cpp b/clang/lib/Analysis/LifetimeSafety/LiveOrigins.cpp
index 7f827a2865782..cc9ee66ab0f86 100644
--- a/clang/lib/Analysis/LifetimeSafety/LiveOrigins.cpp
+++ b/clang/lib/Analysis/LifetimeSafety/LiveOrigins.cpp
@@ -69,6 +69,8 @@ static SourceLocation GetFactLoc(CausingFactType F) {
       return FieldEsc->getFieldDecl()->getLocation();
     if (auto *GlobalEsc = dyn_cast<GlobalEscapeFact>(OEF))
       return GlobalEsc->getGlobal()->getLocation();
+    if (auto *ThisEsc = dyn_cast<ThisEscapeFact>(OEF))
+      return ThisEsc->getLoc();
   }
   llvm_unreachable("unhandled causing fact in PointerUnion");
 }
diff --git a/clang/lib/Sema/SemaLifetimeSafety.h b/clang/lib/Sema/SemaLifetimeSafety.h
index 620032c27f955..b14315ee393ba 100644
--- a/clang/lib/Sema/SemaLifetimeSafety.h
+++ b/clang/lib/Sema/SemaLifetimeSafety.h
@@ -157,6 +157,25 @@ class LifetimeSafetySemaHelperImpl : public LifetimeSafetySemaHelper {
         << UseExpr->getSourceRange();
   }
 
+  void reportUseAfterScope(const Expr *IssueExpr, SourceLocation UseLoc,
+                           const Expr *MovedExpr,
+                           SourceLocation FreeLoc) override {
+    unsigned DiagID = MovedExpr
+                          ? diag::warn_lifetime_safety_use_after_scope_moved
+                          : diag::warn_lifetime_safety_use_after_scope;
+    std::string DestroyedSubject = getDiagSubjectDescription(IssueExpr);
+
+    S.Diag(IssueExpr->getExprLoc(), DiagID)
+        << DestroyedSubject << IssueExpr->getSourceRange();
+    if (MovedExpr)
+      S.Diag(MovedExpr->getExprLoc(), diag::note_lifetime_safety_moved_here)
+          << MovedExpr->getSourceRange();
+    S.Diag(FreeLoc, diag::note_lifetime_safety_destroyed_here)
+        << DestroyedSubject;
+
+    S.Diag(UseLoc, diag::note_lifetime_safety_used_here);
+  }
+
   void reportUseAfterReturn(const Expr *IssueExpr, const Expr *ReturnExpr,
                             const Expr *MovedExpr) override {
     unsigned DiagID = MovedExpr
diff --git a/clang/test/Sema/LifetimeSafety/noescape-violation.cpp b/clang/test/Sema/LifetimeSafety/noescape-violation.cpp
index 9978850a92e51..0ee36d240903b 100644
--- a/clang/test/Sema/LifetimeSafety/noescape-violation.cpp
+++ b/clang/test/Sema/LifetimeSafety/noescape-violation.cpp
@@ -192,6 +192,18 @@ int* return_spaced_brackets(int* p [ [clang::noescape] /*some comment*/ ]) { //
   return p; // expected-note {{returned here}}
 }
 
+// FIXME: A [[clang::noescape]] parameter captured into the object via
+// [[clang::lifetime_capture_by_this]] escapes the function and should be
+// diagnosed. It currently is not: the escape is modeled as a ThisEscapeFact at
+// exit, which does not feed the noescape-violation machinery.
+struct CaptureByThisNoescape {
+  const int *p;
+  void store(const int &x [[clang::lifetime_capture_by_this]]);
+  void captures_noescape(const int &n [[clang::noescape]]) {
+    store(n); // FIXME-warning: parameter is marked [[clang::noescape]] but escapes
+  }
+};
+
 namespace callable_wrappers {
 
 std::function<void()> escape_noescape_via_function(int &x [[clang::noescape]]) { // expected-warning {{parameter is marked [[clang::noescape]] but escapes}}
diff --git a/clang/test/Sema/LifetimeSafety/safety.cpp b/clang/test/Sema/LifetimeSafety/safety.cpp
index cd16a4d723f84..23799fef3fc2c 100644
--- a/clang/test/Sema/LifetimeSafety/safety.cpp
+++ b/clang/test/Sema/LifetimeSafety/safety.cpp
@@ -4766,3 +4766,30 @@ void asm_inout_operand_is_read() {
 }
 } // namespace class_reads
 } // namespace what_is_a_use
+
+// A borrow captured into the implicit object via
+// [[clang::lifetime_capture_by_this]] that outlives the captured local is
+// caught at the capturing method's exit.
+struct CaptureByThis {
+  int member;
+  const int *p;
+  void store(const int &x [[clang::lifetime_capture_by_this]]);
+  void captures_dangling_local() {
+    int local = 0;
+    store(local); // expected-warning {{local variable 'local' does not live long enough}}
+  }               // expected-note {{local variable 'local' is destroyed here}} expected-note {{later used here}}
+  void captures_in_nested_scope() {
+    {
+      int local = 0;
+      store(local); // expected-warning {{local variable 'local' does not live long enough}}
+    }               // expected-note {{local variable 'local' is destroyed here}}
+  }                 // expected-note {{later used here}}
+  // Negative: capturing a caller-scoped reference into `this` does not dangle.
+  void captures_caller_ref(const int &caller_ref) {
+    store(caller_ref);
+  }
+  // Negative: capturing a member (same lifetime as the object) does not dangle.
+  void captures_member() {
+    store(member);
+  }
+};



More information about the cfe-commits mailing list