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 * 26 getInsertionRegion(DialectInterfaceCollection<DialectFoldInterface> &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->mightHaveTrait<OpTrait::IsIsolatedFromAbove>() || 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 // TODO: To facilitate splitting the std dialect (PR48490), have a special 65 // case for falling back to std.constant. Eventually, we will have separate 66 // ops tensor.constant, int.constant, float.constant, etc. that live in their 67 // respective dialects, which will allow each dialect to implement the 68 // materializeConstant hook above. 69 // 70 // The special case is needed because in the interim state while we are 71 // splitting out those dialects from std, the std dialect depends on the 72 // tensor dialect, which makes it impossible for the tensor dialect to use 73 // std.constant (it would be a cyclic dependency) as part of its 74 // materializeConstant hook. 75 // 76 // If the dialect is unable to materialize a constant, check to see if the 77 // standard constant can be used. 78 if (ConstantOp::isBuildableWith(value, type)) 79 return builder.create<ConstantOp>(loc, type, value); 80 return nullptr; 81 } 82 83 //===----------------------------------------------------------------------===// 84 // OperationFolder 85 //===----------------------------------------------------------------------===// 86 87 /// Scan the specified region for constants that can be used in folding, 88 /// moving them to the entry block and adding them to our known-constants 89 /// table. 90 void OperationFolder::processExistingConstants(Region ®ion) { 91 if (region.empty()) 92 return; 93 94 // March the constant insertion point forward, moving all constants to the 95 // top of the block, but keeping them in their order of discovery. 96 Region *insertRegion = getInsertionRegion(interfaces, ®ion.front()); 97 auto &uniquedConstants = foldScopes[insertRegion]; 98 99 Block &insertBlock = insertRegion->front(); 100 Block::iterator constantIterator = insertBlock.begin(); 101 102 // Process each constant that we discover in this region. 103 auto processConstant = [&](Operation *op, Attribute value) { 104 // Check to see if we already have an instance of this constant. 105 Operation *&constOp = uniquedConstants[std::make_tuple( 106 op->getDialect(), value, op->getResult(0).getType())]; 107 108 // If we already have an instance of this constant, CSE/delete this one as 109 // we go. 110 if (constOp) { 111 if (constantIterator == Block::iterator(op)) 112 ++constantIterator; // Don't invalidate our iterator when scanning. 113 op->getResult(0).replaceAllUsesWith(constOp->getResult(0)); 114 op->erase(); 115 return; 116 } 117 118 // Otherwise, remember that we have this constant. 119 constOp = op; 120 referencedDialects[op].push_back(op->getDialect()); 121 122 // If the constant isn't already at the insertion point then move it up. 123 if (constantIterator == insertBlock.end() || &*constantIterator != op) 124 op->moveBefore(&insertBlock, constantIterator); 125 else 126 ++constantIterator; // It was pointing at the constant. 127 }; 128 129 SmallVector<Operation *> isolatedOps; 130 region.walk<WalkOrder::PreOrder>([&](Operation *op) { 131 // If this is a constant, process it. 132 Attribute value; 133 if (matchPattern(op, m_Constant(&value))) { 134 processConstant(op, value); 135 // We may have deleted the operation, don't check it for regions. 136 return WalkResult::advance(); 137 } 138 139 // If the operation has regions and is isolated, don't recurse into it. 140 if (op->getNumRegions() != 0) { 141 auto hasDifferentInsertRegion = [&](Region ®ion) { 142 return !region.empty() && 143 getInsertionRegion(interfaces, ®ion.front()) != insertRegion; 144 }; 145 if (llvm::any_of(op->getRegions(), hasDifferentInsertRegion)) { 146 isolatedOps.push_back(op); 147 return WalkResult::skip(); 148 } 149 } 150 151 // Otherwise keep going. 152 return WalkResult::advance(); 153 }); 154 155 // Process regions in any isolated ops separately. 156 for (Operation *isolated : isolatedOps) { 157 for (Region ®ion : isolated->getRegions()) 158 processExistingConstants(region); 159 } 160 } 161 162 LogicalResult OperationFolder::tryToFold( 163 Operation *op, function_ref<void(Operation *)> processGeneratedConstants, 164 function_ref<void(Operation *)> preReplaceAction, bool *inPlaceUpdate) { 165 if (inPlaceUpdate) 166 *inPlaceUpdate = false; 167 168 // If this is a unique'd constant, return failure as we know that it has 169 // already been folded. 170 if (referencedDialects.count(op)) 171 return failure(); 172 173 // Try to fold the operation. 174 SmallVector<Value, 8> results; 175 OpBuilder builder(op); 176 if (failed(tryToFold(builder, op, results, processGeneratedConstants))) 177 return failure(); 178 179 // Check to see if the operation was just updated in place. 180 if (results.empty()) { 181 if (inPlaceUpdate) 182 *inPlaceUpdate = true; 183 return success(); 184 } 185 186 // Constant folding succeeded. We will start replacing this op's uses and 187 // erase this op. Invoke the callback provided by the caller to perform any 188 // pre-replacement action. 189 if (preReplaceAction) 190 preReplaceAction(op); 191 192 // Replace all of the result values and erase the operation. 193 for (unsigned i = 0, e = results.size(); i != e; ++i) 194 op->getResult(i).replaceAllUsesWith(results[i]); 195 op->erase(); 196 return success(); 197 } 198 199 /// Notifies that the given constant `op` should be remove from this 200 /// OperationFolder's internal bookkeeping. 201 void OperationFolder::notifyRemoval(Operation *op) { 202 // Check to see if this operation is uniqued within the folder. 203 auto it = referencedDialects.find(op); 204 if (it == referencedDialects.end()) 205 return; 206 207 // Get the constant value for this operation, this is the value that was used 208 // to unique the operation internally. 209 Attribute constValue; 210 matchPattern(op, m_Constant(&constValue)); 211 assert(constValue); 212 213 // Get the constant map that this operation was uniqued in. 214 auto &uniquedConstants = 215 foldScopes[getInsertionRegion(interfaces, op->getBlock())]; 216 217 // Erase all of the references to this operation. 218 auto type = op->getResult(0).getType(); 219 for (auto *dialect : it->second) 220 uniquedConstants.erase(std::make_tuple(dialect, constValue, type)); 221 referencedDialects.erase(it); 222 } 223 224 /// Clear out any constants cached inside of the folder. 225 void OperationFolder::clear() { 226 foldScopes.clear(); 227 referencedDialects.clear(); 228 } 229 230 /// Get or create a constant using the given builder. On success this returns 231 /// the constant operation, nullptr otherwise. 232 Value OperationFolder::getOrCreateConstant(OpBuilder &builder, Dialect *dialect, 233 Attribute value, Type type, 234 Location loc) { 235 OpBuilder::InsertionGuard foldGuard(builder); 236 237 // Use the builder insertion block to find an insertion point for the 238 // constant. 239 auto *insertRegion = 240 getInsertionRegion(interfaces, builder.getInsertionBlock()); 241 auto &entry = insertRegion->front(); 242 builder.setInsertionPoint(&entry, entry.begin()); 243 244 // Get the constant map for the insertion region of this operation. 245 auto &uniquedConstants = foldScopes[insertRegion]; 246 Operation *constOp = tryGetOrCreateConstant(uniquedConstants, dialect, 247 builder, value, type, loc); 248 return constOp ? constOp->getResult(0) : Value(); 249 } 250 251 /// Tries to perform folding on the given `op`. If successful, populates 252 /// `results` with the results of the folding. 253 LogicalResult OperationFolder::tryToFold( 254 OpBuilder &builder, Operation *op, SmallVectorImpl<Value> &results, 255 function_ref<void(Operation *)> processGeneratedConstants) { 256 SmallVector<Attribute, 8> operandConstants; 257 SmallVector<OpFoldResult, 8> foldResults; 258 259 // If this is a commutative operation, move constants to be trailing operands. 260 if (op->getNumOperands() >= 2 && op->hasTrait<OpTrait::IsCommutative>()) { 261 std::stable_partition( 262 op->getOpOperands().begin(), op->getOpOperands().end(), 263 [&](OpOperand &O) { return !matchPattern(O.get(), m_Constant()); }); 264 } 265 266 // Check to see if any operands to the operation is constant and whether 267 // the operation knows how to constant fold itself. 268 operandConstants.assign(op->getNumOperands(), Attribute()); 269 for (unsigned i = 0, e = op->getNumOperands(); i != e; ++i) 270 matchPattern(op->getOperand(i), m_Constant(&operandConstants[i])); 271 272 // Attempt to constant fold the operation. 273 if (failed(op->fold(operandConstants, foldResults))) 274 return failure(); 275 276 // Check to see if the operation was just updated in place. 277 if (foldResults.empty()) 278 return success(); 279 assert(foldResults.size() == op->getNumResults()); 280 281 // Create a builder to insert new operations into the entry block of the 282 // insertion region. 283 auto *insertRegion = 284 getInsertionRegion(interfaces, builder.getInsertionBlock()); 285 auto &entry = insertRegion->front(); 286 OpBuilder::InsertionGuard foldGuard(builder); 287 builder.setInsertionPoint(&entry, entry.begin()); 288 289 // Get the constant map for the insertion region of this operation. 290 auto &uniquedConstants = foldScopes[insertRegion]; 291 292 // Create the result constants and replace the results. 293 auto *dialect = op->getDialect(); 294 for (unsigned i = 0, e = op->getNumResults(); i != e; ++i) { 295 assert(!foldResults[i].isNull() && "expected valid OpFoldResult"); 296 297 // Check if the result was an SSA value. 298 if (auto repl = foldResults[i].dyn_cast<Value>()) { 299 if (repl.getType() != op->getResult(i).getType()) 300 return failure(); 301 results.emplace_back(repl); 302 continue; 303 } 304 305 // Check to see if there is a canonicalized version of this constant. 306 auto res = op->getResult(i); 307 Attribute attrRepl = foldResults[i].get<Attribute>(); 308 if (auto *constOp = 309 tryGetOrCreateConstant(uniquedConstants, dialect, builder, attrRepl, 310 res.getType(), op->getLoc())) { 311 results.push_back(constOp->getResult(0)); 312 continue; 313 } 314 // If materialization fails, cleanup any operations generated for the 315 // previous results and return failure. 316 for (Operation &op : llvm::make_early_inc_range( 317 llvm::make_range(entry.begin(), builder.getInsertionPoint()))) { 318 notifyRemoval(&op); 319 op.erase(); 320 } 321 return failure(); 322 } 323 324 // Process any newly generated operations. 325 if (processGeneratedConstants) { 326 for (auto i = entry.begin(), e = builder.getInsertionPoint(); i != e; ++i) 327 processGeneratedConstants(&*i); 328 } 329 330 return success(); 331 } 332 333 /// Try to get or create a new constant entry. On success this returns the 334 /// constant operation value, nullptr otherwise. 335 Operation *OperationFolder::tryGetOrCreateConstant( 336 ConstantMap &uniquedConstants, Dialect *dialect, OpBuilder &builder, 337 Attribute value, Type type, Location loc) { 338 // Check if an existing mapping already exists. 339 auto constKey = std::make_tuple(dialect, value, type); 340 auto *&constOp = uniquedConstants[constKey]; 341 if (constOp) 342 return constOp; 343 344 // If one doesn't exist, try to materialize one. 345 if (!(constOp = materializeConstant(dialect, builder, value, type, loc))) 346 return nullptr; 347 348 // Check to see if the generated constant is in the expected dialect. 349 auto *newDialect = constOp->getDialect(); 350 if (newDialect == dialect) { 351 referencedDialects[constOp].push_back(dialect); 352 return constOp; 353 } 354 355 // If it isn't, then we also need to make sure that the mapping for the new 356 // dialect is valid. 357 auto newKey = std::make_tuple(newDialect, value, type); 358 359 // If an existing operation in the new dialect already exists, delete the 360 // materialized operation in favor of the existing one. 361 if (auto *existingOp = uniquedConstants.lookup(newKey)) { 362 constOp->erase(); 363 referencedDialects[existingOp].push_back(dialect); 364 return constOp = existingOp; 365 } 366 367 // Otherwise, update the new dialect to the materialized operation. 368 referencedDialects[constOp].assign({dialect, newDialect}); 369 auto newIt = uniquedConstants.insert({newKey, constOp}); 370 return newIt.first->second; 371 } 372