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