clang 24.0.0git
LiveOrigins.cpp
Go to the documentation of this file.
1//===- LiveOrigins.cpp - Live Origins 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
10#include "Dataflow.h"
12#include "llvm/Support/ErrorHandling.h"
13
15namespace {
16
17/// The dataflow lattice for origin liveness analysis.
18/// It tracks which origins are live, why they're live (which UseFact),
19/// and the confidence level of that liveness.
20struct Lattice {
21 /// Origins referenced from more than one block. Participates in joins.
22 LivenessMap Persistent;
23 /// Origins confined to a single block. Discarded at block boundaries.
24 LivenessMap BlockLocal;
25
26 Lattice() : Persistent(nullptr), BlockLocal(nullptr) {};
27
28 Lattice(LivenessMap Persistent, LivenessMap BlockLocal)
29 : Persistent(Persistent), BlockLocal(BlockLocal) {}
30
31 bool operator==(const Lattice &Other) const {
32 return Persistent == Other.Persistent && BlockLocal == Other.BlockLocal;
33 }
34
35 bool operator!=(const Lattice &Other) const { return !(*this == Other); }
36
37 void dump(llvm::raw_ostream &OS, const OriginManager &OM) const {
38 if (Persistent.isEmpty() && BlockLocal.isEmpty())
39 OS << " <empty>\n";
40 for (const LivenessMap &Live : {Persistent, BlockLocal})
41 for (const auto &Entry : Live) {
42 OriginID OID = Entry.first;
43 const LivenessInfo &Info = Entry.second;
44 OS << " ";
45 OM.dump(OID, OS);
46 OS << " is ";
47 switch (Info.Kind) {
49 OS << "definitely";
50 break;
52 OS << "maybe";
53 break;
55 llvm_unreachable("liveness kind of live origins should not be dead.");
56 }
57 OS << " live at this point\n";
58 }
59 }
60};
61
62static SourceLocation GetFactLoc(CausingFactType F) {
63 if (const auto *UF = dyn_cast<const UseFact *>(F))
64 return UF->getUseSite().getLoc();
65 if (const auto *OEF = dyn_cast<const OriginEscapesFact *>(F)) {
66 if (auto *ReturnEsc = dyn_cast<ReturnEscapeFact>(OEF))
67 return ReturnEsc->getReturnExpr()->getExprLoc();
68 if (auto *FieldEsc = dyn_cast<FieldEscapeFact>(OEF))
69 return FieldEsc->getFieldDecl()->getLocation();
70 if (auto *GlobalEsc = dyn_cast<GlobalEscapeFact>(OEF))
71 return GlobalEsc->getGlobal()->getLocation();
72 if (auto *ThisEsc = dyn_cast<ThisEscapeFact>(OEF))
73 return ThisEsc->getLoc();
74 }
75 llvm_unreachable("unhandled causing fact in PointerUnion");
76}
77
78/// The analysis that tracks which origins are live, with granular information
79/// about the causing use fact and confidence level. This is a backward
80/// analysis.
81class AnalysisImpl
82 : public DataflowAnalysis<AnalysisImpl, Lattice, Direction::Backward> {
83
84public:
85 AnalysisImpl(const CFG &C, AnalysisDeclContext &AC, FactManager &F,
86 LivenessMap::Factory &SF)
87 : DataflowAnalysis(C, AC, F), FactMgr(F), Factory(SF),
88 PersistentOrigins(F.getPersistentOrigins()) {}
89 using DataflowAnalysis<AnalysisImpl, Lattice, Direction::Backward>::transfer;
90
91 StringRef getAnalysisName() const { return "LiveOrigins"; }
92
93 Lattice getInitialState() {
94 return Lattice(Factory.getEmptyMap(), Factory.getEmptyMap());
95 }
96
97 /// An origin referenced from a single block need not be live outside it.
98 ///
99 /// Loans only ever enter an origin through an `IssueFact` or an
100 /// `OriginFlowFact` naming it as the destination, and both would make the
101 /// origin persistent if they lived in another block. So a block-local origin
102 /// holds no loans anywhere outside its own block, and every consumer of
103 /// liveness intersects it with the origin's loans. Dropping these here keeps
104 /// them out of the joins and out of the block-entry state comparison.
105 Lattice transferAtBlockExit(Lattice L) {
106 return Lattice(L.Persistent, Factory.getEmptyMap());
107 }
108
109 /// Merges two lattices by combining liveness information.
110 /// When the same origin has different confidence levels, we take the lower
111 /// one.
112 Lattice join(Lattice L1, Lattice L2) const {
113 assert(L1.BlockLocal.isEmpty() && L2.BlockLocal.isEmpty() &&
114 "block-local origins must not reach a block boundary");
115 // Take the earliest Fact to make the join hermetic and commutative.
116 auto CombineCausingFact = [](CausingFactType A,
118 if (!A)
119 return B;
120 if (!B)
121 return A;
122 return GetFactLoc(A) < GetFactLoc(B) ? A : B;
123 };
124 auto CombineLivenessKind = [](LivenessKind K1,
126 assert(K1 != LivenessKind::Dead && "LivenessKind should not be dead.");
127 assert(K2 != LivenessKind::Dead && "LivenessKind should not be dead.");
128 // Only return "Must" if both paths are "Must", otherwise Maybe.
129 if (K1 == LivenessKind::Must && K2 == LivenessKind::Must)
130 return LivenessKind::Must;
131 return LivenessKind::Maybe;
132 };
133 auto CombineLivenessInfo = [&](const LivenessInfo *L1,
134 const LivenessInfo *L2) -> LivenessInfo {
135 assert((L1 || L2) && "unexpectedly merging 2 empty sets");
136 if (!L1)
137 return LivenessInfo(L2->CausingFact, LivenessKind::Maybe);
138 if (!L2)
139 return LivenessInfo(L1->CausingFact, LivenessKind::Maybe);
140 return LivenessInfo(CombineCausingFact(L1->CausingFact, L2->CausingFact),
141 CombineLivenessKind(L1->Kind, L2->Kind));
142 };
143 // A symmetric join is required here. If an origin is live on one branch but
144 // not the other, its confidence must be demoted to `Maybe`.
145 LivenessMap Joined =
146 utils::join(L1.Persistent, L2.Persistent, Factory, CombineLivenessInfo,
148 return Lattice(Joined, Factory.getEmptyMap());
149 }
150
151 /// A use makes the origin live with definite confidence, as it dominates this
152 /// program point.
153 Lattice transfer(Lattice In, const UseFact &UF) {
154 Lattice Out = In;
155 for (const OriginList *Cur = UF.getUsedOrigins(); Cur;
156 Cur = Cur->peelOuterOrigin())
157 Out = addLive(Out, Cur->getOuterOriginID(),
158 LivenessInfo(&UF, LivenessKind::Must));
159 return Out;
160 }
161
162 /// An escaping origin (e.g., via return) makes the origin live with definite
163 /// confidence, as it dominates this program point.
164 Lattice transfer(Lattice In, const OriginEscapesFact &OEF) {
165 return addLive(In, OEF.getEscapedOriginID(),
166 LivenessInfo(&OEF, LivenessKind::Must));
167 }
168
169 /// Issuing a new loan to an origin kills its liveness.
170 Lattice transfer(Lattice In, const IssueFact &IF) {
171 return removeLive(In, IF.getOriginID());
172 }
173
174 /// An OriginFlow kills the liveness of the destination origin if `KillDest`
175 /// is true. Otherwise, it propagates liveness from destination to source.
176 Lattice transfer(Lattice In, const OriginFlowFact &OF) {
177 Lattice Out = In;
178 OriginID Dest = OF.getDestOriginID();
179 // If the destination of the flow is live, the source of the flow must also
180 // be marked live before this point as its value will flow into the
181 // destination.
182 if (const LivenessInfo *DestInfo = lookupLive(In, Dest))
183 Out = addLive(Out, OF.getSrcOriginID(), *DestInfo);
184 if (OF.getKillDest())
185 Out = removeLive(Out, Dest);
186 return Out;
187 }
188
189 Lattice transfer(Lattice In, const KillOriginFact &F) {
190 return removeLive(In, F.getKilledOrigin());
191 }
192
193 Lattice transfer(Lattice In, const ExpireFact &F) {
194 if (auto OID = F.getOriginID())
195 return removeLive(In, *OID);
196 return In;
197 }
198
199 LiveOriginSet getLiveOriginsAt(ProgramPoint P) const {
200 Lattice L = getState(P);
201 return LiveOriginSet{L.Persistent, L.BlockLocal};
202 }
203
204 // Dump liveness values on all test points in the program.
205 void dump(llvm::raw_ostream &OS,
206 const llvm::StringMap<ProgramPoint> &TestPoints) const {
207 llvm::dbgs() << "==========================================\n";
208 llvm::dbgs() << getAnalysisName() << " results:\n";
209 llvm::dbgs() << "==========================================\n";
210 for (const auto &Entry : TestPoints) {
211 OS << "TestPoint: " << Entry.getKey() << "\n";
212 getState(Entry.getValue()).dump(OS, FactMgr.getOriginMgr());
213 }
214 }
215
216private:
217 /// Routes an origin to the half of the lattice it belongs to.
218 bool isPersistent(OriginID OID) const {
219 return PersistentOrigins.test(OID.Value);
220 }
221
222 Lattice addLive(Lattice L, OriginID OID, LivenessInfo Info) {
223 if (isPersistent(OID))
224 return Lattice(Factory.add(L.Persistent, OID, Info), L.BlockLocal);
225 return Lattice(L.Persistent, Factory.add(L.BlockLocal, OID, Info));
226 }
227
228 Lattice removeLive(Lattice L, OriginID OID) {
229 if (isPersistent(OID))
230 return Lattice(Factory.remove(L.Persistent, OID), L.BlockLocal);
231 return Lattice(L.Persistent, Factory.remove(L.BlockLocal, OID));
232 }
233
234 const LivenessInfo *lookupLive(const Lattice &L, OriginID OID) const {
235 return isPersistent(OID) ? L.Persistent.lookup(OID)
236 : L.BlockLocal.lookup(OID);
237 }
238
239 FactManager &FactMgr;
240 LivenessMap::Factory &Factory;
241 /// Origins referenced from more than one basic block; see
242 /// `FactManager::getPersistentOrigins`.
243 const llvm::BitVector &PersistentOrigins;
244};
245} // namespace
246
247// PImpl wrapper implementation
248class LiveOriginsAnalysis::Impl final : public AnalysisImpl {
249 using AnalysisImpl::AnalysisImpl;
250};
251
253 FactManager &F,
254 LivenessMap::Factory &SF)
255 : PImpl(std::make_unique<Impl>(C, AC, F, SF)) {
256 PImpl->run();
257}
258
260
262 return PImpl->getLiveOriginsAt(P);
263}
264
266 llvm::raw_ostream &OS,
267 const llvm::StringMap<ProgramPoint> &TestPoints) const {
268 PImpl->dump(OS, TestPoints);
269}
270} // namespace clang::lifetimes::internal
static void dump(llvm::raw_ostream &OS, StringRef FunctionName, ArrayRef< CounterExpression > Expressions, ArrayRef< CounterMappingRegion > Regions)
AnalysisDeclContext contains the context data for the function, method or block under analysis.
Represents a source-level, intra-procedural CFG that represents the control-flow of a Stmt.
Definition CFG.h:1294
A generic, policy-based driver for dataflow analyses.
Definition Dataflow.h:60
LiveOriginSet getLiveOriginsAt(ProgramPoint P) const
Returns the set of origins that are live at a specific program point, along with the the details of t...
LiveOriginsAnalysis(const CFG &C, AnalysisDeclContext &AC, FactManager &F, LivenessMap::Factory &SF)
void dump(llvm::raw_ostream &OS, const llvm::StringMap< ProgramPoint > &TestPoints) const
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,...
@ Symmetric
A symmetric join applies the JoinValues operation to keys unique to either map, ensuring that values ...
Definition Utils.h:63
SetTy< T > join(SetTy< T > A, SetTy< T > B, typename SetTy< T >::Factory &F)
Computes the union of two ImmutableSets.
Definition Utils.h:49
const Fact * ProgramPoint
A ProgramPoint identifies a location in the CFG by pointing to a specific Fact.
Definition Facts.h:157
utils::ID< struct OriginTag > OriginID
Definition Origins.h:28
::llvm::PointerUnion< const UseFact *, const OriginEscapesFact * > CausingFactType
Definition LiveOrigins.h:34
utils::MapTy< OriginID, LivenessInfo > LivenessMap
Definition LiveOrigins.h:76
bool operator==(const CallGraphNode::CallRecord &LHS, const CallGraphNode::CallRecord &RHS)
Definition CallGraph.h:218
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
bool operator!=(CanQual< T > x, CanQual< U > y)
@ Other
Other implicit parameter.
Definition Decl.h:1787
The origins that are live at a program point.
Definition LiveOrigins.h:86