clang 24.0.0git
LifetimeSafety.h
Go to the documentation of this file.
1//===- LifetimeSafety.h - C++ Lifetime Safety Analysis -*----------- C++-*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file defines the main entry point and orchestrator for the C++ Lifetime
10// Safety Analysis. It coordinates the entire analysis pipeline: fact
11// generation, loan propagation, live origins analysis, and enforcement of
12// lifetime safety policy.
13//
14// The analysis is based on the concepts of "origins" and "loans" to track
15// pointer lifetimes and detect issues like use-after-free and dangling
16// pointers. See the RFC for more details:
17// https://discourse.llvm.org/t/rfc-intra-procedural-lifetime-analysis-in-clang/86291
18//
19//===----------------------------------------------------------------------===//
20#ifndef LLVM_CLANG_ANALYSIS_ANALYSES_LIFETIMESAFETY_H
21#define LLVM_CLANG_ANALYSIS_ANALYSES_LIFETIMESAFETY_H
22
23#include "clang/AST/Decl.h"
31#include "llvm/ADT/PointerUnion.h"
32#include <cstddef>
33#include <memory>
34
35namespace clang {
36class LifetimeCaptureByAttr;
37} // namespace clang
38
39namespace clang::lifetimes {
40
42 /// Maximum number of CFG blocks to analyze. Functions with larger CFGs will
43 /// be skipped.
44 size_t MaxCFGBlocks = 0;
45
46 /// Whether to suggest lifetime annotations.
47 bool SuggestAnnotations = false;
48
54 /// Whether to model non-trivial destructors at scope exit as uses.
55 bool CheckDestructorUses = false;
57};
58
59/// Enum to track functions visible across or within TU.
60enum class WarningScope {
61 CrossTU, // For warnings on declarations visible across Translation Units.
62 IntraTU // For warnings on functions local to a Translation Unit.
63};
64
65/// Abstract interface for operations requiring Sema access.
66///
67/// This class exists to break a circular dependency: the LifetimeSafety
68/// analysis target cannot directly depend on clangSema (which would create the
69/// cycle: clangSema -> clangAnalysis -> clangAnalysisLifetimeSafety ->
70/// clangSema).
71///
72/// Instead, this interface is implemented in AnalysisBasedWarnings.cpp (part of
73/// clangSema), allowing the analysis to report diagnostics and modify the AST
74/// through Sema without introducing a circular dependency.
76public:
78 virtual ~LifetimeSafetySemaHelper() = default;
79
80 virtual void reportUseAfterScope(const Expr *IssueExpr, const UseSite &Use,
81 const Expr *MovedExpr,
82 SourceLocation FreeLoc,
84
85 // TODO: Report where the object was destroyed when that happens before the
86 // return (inner scopes, temporaries).
87 virtual void reportUseAfterReturn(const Expr *IssueExpr,
88 const Expr *ReturnExpr,
89 const Expr *MovedExpr,
91
92 virtual void reportDanglingField(const Expr *IssueExpr,
93 const FieldDecl *Field,
94 const Expr *MovedExpr,
95 bool IsCapturedByLambda,
96 SourceLocation ExpiryLoc,
98
99 virtual void reportDanglingGlobal(const Expr *IssueExpr,
100 const VarDecl *DanglingGlobal,
101 const Expr *MovedExpr,
102 SourceLocation ExpiryLoc,
104 bool IsMain = false) {}
105
106 // Reports when a reference/iterator is used after the container operation
107 // that invalidated it.
108 virtual void
109 reportUseAfterInvalidation(const Expr *IssueExpr, const UseSite &Use,
110 const Expr *InvalidationExpr,
111 llvm::ArrayRef<const Expr *> ExprChain) {}
112 virtual void
114 const Expr *InvalidationExpr,
115 llvm::ArrayRef<const Expr *> ExprChain) {}
116 virtual void reportInvalidatedField(const Expr *IssueExpr,
117 const FieldDecl *Field,
118 const Expr *InvalidationExpr,
119 llvm::ArrayRef<const Expr *> ExprChain) {}
120 virtual void reportInvalidatedField(const ParmVarDecl *PVD,
121 const FieldDecl *Field,
122 const Expr *InvalidationExpr,
123 llvm::ArrayRef<const Expr *> ExprChain) {}
124 virtual void reportInvalidatedGlobal(const Expr *IssueExpr,
125 const VarDecl *Global,
126 const Expr *InvalidationExpr,
128 }
129 virtual void reportInvalidatedGlobal(const ParmVarDecl *PVD,
130 const VarDecl *Global,
131 const Expr *InvalidationExpr,
133 }
134
136 llvm::PointerUnion<const Expr *, const FieldDecl *, const VarDecl *>;
137
138 // Suggests lifetime bound annotations for function parameters.
140 const ParmVarDecl *ParmToAnnotate,
142
143 // Reports misuse of [[clang::noescape]] when parameter escapes through return
144 virtual void reportNoescapeViolation(const ParmVarDecl *ParmWithNoescape,
145 const Expr *EscapeExpr) {}
146 // Reports misuse of [[clang::noescape]] when parameter escapes through field
147 virtual void reportNoescapeViolation(const ParmVarDecl *ParmWithNoescape,
148 const FieldDecl *EscapeField) {}
149 // Reports misuse of [[clang::noescape]] when parameter escapes through
150 // assignment to a global variable
151 virtual void reportNoescapeViolation(const ParmVarDecl *ParmWithNoescape,
152 const VarDecl *EscapeGlobal) {}
153
154 // Reports misuse of [[clang::lifetimebound]] when parameter doesn't escape
155 // through return.
156 virtual void
157 reportLifetimeboundViolation(const ParmVarDecl *ParmWithLifetimebound) {}
158
159 // Reports misuse of [[clang::lifetimebound]] when implicit this parameter
160 // doesn't escape through return.
161 virtual void
162 reportLifetimeboundViolation(const CXXMethodDecl *MDWithLifetimebound) {}
163
164 // Reports a parameter captured by an entity that its
165 // [[clang::lifetime_capture_by]] attributes do not name. \p CapturerIdx is
166 // the index such an attribute uses for that entity, and \p CapturedBy is the
167 // field or global it is captured by, if known.
168 virtual void reportCaptureByViolation(const ParmVarDecl *PVD,
169 const LifetimeCaptureByAttr *Attr,
170 int CapturerIdx,
171 const ValueDecl *CapturedBy) {}
172
173 // Reports a member function definition that has [[clang::lifetimebound]] on
174 // the implicit this parameter when the canonical declaration does not.
176 const CXXMethodDecl *FDef,
177 const CXXMethodDecl *FDecl) {}
178
179 // Reports a function definition parameter that has [[clang::lifetimebound]]
180 // when the corresponding parameter in the canonical declaration.
182 const ParmVarDecl *PVDDef,
183 const ParmVarDecl *PVDDecl) {}
184
186
187 // Suggests lifetime bound annotations for implicit this.
189 const CXXMethodDecl *MD,
190 const Expr *EscapeExpr) {}
191
192 // Reports when a member function returns an origin of a field.
194 const FieldDecl *FD,
195 const Expr *EscapeExpr) {}
196
197 // Adds inferred lifetime bound attribute for implicit this to its
198 // TypeSourceInfo.
200};
201
202/// The main entry point for the analysis.
204 LifetimeSafetySemaHelper *SemaHelper,
205 const LifetimeSafetyOpts &Opts,
206 LifetimeSafetyStats &Stats, bool CollectStats);
207
208namespace internal {
209
210void collectLifetimeStats(AnalysisDeclContext &AC, OriginManager &OM,
211 LifetimeSafetyStats &Stats);
212
213/// An object to hold the factories for immutable collections, ensuring
214/// that all created states share the same underlying memory management.
216 OriginLoanMap::Factory OriginMapFactory;
217 LoanSet::Factory LoanSetFactory;
218 MovedLoansMap::Factory MovedLoansMapFactory;
219 LivenessMap::Factory LivenessMapFactory;
220};
221
222/// Running the lifetime safety analysis and querying its results. It
223/// encapsulates the various dataflow analyses.
225public:
227 LifetimeSafetySemaHelper *SemaHelper,
228 const LifetimeSafetyOpts &LSOpts);
229
230 void run();
231
232 /// \note These are provided only for testing purposes.
234 return *LoanPropagation;
235 }
236 LiveOriginsAnalysis &getLiveOrigins() const { return *LiveOrigins; }
237 FactManager &getFactManager() { return *FactMgr; }
238
239private:
241 LifetimeSafetySemaHelper *SemaHelper;
242 const LifetimeSafetyOpts LSOpts;
243 LifetimeFactory Factory;
244 std::unique_ptr<FactManager> FactMgr;
245 std::unique_ptr<LiveOriginsAnalysis> LiveOrigins;
246 std::unique_ptr<LoanPropagationAnalysis> LoanPropagation;
247 std::unique_ptr<MovedLoansAnalysis> MovedLoans;
248};
249} // namespace internal
250} // namespace clang::lifetimes
251
252#endif // LLVM_CLANG_ANALYSIS_ANALYSES_LIFETIMESAFETY_H
This file defines AnalysisDeclContext, a class that manages the analysis context data for context sen...
AnalysisDeclContext contains the context data for the function, method or block under analysis.
Attr - This represents one attribute.
Definition Attr.h:47
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2153
This represents one expression.
Definition Expr.h:114
Represents a member of a struct/union/class.
Definition Decl.h:3341
Represents a parameter to a function.
Definition Decl.h:1832
Scope - A scope is a transient data structure that is used while parsing the program.
Definition Scope.h:41
Encodes a location in the source.
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition Decl.h:714
Represents a variable declaration or definition.
Definition Decl.h:934
Abstract interface for operations requiring Sema access.
virtual void reportInapplicableLifetimebound(const ParmVarDecl *PVD)
llvm::PointerUnion< const Expr *, const FieldDecl *, const VarDecl * > EscapingTarget
virtual void suggestLifetimeboundToParmVar(WarningScope Scope, const ParmVarDecl *ParmToAnnotate, EscapingTarget Target)
virtual void reportCaptureByViolation(const ParmVarDecl *PVD, const LifetimeCaptureByAttr *Attr, int CapturerIdx, const ValueDecl *CapturedBy)
virtual void reportInvalidatedField(const ParmVarDecl *PVD, const FieldDecl *Field, const Expr *InvalidationExpr, llvm::ArrayRef< const Expr * > ExprChain)
virtual void reportUseAfterInvalidation(const Expr *IssueExpr, const UseSite &Use, const Expr *InvalidationExpr, llvm::ArrayRef< const Expr * > ExprChain)
virtual void reportUseAfterScope(const Expr *IssueExpr, const UseSite &Use, const Expr *MovedExpr, SourceLocation FreeLoc, llvm::ArrayRef< const Expr * > ExprChain)
virtual void reportInvalidatedGlobal(const Expr *IssueExpr, const VarDecl *Global, const Expr *InvalidationExpr, llvm::ArrayRef< const Expr * > ExprChain)
virtual void reportMisplacedLifetimebound(WarningScope Scope, const ParmVarDecl *PVDDef, const ParmVarDecl *PVDDecl)
virtual void reportInvalidatedField(const Expr *IssueExpr, const FieldDecl *Field, const Expr *InvalidationExpr, llvm::ArrayRef< const Expr * > ExprChain)
virtual void reportFieldOriginEscape(const CXXMethodDecl *MD, const FieldDecl *FD, const Expr *EscapeExpr)
virtual void reportNoescapeViolation(const ParmVarDecl *ParmWithNoescape, const VarDecl *EscapeGlobal)
virtual void reportDanglingField(const Expr *IssueExpr, const FieldDecl *Field, const Expr *MovedExpr, bool IsCapturedByLambda, SourceLocation ExpiryLoc, llvm::ArrayRef< const Expr * > ExprChain)
virtual void reportUseAfterInvalidation(const ParmVarDecl *PVD, const UseSite &Use, const Expr *InvalidationExpr, llvm::ArrayRef< const Expr * > ExprChain)
virtual void reportNoescapeViolation(const ParmVarDecl *ParmWithNoescape, const FieldDecl *EscapeField)
virtual void reportLifetimeboundViolation(const ParmVarDecl *ParmWithLifetimebound)
virtual void addLifetimeBoundToImplicitThis(const CXXMethodDecl *MD)
virtual void reportDanglingGlobal(const Expr *IssueExpr, const VarDecl *DanglingGlobal, const Expr *MovedExpr, SourceLocation ExpiryLoc, llvm::ArrayRef< const Expr * > ExprChain, bool IsMain=false)
virtual void reportNoescapeViolation(const ParmVarDecl *ParmWithNoescape, const Expr *EscapeExpr)
virtual void reportMisplacedLifetimebound(WarningScope Scope, const CXXMethodDecl *FDef, const CXXMethodDecl *FDecl)
virtual void suggestLifetimeboundToImplicitThis(WarningScope Scope, const CXXMethodDecl *MD, const Expr *EscapeExpr)
virtual void reportLifetimeboundViolation(const CXXMethodDecl *MDWithLifetimebound)
virtual void reportInvalidatedGlobal(const ParmVarDecl *PVD, const VarDecl *Global, const Expr *InvalidationExpr, llvm::ArrayRef< const Expr * > ExprChain)
virtual void reportUseAfterReturn(const Expr *IssueExpr, const Expr *ReturnExpr, const Expr *MovedExpr, llvm::ArrayRef< const Expr * > ExprChain)
Where and how an origin is used, for diagnostics.
Definition Facts.h:40
LifetimeSafetyAnalysis(AnalysisDeclContext &AC, LifetimeSafetySemaHelper *SemaHelper, const LifetimeSafetyOpts &LSOpts)
LoanPropagationAnalysis & getLoanPropagation() const
void collectLifetimeStats(AnalysisDeclContext &AC, OriginManager &OM, LifetimeSafetyStats &Stats)
void runLifetimeSafetyAnalysis(AnalysisDeclContext &AC, LifetimeSafetySemaHelper *SemaHelper, const LifetimeSafetyOpts &Opts, LifetimeSafetyStats &Stats, bool CollectStats)
The main entry point for the analysis.
WarningScope
Enum to track functions visible across or within TU.
Top level wrappers for InstallAPI frontend operations.
bool SuggestAnnotations
Whether to suggest lifetime annotations.
size_t MaxCFGBlocks
Maximum number of CFG blocks to analyze.
bool CheckDestructorUses
Whether to model non-trivial destructors at scope exit as uses.
An object to hold the factories for immutable collections, ensuring that all created states share the...