1 //===- SymbolDCE.cpp - Pass to delete dead symbols ------------------------===//
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 implements an algorithm for eliminating symbol operations that are
10 // known to be dead.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "PassDetail.h"
15 #include "mlir/Transforms/Passes.h"
16 
17 using namespace mlir;
18 
19 namespace {
20 struct SymbolDCE : public SymbolDCEBase<SymbolDCE> {
21   void runOnOperation() override;
22 
23   /// Compute the liveness of the symbols within the given symbol table.
24   /// `symbolTableIsHidden` is true if this symbol table is known to be
25   /// unaccessible from operations in its parent regions.
26   LogicalResult computeLiveness(Operation *symbolTableOp,
27                                 SymbolTableCollection &symbolTable,
28                                 bool symbolTableIsHidden,
29                                 DenseSet<Operation *> &liveSymbols);
30 };
31 } // end anonymous namespace
32 
runOnOperation()33 void SymbolDCE::runOnOperation() {
34   Operation *symbolTableOp = getOperation();
35 
36   // SymbolDCE should only be run on operations that define a symbol table.
37   if (!symbolTableOp->hasTrait<OpTrait::SymbolTable>()) {
38     symbolTableOp->emitOpError()
39         << " was scheduled to run under SymbolDCE, but does not define a "
40            "symbol table";
41     return signalPassFailure();
42   }
43 
44   // A flag that signals if the top level symbol table is hidden, i.e. not
45   // accessible from parent scopes.
46   bool symbolTableIsHidden = true;
47   SymbolOpInterface symbol = dyn_cast<SymbolOpInterface>(symbolTableOp);
48   if (symbolTableOp->getParentOp() && symbol)
49     symbolTableIsHidden = symbol.isPrivate();
50 
51   // Compute the set of live symbols within the symbol table.
52   DenseSet<Operation *> liveSymbols;
53   SymbolTableCollection symbolTable;
54   if (failed(computeLiveness(symbolTableOp, symbolTable, symbolTableIsHidden,
55                              liveSymbols)))
56     return signalPassFailure();
57 
58   // After computing the liveness, delete all of the symbols that were found to
59   // be dead.
60   symbolTableOp->walk([&](Operation *nestedSymbolTable) {
61     if (!nestedSymbolTable->hasTrait<OpTrait::SymbolTable>())
62       return;
63     for (auto &block : nestedSymbolTable->getRegion(0)) {
64       for (Operation &op :
65            llvm::make_early_inc_range(block.without_terminator())) {
66         if (isa<SymbolOpInterface>(&op) && !liveSymbols.count(&op))
67           op.erase();
68       }
69     }
70   });
71 }
72 
73 /// Compute the liveness of the symbols within the given symbol table.
74 /// `symbolTableIsHidden` is true if this symbol table is known to be
75 /// unaccessible from operations in its parent regions.
computeLiveness(Operation * symbolTableOp,SymbolTableCollection & symbolTable,bool symbolTableIsHidden,DenseSet<Operation * > & liveSymbols)76 LogicalResult SymbolDCE::computeLiveness(Operation *symbolTableOp,
77                                          SymbolTableCollection &symbolTable,
78                                          bool symbolTableIsHidden,
79                                          DenseSet<Operation *> &liveSymbols) {
80   // A worklist of live operations to propagate uses from.
81   SmallVector<Operation *, 16> worklist;
82 
83   // Walk the symbols within the current symbol table, marking the symbols that
84   // are known to be live.
85   for (auto &block : symbolTableOp->getRegion(0)) {
86     // Add all non-symbols or symbols that can't be discarded.
87     for (Operation &op : block.without_terminator()) {
88       SymbolOpInterface symbol = dyn_cast<SymbolOpInterface>(&op);
89       if (!symbol) {
90         worklist.push_back(&op);
91         continue;
92       }
93       bool isDiscardable = (symbolTableIsHidden || symbol.isPrivate()) &&
94                            symbol.canDiscardOnUseEmpty();
95       if (!isDiscardable && liveSymbols.insert(&op).second)
96         worklist.push_back(&op);
97     }
98   }
99 
100   // Process the set of symbols that were known to be live, adding new symbols
101   // that are referenced within.
102   while (!worklist.empty()) {
103     Operation *op = worklist.pop_back_val();
104 
105     // If this is a symbol table, recursively compute its liveness.
106     if (op->hasTrait<OpTrait::SymbolTable>()) {
107       // The internal symbol table is hidden if the parent is, if its not a
108       // symbol, or if it is a private symbol.
109       SymbolOpInterface symbol = dyn_cast<SymbolOpInterface>(op);
110       bool symIsHidden = symbolTableIsHidden || !symbol || symbol.isPrivate();
111       if (failed(computeLiveness(op, symbolTable, symIsHidden, liveSymbols)))
112         return failure();
113     }
114 
115     // Collect the uses held by this operation.
116     Optional<SymbolTable::UseRange> uses = SymbolTable::getSymbolUses(op);
117     if (!uses) {
118       return op->emitError()
119              << "operation contains potentially unknown symbol table, "
120                 "meaning that we can't reliable compute symbol uses";
121     }
122 
123     SmallVector<Operation *, 4> resolvedSymbols;
124     for (const SymbolTable::SymbolUse &use : *uses) {
125       // Lookup the symbols referenced by this use.
126       resolvedSymbols.clear();
127       if (failed(symbolTable.lookupSymbolIn(
128               op->getParentOp(), use.getSymbolRef(), resolvedSymbols))) {
129         return use.getUser()->emitError()
130                << "unable to resolve reference to symbol "
131                << use.getSymbolRef();
132       }
133 
134       // Mark each of the resolved symbols as live.
135       for (Operation *resolvedSymbol : resolvedSymbols)
136         if (liveSymbols.insert(resolvedSymbol).second)
137           worklist.push_back(resolvedSymbol);
138     }
139   }
140 
141   return success();
142 }
143 
createSymbolDCEPass()144 std::unique_ptr<Pass> mlir::createSymbolDCEPass() {
145   return std::make_unique<SymbolDCE>();
146 }
147