clang 24.0.0git
Origins.h
Go to the documentation of this file.
1//===- Origins.h - Origin and Origin Management ----------------*- 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 Origins, which represent the set of possible loans a
10// pointer-like object could hold, and the OriginManager, which manages the
11// creation, storage, and retrieval of origins for variables and expressions.
12//
13//===----------------------------------------------------------------------===//
14#ifndef LLVM_CLANG_ANALYSIS_ANALYSES_LIFETIMESAFETY_ORIGINS_H
15#define LLVM_CLANG_ANALYSIS_ANALYSES_LIFETIMESAFETY_ORIGINS_H
16
17#include "clang/AST/Decl.h"
18#include "clang/AST/DeclCXX.h"
19#include "clang/AST/Expr.h"
20#include "clang/AST/TypeBase.h"
24#include "llvm/Support/Allocator.h"
25#include "llvm/Support/raw_ostream.h"
26
28
30
31inline llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, OriginID ID) {
32 return OS << ID.Value;
33}
34
35/// An Origin is a symbolic identifier that represents the set of possible
36/// loans a pointer-like object could hold at any given time.
37///
38/// Each Origin corresponds to a single level of indirection. For complex types
39/// with multiple levels of indirection (e.g., `int**`), multiple Origins are
40/// organized into an OriginList structure (see below).
41struct Origin {
43 /// A pointer to the AST node that this origin represents. This union
44 /// distinguishes between origins from declarations (variables or parameters)
45 /// and origins from expressions.
46 llvm::PointerUnion<const clang::ValueDecl *, const clang::Expr *> Ptr;
47
48 /// The type at this indirection level.
49 ///
50 /// For `int** pp`:
51 /// Root origin: QT = `int**` (what pp points to)
52 /// Pointee origin: QT = `int*` (what *pp points to)
53 ///
54 /// Null for synthetic lvalue origins (e.g., outer origin of DeclRefExpr).
55 const Type *Ty;
56
57 /// True if this origin only holds a loan to a declaration named in scope, so
58 /// it can never hold an expired loan. For example, in
59 /// int s = 42;
60 /// int t = s;
61 /// the outer origin of the expression `s` holds a loan to `s`, which is alive
62 /// wherever `s` can be named.
64
65 Origin(OriginID ID, const clang::ValueDecl *D, const Type *QT,
68 Origin(OriginID ID, const clang::Expr *E, const Type *QT,
71
72 const clang::ValueDecl *getDecl() const {
73 return dyn_cast<const clang::ValueDecl *>(Ptr);
74 }
75 const clang::Expr *getExpr() const {
76 return dyn_cast<const clang::Expr *>(Ptr);
77 }
78};
79
80/// A list of origins representing levels of indirection for pointer-like types.
81///
82/// Each node in the list contains an OriginID representing a level of
83/// indirection. The list structure captures the multi-level nature of
84/// pointer and reference types in the lifetime analysis.
85///
86/// Examples:
87/// - For `int& x`, the list has size 2:
88/// * Outer: origin for the reference storage itself (the lvalue `x`)
89/// * Inner: origin for what `x` refers to
90///
91/// - For `int* p`, the list has size 2:
92/// * Outer: origin for the pointer variable `p`
93/// * Inner: origin for what `p` points to
94///
95/// - For `View v` (where View is gsl::Pointer), the list has size 2:
96/// * Outer: origin for the view object itself
97/// * Inner: origin for what the view refers to
98///
99/// - For `int** pp`, the list has size 3:
100/// * Outer: origin for `pp` itself
101/// * Inner: origin for `*pp` (what `pp` points to)
102/// * Inner->Inner: origin for `**pp` (what `*pp` points to)
103///
104/// The list structure enables the analysis to track how loans flow through
105/// different levels of indirection when assignments and dereferences occur.
107public:
108 OriginList(OriginID OID) : OuterOID(OID) {}
109
110 OriginList *peelOuterOrigin() const { return InnerList; }
111 OriginID getOuterOriginID() const { return OuterOID; }
112
113 void setInnerOriginList(OriginList *Inner) { InnerList = Inner; }
114
115 // Used for assertion checks only (to ensure origin lists have matching
116 // lengths).
117 size_t getLength() const {
118 size_t Length = 1;
119 const OriginList *T = this;
120 while (T->InnerList) {
121 T = T->InnerList;
122 Length++;
123 }
124 return Length;
125 }
126
127private:
128 OriginID OuterOID;
129 OriginList *InnerList = nullptr;
130};
131
132bool doesDeclHaveStorage(const ValueDecl *D);
133
134/// Manages the creation, storage, and retrieval of origins for pointer-like
135/// variables and expressions.
137public:
138 OriginManager(const AnalysisDeclContext &AC, llvm::BumpPtrAllocator &Alloc);
139
140 /// Gets or creates the OriginList for a given ValueDecl.
141 ///
142 /// Creates a list structure mirroring the levels of indirection in the
143 /// declaration's type (e.g., `int** p` creates list of size 2).
144 ///
145 /// \returns The OriginList, or nullptr if the type is not pointer-like.
147
148 /// Gets or creates the OriginList for a given Expr.
149 ///
150 /// Creates a list based on the expression's type and value category:
151 /// - Lvalues get an implicit reference level (modeling addressability)
152 /// - Rvalues of non-pointer type return nullptr (no trackable origin)
153 /// - DeclRefExpr may reuse the underlying declaration's list
154 ///
155 /// \returns The OriginList, or nullptr for non-pointer rvalues.
157
158 /// Wraps an existing OriginID in a new single-element OriginList, so a fact
159 /// can refer to a single level of an existing OriginList.
161
162 /// Returns the OriginList for the implicit 'this' parameter if the current
163 /// declaration is an instance method.
164 std::optional<OriginList *> getThisOrigins() const { return ThisOrigins; }
165
166 const Origin &getOrigin(OriginID ID) const;
167
168 llvm::ArrayRef<Origin> getOrigins() const { return AllOrigins; }
169
170 unsigned getNumOrigins() const { return NextOriginID.Value; }
171
172 /// Determines whether a type can carry lifetime origins.
173 ///
174 /// \param QT The type to check.
175 /// \param IntrinsicOnly If true, only consider types that can intrinsically
176 /// carry origins. If false, also include types that are tracked due to
177 /// context-sensitive annotations (e.g., return types of
178 /// [[clang::lifetimebound]] functions).
179 ///
180 /// Intrinsic origin types:
181 /// - Pointer types (int*, void*)
182 /// - Reference types (int&, const T&)
183 /// - gsl::Pointer annotated types (std::string_view)
184 /// - Lambdas capturing pointer-like objects
185 /// - Standard callable wrappers (std::function)
186 ///
187 /// TODO: Expand this list with other origin types such as: user-defined
188 /// structs with pointer-like fields.
189 ///
190 /// Contextual origin types (excluded when IntrinsicOnly=true):
191 /// - Types appearing as return values of functions with
192 /// [[clang::lifetimebound]] parameters, stored in
193 /// LifetimeAnnotatedOriginTypes during function body analysis.
194 bool hasOrigins(QualType QT, bool IntrinsicOnly = false) const;
195 bool hasOrigins(const Expr *E) const;
196
197 void dump(OriginID OID, llvm::raw_ostream &OS) const;
198
199 /// Collects statistics about expressions that lack associated origins.
200 void collectMissingOrigins(Stmt &FunctionBody, LifetimeSafetyStats &LSStats);
201
202private:
203 OriginID getNextOriginID() { return NextOriginID++; }
204
205 OriginList *createNode(const ValueDecl *D, QualType QT,
206 bool NamesDeclStorage = false);
207 OriginList *createNode(const Expr *E, QualType QT,
208 bool NamesDeclStorage = false);
209
210 template <typename T>
211 OriginList *buildListForType(QualType QT, const T *Node,
212 bool NamesDeclStorage = false);
213
214 void initializeThisOrigins(const Decl *D);
215
216 /// Pre-scans the function body (and constructor init lists) to discover
217 /// return types of lifetime-annotated calls (currently
218 /// [[clang::lifetimebound]]), registering them for origin tracking.
219 void collectLifetimeAnnotatedOriginTypes(const AnalysisDeclContext &AC);
220 void registerLifetimeAnnotatedOriginType(QualType QT);
221
222 ASTContext &AST;
223 OriginID NextOriginID{0};
224 /// TODO(opt): Profile and evaluate the usefulness of small buffer
225 /// optimisation.
226 llvm::SmallVector<Origin> AllOrigins;
227 llvm::BumpPtrAllocator &ListAllocator;
228 llvm::DenseMap<const clang::ValueDecl *, OriginList *> DeclToList;
229 llvm::DenseMap<const clang::Expr *, OriginList *> ExprToList;
230 std::optional<OriginList *> ThisOrigins;
231 /// Types that are not inherently pointer-like but require origin tracking
232 /// because of lifetime annotations (currently [[clang::lifetimebound]]) on
233 /// functions that return them.
234 llvm::DenseSet<const Type *> LifetimeAnnotatedOriginTypes;
235};
236} // namespace clang::lifetimes::internal
237
238#endif // LLVM_CLANG_ANALYSIS_ANALYSES_LIFETIMESAFETY_ORIGINS_H
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....
C Language Family Type Representation.
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:245
AnalysisDeclContext contains the context data for the function, method or block under analysis.
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
This represents one expression.
Definition Expr.h:114
A (possibly-)qualified type.
Definition TypeBase.h:938
Stmt - This represents one statement.
Definition Stmt.h:85
The base class of the type hierarchy.
Definition TypeBase.h:1879
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition Decl.h:714
A list of origins representing levels of indirection for pointer-like types.
Definition Origins.h:106
OriginList * peelOuterOrigin() const
Definition Origins.h:110
void setInnerOriginList(OriginList *Inner)
Definition Origins.h:113
std::optional< OriginList * > getThisOrigins() const
Returns the OriginList for the implicit 'this' parameter if the current declaration is an instance me...
Definition Origins.h:164
OriginList * getOrCreateList(const ValueDecl *D)
Gets or creates the OriginList for a given ValueDecl.
Definition Origins.cpp:256
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:233
const Origin & getOrigin(OriginID ID) const
Definition Origins.cpp:388
llvm::ArrayRef< Origin > getOrigins() const
Definition Origins.h:168
void collectMissingOrigins(Stmt &FunctionBody, LifetimeSafetyStats &LSStats)
Collects statistics about expressions that lack associated origins.
Definition Origins.cpp:393
void dump(OriginID OID, llvm::raw_ostream &OS) const
Definition Origins.cpp:369
bool hasOrigins(QualType QT, bool IntrinsicOnly=false) const
Determines whether a type can carry lifetime origins.
Definition Origins.cpp:139
OriginManager(const AnalysisDeclContext &AC, llvm::BumpPtrAllocator &Alloc)
Definition Origins.cpp:201
utils::ID< struct OriginTag > OriginID
Definition Origins.h:29
bool doesDeclHaveStorage(const ValueDecl *D)
Returns true if the declaration has its own storage that can be borrowed.
Definition Origins.cpp:197
llvm::raw_ostream & operator<<(llvm::raw_ostream &OS, LoanID ID)
Definition Loans.h:29
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:41
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:63
const clang::Expr * getExpr() const
Definition Origins.h:75
Origin(OriginID ID, const clang::ValueDecl *D, const Type *QT, bool NamesDeclStorage)
Definition Origins.h:65
const clang::ValueDecl * getDecl() const
Definition Origins.h:72
llvm::PointerUnion< const clang::ValueDecl *, const clang::Expr * > Ptr
A pointer to the AST node that this origin represents.
Definition Origins.h:46
const Type * Ty
The type at this indirection level.
Definition Origins.h:55
Origin(OriginID ID, const clang::Expr *E, const Type *QT, bool NamesDeclStorage)
Definition Origins.h:68
A generic, type-safe wrapper for an ID, distinguished by its Tag type.
Definition Utils.h:21