clang 24.0.0git
FactsGenerator.cpp
Go to the documentation of this file.
1//===- FactsGenerator.cpp - Lifetime Facts Generation -----------*- 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#include <cassert>
10#include <string>
11
12#include "clang/AST/Decl.h"
13#include "clang/AST/DeclCXX.h"
14#include "clang/AST/Expr.h"
15#include "clang/AST/ExprCXX.h"
22#include "clang/Analysis/CFG.h"
24#include "llvm/ADT/ArrayRef.h"
25#include "llvm/ADT/STLExtras.h"
26#include "llvm/Support/Casting.h"
27#include "llvm/Support/Signals.h"
28#include "llvm/Support/TimeProfiler.h"
29
31using llvm::isa_and_present;
32
33OriginList *FactsGenerator::getOriginsList(const ValueDecl &D) {
34 return FactMgr.getOriginMgr().getOrCreateList(&D);
35}
36OriginList *FactsGenerator::getOriginsList(const Expr &E) {
37 return FactMgr.getOriginMgr().getOrCreateList(&E);
38}
39
40bool FactsGenerator::hasOrigins(QualType QT) const {
41 return FactMgr.getOriginMgr().hasOrigins(QT);
42}
43
44bool FactsGenerator::hasOrigins(const Expr *E) const {
45 return FactMgr.getOriginMgr().hasOrigins(E);
46}
47
48/// Propagates origin information from Src to Dst through all levels of
49/// indirection, creating OriginFlowFacts at each level.
50///
51/// This function enforces a critical type-safety invariant: both lists must
52/// have the same shape (same depth/structure). This invariant ensures that
53/// origins flow only between compatible types during expression evaluation.
54///
55/// Examples:
56/// - `int* p = &x;` flows origins from `&x` (depth 1) to `p` (depth 1)
57/// - `int** pp = &p;` flows origins from `&p` (depth 2) to `pp` (depth 2)
58/// * Level 1: pp <- p's address
59/// * Level 2: (*pp) <- what p points to (i.e., &x)
60/// - `View v = obj;` flows origins from `obj` (depth 1) to `v` (depth 1)
61///
62/// \param Dst The destination origin list.
63/// \param Src The source origin list.
64/// \param Kill If true, the destination's existing loans are killed before
65/// flowing.
66/// \param Block Optional. If provided, the generated flow facts are appended to
67/// this specific CFG block. Otherwise, they are appended to the
68/// current block being visited.
69void FactsGenerator::flow(OriginList *Dst, OriginList *Src, bool Kill,
70 const CFGBlock *Block) {
71 if (!Dst)
72 return;
73 assert(Src &&
74 "Dst is non-null but Src is null. List must have the same length");
75 assert(Dst->getLength() == Src->getLength() &&
76 "Lists must have the same length");
77
78 while (Dst && Src) {
79 Fact *F = FactMgr.createFact<OriginFlowFact>(Dst->getOuterOriginID(),
80 Src->getOuterOriginID(), Kill);
81 if (Block)
82 FactMgr.appendBlockFact(Block, F);
83 else
84 CurrentBlockFacts.push_back(F);
85 Dst = Dst->peelOuterOrigin();
86 Src = Src->peelOuterOrigin();
87 }
88}
89
90/// Creates a loan for the storage path of a given declaration.
91/// This function should be called whenever an expression naming \p VD
92/// represents a borrow.
93/// \param VD The declaration whose storage is borrowed.
94/// \param IssueExpr The expression (DeclRefExpr or MemberExpr) that initiates
95/// the borrow.
96/// \return The new Loan on success, nullptr otherwise.
97static const Loan *createLoan(FactManager &FactMgr, const ValueDecl &VD,
98 const Expr *IssueExpr) {
99 return FactMgr.getLoanMgr().createLoan(AccessPath(&VD), IssueExpr);
100}
101
102/// Creates a loan for the storage location of a temporary object.
103/// \param MTE The MaterializeTemporaryExpr that represents the temporary
104/// binding.
105/// \param IssueExpr The expression the loan is reported at, if not \p MTE.
106/// \return The new Loan.
107static const Loan *createLoan(FactManager &FactMgr,
108 const MaterializeTemporaryExpr *MTE,
109 const Expr *IssueExpr = nullptr) {
110 return FactMgr.getLoanMgr().createLoan(AccessPath(MTE),
111 IssueExpr ? IssueExpr : MTE);
112}
113
114/// Creates a loan for an allocation through 'new'
115/// \param NE The CXXNewExpr that represents the allocation
116/// \return The new Loan on success, nullptr otherwise
117static const Loan *createLoan(FactManager &FactMgr, const CXXNewExpr *NE) {
118 AccessPath Path(NE);
119 return FactMgr.getLoanMgr().createLoan(Path, NE);
120}
121
122/// Creates a loan for a heap allocation made by a call (e.g. a function
123/// annotated with `ownership_returns`, like `malloc`).
124/// \param CE The CallExpr that represents the allocation
125/// \return The new Loan on success, nullptr otherwise
126static const Loan *createNewAllocLoan(FactManager &FactMgr,
127 const CallExpr *CE) {
128 AccessPath Path(CE);
129 return FactMgr.getLoanMgr().createLoan(Path, CE);
130}
131
133 llvm::TimeTraceScope TimeProfile("FactGenerator");
134 const CFG &Cfg = *AC.getCFG();
135 llvm::SmallVector<Fact *> PlaceholderLoanFacts = issuePlaceholderLoans();
136 // Iterate through the CFG blocks in reverse post-order to ensure that
137 // initializations and destructions are processed in the correct sequence.
138 for (const CFGBlock *Block : *AC.getAnalysis<PostOrderCFGView>()) {
139 CurrentBlockFacts.clear();
140 EscapesInCurrentBlock.clear();
141 CurrentBlock = Block;
142 if (Block == &Cfg.getEntry())
143 CurrentBlockFacts.append(PlaceholderLoanFacts.begin(),
144 PlaceholderLoanFacts.end());
145 for (unsigned I = 0; I < Block->size(); ++I) {
146 const CFGElement &Element = Block->Elements[I];
147 if (std::optional<CFGStmt> CS = Element.getAs<CFGStmt>())
148 Visit(CS->getStmt());
149 else if (std::optional<CFGInitializer> Initializer =
150 Element.getAs<CFGInitializer>())
151 handleCXXCtorInitializer(Initializer->getInitializer());
152 else if (std::optional<CFGLifetimeEnds> LifetimeEnds =
153 Element.getAs<CFGLifetimeEnds>())
154 handleLifetimeEnds(*LifetimeEnds);
155 else if (std::optional<CFGFullExprCleanup> FullExprCleanup =
156 Element.getAs<CFGFullExprCleanup>()) {
157 handleFullExprCleanup(*FullExprCleanup);
158 }
159 }
160 if (Block == &Cfg.getExit())
161 handleExitBlock();
162
163 CurrentBlockFacts.append(EscapesInCurrentBlock.begin(),
164 EscapesInCurrentBlock.end());
165 FactMgr.addBlockFacts(Block, CurrentBlockFacts);
166 }
167 FactMgr.computePersistentOrigins(Cfg);
168}
169
170OriginList *FactsGenerator::readValue(const Expr *E) {
171 OriginList *List = getOriginsList(*E);
172 if (!List)
173 return nullptr;
174 if (!E->isGLValue())
175 return List;
176 handleAccess(E);
177 return List->peelOuterOrigin();
178}
179
181 for (const Decl *D : DS->decls())
182 if (const auto *VD = dyn_cast<VarDecl>(D))
183 if (const Expr *InitExpr = VD->getInit()) {
184 OriginList *VDList = getOriginsList(*VD);
185 if (!VDList)
186 continue;
187 OriginList *InitList = getOriginsList(*InitExpr);
188 assert(InitList && "VarDecl had origins but InitExpr did not");
189 flow(VDList, InitList, /*Kill=*/true);
190 }
191}
192
194 // Skip function references as their lifetimes are not interesting. Skip non
195 // GLValues (like EnumConstants).
196 if (DRE->getFoundDecl()->isFunctionOrFunctionTemplate() || !DRE->isGLValue())
197 return;
198 // For all declarations with storage (non-references), we issue a loan
199 // representing the borrow of the variable's storage itself.
200 //
201 // Examples:
202 // - `int x; x` issues loan to x's storage
203 // - `int* p; p` issues loan to p's storage (the pointer variable)
204 // - `View v; v` issues loan to v's storage (the view object)
205 // - `int& r = x; r` issues no loan (r has no storage, it's an alias to x)
206 if (doesDeclHaveStorage(DRE->getDecl())) {
207 const Loan *L = createLoan(FactMgr, *DRE->getDecl(), DRE);
208 assert(L);
209 OriginList *List = getOriginsList(*DRE);
210 assert(List &&
211 "gl-value DRE of non-pointer type should have an origin list");
212 // This loan specifically tracks borrowing the variable's storage location
213 // itself and is issued to outermost origin (List->OID).
214 CurrentBlockFacts.push_back(
215 FactMgr.createFact<IssueFact>(L->getID(), List->getOuterOriginID()));
216 }
217}
218
220 if (isGslPointerType(CCE->getType())) {
221 handleGSLPointerConstruction(CCE);
222 return;
223 }
224 // For defaulted (implicit or `= default`) copy/move constructors, propagate
225 // origins directly. User-defined copy/move constructors are not handled here
226 // as they have opaque semantics.
228 CCE->getConstructor()->isDefaulted() && CCE->getNumArgs() == 1 &&
229 hasOrigins(CCE->getType())) {
230 const Expr *Arg = CCE->getArg(0);
231 if (OriginList *ArgList = readValue(Arg)) {
232 flow(getOriginsList(*CCE), ArgList, /*Kill=*/true);
233 return;
234 }
235 }
236 // Standard library callable wrappers (e.g., std::function) propagate the
237 // stored lambda's origins.
238 if (const auto *RD = CCE->getType()->getAsCXXRecordDecl();
239 RD && isStdCallableWrapperType(RD) && CCE->getNumArgs() == 1) {
240 const Expr *Arg = CCE->getArg(0);
241 if (OriginList *ArgList = readValue(Arg)) {
242 flow(getOriginsList(*CCE), ArgList, /*Kill=*/true);
243 return;
244 }
245 }
246 handleFunctionCall(CCE, /*IsGslConstruction=*/false);
247}
248
250 // The CFG does not visit a default argument's expression (GH13757), but it
251 // does expire the temporaries it materializes.
252 // Issue the loan here, reported at the call.
253 // FIXME: Model temporaries nested deeper in the default argument.
254 const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(
255 DAE->getExpr()->IgnoreParenBaseCasts());
256 OriginList *List = getOriginsList(*DAE);
257 if (!MTE || !List)
258 return;
259 const Loan *L = createLoan(FactMgr, MTE, /*IssueExpr=*/DAE);
260 CurrentBlockFacts.push_back(
261 FactMgr.createFact<IssueFact>(L->getID(), List->getOuterOriginID()));
262}
263
265 if (const Expr *Init = DIE->getExpr())
266 killAndFlowOrigin(*DIE, *Init);
267}
268
269void FactsGenerator::handleCXXCtorInitializer(const CXXCtorInitializer *CII) {
270 // Flows origins from the initializer expression to the field.
271 // Example: `MyObj(std::string s) : view(s) {}`
272 if (const FieldDecl *FD = CII->getAnyMember()) {
273 killAndFlowOrigin(*FD, *CII->getInit());
274 return;
275 }
276 // A base or delegating initializer initializes the object itself.
277 // Example: `Derived(std::string s) : BaseView(s) {}`
278 if (OriginList *InitList = getOriginsList(*CII->getInit()))
279 CurrentBlockFacts.push_back(FactMgr.createFact<OriginFlowFact>(
280 (*FactMgr.getOriginMgr().getThisOrigins())->getOuterOriginID(),
281 InitList->getOuterOriginID(), /*KillDest=*/false));
282}
283
285 // Specifically for conversion operators,
286 // like `std::string_view p = std::string{};`
287 if (isGslPointerType(MCE->getType()) &&
288 isa_and_present<CXXConversionDecl>(MCE->getCalleeDecl()) &&
290 handleFunctionCall(MCE, /*IsGslConstruction=*/true);
291 return;
292 }
293 // `a.operator=(b)` is `a = b`. For `p->operator=(b)` the object is `*p`.
294 if (const auto *ME = dyn_cast<MemberExpr>(MCE->getCallee());
295 ME && !ME->isArrow() &&
296 MCE->getMethodDecl()->getOverloadedOperator() == OO_Equal &&
297 handleAssignmentOperatorCall(MCE, MCE->getImplicitObjectArgument(),
298 MCE->getArg(0)))
299 return;
300 handleFunctionCall(MCE, /*IsGslConstruction=*/false);
301}
302
304 auto *MD = ME->getMemberDecl();
305 if (const auto *VD = dyn_cast<VarDecl>(MD); VD && doesDeclHaveStorage(VD)) {
306 // A static data member: borrow its storage, as for a DeclRefExpr.
307 const Loan *L = createLoan(FactMgr, *VD, ME);
308 OriginList *List = getOriginsList(*ME);
309 assert(List && "gl-value static member should have an origin list");
310 CurrentBlockFacts.push_back(
311 FactMgr.createFact<IssueFact>(L->getID(), List->getOuterOriginID()));
312 return;
313 }
314 if (isa<FieldDecl>(MD) && doesDeclHaveStorage(MD)) {
315 assert(ME->isGLValue() && "Field member should be GL value");
316 OriginList *Dst = getOriginsList(*ME);
317 assert(Dst && "Field member should have an origin list as it is GL value");
318 OriginList *Src = getOriginsList(*ME->getBase());
319 assert(Src && "Base expression should be a pointer/reference type");
320 // The field's glvalue (outermost origin) holds the same loans as the base
321 // expression.
322 CurrentBlockFacts.push_back(FactMgr.createFact<OriginFlowFact>(
323 Dst->getOuterOriginID(), Src->getOuterOriginID(),
324 /*Kill=*/true));
325 }
326}
327
329 handleFunctionCall(CE);
330}
331
333 const CXXNullPtrLiteralExpr *N) {
334 /// TODO: Handle nullptr expr as a special 'null' loan. Uninitialized
335 /// pointers can use the same type of loan.
336 getOriginsList(*N);
337}
338
340 const Expr *SubExpr = CE->getSubExpr();
341 // May be null: loading an `int` has no origins but still reads the operand.
342 OriginList *Dest = getOriginsList(*CE);
343 OriginList *Src = Dest ? getOriginsList(*SubExpr) : nullptr;
344
345 switch (CE->getCastKind()) {
346 case CK_LValueToRValue:
347 // The result of an LValue-to-RValue cast on a pointer lvalue (like `q` in
348 // `int *p, *q; p = q;`) should propagate the inner origin (what the pointer
349 // points to), not the outer origin (the pointer's storage location).
350 flow(Dest, readValue(SubExpr), /*Kill=*/true);
351 return;
352 case CK_NullToPointer:
353 // TODO: Flow into them a null origin.
354 return;
355 case CK_NoOp:
356 case CK_ConstructorConversion:
357 case CK_UserDefinedConversion:
358 flow(Dest, Src, /*Kill=*/true);
359 return;
360 case CK_Dynamic:
361 // Reads the object's dynamic type.
362 handleAccess(SubExpr);
363 [[fallthrough]];
364 case CK_UncheckedDerivedToBase:
365 case CK_DerivedToBase:
366 case CK_BaseToDerived:
367 // The conversion cast doesn't change what it refers to, so preserve the
368 // borrow if we can.
369 // It is possible that the derived class and base class have different
370 // gsl::Pointer annotations. Skip if their origin shape differ.
371 if (Dest && Src && Dest->getLength() == Src->getLength())
372 flow(Dest, Src, /*Kill=*/true);
373 return;
374 case CK_ArrayToPointerDecay:
375 // va_arg(ap, array_type) is UB and does not provide addressable array
376 // storage to model.
377 if (!Dest || isa<VAArgExpr>(SubExpr->IgnoreParens()))
378 return;
379 assert(Src && "Array expression should have origins as it is GL value");
380 CurrentBlockFacts.push_back(FactMgr.createFact<OriginFlowFact>(
381 Dest->getOuterOriginID(), Src->getOuterOriginID(), /*Kill=*/true));
382 return;
383 case CK_FunctionToPointerDecay:
384 case CK_BuiltinFnToFnPtr:
385 // Ignore function-to-pointer decays.
386 return;
387 case CK_BitCast:
388 // OriginLists for Src and Dst may differ here. For example when casting
389 // from int** to void*
390 if (Src && Dest && Dest->getLength() == Src->getLength())
391 flow(Dest, Src, /*Kill=*/true);
392 return;
393 case CK_LValueToRValueBitCast:
394 case CK_NonAtomicToAtomic:
395 case CK_AtomicToNonAtomic: {
396 // `__builtin_bit_cast`/`std::bit_cast` of a pointer, and
397 // wrapping/unwrapping `_Atomic(T*)`, preserve the pointer value, so
398 // propagate the borrow. readValue peels a glvalue operand's storage level
399 // and records the read. A bit-cast that materializes a pointer from a
400 // non-pointer representation has no matching source origin and is
401 // untracked.
402 OriginList *RVSrc = readValue(SubExpr);
403 if (Dest && RVSrc && Dest->getLength() == RVSrc->getLength())
404 flow(Dest, RVSrc, /*Kill=*/true);
405 return;
406 }
407 default:
408 return;
409 }
410}
411
413 switch (UO->getOpcode()) {
414 case UO_AddrOf: {
415 const Expr *SubExpr = UO->getSubExpr();
416 // Function addresses do not need lifetime tracking.
417 if (SubExpr->getType()->isFunctionType())
418 return;
419 // Skip address-of on void expressions: GNU C permits them, but void itself
420 // has no origins to track.
421 if (IsCMode && SubExpr->getType()->isVoidType())
422 return;
423 assert(!SubExpr->getType()->isVoidType() &&
424 "Taking address of void is not valid in C++");
425 // The origin of an address-of expression (e.g., &x) is the origin of
426 // its sub-expression (x). This fact will cause the dataflow analysis
427 // to propagate any loans held by the sub-expression's origin to the
428 // origin of this UnaryOperator expression.
429 killAndFlowOrigin(*UO, *SubExpr);
430 return;
431 }
432 case UO_Deref: {
433 const Expr *SubExpr = UO->getSubExpr();
434 killAndFlowOrigin(*UO, *SubExpr);
435 return;
436 }
437 case UO_Plus: {
438 // Unary plus on a pointer is the identity (`+p == p`), so the prvalue
439 // result carries the operand's loans. Flow the operand's rvalue origins
440 // (peeling storage only when the operand is itself a glvalue).
441 if (!UO->getType()->isPointerType())
442 return;
443 const Expr *SubExpr = UO->getSubExpr();
444 flow(getOriginsList(*UO), readValue(SubExpr), /*Kill=*/true);
445 return;
446 }
447 case UO_PreInc:
448 case UO_PostInc:
449 case UO_PreDec:
450 case UO_PostDec: {
451 handleAccess(UO->getSubExpr());
452 // Inc/dec keeps a pointer in the same allocation, so the result carries the
453 // operand's loans. Peel the operand's storage origin when the *result* is a
454 // prvalue (post-inc/dec, or any form in C).
455 if (!UO->getType()->isPointerType())
456 return;
457 OriginList *SubList = getOriginsList(*UO->getSubExpr());
458 flow(getOriginsList(*UO),
459 UO->isGLValue() ? SubList : SubList->peelOuterOrigin(), /*Kill=*/true);
460 return;
461 }
462 default:
463 return;
464 }
465}
466
468 if (const Expr *RetExpr = RS->getRetValue()) {
469 if (OriginList *List = getOriginsList(*RetExpr))
470 for (OriginList *L = List; L != nullptr; L = L->peelOuterOrigin())
471 EscapesInCurrentBlock.push_back(FactMgr.createFact<ReturnEscapeFact>(
472 L->getOuterOriginID(), RetExpr));
473 }
474}
475
476void FactsGenerator::handleAssignment(const Expr *TargetExpr,
477 const Expr *LHSExpr,
478 const Expr *RHSExpr) {
479 LHSExpr = ignoreParensAndImpCasts(LHSExpr);
480 handleAccess(LHSExpr);
481 OriginList *RHSList = readValue(RHSExpr);
482 OriginList *LHSList = nullptr;
483
484 if (const auto *DRE_LHS = dyn_cast<DeclRefExpr>(LHSExpr)) {
485 LHSList = getOriginsList(*DRE_LHS);
486 assert(LHSList && "LHS is a DRE and should have an origin list");
487 }
488 // Handle assignment to member fields (e.g., `this->view = s` or `view = s`).
489 // This enables detection of dangling fields when local values escape to
490 // fields.
491 if (const auto *ME_LHS = dyn_cast<MemberExpr>(LHSExpr)) {
492 LHSList = getOriginsList(*ME_LHS);
493 assert(LHSList && "LHS is a MemberExpr and should have an origin list");
494 }
495 if (!LHSList)
496 return;
497
498 if (!RHSList) {
499 // RHS has no tracked origins (e.g., assigning a callable without origins
500 // to std::function). Clear loans of the destination.
501 for (OriginList *LHSInner = LHSList->peelOuterOrigin(); LHSInner;
502 LHSInner = LHSInner->peelOuterOrigin())
503 CurrentBlockFacts.push_back(
504 FactMgr.createFact<KillOriginFact>(LHSInner->getOuterOriginID()));
505 return;
506 }
507 // Kill the old loans of the destination origin and flow the new loans
508 // from the source origin.
509 flow(LHSList->peelOuterOrigin(), RHSList, /*Kill=*/true);
510
511 // In C, assignment expressions are not GLValues, so the assignment result has
512 // the assigned value origins, not the LHS storage origin.
513 if (IsCMode)
514 LHSList = LHSList->peelOuterOrigin();
515 flow(getOriginsList(*TargetExpr), LHSList, /*Kill=*/true);
516}
517
518void FactsGenerator::handlePointerArithmetic(const BinaryOperator *BO) {
519 if (Expr *RHS = BO->getRHS(); RHS->getType()->isPointerType()) {
520 killAndFlowOrigin(*BO, *RHS);
521 return;
522 }
523 Expr *LHS = BO->getLHS();
524 assert(LHS->getType()->isPointerType() &&
525 "Pointer arithmetic must have a pointer operand");
526 killAndFlowOrigin(*BO, *LHS);
527}
528
530 if (BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI) {
531 // `obj.*pm` / `objptr->*pm` names a member of the object, so a borrow of it
532 // borrows the object; flow the object's origin into the result. For `.*`
533 // the object is the LHS; for `->*` it is the LHS pointer's pointee.
534 //
535 // Only the result's outer (storage) origin relates to the object: borrowing
536 // the member borrows the object's storage. Deeper levels of the result (a
537 // pointer/view member's own pointee) are the member's value, with no
538 // counterpart in the object's origin -- so the lists may differ in length
539 // and we flow just the top level, leaving the member's value untouched.
540 OriginList *Dst = getOriginsList(*BO);
541 OriginList *ObjSrc = BO->getOpcode() == BO_PtrMemD
542 ? getOriginsList(*BO->getLHS())
543 : readValue(BO->getLHS());
544 if (Dst && ObjSrc)
545 CurrentBlockFacts.push_back(FactMgr.createFact<OriginFlowFact>(
546 Dst->getOuterOriginID(), ObjSrc->getOuterOriginID(), /*Kill=*/true));
547 return;
548 }
549 if (BO->getOpcode() == BO_Comma) {
550 killAndFlowOrigin(*BO, *BO->getRHS());
551 return;
552 }
553 if (BO->isCompoundAssignmentOp()) {
554 handleAccess(BO->getLHS());
555 // A pointer compound additive assignment (`p += n`) carries the LHS's loans
556 // like inc/dec above; in C the result is a prvalue, so peel its outer
557 // (storage) origin.
558 if (BO->getType()->isPointerType()) {
559 OriginList *LHSList = getOriginsList(*BO->getLHS());
560 flow(getOriginsList(*BO), IsCMode ? LHSList->peelOuterOrigin() : LHSList,
561 /*Kill=*/true);
562 }
563 return;
564 }
565 if (BO->getType()->isPointerType() && BO->isAdditiveOp())
566 handlePointerArithmetic(BO);
567 if (BO->isAssignmentOp())
568 handleAssignment(BO, BO->getLHS(), BO->getRHS());
569 // TODO: Propagate origins for assignments through a dereference (`*p = q`).
570}
571
572static const CFGBlock *findPredBlockForExpr(const CFGBlock *MergeBlock,
573 const Expr *ArmExpr) {
574 if (!ArmExpr)
575 return nullptr;
576 const Expr *Target = ignoreParensAndImpCasts(ArmExpr);
577 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(Target))
578 if (const Expr *Src = OVE->getSourceExpr())
580
581 for (const CFGBlock *Pred : MergeBlock->preds()) {
582 if (!Pred)
583 continue;
584 for (const CFGElement &Elt : *Pred)
585 if (auto CS = Elt.getAs<CFGStmt>())
586 if (const auto *E = dyn_cast<Expr>(CS->getStmt()))
588 return Pred;
589 }
590 return nullptr;
591}
592
593/// Visits conditional operators (e.g., `cond ? a : b`).
594///
595/// To prevent liveness leakage across loop backedges (which causes false
596/// positives like in `while (...) { int x; consume(cond ? &x : nullptr); }`),
597/// we generate the flow facts in the respective predecessor blocks of the arms
598/// rather than in the merge block. This ensures that the liveness of the
599/// temporary origin from one arm does not propagate into the other arm's path.
601 const AbstractConditionalOperator *CO) {
602 if (!hasOrigins(CO))
603 return;
604
605 const Expr *TrueExpr = CO->getTrueExpr();
606 const Expr *FalseExpr = CO->getFalseExpr();
607
608 if (const CFGBlock *TBPred = findPredBlockForExpr(CurrentBlock, TrueExpr))
609 flow(getOriginsList(*CO), getOriginsList(*TrueExpr), /*Kill=*/true, TBPred);
610 if (const CFGBlock *FBPred = findPredBlockForExpr(CurrentBlock, FalseExpr))
611 flow(getOriginsList(*CO), getOriginsList(*FalseExpr), /*Kill=*/true,
612 FBPred);
613}
614
615bool FactsGenerator::handleAssignmentOperatorCall(const CallExpr *CE,
616 const Expr *LHSExpr,
617 const Expr *RHSExpr) {
618 QualType LHSTy = LHSExpr->getType();
619 if (!hasOrigins(LHSTy))
620 return false;
621 // Pointer-like types: assignment inherently propagates origins.
622 if (LHSTy->isPointerOrReferenceType() || isGslPointerType(LHSTy) ||
623 isGslOwnerType(LHSTy)) {
624 handleAssignment(CE, LHSExpr, RHSExpr);
625 return true;
626 }
627 // Standard library callable wrappers (e.g., std::function) can propagate
628 // the stored lambda's origins.
629 if (const auto *RD = LHSTy->getAsCXXRecordDecl();
630 RD && isStdCallableWrapperType(RD)) {
631 handleAssignment(CE, LHSExpr, RHSExpr);
632 return true;
633 }
634 // Other tracked types: only defaulted operator= propagates origins.
635 // User-defined operator= has opaque semantics, so don't handle them now.
636 if (const auto *MD = dyn_cast_or_null<CXXMethodDecl>(CE->getDirectCallee());
637 MD && MD->isDefaulted()) {
638 handleAssignment(CE, LHSExpr, RHSExpr);
639 return true;
640 }
641 return false;
642}
643
645 // Assignment operators have special "kill-then-propagate" semantics
646 // and are handled separately.
647 if (OCE->getOperator() == OO_Equal && OCE->getNumArgs() == 2 &&
648 handleAssignmentOperatorCall(OCE, OCE->getArg(0), OCE->getArg(1)))
649 return;
650
651 handleFunctionCall(OCE);
652}
653
655 const CXXFunctionalCastExpr *FCE) {
656 // Check if this is a test point marker. If so, we are done with this
657 // expression.
658 if (handleTestPoint(FCE))
659 return;
660 VisitCastExpr(FCE);
661}
662
664 if (!hasOrigins(ILE))
665 return;
666 // For list initialization with a single element, like `View{...}`, the
667 // origin of the list itself is the origin of its single element.
668 if (ILE->getNumInits() == 1) {
669 // A type with origins may be list-initialized from an element with none
670 // (e.g., an int). Only flow if the element carries any.
671 if (!hasOrigins(ILE->getInit(0)))
672 return;
673 killAndFlowOrigin(*ILE, *ILE->getInit(0));
674 }
675}
676
678 const CXXBindTemporaryExpr *BTE) {
679 killAndFlowOrigin(*BTE, *BTE->getSubExpr());
680}
681
683 const MaterializeTemporaryExpr *MTE) {
684 assert(MTE->isGLValue());
685 OriginList *MTEList = getOriginsList(*MTE);
686 if (!MTEList)
687 return;
688 OriginList *SubExprList = getOriginsList(*MTE->getSubExpr());
689 assert((!SubExprList ||
690 MTEList->getLength() == (SubExprList->getLength() + 1)) &&
691 "MTE top level origin should contain a loan to the MTE itself");
692
693 OriginList *RValMTEList = MTEList->peelOuterOrigin();
694 flow(RValMTEList, SubExprList, /*Kill=*/true);
695 OriginID OuterMTEID = MTEList->getOuterOriginID();
696 const Loan *L = createLoan(FactMgr, MTE);
697 CurrentBlockFacts.push_back(
698 FactMgr.createFact<IssueFact>(L->getID(), OuterMTEID));
699 // A temporary extended to static or thread storage duration does not expire
700 // within the function.
701 // Thread termination is not modeled; a thread-local value used after its
702 // thread exits is not diagnosed.
703 if (MTE->getStorageDuration() == SD_Automatic)
704 if (const ValueDecl *ExtendingDecl = MTE->getExtendingDecl())
705 ExtendedTemporaries[ExtendingDecl].push_back(MTE);
706}
707
709 for (const LambdaCapture &C : LE->captures()) {
710 if (C.capturesThis())
711 FactMgr.setThisCapturedByLambda();
712 else if (C.capturesVariable() && C.getCapturedVar()->isInitCapture()) {
713 const Expr *Init = cast<VarDecl>(C.getCapturedVar())->getInit();
714 if (!Init)
715 continue;
716 if (const auto *ME =
717 dyn_cast<MemberExpr>(ignoreParensAndImpCasts(Init))) {
718 if (const auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
719 FactMgr.addCapturedField(FD);
720 }
721 }
722 }
723
724 // The lambda gets a single merged origin that aggregates all captured
725 // pointer-like origins. Currently we only need to detect whether the lambda
726 // outlives any capture.
727 OriginList *LambdaList = getOriginsList(*LE);
728 if (!LambdaList)
729 return;
730 bool Kill = true;
731 for (const Expr *Init : LE->capture_inits()) {
732 if (!Init)
733 continue;
734 // The lambda body may dereference a capture to any depth.
735 handleUse(Init);
736 OriginList *InitList = getOriginsList(*Init);
737 if (!InitList)
738 continue;
739 // FIXME: Consider flowing all origin levels once lambdas support more than
740 // one origin. Currently only the outermost origin is flowed, so by-ref
741 // captures like `[&p]` (where p is string_view) miss inner-level
742 // invalidation.
743 CurrentBlockFacts.push_back(FactMgr.createFact<OriginFlowFact>(
744 LambdaList->getOuterOriginID(), InitList->getOuterOriginID(), Kill));
745 Kill = false;
746 }
747}
748
750 // Some C subscripts do not refer to addressable storage with origins, such as
751 // GNU void-pointer subscripts and vector element extraction from rvalues.
752 if (IsCMode && !ASE->isGLValue())
753 return;
754 assert(ASE->isGLValue() && "Array subscript should be a GL value");
755 OriginList *Dst = getOriginsList(*ASE);
756 assert(Dst && "Array subscript should have origins as it is a GL value");
757 OriginList *Src = getOriginsList(*ASE->getBase());
758 assert(Src && "Base of array subscript should have origins");
759 CurrentBlockFacts.push_back(FactMgr.createFact<OriginFlowFact>(
760 Dst->getOuterOriginID(), Src->getOuterOriginID(), /*Kill=*/true));
761}
762
763bool FactsGenerator::handlePlacementNew(const CXXNewExpr *NE,
764 OriginList *NewList) {
765 // Model only the standard single-argument placement new form, where the
766 // placement argument corresponds to a void* allocation-function parameter.
767 // Other placement forms, such as std::nothrow, are not modeled as providing
768 // storage for the returned pointer.
769 if (NE->getNumPlacementArgs() != 1)
770 return false;
771
772 const FunctionDecl *OperatorNew = NE->getOperatorNew();
773 if (OperatorNew->getNumParams() <= 1)
774 return false;
775
776 const auto *Arg =
777 OperatorNew->getParamDecl(1)->getType()->getAs<PointerType>();
778 if (!Arg || !Arg->isVoidPointerType())
779 return false;
780
781 // Use the placement argument before the implicit conversion to void*, so
782 // inner origins are still available.
783 const Expr *PlacementArg = NE->getPlacementArg(0);
784 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(PlacementArg);
785 ICE && ICE->getCastKind() == CK_BitCast &&
786 PlacementArg->getType()->isVoidPointerType())
787 PlacementArg = ICE->getSubExpr();
788 OriginList *PlacementList = getOriginsList(*PlacementArg);
789 // FIXME: General placement arguments need separate handling to overwrite
790 // the right origins.
791
792 handleAccess(PlacementArg);
793
794 // The pointer returned by placement new comes from the placement
795 // argument.
796 if (PlacementList)
797 CurrentBlockFacts.push_back(FactMgr.createFact<OriginFlowFact>(
798 NewList->getOuterOriginID(), PlacementList->getOuterOriginID(), true));
799 return true;
800}
801
803 OriginList *NewList = getOriginsList(*NE);
804 const Expr *Init = NE->getInitializer();
805
806 bool HandledAsPlacementNew = false;
807 if (NE->getNumPlacementArgs() == 1)
808 HandledAsPlacementNew = handlePlacementNew(NE, NewList);
809
810 // Treat ordinary new and replaceable global allocation forms as heap
811 // allocations.
812 const FunctionDecl *OperatorNew = NE->getOperatorNew();
813 if (!HandledAsPlacementNew &&
814 (NE->getNumPlacementArgs() == 0 ||
815 (OperatorNew && OperatorNew->isReplaceableGlobalAllocationFunction()))) {
816 const Loan *L = createLoan(FactMgr, NE);
817 CurrentBlockFacts.push_back(
818 FactMgr.createFact<IssueFact>(L->getID(), NewList->getOuterOriginID()));
819 }
820
821 NewList = NewList->peelOuterOrigin();
822
823 if (!NewList || !Init)
824 return;
825
826 // FIXME: OriginList is null for `new[]` initializers. Remove this `Init`
827 // check once array origins are supported.
828 if (OriginList *InitList = getOriginsList(*Init); InitList)
829 flow(NewList, InitList, true);
830}
831
832// TODO: An escape fact may fit `throw` and asm better than a use.
834 if (const Expr *Sub = TE->getSubExpr())
835 handleUse(Sub);
836}
837
839 for (const Expr *Input : AS->inputs())
840 handleUse(Input);
841 for (unsigned I = 0, N = AS->getNumOutputs(); I != N; ++I)
842 if (AS->isOutputPlusConstraint(I)) // Also read.
843 handleUse(AS->getOutputExpr(I));
844 else
845 handleAccess(AS->getOutputExpr(I));
846}
847
849 if (TE->isPotentiallyEvaluated())
850 handleAccess(TE->getExprOperand());
851}
852
854 // The destructor may dereference to any depth.
855 handleUse(DE->getArgument());
856 OriginList *List = getOriginsList(*DE->getArgument());
857 CurrentBlockFacts.push_back(
858 FactMgr.createFact<InvalidateOriginFact>(List->getOuterOriginID(), DE));
859}
860
862 // A statement expression (`({ ...; e; })`) yields the value of its final
863 // expression `e`. Flow `e`'s origins into the statement expression's origin
864 // so a borrow `e` carries reaches the value's users.
865 const auto *CS = SE->getSubStmt();
866 if (!CS || CS->body_empty())
867 return;
868 const auto *Last = dyn_cast<Expr>(CS->body_back());
869 if (!Last)
870 return;
871 if (OriginList *Dst = getOriginsList(*SE))
872 if (OriginList *Src = readValue(Last))
873 flow(Dst, Src, /*Kill=*/true);
874}
875
876bool FactsGenerator::escapesViaReturn(OriginID OID) const {
877 return llvm::any_of(EscapesInCurrentBlock, [OID](const Fact *F) {
878 if (const auto *EF = F->getAs<ReturnEscapeFact>())
879 return EF->getEscapedOriginID() == OID;
880 return false;
881 });
882}
883
884void FactsGenerator::handleLifetimeEnds(const CFGLifetimeEnds &LifetimeEnds) {
885 const VarDecl *LifetimeEndsVD = LifetimeEnds.getVarDecl();
886 if (!LifetimeEndsVD)
887 return;
888 SourceLocation EndLoc = LifetimeEnds.getTriggerStmt()->getEndLoc();
889 // A cleanup callback or a non-trivial destructor (other than an owner's) run
890 // at scope exit may read the borrows the variable holds.
891 QualType Ty = LifetimeEndsVD->getType();
892 bool HasCleanup = LifetimeEndsVD->hasAttr<CleanupAttr>();
893 bool IsDestructorUse =
894 LSOpts.CheckDestructorUses &&
897 if (HasCleanup || IsDestructorUse)
898 if (OriginList *List = getOriginsList(*LifetimeEndsVD))
899 CurrentBlockFacts.push_back(FactMgr.createFact<UseFact>(
900 UseSite::scopeExit(EndLoc, *LifetimeEndsVD,
901 HasCleanup ? UseKind::Cleanup
903 List));
904 // Expire the origin when its variable's lifetime ends to ensure liveness
905 // doesn't persist through loop back-edges.
906 std::optional<OriginID> ExpiredOID;
907 if (OriginList *List = getOriginsList(*LifetimeEndsVD)) {
908 OriginID OID = List->getOuterOriginID();
909 // Skip origins that escape via return; the escape checker needs their loans
910 // to remain until the return statement is processed.
911 if (!escapesViaReturn(OID))
912 ExpiredOID = OID;
913 }
914 CurrentBlockFacts.push_back(FactMgr.createFact<ExpireFact>(
915 AccessPath(LifetimeEndsVD), EndLoc, ExpiredOID));
916 if (auto It = ExtendedTemporaries.find(LifetimeEndsVD);
917 It != ExtendedTemporaries.end())
918 for (const MaterializeTemporaryExpr *MTE : It->second)
919 CurrentBlockFacts.push_back(
920 FactMgr.createFact<ExpireFact>(AccessPath(MTE), EndLoc));
921}
922
923void FactsGenerator::handleFullExprCleanup(
924 const CFGFullExprCleanup &FullExprCleanup) {
925 for (const auto *MTE : FullExprCleanup.getExpiringMTEs())
926 CurrentBlockFacts.push_back(FactMgr.createFact<ExpireFact>(
927 AccessPath(MTE), FullExprCleanup.getCleanupLoc()));
928}
929
930void FactsGenerator::handleExitBlock() {
931 bool IsDestructor = isa_and_nonnull<CXXDestructorDecl>(AC.getDecl());
932 for (const Origin &O : FactMgr.getOriginMgr().getOrigins())
933 // Create FieldEscapeFacts for all field origins that remain live at exit.
934 // Fields in destructors do not escape since the object is being destroyed.
935 if (auto *FD = dyn_cast_if_present<FieldDecl>(O.getDecl());
936 FD && !IsDestructor)
937 EscapesInCurrentBlock.push_back(
938 FactMgr.createFact<FieldEscapeFact>(O.ID, FD));
939 else if (auto *VD = dyn_cast_if_present<VarDecl>(O.getDecl())) {
940 // Create GlobalEscapeFacts for all origins with global-storage that
941 // remain live at exit.
942 if (VD->hasGlobalStorage()) {
943 EscapesInCurrentBlock.push_back(
944 FactMgr.createFact<GlobalEscapeFact>(O.ID, VD));
945 }
946 }
947
948 // Keep the never-expiring `this` origin live at exit: the object outlives
949 // the method, so whatever it holds (e.g. borrows captured via
950 // [[clang::lifetime_capture_by_this]], or loans reachable through its
951 // fields) is considered used after the method returns. This is emitted for
952 // every method with a `this` origin, not only those that capture something.
953 // Destructors are skipped since the object is being destroyed.
954 if (auto ThisOrigins = FactMgr.getOriginMgr().getThisOrigins();
955 ThisOrigins && !IsDestructor)
956 EscapesInCurrentBlock.push_back(FactMgr.createFact<ThisEscapeFact>(
957 (*ThisOrigins)->getOuterOriginID(), AC.getDecl()->getEndLoc()));
958
959 // Storage reachable through a reference parameter, i.e. every origin of the
960 // parameter but the outermost, is visible to the caller. A pointer parameter
961 // can be pointed at local storage, so stores through it are not necessarily
962 // visible to the caller.
963 if (const auto *Fn = dyn_cast_if_present<FunctionDecl>(AC.getDecl()))
964 for (const ParmVarDecl *PVD : Fn->parameters()) {
965 OriginList *List = getOriginsList(*PVD);
966 if (!List || !PVD->getType()->isReferenceType())
967 continue;
968 for (OriginList *Inner = List->peelOuterOrigin(); Inner;
969 Inner = Inner->peelOuterOrigin())
970 EscapesInCurrentBlock.push_back(FactMgr.createFact<ParamEscapeFact>(
971 Inner->getOuterOriginID(), PVD));
972 }
973}
974
975void FactsGenerator::handleGSLPointerConstruction(const CXXConstructExpr *CCE) {
976 assert(isGslPointerType(CCE->getType()));
977 // Only lifetimebound parameters propagate for a constructor taking several
978 // arguments; the owner heuristic applies to single-argument construction.
979 if (CCE->getNumArgs() != 1) {
980 handleFunctionCall(CCE, /*IsGslConstruction=*/true);
981 return;
982 }
983
984 const Expr *Arg = CCE->getArg(0);
985 if (isGslPointerType(Arg->getType())) {
986 // GSL pointer is constructed from another gsl pointer.
987 // Example:
988 // View(View v);
989 // View(const View &v);
990 OriginList *ArgList = readValue(Arg);
991 assert(ArgList && "GSL pointer argument should have an origin list");
992 flow(getOriginsList(*CCE), ArgList, /*Kill=*/true);
993 } else if (Arg->getType()->isPointerType()) {
994 // GSL pointer is constructed from a raw pointer. Flow only the outermost
995 // raw pointer. Example:
996 // View(const char*);
997 // Span<int*>(const in**);
998 OriginList *ArgList = getOriginsList(*Arg);
999 CurrentBlockFacts.push_back(FactMgr.createFact<OriginFlowFact>(
1000 getOriginsList(*CCE)->getOuterOriginID(), ArgList->getOuterOriginID(),
1001 /*Kill=*/true));
1002 } else {
1003 // This could be a new borrow.
1004 // TODO: Add code example here.
1005 handleFunctionCall(CCE, /*IsGslConstruction=*/true);
1006 }
1007}
1008
1009void FactsGenerator::handleMovedArgsInCall(const FunctionDecl *FD,
1010 ArrayRef<const Expr *> Args) {
1011 // std::unique_ptr::release() transfers ownership.
1012 // Treat it as a move to prevent false-positive warnings when the unique_ptr
1013 // destructor runs after ownership has been transferred.
1014 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD);
1015 MD && hasImplicitObjectArg(*FD) && isUniquePtrRelease(*MD)) {
1016 const Expr *UniquePtrExpr = Args[0];
1017 OriginList *MovedOrigins = getOriginsList(*UniquePtrExpr);
1018 if (MovedOrigins)
1019 CurrentBlockFacts.push_back(FactMgr.createFact<MovedOriginFact>(
1020 UniquePtrExpr, MovedOrigins->getOuterOriginID()));
1021 }
1022
1023 for (unsigned I = 0; I < Args.size(); ++I) {
1024 // Null for the implicit 'this' arg, which cannot be moved.
1025 const ParmVarDecl *PVD = getParamForArg(*FD, I);
1026 if (!PVD)
1027 continue;
1028 // In principle, explicit object parameters can be moved, but skip marking
1029 // them as moved for consistency with implicit 'this'.
1030 if (PVD->isExplicitObjectParameter())
1031 continue;
1032 if (!PVD->getType()->isRValueReferenceType())
1033 continue;
1034 // Skip lifetime annotated r-value reference parameters. Lifetime annotation
1035 // indicates that the parameter is borrowed (not consumed), so it should not
1036 // be marked as moved even though it's an r-value reference.
1037 if (PVD->hasAttr<LifetimeBoundAttr>() ||
1038 PVD->hasAttr<LifetimeCaptureByAttr>())
1039 continue;
1040 const Expr *Arg = Args[I];
1041 OriginList *MovedOrigins = getOriginsList(*Arg);
1042 assert(MovedOrigins->getLength() >= 1 &&
1043 "unexpected length for r-value reference param");
1044 // Arg is being moved to this parameter. Mark the origin as moved.
1045 CurrentBlockFacts.push_back(FactMgr.createFact<MovedOriginFact>(
1046 Arg, MovedOrigins->getOuterOriginID()));
1047 }
1048}
1049
1050void FactsGenerator::handleInvalidatingCall(const Expr *Call,
1051 const FunctionDecl *FD,
1052 ArrayRef<const Expr *> Args) {
1053 const auto *MD = dyn_cast<CXXMethodDecl>(FD);
1054 if (!MD || !MD->isInstance())
1055 return;
1056
1057 if (!isInvalidationMethod(*MD))
1058 return;
1059
1060 // Heuristics to turn-down false positives. Skip member field expressions for
1061 // now. This is not a perfect filter and will still surface some false
1062 // positives (e.g. `auto& r = s.v`). Static data members are not fields.
1063 const Expr *Obj = ignoreParensAndImpCasts(Args[0]);
1064 if (const auto *ME = dyn_cast<MemberExpr>(Obj);
1065 !isa<DeclRefExpr>(Obj) && !(ME && isa<VarDecl>(ME->getMemberDecl())))
1066 return;
1067
1068 OriginList *ThisList = getOriginsList(*Args[0]);
1069 if (ThisList)
1070 CurrentBlockFacts.push_back(FactMgr.createFact<InvalidateOriginFact>(
1071 ThisList->getOuterOriginID(), Call));
1072}
1073
1074void FactsGenerator::handleDestructiveCall(const Expr *Call,
1075 const FunctionDecl *FD,
1076 ArrayRef<const Expr *> Args) {
1077 if (!destructsFirstArg(*FD))
1078 return;
1079 OriginList *ArgList = getOriginsList(*Args[0]);
1080 if (ArgList)
1081 CurrentBlockFacts.push_back(FactMgr.createFact<InvalidateOriginFact>(
1082 ArgList->getOuterOriginID(), Call));
1083}
1084
1085void FactsGenerator::handleImplicitObjectFieldUses(const Expr *Call,
1086 const FunctionDecl *FD) {
1087 const auto *MemberCall = dyn_cast_or_null<CXXMemberCallExpr>(Call);
1088 if (!MemberCall)
1089 return;
1090
1091 if (!isa_and_present<CXXThisExpr>(
1092 ignoreParensAndImpCasts(MemberCall->getImplicitObjectArgument())))
1093 return;
1094
1095 const auto *MD = dyn_cast<CXXMethodDecl>(FD);
1096 assert(MD && "Function must be a CXXMethodDecl for member calls");
1097
1098 const auto *ClassDecl = MD->getParent()->getDefinition();
1099 if (!ClassDecl)
1100 return;
1101
1102 const auto UseFields = [&](const CXXRecordDecl *RD) {
1103 for (const auto *Field : RD->fields())
1104 if (auto *FieldList = getOriginsList(*Field))
1105 CurrentBlockFacts.push_back(
1106 FactMgr.createFact<UseFact>(*Call, FieldList));
1107 };
1108
1109 UseFields(ClassDecl);
1110
1111 ClassDecl->forallBases([&](const CXXRecordDecl *Base) {
1112 UseFields(Base);
1113 return true;
1114 });
1115}
1116
1117void FactsGenerator::handleLifetimeCaptureBy(const FunctionDecl *FD,
1118 ArrayRef<const Expr *> Args) {
1119 if (Args.empty())
1120 return;
1121 // FIXME: Add support for capture_by on constructors.
1123 return;
1124 auto getArgCaptureByAttr =
1125 [FD](unsigned I) -> std::pair<const LifetimeCaptureByAttr *, QualType> {
1126 if (I == 0 && hasImplicitObjectArg(*FD))
1128 cast<CXXMethodDecl>(FD)->getFunctionObjectParameterType()};
1129 if (const ParmVarDecl *PVD = getParamForArg(*FD, I))
1130 return {PVD->getAttr<LifetimeCaptureByAttr>(), PVD->getType()};
1131 return {nullptr, QualType()};
1132 };
1133 for (unsigned I = 0; I < Args.size(); ++I) {
1134 auto [Attr, ParamType] = getArgCaptureByAttr(I);
1135 if (!Attr)
1136 continue;
1137 OriginList *CapturedOriginList = getOriginsList(*Args[I]);
1138 if (!CapturedOriginList)
1139 continue;
1140 // For references to pointer-like types, peel the outer origin (the pointer
1141 // object itself) so that we capture the underlying data (the inner origin).
1142 if (!ParamType.isNull() &&
1143 (ParamType->isReferenceType() &&
1144 isPointerLikeType(ParamType->getPointeeType())) &&
1145 CapturedOriginList->getLength() > 1)
1146 CapturedOriginList = CapturedOriginList->peelOuterOrigin();
1147 for (int CapturingArgIdx : Attr->params()) {
1148 // FIXME: Add support for capturing to Global/unknown.
1149 if (CapturingArgIdx == LifetimeCaptureByAttr::Global ||
1150 CapturingArgIdx == LifetimeCaptureByAttr::Unknown ||
1151 CapturingArgIdx == LifetimeCaptureByAttr::Invalid)
1152 continue;
1153 // FIXME: Diagnose bad CapturingArgIdx.
1154 if (CapturingArgIdx != LifetimeCaptureByAttr::This &&
1155 (CapturingArgIdx < 0 ||
1156 static_cast<size_t>(CapturingArgIdx) >= Args.size()))
1157 continue;
1158 const Expr *CapturedByArg = Args[CapturingArgIdx];
1159 assert(CapturedByArg && "Capturer expression must be valid");
1160
1161 OriginList *Dest = readValue(CapturedByArg);
1162 if (!Dest)
1163 continue;
1164 // KillDest=false because we cannot know if previous captures are being
1165 // replaced or accumulated. Multiple successive captures into the same
1166 // destination must all be tracked, so captured lifetimes are always
1167 // merged.
1168 CurrentBlockFacts.push_back(FactMgr.createFact<OriginFlowFact>(
1169 Dest->getOuterOriginID(), CapturedOriginList->getOuterOriginID(),
1170 /*KillDest=*/false));
1171 }
1172 }
1173}
1174
1175void FactsGenerator::handleFreeingCall(const Expr *Call, const FunctionDecl *FD,
1176 ArrayRef<const Expr *> Args) {
1177 if (!isFreeingFunction(*FD))
1178 return;
1179 auto InvalidateArg = [&](unsigned ArgIndex) {
1180 assert(ArgIndex < Args.size() && "Arg index should be in bounds");
1181
1182 OriginList *ArgList = getOriginsList(*Args[ArgIndex]);
1183 if (!ArgList)
1184 return;
1185 CurrentBlockFacts.push_back(FactMgr.createFact<InvalidateOriginFact>(
1186 ArgList->getOuterOriginID(), Call));
1187 };
1188
1189 bool HasOwnershipTakesAttr = false;
1190 for (const OwnershipAttr *Attr : FD->specific_attrs<OwnershipAttr>()) {
1191 if (Attr->getOwnKind() != OwnershipAttr::Takes)
1192 continue;
1193 HasOwnershipTakesAttr = true;
1194 for (const ParamIdx &Idx : Attr->args()) {
1195 // Attribute indices count implicit 'this', but constructor Args omits it:
1196 // the first explicit parameter (2) maps to Args[0], not Args[1].
1197 InvalidateArg(Idx.getLLVMIndex() - isa<CXXConstructorDecl>(FD));
1198 }
1199 }
1200 // Allocating/freeing builtins (e.g. `free`, `realloc`) free their first
1201 // argument.
1202 if (!HasOwnershipTakesAttr) {
1203 assert(!Args.empty() && "freeing builtins take at least one argument");
1204 InvalidateArg(0);
1205 }
1206}
1207
1208void FactsGenerator::handleAllocatingCall(const Expr *Call,
1209 const FunctionDecl *FD) {
1210 if (!isAllocatingFunction(*FD))
1211 return;
1212 const auto *CE = dyn_cast<CallExpr>(Call);
1213 if (!CE)
1214 return;
1215 OriginList *CallList = getOriginsList(*Call);
1216 if (!CallList)
1217 return;
1218 const Loan *L = createNewAllocLoan(FactMgr, CE);
1219 CurrentBlockFacts.push_back(
1220 FactMgr.createFact<IssueFact>(L->getID(), CallList->getOuterOriginID()));
1221}
1222
1223void FactsGenerator::handleFunctionCall(const Expr *Call,
1224 bool IsGslConstruction) {
1225 FunctionCallInfo CallInfo(Call);
1226 llvm::ArrayRef<const Expr *> Args = CallInfo.Args;
1227 // The callee may dereference any argument to any depth.
1228 for (const Expr *Arg : Args)
1229 handleUse(Arg);
1230 if (!CallInfo.FD)
1231 return;
1232 OriginList *CallList = getOriginsList(*Call);
1233 // Ignore functions returning values with no origin.
1234 const FunctionDecl *FD = getDeclWithMergedLifetimeBoundAttrs(CallInfo.FD);
1235 if (!FD)
1236 return;
1237 handleInvalidatingCall(Call, FD, Args);
1238 handleDestructiveCall(Call, FD, Args);
1239 handleMovedArgsInCall(FD, Args);
1240 handleImplicitObjectFieldUses(Call, FD);
1241 handleLifetimeCaptureBy(FD, Args);
1242 handleAllocatingCall(Call, FD);
1243 handleFreeingCall(Call, FD, Args);
1244 if (!CallList)
1245 return;
1246 if (isStdReferenceCast(FD)) {
1247 assert(Args.size() == 1 &&
1248 "std reference cast builtins take exactly one argument");
1249 // std reference-cast functions like std::move return a result that refers
1250 // to the same object as the argument, so propagate the full origins.
1251 flow(CallList, getOriginsList(*Args[0]), /*Kill=*/true);
1252 return;
1253 }
1254 auto shouldTrackPointerImplicitObjectArg = [FD, &Args](unsigned I) -> bool {
1255 if (I != 0 || !hasObjectArg(*FD))
1256 return false;
1257 // A by-value explicit object parameter takes a prvalue copy, which is
1258 // handled as an ordinary argument below.
1259 if (!hasImplicitObjectArg(*FD) && !Args[0]->isGLValue())
1260 return false;
1261 const auto *Method = cast<CXXMethodDecl>(FD);
1262 return isGslPointerType(Method->getFunctionObjectParameterType()) &&
1264 /*RunningUnderLifetimeSafety=*/true);
1265 };
1266 if (Args.empty())
1267 return;
1268 bool KillSrc = true;
1269 for (unsigned I = 0; I < Args.size(); ++I) {
1270 OriginList *ArgList = getOriginsList(*Args[I]);
1271 if (!ArgList)
1272 continue;
1273 bool ShouldTrackArg = getTrackedArgInfo(FD, Args, I).has_value();
1274 if (IsGslConstruction) {
1275 // TODO: document with code example.
1276 // std::string_view(const std::string_view& from)
1277 if (isGslPointerType(Args[I]->getType())) {
1278 assert(!Args[I]->isGLValue() || ArgList->getLength() >= 2);
1279 ArgList = readValue(Args[I]);
1280 }
1281 if (isGslOwnerType(Args[I]->getType()) &&
1282 (Args.size() == 1 || ShouldTrackArg)) {
1283 // The constructed gsl::Pointer borrows from the Owner's storage, not
1284 // from what the Owner itself borrows, so only the outermost origin is
1285 // needed.
1286 CurrentBlockFacts.push_back(FactMgr.createFact<OriginFlowFact>(
1287 CallList->getOuterOriginID(), ArgList->getOuterOriginID(),
1288 KillSrc));
1289 KillSrc = false;
1290 } else if (ShouldTrackArg) {
1291 // Only flow the outer origin here. For lifetimebound args in
1292 // gsl::Pointer construction, we do not have enough information to
1293 // safely match inner origins, so the source and
1294 // destination origin lists may have different lengths.
1295 // FIXME: Handle origin-shape mismatches gracefully so we can also flow
1296 // inner origins.
1297 CurrentBlockFacts.push_back(FactMgr.createFact<OriginFlowFact>(
1298 CallList->getOuterOriginID(), ArgList->getOuterOriginID(),
1299 KillSrc));
1300 KillSrc = false;
1301 }
1302 } else if (shouldTrackPointerImplicitObjectArg(I)) {
1303 assert(ArgList->getLength() >= 2 &&
1304 "Object arg of pointer type should have at least two origins");
1305 // See through the GSLPointer reference to see the pointer's value.
1306 CurrentBlockFacts.push_back(FactMgr.createFact<OriginFlowFact>(
1307 CallList->getOuterOriginID(),
1308 ArgList->peelOuterOrigin()->getOuterOriginID(), KillSrc));
1309 KillSrc = false;
1310 } else if (ShouldTrackArg) {
1311 // Lifetimebound on a non-GSL-ctor function means the returned
1312 // pointer/reference itself must not outlive the arguments. This
1313 // only constrains the top-level origin.
1314 CurrentBlockFacts.push_back(FactMgr.createFact<OriginFlowFact>(
1315 CallList->getOuterOriginID(), ArgList->getOuterOriginID(), KillSrc));
1316 KillSrc = false;
1317 }
1318 }
1319}
1320
1321/// Checks if the expression is a `void("__lifetime_test_point_...")` cast.
1322/// If so, creates a `TestPointFact` and returns true.
1323bool FactsGenerator::handleTestPoint(const CXXFunctionalCastExpr *FCE) {
1324 if (!FCE->getType()->isVoidType())
1325 return false;
1326
1327 const auto *SubExpr = ignoreParensAndImpCasts(FCE->getSubExpr());
1328 if (const auto *SL = dyn_cast<StringLiteral>(SubExpr)) {
1329 llvm::StringRef LiteralValue = SL->getString();
1330 const std::string Prefix = "__lifetime_test_point_";
1331
1332 if (LiteralValue.starts_with(Prefix)) {
1333 StringRef Annotation = LiteralValue.drop_front(Prefix.length());
1334 CurrentBlockFacts.push_back(
1335 FactMgr.createFact<TestPointFact>(Annotation));
1336 return true;
1337 }
1338 }
1339 return false;
1340}
1341
1342bool FactsGenerator::namesDeclStorage(const OriginList *List) const {
1343 return FactMgr.getOriginMgr()
1344 .getOrigin(List->getOuterOriginID())
1345 .NamesDeclStorage;
1346}
1347
1348void FactsGenerator::handleAccess(const Expr *E) {
1349 OriginList *List = getOriginsList(*E);
1350 if (!List || namesDeclStorage(List))
1351 return;
1352 CurrentBlockFacts.push_back(FactMgr.createFact<UseFact>(
1353 *E,
1354 FactMgr.getOriginMgr().createSingleOriginList(List->getOuterOriginID())));
1355}
1356
1357void FactsGenerator::handleUse(const Expr *E) {
1358 OriginList *List = getOriginsList(*E);
1359 if (List && namesDeclStorage(List))
1360 List = List->peelOuterOrigin();
1361 if (List)
1362 CurrentBlockFacts.push_back(FactMgr.createFact<UseFact>(*E, List));
1363}
1364
1365// Issues a placeholder loan (this->field) for each origin-carrying field of the
1366// class and its bases. It represents the storage the field refers to, as
1367// opposed to the field itself (covered by $this).
1368void FactsGenerator::issueFieldPlaceholderLoans(
1369 const CXXRecordDecl *ClassDef, llvm::SmallVectorImpl<Fact *> &Facts) {
1370 assert(ClassDef && "class methods have a defined parent");
1371 // Eagerly instantiated methods may see their class still being defined.
1372 assert(ClassDef->isCompleteDefinition() || ClassDef->isBeingDefined());
1373 auto IssueForRecord = [&](const CXXRecordDecl *RD) {
1374 for (const FieldDecl *Field : RD->fields()) {
1375 // Skip private fields of bases as they cannot be named in ClassDef.
1376 if (RD != ClassDef && Field->getAccess() == AS_private)
1377 continue;
1378
1379 if (Field->isAnonymousStructOrUnion()) {
1380 if (const CXXRecordDecl *Sub = Field->getType()->getAsCXXRecordDecl()) {
1381 if (const CXXRecordDecl *SubDef = Sub->getDefinition()) {
1382 // Anonymous records cannot have base classes and they can only have
1383 // public fields. Sema rejects them with an error otherwise.
1384 issueFieldPlaceholderLoans(SubDef, Facts);
1385 continue;
1386 }
1387 }
1388 }
1389 OriginList *FieldList = getOriginsList(*Field);
1390 if (!FieldList)
1391 continue;
1392 const Loan *L = FactMgr.getLoanMgr().createPlaceholderLoan(Field);
1393 Facts.push_back(FactMgr.createFact<IssueFact>(
1394 L->getID(), FieldList->getOuterOriginID()));
1395 }
1396 return true;
1397 };
1398 IssueForRecord(ClassDef);
1399 ClassDef->forallBases(IssueForRecord);
1400}
1401
1402// Creates an IssueFact for a new placeholder loan for each pointer or reference
1403// parameter, the implicit 'this', and (if enabled) each origin-carrying field
1404// at the function's entry.
1405llvm::SmallVector<Fact *> FactsGenerator::issuePlaceholderLoans() {
1406 const auto *FD = dyn_cast<FunctionDecl>(AC.getDecl());
1407 if (!FD)
1408 return {};
1409
1410 llvm::SmallVector<Fact *> PlaceholderLoanFacts;
1411 if (auto ThisOrigins = FactMgr.getOriginMgr().getThisOrigins()) {
1412 OriginList *List = *ThisOrigins;
1413 const auto *MD = cast<CXXMethodDecl>(FD);
1414 const Loan *L = FactMgr.getLoanMgr().createPlaceholderLoan(MD);
1415 PlaceholderLoanFacts.push_back(
1416 FactMgr.createFact<IssueFact>(L->getID(), List->getOuterOriginID()));
1417 if (LSOpts.CheckFieldOriginEscape && !isa<CXXConstructorDecl>(MD))
1418 issueFieldPlaceholderLoans(MD->getParent()->getDefinition(),
1419 PlaceholderLoanFacts);
1420 }
1421 for (const ParmVarDecl *PVD : FD->parameters()) {
1422 OriginList *List = getOriginsList(*PVD);
1423 if (!List)
1424 continue;
1425 const Loan *L = FactMgr.getLoanMgr().createPlaceholderLoan(PVD);
1426 PlaceholderLoanFacts.push_back(
1427 FactMgr.createFact<IssueFact>(L->getID(), List->getOuterOriginID()));
1428 }
1429 return PlaceholderLoanFacts;
1430}
1431
1432} // namespace clang::lifetimes::internal
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
Defines the clang::Expr interface and subclasses for C++ expressions.
static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal, QualType LValType, APValue &Val)
Perform an assignment of Val to LVal. Takes ownership of Val.
TokenType getType() const
Returns the token's type, e.g.
Defines an enumeration for C++ overloaded operators.
QualType getBaseElementType(const ArrayType *VAT) const
Return the innermost element type of an array type.
AbstractConditionalOperator - An abstract base class for ConditionalOperator and BinaryConditionalOpe...
Definition Expr.h:4422
Expr * getTrueExpr() const
getTrueExpr - Return the subexpression representing the value of the expression if the condition eval...
Definition Expr.h:4606
Expr * getFalseExpr() const
getFalseExpr - Return the subexpression representing the value of the expression if the condition eva...
Definition Expr.h:4612
ASTContext & getASTContext() const
ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
Definition Expr.h:2790
inputs_range inputs()
Definition Stmt.h:3404
bool isOutputPlusConstraint(unsigned i) const
isOutputPlusConstraint - Return true if the specified output constraint is a "+" constraint (which is...
Definition Stmt.h:3359
unsigned getNumOutputs() const
Definition Stmt.h:3349
A builtin binary operation expression such as "x + y" or "x <= y".
Definition Expr.h:4107
Expr * getLHS() const
Definition Expr.h:4157
Expr * getRHS() const
Definition Expr.h:4159
static bool isAdditiveOp(Opcode Opc)
Definition Expr.h:4193
static bool isAssignmentOp(Opcode Opc)
Definition Expr.h:4243
static bool isCompoundAssignmentOp(Opcode Opc)
Definition Expr.h:4248
Opcode getOpcode() const
Definition Expr.h:4152
Represents a single basic block in a source-level CFG.
Definition CFG.h:651
pred_range preds()
Definition CFG.h:1037
Represents a top-level expression in a basic block.
Definition CFG.h:55
std::optional< T > getAs() const
Convert to the specified CFGElement type, returning std::nullopt if this CFGElement is not of the des...
Definition CFG.h:113
Represents C++ base or member initializer from constructor's initialization list.
Definition CFG.h:232
Represents the point where the lifetime of an automatic object ends.
Definition CFG.h:321
const VarDecl * getVarDecl() const
Definition CFG.h:326
LLVM_ATTRIBUTE_RETURNS_NONNULL const Stmt * getTriggerStmt() const
Definition CFG.h:300
Represents a source-level, intra-procedural CFG that represents the control-flow of a Stmt.
Definition CFG.h:1294
CFGBlock & getExit()
Definition CFG.h:1410
CFGBlock & getEntry()
Definition CFG.h:1408
Represents binding an expression to a temporary.
Definition ExprCXX.h:1498
const Expr * getSubExpr() const
Definition ExprCXX.h:1520
Represents a call to a C++ constructor.
Definition ExprCXX.h:1553
Expr * getArg(unsigned Arg)
Return the specified argument.
Definition ExprCXX.h:1696
CXXConstructorDecl * getConstructor() const
Get the constructor that this expression will (ultimately) call.
Definition ExprCXX.h:1616
unsigned getNumArgs() const
Return the number of arguments to the constructor call.
Definition ExprCXX.h:1693
bool isCopyOrMoveConstructor(unsigned &TypeQuals) const
Determine whether this is a copy or move constructor.
Definition DeclCXX.cpp:3069
Represents a C++ base or member initializer.
Definition DeclCXX.h:2410
Expr * getInit() const
Get the initializer.
Definition DeclCXX.h:2612
FieldDecl * getAnyMember() const
Definition DeclCXX.h:2556
A default argument (C++ [dcl.fct.default]).
Definition ExprCXX.h:1275
A use of a default initializer in a constructor or in aggregate initialization.
Definition ExprCXX.h:1382
Expr * getExpr()
Get the initialization expression that will be used.
Definition ExprCXX.cpp:1137
Represents a delete expression for memory deallocation and destructor calls, e.g.
Definition ExprCXX.h:2631
Represents an explicit C++ type conversion that uses "functional" notation (C++ [expr....
Definition ExprCXX.h:1836
Represents a call to a member function that may be written either with member call syntax (e....
Definition ExprCXX.h:184
CXXMethodDecl * getMethodDecl() const
Retrieve the declaration of the called method.
Definition ExprCXX.cpp:773
Expr * getImplicitObjectArgument() const
Retrieve the implicit object argument for the member call.
Definition ExprCXX.cpp:754
Represents a new-expression for memory allocation and constructor calls, e.g: "new CXXNewExpr(foo)".
Definition ExprCXX.h:2360
The null pointer literal (C++11 [lex.nullptr])
Definition ExprCXX.h:773
A call to an overloaded operator written using operator syntax.
Definition ExprCXX.h:86
OverloadedOperatorKind getOperator() const
Returns the kind of overloaded operator that this expression refers to.
Definition ExprCXX.h:116
A C++ throw-expression (C++ [except.throw]).
Definition ExprCXX.h:1213
const Expr * getSubExpr() const
Definition ExprCXX.h:1233
A C++ typeid expression (C++ [expr.typeid]), which gets the type_info that corresponds to the supplie...
Definition ExprCXX.h:853
Expr * getExprOperand() const
Definition ExprCXX.h:900
bool isPotentiallyEvaluated() const
Determine whether this typeid has a type operand which is potentially evaluated, per C++11 [expr....
Definition ExprCXX.cpp:136
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition Expr.h:3012
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition Expr.h:3216
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return null.
Definition Expr.h:3195
Expr * getCallee()
Definition Expr.h:3159
unsigned getNumArgs() const
getNumArgs - Return the number of actual arguments to this call.
Definition Expr.h:3203
Decl * getCalleeDecl()
Definition Expr.h:3189
CastExpr - Base class for type casts, including both implicit casts (ImplicitCastExpr) and explicit c...
Definition Expr.h:3745
CastKind getCastKind() const
Definition Expr.h:3789
Expr * getSubExpr()
Definition Expr.h:3795
A reference to a declared variable, function, enum, etc.
Definition Expr.h:1315
NamedDecl * getFoundDecl()
Get the NamedDecl through which this reference occurred.
Definition Expr.h:1426
ValueDecl * getDecl()
Definition Expr.h:1383
DeclStmt - Adaptor class for mixing declarations with statements and expressions.
Definition Stmt.h:1642
decl_range decls()
Definition Stmt.h:1690
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
bool isFunctionOrFunctionTemplate() const
Whether this declaration is a function or function template.
Definition DeclBase.h:1137
bool hasAttr() const
Definition DeclBase.h:586
This represents one expression.
Definition Expr.h:114
bool isGLValue() const
Definition Expr.h:289
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3125
Expr * IgnoreParenBaseCasts() LLVM_READONLY
Skip past any parentheses and derived-to-base casts until reaching a fixed point.
Definition Expr.cpp:3151
QualType getType() const
Definition Expr.h:146
Represents a member of a struct/union/class.
Definition Decl.h:3341
Represents a function declaration or definition.
Definition Decl.h:2082
bool isDefaulted() const
Whether this function is defaulted.
Definition Decl.h:2554
OverloadedOperatorKind getOverloadedOperator() const
getOverloadedOperator - Which C++ overloaded operator this function represents, if any.
Definition Decl.cpp:4206
This represents a GCC inline-assembly statement extension.
Definition Stmt.h:3459
Expr * getOutputExpr(unsigned i)
Definition Stmt.cpp:582
Describes an C or C++ initializer list.
Definition Expr.h:5377
unsigned getNumInits() const
Definition Expr.h:5410
const Expr * getInit(unsigned Init) const
Definition Expr.h:5443
Describes the capture of a variable or of this, or of a C++1y init-capture.
A C++ lambda expression, which produces a function object (of unspecified type) that can be invoked l...
Definition ExprCXX.h:1973
Represents a prvalue temporary that is written into memory so that a reference can bind to it.
Definition ExprCXX.h:4974
StorageDuration getStorageDuration() const
Retrieve the storage duration for the materialized temporary.
Definition ExprCXX.h:4999
Expr * getSubExpr() const
Retrieve the temporary-generating subexpression whose value will be materialized into a glvalue.
Definition ExprCXX.h:4991
ValueDecl * getExtendingDecl()
Get the declaration which triggered the lifetime-extension of this temporary, if any.
Definition ExprCXX.h:5024
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition Expr.h:3433
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition Expr.h:3516
Expr * getBase() const
Definition Expr.h:3510
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition TypeBase.h:3403
A (possibly-)qualified type.
Definition TypeBase.h:938
DestructionKind isDestructedType() const
Returns a nonzero value if objects of this type require non-trivial work to clean up after.
Definition TypeBase.h:1561
ReturnStmt - This represents a return, optionally of an expression: return; return 4;.
Definition Stmt.h:3173
Expr * getRetValue()
Definition Stmt.h:3200
Encodes a location in the source.
StmtExpr - This is the GNU Statement Expression extension: ({int X=4; X;}).
Definition Expr.h:4664
CompoundStmt * getSubStmt()
Definition Expr.h:4681
RetTy Visit(PTR(Stmt) S, ParamTys... P)
Definition StmtVisitor.h:45
SourceLocation getEndLoc() const LLVM_READONLY
Definition Stmt.cpp:367
bool isVoidType() const
Definition TypeBase.h:9200
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition Type.h:26
bool isPointerType() const
Definition TypeBase.h:8815
bool isPointerOrReferenceType() const
Definition TypeBase.h:8819
bool isFunctionType() const
Definition TypeBase.h:8811
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition Expr.h:2313
Expr * getSubExpr() const
Definition Expr.h:2354
Opcode getOpcode() const
Definition Expr.h:2349
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition Decl.h:714
QualType getType() const
Definition Decl.h:725
Represents a variable declaration or definition.
Definition Decl.h:934
static UseSite scopeExit(SourceLocation Loc, const VarDecl &VD, UseKind Kind)
Definition Facts.h:60
Represents the storage location being borrowed, e.g., a specific stack variable or a field within it:...
Definition Loans.h:127
FactType * createFact(Args &&...args)
Definition Facts.h:474
An abstract base class for a single, atomic lifetime-relevant event.
Definition Facts.h:99
const T * getAs() const
Definition Facts.h:141
void VisitDeclRefExpr(const DeclRefExpr *DRE)
void VisitBinaryOperator(const BinaryOperator *BO)
void VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *MTE)
void VisitCXXConstructExpr(const CXXConstructExpr *CCE)
void VisitCXXTypeidExpr(const CXXTypeidExpr *TE)
void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO)
Visits conditional operators (e.g., cond ?
void VisitCXXDeleteExpr(const CXXDeleteExpr *DE)
void VisitCXXFunctionalCastExpr(const CXXFunctionalCastExpr *FCE)
void VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *DIE)
void VisitInitListExpr(const InitListExpr *ILE)
void VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *DAE)
void VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *N)
void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *OCE)
void VisitArraySubscriptExpr(const ArraySubscriptExpr *ASE)
void VisitUnaryOperator(const UnaryOperator *UO)
void VisitCXXThrowExpr(const CXXThrowExpr *TE)
void VisitCXXMemberCallExpr(const CXXMemberCallExpr *MCE)
void VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *BTE)
Represents that an origin's storage has been invalidated by a container operation (e....
Definition Facts.h:379
Loan * createLoan(AccessPath Path, const Expr *IssueExpr=nullptr)
Definition Loans.h:238
Represents a component of an access path: either a named field access or an abstract unnamed interior...
Definition Loans.h:214
A list of origins representing levels of indirection for pointer-like types.
Definition Origins.h:105
OriginList * peelOuterOrigin() const
Definition Origins.h:109
std::optional< OriginList * > getThisOrigins() const
Returns the OriginList for the implicit 'this' parameter if the current declaration is an instance me...
Definition Origins.h:163
Represents that an origin escapes via a return statement.
Definition Facts.h:252
bool Sub(InterpState &S, CodePtr OpPC)
Definition Interp.h:426
utils::ID< struct OriginTag > OriginID
Definition Origins.h:28
static const Loan * createLoan(FactManager &FactMgr, const ValueDecl &VD, const Expr *IssueExpr)
Creates a loan for the storage path of a given declaration.
static const Loan * createNewAllocLoan(FactManager &FactMgr, const CallExpr *CE)
Creates a loan for a heap allocation made by a call (e.g.
static const CFGBlock * findPredBlockForExpr(const CFGBlock *MergeBlock, const Expr *ArmExpr)
bool doesDeclHaveStorage(const ValueDecl *D)
Returns true if the declaration has its own storage that can be borrowed.
Definition Origins.cpp:197
const Expr * ignoreParensAndImpCasts(const Expr *E)
bool isFreeingFunction(const FunctionDecl &FD)
bool isGslPointerType(QualType QT)
bool isStdCallableWrapperType(const CXXRecordDecl *RD)
bool shouldTrackImplicitObjectArg(const Expr &ImplicitObjectArgument, const CXXMethodDecl *Callee, bool RunningUnderLifetimeSafety)
bool isPointerLikeType(QualType QT)
bool hasObjectArg(const FunctionDecl &FD)
bool isUniquePtrRelease(const CXXMethodDecl &MD)
bool isStdReferenceCast(const FunctionDecl *FD)
bool hasImplicitObjectArg(const FunctionDecl &FD)
const FunctionDecl * getDeclWithMergedLifetimeBoundAttrs(const FunctionDecl *FD)
bool isInvalidationMethod(const CXXMethodDecl &MD)
bool destructsFirstArg(const FunctionDecl &FD)
bool isGslOwnerType(QualType QT)
std::optional< LifetimeBoundParamInfo > getTrackedArgInfo(const FunctionDecl *FD, llvm::ArrayRef< const Expr * > Args, unsigned I)
bool isAllocatingFunction(const FunctionDecl &FD)
const LifetimeCaptureByAttr * getCaptureByAttrFromFunctionType(const FunctionDecl *FD)
const ParmVarDecl * getParamForArg(const FunctionDecl &FD, unsigned I)
bool isa(CodeGen::Address addr)
Definition Address.h:330
@ AS_private
Definition Specifiers.h:130
@ SD_Automatic
Automatic storage duration (most local variables).
Definition Specifiers.h:343
U cast(CodeGen::Address addr)
Definition Address.h:327
bool CheckDestructorUses
Whether to model non-trivial destructors at scope exit as uses.