1 //===- FoldUtils.cpp ---- Fold Utilities ----------------------------------===// 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 various operation fold utilities. These utilities are 10 // intended to be used by passes to unify and simply their logic. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "mlir/Transforms/FoldUtils.h" 15 16 #include "mlir/Dialect/StandardOps/IR/Ops.h" 17 #include "mlir/IR/Builders.h" 18 #include "mlir/IR/Matchers.h" 19 #include "mlir/IR/Operation.h" 20 21 using namespace mlir; 22 23 /// Given an operation, find the parent region that folded constants should be 24 /// inserted into. 25 static Region *getInsertionRegion( 26 DialectInterfaceCollection<OpFolderDialectInterface> &interfaces, 27 Block *insertionBlock) { 28 while (Region *region = insertionBlock->getParent()) { 29 // Insert in this region for any of the following scenarios: 30 // * The parent is unregistered, or is known to be isolated from above. 31 // * The parent is a top-level operation. 32 auto *parentOp = region->getParentOp(); 33 if (!parentOp->isRegistered() || parentOp->isKnownIsolatedFromAbove() || 34 !parentOp->getBlock()) 35 return region; 36 37 // Otherwise, check if this region is a desired insertion region. 38 auto *interface = interfaces.getInterfaceFor(parentOp); 39 if (LLVM_UNLIKELY(interface && interface->shouldMaterializeInto(region))) 40 return region; 41 42 // Traverse up the parent looking for an insertion region. 43 insertionBlock = parentOp->getBlock(); 44 } 45 llvm_unreachable("expected valid insertion region"); 46 } 47 48 /// A utility function used to materialize a constant for a given attribute and 49 /// type. On success, a valid constant value is returned. Otherwise, null is 50 /// returned 51 static Operation *materializeConstant(Dialect *dialect, OpBuilder &builder, 52 Attribute value, Type type, 53 Location loc) { 54 auto insertPt = builder.getInsertionPoint(); 55 (void)insertPt; 56 57 // Ask the dialect to materialize a constant operation for this value. 58 if (auto *constOp = dialect->materializeConstant(builder, value, type, loc)) { 59 assert(insertPt == builder.getInsertionPoint()); 60 assert(matchPattern(constOp, m_Constant())); 61 return constOp; 62 } 63 64 // If the dialect is unable to materialize a constant, check to see if the 65 // standard constant can be used. 66 if (ConstantOp::isBuildableWith(value, type)) 67 return builder.create<ConstantOp>(loc, type, value); 68 return nullptr; 69 } 70 71 //===----------------------------------------------------------------------===// 72 // OperationFolder 73 //===----------------------------------------------------------------------===// 74 75 LogicalResult OperationFolder::tryToFold( 76 Operation *op, function_ref<void(Operation *)> processGeneratedConstants, 77 function_ref<void(Operation *)> preReplaceAction, bool *inPlaceUpdate) { 78 if (inPlaceUpdate) 79 *inPlaceUpdate = false; 80 81 // If this is a unique'd constant, return failure as we know that it has 82 // already been folded. 83 if (referencedDialects.count(op)) 84 return failure(); 85 86 // Try to fold the operation. 87 SmallVector<Value, 8> results; 88 OpBuilder builder(op); 89 if (failed(tryToFold(builder, op, results, processGeneratedConstants))) 90 return failure(); 91 92 // Check to see if the operation was just updated in place. 93 if (results.empty()) { 94 if (inPlaceUpdate) 95 *inPlaceUpdate = true; 96 return success(); 97 } 98 99 // Constant folding succeeded. We will start replacing this op's uses and 100 // erase this op. Invoke the callback provided by the caller to perform any 101 // pre-replacement action. 102 if (preReplaceAction) 103 preReplaceAction(op); 104 105 // Replace all of the result values and erase the operation. 106 for (unsigned i = 0, e = results.size(); i != e; ++i) 107 op->getResult(i).replaceAllUsesWith(results[i]); 108 op->erase(); 109 return success(); 110 } 111 112 /// Notifies that the given constant `op` should be remove from this 113 /// OperationFolder's internal bookkeeping. 114 void OperationFolder::notifyRemoval(Operation *op) { 115 // Check to see if this operation is uniqued within the folder. 116 auto it = referencedDialects.find(op); 117 if (it == referencedDialects.end()) 118 return; 119 120 // Get the constant value for this operation, this is the value that was used 121 // to unique the operation internally. 122 Attribute constValue; 123 matchPattern(op, m_Constant(&constValue)); 124 assert(constValue); 125 126 // Get the constant map that this operation was uniqued in. 127 auto &uniquedConstants = 128 foldScopes[getInsertionRegion(interfaces, op->getBlock())]; 129 130 // Erase all of the references to this operation. 131 auto type = op->getResult(0).getType(); 132 for (auto *dialect : it->second) 133 uniquedConstants.erase(std::make_tuple(dialect, constValue, type)); 134 referencedDialects.erase(it); 135 } 136 137 /// Clear out any constants cached inside of the folder. 138 void OperationFolder::clear() { 139 foldScopes.clear(); 140 referencedDialects.clear(); 141 } 142 143 /// Get or create a constant using the given builder. On success this returns 144 /// the constant operation, nullptr otherwise. 145 Value OperationFolder::getOrCreateConstant(OpBuilder &builder, Dialect *dialect, 146 Attribute value, Type type, 147 Location loc) { 148 OpBuilder::InsertionGuard foldGuard(builder); 149 150 // Use the builder insertion block to find an insertion point for the 151 // constant. 152 auto *insertRegion = 153 getInsertionRegion(interfaces, builder.getInsertionBlock()); 154 auto &entry = insertRegion->front(); 155 builder.setInsertionPoint(&entry, entry.begin()); 156 157 // Get the constant map for the insertion region of this operation. 158 auto &uniquedConstants = foldScopes[insertRegion]; 159 Operation *constOp = tryGetOrCreateConstant(uniquedConstants, dialect, 160 builder, value, type, loc); 161 return constOp ? constOp->getResult(0) : Value(); 162 } 163 164 /// Tries to perform folding on the given `op`. If successful, populates 165 /// `results` with the results of the folding. 166 LogicalResult OperationFolder::tryToFold( 167 OpBuilder &builder, Operation *op, SmallVectorImpl<Value> &results, 168 function_ref<void(Operation *)> processGeneratedConstants) { 169 SmallVector<Attribute, 8> operandConstants; 170 SmallVector<OpFoldResult, 8> foldResults; 171 172 // If this is a commutative operation, move constants to be trailing operands. 173 if (op->getNumOperands() >= 2 && op->isCommutative()) { 174 std::stable_partition( 175 op->getOpOperands().begin(), op->getOpOperands().end(), 176 [&](OpOperand &O) { return !matchPattern(O.get(), m_Constant()); }); 177 } 178 179 // Check to see if any operands to the operation is constant and whether 180 // the operation knows how to constant fold itself. 181 operandConstants.assign(op->getNumOperands(), Attribute()); 182 for (unsigned i = 0, e = op->getNumOperands(); i != e; ++i) 183 matchPattern(op->getOperand(i), m_Constant(&operandConstants[i])); 184 185 // Attempt to constant fold the operation. 186 if (failed(op->fold(operandConstants, foldResults))) 187 return failure(); 188 189 // Check to see if the operation was just updated in place. 190 if (foldResults.empty()) 191 return success(); 192 assert(foldResults.size() == op->getNumResults()); 193 194 // Create a builder to insert new operations into the entry block of the 195 // insertion region. 196 auto *insertRegion = 197 getInsertionRegion(interfaces, builder.getInsertionBlock()); 198 auto &entry = insertRegion->front(); 199 OpBuilder::InsertionGuard foldGuard(builder); 200 builder.setInsertionPoint(&entry, entry.begin()); 201 202 // Get the constant map for the insertion region of this operation. 203 auto &uniquedConstants = foldScopes[insertRegion]; 204 205 // Create the result constants and replace the results. 206 auto *dialect = op->getDialect(); 207 for (unsigned i = 0, e = op->getNumResults(); i != e; ++i) { 208 assert(!foldResults[i].isNull() && "expected valid OpFoldResult"); 209 210 // Check if the result was an SSA value. 211 if (auto repl = foldResults[i].dyn_cast<Value>()) { 212 results.emplace_back(repl); 213 continue; 214 } 215 216 // Check to see if there is a canonicalized version of this constant. 217 auto res = op->getResult(i); 218 Attribute attrRepl = foldResults[i].get<Attribute>(); 219 if (auto *constOp = 220 tryGetOrCreateConstant(uniquedConstants, dialect, builder, attrRepl, 221 res.getType(), op->getLoc())) { 222 results.push_back(constOp->getResult(0)); 223 continue; 224 } 225 // If materialization fails, cleanup any operations generated for the 226 // previous results and return failure. 227 for (Operation &op : llvm::make_early_inc_range( 228 llvm::make_range(entry.begin(), builder.getInsertionPoint()))) { 229 notifyRemoval(&op); 230 op.erase(); 231 } 232 return failure(); 233 } 234 235 // Process any newly generated operations. 236 if (processGeneratedConstants) { 237 for (auto i = entry.begin(), e = builder.getInsertionPoint(); i != e; ++i) 238 processGeneratedConstants(&*i); 239 } 240 241 return success(); 242 } 243 244 /// Try to get or create a new constant entry. On success this returns the 245 /// constant operation value, nullptr otherwise. 246 Operation *OperationFolder::tryGetOrCreateConstant( 247 ConstantMap &uniquedConstants, Dialect *dialect, OpBuilder &builder, 248 Attribute value, Type type, Location loc) { 249 // Check if an existing mapping already exists. 250 auto constKey = std::make_tuple(dialect, value, type); 251 auto *&constInst = uniquedConstants[constKey]; 252 if (constInst) 253 return constInst; 254 255 // If one doesn't exist, try to materialize one. 256 if (!(constInst = materializeConstant(dialect, builder, value, type, loc))) 257 return nullptr; 258 259 // Check to see if the generated constant is in the expected dialect. 260 auto *newDialect = constInst->getDialect(); 261 if (newDialect == dialect) { 262 referencedDialects[constInst].push_back(dialect); 263 return constInst; 264 } 265 266 // If it isn't, then we also need to make sure that the mapping for the new 267 // dialect is valid. 268 auto newKey = std::make_tuple(newDialect, value, type); 269 270 // If an existing operation in the new dialect already exists, delete the 271 // materialized operation in favor of the existing one. 272 if (auto *existingOp = uniquedConstants.lookup(newKey)) { 273 constInst->erase(); 274 referencedDialects[existingOp].push_back(dialect); 275 return constInst = existingOp; 276 } 277 278 // Otherwise, update the new dialect to the materialized operation. 279 referencedDialects[constInst].assign({dialect, newDialect}); 280 auto newIt = uniquedConstants.insert({newKey, constInst}); 281 return newIt.first->second; 282 } 283