clang 24.0.0git
Dataflow.h
Go to the documentation of this file.
1//===- Dataflow.h - Generic Dataflow Analysis Framework --------*- 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 a generic, policy-based driver for dataflow analyses.
10// It provides a flexible framework that combines the dataflow runner and
11// transfer functions, allowing derived classes to implement specific analyses
12// by defining their lattice, join, and transfer functions.
13//
14//===----------------------------------------------------------------------===//
15#ifndef LLVM_CLANG_ANALYSIS_ANALYSES_LIFETIMESAFETY_DATAFLOW_H
16#define LLVM_CLANG_ANALYSIS_ANALYSES_LIFETIMESAFETY_DATAFLOW_H
17
20#include "clang/Analysis/CFG.h"
22#include "llvm/Support/Debug.h"
23#include "llvm/Support/ErrorHandling.h"
24#include "llvm/Support/TimeProfiler.h"
25#include <optional>
26
28
29enum class Direction { Forward, Backward };
30
31/// A `ProgramPoint` identifies a location in the CFG by pointing to a specific
32/// `Fact`. identified by a lifetime-related event (`Fact`).
33///
34/// A `ProgramPoint` has "after" semantics: it represents the location
35/// immediately after its corresponding `Fact`.
36using ProgramPoint = const Fact *;
37
38/// A generic, policy-based driver for dataflow analyses. It combines
39/// the dataflow runner and the transferer logic into a single class hierarchy.
40///
41/// The derived class is expected to provide:
42/// - A `Lattice` type.
43/// - `StringRef getAnalysisName() const`
44/// - `Lattice getInitialState();` The initial state of the analysis.
45/// - `Lattice join(Lattice, Lattice);` Merges states from multiple CFG paths.
46/// - `Lattice transfer(Lattice, const FactType&);` Defines how a single
47/// lifetime-relevant `Fact` transforms the lattice state. Only overloads
48/// for facts relevant to the analysis need to be implemented.
49///
50/// It may additionally override `Lattice transferAtBlockExit(Lattice);` to
51/// drop state that is not visible outside the block it was computed in.
52///
53/// \tparam Derived The CRTP derived class that implements the specific
54/// analysis.
55/// \tparam LatticeType The dataflow lattice used by the analysis.
56/// \tparam Dir The direction of the analysis (Forward or Backward).
57/// TODO: Maybe use the dataflow framework! The framework might need changes
58/// to support the current comparison done at block-entry.
59template <typename Derived, typename LatticeType, Direction Dir>
61public:
62 using Lattice = LatticeType;
64
65private:
66 const CFG &Cfg;
68
69 /// The dataflow state before each basic block is processed, indexed by block
70 /// ID. Unset for blocks that have not been reached yet.
72 /// The dataflow state after each basic block is processed, indexed by block
73 /// ID.
75 /// Dataflow state at each program point, indexed by Fact ID.
76 /// In a forward analysis, this is the state after the Fact at that point has
77 /// been applied, while in a backward analysis, it is the state before.
78 llvm::SmallVector<Lattice> PointToState;
79
80 static constexpr bool isForward() { return Dir == Direction::Forward; }
81
82protected:
84
85 explicit DataflowAnalysis(const CFG &Cfg, AnalysisDeclContext &AC,
87 : Cfg(Cfg), AC(AC), FactMgr(FactMgr) {}
88
89public:
90 void run() {
91 Derived &D = static_cast<Derived &>(*this);
92 llvm::TimeTraceScope Time(D.getAnalysisName());
93
94 PointToState.resize(FactMgr.getNumFacts());
95 InStates.resize(Cfg.getNumBlockIDs());
96 OutStates.resize(Cfg.getNumBlockIDs());
97
98 using Worklist =
99 std::conditional_t<Dir == Direction::Forward, ForwardDataflowWorklist,
101 Worklist W(Cfg, AC);
102
103 const CFGBlock *Start = isForward() ? &Cfg.getEntry() : &Cfg.getExit();
104 InStates[Start->getBlockID()] = D.getInitialState();
105 W.enqueueBlock(Start);
106 drainWorklist(D, W);
107
108 // Walking predecessors from the exit only reaches blocks that can reach the
109 // exit, e.g., it misses the body of an infinite loop. Analyze those too.
110 // Their in-state is left unset rather than seeded, so that only the first
111 // block analyzed in each such cycle starts from the initial state.
112 if constexpr (!isForward()) {
113 for (const CFGBlock *B : Cfg)
114 if (!InStates[B->getBlockID()])
115 W.enqueueBlock(B);
116 drainWorklist(D, W);
117 }
118 }
119
120private:
121 template <typename WorklistT> void drainWorklist(Derived &D, WorklistT &W) {
122 while (const CFGBlock *B = W.dequeue()) {
123 std::optional<Lattice> StateIn = getInState(B);
124 Lattice StateOut =
125 transferBlock(B, StateIn ? *StateIn : D.getInitialState());
126 OutStates[B->getBlockID()] = StateOut;
127 for (const CFGBlock *AdjacentB : isForward() ? B->succs() : B->preds()) {
128 if (!AdjacentB)
129 continue;
130 std::optional<Lattice> OldInState = getInState(AdjacentB);
131 Lattice NewInState =
132 !OldInState ? StateOut : D.join(*OldInState, StateOut);
133 // Enqueue the adjacent block if its in-state has changed or if we have
134 // never seen it.
135 if (!OldInState || NewInState != *OldInState) {
136 InStates[AdjacentB->getBlockID()] = NewInState;
137 W.enqueueBlock(AdjacentB);
138 }
139 }
140 }
141 }
142
143protected:
145 return PointToState[P->getID().Value];
146 }
147
148 std::optional<Lattice> getInState(const CFGBlock *B) const {
149 return InStates[B->getBlockID()];
150 }
151
152 Lattice getOutState(const CFGBlock *B) const {
153 return OutStates[B->getBlockID()];
154 }
155
156 void dump() const {
157 const Derived *D = static_cast<const Derived *>(this);
158 llvm::dbgs() << "==========================================\n";
159 llvm::dbgs() << D->getAnalysisName() << " results:\n";
160 llvm::dbgs() << "==========================================\n";
161 const CFGBlock &B = isForward() ? Cfg.getExit() : Cfg.getEntry();
162 getOutState(&B).dump(llvm::dbgs());
163 }
164
165private:
166 /// Computes the state at one end of a block by applying all its facts
167 /// sequentially to a given state from the other end.
168 Lattice transferBlock(const CFGBlock *Block, Lattice State) {
169 auto Facts = FactMgr.getFacts(Block);
170 if constexpr (isForward()) {
171 for (const Fact *F : Facts) {
172 State = transferFact(State, F);
173 PointToState[F->getID().Value] = State;
174 }
175 } else {
176 for (const Fact *F : llvm::reverse(Facts)) {
177 // In backward analysis, capture the state before applying the fact.
178 PointToState[F->getID().Value] = State;
179 State = transferFact(State, F);
180 }
181 }
182 return static_cast<Derived *>(this)->transferAtBlockExit(State);
183 }
184
185 Lattice transferFact(Lattice In, const Fact *F) {
186 assert(F);
187 Derived *D = static_cast<Derived *>(this);
188 switch (F->getKind()) {
190 return D->transfer(In, *F->getAs<IssueFact>());
192 return D->transfer(In, *F->getAs<ExpireFact>());
194 return D->transfer(In, *F->getAs<OriginFlowFact>());
196 return D->transfer(In, *F->getAs<MovedOriginFact>());
198 return D->transfer(In, *F->getAs<OriginEscapesFact>());
199 case Fact::Kind::Use:
200 return D->transfer(In, *F->getAs<UseFact>());
202 return D->transfer(In, *F->getAs<TestPointFact>());
204 return D->transfer(In, *F->getAs<InvalidateOriginFact>());
206 return D->transfer(In, *F->getAs<KillOriginFact>());
207 }
208 llvm_unreachable("Unknown fact kind");
209 }
210
211public:
213
214 Lattice transfer(Lattice In, const IssueFact &) { return In; }
215 Lattice transfer(Lattice In, const ExpireFact &) { return In; }
216 Lattice transfer(Lattice In, const OriginFlowFact &) { return In; }
217 Lattice transfer(Lattice In, const MovedOriginFact &) { return In; }
218 Lattice transfer(Lattice In, const OriginEscapesFact &) { return In; }
219 Lattice transfer(Lattice In, const UseFact &) { return In; }
220 Lattice transfer(Lattice In, const TestPointFact &) { return In; }
221 Lattice transfer(Lattice In, const InvalidateOriginFact &) { return In; }
222 Lattice transfer(Lattice In, const KillOriginFact &) { return In; }
223};
224} // namespace clang::lifetimes::internal
225#endif // LLVM_CLANG_ANALYSIS_ANALYSES_LIFETIMESAFETY_DATAFLOW_H
This file defines AnalysisDeclContext, a class that manages the analysis context data for context sen...
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:651
void dump() const
Definition CFG.cpp:6382
unsigned getBlockID() const
Definition CFG.h:1177
Represents a source-level, intra-procedural CFG that represents the control-flow of a Stmt.
Definition CFG.h:1294
Lattice transfer(Lattice In, const InvalidateOriginFact &)
Definition Dataflow.h:221
DataflowAnalysis(const CFG &Cfg, AnalysisDeclContext &AC, FactManager &FactMgr)
Definition Dataflow.h:85
Lattice transfer(Lattice In, const KillOriginFact &)
Definition Dataflow.h:222
std::optional< Lattice > getInState(const CFGBlock *B) const
Definition Dataflow.h:148
Lattice transfer(Lattice In, const OriginFlowFact &)
Definition Dataflow.h:216
Lattice transfer(Lattice In, const MovedOriginFact &)
Definition Dataflow.h:217
Lattice transfer(Lattice In, const TestPointFact &)
Definition Dataflow.h:220
Lattice getOutState(const CFGBlock *B) const
Definition Dataflow.h:152
Lattice transfer(Lattice In, const UseFact &)
Definition Dataflow.h:219
Lattice transfer(Lattice In, const IssueFact &)
Definition Dataflow.h:214
Lattice transfer(Lattice In, const OriginEscapesFact &)
Definition Dataflow.h:218
Lattice transfer(Lattice In, const ExpireFact &)
Definition Dataflow.h:215
DataflowAnalysis< Derived, Lattice, Dir > Base
Definition Dataflow.h:63
Lattice getState(ProgramPoint P) const
Definition Dataflow.h:144
When an AccessPath expires (e.g., a variable goes out of scope), all loans that are associated with t...
Definition Facts.h:178
llvm::ArrayRef< const Fact * > getFacts(const CFGBlock *B) const
Definition Facts.h:463
An abstract base class for a single, atomic lifetime-relevant event.
Definition Facts.h:100
@ InvalidateOrigin
An origin is invalidated (e.g. vector resized, delete called).
Definition Facts.h:123
@ TestPoint
A marker for a specific point in the code, for testing.
Definition Facts.h:119
@ Expire
A loan expires as its underlying storage is freed (e.g., variable goes out of scope).
Definition Facts.h:108
@ Issue
A new loan is issued from a borrow expression (e.g., &x).
Definition Facts.h:105
@ OriginFlow
An origin is propagated from a source to a destination (e.g., p = q).
Definition Facts.h:113
@ MovedOrigin
An origin that is moved (e.g., passed to an rvalue reference parameter).
Definition Facts.h:117
@ Use
An origin is used (eg. appears as l-value expression like DeclRefExpr).
Definition Facts.h:115
@ OriginEscapes
An origin that escapes the function scope (e.g., via return).
Definition Facts.h:121
@ KillOrigin
All loans of an origin are cleared.
Definition Facts.h:125
Represents that an origin's storage has been invalidated by a container operation (e....
Definition Facts.h:380
All loans are cleared from an origin (e.g., assigning a callable without tracked origins to std::func...
Definition Facts.h:439
Top-level origin of the expression which was found to be moved, e.g, when being used as an argument t...
Definition Facts.h:401
Represents that an origin escapes the current scope through various means.
Definition Facts.h:228
A dummy-fact used to mark a specific point in the code for testing.
Definition Facts.h:422
const Fact * ProgramPoint
A ProgramPoint identifies a location in the CFG by pointing to a specific Fact.
Definition Facts.h:158
A worklist implementation for backward dataflow analysis.
A worklist implementation for forward dataflow analysis.