https://github.com/Xazax-hun updated https://github.com/llvm/llvm-project/pull/246623
From 2a9c82bd690b14b962e942a19f5bd0c0345c59af Mon Sep 17 00:00:00 2001 From: Gabor Horvath <[email protected]> Date: Fri, 27 Nov 2026 11:14:26 +0000 Subject: [PATCH 1/2] [LifetimeSafety] Collect lifetime-annotated origin types from the CFG Before generating facts, the OriginManager collects the return types of lifetimebound calls by traversing the function body and the constructor initializers with a RecursiveASTVisitor. The analysis builds its CFG with every evaluated statement as an element, so visit those elements instead. This also covers the calls the visitor skipped as implicit code but the facts are generated for, such as those in the default member initializers of a constructor, so a dangling field initialized there is now reported. Calls that only appear in unevaluated operands are no longer collected. On some LLVM TUs (GVN, LiveVariables, RegionStore, SemaExpr) this reduces the instructions of the analysis by 5.0-6.0% (0.37-0.54% of -fsyntax-only). The diagnostics on these TUs are unchanged. Assisted-by: Claude Opus 5.5 --- .../Analysis/Analyses/LifetimeSafety/Facts.h | 2 +- .../Analyses/LifetimeSafety/Origins.h | 15 ++++-- clang/lib/Analysis/LifetimeSafety/Origins.cpp | 53 +++++++++---------- .../dangling-field-implicit-ctor.cpp | 22 ++++++++ 4 files changed, 59 insertions(+), 33 deletions(-) diff --git a/clang/include/clang/Analysis/Analyses/LifetimeSafety/Facts.h b/clang/include/clang/Analysis/Analyses/LifetimeSafety/Facts.h index 7d32db996b356e..9feed1f338f6dc 100644 --- a/clang/include/clang/Analysis/Analyses/LifetimeSafety/Facts.h +++ b/clang/include/clang/Analysis/Analyses/LifetimeSafety/Facts.h @@ -456,7 +456,7 @@ class FactManager { public: FactManager(const AnalysisDeclContext &AC, const CFG &Cfg, llvm::BumpPtrAllocator &Alloc) - : LoanMgr(Alloc), OriginMgr(AC, Alloc), FactAllocator(Alloc) { + : LoanMgr(Alloc), OriginMgr(AC, Cfg, Alloc), FactAllocator(Alloc) { BlockToFacts.resize(Cfg.getNumBlockIDs()); } diff --git a/clang/include/clang/Analysis/Analyses/LifetimeSafety/Origins.h b/clang/include/clang/Analysis/Analyses/LifetimeSafety/Origins.h index 6f672b49387906..a2beaeaa7e0391 100644 --- a/clang/include/clang/Analysis/Analyses/LifetimeSafety/Origins.h +++ b/clang/include/clang/Analysis/Analyses/LifetimeSafety/Origins.h @@ -24,6 +24,10 @@ #include "llvm/Support/Allocator.h" #include "llvm/Support/raw_ostream.h" +namespace clang { +class CFG; +} // namespace clang + namespace clang::lifetimes::internal { using OriginID = utils::ID<struct OriginTag>; @@ -135,7 +139,8 @@ bool doesDeclHaveStorage(const ValueDecl *D); /// variables and expressions. class OriginManager { public: - OriginManager(const AnalysisDeclContext &AC, llvm::BumpPtrAllocator &Alloc); + OriginManager(const AnalysisDeclContext &AC, const CFG &Cfg, + llvm::BumpPtrAllocator &Alloc); /// Gets or creates the OriginList for a given ValueDecl. /// @@ -213,10 +218,10 @@ class OriginManager { void initializeThisOrigins(const Decl *D); - /// Pre-scans the function body (and constructor init lists) to discover - /// return types of lifetime-annotated calls (currently - /// [[clang::lifetimebound]]), registering them for origin tracking. - void collectLifetimeAnnotatedOriginTypes(const AnalysisDeclContext &AC); + /// Pre-scans the calls in the CFG to discover return types of + /// lifetime-annotated calls (currently [[clang::lifetimebound]]), + /// registering them for origin tracking. + void collectLifetimeAnnotatedOriginTypes(const CFG &Cfg); void registerLifetimeAnnotatedOriginType(QualType QT); ASTContext &AST; diff --git a/clang/lib/Analysis/LifetimeSafety/Origins.cpp b/clang/lib/Analysis/LifetimeSafety/Origins.cpp index d5a55d4d3d0d35..15b80c53adb8c4 100644 --- a/clang/lib/Analysis/LifetimeSafety/Origins.cpp +++ b/clang/lib/Analysis/LifetimeSafety/Origins.cpp @@ -19,6 +19,7 @@ #include "clang/Analysis/Analyses/LifetimeSafety/LifetimeAnnotations.h" #include "clang/Analysis/Analyses/LifetimeSafety/LifetimeStats.h" #include "clang/Analysis/AnalysisDeclContext.h" +#include "clang/Analysis/CFG.h" #include "llvm/ADT/StringMap.h" namespace clang::lifetimes::internal { @@ -51,28 +52,24 @@ class MissingOriginCollector LifetimeSafetyStats &LSStats; }; -class LifetimeAnnotatedOriginTypeCollector - : public RecursiveASTVisitor<LifetimeAnnotatedOriginTypeCollector> { +/// Collects the types that need origins because of the lifetime annotations of +/// the functions and constructors called in the CFG. +class LifetimeAnnotatedOriginTypeCollector { public: - bool VisitCallExpr(const CallExpr *CE) { - // Indirect calls (e.g., function pointers) are skipped because lifetime - // annotations currently apply to declarations, not types. - if (const auto *FD = CE->getDirectCallee()) { - collect(FD, FD->getReturnType()); - collectCaptureBy(FD); + void visit(const Stmt *S) { + if (const auto *CE = dyn_cast<CallExpr>(S)) { + // Indirect calls (e.g., function pointers) are skipped because lifetime + // annotations currently apply to declarations, not types. + if (const auto *FD = CE->getDirectCallee()) { + collect(FD, FD->getReturnType()); + collectCaptureBy(FD); + } + } else if (const auto *CCE = dyn_cast<CXXConstructExpr>(S)) { + collect(CCE->getConstructor(), CCE->getType()); + collectCaptureBy(CCE->getConstructor()); } - return true; - } - - bool VisitCXXConstructExpr(const CXXConstructExpr *CCE) { - collect(CCE->getConstructor(), CCE->getType()); - collectCaptureBy(CCE->getConstructor()); - return true; } - bool shouldVisitLambdaBody() const { return false; } - bool shouldVisitTemplateInstantiations() const { return true; } - const llvm::SmallVector<QualType> &getCollectedTypes() const { return CollectedTypes; } @@ -198,10 +195,10 @@ bool doesDeclHaveStorage(const ValueDecl *D) { return !D->getType()->isReferenceType(); } -OriginManager::OriginManager(const AnalysisDeclContext &AC, +OriginManager::OriginManager(const AnalysisDeclContext &AC, const CFG &Cfg, llvm::BumpPtrAllocator &Alloc) : AST(AC.getASTContext()), ListAllocator(Alloc) { - collectLifetimeAnnotatedOriginTypes(AC); + collectLifetimeAnnotatedOriginTypes(Cfg); initializeThisOrigins(AC.getDecl()); } @@ -396,14 +393,16 @@ void OriginManager::collectMissingOrigins(Stmt &FunctionBody, Collector.TraverseStmt(const_cast<Stmt *>(&FunctionBody)); } -void OriginManager::collectLifetimeAnnotatedOriginTypes( - const AnalysisDeclContext &AC) { +void OriginManager::collectLifetimeAnnotatedOriginTypes(const CFG &Cfg) { + // The CFG has every evaluated statement as an element, including the + // constructor initializers and the default member initializers they use (see + // setLifetimeSafetyCFGBuildOptions), so these are the calls the facts are + // generated for. LifetimeAnnotatedOriginTypeCollector Collector; - if (Stmt *Body = AC.getBody()) - Collector.TraverseStmt(Body); - if (const auto *CD = dyn_cast<CXXConstructorDecl>(AC.getDecl())) - for (const auto *Init : CD->inits()) - Collector.TraverseStmt(Init->getInit()); + for (const CFGBlock *Block : Cfg) + for (const CFGElement &Elt : *Block) + if (std::optional<CFGStmt> S = Elt.getAs<CFGStmt>()) + Collector.visit(S->getStmt()); for (QualType QT : Collector.getCollectedTypes()) registerLifetimeAnnotatedOriginType(QT); } diff --git a/clang/test/Sema/LifetimeSafety/dangling-field-implicit-ctor.cpp b/clang/test/Sema/LifetimeSafety/dangling-field-implicit-ctor.cpp index e3ea0f583f06fb..2d08cac048289a 100644 --- a/clang/test/Sema/LifetimeSafety/dangling-field-implicit-ctor.cpp +++ b/clang/test/Sema/LifetimeSafety/dangling-field-implicit-ctor.cpp @@ -47,3 +47,25 @@ struct SafeLiteral { std::string_view v = "literal"; }; void use_safe() { SafeLiteral c; (void)c; } + +// A type that has origins only because a lifetimebound function returns it, +// returned by such a call in a default member initializer. +struct MyObj {}; +struct View { + const MyObj *p; +}; +View makeView(const MyObj &obj [[clang::lifetimebound]]); + +struct ImplicitCtorView { + View view{makeView(MyObj{})}; // expected-warning {{stack memory associated with temporary object escapes to the field 'view' which will dangle}} + // expected-note@-1 {{result of call to 'makeView' aliases the storage of temporary object because parameter 'obj' is marked as lifetimebound}} + // expected-note@-2 {{this field dangles}} +}; +void use_implicit_view() { ImplicitCtorView c; (void)c; } // perfunc-note {{in implicit default constructor for 'ImplicitCtorView' first required here}} + +struct UserCtorView { + View view{makeView(MyObj{})}; // expected-warning {{stack memory associated with temporary object escapes to the field 'view' which will dangle}} + // expected-note@-1 {{result of call to 'makeView' aliases the storage of temporary object because parameter 'obj' is marked as lifetimebound}} + // expected-note@-2 {{this field dangles}} + UserCtorView() {} +}; From 110b84ddbb42abbffe410ce0e4ebbc326ed3840d Mon Sep 17 00:00:00 2001 From: Gabor Horvath <[email protected]> Date: Fri, 27 Nov 2026 12:38:30 +0000 Subject: [PATCH 2/2] [LifetimeSafety][NFC] Test that unevaluated calls are not collected Assisted-by: Claude Opus 5.5 --- clang/test/Sema/LifetimeSafety/safety.cpp | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/clang/test/Sema/LifetimeSafety/safety.cpp b/clang/test/Sema/LifetimeSafety/safety.cpp index 077c5de9648cbf..eb029b098439c0 100644 --- a/clang/test/Sema/LifetimeSafety/safety.cpp +++ b/clang/test/Sema/LifetimeSafety/safety.cpp @@ -3367,6 +3367,28 @@ DefaultedOuter nested_defaulted_outer_with_user_defined_inner() { return copy; // expected-note {{returned here}} } +// Only evaluated lifetimebound calls make their return type tracked. +namespace unevaluated_lifetimebound_call { +struct View { + const int *p; +}; +View makeView(const int &x [[clang::lifetimebound]]); + +View sizeof_only() { + int x; + (void)sizeof(makeView(x)); + View v{&x}; + return v; // no-warning +} + +View evaluated() { + int x; + (void)makeView(x); + View v{&x}; // expected-warning {{stack memory associated with local variable 'x' is returned}} + return v; // expected-note {{returned here}} +} +} // namespace unevaluated_lifetimebound_call + std::string_view getSV(S s [[clang::lifetimebound]]); // FIXME: False negative. Non-pointer/ref/gsl::Pointer parameter types marked _______________________________________________ cfe-commits mailing list [email protected] https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
