clang 23.0.0git
LoanPropagation.cpp
Go to the documentation of this file.
1//===- LoanPropagation.cpp - Loan Propagation Analysis ---------*- 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#include <cassert>
9#include <memory>
10
11#include "Dataflow.h"
18#include "clang/Analysis/CFG.h"
19#include "clang/Basic/LLVM.h"
20#include "llvm/ADT/BitVector.h"
21#include "llvm/ADT/SmallVector.h"
22#include "llvm/Support/TimeProfiler.h"
23#include "llvm/Support/raw_ostream.h"
24
26
27// Prepass to find persistent origins. An origin is persistent if it is
28// referenced in more than one basic block.
29static llvm::BitVector computePersistentOrigins(const FactManager &FactMgr,
30 const CFG &C) {
31 llvm::TimeTraceScope("ComputePersistentOrigins");
32 unsigned NumOrigins = FactMgr.getOriginMgr().getNumOrigins();
33 llvm::BitVector PersistentOrigins(NumOrigins);
34
35 llvm::SmallVector<const CFGBlock *> OriginToFirstSeenBlock(NumOrigins,
36 nullptr);
37 for (const CFGBlock *B : C) {
38 for (const Fact *F : FactMgr.getFacts(B)) {
39 auto CheckOrigin = [&](OriginID OID) {
40 if (PersistentOrigins.test(OID.Value))
41 return;
42 auto &FirstSeenBlock = OriginToFirstSeenBlock[OID.Value];
43 if (FirstSeenBlock == nullptr)
44 FirstSeenBlock = B;
45 if (FirstSeenBlock != B) {
46 // We saw this origin in more than one block.
47 PersistentOrigins.set(OID.Value);
48 }
49 };
50
51 switch (F->getKind()) {
53 CheckOrigin(F->getAs<IssueFact>()->getOriginID());
54 break;
56 const auto *OF = F->getAs<OriginFlowFact>();
57 CheckOrigin(OF->getDestOriginID());
58 CheckOrigin(OF->getSrcOriginID());
59 break;
60 }
61 case Fact::Kind::Use:
62 for (const OriginList *Cur = F->getAs<UseFact>()->getUsedOrigins(); Cur;
63 Cur = Cur->peelOuterOrigin())
64 CheckOrigin(Cur->getOuterOriginID());
65 break;
67 CheckOrigin(F->getAs<KillOriginFact>()->getKilledOrigin());
68 break;
70 // An escaping origin is read at the exit block but defined earlier, so
71 // it spans blocks and must participate in joins.
72 CheckOrigin(F->getAs<OriginEscapesFact>()->getEscapedOriginID());
73 break;
78 break;
79 }
80 }
81 }
82 return PersistentOrigins;
83}
84
85namespace {
86
87/// Represents the dataflow lattice for loan propagation.
88///
89/// This lattice tracks which loans each origin may hold at a given program
90/// point.The lattice has a finite height: An origin's loan set is bounded by
91/// the total number of loans in the function.
92struct Lattice {
93 /// The map from an origin to the set of loans it contains.
94 /// Origins that appear in multiple blocks. Participates in join operations.
95 OriginLoanMap PersistentOrigins = OriginLoanMap(nullptr);
96 /// Origins confined to a single block. Discarded at block boundaries.
97 OriginLoanMap BlockLocalOrigins = OriginLoanMap(nullptr);
98
99 explicit Lattice(const OriginLoanMap &Persistent,
100 const OriginLoanMap &BlockLocal)
101 : PersistentOrigins(Persistent), BlockLocalOrigins(BlockLocal) {}
102 Lattice() = default;
103
104 bool operator==(const Lattice &Other) const {
105 return PersistentOrigins == Other.PersistentOrigins &&
106 BlockLocalOrigins == Other.BlockLocalOrigins;
107 }
108 bool operator!=(const Lattice &Other) const { return !(*this == Other); }
109
110 void dump(llvm::raw_ostream &OS) const {
111 OS << "LoanPropagationLattice State:\n";
112 OS << " Persistent Origins:\n";
113 if (PersistentOrigins.isEmpty())
114 OS << " <empty>\n";
115 for (const auto &Entry : PersistentOrigins) {
116 if (Entry.second.isEmpty())
117 OS << " Origin " << Entry.first << " contains no loans\n";
118 for (const LoanID &LID : Entry.second)
119 OS << " Origin " << Entry.first << " contains Loan " << LID << "\n";
120 }
121 OS << " Block-Local Origins:\n";
122 if (BlockLocalOrigins.isEmpty())
123 OS << " <empty>\n";
124 for (const auto &Entry : BlockLocalOrigins) {
125 if (Entry.second.isEmpty())
126 OS << " Origin " << Entry.first << " contains no loans\n";
127 for (const LoanID &LID : Entry.second)
128 OS << " Origin " << Entry.first << " contains Loan " << LID << "\n";
129 }
130 }
131};
132
133class AnalysisImpl
134 : public DataflowAnalysis<AnalysisImpl, Lattice, Direction::Forward> {
135public:
136 AnalysisImpl(const CFG &C, AnalysisDeclContext &AC, FactManager &F,
137 OriginLoanMap::Factory &OriginLoanMapFactory,
138 LoanSet::Factory &LoanSetFactory)
139 : DataflowAnalysis(C, AC, F), OriginLoanMapFactory(OriginLoanMapFactory),
140 LoanSetFactory(LoanSetFactory),
141 PersistentOrigins(computePersistentOrigins(F, C)) {}
142
143 using Base::transfer;
144
145 StringRef getAnalysisName() const { return "LoanPropagation"; }
146
147 Lattice getInitialState() { return Lattice{}; }
148
149 /// Merges two lattices by taking the union of loans for each origin.
150 /// Only persistent origins are joined; block-local origins are discarded.
151 Lattice join(Lattice A, Lattice B) {
152 OriginLoanMap JoinedOrigins = utils::join(
153 A.PersistentOrigins, B.PersistentOrigins, OriginLoanMapFactory,
154 [&](const LoanSet *S1, const LoanSet *S2) {
155 assert((S1 || S2) && "unexpectedly merging 2 empty sets");
156 if (!S1)
157 return *S2;
158 if (!S2)
159 return *S1;
160 return utils::join(*S1, *S2, LoanSetFactory);
161 },
162 // Asymmetric join is a performance win. For origins present only on one
163 // branch, the loan set can be carried over as-is.
165 return Lattice(JoinedOrigins, OriginLoanMapFactory.getEmptyMap());
166 }
167
168 /// A new loan is issued to the origin. Old loans are erased.
169 Lattice transfer(Lattice In, const IssueFact &F) {
170 OriginID OID = F.getOriginID();
171 LoanID LID = F.getLoanID();
172 LoanSet NewLoans = LoanSetFactory.add(LoanSetFactory.getEmptySet(), LID);
173 return setLoans(In, OID, NewLoans);
174 }
175
176 /// A flow from source to destination. If `KillDest` is true, this replaces
177 /// the destination's loans with the source's. Otherwise, the source's loans
178 /// are merged into the destination's.
179 Lattice transfer(Lattice In, const OriginFlowFact &F) {
180 OriginID DestOID = F.getDestOriginID();
181 OriginID SrcOID = F.getSrcOriginID();
182
183 LoanSet DestLoans =
184 F.getKillDest() ? LoanSetFactory.getEmptySet() : getLoans(In, DestOID);
185 LoanSet SrcLoans = getLoans(In, SrcOID);
186 LoanSet MergedLoans = utils::join(DestLoans, SrcLoans, LoanSetFactory);
187
188 return setLoans(In, DestOID, MergedLoans);
189 }
190
191 Lattice transfer(Lattice In, const KillOriginFact &F) {
192 return setLoans(In, F.getKilledOrigin(), LoanSetFactory.getEmptySet());
193 }
194
195 Lattice transfer(Lattice In, const ExpireFact &F) {
196 if (auto OID = F.getOriginID())
197 return setLoans(In, *OID, LoanSetFactory.getEmptySet());
198 return In;
199 }
200
201 LoanSet getLoans(OriginID OID, ProgramPoint P) const {
202 return getLoans(getState(P), OID);
203 }
204
205 llvm::SmallVector<OriginID>
206 buildOriginFlowChain(ProgramPoint StartPoint, const OriginID StartOID,
207 const LoanID TargetLoan) const {
208 assert(getLoans(StartOID, StartPoint).contains(TargetLoan) &&
209 "TargetLoan must be present in the StartOID at the StartPoint");
210
211 OriginID CurrOID = StartOID;
212 llvm::SmallVector<OriginID> OriginFlowChain;
213 llvm::ArrayRef<const Fact *> Facts = FactMgr.getBlockContaining(StartPoint);
214 const auto *StartIt = llvm::find(Facts, StartPoint);
215 assert(StartIt != Facts.end());
216
217 for (const Fact *F :
218 llvm::reverse(llvm::make_range(Facts.begin(), StartIt))) {
219 if (const auto *IF = F->getAs<IssueFact>())
220 if (IF->getLoanID() == TargetLoan) {
221 assert(IF->getOriginID() == CurrOID);
222 return OriginFlowChain;
223 }
224
225 const auto *OFF = F->getAs<OriginFlowFact>();
226 if (!OFF)
227 continue;
228 if (OFF->getDestOriginID() != CurrOID)
229 continue;
230
231 const OriginID SrcOriginID = OFF->getSrcOriginID();
232 if (!getLoans(SrcOriginID, OFF).contains(TargetLoan))
233 continue;
234 OriginFlowChain.push_back(SrcOriginID);
235 CurrOID = SrcOriginID;
236 }
237
238 // FIXME: Ideally, this return is unreachable and should be an assert
239 // because we expect to always finish at an IssueFact. But since current
240 // traversal is limited to a single CFG block, multi-block OriginFlowChain
241 // construction might miss the IssueFact. We should add llvm_unreachable
242 // here once multi-block support is implemented.
243 return {};
244 }
245
246 llvm::SmallVector<OriginID>
247 buildOriginFlowChain(const UseFact *UF, const LoanID TargetLoan) const {
248 for (const OriginList *Cur = UF->getUsedOrigins(); Cur;
249 Cur = Cur->peelOuterOrigin())
250 if (getLoans(Cur->getOuterOriginID(), UF).contains(TargetLoan))
251 return buildOriginFlowChain(UF, Cur->getOuterOriginID(), TargetLoan);
252
253 return {};
254 }
255
256private:
257 /// Returns true if the origin is persistent (referenced in multiple blocks).
258 bool isPersistent(OriginID OID) const {
259 return PersistentOrigins.test(OID.Value);
260 }
261
262 Lattice setLoans(Lattice L, OriginID OID, LoanSet Loans) {
263 if (isPersistent(OID))
264 return Lattice(OriginLoanMapFactory.add(L.PersistentOrigins, OID, Loans),
265 L.BlockLocalOrigins);
266 return Lattice(L.PersistentOrigins,
267 OriginLoanMapFactory.add(L.BlockLocalOrigins, OID, Loans));
268 }
269
270 LoanSet getLoans(Lattice L, OriginID OID) const {
271 const OriginLoanMap *Map =
272 isPersistent(OID) ? &L.PersistentOrigins : &L.BlockLocalOrigins;
273 if (auto *Loans = Map->lookup(OID))
274 return *Loans;
275 return LoanSetFactory.getEmptySet();
276 }
277
278 OriginLoanMap::Factory &OriginLoanMapFactory;
279 LoanSet::Factory &LoanSetFactory;
280 /// Boolean vector indexed by origin ID. If true, the origin appears in
281 /// multiple basic blocks and must participate in join operations. If false,
282 /// the origin is block-local and can be discarded at block boundaries.
283 llvm::BitVector PersistentOrigins;
284};
285} // namespace
286
287class LoanPropagationAnalysis::Impl final : public AnalysisImpl {
288 using AnalysisImpl::AnalysisImpl;
289};
290
292 const CFG &C, AnalysisDeclContext &AC, FactManager &F,
293 OriginLoanMap::Factory &OriginLoanMapFactory,
294 LoanSet::Factory &LoanSetFactory)
295 : PImpl(std::make_unique<Impl>(C, AC, F, OriginLoanMapFactory,
296 LoanSetFactory)) {
297 PImpl->run();
298}
299
301
303 return PImpl->getLoans(OID, P);
304}
305
308 const OriginID StartOID,
309 const LoanID TargetLoan) const {
310 return PImpl->buildOriginFlowChain(StartPoint, StartOID, TargetLoan);
311}
312
315 const LoanID TargetLoan) const {
316 return PImpl->buildOriginFlowChain(UF, TargetLoan);
317}
318} // namespace clang::lifetimes::internal
This file defines AnalysisDeclContext, a class that manages the analysis context data for context sen...
static void dump(llvm::raw_ostream &OS, StringRef FunctionName, ArrayRef< CounterExpression > Expressions, ArrayRef< CounterMappingRegion > Regions)
Forward-declares and imports various common LLVM datatypes that clang wants to use unqualified.
static bool contains(const std::set< tok::TokenKind > &Terminators, const Token &Tok)
AnalysisDeclContext contains the context data for the function, method or block under analysis.
Represents a single basic block in a source-level CFG.
Definition CFG.h:652
Represents a source-level, intra-procedural CFG that represents the control-flow of a Stmt.
Definition CFG.h:1271
A generic, policy-based driver for dataflow analyses.
Definition Dataflow.h:57
llvm::ArrayRef< const Fact * > getFacts(const CFGBlock *B) const
Definition Facts.h:345
An abstract base class for a single, atomic lifetime-relevant event.
Definition Facts.h:34
@ InvalidateOrigin
An origin is invalidated (e.g. vector resized, delete called).
Definition Facts.h:57
@ TestPoint
A marker for a specific point in the code, for testing.
Definition Facts.h:53
@ Expire
A loan expires as its underlying storage is freed (e.g., variable goes out of scope).
Definition Facts.h:42
@ Issue
A new loan is issued from a borrow expression (e.g., &x).
Definition Facts.h:39
@ OriginFlow
An origin is propagated from a source to a destination (e.g., p = q).
Definition Facts.h:47
@ MovedOrigin
An origin that is moved (e.g., passed to an rvalue reference parameter).
Definition Facts.h:51
@ Use
An origin is used (eg. appears as l-value expression like DeclRefExpr).
Definition Facts.h:49
@ OriginEscapes
An origin that escapes the function scope (e.g., via return).
Definition Facts.h:55
@ KillOrigin
All loans of an origin are cleared.
Definition Facts.h:59
All loans are cleared from an origin (e.g., assigning a callable without tracked origins to std::func...
Definition Facts.h:323
LoanSet getLoans(OriginID OID, ProgramPoint P) const
llvm::SmallVector< OriginID > buildOriginFlowChain(ProgramPoint StartPoint, const OriginID StartOID, const LoanID TargetLoan) const
Builds the chain of origins through which a loan has propagated.
LoanPropagationAnalysis(const CFG &C, AnalysisDeclContext &AC, FactManager &F, OriginLoanMap::Factory &OriginLoanMapFactory, LoanSet::Factory &LoanSetFactory)
Represents that an origin escapes the current scope through various means.
Definition Facts.h:159
A list of origins representing levels of indirection for pointer-like types.
Definition Origins.h:95
OriginList * peelOuterOrigin() const
Definition Origins.h:99
const OriginList * getUsedOrigins() const
Definition Facts.h:250
void transfer(const StmtToEnvMap &StmtToEnv, const Stmt &S, Environment &Env, Environment::ValueModel &Model)
Evaluates S and updates Env accordingly.
Definition Transfer.cpp:986
@ OS
Indicates that the tracking object is a descendant of a referenced-counted OSObject,...
@ Asymmetric
An asymmetric join preserves keys unique to the first map as-is, while applying the JoinValues operat...
Definition Utils.h:61
llvm::ImmutableSet< T > join(llvm::ImmutableSet< T > A, llvm::ImmutableSet< T > B, typename llvm::ImmutableSet< T >::Factory &F)
Computes the union of two ImmutableSets.
Definition Utils.h:39
const Fact * ProgramPoint
A ProgramPoint identifies a location in the CFG by pointing to a specific Fact.
Definition Facts.h:91
llvm::ImmutableSet< LoanID > LoanSet
utils::ID< struct LoanTag > LoanID
Definition Loans.h:25
utils::ID< struct OriginTag > OriginID
Definition Origins.h:28
llvm::ImmutableMap< OriginID, LoanSet > OriginLoanMap
static llvm::BitVector computePersistentOrigins(const FactManager &FactMgr, const CFG &C)
bool operator==(const CallGraphNode::CallRecord &LHS, const CallGraphNode::CallRecord &RHS)
Definition CallGraph.h:207
bool operator!=(CanQual< T > x, CanQual< U > y)
@ Other
Other implicit parameter.
Definition Decl.h:1763