clang 23.0.0git
FactsGenerator.h
Go to the documentation of this file.
1//===- FactsGenerator.h - 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// This file defines the FactsGenerator, which traverses the AST to generate
10// lifetime-relevant facts (such as loan issuance, expiration, origin flow,
11// and use) from CFG statements. These facts are used by the dataflow analyses
12// to track pointer lifetimes and detect use-after-free errors.
13//
14//===----------------------------------------------------------------------===//
15#ifndef LLVM_CLANG_ANALYSIS_ANALYSES_LIFETIMESAFETY_FACTSGENERATOR_H
16#define LLVM_CLANG_ANALYSIS_ANALYSES_LIFETIMESAFETY_FACTSGENERATOR_H
17
22#include "clang/Analysis/CFG.h"
23#include "llvm/ADT/SmallVector.h"
24
26
27class FactsGenerator : public ConstStmtVisitor<FactsGenerator> {
29
30public:
32 : FactMgr(FactMgr), AC(AC),
33 IsCMode(!AC.getASTContext().getLangOpts().CPlusPlus &&
34 !AC.getASTContext().getLangOpts().ObjC) {}
35
36 void run();
37
38 void VisitDeclStmt(const DeclStmt *DS);
39 void VisitDeclRefExpr(const DeclRefExpr *DRE);
43 void VisitMemberExpr(const MemberExpr *ME);
44 void VisitCallExpr(const CallExpr *CE);
46 void VisitCastExpr(const CastExpr *CE);
47 void VisitUnaryOperator(const UnaryOperator *UO);
48 void VisitReturnStmt(const ReturnStmt *RS);
49 void VisitBinaryOperator(const BinaryOperator *BO);
53 void VisitInitListExpr(const InitListExpr *ILE);
56 void VisitLambdaExpr(const LambdaExpr *LE);
58 void VisitCXXNewExpr(const CXXNewExpr *NE);
59 void VisitCXXDeleteExpr(const CXXDeleteExpr *DE);
60 void VisitStmtExpr(const StmtExpr *SE);
61
62private:
63 OriginList *getOriginsList(const ValueDecl &D);
64 OriginList *getOriginsList(const Expr &E);
65
66 bool hasOrigins(QualType QT) const;
67 bool hasOrigins(const Expr *E) const;
68
69 void flow(OriginList *Dst, OriginList *Src, bool Kill,
70 const CFGBlock *Block = nullptr);
71
72 /// Handles assignment for both BinaryOperator and CXXOperatorCallExpr.
73 ///
74 /// LHSExpr is the destination whose stored loans are replaced by RHSExpr's
75 /// loans. TargetExpr is the assignment expression itself; it receives
76 /// LHSExpr's origins so chained assignments like `a = b = c` can propagate
77 /// through the result of `b = c`.
78 void handleAssignment(const Expr *TargetExpr, const Expr *LHSExpr,
79 const Expr *RHSExpr);
80
81 void handlePointerArithmetic(const BinaryOperator *BO);
82
83 bool handlePlacementNew(const CXXNewExpr *NE, OriginList *NewList);
84
85 void handleCXXCtorInitializer(const CXXCtorInitializer *CII);
86
87 void handleLifetimeEnds(const CFGLifetimeEnds &LifetimeEnds);
88
89 void handleFullExprCleanup(const CFGFullExprCleanup &FullExprCleanup);
90
91 void handleExitBlock();
92
93 /// Mark all fields of the implicit object as used for an instance method
94 /// call, since the callee may access any part of the object.
95 void handleImplicitObjectFieldUses(const Expr *Call, const FunctionDecl *FD);
96
97 void handleGSLPointerConstruction(const CXXConstructExpr *CCE);
98
99 /// Detects arguments passed to rvalue reference parameters and creates
100 /// MovedOriginFact for them. The MovedLoansAnalysis then uses these facts
101 /// to track in a flow-sensitive manner which loans have been moved at each
102 /// program point, allowing warnings to distinguish potentially moved storage
103 /// from other use-after-free errors.
104 void handleMovedArgsInCall(const FunctionDecl *FD,
106
107 // Handles [[clang::lifetime_capture_by(X)]] annotations on a function call to
108 // create flow facts from captured arguments to the capturer
109 void handleLifetimeCaptureBy(const FunctionDecl *FD,
111
112 /// Checks if a call-like expression creates a borrow by passing a value to a
113 /// reference parameter, creating an IssueFact if it does.
114 /// \param IsGslConstruction True if this is a GSL construction where all
115 /// argument origins should flow to the returned origin.
116 void handleFunctionCall(const Expr *Call, const FunctionDecl *FD,
118 bool IsGslConstruction = false);
119
120 // Detect methods that invalidate iterators/references/pointees.
121 // For instance methods, Args[0] is the implicit 'this' pointer.
122 void handleInvalidatingCall(const Expr *Call, const FunctionDecl *FD,
124
125 // Detect explicit destructor calls/`std::destroy_at`
126 void handleDestructiveCall(const Expr *Call, const FunctionDecl *FD,
128
129 template <typename Destination, typename Source>
130 void flowOrigin(const Destination &D, const Source &S) {
131 flow(getOriginsList(D), getOriginsList(S), /*Kill=*/false);
132 }
133
134 template <typename Destination, typename Source>
135 void killAndFlowOrigin(const Destination &D, const Source &S) {
136 flow(getOriginsList(D), getOriginsList(S), /*Kill=*/true);
137 }
138
139 /// Checks if the expression is a `void("__lifetime_test_point_...")` cast.
140 /// If so, creates a `TestPointFact` and returns true.
141 bool handleTestPoint(const CXXFunctionalCastExpr *FCE);
142
143 // Treats an expression as a use of the referenced object. It will be
144 // checked for use-after-free unless it is later marked as being written to
145 // (e.g. on the left-hand side of an assignment in the case of a DeclRefExpr).
146 void handleUse(const Expr *E);
147
148 void markUseAsWrite(const DeclRefExpr *DRE);
149
150 bool escapesViaReturn(OriginID OID) const;
151
152 llvm::SmallVector<Fact *> issuePlaceholderLoans();
153 FactManager &FactMgr;
155 llvm::SmallVector<Fact *> CurrentBlockFacts;
156 // Collect origins that escape the function in this block (OriginEscapesFact),
157 // appended at the end of CurrentBlockFacts to ensure they appear after
158 // ExpireFact entries.
159 llvm::SmallVector<Fact *> EscapesInCurrentBlock;
160 // To distinguish between reads and writes for use-after-free checks, this map
161 // stores the `UseFact` for each `DeclRefExpr`. We initially identify all
162 // `DeclRefExpr`s as "read" uses. When an assignment is processed, the use
163 // corresponding to the left-hand side is updated to be a "write", thereby
164 // exempting it from the check.
165 llvm::DenseMap<const Expr *, UseFact *> UseFacts;
166 const CFGBlock *CurrentBlock;
167 bool IsCMode = false;
168};
169
170} // namespace clang::lifetimes::internal
171
172#endif // LLVM_CLANG_ANALYSIS_ANALYSES_LIFETIMESAFETY_FACTSGENERATOR_H
This file defines AnalysisDeclContext, a class that manages the analysis context data for context sen...
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.
AbstractConditionalOperator - An abstract base class for ConditionalOperator and BinaryConditionalOpe...
Definition Expr.h:4359
AnalysisDeclContext contains the context data for the function, method or block under analysis.
ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
Definition Expr.h:2727
A builtin binary operation expression such as "x + y" or "x <= y".
Definition Expr.h:4044
Represents a single basic block in a source-level CFG.
Definition CFG.h:652
Represents the point where the lifetime of an automatic object ends.
Definition CFG.h:321
Represents binding an expression to a temporary.
Definition ExprCXX.h:1497
Represents a call to a C++ constructor.
Definition ExprCXX.h:1552
Represents a C++ base or member initializer.
Definition DeclCXX.h:2398
A use of a default initializer in a constructor or in aggregate initialization.
Definition ExprCXX.h:1381
Represents a delete expression for memory deallocation and destructor calls, e.g.
Definition ExprCXX.h:2630
Represents an explicit C++ type conversion that uses "functional" notation (C++ [expr....
Definition ExprCXX.h:1835
Represents a call to a member function that may be written either with member call syntax (e....
Definition ExprCXX.h:183
Represents a new-expression for memory allocation and constructor calls, e.g: "new CXXNewExpr(foo)".
Definition ExprCXX.h:2359
The null pointer literal (C++11 [lex.nullptr])
Definition ExprCXX.h:772
A call to an overloaded operator written using operator syntax.
Definition ExprCXX.h:85
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition Expr.h:2949
CastExpr - Base class for type casts, including both implicit casts (ImplicitCastExpr) and explicit c...
Definition Expr.h:3682
ConstStmtVisitor - This class implements a simple visitor for Stmt subclasses.
A reference to a declared variable, function, enum, etc.
Definition Expr.h:1276
DeclStmt - Adaptor class for mixing declarations with statements and expressions.
Definition Stmt.h:1641
This represents one expression.
Definition Expr.h:112
Represents a function declaration or definition.
Definition Decl.h:2027
Describes an C or C++ initializer list.
Definition Expr.h:5305
A C++ lambda expression, which produces a function object (of unspecified type) that can be invoked l...
Definition ExprCXX.h:1972
Represents a prvalue temporary that is written into memory so that a reference can bind to it.
Definition ExprCXX.h:4920
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition Expr.h:3370
A (possibly-)qualified type.
Definition TypeBase.h:937
ReturnStmt - This represents a return, optionally of an expression: return; return 4;.
Definition Stmt.h:3170
StmtExpr - This is the GNU Statement Expression extension: ({int X=4; X;}).
Definition Expr.h:4601
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition Expr.h:2250
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition Decl.h:712
void VisitDeclRefExpr(const DeclRefExpr *DRE)
void VisitBinaryOperator(const BinaryOperator *BO)
void VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *MTE)
FactsGenerator(FactManager &FactMgr, AnalysisDeclContext &AC)
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)
A list of origins representing levels of indirection for pointer-like types.
Definition Origins.h:95
utils::ID< struct OriginTag > OriginID
Definition Origins.h:28
@ CPlusPlus