MLIR 23.0.0git
LivenessAnalysis.cpp
Go to the documentation of this file.
1//===- LivenessAnalysis.cpp - Liveness analysis ---------------------------===//
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 <cassert>
12
13#include <llvm/Support/DebugLog.h>
17#include <mlir/IR/Operation.h>
18#include <mlir/IR/Value.h>
21#include <mlir/Support/LLVM.h>
22
23#define DEBUG_TYPE "liveness-analysis"
24
25using namespace mlir;
26using namespace mlir::dataflow;
27
28//===----------------------------------------------------------------------===//
29// Liveness
30//===----------------------------------------------------------------------===//
31
33 os << (isLive ? "live" : "not live");
34}
35
37 bool wasLive = isLive;
38 isLive = true;
40}
41
43 const auto *otherLiveness = reinterpret_cast<const Liveness *>(&other);
44 return otherLiveness->isLive ? markLive() : ChangeResult::NoChange;
45}
46
47//===----------------------------------------------------------------------===//
48// LivenessAnalysis
49//===----------------------------------------------------------------------===//
50
51/// For every value, liveness analysis determines whether or not it is "live".
52///
53/// A value is considered "live" iff it:
54/// (1) has memory effects OR
55/// (2) is returned by a public function OR
56/// (3) is used to compute a value of type (1) or (2) OR
57/// (4) is returned by a return-like op whose parent isn't a callable
58/// nor a RegionBranchOpInterface (e.g.: linalg.yield, gpu.yield,...)
59/// These ops have their own semantics, so we conservatively mark the
60/// the yield value as live.
61/// It is also to be noted that a value could be of multiple types (1/2/3) at
62/// the same time.
63///
64/// A value "has memory effects" iff it:
65/// (1.a) is an operand of an op with memory effects OR
66/// (1.b) is a non-forwarded branch operand and its branch op could take the
67/// control to a block that has an op with memory effects OR
68/// (1.c) is a non-forwarded branch operand and its branch op could result
69/// in different live result OR
70/// (1.d) is a non-forwarded call operand.
71///
72/// A value `A` is said to be "used to compute" value `B` iff `B` cannot be
73/// computed in the absence of `A`. Thus, in this implementation, we say that
74/// value `A` is used to compute value `B` iff:
75/// (3.a) `B` is a result of an op with operand `A` OR
76/// (3.b) `A` is used to compute some value `C` and `C` is used to compute
77/// `B`.
78
79LogicalResult
82 LDBG() << "[visitOperation] Enter: "
83 << OpWithFlags(op, OpPrintingFlags().skipRegions());
84 // This marks values of type (1.a) and (4) liveness as "live".
85 if (!wouldOpBeTriviallyDead(op)) {
86 LDBG() << "[visitOperation] Operation has memory effects or is "
87 "return-like, marking operands live";
88 for (auto *operand : operands) {
89 LDBG() << " [visitOperation] Marking operand live: " << operand << " ("
90 << operand->isLive << ")";
91 propagateIfChanged(operand, operand->markLive());
92 }
93 }
94
95 // This marks values of type (3) liveness as "live".
96 bool foundLiveResult = false;
97 for (const Liveness *r : results) {
98 if (r->isLive && !foundLiveResult) {
99 LDBG() << "[visitOperation] Found live result, "
100 "meeting all operands with result: "
101 << r;
102 // It is assumed that each operand is used to compute each result of an
103 // op. Thus, if at least one result is live, each operand is live.
104 for (Liveness *operand : operands) {
105 LDBG() << " [visitOperation] Meeting operand: " << operand
106 << " with result: " << r;
107 meet(operand, *r);
108 }
109 foundLiveResult = true;
110 }
111 LDBG() << "[visitOperation] Adding dependency for result: " << r
112 << " after op: " << OpWithFlags(op, OpPrintingFlags().skipRegions());
113 addDependency(const_cast<Liveness *>(r), getProgramPointAfter(op));
114 }
115 return success();
116}
117
119 Operation *op = operand.getOwner();
120 LDBG() << "Visiting branch operand: " << operand.get()
121 << " in op: " << OpWithFlags(op, OpPrintingFlags().skipRegions());
122 // We know (at the moment) and assume (for the future) that `operand` is a
123 // non-forwarded branch operand of a `RegionBranchOpInterface`,
124 // `BranchOpInterface`, `RegionBranchTerminatorOpInterface` or return-like op.
125 assert((isa<RegionBranchOpInterface>(op) || isa<BranchOpInterface>(op) ||
126 isa<RegionBranchTerminatorOpInterface>(op)) &&
127 "expected the op to be `RegionBranchOpInterface`, "
128 "`BranchOpInterface` or `RegionBranchTerminatorOpInterface`");
129
130 // The lattices of the non-forwarded branch operands don't get updated like
131 // the forwarded branch operands or the non-branch operands. Thus they need
132 // to be handled separately. This is where we handle them.
133
134 // 1. BranchOpInterface: We cannot track all successor blocks. Therefore, we
135 // conservatively consider the non-forwarded operand of the branch operation
136 // live. We can just call visitOperation, which treats any terminator as live.
137 // 2. RegionBranchOpInterface: We can simply visit it as a normal operation
138 // with this operand. The operand is live if the results of the op are used,
139 // or if it has any recursive memory side effects (which visitOperation will
140 // check).
141 // 3. RegionBranchOpTerminatorInterface, the operand is live if the
142 // surrounding RegionBranchOp is live, so we call visitOperation on the
143 // surrounding op, but with the operand that we are looking at.
144 auto *visitOp =
145 isa<RegionBranchTerminatorOpInterface>(op) ? op->getParentOp() : op;
146 Liveness *operandLiveness[] = {getLatticeElement(operand.get())};
147 SmallVector<const Liveness *, 4> resultsLiveness;
148 for (const Value result : visitOp->getResults())
149 resultsLiveness.push_back(getLatticeElement(result));
150 LDBG() << "Visiting operation for non-forwarded branch operand: "
151 << OpWithFlags(visitOp, OpPrintingFlags().skipRegions());
152 (void)visitOperation(visitOp, operandLiveness, resultsLiveness);
153}
154
156 LDBG() << "Visiting call operand: " << operand.get()
157 << " in op: " << *operand.getOwner();
158 // We know (at the moment) and assume (for the future) that `operand` is a
159 // non-forwarded call operand of an op implementing `CallOpInterface`.
160 assert(isa<CallOpInterface>(operand.getOwner()) &&
161 "expected the op to implement `CallOpInterface`");
162
163 // The lattices of the non-forwarded call operands don't get updated like the
164 // forwarded call operands or the non-call operands. Thus they need to be
165 // handled separately. This is where we handle them.
166
167 // This marks values of type (1.c) liveness as "live". A non-forwarded
168 // call operand is live.
169 Liveness *operandLiveness = getLatticeElement(operand.get());
170 LDBG() << "Marking call operand live: " << operand.get();
171 propagateIfChanged(operandLiveness, operandLiveness->markLive());
172}
173
175 RegionSuccessor &successor, ArrayRef<BlockArgument> arguments) {
176 Operation *parentOp = successor.getSuccessor()->getParentOp();
177 LDBG() << "visitNonControlFlowArguments visit the region: #"
178 << successor.getSuccessor()->getRegionNumber() << " of "
179 << OpWithFlags(parentOp, OpPrintingFlags().skipRegions());
180 auto valuesToLattices = [&](Value value) { return getLatticeElement(value); };
181 SmallVector<Liveness *> argumentLattices =
182 llvm::map_to_vector(arguments, valuesToLattices);
183 SmallVector<Liveness *> parentResultLattices =
184 llvm::map_to_vector(parentOp->getResults(), valuesToLattices);
185
186 for (Liveness *resultLattice : parentResultLattices) {
187 if (resultLattice->isLive) {
188 for (Liveness *argumentLattice : argumentLattices) {
189 LDBG() << "make lattice: " << argumentLattice << " live";
190 propagateIfChanged(argumentLattice, argumentLattice->markLive());
191 }
192 return;
193 }
194 }
195 (void)visitOperation(parentOp, argumentLattices, parentResultLattices);
196}
197
199 LDBG() << "setToExitState for lattice: " << lattice;
200 if (lattice->isLive) {
201 LDBG() << "Lattice already live, nothing to do";
202 return;
203 }
204 // This marks values of type (2) liveness as "live".
205 LDBG() << "Marking lattice live due to exit state";
206 (void)lattice->markLive();
208}
209
210//===----------------------------------------------------------------------===//
211// RunLivenessAnalysis
212//===----------------------------------------------------------------------===//
213
215 LDBG() << "Constructing RunLivenessAnalysis for op: " << op->getName();
216 SymbolTableCollection symbolTable;
217
218 loadBaselineAnalyses(solver);
219 solver.load<LivenessAnalysis>(symbolTable);
220 LDBG() << "Initializing and running solver";
221 (void)solver.initializeAndRun(op);
222 LDBG() << "RunLivenessAnalysis initialized for op: " << op->getName()
223 << " check on unreachable code now:";
224 // The framework doesn't visit operations in dead blocks, so we need to
225 // explicitly mark them as dead.
226 op->walk([&](Operation *op) {
227 for (auto result : llvm::enumerate(op->getResults())) {
228 if (getLiveness(result.value()))
229 continue;
230 LDBG() << "Result: " << result.index() << " of "
231 << OpWithFlags(op, OpPrintingFlags().skipRegions())
232 << " has no liveness info (unreachable), mark dead";
233 solver.getOrCreateState<Liveness>(result.value());
234 }
235 for (auto &region : op->getRegions()) {
236 for (auto &block : region) {
237 for (auto blockArg : llvm::enumerate(block.getArguments())) {
238 if (getLiveness(blockArg.value()))
239 continue;
240 LDBG() << "Block argument: " << blockArg.index() << " of "
241 << OpWithFlags(op, OpPrintingFlags().skipRegions())
242 << " has no liveness info, mark dead";
243 solver.getOrCreateState<Liveness>(blockArg.value());
244 }
245 }
246 }
247 });
248}
249
251 return solver.lookupState<Liveness>(val);
252}
return success()
static LogicalResult visitOp(Operation *op, OpBuilder &builder)
void addDependency(AnalysisState *state, ProgramPoint *point)
Create a dependency between the given analysis state and lattice anchor on this analysis.
void propagateIfChanged(AnalysisState *state, ChangeResult changed)
Propagate an update to a state if it changed.
ProgramPoint * getProgramPointAfter(Operation *op)
IRValueT get() const
Return the current value being used by this operand.
This class represents an operand of an operation.
Definition Value.h:257
Set of flags used to control the behavior of the various IR print methods (e.g.
A wrapper class that allows for printing an operation with a set of flags, useful to act as a "stream...
Definition Operation.h:1111
Operation is the basic unit of execution within MLIR.
Definition Operation.h:88
Operation * getParentOp()
Returns the closest surrounding operation that contains this operation or nullptr if this is a top-le...
Definition Operation.h:234
OperationName getName()
The name of an operation is the key identifier for it.
Definition Operation.h:119
MutableArrayRef< Region > getRegions()
Returns the regions held by this operation.
Definition Operation.h:677
std::enable_if_t< llvm::function_traits< std::decay_t< FnT > >::num_args==1, RetT > walk(FnT &&callback)
Walk the operation by calling the callback for each nested operation (including this one),...
Definition Operation.h:797
result_range getResults()
Definition Operation.h:415
This class represents a successor of a region.
Region * getSuccessor() const
Return the given region successor.
unsigned getRegionNumber()
Return the number of this region in the parent operation.
Definition Region.cpp:62
Operation * getParentOp()
Return the parent operation this region is attached to.
Definition Region.h:200
This class represents a collection of SymbolTables.
This class represents an instance of an SSA value in the MLIR system, representing a computable value...
Definition Value.h:96
void meet(AbstractSparseLattice *lhs, const AbstractSparseLattice &rhs)
Join the lattice element and propagate and update if it changed.
An analysis that, by going backwards along the dataflow graph, annotates each value with a boolean st...
void setToExitState(Liveness *lattice) override
Set the given lattice element(s) at control flow exit point(s).
void visitBranchOperand(OpOperand &operand) override
void visitCallOperand(OpOperand &operand) override
void visitNonControlFlowArguments(RegionSuccessor &successor, ArrayRef< BlockArgument > arguments) override
LogicalResult visitOperation(Operation *op, ArrayRef< Liveness * > operands, ArrayRef< const Liveness * > results) override
For every value, liveness analysis determines whether or not it is "live".
Operation * getOwner() const
Return the owner of this operand.
Definition UseDefLists.h:38
void loadBaselineAnalyses(DataFlowSolver &solver)
Populates a DataFlowSolver with analyses that are required to ensure user-defined analyses are run pr...
Definition Utils.h:29
Include the generated interface declarations.
ChangeResult
A result type used to indicate if a change happened.
bool wouldOpBeTriviallyDead(Operation *op)
Return true if the given operation would be dead if unused, and has no side effects on memory that wo...
This lattice represents, for a given value, whether or not it is "live".
void print(raw_ostream &os) const override
AbstractSparseLattice(Value value)
Lattices can only be created for values.
ChangeResult meet(const AbstractSparseLattice &other) override
Meet (intersect) the information in this lattice with 'rhs'.
const Liveness * getLiveness(Value val)