1//===- Checker.cpp - C++ Lifetime Safety Checker ----------------*- 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 implements the LifetimeChecker, which detects use-after-free
10// errors by checking if live origins hold loans that have expired.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/Analysis/Analyses/LifetimeSafety/Checker.h"
15#include "clang/AST/Decl.h"
16#include "clang/AST/Expr.h"
17#include "clang/Analysis/Analyses/LifetimeSafety/Facts.h"
18#include "clang/Analysis/Analyses/LifetimeSafety/LifetimeAnnotations.h"
19#include "clang/Analysis/Analyses/LifetimeSafety/LiveOrigins.h"
20#include "clang/Analysis/Analyses/LifetimeSafety/LoanPropagation.h"
21#include "clang/Analysis/Analyses/LifetimeSafety/Loans.h"
22#include "clang/Analysis/Analyses/PostOrderCFGView.h"
23#include "clang/Analysis/AnalysisDeclContext.h"
24#include "clang/Basic/SourceLocation.h"
25#include "clang/Basic/SourceManager.h"
26#include "llvm/ADT/DenseMap.h"
27#include "llvm/Support/ErrorHandling.h"
28#include "llvm/Support/TimeProfiler.h"
29
30namespace clang::lifetimes::internal {
31
32static bool causingFactDominatesExpiry(LivenessKind K) {
33 switch (K) {
34 case LivenessKind::Must:
35 return true;
36 case LivenessKind::Maybe:
37 case LivenessKind::Dead:
38 return false;
39 }
40 llvm_unreachable("unknown liveness kind");
41}
42
43namespace {
44
45/// Struct to store the complete context for a potential lifetime violation.
46struct PendingWarning {
47 SourceLocation ExpiryLoc; // Where the loan expired.
48 llvm::PointerUnion<const UseFact *, const OriginEscapesFact *> CausingFact;
49 const Expr *MovedExpr;
50 const Expr *InvalidatedByExpr;
51 bool CausingFactDominatesExpiry;
52};
53
54using AnnotationTarget =
55 llvm::PointerUnion<const ParmVarDecl *, const CXXMethodDecl *>;
56using EscapingTarget = LifetimeSafetySemaHelper::EscapingTarget;
57
58class LifetimeChecker {
59private:
60 llvm::DenseMap<LoanID, PendingWarning> FinalWarningsMap;
61 llvm::DenseMap<AnnotationTarget, EscapingTarget> AnnotationWarningsMap;
62 llvm::DenseMap<const ParmVarDecl *, EscapingTarget> NoescapeWarningsMap;
63 llvm::DenseMap<const FieldDecl *, const Expr *> FieldOriginEscapesMap;
64 llvm::DenseSet<const Decl *> VerifiedLiftimeboundEscapes;
65 const LoanPropagationAnalysis &LoanPropagation;
66 const MovedLoansAnalysis &MovedLoans;
67 const LiveOriginsAnalysis &LiveOrigins;
68 FactManager &FactMgr;
69 LifetimeSafetySemaHelper *SemaHelper;
70 ASTContext &AST;
71 const CFG *Cfg;
72 const Decl *FD;
73 const LifetimeSafetyOpts &LSOpts;
74
75 static SourceLocation
76 GetFactLoc(llvm::PointerUnion<const UseFact *, const OriginEscapesFact *> F) {
77 if (const auto *UF = dyn_cast<const UseFact *>(Val&: F))
78 return UF->getUseExpr()->getExprLoc();
79 if (const auto *OEF = dyn_cast<const OriginEscapesFact *>(Val&: F)) {
80 if (auto *ReturnEsc = dyn_cast<ReturnEscapeFact>(Val: OEF))
81 return ReturnEsc->getReturnExpr()->getExprLoc();
82 if (auto *FieldEsc = dyn_cast<FieldEscapeFact>(Val: OEF))
83 return FieldEsc->getFieldDecl()->getLocation();
84 }
85 llvm_unreachable("unhandled causing fact in PointerUnion");
86 }
87
88public:
89 LifetimeChecker(const LoanPropagationAnalysis &LoanPropagation,
90 const MovedLoansAnalysis &MovedLoans,
91 const LiveOriginsAnalysis &LiveOrigins, FactManager &FM,
92 AnalysisDeclContext &ADC,
93 LifetimeSafetySemaHelper *SemaHelper,
94 const LifetimeSafetyOpts &LSOpts)
95 : LoanPropagation(LoanPropagation), MovedLoans(MovedLoans),
96 LiveOrigins(LiveOrigins), FactMgr(FM), SemaHelper(SemaHelper),
97 AST(ADC.getASTContext()), Cfg(ADC.getCFG()), FD(ADC.getDecl()),
98 LSOpts(LSOpts) {
99 for (const CFGBlock *B : *ADC.getAnalysis<PostOrderCFGView>())
100 for (const Fact *F : FactMgr.getFacts(B))
101 if (const auto *EF = F->getAs<ExpireFact>())
102 checkExpiry(EF);
103 else if (const auto *IOF = F->getAs<InvalidateOriginFact>())
104 checkInvalidation(IOF);
105 else if (const auto *OEF = F->getAs<OriginEscapesFact>())
106 checkAnnotations(OEF);
107 issuePendingWarnings();
108 suggestAnnotations();
109 if (LSOpts.CheckFieldOriginEscape)
110 reportFieldOriginEscapes();
111 if (LSOpts.CheckNoescapeViolations)
112 reportNoescapeViolations();
113 if (LSOpts.CheckLifetimeboundViolations)
114 reportLifetimeboundViolations();
115 if (LSOpts.CheckMisplacedLifetimebound)
116 reportMisplacedLifetimebound();
117 if (LSOpts.CheckInapplicableLifetimebound)
118 reportInapplicableLifetimebound();
119 // Annotation inference is currently guarded by a frontend flag. In the
120 // future, this might be replaced by a design that differentiates between
121 // explicit and inferred findings with separate warning groups.
122 if (AST.getLangOpts().EnableLifetimeSafetyInference)
123 inferAnnotations();
124 }
125
126 /// Checks if an escaping origin holds a placeholder loan, indicating a
127 /// missing [[clang::lifetimebound]] annotation or a violation of
128 /// [[clang::noescape]].
129 void checkAnnotations(const OriginEscapesFact *OEF) {
130 OriginID EscapedOID = OEF->getEscapedOriginID();
131 LoanSet EscapedLoans = LoanPropagation.getLoans(OID: EscapedOID, P: OEF);
132 auto CheckParam = [&](const ParmVarDecl *PVD, bool IsMoved) {
133 // NoEscape param should not escape.
134 if (PVD->hasAttr<NoEscapeAttr>()) {
135 if (auto *ReturnEsc = dyn_cast<ReturnEscapeFact>(Val: OEF))
136 NoescapeWarningsMap.try_emplace(Key: PVD, Args: ReturnEsc->getReturnExpr());
137 if (auto *FieldEsc = dyn_cast<FieldEscapeFact>(Val: OEF))
138 NoescapeWarningsMap.try_emplace(Key: PVD, Args: FieldEsc->getFieldDecl());
139 if (auto *GlobalEsc = dyn_cast<GlobalEscapeFact>(Val: OEF))
140 NoescapeWarningsMap.try_emplace(Key: PVD, Args: GlobalEsc->getGlobal());
141 return;
142 }
143 // Skip annotation suggestion for moved loans, as ownership transfer
144 // obscures the lifetime relationship (e.g., shared_ptr from unique_ptr).
145 if (IsMoved)
146 return;
147 if (PVD->hasAttr<LifetimeBoundAttr>()) {
148 // Track that this lifetimebound parameter correctly escapes
149 // (via return or via field assignment in a constructor).
150 if (isa<ReturnEscapeFact>(Val: OEF) ||
151 (isa<FieldEscapeFact>(Val: OEF) && isa<CXXConstructorDecl>(Val: FD)))
152 VerifiedLiftimeboundEscapes.insert(V: PVD);
153 } else {
154 // Otherwise, suggest lifetimebound for parameter escaping through
155 // return or a field in constructor.
156 if (auto *ReturnEsc = dyn_cast<ReturnEscapeFact>(Val: OEF))
157 AnnotationWarningsMap.try_emplace(Key: PVD, Args: ReturnEsc->getReturnExpr());
158 else if (auto *FieldEsc = dyn_cast<FieldEscapeFact>(Val: OEF);
159 FieldEsc && isa<CXXConstructorDecl>(Val: FD)) {
160 // Disable inference for pointers being captured by an owner type,
161 // as owners typically consume these pointers rather than borrow them.
162 if (!isOwnerPtrCtor(Ctor: dyn_cast<CXXConstructorDecl>(Val: FD), PVD))
163 AnnotationWarningsMap.try_emplace(Key: PVD, Args: FieldEsc->getFieldDecl());
164 }
165 }
166 // TODO: Suggest lifetime_capture_by(this) for parameter escaping to a
167 // field!
168 };
169 auto CheckImplicitThis = [&](const CXXMethodDecl *MD) {
170 if (auto *ReturnEsc = dyn_cast<ReturnEscapeFact>(Val: OEF)) {
171 if (implicitObjectParamIsLifetimeBound(FD: MD))
172 VerifiedLiftimeboundEscapes.insert(V: MD);
173 else
174 AnnotationWarningsMap.try_emplace(Key: MD, Args: ReturnEsc->getReturnExpr());
175 }
176 };
177 // Identifies methods whose return value derives from a field's origin
178 // rather than *this, e.g., Span::data() or Vector::data().
179 auto CheckField = [&](const FieldDecl *Field) {
180 if (!LSOpts.CheckFieldOriginEscape)
181 return;
182 // Lifetimebound marks the field as owned by *this (e.g., Vector::data()).
183 const auto *MD = dyn_cast<CXXMethodDecl>(Val: FD);
184 if (MD && implicitObjectParamIsLifetimeBound(FD: MD))
185 return;
186 if (auto *ReturnEsc = dyn_cast<ReturnEscapeFact>(Val: OEF)) {
187 // Ignore field loans in inner origins, e.g., returning a reference to
188 // a view field borrows *this.
189 if (OriginList *RetList = FactMgr.getOriginMgr().getOrCreateList(
190 E: ReturnEsc->getReturnExpr());
191 RetList && RetList->getOuterOriginID() == EscapedOID)
192 FieldOriginEscapesMap.try_emplace(Key: Field, Args: ReturnEsc->getReturnExpr());
193 }
194 };
195 auto MovedAtEscape = MovedLoans.getMovedLoans(P: OEF);
196 for (LoanID LID : EscapedLoans) {
197 const Loan *L = FactMgr.getLoanMgr().getLoan(ID: LID);
198 const PlaceholderBase *PB = L->getAccessPath().getAsPlaceholderBase();
199 if (!PB)
200 continue;
201 if (const auto *PVD = PB->getParmVarDecl())
202 CheckParam(PVD, /*IsMoved=*/MovedAtEscape.lookup(K: LID));
203 else if (const auto *MD = PB->getImplicitThisParent())
204 CheckImplicitThis(MD);
205 else if (const auto *Field = PB->getFieldDecl())
206 CheckField(Field);
207 }
208 }
209
210 /// Checks for use-after-free & use-after-return errors when an access path
211 /// expires (e.g., a variable goes out of scope).
212 ///
213 /// When a path expires, all loans prefixed by that path expire. For example,
214 /// if `x` expires, loans to `x`, `x.field`, and `x.field.*` all expire.
215 /// This method examines all live origins and reports warnings for loans they
216 /// hold that are prefixed by the expired path.
217 void checkExpiry(const ExpireFact *EF) {
218 const AccessPath &ExpiredPath = EF->getAccessPath();
219 LiveOriginSet Origins = LiveOrigins.getLiveOriginsAt(P: EF);
220 for (const LivenessMap &Live : {Origins.Persistent, Origins.BlockLocal})
221 for (auto &[OID, LiveInfo] : Live) {
222 LoanSet HeldLoans = LoanPropagation.getLoans(OID, P: EF);
223 for (LoanID HeldLoanID : HeldLoans) {
224 const Loan *HeldLoan = FactMgr.getLoanMgr().getLoan(ID: HeldLoanID);
225 if (!ExpiredPath.isPrefixOf(Other: HeldLoan->getAccessPath()))
226 continue;
227 // HeldLoan is expired because its base or itself is expired.
228 PendingWarning &CurWarning = FinalWarningsMap[HeldLoan->getID()];
229 const Expr *MovedExpr = nullptr;
230 if (auto *ME = MovedLoans.getMovedLoans(P: EF).lookup(K: HeldLoanID))
231 MovedExpr = *ME;
232 // Skip if we already have a dominating causing fact.
233 if (CurWarning.CausingFactDominatesExpiry)
234 continue;
235 if (causingFactDominatesExpiry(K: LiveInfo.Kind))
236 CurWarning.CausingFactDominatesExpiry = true;
237 CurWarning.CausingFact = LiveInfo.CausingFact;
238 CurWarning.ExpiryLoc = EF->getExpiryLoc();
239 CurWarning.MovedExpr = MovedExpr;
240 CurWarning.InvalidatedByExpr = nullptr;
241 }
242 }
243 }
244
245 /// Checks for use-after-invalidation errors when a container is modified.
246 ///
247 /// When a container is invalidated, loans pointing into its interior are
248 /// invalidated. For example, if container `v` is invalidated, iterators with
249 /// loans to `v.*` are invalidated. This method finds live origins holding
250 /// such loans and reports warnings. A loan is invalidated if its path extends
251 /// an invalidated container's path (e.g., `v.*` extends `v`).
252 void checkInvalidation(const InvalidateOriginFact *IOF) {
253 OriginID InvalidatedOrigin = IOF->getInvalidatedOrigin();
254 /// Get loans directly pointing to the invalidated container
255 LoanSet DirectlyInvalidatedLoans =
256 LoanPropagation.getLoans(OID: InvalidatedOrigin, P: IOF);
257 auto IsInvalidated = [&](const Loan *L) {
258 for (LoanID InvalidID : DirectlyInvalidatedLoans) {
259 const Loan *InvalidL = FactMgr.getLoanMgr().getLoan(ID: InvalidID);
260 if (InvalidL->getAccessPath().isPrefixOf(Other: L->getAccessPath()))
261 return true;
262 }
263 return false;
264 };
265 // For each live origin, check if it holds an invalidated loan and report.
266 LiveOriginSet Origins = LiveOrigins.getLiveOriginsAt(P: IOF);
267 for (const LivenessMap &Live : {Origins.Persistent, Origins.BlockLocal})
268 for (auto &[OID, LiveInfo] : Live) {
269 LoanSet HeldLoans = LoanPropagation.getLoans(OID, P: IOF);
270 for (LoanID LiveLoanID : HeldLoans)
271 if (IsInvalidated(FactMgr.getLoanMgr().getLoan(ID: LiveLoanID))) {
272 bool CurDomination = causingFactDominatesExpiry(K: LiveInfo.Kind);
273 bool LastDomination =
274 FinalWarningsMap.lookup(Val: LiveLoanID).CausingFactDominatesExpiry;
275 if (!LastDomination) {
276 FinalWarningsMap[LiveLoanID] = {
277 /*ExpiryLoc=*/{},
278 /*CausingFact=*/LiveInfo.CausingFact,
279 /*MovedExpr=*/nullptr,
280 /*InvalidatedByExpr=*/IOF->getInvalidationExpr(),
281 /*CausingFactDominatesExpiry=*/CurDomination};
282 }
283 }
284 }
285 }
286
287 void issuePendingWarnings() {
288 llvm::TimeTraceScope TimeTrace("IssuePendingWarnings");
289 if (!SemaHelper)
290 return;
291 for (const auto &[LID, Warning] : FinalWarningsMap) {
292 const Loan *L = FactMgr.getLoanMgr().getLoan(ID: LID);
293 const Expr *IssueExpr = L->getIssueExpr();
294 const ParmVarDecl *InvalidatedPVD = nullptr;
295 if (const PlaceholderBase *PB = L->getAccessPath().getAsPlaceholderBase())
296 InvalidatedPVD = PB->getParmVarDecl();
297
298 llvm::PointerUnion<const UseFact *, const OriginEscapesFact *>
299 CausingFact = Warning.CausingFact;
300 const Expr *MovedExpr = Warning.MovedExpr;
301 SourceLocation ExpiryLoc = Warning.ExpiryLoc;
302
303 if (const auto *UF = dyn_cast<const UseFact *>(Val&: CausingFact)) {
304 llvm::SmallVector<const Expr *> ExprChain =
305 getExprChain(OriginFlowChain: LoanPropagation.buildOriginFlowChain(UF, TargetLoan: LID, Cfg));
306 if (Warning.InvalidatedByExpr) {
307 if (IssueExpr)
308 // Use-after-invalidation of an object on stack.
309 SemaHelper->reportUseAfterInvalidation(IssueExpr, UseExpr: UF->getUseExpr(),
310 InvalidationExpr: Warning.InvalidatedByExpr,
311 ExprChain);
312 else if (InvalidatedPVD)
313 // Use-after-invalidation of a parameter.
314 SemaHelper->reportUseAfterInvalidation(
315 PVD: InvalidatedPVD, UseExpr: UF->getUseExpr(), InvalidationExpr: Warning.InvalidatedByExpr,
316 ExprChain);
317
318 } else
319 // Scope-based expiry (use-after-scope).
320 SemaHelper->reportUseAfterScope(IssueExpr, UseExpr: UF->getUseExpr(),
321 MovedExpr, FreeLoc: ExpiryLoc, ExprChain);
322
323 } else if (const auto *OEF =
324 dyn_cast<const OriginEscapesFact *>(Val&: CausingFact)) {
325 if (Warning.InvalidatedByExpr) {
326 if (const auto *FieldEscape = dyn_cast<FieldEscapeFact>(Val: OEF)) {
327 // Invalidated object escapes to a field.
328 if (IssueExpr)
329 // Invalidated object on stack escapes to a field.
330 SemaHelper->reportInvalidatedField(IssueExpr,
331 Field: FieldEscape->getFieldDecl(),
332 InvalidationExpr: Warning.InvalidatedByExpr);
333 else if (InvalidatedPVD)
334 // Invalidated parameter escapes to a field.
335 SemaHelper->reportInvalidatedField(PVD: InvalidatedPVD,
336 Field: FieldEscape->getFieldDecl(),
337 InvalidationExpr: Warning.InvalidatedByExpr);
338 } else if (const auto *GlobalEscape =
339 dyn_cast<GlobalEscapeFact>(Val: OEF)) {
340 // Invalidated object escapes to global or static storage.
341 if (IssueExpr)
342 // Invalidated object on stack escapes to global or static
343 // storage.
344 SemaHelper->reportInvalidatedGlobal(IssueExpr,
345 Global: GlobalEscape->getGlobal(),
346 InvalidationExpr: Warning.InvalidatedByExpr);
347 else if (InvalidatedPVD)
348 // Invalidated parameter escapes to global or static storage.
349 SemaHelper->reportInvalidatedGlobal(PVD: InvalidatedPVD,
350 Global: GlobalEscape->getGlobal(),
351 InvalidationExpr: Warning.InvalidatedByExpr);
352 } else if (isa<ReturnEscapeFact>(Val: OEF)) {
353 // FIXME: Diagnose invalidated return escapes separately.
354 } else
355 llvm_unreachable("Unhandled OriginEscapesFact type");
356 } else if (const auto *RetEscape = dyn_cast<ReturnEscapeFact>(Val: OEF)) {
357 // Return stack address.
358 SemaHelper->reportUseAfterReturn(
359 IssueExpr, ReturnExpr: RetEscape->getReturnExpr(), MovedExpr,
360 ExprChain: getExprChain(
361 OriginFlowChain: LoanPropagation.buildOriginFlowChain(OEF, TargetLoan: LID, Cfg)));
362 } else if (const auto *FieldEscape = dyn_cast<FieldEscapeFact>(Val: OEF)) {
363 // Dangling field.
364 bool IsCapturedByLambda =
365 FactMgr.isFieldCapturedByLambda(FD: FieldEscape->getFieldDecl());
366 SemaHelper->reportDanglingField(
367 IssueExpr, Field: FieldEscape->getFieldDecl(), MovedExpr,
368 IsCapturedByLambda, ExpiryLoc);
369 } else if (const auto *GlobalEscape = dyn_cast<GlobalEscapeFact>(Val: OEF)) {
370 // Global escape.
371 bool IsMain = false;
372 if (const auto *Func = dyn_cast_if_present<FunctionDecl>(Val: FD))
373 IsMain = Func->isMain();
374 SemaHelper->reportDanglingGlobal(IssueExpr, DanglingGlobal: GlobalEscape->getGlobal(),
375 MovedExpr, ExpiryLoc, IsMain);
376 } else
377 llvm_unreachable("Unhandled OriginEscapesFact type");
378 } else
379 llvm_unreachable("Unhandled CausingFact type");
380 }
381 }
382
383 // Returns declarations that should be annotated with lifetime attributes
384 // in order to annotate FDef: the canonical declaration and the earliest
385 // redeclarations in each other file. This defines the placement policy for
386 // lifetime annotations. Each target is paired with its corresponding warning
387 // scope.
388 llvm::SmallVector<std::pair<const FunctionDecl *, WarningScope>, 2>
389 getTargetDeclsForAttr(const FunctionDecl *FDef) {
390 if (!FDef)
391 return {};
392
393 assert(FDef->isThisDeclarationADefinition() &&
394 "Expected FunctionDecl to be a definition");
395
396 const auto &SM = FDef->getASTContext().getSourceManager();
397
398 auto GetFile = [&SM](const FunctionDecl *FD) {
399 return SM.getFileID(SpellingLoc: SM.getExpansionLoc(Loc: FD->getLocation()));
400 };
401
402 const FileID DefFile = GetFile(FDef);
403 const FunctionDecl *CanonicalDecl = FDef->getCanonicalDecl();
404 llvm::SmallVector<std::pair<const FunctionDecl *, WarningScope>, 2> Targets{
405 {CanonicalDecl, GetFile(CanonicalDecl) == DefFile
406 ? WarningScope::IntraTU
407 : WarningScope::CrossTU}};
408
409 // Find the earliest redeclaration in each file other than the definition
410 // file.
411 auto AddCrossTUDecl = [&](const FunctionDecl *FD) {
412 FileID File = GetFile(FD);
413 if (File == DefFile)
414 return;
415 for (auto [SeenFD, _] : Targets)
416 if (GetFile(SeenFD) == File)
417 return;
418 Targets.push_back(Elt: {FD, WarningScope::CrossTU});
419 };
420
421 // We iterate in reverse order (from most recent to oldest) to find
422 // the first declaration in each file.
423
424 // Store in temporary variable to manually extend lifetime
425 auto redecls = llvm::to_vector(Range: FDef->redecls());
426
427 for (const FunctionDecl *Redecl : llvm::reverse(C&: redecls))
428 AddCrossTUDecl(Redecl);
429
430 return Targets;
431 }
432
433 void suggestWithScopeForParmVar(const ParmVarDecl *PVD,
434 EscapingTarget EscapeTarget) {
435 if (llvm::isa<const VarDecl *>(Val: EscapeTarget))
436 return;
437
438 for (auto [Decl, Scope] : getTargetDeclsForAttr(FDef: cast<FunctionDecl>(Val: FD))) {
439 const auto *ParmToAnnotate =
440 Decl->getParamDecl(i: PVD->getFunctionScopeIndex());
441 SemaHelper->suggestLifetimeboundToParmVar(Scope, ParmToAnnotate,
442 Target: EscapeTarget);
443 }
444 }
445
446 void suggestWithScopeForImplicitThis(const CXXMethodDecl *MD,
447 const Expr *EscapeExpr) {
448 for (auto [Decl, Scope] : getTargetDeclsForAttr(FDef: MD)) {
449 SemaHelper->suggestLifetimeboundToImplicitThis(
450 Scope, MD: cast<CXXMethodDecl>(Val: Decl), EscapeExpr);
451 }
452 }
453
454 void suggestAnnotations() {
455 if (!SemaHelper)
456 return;
457 if (!LSOpts.SuggestAnnotations)
458 return;
459 llvm::TimeTraceScope TimeTrace("SuggestAnnotations");
460 for (auto [Target, EscapeTarget] : AnnotationWarningsMap) {
461 if (const auto *PVD = dyn_cast<const ParmVarDecl *>(Val&: Target))
462 suggestWithScopeForParmVar(PVD, EscapeTarget);
463 else if (const auto *MD = dyn_cast<const CXXMethodDecl *>(Val&: Target)) {
464 if (const auto *EscapeExpr = dyn_cast<const Expr *>(Val&: EscapeTarget))
465 suggestWithScopeForImplicitThis(MD, EscapeExpr);
466 else
467 llvm_unreachable("Implicit this can only escape via Expr (return)");
468 }
469 }
470 }
471
472 void reportFieldOriginEscapes() {
473 if (!SemaHelper)
474 return;
475 const auto *MD = dyn_cast<CXXMethodDecl>(Val: FD);
476 if (!MD)
477 return;
478 llvm::TimeTraceScope TimeTrace("ReportFieldOriginEscapes");
479 for (auto [Field, EscapeExpr] : FieldOriginEscapesMap)
480 SemaHelper->reportFieldOriginEscape(MD, FD: Field, EscapeExpr);
481 }
482
483 void reportNoescapeViolations() {
484 llvm::TimeTraceScope TimeTrace("ReportNoescapeViolations");
485 for (auto [PVD, EscapeTarget] : NoescapeWarningsMap) {
486 if (const auto *E = dyn_cast<const Expr *>(Val&: EscapeTarget))
487 SemaHelper->reportNoescapeViolation(ParmWithNoescape: PVD, EscapeExpr: E);
488 else if (const auto *FD = dyn_cast<const FieldDecl *>(Val&: EscapeTarget))
489 SemaHelper->reportNoescapeViolation(ParmWithNoescape: PVD, EscapeField: FD);
490 else if (const auto *G = dyn_cast<const VarDecl *>(Val&: EscapeTarget))
491 SemaHelper->reportNoescapeViolation(ParmWithNoescape: PVD, EscapeGlobal: G);
492 else
493 llvm_unreachable("Unhandled EscapingTarget type");
494 }
495 }
496
497 void reportLifetimeboundViolations() {
498 llvm::TimeTraceScope TimeTrace("ReportLifetimeboundViolations");
499 if (!isa<FunctionDecl>(Val: FD))
500 return;
501 if (const auto *MD = dyn_cast<CXXMethodDecl>(Val: FD);
502 MD && getImplicitObjectParamLifetimeBoundAttr(FD: MD) &&
503 !VerifiedLiftimeboundEscapes.contains(V: MD))
504 SemaHelper->reportLifetimeboundViolation(MDWithLifetimebound: MD);
505 for (const ParmVarDecl *PVD : cast<FunctionDecl>(Val: FD)->parameters()) {
506 if (!PVD->hasAttr<LifetimeBoundAttr>())
507 continue;
508 bool isImplicit = PVD->getAttr<LifetimeBoundAttr>()->isImplicit();
509 bool Escapes = VerifiedLiftimeboundEscapes.contains(V: PVD);
510 assert((!isImplicit || Escapes || isInStlNamespace(FD)) &&
511 "Implicit lifetimebound parameters "
512 "should escape through return");
513 if (!isImplicit && !Escapes)
514 SemaHelper->reportLifetimeboundViolation(ParmWithLifetimebound: PVD);
515 }
516 }
517
518 // Reports lifetimebound attributes that are placed on a function definition
519 // but not on the corresponding declaration.
520 void reportMisplacedLifetimebound() {
521 llvm::TimeTraceScope TimeTrace("ReportMisplacedLifetimebound");
522 const FunctionDecl *FDef = dyn_cast<FunctionDecl>(Val: FD);
523 if (!FDef)
524 return;
525
526 auto TargetDecls = getTargetDeclsForAttr(FDef);
527 // Check if implicit 'this' has lifetimebound on definition but not on
528 // declaration.
529 if (const auto *MDef = dyn_cast<CXXMethodDecl>(Val: FDef);
530 MDef && getDirectImplicitObjectLifetimeBoundAttr(FD: MDef))
531 for (auto [Decl, Scope] : TargetDecls) {
532 const auto *MDecl = cast<CXXMethodDecl>(Val: Decl);
533 if (!getDirectImplicitObjectLifetimeBoundAttr(FD: MDecl))
534 SemaHelper->reportMisplacedLifetimebound(Scope, FDef: MDef, FDecl: MDecl);
535 }
536
537 // Check each parameter for explicit lifetimebound on definition but not on
538 // declaration.
539 for (const auto *PDef : FDef->parameters()) {
540 const auto *Attr = PDef->getAttr<LifetimeBoundAttr>();
541 if (!Attr || Attr->isImplicit())
542 continue;
543 for (auto [Decl, Scope] : TargetDecls) {
544 const auto *PDecl = Decl->getParamDecl(i: PDef->getFunctionScopeIndex());
545 if (!PDecl->hasAttr<LifetimeBoundAttr>())
546 SemaHelper->reportMisplacedLifetimebound(Scope, PVDDef: PDef, PVDDecl: PDecl);
547 }
548 }
549 }
550
551 void reportInapplicableLifetimebound() {
552 llvm::TimeTraceScope TimeTrace("ReportInapplicableLifetimebound");
553 const auto *FDef = dyn_cast<FunctionDecl>(Val: FD);
554 if (!FDef)
555 return;
556
557 // If analyzed function is a template definition or an implicit
558 // instantiation, skip.
559 if (FDef->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate ||
560 FDef->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
561 return;
562
563 for (const auto &PVD : FDef->parameters())
564 if (PVD->hasAttr<LifetimeBoundAttr>() &&
565 !FactMgr.getOriginMgr().hasOrigins(QT: PVD->getType(),
566 /*IntrinsicOnly=*/true))
567 SemaHelper->reportInapplicableLifetimebound(PVD);
568 }
569
570 void inferAnnotations() {
571 for (auto [Target, EscapeTarget] : AnnotationWarningsMap) {
572 if (const auto *MD = dyn_cast<const CXXMethodDecl *>(Val&: Target)) {
573 if (!implicitObjectParamIsLifetimeBound(FD: MD))
574 SemaHelper->addLifetimeBoundToImplicitThis(MD: cast<CXXMethodDecl>(Val: MD));
575 } else if (const auto *PVD = dyn_cast<const ParmVarDecl *>(Val&: Target)) {
576 const auto *FD = dyn_cast<FunctionDecl>(Val: PVD->getDeclContext());
577 if (!FD)
578 continue;
579 // Propagates inferred attributes via the most recent declaration to
580 // ensure visibility for callers in post-order analysis.
581 FD = getDeclWithMergedLifetimeBoundAttrs(FD);
582 ParmVarDecl *InferredPVD = const_cast<ParmVarDecl *>(
583 FD->getParamDecl(i: PVD->getFunctionScopeIndex()));
584 if (!InferredPVD->hasAttr<LifetimeBoundAttr>())
585 InferredPVD->addAttr(
586 A: LifetimeBoundAttr::CreateImplicit(Ctx&: AST, Range: PVD->getLocation()));
587 }
588 }
589 }
590
591 /// Extract expressions from the origin flow chain for diagnostic purposes.
592 ///
593 /// Given a chain of origins that shows how a loan propagates, this function
594 /// extracts the corresponding expressions for each origin. Origins that refer
595 /// to declarations (rather than expressions) are skipped.
596 llvm::SmallVector<const Expr *>
597 getExprChain(llvm::ArrayRef<OriginID> OriginFlowChain) {
598 llvm::SmallVector<const Expr *> rs;
599 for (const OriginID CurrOID : OriginFlowChain)
600 if (const Expr *CurrExpr =
601 FactMgr.getOriginMgr().getOrigin(ID: CurrOID).getExpr())
602 rs.push_back(Elt: CurrExpr);
603 return rs;
604 }
605};
606} // namespace
607
608void runLifetimeChecker(const LoanPropagationAnalysis &LP,
609 const MovedLoansAnalysis &MovedLoans,
610 const LiveOriginsAnalysis &LO, FactManager &FactMgr,
611 AnalysisDeclContext &ADC,
612 LifetimeSafetySemaHelper *SemaHelper,
613 const LifetimeSafetyOpts &LSOpts) {
614 llvm::TimeTraceScope TimeProfile("LifetimeChecker");
615 LifetimeChecker Checker(LP, MovedLoans, LO, FactMgr, ADC, SemaHelper, LSOpts);
616}
617
618} // namespace clang::lifetimes::internal
619