25#include "llvm/ADT/ScopeExit.h"
26#include "llvm/Support/Casting.h"
27#include "llvm/Support/Debug.h"
28#include "llvm/Support/DebugLog.h"
32#define DEBUG_TYPE "dead-code-analysis"
49 os << (live ?
"live" :
"dead");
56 if (pp->isBlockStart()) {
59 solver->
enqueue({pp, analysis});
65 }
else if (
auto *latticeAnchor =
66 llvm::dyn_cast_if_present<GenericLatticeAnchor *>(
anchor)) {
68 if (
auto *edge = dyn_cast<CFGEdge>(latticeAnchor)) {
83 os <<
"predecessors:";
103 if (!inputs.empty()) {
104 ValueRange &curInputs = successorInputs[predecessor];
105 if (curInputs != inputs) {
118 return FusedLoc::get(
139 LDBG() <<
"Initializing DeadCodeAnalysis for top-level op: "
148 LDBG() <<
"Marked entry block live for region in op: "
153 if (isa<CallableOpInterface>(top)) {
156 LDBG() <<
"[init] Marked callable root as having unknown predecessors: "
162 initializeSymbolCallables(top);
164 return initializeRecursively(top);
167void DeadCodeAnalysis::initializeSymbolCallables(
Operation *top) {
168 LDBG() <<
"[init] Entering initializeSymbolCallables for top-level op: "
172 auto walkFn = [&](
Operation *symTable,
bool allUsesVisible) {
173 LDBG() <<
"[init] Processing symbol table op: "
176 Block *symbolTableBlock = &symbolTableRegion.
front();
178 bool foundSymbolCallable =
false;
179 for (
auto callable : symbolTableBlock->
getOps<CallableOpInterface>()) {
180 LDBG() <<
"[init] Found CallableOpInterface: "
183 Region *callableRegion = callable.getCallableRegion();
186 auto symbol = dyn_cast<SymbolOpInterface>(callable.getOperation());
192 if (symbol.isPublic() || (!allUsesVisible && symbol.isNested())) {
196 LDBG() <<
"[init] Marked callable as having unknown predecessors: "
200 foundSymbolCallable =
true;
204 if (!foundSymbolCallable)
208 std::optional<SymbolTable::UseRange> uses =
213 LDBG() <<
"[init] Could not gather symbol uses, conservatively marking "
214 "all nested callables as having unknown predecessors";
215 return top->
walk([&](CallableOpInterface callable) {
219 LDBG() <<
"[init] Marked nested callable as "
220 "having unknown predecessors: "
226 for (
const SymbolTable::SymbolUse &use : *uses) {
227 if (isa<CallOpInterface>(use.getUser()))
231 Operation *symbol = symbolTable.lookupSymbolIn(top, use.getSymbolRef());
236 LDBG() <<
"[init] Found non-call use for symbol, "
237 "marked as having unknown predecessors: "
238 << OpWithFlags(symbol, OpPrintingFlags().skipRegions());
243 LDBG() <<
"[init] Finished initializeSymbolCallables for top-level op: "
244 << OpWithFlags(top, OpPrintingFlags().skipRegions());
251 isa<RegionBranchOpInterface, CallableOpInterface>(op->
getParentOp()) &&
255LogicalResult DeadCodeAnalysis::initializeRecursively(Operation *op) {
256 LDBG() <<
"[init] Entering initializeRecursively for op: "
257 << OpWithFlags(op, OpPrintingFlags().skipRegions());
261 LDBG() <<
"[init] Visiting op with control-flow semantics: "
262 << OpWithFlags(op, OpPrintingFlags().skipRegions());
267 ->blockContentSubscribe(
this);
277 bool savedHasSymbolTable = hasSymbolTable;
278 llvm::scope_exit restoreHasSymbolTable(
279 [&]() { hasSymbolTable = savedHasSymbolTable; });
280 if (!hasSymbolTable && op->
hasTrait<OpTrait::SymbolTable>())
281 hasSymbolTable =
true;
284 LDBG() <<
"[init] Recursing into region of op: "
285 << OpWithFlags(op, OpPrintingFlags().skipRegions());
286 for (Operation &nestedOp : region.getOps()) {
287 LDBG() <<
"[init] Recursing into nested op: "
288 << OpWithFlags(&nestedOp, OpPrintingFlags().skipRegions());
289 if (
failed(initializeRecursively(&nestedOp)))
294 LDBG() <<
"[init] Finished initializeRecursively for op: "
295 << OpWithFlags(op, OpPrintingFlags().skipRegions());
299void DeadCodeAnalysis::markEdgeLive(
Block *from,
Block *to) {
300 LDBG() <<
"Marking edge live from block " << from <<
" to block " << to;
308void DeadCodeAnalysis::markEntryBlocksLive(Operation *op) {
309 LDBG() <<
"Marking entry blocks live for op: "
310 << OpWithFlags(op, OpPrintingFlags().skipRegions());
317 LDBG() <<
"Marked entry block live for region in op: "
318 << OpWithFlags(op, OpPrintingFlags().skipRegions());
323 LDBG() <<
"Visiting program point: " << *point;
327 LDBG() <<
"Visiting operation: "
334 LDBG() <<
"Parent block not live, skipping op: "
340 if (
auto call = dyn_cast<CallOpInterface>(op)) {
341 LDBG() <<
"Visiting call operation: "
343 visitCallOperation(call);
349 if (
auto branch = dyn_cast<RegionBranchOpInterface>(op)) {
350 LDBG() <<
"Visiting region branch operation: "
352 visitRegionBranchOperation(branch);
355 }
else if (
auto callable = dyn_cast<CallableOpInterface>(op)) {
356 LDBG() <<
"Visiting callable operation: "
363 if (!callsites->allPredecessorsKnown() ||
364 !callsites->getKnownPredecessors().empty())
365 markEntryBlocksLive(callable);
369 LDBG() <<
"Marking all entry blocks live for op: "
371 markEntryBlocksLive(op);
376 if (
auto branch = dyn_cast<RegionBranchOpInterface>(op->
getParentOp())) {
377 LDBG() <<
"Visiting region terminator: "
380 visitRegionTerminator(op, branch);
381 }
else if (
auto callable =
382 dyn_cast<CallableOpInterface>(op->
getParentOp())) {
383 LDBG() <<
"Visiting callable terminator: "
386 visitCallableTerminator(op, callable);
392 if (
auto branch = dyn_cast<BranchOpInterface>(op)) {
393 LDBG() <<
"Visiting branch operation: "
395 visitBranchOperation(branch);
399 LDBG() <<
"Marking all successors live for op: "
402 markEdgeLive(op->
getBlock(), successor);
409void DeadCodeAnalysis::visitCallOperation(CallOpInterface call) {
410 LDBG() <<
"visitCallOperation: "
415 callableOp = call.resolveCallableInTable(&symbolTable);
418 <<
"No symbol table present in analysis scope, can't resolve callable";
421 const auto isExternalCallable = [
this](
Operation *op) {
426 if (
auto callable = dyn_cast<CallableOpInterface>(op))
427 return !callable.getCallableRegion();
434 if (isa_and_nonnull<SymbolOpInterface>(callableOp) &&
435 !isExternalCallable(callableOp)) {
440 LDBG() <<
"Added callsite as predecessor for callable: "
447 LDBG() <<
"Marked call op's predecessors as unknown for: "
455std::optional<SmallVector<Attribute>>
456DeadCodeAnalysis::getOperandValues(Operation *op) {
457 SmallVector<Attribute> operands;
463 if (cv->
getValue().isUninitialized())
465 operands.push_back(cv->
getValue().getConstantValue());
470void DeadCodeAnalysis::visitBranchOperation(BranchOpInterface branch) {
471 LDBG() <<
"visitBranchOperation: "
472 << OpWithFlags(branch.getOperation(), OpPrintingFlags().skipRegions());
474 std::optional<SmallVector<Attribute>> operands = getOperandValues(branch);
478 if (
Block *successor = branch.getSuccessorForOperands(*operands)) {
479 markEdgeLive(branch->getBlock(), successor);
480 LDBG() <<
"Branch has single successor: " << successor;
483 for (
Block *successor : branch->getSuccessors())
484 markEdgeLive(branch->getBlock(), successor);
485 LDBG() <<
"Branch has multiple/all successors live";
489void DeadCodeAnalysis::visitRegionBranchOperation(
490 RegionBranchOpInterface branch) {
491 LDBG() <<
"visitRegionBranchOperation: "
492 << OpWithFlags(branch.getOperation(), OpPrintingFlags().skipRegions());
494 std::optional<SmallVector<Attribute>> operands = getOperandValues(branch);
498 SmallVector<RegionSuccessor> successors;
499 branch.getEntrySuccessorRegions(*operands, successors);
501 visitRegionBranchEdges(branch, branch.getOperation(), successors);
504void DeadCodeAnalysis::visitRegionTerminator(Operation *op,
505 RegionBranchOpInterface branch) {
506 LDBG() <<
"visitRegionTerminator: " << *op;
507 std::optional<SmallVector<Attribute>> operands = getOperandValues(op);
511 SmallVector<RegionSuccessor> successors;
512 auto terminator = dyn_cast<RegionBranchTerminatorOpInterface>(op);
515 terminator.getSuccessorRegions(*operands, successors);
516 visitRegionBranchEdges(branch, op, successors);
519void DeadCodeAnalysis::visitRegionBranchEdges(
520 RegionBranchOpInterface regionBranchOp, Operation *predecessorOp,
521 const SmallVector<RegionSuccessor> &successors) {
522 for (
const RegionSuccessor &successor : successors) {
524 ProgramPoint *point =
532 LDBG() <<
"Marked region successor live: " << *point;
538 predecessors->join(predecessorOp,
539 regionBranchOp.getSuccessorInputs(successor)));
540 LDBG() <<
"Added region branch as predecessor for successor: " << *point;
544void DeadCodeAnalysis::visitCallableTerminator(Operation *op,
545 CallableOpInterface callable) {
546 LDBG() <<
"visitCallableTerminator: " << *op;
550 bool canResolve = op->
hasTrait<OpTrait::ReturnLike>();
551 for (Operation *predecessor : callsites->getKnownPredecessors()) {
552 assert(isa<CallOpInterface>(predecessor));
557 LDBG() <<
"Added callable terminator as predecessor for callsite: "
558 << OpWithFlags(predecessor, OpPrintingFlags().skipRegions());
563 predecessors->setHasUnknownPredecessors());
564 LDBG() <<
"Could not resolve callable terminator for callsite: "
565 << OpWithFlags(predecessor, OpPrintingFlags().skipRegions());
static bool isRegionOrCallableReturn(Operation *op)
Returns true if the operation is a returning terminator in region control-flow or the terminator of a...
virtual void onUpdate(DataFlowSolver *solver) const
This function is called by the solver when the analysis state is updated to enqueue more work items.
LatticeAnchor anchor
The lattice anchor to which the state belongs.
friend class DataFlowSolver
Allow the framework to access the dependents.
Block represents an ordered list of Operations.
iterator_range< op_iterator< OpT > > getOps()
Return an iterator range over the operations within this block that are of 'OpT'.
Region * getParent() const
Provide a 'getParent' method for ilist_node_with_parent methods.
Operation * getTerminator()
Get the terminator operation of this block.
void print(raw_ostream &os)
Base class for all data-flow analyses.
ProgramPoint * getProgramPointBefore(Operation *op)
Get a uniqued program point instance.
void propagateIfChanged(AnalysisState *state, ChangeResult changed)
Propagate an update to a state if it changed.
StateT * getOrCreate(AnchorT anchor)
Get the analysis state associated with the lattice anchor.
ProgramPoint * getProgramPointAfter(Operation *op)
DataFlowAnalysis(DataFlowSolver &solver)
Create an analysis with a reference to the parent solver.
AnchorT * getLatticeAnchor(Args &&...args)
Get or create a custom lattice anchor.
void registerAnchorKind()
Register a custom lattice anchor class.
friend class DataFlowSolver
Allow the data-flow solver to access the internals of this class.
const StateT * getOrCreateFor(ProgramPoint *dependent, AnchorT anchor)
Get a read-only analysis state for the given point and create a dependency on dependent.
void enqueue(WorkItem item)
Push a work item onto the worklist.
ProgramPoint * getProgramPointBefore(Operation *op)
Get a uniqued program point instance.
ProgramPoint * getProgramPointAfter(Operation *op)
This class defines the main interface for locations in MLIR and acts as a non-nullable wrapper around...
Set of flags used to control the behavior of the various IR print methods (e.g.
A trait used to provide symbol table functionalities to a region operation.
A wrapper class that allows for printing an operation with a set of flags, useful to act as a "stream...
Operation is the basic unit of execution within MLIR.
Region & getRegion(unsigned index)
Returns the region held by this operation at position 'index'.
bool hasTrait()
Returns true if the operation was registered with a particular trait, e.g.
unsigned getNumSuccessors()
Block * getBlock()
Returns the operation block that contains this operation.
unsigned getNumRegions()
Returns the number of regions held by this operation.
Operation * getParentOp()
Returns the closest surrounding operation that contains this operation or nullptr if this is a top-le...
unsigned getNumOperands()
MutableArrayRef< Region > getRegions()
Returns the regions held by this operation.
operand_range getOperands()
Returns an iterator on the underlying Value's.
bool isAncestor(Operation *other)
Return true if this operation is an ancestor of the other operation.
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),...
SuccessorRange getSuccessors()
This class contains a list of basic blocks and a link to the parent operation it is attached to.
Location getLoc()
Return a location for this region.
static void walkSymbolTables(Operation *op, bool allSymUsesVisible, function_ref< void(Operation *, bool)> callback)
Walks all symbol table operations nested within, and including, op.
static std::optional< UseRange > getSymbolUses(Operation *from)
Get an iterator range for all of the uses, for any symbol, that are nested within the given operation...
This class provides an abstraction over the different types of ranges over Values.
void useDefSubscribe(DataFlowAnalysis *analysis)
Subscribe an analysis to updates of the lattice.
Location getLoc() const override
Get a fused location of both blocks.
Block * getTo() const
Get the target block.
Block * getFrom() const
Get the block from which the edge originates.
void print(raw_ostream &os) const override
Print the blocks between the control-flow edge.
DeadCodeAnalysis(DataFlowSolver &solver)
LogicalResult visit(ProgramPoint *point) override
Visit an operation with control-flow semantics and deduce which of its successors are live.
LogicalResult initialize(Operation *top) override
Initialize the analysis by visiting every operation with potential control-flow semantics.
void onUpdate(DataFlowSolver *solver) const override
When the state of the lattice anchor is changed to live, re-invoke subscribed analyses on the operati...
ChangeResult setToLive()
Set the state of the lattice anchor to live.
void print(raw_ostream &os) const override
Print the liveness.
ValueT & getValue()
Return the value held by this lattice.
ArrayRef< Operation * > getKnownPredecessors() const
Get the known predecessors.
bool allPredecessorsKnown() const
Returns true if all predecessors are known.
void print(raw_ostream &os) const override
Print the known predecessors.
ChangeResult join(Operation *predecessor)
Add a known predecessor.
Include the generated interface declarations.
ChangeResult
A result type used to indicate if a change happened.
Program point represents a specific location in the execution of a program.
bool isBlockStart() const
Operation * getPrevOp() const
Get the previous operation of this program point.