1 //===- CSE.cpp - Common Sub-expression Elimination ------------------------===// 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 transformation pass performs a simple common sub-expression elimination 10 // algorithm on operations within a region. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "PassDetail.h" 15 #include "mlir/IR/Dominance.h" 16 #include "mlir/Pass/Pass.h" 17 #include "mlir/Transforms/Passes.h" 18 #include "llvm/ADT/DenseMapInfo.h" 19 #include "llvm/ADT/Hashing.h" 20 #include "llvm/ADT/ScopedHashTable.h" 21 #include "llvm/Support/Allocator.h" 22 #include "llvm/Support/RecyclingAllocator.h" 23 #include <deque> 24 25 using namespace mlir; 26 27 namespace { 28 struct SimpleOperationInfo : public llvm::DenseMapInfo<Operation *> { 29 static unsigned getHashValue(const Operation *opC) { 30 return OperationEquivalence::computeHash( 31 const_cast<Operation *>(opC), 32 /*hashOperands=*/OperationEquivalence::directHashValue, 33 /*hashResults=*/OperationEquivalence::ignoreHashValue, 34 OperationEquivalence::IgnoreLocations); 35 } 36 static bool isEqual(const Operation *lhsC, const Operation *rhsC) { 37 auto *lhs = const_cast<Operation *>(lhsC); 38 auto *rhs = const_cast<Operation *>(rhsC); 39 if (lhs == rhs) 40 return true; 41 if (lhs == getTombstoneKey() || lhs == getEmptyKey() || 42 rhs == getTombstoneKey() || rhs == getEmptyKey()) 43 return false; 44 return OperationEquivalence::isEquivalentTo( 45 const_cast<Operation *>(lhsC), const_cast<Operation *>(rhsC), 46 /*mapOperands=*/OperationEquivalence::exactValueMatch, 47 /*mapResults=*/OperationEquivalence::ignoreValueEquivalence, 48 OperationEquivalence::IgnoreLocations); 49 } 50 }; 51 } // namespace 52 53 namespace { 54 /// Simple common sub-expression elimination. 55 struct CSE : public CSEBase<CSE> { 56 /// Shared implementation of operation elimination and scoped map definitions. 57 using AllocatorTy = llvm::RecyclingAllocator< 58 llvm::BumpPtrAllocator, 59 llvm::ScopedHashTableVal<Operation *, Operation *>>; 60 using ScopedMapTy = llvm::ScopedHashTable<Operation *, Operation *, 61 SimpleOperationInfo, AllocatorTy>; 62 63 /// Represents a single entry in the depth first traversal of a CFG. 64 struct CFGStackNode { 65 CFGStackNode(ScopedMapTy &knownValues, DominanceInfoNode *node) 66 : scope(knownValues), node(node), childIterator(node->begin()) {} 67 68 /// Scope for the known values. 69 ScopedMapTy::ScopeTy scope; 70 71 DominanceInfoNode *node; 72 DominanceInfoNode::const_iterator childIterator; 73 74 /// If this node has been fully processed yet or not. 75 bool processed = false; 76 }; 77 78 /// Attempt to eliminate a redundant operation. Returns success if the 79 /// operation was marked for removal, failure otherwise. 80 LogicalResult simplifyOperation(ScopedMapTy &knownValues, Operation *op, 81 bool hasSSADominance); 82 void simplifyBlock(ScopedMapTy &knownValues, Block *bb, bool hasSSADominance); 83 void simplifyRegion(ScopedMapTy &knownValues, Region ®ion); 84 85 void runOnOperation() override; 86 87 private: 88 /// Operations marked as dead and to be erased. 89 std::vector<Operation *> opsToErase; 90 DominanceInfo *domInfo = nullptr; 91 }; 92 } // namespace 93 94 /// Attempt to eliminate a redundant operation. 95 LogicalResult CSE::simplifyOperation(ScopedMapTy &knownValues, Operation *op, 96 bool hasSSADominance) { 97 // Don't simplify terminator operations. 98 if (op->hasTrait<OpTrait::IsTerminator>()) 99 return failure(); 100 101 // If the operation is already trivially dead just add it to the erase list. 102 if (isOpTriviallyDead(op)) { 103 opsToErase.push_back(op); 104 ++numDCE; 105 return success(); 106 } 107 108 // Don't simplify operations with nested blocks. We don't currently model 109 // equality comparisons correctly among other things. It is also unclear 110 // whether we would want to CSE such operations. 111 if (op->getNumRegions() != 0) 112 return failure(); 113 114 // TODO: We currently only eliminate non side-effecting 115 // operations. 116 if (!MemoryEffectOpInterface::hasNoEffect(op)) 117 return failure(); 118 119 // Look for an existing definition for the operation. 120 if (auto *existing = knownValues.lookup(op)) { 121 122 // If we find one then replace all uses of the current operation with the 123 // existing one and mark it for deletion. We can only replace an operand in 124 // an operation if it has not been visited yet. 125 if (hasSSADominance) { 126 // If the region has SSA dominance, then we are guaranteed to have not 127 // visited any use of the current operation. 128 op->replaceAllUsesWith(existing); 129 opsToErase.push_back(op); 130 } else { 131 // When the region does not have SSA dominance, we need to check if we 132 // have visited a use before replacing any use. 133 for (auto it : llvm::zip(op->getResults(), existing->getResults())) { 134 std::get<0>(it).replaceUsesWithIf( 135 std::get<1>(it), [&](OpOperand &operand) { 136 return !knownValues.count(operand.getOwner()); 137 }); 138 } 139 140 // There may be some remaining uses of the operation. 141 if (op->use_empty()) 142 opsToErase.push_back(op); 143 } 144 145 // If the existing operation has an unknown location and the current 146 // operation doesn't, then set the existing op's location to that of the 147 // current op. 148 if (existing->getLoc().isa<UnknownLoc>() && 149 !op->getLoc().isa<UnknownLoc>()) { 150 existing->setLoc(op->getLoc()); 151 } 152 153 ++numCSE; 154 return success(); 155 } 156 157 // Otherwise, we add this operation to the known values map. 158 knownValues.insert(op, op); 159 return failure(); 160 } 161 162 void CSE::simplifyBlock(ScopedMapTy &knownValues, Block *bb, 163 bool hasSSADominance) { 164 for (auto &op : *bb) { 165 // If the operation is simplified, we don't process any held regions. 166 if (succeeded(simplifyOperation(knownValues, &op, hasSSADominance))) 167 continue; 168 169 // Most operations don't have regions, so fast path that case. 170 if (op.getNumRegions() == 0) 171 continue; 172 173 // If this operation is isolated above, we can't process nested regions with 174 // the given 'knownValues' map. This would cause the insertion of implicit 175 // captures in explicit capture only regions. 176 if (op.mightHaveTrait<OpTrait::IsIsolatedFromAbove>()) { 177 ScopedMapTy nestedKnownValues; 178 for (auto ®ion : op.getRegions()) 179 simplifyRegion(nestedKnownValues, region); 180 continue; 181 } 182 183 // Otherwise, process nested regions normally. 184 for (auto ®ion : op.getRegions()) 185 simplifyRegion(knownValues, region); 186 } 187 } 188 189 void CSE::simplifyRegion(ScopedMapTy &knownValues, Region ®ion) { 190 // If the region is empty there is nothing to do. 191 if (region.empty()) 192 return; 193 194 bool hasSSADominance = domInfo->hasSSADominance(®ion); 195 196 // If the region only contains one block, then simplify it directly. 197 if (region.hasOneBlock()) { 198 ScopedMapTy::ScopeTy scope(knownValues); 199 simplifyBlock(knownValues, ®ion.front(), hasSSADominance); 200 return; 201 } 202 203 // If the region does not have dominanceInfo, then skip it. 204 // TODO: Regions without SSA dominance should define a different 205 // traversal order which is appropriate and can be used here. 206 if (!hasSSADominance) 207 return; 208 209 // Note, deque is being used here because there was significant performance 210 // gains over vector when the container becomes very large due to the 211 // specific access patterns. If/when these performance issues are no 212 // longer a problem we can change this to vector. For more information see 213 // the llvm mailing list discussion on this: 214 // http://lists.llvm.org/pipermail/llvm-commits/Week-of-Mon-20120116/135228.html 215 std::deque<std::unique_ptr<CFGStackNode>> stack; 216 217 // Process the nodes of the dom tree for this region. 218 stack.emplace_back(std::make_unique<CFGStackNode>( 219 knownValues, domInfo->getRootNode(®ion))); 220 221 while (!stack.empty()) { 222 auto ¤tNode = stack.back(); 223 224 // Check to see if we need to process this node. 225 if (!currentNode->processed) { 226 currentNode->processed = true; 227 simplifyBlock(knownValues, currentNode->node->getBlock(), 228 hasSSADominance); 229 } 230 231 // Otherwise, check to see if we need to process a child node. 232 if (currentNode->childIterator != currentNode->node->end()) { 233 auto *childNode = *(currentNode->childIterator++); 234 stack.emplace_back( 235 std::make_unique<CFGStackNode>(knownValues, childNode)); 236 } else { 237 // Finally, if the node and all of its children have been processed 238 // then we delete the node. 239 stack.pop_back(); 240 } 241 } 242 } 243 244 void CSE::runOnOperation() { 245 /// A scoped hash table of defining operations within a region. 246 ScopedMapTy knownValues; 247 248 domInfo = &getAnalysis<DominanceInfo>(); 249 Operation *rootOp = getOperation(); 250 251 for (auto ®ion : rootOp->getRegions()) 252 simplifyRegion(knownValues, region); 253 254 // If no operations were erased, then we mark all analyses as preserved. 255 if (opsToErase.empty()) 256 return markAllAnalysesPreserved(); 257 258 /// Erase any operations that were marked as dead during simplification. 259 for (auto *op : opsToErase) 260 op->erase(); 261 opsToErase.clear(); 262 263 // We currently don't remove region operations, so mark dominance as 264 // preserved. 265 markAnalysesPreserved<DominanceInfo, PostDominanceInfo>(); 266 domInfo = nullptr; 267 } 268 269 std::unique_ptr<Pass> mlir::createCSEPass() { return std::make_unique<CSE>(); } 270