clang 24.0.0git
Checker.cpp
Go to the documentation of this file.
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
15#include "clang/AST/Decl.h"
16#include "clang/AST/Expr.h"
26#include "llvm/ADT/DenseMap.h"
27#include "llvm/Support/ErrorHandling.h"
28#include "llvm/Support/TimeProfiler.h"
29
31
33 switch (K) {
35 return true;
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::DenseSet<const Decl *> VerifiedLiftimeboundEscapes;
64 const LoanPropagationAnalysis &LoanPropagation;
65 const MovedLoansAnalysis &MovedLoans;
66 const LiveOriginsAnalysis &LiveOrigins;
67 FactManager &FactMgr;
68 LifetimeSafetySemaHelper *SemaHelper;
69 ASTContext &AST;
70 const CFG *Cfg;
71 const Decl *FD;
72 const LifetimeSafetyOpts &LSOpts;
73
74 static SourceLocation
75 GetFactLoc(llvm::PointerUnion<const UseFact *, const OriginEscapesFact *> F) {
76 if (const auto *UF = F.dyn_cast<const UseFact *>())
77 return UF->getUseExpr()->getExprLoc();
78 if (const auto *OEF = F.dyn_cast<const OriginEscapesFact *>()) {
79 if (auto *ReturnEsc = dyn_cast<ReturnEscapeFact>(OEF))
80 return ReturnEsc->getReturnExpr()->getExprLoc();
81 if (auto *FieldEsc = dyn_cast<FieldEscapeFact>(OEF))
82 return FieldEsc->getFieldDecl()->getLocation();
83 }
84 llvm_unreachable("unhandled causing fact in PointerUnion");
85 }
86
87public:
88 LifetimeChecker(const LoanPropagationAnalysis &LoanPropagation,
89 const MovedLoansAnalysis &MovedLoans,
90 const LiveOriginsAnalysis &LiveOrigins, FactManager &FM,
91 AnalysisDeclContext &ADC,
92 LifetimeSafetySemaHelper *SemaHelper,
93 const LifetimeSafetyOpts &LSOpts)
94 : LoanPropagation(LoanPropagation), MovedLoans(MovedLoans),
95 LiveOrigins(LiveOrigins), FactMgr(FM), SemaHelper(SemaHelper),
96 AST(ADC.getASTContext()), Cfg(ADC.getCFG()), FD(ADC.getDecl()),
97 LSOpts(LSOpts) {
98 for (const CFGBlock *B : *ADC.getAnalysis<PostOrderCFGView>())
99 for (const Fact *F : FactMgr.getFacts(B))
100 if (const auto *EF = F->getAs<ExpireFact>())
101 checkExpiry(EF);
102 else if (const auto *IOF = F->getAs<InvalidateOriginFact>())
103 checkInvalidation(IOF);
104 else if (const auto *OEF = F->getAs<OriginEscapesFact>())
105 checkAnnotations(OEF);
106 issuePendingWarnings();
107 suggestAnnotations();
108 reportNoescapeViolations();
109 reportLifetimeboundViolations();
110 reportMisplacedLifetimebound();
111 reportInapplicableLifetimebound();
112 // Annotation inference is currently guarded by a frontend flag. In the
113 // future, this might be replaced by a design that differentiates between
114 // explicit and inferred findings with separate warning groups.
115 if (AST.getLangOpts().EnableLifetimeSafetyInference)
116 inferAnnotations();
117 }
118
119 /// Checks if an escaping origin holds a placeholder loan, indicating a
120 /// missing [[clang::lifetimebound]] annotation or a violation of
121 /// [[clang::noescape]].
122 void checkAnnotations(const OriginEscapesFact *OEF) {
123 OriginID EscapedOID = OEF->getEscapedOriginID();
124 LoanSet EscapedLoans = LoanPropagation.getLoans(EscapedOID, OEF);
125 auto CheckParam = [&](const ParmVarDecl *PVD, bool IsMoved) {
126 // NoEscape param should not escape.
127 if (PVD->hasAttr<NoEscapeAttr>()) {
128 if (auto *ReturnEsc = dyn_cast<ReturnEscapeFact>(OEF))
129 NoescapeWarningsMap.try_emplace(PVD, ReturnEsc->getReturnExpr());
130 if (auto *FieldEsc = dyn_cast<FieldEscapeFact>(OEF))
131 NoescapeWarningsMap.try_emplace(PVD, FieldEsc->getFieldDecl());
132 if (auto *GlobalEsc = dyn_cast<GlobalEscapeFact>(OEF))
133 NoescapeWarningsMap.try_emplace(PVD, GlobalEsc->getGlobal());
134 return;
135 }
136 // Skip annotation suggestion for moved loans, as ownership transfer
137 // obscures the lifetime relationship (e.g., shared_ptr from unique_ptr).
138 if (IsMoved)
139 return;
140 if (PVD->hasAttr<LifetimeBoundAttr>()) {
141 // Track that this lifetimebound parameter correctly escapes
142 // (via return or via field assignment in a constructor).
143 if (isa<ReturnEscapeFact>(OEF) ||
145 VerifiedLiftimeboundEscapes.insert(PVD);
146 } else {
147 // Otherwise, suggest lifetimebound for parameter escaping through
148 // return or a field in constructor.
149 if (auto *ReturnEsc = dyn_cast<ReturnEscapeFact>(OEF))
150 AnnotationWarningsMap.try_emplace(PVD, ReturnEsc->getReturnExpr());
151 else if (auto *FieldEsc = dyn_cast<FieldEscapeFact>(OEF);
152 FieldEsc && isa<CXXConstructorDecl>(FD))
153 AnnotationWarningsMap.try_emplace(PVD, FieldEsc->getFieldDecl());
154 }
155 // TODO: Suggest lifetime_capture_by(this) for parameter escaping to a
156 // field!
157 };
158 auto CheckImplicitThis = [&](const CXXMethodDecl *MD) {
159 if (auto *ReturnEsc = dyn_cast<ReturnEscapeFact>(OEF)) {
161 VerifiedLiftimeboundEscapes.insert(MD);
162 else
163 AnnotationWarningsMap.try_emplace(MD, ReturnEsc->getReturnExpr());
164 }
165 };
166 auto MovedAtEscape = MovedLoans.getMovedLoans(OEF);
167 for (LoanID LID : EscapedLoans) {
168 const Loan *L = FactMgr.getLoanMgr().getLoan(LID);
169 const PlaceholderBase *PB = L->getAccessPath().getAsPlaceholderBase();
170 if (!PB)
171 continue;
172 if (const auto *PVD = PB->getParmVarDecl())
173 CheckParam(PVD, /*IsMoved=*/MovedAtEscape.lookup(LID));
174 else if (const auto *MD = PB->getImplicitThisParent())
175 CheckImplicitThis(MD);
176 }
177 }
178
179 /// Checks for use-after-free & use-after-return errors when an access path
180 /// expires (e.g., a variable goes out of scope).
181 ///
182 /// When a path expires, all loans prefixed by that path expire. For example,
183 /// if `x` expires, loans to `x`, `x.field`, and `x.field.*` all expire.
184 /// This method examines all live origins and reports warnings for loans they
185 /// hold that are prefixed by the expired path.
186 void checkExpiry(const ExpireFact *EF) {
187 const AccessPath &ExpiredPath = EF->getAccessPath();
188 LiveOriginSet Origins = LiveOrigins.getLiveOriginsAt(EF);
189 for (const LivenessMap &Live : {Origins.Persistent, Origins.BlockLocal})
190 for (auto &[OID, LiveInfo] : Live) {
191 LoanSet HeldLoans = LoanPropagation.getLoans(OID, EF);
192 for (LoanID HeldLoanID : HeldLoans) {
193 const Loan *HeldLoan = FactMgr.getLoanMgr().getLoan(HeldLoanID);
194 if (!ExpiredPath.isPrefixOf(HeldLoan->getAccessPath()))
195 continue;
196 // HeldLoan is expired because its base or itself is expired.
197 PendingWarning &CurWarning = FinalWarningsMap[HeldLoan->getID()];
198 const Expr *MovedExpr = nullptr;
199 if (auto *ME = MovedLoans.getMovedLoans(EF).lookup(HeldLoanID))
200 MovedExpr = *ME;
201 // Skip if we already have a dominating causing fact.
202 if (CurWarning.CausingFactDominatesExpiry)
203 continue;
204 if (causingFactDominatesExpiry(LiveInfo.Kind))
205 CurWarning.CausingFactDominatesExpiry = true;
206 CurWarning.CausingFact = LiveInfo.CausingFact;
207 CurWarning.ExpiryLoc = EF->getExpiryLoc();
208 CurWarning.MovedExpr = MovedExpr;
209 CurWarning.InvalidatedByExpr = nullptr;
210 }
211 }
212 }
213
214 /// Checks for use-after-invalidation errors when a container is modified.
215 ///
216 /// When a container is invalidated, loans pointing into its interior are
217 /// invalidated. For example, if container `v` is invalidated, iterators with
218 /// loans to `v.*` are invalidated. This method finds live origins holding
219 /// such loans and reports warnings. A loan is invalidated if its path extends
220 /// an invalidated container's path (e.g., `v.*` extends `v`).
221 void checkInvalidation(const InvalidateOriginFact *IOF) {
222 OriginID InvalidatedOrigin = IOF->getInvalidatedOrigin();
223 /// Get loans directly pointing to the invalidated container
224 LoanSet DirectlyInvalidatedLoans =
225 LoanPropagation.getLoans(InvalidatedOrigin, IOF);
226 auto IsInvalidated = [&](const Loan *L) {
227 for (LoanID InvalidID : DirectlyInvalidatedLoans) {
228 const Loan *InvalidL = FactMgr.getLoanMgr().getLoan(InvalidID);
229 if (InvalidL->getAccessPath().isPrefixOf(L->getAccessPath()))
230 return true;
231 }
232 return false;
233 };
234 // For each live origin, check if it holds an invalidated loan and report.
235 LiveOriginSet Origins = LiveOrigins.getLiveOriginsAt(IOF);
236 for (const LivenessMap &Live : {Origins.Persistent, Origins.BlockLocal})
237 for (auto &[OID, LiveInfo] : Live) {
238 LoanSet HeldLoans = LoanPropagation.getLoans(OID, IOF);
239 for (LoanID LiveLoanID : HeldLoans)
240 if (IsInvalidated(FactMgr.getLoanMgr().getLoan(LiveLoanID))) {
241 bool CurDomination = causingFactDominatesExpiry(LiveInfo.Kind);
242 bool LastDomination =
243 FinalWarningsMap.lookup(LiveLoanID).CausingFactDominatesExpiry;
244 if (!LastDomination) {
245 FinalWarningsMap[LiveLoanID] = {
246 /*ExpiryLoc=*/{},
247 /*CausingFact=*/LiveInfo.CausingFact,
248 /*MovedExpr=*/nullptr,
249 /*InvalidatedByExpr=*/IOF->getInvalidationExpr(),
250 /*CausingFactDominatesExpiry=*/CurDomination};
251 }
252 }
253 }
254 }
255
256 void issuePendingWarnings() {
257 if (!SemaHelper)
258 return;
259 for (const auto &[LID, Warning] : FinalWarningsMap) {
260 const Loan *L = FactMgr.getLoanMgr().getLoan(LID);
261 const Expr *IssueExpr = L->getIssueExpr();
262 const ParmVarDecl *InvalidatedPVD = nullptr;
263 if (const PlaceholderBase *PB = L->getAccessPath().getAsPlaceholderBase())
264 InvalidatedPVD = PB->getParmVarDecl();
265
266 llvm::PointerUnion<const UseFact *, const OriginEscapesFact *>
267 CausingFact = Warning.CausingFact;
268 const Expr *MovedExpr = Warning.MovedExpr;
269 SourceLocation ExpiryLoc = Warning.ExpiryLoc;
270
271 if (const auto *UF = CausingFact.dyn_cast<const UseFact *>()) {
272 llvm::SmallVector<const Expr *> ExprChain =
273 getExprChain(LoanPropagation.buildOriginFlowChain(UF, LID, Cfg));
274 if (Warning.InvalidatedByExpr) {
275 if (IssueExpr)
276 // Use-after-invalidation of an object on stack.
277 SemaHelper->reportUseAfterInvalidation(IssueExpr, UF->getUseExpr(),
278 Warning.InvalidatedByExpr,
279 ExprChain);
280 else if (InvalidatedPVD)
281 // Use-after-invalidation of a parameter.
282 SemaHelper->reportUseAfterInvalidation(
283 InvalidatedPVD, UF->getUseExpr(), Warning.InvalidatedByExpr,
284 ExprChain);
285
286 } else
287 // Scope-based expiry (use-after-scope).
288 SemaHelper->reportUseAfterScope(IssueExpr, UF->getUseExpr(),
289 MovedExpr, ExpiryLoc, ExprChain);
290
291 } else if (const auto *OEF =
292 CausingFact.dyn_cast<const OriginEscapesFact *>()) {
293 if (Warning.InvalidatedByExpr) {
294 if (const auto *FieldEscape = dyn_cast<FieldEscapeFact>(OEF)) {
295 // Invalidated object escapes to a field.
296 if (IssueExpr)
297 // Invalidated object on stack escapes to a field.
298 SemaHelper->reportInvalidatedField(IssueExpr,
299 FieldEscape->getFieldDecl(),
300 Warning.InvalidatedByExpr);
301 else if (InvalidatedPVD)
302 // Invalidated parameter escapes to a field.
303 SemaHelper->reportInvalidatedField(InvalidatedPVD,
304 FieldEscape->getFieldDecl(),
305 Warning.InvalidatedByExpr);
306 } else if (const auto *GlobalEscape =
307 dyn_cast<GlobalEscapeFact>(OEF)) {
308 // Invalidated object escapes to global or static storage.
309 if (IssueExpr)
310 // Invalidated object on stack escapes to global or static
311 // storage.
312 SemaHelper->reportInvalidatedGlobal(IssueExpr,
313 GlobalEscape->getGlobal(),
314 Warning.InvalidatedByExpr);
315 else if (InvalidatedPVD)
316 // Invalidated parameter escapes to global or static storage.
317 SemaHelper->reportInvalidatedGlobal(InvalidatedPVD,
318 GlobalEscape->getGlobal(),
319 Warning.InvalidatedByExpr);
320 } else if (isa<ReturnEscapeFact>(OEF)) {
321 // FIXME: Diagnose invalidated return escapes separately.
322 } else
323 llvm_unreachable("Unhandled OriginEscapesFact type");
324 } else if (const auto *RetEscape = dyn_cast<ReturnEscapeFact>(OEF))
325 // Return stack address.
326 SemaHelper->reportUseAfterReturn(
327 IssueExpr, RetEscape->getReturnExpr(), MovedExpr);
328 else if (const auto *FieldEscape = dyn_cast<FieldEscapeFact>(OEF)) {
329 // Dangling field.
330 bool IsCapturedByLambda =
331 FactMgr.isFieldCapturedByLambda(FieldEscape->getFieldDecl());
332 SemaHelper->reportDanglingField(
333 IssueExpr, FieldEscape->getFieldDecl(), MovedExpr,
334 IsCapturedByLambda, ExpiryLoc);
335 } else if (const auto *GlobalEscape = dyn_cast<GlobalEscapeFact>(OEF))
336 // Global escape.
337 SemaHelper->reportDanglingGlobal(IssueExpr, GlobalEscape->getGlobal(),
338 MovedExpr, ExpiryLoc);
339 else
340 llvm_unreachable("Unhandled OriginEscapesFact type");
341 } else
342 llvm_unreachable("Unhandled CausingFact type");
343 }
344 }
345
346 // Returns declarations that should be annotated with lifetime attributes
347 // in order to annotate FDef: the canonical declaration and the earliest
348 // redeclarations in each other file. This defines the placement policy for
349 // lifetime annotations. Each target is paired with its corresponding warning
350 // scope.
351 llvm::SmallVector<std::pair<const FunctionDecl *, WarningScope>, 2>
352 getTargetDeclsForAttr(const FunctionDecl *FDef) {
353 if (!FDef)
354 return {};
355
356 assert(FDef->isThisDeclarationADefinition() &&
357 "Expected FunctionDecl to be a definition");
358
359 const auto &SM = FDef->getASTContext().getSourceManager();
360
361 auto GetFile = [&SM](const FunctionDecl *FD) {
362 return SM.getFileID(SM.getExpansionLoc(FD->getLocation()));
363 };
364
365 const FileID DefFile = GetFile(FDef);
366 const FunctionDecl *CanonicalDecl = FDef->getCanonicalDecl();
367 llvm::SmallVector<std::pair<const FunctionDecl *, WarningScope>, 2> Targets{
368 {CanonicalDecl, GetFile(CanonicalDecl) == DefFile
371
372 // Find the earliest redeclaration in each file other than the definition
373 // file.
374 auto AddCrossTUDecl = [&](const FunctionDecl *FD) {
375 FileID File = GetFile(FD);
376 if (File == DefFile)
377 return;
378 for (auto [SeenFD, _] : Targets)
379 if (GetFile(SeenFD) == File)
380 return;
381 Targets.push_back({FD, WarningScope::CrossTU});
382 };
383
384 // We iterate in reverse order (from most recent to oldest) to find
385 // the first declaration in each file.
386
387 // Store in temporary variable to manually extend lifetime
388 auto redecls = llvm::to_vector(FDef->redecls());
389
390 for (const FunctionDecl *Redecl : llvm::reverse(redecls))
391 AddCrossTUDecl(Redecl);
392
393 return Targets;
394 }
395
396 void suggestWithScopeForParmVar(const ParmVarDecl *PVD,
397 EscapingTarget EscapeTarget) {
398 if (llvm::isa<const VarDecl *>(EscapeTarget))
399 return;
400
401 for (auto [Decl, Scope] : getTargetDeclsForAttr(cast<FunctionDecl>(FD))) {
402 const auto *ParmToAnnotate =
403 Decl->getParamDecl(PVD->getFunctionScopeIndex());
404 SemaHelper->suggestLifetimeboundToParmVar(Scope, ParmToAnnotate,
405 EscapeTarget);
406 }
407 }
408
409 void suggestWithScopeForImplicitThis(const CXXMethodDecl *MD,
410 const Expr *EscapeExpr) {
411 for (auto [Decl, Scope] : getTargetDeclsForAttr(MD)) {
412 SemaHelper->suggestLifetimeboundToImplicitThis(
413 Scope, cast<CXXMethodDecl>(Decl), EscapeExpr);
414 }
415 }
416
417 void suggestAnnotations() {
418 if (!SemaHelper)
419 return;
420 if (!LSOpts.SuggestAnnotations)
421 return;
422 llvm::TimeTraceScope TimeTrace("SuggestAnnotations");
423 for (auto [Target, EscapeTarget] : AnnotationWarningsMap) {
424 if (const auto *PVD = Target.dyn_cast<const ParmVarDecl *>())
425 suggestWithScopeForParmVar(PVD, EscapeTarget);
426 else if (const auto *MD = Target.dyn_cast<const CXXMethodDecl *>()) {
427 if (const auto *EscapeExpr = EscapeTarget.dyn_cast<const Expr *>())
428 suggestWithScopeForImplicitThis(MD, EscapeExpr);
429 else
430 llvm_unreachable("Implicit this can only escape via Expr (return)");
431 }
432 }
433 }
434
435 void reportNoescapeViolations() {
436 for (auto [PVD, EscapeTarget] : NoescapeWarningsMap) {
437 if (const auto *E = EscapeTarget.dyn_cast<const Expr *>())
438 SemaHelper->reportNoescapeViolation(PVD, E);
439 else if (const auto *FD = EscapeTarget.dyn_cast<const FieldDecl *>())
440 SemaHelper->reportNoescapeViolation(PVD, FD);
441 else if (const auto *G = EscapeTarget.dyn_cast<const VarDecl *>())
442 SemaHelper->reportNoescapeViolation(PVD, G);
443 else
444 llvm_unreachable("Unhandled EscapingTarget type");
445 }
446 }
447
448 void reportLifetimeboundViolations() {
449 if (!isa<FunctionDecl>(FD))
450 return;
451 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD);
453 !VerifiedLiftimeboundEscapes.contains(MD))
454 SemaHelper->reportLifetimeboundViolation(MD);
455 for (const ParmVarDecl *PVD : cast<FunctionDecl>(FD)->parameters()) {
456 if (!PVD->hasAttr<LifetimeBoundAttr>())
457 continue;
458 bool isImplicit = PVD->getAttr<LifetimeBoundAttr>()->isImplicit();
459 bool Escapes = VerifiedLiftimeboundEscapes.contains(PVD);
460 assert((!isImplicit || Escapes || isInStlNamespace(FD)) &&
461 "Implicit lifetimebound parameters "
462 "should escape through return");
463 if (!isImplicit && !Escapes)
464 SemaHelper->reportLifetimeboundViolation(PVD);
465 }
466 }
467
468 // Reports lifetimebound attributes that are placed on a function definition
469 // but not on the corresponding declaration.
470 void reportMisplacedLifetimebound() {
471 const FunctionDecl *FDef = dyn_cast<FunctionDecl>(FD);
472 if (!FDef)
473 return;
474
475 auto TargetDecls = getTargetDeclsForAttr(FDef);
476 // Check if implicit 'this' has lifetimebound on definition but not on
477 // declaration.
478 if (const auto *MDef = dyn_cast<CXXMethodDecl>(FDef);
480 for (auto [Decl, Scope] : TargetDecls) {
481 const auto *MDecl = cast<CXXMethodDecl>(Decl);
483 SemaHelper->reportMisplacedLifetimebound(Scope, MDef, MDecl);
484 }
485
486 // Check each parameter for explicit lifetimebound on definition but not on
487 // declaration.
488 for (const auto *PDef : FDef->parameters()) {
489 const auto *Attr = PDef->getAttr<LifetimeBoundAttr>();
490 if (!Attr || Attr->isImplicit())
491 continue;
492 for (auto [Decl, Scope] : TargetDecls) {
493 const auto *PDecl = Decl->getParamDecl(PDef->getFunctionScopeIndex());
494 if (!PDecl->hasAttr<LifetimeBoundAttr>())
495 SemaHelper->reportMisplacedLifetimebound(Scope, PDef, PDecl);
496 }
497 }
498 }
499
500 void reportInapplicableLifetimebound() {
501 const auto *FDef = dyn_cast<FunctionDecl>(FD);
502 if (!FDef)
503 return;
504
505 // If analyzed function is a template definition or an implicit
506 // instantiation, skip.
507 if (FDef->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate ||
508 FDef->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
509 return;
510
511 for (const auto &PVD : FDef->parameters())
512 if (PVD->hasAttr<LifetimeBoundAttr>() &&
513 !FactMgr.getOriginMgr().hasOrigins(PVD->getType(),
514 /*IntrinsicOnly=*/true))
515 SemaHelper->reportInapplicableLifetimebound(PVD);
516 }
517
518 void inferAnnotations() {
519 for (auto [Target, EscapeTarget] : AnnotationWarningsMap) {
520 if (const auto *MD = Target.dyn_cast<const CXXMethodDecl *>()) {
522 SemaHelper->addLifetimeBoundToImplicitThis(cast<CXXMethodDecl>(MD));
523 } else if (const auto *PVD = Target.dyn_cast<const ParmVarDecl *>()) {
524 const auto *FD = dyn_cast<FunctionDecl>(PVD->getDeclContext());
525 if (!FD)
526 continue;
527 // Propagates inferred attributes via the most recent declaration to
528 // ensure visibility for callers in post-order analysis.
530 ParmVarDecl *InferredPVD = const_cast<ParmVarDecl *>(
531 FD->getParamDecl(PVD->getFunctionScopeIndex()));
532 if (!InferredPVD->hasAttr<LifetimeBoundAttr>())
533 InferredPVD->addAttr(
534 LifetimeBoundAttr::CreateImplicit(AST, PVD->getLocation()));
535 }
536 }
537 }
538
539 /// Extract expressions from the origin flow chain for diagnostic purposes.
540 ///
541 /// Given a chain of origins that shows how a loan propagates, this function
542 /// extracts the corresponding expressions for each origin. Origins that refer
543 /// to declarations (rather than expressions) are skipped.
544 llvm::SmallVector<const Expr *>
545 getExprChain(llvm::ArrayRef<OriginID> OriginFlowChain) {
546 llvm::SmallVector<const Expr *> rs;
547 for (const OriginID CurrOID : OriginFlowChain)
548 if (const Expr *CurrExpr =
549 FactMgr.getOriginMgr().getOrigin(CurrOID).getExpr())
550 rs.push_back(CurrExpr);
551 return rs;
552 }
553};
554} // namespace
555
557 const MovedLoansAnalysis &MovedLoans,
558 const LiveOriginsAnalysis &LO, FactManager &FactMgr,
560 LifetimeSafetySemaHelper *SemaHelper,
561 const LifetimeSafetyOpts &LSOpts) {
562 llvm::TimeTraceScope TimeProfile("LifetimeChecker");
563 LifetimeChecker Checker(LP, MovedLoans, LO, FactMgr, ADC, SemaHelper, LSOpts);
564}
565
566} // namespace clang::lifetimes::internal
This file defines AnalysisDeclContext, a class that manages the analysis context data for context sen...
Defines the clang::SourceLocation class and associated facilities.
Defines the SourceManager interface.
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:223
AnalysisDeclContext contains the context data for the function, method or block under analysis.
Represents a source-level, intra-procedural CFG that represents the control-flow of a Stmt.
Definition CFG.h:1271
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
This represents one expression.
Definition Expr.h:112
Encodes a location in the source.
Abstract interface for operations requiring Sema access.
llvm::PointerUnion< const Expr *, const FieldDecl *, const VarDecl * > EscapingTarget
utils::ID< struct LoanTag > LoanID
Definition Loans.h:27
utils::ID< struct OriginTag > OriginID
Definition Origins.h:28
static bool causingFactDominatesExpiry(LivenessKind K)
Definition Checker.cpp:32
utils::SetTy< LoanID > LoanSet
void runLifetimeChecker(const LoanPropagationAnalysis &LoanPropagation, const MovedLoansAnalysis &MovedLoans, const LiveOriginsAnalysis &LiveOrigins, FactManager &FactMgr, AnalysisDeclContext &ADC, LifetimeSafetySemaHelper *SemaHelper, const LifetimeSafetyOpts &LSOpts)
Runs the lifetime checker, which detects use-after-free errors by examining loan expiration points an...
Definition Checker.cpp:556
utils::MapTy< OriginID, LivenessInfo > LivenessMap
Definition LiveOrigins.h:76
const LifetimeBoundAttr * getDirectImplicitObjectLifetimeBoundAttr(const FunctionDecl *FD)
bool implicitObjectParamIsLifetimeBound(const FunctionDecl *FD)
const LifetimeBoundAttr * getImplicitObjectParamLifetimeBoundAttr(const FunctionDecl *FD)
const FunctionDecl * getDeclWithMergedLifetimeBoundAttrs(const FunctionDecl *FD)
bool isInStlNamespace(const Decl *D)
std::variant< struct RequiresDecl, struct HeaderDecl, struct UmbrellaDirDecl, struct ModuleDecl, struct ExcludeDecl, struct ExportDecl, struct ExportAsDecl, struct ExternModuleDecl, struct UseDecl, struct LinkDecl, struct ConfigMacrosDecl, struct ConflictDecl > Decl
All declarations that can appear in a module declaration.
bool isa(CodeGen::Address addr)
Definition Address.h:330
if(T->getSizeExpr()) TRY_TO(TraverseStmt(const_cast< Expr * >(T -> getSizeExpr())))
for(const auto &A :T->param_types())
@ TSK_ImplicitInstantiation
This template specialization was implicitly instantiated from a template.
Definition Specifiers.h:195
U cast(CodeGen::Address addr)
Definition Address.h:327