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 reference.
91/// This function should be called whenever a DeclRefExpr represents a borrow.
92/// \param DRE The declaration reference expression that initiates the borrow.
93/// \return The new Loan on success, nullptr otherwise.
94static const Loan *createLoan(FactManager &FactMgr, const DeclRefExpr *DRE) {
95 const ValueDecl *VD = DRE->getDecl();
96 AccessPath Path(VD);
97 // The loan is created at the location of the DeclRefExpr.
98 return FactMgr.getLoanMgr().createLoan(Path, DRE);
99}
100
101/// Creates a loan for the storage location of a temporary object.
102/// \param MTE The MaterializeTemporaryExpr that represents the temporary
103/// binding. \return The new Loan.
104static const Loan *createLoan(FactManager &FactMgr,
105 const MaterializeTemporaryExpr *MTE) {
106 AccessPath Path(MTE);
107 return FactMgr.getLoanMgr().createLoan(Path, MTE);
108}
109
110/// Creates a loan for an allocation through 'new'
111/// \param NE The CXXNewExpr that represents the allocation
112/// \return The new Loan on success, nullptr otherwise
113static const Loan *createLoan(FactManager &FactMgr, const CXXNewExpr *NE) {
114 AccessPath Path(NE);
115 return FactMgr.getLoanMgr().createLoan(Path, NE);
116}
117
119 llvm::TimeTraceScope TimeProfile("FactGenerator");
120 const CFG &Cfg = *AC.getCFG();
121 llvm::SmallVector<Fact *> PlaceholderLoanFacts = issuePlaceholderLoans();
122 // Iterate through the CFG blocks in reverse post-order to ensure that
123 // initializations and destructions are processed in the correct sequence.
124 for (const CFGBlock *Block : *AC.getAnalysis<PostOrderCFGView>()) {
125 CurrentBlockFacts.clear();
126 EscapesInCurrentBlock.clear();
127 CurrentBlock = Block;
128 if (Block == &Cfg.getEntry())
129 CurrentBlockFacts.append(PlaceholderLoanFacts.begin(),
130 PlaceholderLoanFacts.end());
131 for (unsigned I = 0; I < Block->size(); ++I) {
132 const CFGElement &Element = Block->Elements[I];
133 if (std::optional<CFGStmt> CS = Element.getAs<CFGStmt>())
134 Visit(CS->getStmt());
135 else if (std::optional<CFGInitializer> Initializer =
136 Element.getAs<CFGInitializer>())
137 handleCXXCtorInitializer(Initializer->getInitializer());
138 else if (std::optional<CFGLifetimeEnds> LifetimeEnds =
139 Element.getAs<CFGLifetimeEnds>())
140 handleLifetimeEnds(*LifetimeEnds);
141 else if (std::optional<CFGFullExprCleanup> FullExprCleanup =
142 Element.getAs<CFGFullExprCleanup>()) {
143 handleFullExprCleanup(*FullExprCleanup);
144 }
145 }
146 if (Block == &Cfg.getExit())
147 handleExitBlock();
148
149 CurrentBlockFacts.append(EscapesInCurrentBlock.begin(),
150 EscapesInCurrentBlock.end());
151 FactMgr.addBlockFacts(Block, CurrentBlockFacts);
152 }
153 FactMgr.computePersistentOrigins(Cfg);
154}
155
156/// Simulates LValueToRValue conversion by peeling the outer lvalue origin
157/// if the expression is a GLValue. For pointer/view GLValues, this strips
158/// the origin representing the storage location to get the origins of the
159/// pointed-to value.
160///
161/// Example: For `View& v`, returns the origin of what v points to, not v's
162/// storage.
163static OriginList *getRValueOrigins(const Expr *E, OriginList *List) {
164 if (!List)
165 return nullptr;
166 return E->isGLValue() ? List->peelOuterOrigin() : List;
167}
168
170 for (const Decl *D : DS->decls())
171 if (const auto *VD = dyn_cast<VarDecl>(D))
172 if (const Expr *InitExpr = VD->getInit()) {
173 OriginList *VDList = getOriginsList(*VD);
174 if (!VDList)
175 continue;
176 OriginList *InitList = getOriginsList(*InitExpr);
177 assert(InitList && "VarDecl had origins but InitExpr did not");
178 flow(VDList, InitList, /*Kill=*/true);
179 }
180}
181
183 // Skip function references as their lifetimes are not interesting. Skip non
184 // GLValues (like EnumConstants).
185 if (DRE->getFoundDecl()->isFunctionOrFunctionTemplate() || !DRE->isGLValue())
186 return;
187 handleUse(DRE);
188 // For all declarations with storage (non-references), we issue a loan
189 // representing the borrow of the variable's storage itself.
190 //
191 // Examples:
192 // - `int x; x` issues loan to x's storage
193 // - `int* p; p` issues loan to p's storage (the pointer variable)
194 // - `View v; v` issues loan to v's storage (the view object)
195 // - `int& r = x; r` issues no loan (r has no storage, it's an alias to x)
196 if (doesDeclHaveStorage(DRE->getDecl())) {
197 const Loan *L = createLoan(FactMgr, DRE);
198 assert(L);
199 OriginList *List = getOriginsList(*DRE);
200 assert(List &&
201 "gl-value DRE of non-pointer type should have an origin list");
202 // This loan specifically tracks borrowing the variable's storage location
203 // itself and is issued to outermost origin (List->OID).
204 CurrentBlockFacts.push_back(
205 FactMgr.createFact<IssueFact>(L->getID(), List->getOuterOriginID()));
206 }
207}
208
210 if (isGslPointerType(CCE->getType())) {
211 handleGSLPointerConstruction(CCE);
212 return;
213 }
214 // For defaulted (implicit or `= default`) copy/move constructors, propagate
215 // origins directly. User-defined copy/move constructors are not handled here
216 // as they have opaque semantics.
218 CCE->getConstructor()->isDefaulted() && CCE->getNumArgs() == 1 &&
219 hasOrigins(CCE->getType())) {
220 const Expr *Arg = CCE->getArg(0);
221 if (OriginList *ArgList = getRValueOrigins(Arg, getOriginsList(*Arg))) {
222 flow(getOriginsList(*CCE), ArgList, /*Kill=*/true);
223 return;
224 }
225 }
226 // Standard library callable wrappers (e.g., std::function) propagate the
227 // stored lambda's origins.
228 if (const auto *RD = CCE->getType()->getAsCXXRecordDecl();
229 RD && isStdCallableWrapperType(RD) && CCE->getNumArgs() == 1) {
230 const Expr *Arg = CCE->getArg(0);
231 if (OriginList *ArgList = getRValueOrigins(Arg, getOriginsList(*Arg))) {
232 flow(getOriginsList(*CCE), ArgList, /*Kill=*/true);
233 return;
234 }
235 }
236 auto [FD, Args] = getFunctionCallInfo(CCE);
237 handleFunctionCall(CCE, FD, Args,
238 /*IsGslConstruction=*/false);
239}
240
242 if (const Expr *Init = DIE->getExpr())
243 killAndFlowOrigin(*DIE, *Init);
244}
245
246void FactsGenerator::handleCXXCtorInitializer(const CXXCtorInitializer *CII) {
247 // Flows origins from the initializer expression to the field.
248 // Example: `MyObj(std::string s) : view(s) {}`
249 if (const FieldDecl *FD = CII->getAnyMember())
250 killAndFlowOrigin(*FD, *CII->getInit());
251}
252
254 // Specifically for conversion operators,
255 // like `std::string_view p = std::string{};`
256 if (isGslPointerType(MCE->getType()) &&
257 isa_and_present<CXXConversionDecl>(MCE->getCalleeDecl()) &&
259 auto [FD, Args] = getFunctionCallInfo(MCE);
260 handleFunctionCall(MCE, FD, Args,
261 /*IsGslConstruction=*/true);
262 return;
263 }
264 auto [FD, Args] = getFunctionCallInfo(MCE);
265 handleFunctionCall(MCE, FD, Args, /*IsGslConstruction=*/false);
266}
267
269 auto *MD = ME->getMemberDecl();
270 if (isa<FieldDecl>(MD) && doesDeclHaveStorage(MD)) {
271 assert(ME->isGLValue() && "Field member should be GL value");
272 OriginList *Dst = getOriginsList(*ME);
273 assert(Dst && "Field member should have an origin list as it is GL value");
274 OriginList *Src = getOriginsList(*ME->getBase());
275 assert(Src && "Base expression should be a pointer/reference type");
276 // The field's glvalue (outermost origin) holds the same loans as the base
277 // expression.
278 CurrentBlockFacts.push_back(FactMgr.createFact<OriginFlowFact>(
279 Dst->getOuterOriginID(), Src->getOuterOriginID(),
280 /*Kill=*/true));
281 }
282}
283
285 auto [FD, Args] = getFunctionCallInfo(CE);
286 handleFunctionCall(CE, FD, Args);
287}
288
290 const CXXNullPtrLiteralExpr *N) {
291 /// TODO: Handle nullptr expr as a special 'null' loan. Uninitialized
292 /// pointers can use the same type of loan.
293 getOriginsList(*N);
294}
295
297 OriginList *Dest = getOriginsList(*CE);
298 if (!Dest)
299 return;
300 const Expr *SubExpr = CE->getSubExpr();
301 OriginList *Src = getOriginsList(*SubExpr);
302
303 switch (CE->getCastKind()) {
304 case CK_LValueToRValue:
305 if (!SubExpr->isGLValue())
306 return;
307
308 assert(Src && "LValue being cast to RValue has no origin list");
309 // The result of an LValue-to-RValue cast on a pointer lvalue (like `q` in
310 // `int *p, *q; p = q;`) should propagate the inner origin (what the pointer
311 // points to), not the outer origin (the pointer's storage location). Strip
312 // the outer lvalue origin.
313 flow(getOriginsList(*CE), getRValueOrigins(SubExpr, Src),
314 /*Kill=*/true);
315 return;
316 case CK_NullToPointer:
317 getOriginsList(*CE);
318 // TODO: Flow into them a null origin.
319 return;
320 case CK_NoOp:
321 case CK_ConstructorConversion:
322 case CK_UserDefinedConversion:
323 flow(Dest, Src, /*Kill=*/true);
324 return;
325 case CK_UncheckedDerivedToBase:
326 case CK_DerivedToBase:
327 // It is possible that the derived class and base class have different
328 // gsl::Pointer annotations. Skip if their origin shape differ.
329 if (Dest && Src && Dest->getLength() == Src->getLength())
330 flow(Dest, Src, /*Kill=*/true);
331 return;
332 case CK_ArrayToPointerDecay:
333 // va_arg(ap, array_type) is UB and does not provide addressable array
334 // storage to model.
335 if (isa<VAArgExpr>(SubExpr->IgnoreParens()))
336 return;
337 assert(Src && "Array expression should have origins as it is GL value");
338 CurrentBlockFacts.push_back(FactMgr.createFact<OriginFlowFact>(
339 Dest->getOuterOriginID(), Src->getOuterOriginID(), /*Kill=*/true));
340 return;
341 case CK_FunctionToPointerDecay:
342 case CK_BuiltinFnToFnPtr:
343 // Ignore function-to-pointer decays.
344 return;
345 case CK_BitCast:
346 // OriginLists for Src and Dst may differ here. For example when casting
347 // from int** to void*
348 if (Src && Dest && Dest->getLength() == Src->getLength())
349 flow(Dest, Src, /*Kill=*/true);
350 return;
351 case CK_LValueToRValueBitCast:
352 case CK_NonAtomicToAtomic:
353 case CK_AtomicToNonAtomic: {
354 // `__builtin_bit_cast`/`std::bit_cast` of a pointer, and
355 // wrapping/unwrapping `_Atomic(T*)`, preserve the pointer value, so
356 // propagate the borrow. The operand may be a glvalue, so strip its outer
357 // lvalue level first. A bit-cast that materializes a pointer from a
358 // non-pointer representation has no matching source origin and is
359 // untracked.
360 OriginList *RVSrc = getRValueOrigins(SubExpr, Src);
361 if (RVSrc && Dest->getLength() == RVSrc->getLength())
362 flow(Dest, RVSrc, /*Kill=*/true);
363 return;
364 }
365 default:
366 return;
367 }
368}
369
371 switch (UO->getOpcode()) {
372 case UO_AddrOf: {
373 const Expr *SubExpr = UO->getSubExpr();
374 // Function addresses do not need lifetime tracking.
375 if (SubExpr->getType()->isFunctionType())
376 return;
377 // Skip address-of on void expressions: GNU C permits them, but void itself
378 // has no origins to track.
379 if (IsCMode && SubExpr->getType()->isVoidType())
380 return;
381 assert(!SubExpr->getType()->isVoidType() &&
382 "Taking address of void is not valid in C++");
383 // The origin of an address-of expression (e.g., &x) is the origin of
384 // its sub-expression (x). This fact will cause the dataflow analysis
385 // to propagate any loans held by the sub-expression's origin to the
386 // origin of this UnaryOperator expression.
387 killAndFlowOrigin(*UO, *SubExpr);
388 return;
389 }
390 case UO_Deref: {
391 const Expr *SubExpr = UO->getSubExpr();
392 killAndFlowOrigin(*UO, *SubExpr);
393 return;
394 }
395 case UO_Plus: {
396 // Unary plus on a pointer is the identity (`+p == p`), so the prvalue
397 // result carries the operand's loans. Flow the operand's rvalue origins
398 // (peeling storage only when the operand is itself a glvalue).
399 if (!UO->getType()->isPointerType())
400 return;
401 const Expr *SubExpr = UO->getSubExpr();
402 flow(getOriginsList(*UO),
403 getRValueOrigins(SubExpr, getOriginsList(*SubExpr)), /*Kill=*/true);
404 return;
405 }
406 case UO_PreInc:
407 case UO_PostInc:
408 case UO_PreDec:
409 case UO_PostDec: {
410 // Inc/dec keeps a pointer in the same allocation, so the result carries the
411 // operand's loans. Peel the operand's storage origin when the *result* is a
412 // prvalue (post-inc/dec, or any form in C) -- the inverse of
413 // getRValueOrigins, which peels when its own argument is a glvalue.
414 if (!UO->getType()->isPointerType())
415 return;
416 OriginList *SubList = getOriginsList(*UO->getSubExpr());
417 flow(getOriginsList(*UO),
418 UO->isGLValue() ? SubList : SubList->peelOuterOrigin(), /*Kill=*/true);
419 return;
420 }
421 default:
422 return;
423 }
424}
425
427 if (const Expr *RetExpr = RS->getRetValue()) {
428 if (OriginList *List = getOriginsList(*RetExpr))
429 for (OriginList *L = List; L != nullptr; L = L->peelOuterOrigin())
430 EscapesInCurrentBlock.push_back(FactMgr.createFact<ReturnEscapeFact>(
431 L->getOuterOriginID(), RetExpr));
432 }
433}
434
435void FactsGenerator::handleAssignment(const Expr *TargetExpr,
436 const Expr *LHSExpr,
437 const Expr *RHSExpr) {
438 LHSExpr = LHSExpr->IgnoreParenImpCasts();
439 OriginList *LHSList = nullptr;
440
441 if (const auto *DRE_LHS = dyn_cast<DeclRefExpr>(LHSExpr)) {
442 LHSList = getOriginsList(*DRE_LHS);
443 assert(LHSList && "LHS is a DRE and should have an origin list");
444 }
445 // Handle assignment to member fields (e.g., `this->view = s` or `view = s`).
446 // This enables detection of dangling fields when local values escape to
447 // fields.
448 if (const auto *ME_LHS = dyn_cast<MemberExpr>(LHSExpr)) {
449 LHSList = getOriginsList(*ME_LHS);
450 assert(LHSList && "LHS is a MemberExpr and should have an origin list");
451 }
452 if (!LHSList)
453 return;
454 OriginList *RHSList = getOriginsList(*RHSExpr);
455 // For operator= with reference parameters (e.g.,
456 // `View& operator=(const View&)`), the RHS argument stays an lvalue,
457 // unlike built-in assignment where LValueToRValue cast strips the outer
458 // lvalue origin. Strip it manually to get the actual value origins being
459 // assigned.
460 RHSList = getRValueOrigins(RHSExpr, RHSList);
461
462 if (const auto *DRE_LHS = dyn_cast<DeclRefExpr>(LHSExpr)) {
463 QualType QT = DRE_LHS->getDecl()->getType();
464 if (QT->isReferenceType()) {
465 if (hasOrigins(QT->getPointeeType())) {
466 // Writing through a reference uses the binding but overwrites the
467 // pointee. Model this as a Read of the outer origin (keeping the
468 // binding live) and a Write of the inner origins (killing the pointee's
469 // liveness).
470 if (UseFact *UF = UseFacts.lookup(DRE_LHS)) {
471 const OriginList *FullList = UF->getUsedOrigins();
472 assert(FullList);
473 UF->setUsedOrigins(FactMgr.getOriginMgr().createSingleOriginList(
474 FullList->getOuterOriginID()));
475 if (const OriginList *InnerList = FullList->peelOuterOrigin()) {
476 UseFact *WriteUF = FactMgr.createFact<UseFact>(DRE_LHS, InnerList);
477 WriteUF->markAsWritten();
478 CurrentBlockFacts.push_back(WriteUF);
479 }
480 }
481 }
482 } else
483 markUseAsWrite(DRE_LHS);
484 }
485 if (!RHSList) {
486 // RHS has no tracked origins (e.g., assigning a callable without origins
487 // to std::function). Clear loans of the destination.
488 for (OriginList *LHSInner = LHSList->peelOuterOrigin(); LHSInner;
489 LHSInner = LHSInner->peelOuterOrigin())
490 CurrentBlockFacts.push_back(
491 FactMgr.createFact<KillOriginFact>(LHSInner->getOuterOriginID()));
492 return;
493 }
494 // Kill the old loans of the destination origin and flow the new loans
495 // from the source origin.
496 flow(LHSList->peelOuterOrigin(), RHSList, /*Kill=*/true);
497
498 // In C, assignment expressions are not GLValues, so the assignment result has
499 // the assigned value origins, not the LHS storage origin.
500 if (IsCMode)
501 LHSList = getRValueOrigins(LHSExpr, LHSList);
502 flow(getOriginsList(*TargetExpr), LHSList, /*Kill=*/true);
503}
504
505void FactsGenerator::handlePointerArithmetic(const BinaryOperator *BO) {
506 if (Expr *RHS = BO->getRHS(); RHS->getType()->isPointerType()) {
507 killAndFlowOrigin(*BO, *RHS);
508 return;
509 }
510 Expr *LHS = BO->getLHS();
511 assert(LHS->getType()->isPointerType() &&
512 "Pointer arithmetic must have a pointer operand");
513 killAndFlowOrigin(*BO, *LHS);
514}
515
517 if (BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI) {
518 // `obj.*pm` / `objptr->*pm` names a member of the object, so a borrow of it
519 // borrows the object; flow the object's origin into the result. For `.*`
520 // the object is the LHS; for `->*` it is the LHS pointer's pointee.
521 //
522 // Only the result's outer (storage) origin relates to the object: borrowing
523 // the member borrows the object's storage. Deeper levels of the result (a
524 // pointer/view member's own pointee) are the member's value, with no
525 // counterpart in the object's origin -- so the lists may differ in length
526 // and we flow just the top level, leaving the member's value untouched.
527 OriginList *Dst = getOriginsList(*BO);
528 OriginList *ObjSrc =
529 BO->getOpcode() == BO_PtrMemD
530 ? getOriginsList(*BO->getLHS())
531 : getRValueOrigins(BO->getLHS(), getOriginsList(*BO->getLHS()));
532 if (Dst && ObjSrc)
533 CurrentBlockFacts.push_back(FactMgr.createFact<OriginFlowFact>(
534 Dst->getOuterOriginID(), ObjSrc->getOuterOriginID(), /*Kill=*/true));
535 handleUse(BO->getLHS());
536 return;
537 }
538 if (BO->getOpcode() == BO_Comma) {
539 killAndFlowOrigin(*BO, *BO->getRHS());
540 return;
541 }
542 if (BO->isCompoundAssignmentOp()) {
543 // A pointer compound additive assignment (`p += n`) carries the LHS's loans
544 // like inc/dec above; in C the result is a prvalue, so peel its outer
545 // (storage) origin.
546 if (BO->getType()->isPointerType()) {
547 OriginList *LHSList = getOriginsList(*BO->getLHS());
548 flow(getOriginsList(*BO), IsCMode ? LHSList->peelOuterOrigin() : LHSList,
549 /*Kill=*/true);
550 }
551 return;
552 }
553 if (BO->getType()->isPointerType() && BO->isAdditiveOp())
554 handlePointerArithmetic(BO);
555 handleUse(BO->getRHS());
556 if (BO->isAssignmentOp())
557 handleAssignment(BO, BO->getLHS(), BO->getRHS());
558 // TODO: Handle assignments involving dereference like `*p = q`.
559}
560
561static const CFGBlock *findPredBlockForExpr(const CFGBlock *MergeBlock,
562 const Expr *ArmExpr) {
563 if (!ArmExpr)
564 return nullptr;
565 const Expr *Target = ArmExpr->IgnoreParenImpCasts();
566 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(Target))
567 if (const Expr *Src = OVE->getSourceExpr())
568 Target = Src->IgnoreParenImpCasts();
569
570 for (const CFGBlock *Pred : MergeBlock->preds()) {
571 if (!Pred)
572 continue;
573 for (const CFGElement &Elt : *Pred)
574 if (auto CS = Elt.getAs<CFGStmt>())
575 if (const auto *E = dyn_cast<Expr>(CS->getStmt()))
576 if (E->IgnoreParenImpCasts() == Target)
577 return Pred;
578 }
579 return nullptr;
580}
581
582/// Visits conditional operators (e.g., `cond ? a : b`).
583///
584/// To prevent liveness leakage across loop backedges (which causes false
585/// positives like in `while (...) { int x; consume(cond ? &x : nullptr); }`),
586/// we generate the flow facts in the respective predecessor blocks of the arms
587/// rather than in the merge block. This ensures that the liveness of the
588/// temporary origin from one arm does not propagate into the other arm's path.
590 const AbstractConditionalOperator *CO) {
591 if (!hasOrigins(CO))
592 return;
593
594 const Expr *TrueExpr = CO->getTrueExpr();
595 const Expr *FalseExpr = CO->getFalseExpr();
596
597 if (const CFGBlock *TBPred = findPredBlockForExpr(CurrentBlock, TrueExpr))
598 flow(getOriginsList(*CO), getOriginsList(*TrueExpr), /*Kill=*/true, TBPred);
599 if (const CFGBlock *FBPred = findPredBlockForExpr(CurrentBlock, FalseExpr))
600 flow(getOriginsList(*CO), getOriginsList(*FalseExpr), /*Kill=*/true,
601 FBPred);
602}
603
605 // Assignment operators have special "kill-then-propagate" semantics
606 // and are handled separately.
607 if (OCE->getOperator() == OO_Equal && OCE->getNumArgs() == 2 &&
608 hasOrigins(OCE->getArg(0)->getType())) {
609 // Pointer-like types: assignment inherently propagates origins.
610 QualType LHSTy = OCE->getArg(0)->getType();
611 if (LHSTy->isPointerOrReferenceType() || isGslPointerType(LHSTy) ||
612 isGslOwnerType(LHSTy)) {
613 handleAssignment(OCE, OCE->getArg(0), OCE->getArg(1));
614 return;
615 }
616 // Standard library callable wrappers (e.g., std::function) can propagate
617 // the stored lambda's origins.
618 if (const auto *RD = LHSTy->getAsCXXRecordDecl();
619 RD && isStdCallableWrapperType(RD)) {
620 handleAssignment(OCE, OCE->getArg(0), OCE->getArg(1));
621 return;
622 }
623 // Other tracked types: only defaulted operator= propagates origins.
624 // User-defined operator= has opaque semantics, so don't handle them now.
625 if (const auto *MD =
626 dyn_cast_or_null<CXXMethodDecl>(OCE->getDirectCallee());
627 MD && MD->isDefaulted()) {
628 handleAssignment(OCE, OCE->getArg(0), OCE->getArg(1));
629 return;
630 }
631 }
632
633 auto [FD, Args] = getFunctionCallInfo(OCE);
634 handleFunctionCall(OCE, FD, Args);
635}
636
638 const CXXFunctionalCastExpr *FCE) {
639 // Check if this is a test point marker. If so, we are done with this
640 // expression.
641 if (handleTestPoint(FCE))
642 return;
643 VisitCastExpr(FCE);
644}
645
647 if (!hasOrigins(ILE))
648 return;
649 // For list initialization with a single element, like `View{...}`, the
650 // origin of the list itself is the origin of its single element.
651 if (ILE->getNumInits() == 1) {
652 // A type with origins may be list-initialized from an element with none
653 // (e.g., an int). Only flow if the element carries any.
654 if (!hasOrigins(ILE->getInit(0)))
655 return;
656 killAndFlowOrigin(*ILE, *ILE->getInit(0));
657 }
658}
659
661 const CXXBindTemporaryExpr *BTE) {
662 killAndFlowOrigin(*BTE, *BTE->getSubExpr());
663}
664
666 const MaterializeTemporaryExpr *MTE) {
667 assert(MTE->isGLValue());
668 OriginList *MTEList = getOriginsList(*MTE);
669 if (!MTEList)
670 return;
671 OriginList *SubExprList = getOriginsList(*MTE->getSubExpr());
672 assert((!SubExprList ||
673 MTEList->getLength() == (SubExprList->getLength() + 1)) &&
674 "MTE top level origin should contain a loan to the MTE itself");
675
676 OriginList *RValMTEList = getRValueOrigins(MTE, MTEList);
677 flow(RValMTEList, SubExprList, /*Kill=*/true);
678 OriginID OuterMTEID = MTEList->getOuterOriginID();
680 // Issue a loan to MTE for the storage location represented by MTE.
681 const Loan *L = createLoan(FactMgr, MTE);
682 CurrentBlockFacts.push_back(
683 FactMgr.createFact<IssueFact>(L->getID(), OuterMTEID));
684 }
685}
686
688 for (const LambdaCapture &C : LE->captures()) {
689 if (C.capturesThis())
690 FactMgr.setThisCapturedByLambda();
691 else if (C.capturesVariable() && C.getCapturedVar()->isInitCapture()) {
692 const Expr *Init = cast<VarDecl>(C.getCapturedVar())->getInit();
693 if (!Init)
694 continue;
695 if (const auto *ME = dyn_cast<MemberExpr>(Init->IgnoreParenImpCasts())) {
696 if (const auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
697 FactMgr.addCapturedField(FD);
698 }
699 }
700 }
701
702 // The lambda gets a single merged origin that aggregates all captured
703 // pointer-like origins. Currently we only need to detect whether the lambda
704 // outlives any capture.
705 OriginList *LambdaList = getOriginsList(*LE);
706 if (!LambdaList)
707 return;
708 bool Kill = true;
709 for (const Expr *Init : LE->capture_inits()) {
710 if (!Init)
711 continue;
712 OriginList *InitList = getOriginsList(*Init);
713 if (!InitList)
714 continue;
715 // FIXME: Consider flowing all origin levels once lambdas support more than
716 // one origin. Currently only the outermost origin is flowed, so by-ref
717 // captures like `[&p]` (where p is string_view) miss inner-level
718 // invalidation.
719 CurrentBlockFacts.push_back(FactMgr.createFact<OriginFlowFact>(
720 LambdaList->getOuterOriginID(), InitList->getOuterOriginID(), Kill));
721 Kill = false;
722 }
723}
724
726 // Some C subscripts do not refer to addressable storage with origins, such as
727 // GNU void-pointer subscripts and vector element extraction from rvalues.
728 if (IsCMode && !ASE->isGLValue())
729 return;
730 assert(ASE->isGLValue() && "Array subscript should be a GL value");
731 OriginList *Dst = getOriginsList(*ASE);
732 assert(Dst && "Array subscript should have origins as it is a GL value");
733 OriginList *Src = getOriginsList(*ASE->getBase());
734 assert(Src && "Base of array subscript should have origins");
735 CurrentBlockFacts.push_back(FactMgr.createFact<OriginFlowFact>(
736 Dst->getOuterOriginID(), Src->getOuterOriginID(), /*Kill=*/true));
737}
738
739bool FactsGenerator::handlePlacementNew(const CXXNewExpr *NE,
740 OriginList *NewList) {
741 // Model only the standard single-argument placement new form, where the
742 // placement argument corresponds to a void* allocation-function parameter.
743 // Other placement forms, such as std::nothrow, are not modeled as providing
744 // storage for the returned pointer.
745 if (NE->getNumPlacementArgs() != 1)
746 return false;
747
748 const FunctionDecl *OperatorNew = NE->getOperatorNew();
749 if (OperatorNew->getNumParams() <= 1)
750 return false;
751
752 const auto *Arg =
753 OperatorNew->getParamDecl(1)->getType()->getAs<PointerType>();
754 if (!Arg || !Arg->isVoidPointerType())
755 return false;
756
757 // Use the placement argument before the implicit conversion to void*, so
758 // inner origins are still available.
759 const Expr *PlacementArg = NE->getPlacementArg(0);
760 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(PlacementArg);
761 ICE && ICE->getCastKind() == CK_BitCast &&
762 PlacementArg->getType()->isVoidPointerType())
763 PlacementArg = ICE->getSubExpr();
764 OriginList *PlacementList = getOriginsList(*PlacementArg);
765 // FIXME: General placement arguments need separate handling to overwrite
766 // the right origins.
767
768 // The pointer returned by placement new comes from the placement
769 // argument.
770 if (PlacementList)
771 CurrentBlockFacts.push_back(FactMgr.createFact<OriginFlowFact>(
772 NewList->getOuterOriginID(), PlacementList->getOuterOriginID(), true));
773 return true;
774}
775
777 OriginList *NewList = getOriginsList(*NE);
778 const Expr *Init = NE->getInitializer();
779
780 bool HandledAsPlacementNew = false;
781 if (NE->getNumPlacementArgs() == 1)
782 HandledAsPlacementNew = handlePlacementNew(NE, NewList);
783
784 // Treat ordinary new and replaceable global allocation forms as heap
785 // allocations.
786 const FunctionDecl *OperatorNew = NE->getOperatorNew();
787 if (!HandledAsPlacementNew &&
788 (NE->getNumPlacementArgs() == 0 ||
789 (OperatorNew && OperatorNew->isReplaceableGlobalAllocationFunction()))) {
790 const Loan *L = createLoan(FactMgr, NE);
791 CurrentBlockFacts.push_back(
792 FactMgr.createFact<IssueFact>(L->getID(), NewList->getOuterOriginID()));
793 }
794
795 NewList = NewList->peelOuterOrigin();
796
797 if (!NewList || !Init)
798 return;
799
800 // FIXME: OriginList is null for `new[]` initializers. Remove this `Init`
801 // check once array origins are supported.
802 if (OriginList *InitList = getOriginsList(*Init); InitList)
803 flow(NewList, InitList, true);
804}
805
807 OriginList *List = getOriginsList(*DE->getArgument());
808 CurrentBlockFacts.push_back(
809 FactMgr.createFact<InvalidateOriginFact>(List->getOuterOriginID(), DE));
810}
811
813 // A statement expression (`({ ...; e; })`) yields the value of its final
814 // expression `e`. Flow `e`'s origins into the statement expression's origin
815 // so a borrow `e` carries reaches the value's users.
816 const auto *CS = SE->getSubStmt();
817 if (!CS || CS->body_empty())
818 return;
819 const auto *Last = dyn_cast<Expr>(CS->body_back());
820 if (!Last)
821 return;
822 if (OriginList *Dst = getOriginsList(*SE))
823 if (OriginList *Src = getRValueOrigins(Last, getOriginsList(*Last)))
824 flow(Dst, Src, /*Kill=*/true);
825}
826
827bool FactsGenerator::escapesViaReturn(OriginID OID) const {
828 return llvm::any_of(EscapesInCurrentBlock, [OID](const Fact *F) {
829 if (const auto *EF = F->getAs<ReturnEscapeFact>())
830 return EF->getEscapedOriginID() == OID;
831 return false;
832 });
833}
834
835void FactsGenerator::handleLifetimeEnds(const CFGLifetimeEnds &LifetimeEnds) {
836 const VarDecl *LifetimeEndsVD = LifetimeEnds.getVarDecl();
837 if (!LifetimeEndsVD)
838 return;
839 // Expire the origin when its variable's lifetime ends to ensure liveness
840 // doesn't persist through loop back-edges.
841 std::optional<OriginID> ExpiredOID;
842 if (OriginList *List = getOriginsList(*LifetimeEndsVD)) {
843 OriginID OID = List->getOuterOriginID();
844 // Skip origins that escape via return; the escape checker needs their loans
845 // to remain until the return statement is processed.
846 if (!escapesViaReturn(OID))
847 ExpiredOID = OID;
848 }
849 CurrentBlockFacts.push_back(FactMgr.createFact<ExpireFact>(
850 AccessPath(LifetimeEndsVD), LifetimeEnds.getTriggerStmt()->getEndLoc(),
851 ExpiredOID));
852}
853
854void FactsGenerator::handleFullExprCleanup(
855 const CFGFullExprCleanup &FullExprCleanup) {
856 for (const auto *MTE : FullExprCleanup.getExpiringMTEs())
857 CurrentBlockFacts.push_back(FactMgr.createFact<ExpireFact>(
858 AccessPath(MTE), FullExprCleanup.getCleanupLoc()));
859}
860
861void FactsGenerator::handleExitBlock() {
862 bool IsDestructor = isa_and_nonnull<CXXDestructorDecl>(AC.getDecl());
863 for (const Origin &O : FactMgr.getOriginMgr().getOrigins())
864 // Create FieldEscapeFacts for all field origins that remain live at exit.
865 // Fields in destructors do not escape since the object is being destroyed.
866 if (auto *FD = dyn_cast_if_present<FieldDecl>(O.getDecl());
867 FD && !IsDestructor)
868 EscapesInCurrentBlock.push_back(
869 FactMgr.createFact<FieldEscapeFact>(O.ID, FD));
870 else if (auto *VD = dyn_cast_if_present<VarDecl>(O.getDecl())) {
871 // Create GlobalEscapeFacts for all origins with global-storage that
872 // remain live at exit.
873 if (VD->hasGlobalStorage()) {
874 EscapesInCurrentBlock.push_back(
875 FactMgr.createFact<GlobalEscapeFact>(O.ID, VD));
876 }
877 }
878}
879
880void FactsGenerator::handleGSLPointerConstruction(const CXXConstructExpr *CCE) {
881 assert(isGslPointerType(CCE->getType()));
882 if (CCE->getNumArgs() != 1)
883 return;
884
885 const Expr *Arg = CCE->getArg(0);
886 if (isGslPointerType(Arg->getType())) {
887 OriginList *ArgList = getOriginsList(*Arg);
888 assert(ArgList && "GSL pointer argument should have an origin list");
889 // GSL pointer is constructed from another gsl pointer.
890 // Example:
891 // View(View v);
892 // View(const View &v);
893 ArgList = getRValueOrigins(Arg, ArgList);
894 flow(getOriginsList(*CCE), ArgList, /*Kill=*/true);
895 } else if (Arg->getType()->isPointerType()) {
896 // GSL pointer is constructed from a raw pointer. Flow only the outermost
897 // raw pointer. Example:
898 // View(const char*);
899 // Span<int*>(const in**);
900 OriginList *ArgList = getOriginsList(*Arg);
901 CurrentBlockFacts.push_back(FactMgr.createFact<OriginFlowFact>(
902 getOriginsList(*CCE)->getOuterOriginID(), ArgList->getOuterOriginID(),
903 /*Kill=*/true));
904 } else {
905 // This could be a new borrow.
906 // TODO: Add code example here.
907 auto [FD, Args] = getFunctionCallInfo(CCE);
908 handleFunctionCall(CCE, FD, Args,
909 /*IsGslConstruction=*/true);
910 }
911}
912
913void FactsGenerator::handleMovedArgsInCall(const FunctionDecl *FD,
914 ArrayRef<const Expr *> Args) {
915 unsigned ImplicitObjectArgOffset = 0;
916 // Constructors are excluded because Args has no object argument for them,
917 // even though isImplicitObjectMemberFunction() is true.
918 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD);
919 MD && !isa<CXXConstructorDecl>(FD) &&
920 MD->isImplicitObjectMemberFunction()) {
921 ImplicitObjectArgOffset = 1;
922 // std::unique_ptr::release() transfers ownership.
923 // Treat it as a move to prevent false-positive warnings when the unique_ptr
924 // destructor runs after ownership has been transferred.
925 if (isUniquePtrRelease(*MD)) {
926 const Expr *UniquePtrExpr = Args[0];
927 OriginList *MovedOrigins = getOriginsList(*UniquePtrExpr);
928 if (MovedOrigins)
929 CurrentBlockFacts.push_back(FactMgr.createFact<MovedOriginFact>(
930 UniquePtrExpr, MovedOrigins->getOuterOriginID()));
931 }
932 }
933
934 // Skip implicit 'this' arg as it cannot be moved.
935 for (unsigned I = ImplicitObjectArgOffset;
936 I < Args.size() && I < FD->getNumParams() + ImplicitObjectArgOffset;
937 ++I) {
938 const ParmVarDecl *PVD = FD->getParamDecl(I - ImplicitObjectArgOffset);
939 // In principle, explicit object parameters can be moved, but skip marking
940 // them as moved for consistency with implicit 'this'.
941 if (PVD->isExplicitObjectParameter())
942 continue;
943 if (!PVD->getType()->isRValueReferenceType())
944 continue;
945 // Skip lifetime annotated r-value reference parameters. Lifetime annotation
946 // indicates that the parameter is borrowed (not consumed), so it should not
947 // be marked as moved even though it's an r-value reference.
948 if (PVD->hasAttr<LifetimeBoundAttr>() ||
949 PVD->hasAttr<LifetimeCaptureByAttr>())
950 continue;
951 const Expr *Arg = Args[I];
952 OriginList *MovedOrigins = getOriginsList(*Arg);
953 assert(MovedOrigins->getLength() >= 1 &&
954 "unexpected length for r-value reference param");
955 // Arg is being moved to this parameter. Mark the origin as moved.
956 CurrentBlockFacts.push_back(FactMgr.createFact<MovedOriginFact>(
957 Arg, MovedOrigins->getOuterOriginID()));
958 }
959}
960
961void FactsGenerator::handleInvalidatingCall(const Expr *Call,
962 const FunctionDecl *FD,
963 ArrayRef<const Expr *> Args) {
964 const auto *MD = dyn_cast<CXXMethodDecl>(FD);
965 if (!MD || !MD->isInstance())
966 return;
967
968 if (!isInvalidationMethod(*MD))
969 return;
970
971 // Heuristics to turn-down false positives. Skip member field expressions for
972 // now. This is not a perfect filter and will still surface some false
973 // positives (e.g. `auto& r = s.v`).
974 if (!isa<DeclRefExpr>(Args[0]->IgnoreImpCasts()))
975 return;
976
977 OriginList *ThisList = getOriginsList(*Args[0]);
978 if (ThisList)
979 CurrentBlockFacts.push_back(FactMgr.createFact<InvalidateOriginFact>(
980 ThisList->getOuterOriginID(), Call));
981}
982
983void FactsGenerator::handleDestructiveCall(const Expr *Call,
984 const FunctionDecl *FD,
985 ArrayRef<const Expr *> Args) {
986 if (!destructsFirstArg(*FD))
987 return;
988 OriginList *ArgList = getOriginsList(*Args[0]);
989 if (ArgList)
990 CurrentBlockFacts.push_back(FactMgr.createFact<InvalidateOriginFact>(
991 ArgList->getOuterOriginID(), Call));
992}
993
994void FactsGenerator::handleImplicitObjectFieldUses(const Expr *Call,
995 const FunctionDecl *FD) {
996 const auto *MemberCall = dyn_cast_or_null<CXXMemberCallExpr>(Call);
997 if (!MemberCall)
998 return;
999
1000 if (!isa_and_present<CXXThisExpr>(
1001 MemberCall->getImplicitObjectArgument()->IgnoreImpCasts()))
1002 return;
1003
1004 const auto *MD = dyn_cast<CXXMethodDecl>(FD);
1005 assert(MD && "Function must be a CXXMethodDecl for member calls");
1006
1007 const auto *ClassDecl = MD->getParent()->getDefinition();
1008 if (!ClassDecl)
1009 return;
1010
1011 const auto UseFields = [&](const CXXRecordDecl *RD) {
1012 for (const auto *Field : RD->fields())
1013 if (auto *FieldList = getOriginsList(*Field))
1014 CurrentBlockFacts.push_back(
1015 FactMgr.createFact<UseFact>(Call, FieldList));
1016 };
1017
1018 UseFields(ClassDecl);
1019
1020 ClassDecl->forallBases([&](const CXXRecordDecl *Base) {
1021 UseFields(Base);
1022 return true;
1023 });
1024}
1025
1026void FactsGenerator::handleLifetimeCaptureBy(const FunctionDecl *FD,
1027 ArrayRef<const Expr *> Args) {
1028 if (Args.empty())
1029 return;
1030 // FIXME: Add support for capture_by on constructors.
1032 return;
1033 const auto *Method = dyn_cast<CXXMethodDecl>(FD);
1034 bool IsInstance =
1035 Method && Method->isInstance() && !isa<CXXConstructorDecl>(FD);
1036 auto getParamDeclAt = [FD, IsInstance](unsigned I) -> const ParmVarDecl * {
1037 if (IsInstance) {
1038 // FIXME: Add support for I == 0 i.e. capture_by on function declarations
1039 if (I > 0 && I - 1 < FD->getNumParams())
1040 return FD->getParamDecl(I - 1);
1041 } else {
1042 if (I < FD->getNumParams())
1043 return FD->getParamDecl(I);
1044 }
1045 return nullptr;
1046 };
1047 for (unsigned I = 0; I < Args.size(); ++I) {
1048 const ParmVarDecl *PVD = getParamDeclAt(I);
1049 if (!PVD)
1050 continue;
1051 const auto *Attr = PVD->getAttr<LifetimeCaptureByAttr>();
1052 if (!Attr)
1053 continue;
1054 OriginList *CapturedOriginList = getOriginsList(*Args[I]);
1055 if (!CapturedOriginList)
1056 continue;
1057 // For references to pointer-like types, peel the outer origin (the pointer
1058 // object itself) so that we capture the underlying data (the inner origin).
1059 if (QualType ParamType = PVD->getType();
1060 (ParamType->isReferenceType() &&
1061 isPointerLikeType(ParamType->getPointeeType())) &&
1062 CapturedOriginList->getLength() > 1)
1063 CapturedOriginList = CapturedOriginList->peelOuterOrigin();
1064 for (int CapturingArgIdx : Attr->params()) {
1065 // FIXME: Add support for capturing to Global/unknown.
1066 if (CapturingArgIdx == LifetimeCaptureByAttr::Global ||
1067 CapturingArgIdx == LifetimeCaptureByAttr::Unknown ||
1068 CapturingArgIdx == LifetimeCaptureByAttr::Invalid)
1069 continue;
1070 ArrayRef<const Expr *> CallArgs = IsInstance ? Args.drop_front() : Args;
1071 const Expr *CapturedByArg =
1072 (CapturingArgIdx == LifetimeCaptureByAttr::This)
1073 ? Args[0]
1074 : CallArgs[CapturingArgIdx];
1075 assert(CapturedByArg && "Capturer expression must be valid");
1076
1077 OriginList *CapturingOriginList = getOriginsList(*CapturedByArg);
1078 OriginList *Dest = getRValueOrigins(CapturedByArg, CapturingOriginList);
1079 if (!Dest)
1080 continue;
1081 // KillDest=false because we cannot know if previous captures are being
1082 // replaced or accumulated. Multiple successive captures into the same
1083 // destination must all be tracked, so captured lifetimes are always
1084 // merged.
1085 CurrentBlockFacts.push_back(FactMgr.createFact<OriginFlowFact>(
1086 Dest->getOuterOriginID(), CapturedOriginList->getOuterOriginID(),
1087 /*KillDest=*/false));
1088 }
1089 }
1090}
1091
1092void FactsGenerator::handleFunctionCall(const Expr *Call,
1093 const FunctionDecl *FD,
1094 ArrayRef<const Expr *> Args,
1095 bool IsGslConstruction) {
1096 OriginList *CallList = getOriginsList(*Call);
1097 // Ignore functions returning values with no origin.
1099 if (!FD)
1100 return;
1101 // All arguments to a function are a use of the corresponding expressions.
1102 for (const Expr *Arg : Args)
1103 handleUse(Arg);
1104 handleInvalidatingCall(Call, FD, Args);
1105 handleDestructiveCall(Call, FD, Args);
1106 handleMovedArgsInCall(FD, Args);
1107 handleImplicitObjectFieldUses(Call, FD);
1108 handleLifetimeCaptureBy(FD, Args);
1109 if (!CallList)
1110 return;
1111 if (isStdReferenceCast(FD)) {
1112 assert(Args.size() == 1 &&
1113 "std reference cast builtins take exactly one argument");
1114 // std reference-cast functions like std::move return a result that refers
1115 // to the same object as the argument, so propagate the full origins.
1116 flow(CallList, getOriginsList(*Args[0]), /*Kill=*/true);
1117 return;
1118 }
1119 auto shouldTrackPointerImplicitObjectArg = [FD, &Args](unsigned I) -> bool {
1120 const auto *Method = dyn_cast<CXXMethodDecl>(FD);
1121 if (!Method || !Method->isInstance())
1122 return false;
1123 return I == 0 &&
1124 isGslPointerType(Method->getFunctionObjectParameterType()) &&
1126 /*RunningUnderLifetimeSafety=*/true);
1127 };
1128 if (Args.empty())
1129 return;
1130 bool KillSrc = true;
1131 for (unsigned I = 0; I < Args.size(); ++I) {
1132 OriginList *ArgList = getOriginsList(*Args[I]);
1133 if (!ArgList)
1134 continue;
1135 bool ShouldTrackArg = getTrackedArgInfo(FD, Args, I).has_value();
1136 if (IsGslConstruction) {
1137 // TODO: document with code example.
1138 // std::string_view(const std::string_view& from)
1139 if (isGslPointerType(Args[I]->getType())) {
1140 assert(!Args[I]->isGLValue() || ArgList->getLength() >= 2);
1141 ArgList = getRValueOrigins(Args[I], ArgList);
1142 }
1143 if (isGslOwnerType(Args[I]->getType())) {
1144 // The constructed gsl::Pointer borrows from the Owner's storage, not
1145 // from what the Owner itself borrows, so only the outermost origin is
1146 // needed.
1147 CurrentBlockFacts.push_back(FactMgr.createFact<OriginFlowFact>(
1148 CallList->getOuterOriginID(), ArgList->getOuterOriginID(),
1149 KillSrc));
1150 KillSrc = false;
1151 } else if (ShouldTrackArg) {
1152 // Only flow the outer origin here. For lifetimebound args in
1153 // gsl::Pointer construction, we do not have enough information to
1154 // safely match inner origins, so the source and
1155 // destination origin lists may have different lengths.
1156 // FIXME: Handle origin-shape mismatches gracefully so we can also flow
1157 // inner origins.
1158 CurrentBlockFacts.push_back(FactMgr.createFact<OriginFlowFact>(
1159 CallList->getOuterOriginID(), ArgList->getOuterOriginID(),
1160 KillSrc));
1161 KillSrc = false;
1162 }
1163 } else if (shouldTrackPointerImplicitObjectArg(I)) {
1164 assert(ArgList->getLength() >= 2 &&
1165 "Object arg of pointer type should have at least two origins");
1166 // See through the GSLPointer reference to see the pointer's value.
1167 CurrentBlockFacts.push_back(FactMgr.createFact<OriginFlowFact>(
1168 CallList->getOuterOriginID(),
1169 ArgList->peelOuterOrigin()->getOuterOriginID(), KillSrc));
1170 KillSrc = false;
1171 } else if (ShouldTrackArg) {
1172 // Lifetimebound on a non-GSL-ctor function means the returned
1173 // pointer/reference itself must not outlive the arguments. This
1174 // only constrains the top-level origin.
1175 CurrentBlockFacts.push_back(FactMgr.createFact<OriginFlowFact>(
1176 CallList->getOuterOriginID(), ArgList->getOuterOriginID(), KillSrc));
1177 KillSrc = false;
1178 }
1179 }
1180}
1181
1182/// Checks if the expression is a `void("__lifetime_test_point_...")` cast.
1183/// If so, creates a `TestPointFact` and returns true.
1184bool FactsGenerator::handleTestPoint(const CXXFunctionalCastExpr *FCE) {
1185 if (!FCE->getType()->isVoidType())
1186 return false;
1187
1188 const auto *SubExpr = FCE->getSubExpr()->IgnoreParenImpCasts();
1189 if (const auto *SL = dyn_cast<StringLiteral>(SubExpr)) {
1190 llvm::StringRef LiteralValue = SL->getString();
1191 const std::string Prefix = "__lifetime_test_point_";
1192
1193 if (LiteralValue.starts_with(Prefix)) {
1194 StringRef Annotation = LiteralValue.drop_front(Prefix.length());
1195 CurrentBlockFacts.push_back(
1196 FactMgr.createFact<TestPointFact>(Annotation));
1197 return true;
1198 }
1199 }
1200 return false;
1201}
1202
1203void FactsGenerator::handleUse(const Expr *E) {
1204 OriginList *List = getOriginsList(*E);
1205 if (!List)
1206 return;
1207 // For DeclRefExpr: Remove the outer layer of origin which borrows from the
1208 // decl directly (e.g., when this is not a reference). This is a use of the
1209 // underlying decl.
1210 if (auto *DRE = dyn_cast<DeclRefExpr>(E);
1211 DRE && !DRE->getDecl()->getType()->isReferenceType())
1212 List = getRValueOrigins(DRE, List);
1213 // Skip if there is no inner origin (e.g., when it is not a pointer type).
1214 if (!List)
1215 return;
1216 if (!UseFacts.contains(E)) {
1217 UseFact *UF = FactMgr.createFact<UseFact>(E, List);
1218 CurrentBlockFacts.push_back(UF);
1219 UseFacts[E] = UF;
1220 }
1221}
1222
1223void FactsGenerator::markUseAsWrite(const DeclRefExpr *DRE) {
1224 if (UseFacts.contains(DRE))
1225 UseFacts[DRE]->markAsWritten();
1226}
1227
1228// Creates an IssueFact for a new placeholder loan for each pointer or reference
1229// parameter at the function's entry.
1230llvm::SmallVector<Fact *> FactsGenerator::issuePlaceholderLoans() {
1231 const auto *FD = dyn_cast<FunctionDecl>(AC.getDecl());
1232 if (!FD)
1233 return {};
1234
1235 llvm::SmallVector<Fact *> PlaceholderLoanFacts;
1236 if (auto ThisOrigins = FactMgr.getOriginMgr().getThisOrigins()) {
1237 OriginList *List = *ThisOrigins;
1238 const Loan *L =
1239 FactMgr.getLoanMgr().createPlaceholderLoan(cast<CXXMethodDecl>(FD));
1240 PlaceholderLoanFacts.push_back(
1241 FactMgr.createFact<IssueFact>(L->getID(), List->getOuterOriginID()));
1242 }
1243 for (const ParmVarDecl *PVD : FD->parameters()) {
1244 OriginList *List = getOriginsList(*PVD);
1245 if (!List)
1246 continue;
1247 const Loan *L = FactMgr.getLoanMgr().createPlaceholderLoan(PVD);
1248 PlaceholderLoanFacts.push_back(
1249 FactMgr.createFact<IssueFact>(L->getID(), List->getOuterOriginID()));
1250 }
1251 return PlaceholderLoanFacts;
1252}
1253
1254} // 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.
TokenType getType() const
Returns the token's type, e.g.
Defines an enumeration for C++ overloaded operators.
AbstractConditionalOperator - An abstract base class for ConditionalOperator and BinaryConditionalOpe...
Definition Expr.h:4364
Expr * getTrueExpr() const
getTrueExpr - Return the subexpression representing the value of the expression if the condition eval...
Definition Expr.h:4548
Expr * getFalseExpr() const
getFalseExpr - Return the subexpression representing the value of the expression if the condition eva...
Definition Expr.h:4554
ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
Definition Expr.h:2732
A builtin binary operation expression such as "x + y" or "x <= y".
Definition Expr.h:4049
Expr * getLHS() const
Definition Expr.h:4099
Expr * getRHS() const
Definition Expr.h:4101
static bool isAdditiveOp(Opcode Opc)
Definition Expr.h:4135
static bool isAssignmentOp(Opcode Opc)
Definition Expr.h:4185
static bool isCompoundAssignmentOp(Opcode Opc)
Definition Expr.h:4190
Opcode getOpcode() const
Definition Expr.h:4094
Represents a single basic block in a source-level CFG.
Definition CFG.h:652
pred_range preds()
Definition CFG.h:1029
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:1271
CFGBlock & getExit()
Definition CFG.h:1387
CFGBlock & getEntry()
Definition CFG.h:1385
Represents binding an expression to a temporary.
Definition ExprCXX.h:1496
const Expr * getSubExpr() const
Definition ExprCXX.h:1518
Represents a call to a C++ constructor.
Definition ExprCXX.h:1551
Expr * getArg(unsigned Arg)
Return the specified argument.
Definition ExprCXX.h:1694
CXXConstructorDecl * getConstructor() const
Get the constructor that this expression will (ultimately) call.
Definition ExprCXX.h:1614
unsigned getNumArgs() const
Return the number of arguments to the constructor call.
Definition ExprCXX.h:1691
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:2402
Expr * getInit() const
Get the initializer.
Definition DeclCXX.h:2604
FieldDecl * getAnyMember() const
Definition DeclCXX.h:2548
A use of a default initializer in a constructor or in aggregate initialization.
Definition ExprCXX.h:1380
Expr * getExpr()
Get the initialization expression that will be used.
Definition ExprCXX.cpp:1112
Represents a delete expression for memory deallocation and destructor calls, e.g.
Definition ExprCXX.h:2629
Represents an explicit C++ type conversion that uses "functional" notation (C++ [expr....
Definition ExprCXX.h:1834
Represents a call to a member function that may be written either with member call syntax (e....
Definition ExprCXX.h:182
Expr * getImplicitObjectArgument() const
Retrieve the implicit object argument for the member call.
Definition ExprCXX.cpp:729
Represents a new-expression for memory allocation and constructor calls, e.g: "new CXXNewExpr(foo)".
Definition ExprCXX.h:2358
The null pointer literal (C++11 [lex.nullptr])
Definition ExprCXX.h:771
A call to an overloaded operator written using operator syntax.
Definition ExprCXX.h:84
OverloadedOperatorKind getOperator() const
Returns the kind of overloaded operator that this expression refers to.
Definition ExprCXX.h:114
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition Expr.h:2954
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition Expr.h:3158
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return null.
Definition Expr.h:3137
unsigned getNumArgs() const
getNumArgs - Return the number of actual arguments to this call.
Definition Expr.h:3145
Decl * getCalleeDecl()
Definition Expr.h:3131
CastExpr - Base class for type casts, including both implicit casts (ImplicitCastExpr) and explicit c...
Definition Expr.h:3687
CastKind getCastKind() const
Definition Expr.h:3731
Expr * getSubExpr()
Definition Expr.h:3737
A reference to a declared variable, function, enum, etc.
Definition Expr.h:1281
NamedDecl * getFoundDecl()
Get the NamedDecl through which this reference occurred.
Definition Expr.h:1392
ValueDecl * getDecl()
Definition Expr.h:1349
DeclStmt - Adaptor class for mixing declarations with statements and expressions.
Definition Stmt.h:1640
decl_range decls()
Definition Stmt.h:1688
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:1136
This represents one expression.
Definition Expr.h:112
bool isGLValue() const
Definition Expr.h:287
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
Definition Expr.cpp:3101
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3097
QualType getType() const
Definition Expr.h:144
Represents a member of a struct/union/class.
Definition Decl.h:3294
Represents a function declaration or definition.
Definition Decl.h:2058
bool isDefaulted() const
Whether this function is defaulted.
Definition Decl.h:2511
Describes an C or C++ initializer list.
Definition Expr.h:5319
unsigned getNumInits() const
Definition Expr.h:5352
const Expr * getInit(unsigned Init) const
Definition Expr.h:5374
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:1971
Represents a prvalue temporary that is written into memory so that a reference can bind to it.
Definition ExprCXX.h:4919
StorageDuration getStorageDuration() const
Retrieve the storage duration for the materialized temporary.
Definition ExprCXX.h:4944
Expr * getSubExpr() const
Retrieve the temporary-generating subexpression whose value will be materialized into a glvalue.
Definition ExprCXX.h:4936
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition Expr.h:3375
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition Expr.h:3458
Expr * getBase() const
Definition Expr.h:3452
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition TypeBase.h:3408
A (possibly-)qualified type.
Definition TypeBase.h:938
ReturnStmt - This represents a return, optionally of an expression: return; return 4;.
Definition Stmt.h:3169
Expr * getRetValue()
Definition Stmt.h:3196
StmtExpr - This is the GNU Statement Expression extension: ({int X=4; X;}).
Definition Expr.h:4606
CompoundStmt * getSubStmt()
Definition Expr.h:4623
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:9113
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:8741
bool isReferenceType() const
Definition TypeBase.h:8765
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:789
bool isPointerOrReferenceType() const
Definition TypeBase.h:8745
bool isFunctionType() const
Definition TypeBase.h:8737
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition Expr.h:2255
Expr * getSubExpr() const
Definition Expr.h:2296
Opcode getOpcode() const
Definition Expr.h:2291
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition Decl.h:712
Represents a variable declaration or definition.
Definition Decl.h:932
Represents the storage location being borrowed, e.g., a specific stack variable or a field within it:...
Definition Loans.h:113
FactType * createFact(Args &&...args)
Definition Facts.h:368
An abstract base class for a single, atomic lifetime-relevant event.
Definition Facts.h:40
const T * getAs() const
Definition Facts.h:82
void VisitDeclRefExpr(const DeclRefExpr *DRE)
void VisitBinaryOperator(const BinaryOperator *BO)
void VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *MTE)
void VisitCXXConstructExpr(const CXXConstructExpr *CCE)
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 VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *N)
void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *OCE)
void VisitArraySubscriptExpr(const ArraySubscriptExpr *ASE)
void VisitUnaryOperator(const UnaryOperator *UO)
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:273
Loan * createLoan(AccessPath Path, const Expr *IssueExpr=nullptr)
Definition Loans.h:215
Represents a component of an access path: either a named field access or an abstract unnamed interior...
Definition Loans.h:191
A list of origins representing levels of indirection for pointer-like types.
Definition Origins.h:95
OriginList * peelOuterOrigin() const
Definition Origins.h:99
OriginList * createSingleOriginList(OriginID OID)
Wraps an existing OriginID in a new single-element OriginList, so a fact can refer to a single level ...
Definition Origins.cpp:225
Represents that an origin escapes via a return statement.
Definition Facts.h:190
utils::ID< struct OriginTag > OriginID
Definition Origins.h:28
static OriginList * getRValueOrigins(const Expr *E, OriginList *List)
Simulates LValueToRValue conversion by peeling the outer lvalue origin if the expression is a GLValue...
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:192
static const Loan * createLoan(FactManager &FactMgr, const DeclRefExpr *DRE)
Creates a loan for the storage path of a given declaration reference.
FunctionCallInfo getFunctionCallInfo(const Expr *Call)
bool isGslPointerType(QualType QT)
bool isStdCallableWrapperType(const CXXRecordDecl *RD)
bool shouldTrackImplicitObjectArg(const Expr &ImplicitObjectArgument, const CXXMethodDecl *Callee, bool RunningUnderLifetimeSafety)
bool isPointerLikeType(QualType QT)
bool isUniquePtrRelease(const CXXMethodDecl &MD)
bool isStdReferenceCast(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 isa(CodeGen::Address addr)
Definition Address.h:330
@ SD_FullExpression
Full-expression storage duration (for temporaries).
Definition Specifiers.h:341
U cast(CodeGen::Address addr)
Definition Address.h:327