clang 24.0.0git
Origins.cpp
Go to the documentation of this file.
1//===- Origins.cpp - Origin Implementation -----------------------*- 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
11#include "clang/AST/Attr.h"
12#include "clang/AST/Decl.h"
13#include "clang/AST/DeclCXX.h"
15#include "clang/AST/Expr.h"
16#include "clang/AST/ExprCXX.h"
18#include "clang/AST/TypeBase.h"
22#include "llvm/ADT/StringMap.h"
23
25namespace {
26/// A utility class to traverse the function body in the analysis
27/// context and collect the count of expressions with missing origins.
28class MissingOriginCollector
29 : public RecursiveASTVisitor<MissingOriginCollector> {
30public:
31 MissingOriginCollector(
32 const llvm::DenseMap<const clang::Expr *, OriginList *> &ExprToOriginList,
33 const OriginManager &OM, LifetimeSafetyStats &LSStats)
34 : ExprToOriginList(ExprToOriginList), OM(OM), LSStats(LSStats) {}
35 bool VisitExpr(Expr *E) {
36 if (!OM.hasOrigins(E))
37 return true;
38 // Check if we have an origin for this expression.
39 if (!ExprToOriginList.contains(E)) {
40 // No origin found: count this as missing origin.
41 LSStats.ExprTypeToMissingOriginCount[E->getType().getTypePtr()]++;
42 LSStats.ExprStmtClassToMissingOriginCount[std::string(
43 E->getStmtClassName())]++;
44 }
45 return true;
46 }
47
48private:
49 const llvm::DenseMap<const clang::Expr *, OriginList *> &ExprToOriginList;
50 const OriginManager &OM;
51 LifetimeSafetyStats &LSStats;
52};
53
54class LifetimeAnnotatedOriginTypeCollector
55 : public RecursiveASTVisitor<LifetimeAnnotatedOriginTypeCollector> {
56public:
57 bool VisitCallExpr(const CallExpr *CE) {
58 // Indirect calls (e.g., function pointers) are skipped because lifetime
59 // annotations currently apply to declarations, not types.
60 if (const auto *FD = CE->getDirectCallee()) {
61 collect(FD, FD->getReturnType());
62 collectCaptureBy(FD);
63 }
64 return true;
65 }
66
67 bool VisitCXXConstructExpr(const CXXConstructExpr *CCE) {
68 collect(CCE->getConstructor(), CCE->getType());
69 collectCaptureBy(CCE->getConstructor());
70 return true;
71 }
72
73 bool shouldVisitLambdaBody() const { return false; }
74 bool shouldVisitTemplateInstantiations() const { return true; }
75
76 const llvm::SmallVector<QualType> &getCollectedTypes() const {
77 return CollectedTypes;
78 }
79
80private:
81 llvm::SmallVector<QualType> CollectedTypes;
82
83 void collect(const FunctionDecl *FD, QualType RetType) {
84 if (!FD)
85 return;
87
88 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD);
89 MD && MD->isInstance() && !isa<CXXConstructorDecl>(MD) &&
91 CollectedTypes.push_back(RetType);
92 return;
93 }
94
95 for (const auto *Param : FD->parameters()) {
96 if (Param->hasAttr<LifetimeBoundAttr>()) {
97 CollectedTypes.push_back(RetType);
98 return;
99 }
100 }
101 }
102
103 void collectCaptureBy(const FunctionDecl *FD) {
104 if (!FD)
105 return;
107 const auto *MD = dyn_cast<CXXMethodDecl>(FD);
108 bool IsInstance = MD && MD->isInstance();
109 int Offset = (MD && MD->isImplicitObjectMemberFunction()) ? 1 : 0;
110 for (const auto *Param : FD->parameters()) {
111 if (auto *Attr = Param->getAttr<LifetimeCaptureByAttr>()) {
112 for (int Idx : Attr->params()) {
113 if (Idx == LifetimeCaptureByAttr::Global ||
114 Idx == LifetimeCaptureByAttr::Unknown ||
115 Idx == LifetimeCaptureByAttr::Invalid)
116 continue;
117 if (Idx == LifetimeCaptureByAttr::This) {
118 if (IsInstance)
119 CollectedTypes.push_back(MD->getFunctionObjectParameterType());
120 } else if (int LogicalIdx = Idx - Offset;
121 LogicalIdx >= 0 &&
122 (unsigned)LogicalIdx < FD->getNumParams()) {
123 CollectedTypes.push_back(
124 FD->getParamDecl(LogicalIdx)->getType().getNonReferenceType());
125 }
126 }
127 }
128 }
129 }
130};
131
132} // namespace
133
134bool OriginManager::hasOrigins(QualType QT, bool IntrinsicOnly) const {
136 return true;
137 if (!IntrinsicOnly &&
138 LifetimeAnnotatedOriginTypes.contains(QT.getCanonicalType().getTypePtr()))
139 return true;
140 // An `_Atomic(T)` wraps T transparently for lifetime purposes (the atomic
141 // holds the same value); see through it.
142 if (const auto *AT = QT->getAs<AtomicType>())
143 return hasOrigins(AT->getValueType(), IntrinsicOnly);
144 const auto *RD = QT->getAsCXXRecordDecl();
145 if (!RD)
146 return false;
147 // Standard library callable wrappers (e.g., std::function) can propagate the
148 // stored lambda's origins.
150 return true;
151 // TODO: Limit to lambdas for now. This will be extended to user-defined
152 // structs with pointer-like fields.
153 if (!RD->isLambda())
154 return false;
155 for (const auto *FD : RD->fields())
156 if (hasOrigins(FD->getType(), IntrinsicOnly))
157 return true;
158 return false;
159}
160
161/// Determines if an expression has origins that need to be tracked.
162///
163/// An expression has origins if:
164/// - It's a glvalue (has addressable storage), OR
165/// - Its type is pointer-like (pointer, reference, or gsl::Pointer), OR
166/// - Its type is registered for origin tracking (e.g., return type of a
167/// [[clang::lifetimebound]] function)
168///
169/// Examples:
170/// - `int x; x` : has origin (glvalue)
171/// - `int* p; p` : has 2 origins (1 for glvalue and 1 for pointer type)
172/// - `std::string_view{}` : has 1 origin (prvalue of pointer type)
173/// - `42` : no origin (prvalue of non-pointer type)
174/// - `x + y` : (where x, y are int) → no origin (prvalue of non-pointer type)
175bool OriginManager::hasOrigins(const Expr *E) const {
176 return E->isGLValue() || hasOrigins(E->getType());
177}
178
179/// Returns true if the declaration has its own storage that can be borrowed.
180///
181/// References generally have no storage - they are aliases to other storage.
182/// For example:
183/// int x; // has storage (can issue loans to x's storage)
184/// int& r = x; // no storage (r is an alias to x's storage)
185/// int* p; // has storage (the pointer variable p itself has storage)
186///
187/// TODO: Handle lifetime extension. References initialized by temporaries
188/// can have storage when the temporary's lifetime is extended:
189/// const int& r = 42; // temporary has storage, lifetime extended
190/// Foo&& f = Foo{}; // temporary has storage, lifetime extended
191/// Currently, this function returns false for all reference types.
193 return !D->getType()->isReferenceType();
194}
195
197 : AST(AC.getASTContext()) {
198 collectLifetimeAnnotatedOriginTypes(AC);
199 initializeThisOrigins(AC.getDecl());
200}
201
202void OriginManager::initializeThisOrigins(const Decl *D) {
203 const auto *MD = llvm::dyn_cast_or_null<CXXMethodDecl>(D);
204 if (!MD || !MD->isInstance())
205 return;
206 // Lambdas can capture 'this' from the surrounding context, but in that case
207 // 'this' does not refer to the lambda object itself.
208 if (const CXXRecordDecl *P = MD->getParent(); P && P->isLambda())
209 return;
210 ThisOrigins = buildListForType(MD->getThisType(), MD);
211}
212
213OriginList *OriginManager::createNode(const ValueDecl *D, QualType QT,
214 bool NamesDeclStorage) {
215 OriginID NewID = getNextOriginID();
216 AllOrigins.emplace_back(NewID, D, QT.getTypePtrOrNull(), NamesDeclStorage);
217 return new (ListAllocator.Allocate<OriginList>()) OriginList(NewID);
218}
219
220OriginList *OriginManager::createNode(const Expr *E, QualType QT,
221 bool NamesDeclStorage) {
222 OriginID NewID = getNextOriginID();
223 AllOrigins.emplace_back(NewID, E, QT.getTypePtrOrNull(), NamesDeclStorage);
224 return new (ListAllocator.Allocate<OriginList>()) OriginList(NewID);
225}
226
228 return new (ListAllocator.Allocate<OriginList>()) OriginList(OID);
229}
230
231template <typename T>
232OriginList *OriginManager::buildListForType(QualType QT, const T *Node,
233 bool NamesDeclStorage) {
234 assert(hasOrigins(QT) && "buildListForType called for non-pointer type");
235 // `_Atomic(T)` is transparent for lifetime purposes: build the node for T.
236 if (const auto *AT = QT->getAs<AtomicType>())
237 return buildListForType(AT->getValueType(), Node, NamesDeclStorage);
238 OriginList *Head = createNode(Node, QT, NamesDeclStorage);
239
240 if (QT->isPointerOrReferenceType()) {
241 QualType PointeeTy = QT->getPointeeType();
242 // We recurse if the pointee type is pointer-like, to build the next
243 // level in the origin tree. E.g., for T*& / View&.
244 if (hasOrigins(PointeeTy))
245 Head->setInnerOriginList(buildListForType(PointeeTy, Node));
246 }
247 return Head;
248}
249
251 if (!hasOrigins(D->getType()))
252 return nullptr;
253 auto It = DeclToList.find(D);
254 if (It != DeclToList.end())
255 return It->second;
256 return DeclToList[D] = buildListForType(D->getType(), D);
257}
258
260 if (auto *ParenIgnored = E->IgnoreParens(); ParenIgnored != E)
261 return getOrCreateList(ParenIgnored);
262 // We do not see CFG stmts for ExprWithCleanups. Simply peel them.
263 if (const ExprWithCleanups *EWC = dyn_cast<ExprWithCleanups>(E))
264 return getOrCreateList(EWC->getSubExpr());
265
266 // An OpaqueValueExpr is a placeholder for an already-evaluated subexpression
267 // (e.g. the common operand of `a ?: b`) and is not itself a CFG statement, so
268 // reuse its source's origins rather than flowing into a fresh node.
269 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
270 if (const Expr *Src = OVE->getSourceExpr())
271 return getOrCreateList(Src);
272
273 if (!hasOrigins(E))
274 return nullptr;
275
276 auto It = ExprToList.find(E);
277 if (It != ExprToList.end())
278 return It->second;
279
280 QualType Type = E->getType();
281 // Special handling for 'this' expressions to share origins with the method's
282 // implicit object parameter.
283 if (isa<CXXThisExpr>(E) && ThisOrigins)
284 return *ThisOrigins;
285
286 // Special handling for expressions referring to a decl to share origins with
287 // the underlying decl.
288 const ValueDecl *ReferencedDecl = nullptr;
289 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
290 ReferencedDecl = DRE->getDecl();
291 else if (auto *ME = dyn_cast<MemberExpr>(E))
292 if (auto *Field = dyn_cast<FieldDecl>(ME->getMemberDecl());
293 Field && isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
294 ReferencedDecl = Field;
295 if (ReferencedDecl) {
296 OriginList *Head = nullptr;
297 // For non-reference declarations (e.g., `int* p`), the expression is an
298 // lvalue (addressable) that can be borrowed, so we create an outer origin
299 // for the lvalue itself, with the pointee being the declaration's list.
300 // This models taking the address: `&p` borrows the storage of `p`, not what
301 // `p` points to.
302 if (doesDeclHaveStorage(ReferencedDecl)) {
303 // `this->f` reaches its field through `this` instead of naming it.
304 Head = createNode(E, QualType{},
305 /*NamesDeclStorage=*/isa<DeclRefExpr>(E));
306 // This ensures origin sharing: multiple expressions to the same
307 // declaration share the same underlying origins.
308 Head->setInnerOriginList(getOrCreateList(ReferencedDecl));
309 } else {
310 // For reference-typed declarations (e.g., `int& r = p`) which have no
311 // storage, the DeclRefExpr directly reuses the declaration's list since
312 // references don't add an extra level of indirection at the expression
313 // level.
314 Head = getOrCreateList(ReferencedDecl);
315 }
316 return ExprToList[E] = Head;
317 }
318
319 // If E is an lvalue , it refers to storage. We model this storage as the
320 // first level of origin list, as if it were a reference, because l-values are
321 // addressable.
322 if (E->isGLValue() && !Type->isReferenceType())
323 Type = AST.getLValueReferenceType(Type);
324 // A qualification conversion of a glvalue names what its operand names. It is
325 // not transparent: for class types it is the node alias notes report.
326 bool NamesDeclStorage = false;
327 if (const auto *CE = dyn_cast<CastExpr>(E);
328 CE && CE->getCastKind() == CK_NoOp && E->isGLValue())
329 if (const OriginList *Sub = getOrCreateList(CE->getSubExpr()))
330 NamesDeclStorage = getOrigin(Sub->getOuterOriginID()).NamesDeclStorage;
331 return ExprToList[E] = buildListForType(Type, E, NamesDeclStorage);
332}
333
334void OriginManager::dump(OriginID OID, llvm::raw_ostream &OS) const {
335 OS << OID << " (";
336 Origin O = getOrigin(OID);
337 if (const ValueDecl *VD = O.getDecl()) {
338 OS << "Decl: " << VD->getNameAsString();
339 } else if (const Expr *E = O.getExpr()) {
340 OS << "Expr: " << E->getStmtClassName();
341 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) {
342 if (const ValueDecl *VD = DRE->getDecl())
343 OS << ", Decl: " << VD->getNameAsString();
344 }
345 } else {
346 OS << "Unknown";
347 }
348 if (O.Ty)
349 OS << ", Type : " << QualType(O.Ty, 0).getAsString();
350 OS << ")";
351}
352
354 assert(ID.Value < AllOrigins.size());
355 return AllOrigins[ID.Value];
356}
357
359 LifetimeSafetyStats &LSStats) {
360 MissingOriginCollector Collector(this->ExprToList, *this, LSStats);
361 Collector.TraverseStmt(const_cast<Stmt *>(&FunctionBody));
362}
363
364void OriginManager::collectLifetimeAnnotatedOriginTypes(
365 const AnalysisDeclContext &AC) {
366 LifetimeAnnotatedOriginTypeCollector Collector;
367 if (Stmt *Body = AC.getBody())
368 Collector.TraverseStmt(Body);
369 if (const auto *CD = dyn_cast<CXXConstructorDecl>(AC.getDecl()))
370 for (const auto *Init : CD->inits())
371 Collector.TraverseStmt(Init->getInit());
372 for (QualType QT : Collector.getCollectedTypes())
373 registerLifetimeAnnotatedOriginType(QT);
374}
375
376void OriginManager::registerLifetimeAnnotatedOriginType(QualType QT) {
377 if (!QT->getAsCXXRecordDecl() || hasOrigins(QT))
378 return;
379
380 LifetimeAnnotatedOriginTypes.insert(QT.getCanonicalType().getTypePtr());
381}
382
383} // namespace clang::lifetimes::internal
Defines the clang::ASTContext interface.
This file defines AnalysisDeclContext, a class that manages the analysis context data for context sen...
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
Defines the C++ template declaration subclasses.
Defines the clang::Expr interface and subclasses for C++ expressions.
C Language Family Type Representation.
AnalysisDeclContext contains the context data for the function, method or block under analysis.
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition DeclBase.h:2126
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
Represents an expression – generally a full-expression – that introduces cleanups to be run at the en...
Definition ExprCXX.h:3714
This represents one expression.
Definition Expr.h:113
bool isGLValue() const
Definition Expr.h:288
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3119
QualType getType() const
Definition Expr.h:145
A (possibly-)qualified type.
Definition TypeBase.h:938
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition TypeBase.h:8428
QualType getCanonicalType() const
Definition TypeBase.h:8480
const Type * getTypePtrOrNull() const
Definition TypeBase.h:8432
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Definition TypeBase.h:1348
Stmt - This represents one statement.
Definition Stmt.h:85
const char * getStmtClassName() const
Definition Stmt.cpp:86
The base class of the type hierarchy.
Definition TypeBase.h:1879
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 isReferenceType() const
Definition TypeBase.h:8689
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:881
bool isPointerOrReferenceType() const
Definition TypeBase.h:8669
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9264
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition Decl.h:713
QualType getType() const
Definition Decl.h:724
A list of origins representing levels of indirection for pointer-like types.
Definition Origins.h:105
void setInnerOriginList(OriginList *Inner)
Definition Origins.h:112
OriginList * getOrCreateList(const ValueDecl *D)
Gets or creates the OriginList for a given ValueDecl.
Definition Origins.cpp:250
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:227
const Origin & getOrigin(OriginID ID) const
Definition Origins.cpp:353
void collectMissingOrigins(Stmt &FunctionBody, LifetimeSafetyStats &LSStats)
Collects statistics about expressions that lack associated origins.
Definition Origins.cpp:358
OriginManager(const AnalysisDeclContext &AC)
Definition Origins.cpp:196
void dump(OriginID OID, llvm::raw_ostream &OS) const
Definition Origins.cpp:334
bool hasOrigins(QualType QT, bool IntrinsicOnly=false) const
Determines whether a type can carry lifetime origins.
Definition Origins.cpp:134
utils::ID< struct OriginTag > OriginID
Definition Origins.h:28
bool doesDeclHaveStorage(const ValueDecl *D)
Returns true if the declaration has its own storage that can be borrowed.
Definition Origins.cpp:192
bool isGslPointerType(QualType QT)
bool isStdCallableWrapperType(const CXXRecordDecl *RD)
bool implicitObjectParamIsLifetimeBound(const FunctionDecl *FD)
const FunctionDecl * getDeclWithMergedLifetimeBoundAttrs(const FunctionDecl *FD)
bool isa(CodeGen::Address addr)
Definition Address.h:330
const FunctionProtoType * T
A structure to hold the statistics related to LifetimeAnalysis.
An Origin is a symbolic identifier that represents the set of possible loans a pointer-like object co...
Definition Origins.h:40
bool NamesDeclStorage
True if this origin only holds a loan to a declaration named in scope, so it can never hold an expire...
Definition Origins.h:62
const clang::Expr * getExpr() const
Definition Origins.h:74
const clang::ValueDecl * getDecl() const
Definition Origins.h:71
const Type * Ty
The type at this indirection level.
Definition Origins.h:54