1 //===- DialectConversion.cpp - MLIR dialect conversion generic pass -------===// 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 #include "mlir/Transforms/DialectConversion.h" 10 #include "mlir/IR/Block.h" 11 #include "mlir/IR/BlockAndValueMapping.h" 12 #include "mlir/IR/Builders.h" 13 #include "mlir/IR/BuiltinOps.h" 14 #include "mlir/IR/FunctionSupport.h" 15 #include "mlir/Rewrite/PatternApplicator.h" 16 #include "mlir/Transforms/Utils.h" 17 #include "llvm/ADT/SetVector.h" 18 #include "llvm/ADT/SmallPtrSet.h" 19 #include "llvm/Support/Debug.h" 20 #include "llvm/Support/FormatVariadic.h" 21 #include "llvm/Support/SaveAndRestore.h" 22 #include "llvm/Support/ScopedPrinter.h" 23 24 using namespace mlir; 25 using namespace mlir::detail; 26 27 #define DEBUG_TYPE "dialect-conversion" 28 29 /// Recursively collect all of the operations to convert from within 'region'. 30 /// If 'target' is nonnull, operations that are recursively legal have their 31 /// regions pre-filtered to avoid considering them for legalization. 32 static LogicalResult 33 computeConversionSet(iterator_range<Region::iterator> region, 34 Location regionLoc, std::vector<Operation *> &toConvert, 35 ConversionTarget *target = nullptr) { 36 if (llvm::empty(region)) 37 return success(); 38 39 // Traverse starting from the entry block. 40 SmallVector<Block *, 16> worklist(1, &*region.begin()); 41 DenseSet<Block *> visitedBlocks; 42 visitedBlocks.insert(worklist.front()); 43 while (!worklist.empty()) { 44 Block *block = worklist.pop_back_val(); 45 46 // Compute the conversion set of each of the nested operations. 47 for (Operation &op : *block) { 48 toConvert.emplace_back(&op); 49 50 // Don't check this operation's children for conversion if the operation 51 // is recursively legal. 52 auto legalityInfo = target ? target->isLegal(&op) 53 : Optional<ConversionTarget::LegalOpDetails>(); 54 if (legalityInfo && legalityInfo->isRecursivelyLegal) 55 continue; 56 for (auto ®ion : op.getRegions()) { 57 if (failed(computeConversionSet(region.getBlocks(), region.getLoc(), 58 toConvert, target))) 59 return failure(); 60 } 61 } 62 63 // Recurse to children that haven't been visited. 64 for (Block *succ : block->getSuccessors()) 65 if (visitedBlocks.insert(succ).second) 66 worklist.push_back(succ); 67 } 68 69 // Check that all blocks in the region were visited. 70 if (llvm::any_of(llvm::drop_begin(region, 1), 71 [&](Block &block) { return !visitedBlocks.count(&block); })) 72 return emitError(regionLoc, "unreachable blocks were not converted"); 73 return success(); 74 } 75 76 /// A utility function to log a successful result for the given reason. 77 template <typename... Args> 78 static void logSuccess(llvm::ScopedPrinter &os, StringRef fmt, Args &&...args) { 79 LLVM_DEBUG({ 80 os.unindent(); 81 os.startLine() << "} -> SUCCESS"; 82 if (!fmt.empty()) 83 os.getOStream() << " : " 84 << llvm::formatv(fmt.data(), std::forward<Args>(args)...); 85 os.getOStream() << "\n"; 86 }); 87 } 88 89 /// A utility function to log a failure result for the given reason. 90 template <typename... Args> 91 static void logFailure(llvm::ScopedPrinter &os, StringRef fmt, Args &&...args) { 92 LLVM_DEBUG({ 93 os.unindent(); 94 os.startLine() << "} -> FAILURE : " 95 << llvm::formatv(fmt.data(), std::forward<Args>(args)...) 96 << "\n"; 97 }); 98 } 99 100 //===----------------------------------------------------------------------===// 101 // ConversionValueMapping 102 //===----------------------------------------------------------------------===// 103 104 namespace { 105 /// This class wraps a BlockAndValueMapping to provide recursive lookup 106 /// functionality, i.e. we will traverse if the mapped value also has a mapping. 107 struct ConversionValueMapping { 108 /// Lookup a mapped value within the map. If a mapping for the provided value 109 /// does not exist then return the provided value. If `desiredType` is 110 /// non-null, returns the most recently mapped value with that type. If an 111 /// operand of that type does not exist, defaults to normal behavior. 112 Value lookupOrDefault(Value from, Type desiredType = nullptr) const; 113 114 /// Lookup a mapped value within the map, or return null if a mapping does not 115 /// exist. If a mapping exists, this follows the same behavior of 116 /// `lookupOrDefault`. 117 Value lookupOrNull(Value from) const; 118 119 /// Map a value to the one provided. 120 void map(Value oldVal, Value newVal) { mapping.map(oldVal, newVal); } 121 122 /// Drop the last mapping for the given value. 123 void erase(Value value) { mapping.erase(value); } 124 125 /// Returns the inverse raw value mapping (without recursive query support). 126 BlockAndValueMapping getInverse() const { return mapping.getInverse(); } 127 128 private: 129 /// Current value mappings. 130 BlockAndValueMapping mapping; 131 }; 132 } // end anonymous namespace 133 134 Value ConversionValueMapping::lookupOrDefault(Value from, 135 Type desiredType) const { 136 // If there was no desired type, simply find the leaf value. 137 if (!desiredType) { 138 // If this value had a valid mapping, unmap that value as well in the case 139 // that it was also replaced. 140 while (auto mappedValue = mapping.lookupOrNull(from)) 141 from = mappedValue; 142 return from; 143 } 144 145 // Otherwise, try to find the deepest value that has the desired type. 146 Value desiredValue; 147 do { 148 if (from.getType() == desiredType) 149 desiredValue = from; 150 151 Value mappedValue = mapping.lookupOrNull(from); 152 if (!mappedValue) 153 break; 154 from = mappedValue; 155 } while (true); 156 157 // If the desired value was found use it, otherwise default to the leaf value. 158 return desiredValue ? desiredValue : from; 159 } 160 161 Value ConversionValueMapping::lookupOrNull(Value from) const { 162 Value result = lookupOrDefault(from); 163 return result == from ? nullptr : result; 164 } 165 166 //===----------------------------------------------------------------------===// 167 // ArgConverter 168 //===----------------------------------------------------------------------===// 169 namespace { 170 /// This class provides a simple interface for converting the types of block 171 /// arguments. This is done by creating a new block that contains the new legal 172 /// types and extracting the block that contains the old illegal types to allow 173 /// for undoing pending rewrites in the case of failure. 174 struct ArgConverter { 175 ArgConverter(PatternRewriter &rewriter) : rewriter(rewriter) {} 176 177 /// This structure contains the information pertaining to an argument that has 178 /// been converted. 179 struct ConvertedArgInfo { 180 ConvertedArgInfo(unsigned newArgIdx, unsigned newArgSize, 181 Value castValue = nullptr) 182 : newArgIdx(newArgIdx), newArgSize(newArgSize), castValue(castValue) {} 183 184 /// The start index of in the new argument list that contains arguments that 185 /// replace the original. 186 unsigned newArgIdx; 187 188 /// The number of arguments that replaced the original argument. 189 unsigned newArgSize; 190 191 /// The cast value that was created to cast from the new arguments to the 192 /// old. This only used if 'newArgSize' > 1. 193 Value castValue; 194 }; 195 196 /// This structure contains information pertaining to a block that has had its 197 /// signature converted. 198 struct ConvertedBlockInfo { 199 ConvertedBlockInfo(Block *origBlock, TypeConverter &converter) 200 : origBlock(origBlock), converter(&converter) {} 201 202 /// The original block that was requested to have its signature converted. 203 Block *origBlock; 204 205 /// The conversion information for each of the arguments. The information is 206 /// None if the argument was dropped during conversion. 207 SmallVector<Optional<ConvertedArgInfo>, 1> argInfo; 208 209 /// The type converter used to convert the arguments. 210 TypeConverter *converter; 211 }; 212 213 /// Return if the signature of the given block has already been converted. 214 bool hasBeenConverted(Block *block) const { 215 return conversionInfo.count(block) || convertedBlocks.count(block); 216 } 217 218 /// Set the type converter to use for the given region. 219 void setConverter(Region *region, TypeConverter *typeConverter) { 220 assert(typeConverter && "expected valid type converter"); 221 regionToConverter[region] = typeConverter; 222 } 223 224 /// Return the type converter to use for the given region, or null if there 225 /// isn't one. 226 TypeConverter *getConverter(Region *region) { 227 return regionToConverter.lookup(region); 228 } 229 230 //===--------------------------------------------------------------------===// 231 // Rewrite Application 232 //===--------------------------------------------------------------------===// 233 234 /// Erase any rewrites registered for the blocks within the given operation 235 /// which is about to be removed. This merely drops the rewrites without 236 /// undoing them. 237 void notifyOpRemoved(Operation *op); 238 239 /// Cleanup and undo any generated conversions for the arguments of block. 240 /// This method replaces the new block with the original, reverting the IR to 241 /// its original state. 242 void discardRewrites(Block *block); 243 244 /// Fully replace uses of the old arguments with the new. 245 void applyRewrites(ConversionValueMapping &mapping); 246 247 /// Materialize any necessary conversions for converted arguments that have 248 /// live users, using the provided `findLiveUser` to search for a user that 249 /// survives the conversion process. 250 LogicalResult 251 materializeLiveConversions(ConversionValueMapping &mapping, 252 OpBuilder &builder, 253 function_ref<Operation *(Value)> findLiveUser); 254 255 //===--------------------------------------------------------------------===// 256 // Conversion 257 //===--------------------------------------------------------------------===// 258 259 /// Attempt to convert the signature of the given block, if successful a new 260 /// block is returned containing the new arguments. Returns `block` if it did 261 /// not require conversion. 262 FailureOr<Block *> 263 convertSignature(Block *block, TypeConverter &converter, 264 ConversionValueMapping &mapping, 265 SmallVectorImpl<BlockArgument> &argReplacements); 266 267 /// Apply the given signature conversion on the given block. The new block 268 /// containing the updated signature is returned. If no conversions were 269 /// necessary, e.g. if the block has no arguments, `block` is returned. 270 /// `converter` is used to generate any necessary cast operations that 271 /// translate between the origin argument types and those specified in the 272 /// signature conversion. 273 Block *applySignatureConversion( 274 Block *block, TypeConverter &converter, 275 TypeConverter::SignatureConversion &signatureConversion, 276 ConversionValueMapping &mapping, 277 SmallVectorImpl<BlockArgument> &argReplacements); 278 279 /// Insert a new conversion into the cache. 280 void insertConversion(Block *newBlock, ConvertedBlockInfo &&info); 281 282 /// A collection of blocks that have had their arguments converted. This is a 283 /// map from the new replacement block, back to the original block. 284 llvm::MapVector<Block *, ConvertedBlockInfo> conversionInfo; 285 286 /// The set of original blocks that were converted. 287 DenseSet<Block *> convertedBlocks; 288 289 /// A mapping from valid regions, to those containing the original blocks of a 290 /// conversion. 291 DenseMap<Region *, std::unique_ptr<Region>> regionMapping; 292 293 /// A mapping of regions to type converters that should be used when 294 /// converting the arguments of blocks within that region. 295 DenseMap<Region *, TypeConverter *> regionToConverter; 296 297 /// The pattern rewriter to use when materializing conversions. 298 PatternRewriter &rewriter; 299 }; 300 } // end anonymous namespace 301 302 //===----------------------------------------------------------------------===// 303 // Rewrite Application 304 305 void ArgConverter::notifyOpRemoved(Operation *op) { 306 if (conversionInfo.empty()) 307 return; 308 309 for (Region ®ion : op->getRegions()) { 310 for (Block &block : region) { 311 // Drop any rewrites from within. 312 for (Operation &nestedOp : block) 313 if (nestedOp.getNumRegions()) 314 notifyOpRemoved(&nestedOp); 315 316 // Check if this block was converted. 317 auto it = conversionInfo.find(&block); 318 if (it == conversionInfo.end()) 319 continue; 320 321 // Drop all uses of the original arguments and delete the original block. 322 Block *origBlock = it->second.origBlock; 323 for (BlockArgument arg : origBlock->getArguments()) 324 arg.dropAllUses(); 325 conversionInfo.erase(it); 326 } 327 } 328 } 329 330 void ArgConverter::discardRewrites(Block *block) { 331 auto it = conversionInfo.find(block); 332 if (it == conversionInfo.end()) 333 return; 334 Block *origBlock = it->second.origBlock; 335 336 // Drop all uses of the new block arguments and replace uses of the new block. 337 for (int i = block->getNumArguments() - 1; i >= 0; --i) 338 block->getArgument(i).dropAllUses(); 339 block->replaceAllUsesWith(origBlock); 340 341 // Move the operations back the original block and the delete the new block. 342 origBlock->getOperations().splice(origBlock->end(), block->getOperations()); 343 origBlock->moveBefore(block); 344 block->erase(); 345 346 convertedBlocks.erase(origBlock); 347 conversionInfo.erase(it); 348 } 349 350 void ArgConverter::applyRewrites(ConversionValueMapping &mapping) { 351 for (auto &info : conversionInfo) { 352 ConvertedBlockInfo &blockInfo = info.second; 353 Block *origBlock = blockInfo.origBlock; 354 355 // Process the remapping for each of the original arguments. 356 for (unsigned i = 0, e = origBlock->getNumArguments(); i != e; ++i) { 357 Optional<ConvertedArgInfo> &argInfo = blockInfo.argInfo[i]; 358 BlockArgument origArg = origBlock->getArgument(i); 359 360 // Handle the case of a 1->0 value mapping. 361 if (!argInfo) { 362 if (Value newArg = mapping.lookupOrNull(origArg)) 363 origArg.replaceAllUsesWith(newArg); 364 continue; 365 } 366 367 // Otherwise this is a 1->1+ value mapping. 368 Value castValue = argInfo->castValue; 369 assert(argInfo->newArgSize >= 1 && castValue && "expected 1->1+ mapping"); 370 371 // If the argument is still used, replace it with the generated cast. 372 if (!origArg.use_empty()) 373 origArg.replaceAllUsesWith(mapping.lookupOrDefault(castValue)); 374 } 375 } 376 } 377 378 LogicalResult ArgConverter::materializeLiveConversions( 379 ConversionValueMapping &mapping, OpBuilder &builder, 380 function_ref<Operation *(Value)> findLiveUser) { 381 for (auto &info : conversionInfo) { 382 Block *newBlock = info.first; 383 ConvertedBlockInfo &blockInfo = info.second; 384 Block *origBlock = blockInfo.origBlock; 385 386 // Process the remapping for each of the original arguments. 387 for (unsigned i = 0, e = origBlock->getNumArguments(); i != e; ++i) { 388 // FIXME: We should run the below checks even if the type conversion was 389 // 1->N, but a lot of existing lowering rely on the block argument being 390 // blindly replaced. Those usages should be updated, and this if should be 391 // removed. 392 if (blockInfo.argInfo[i]) 393 continue; 394 395 // If the type of this argument changed and the argument is still live, we 396 // need to materialize a conversion. 397 BlockArgument origArg = origBlock->getArgument(i); 398 auto argReplacementValue = mapping.lookupOrDefault(origArg); 399 bool isDroppedArg = argReplacementValue == origArg; 400 if (argReplacementValue.getType() == origArg.getType() && !isDroppedArg) 401 continue; 402 Operation *liveUser = findLiveUser(origArg); 403 if (!liveUser) 404 continue; 405 406 if (OpResult result = argReplacementValue.dyn_cast<OpResult>()) 407 rewriter.setInsertionPointAfter(result.getOwner()); 408 else 409 rewriter.setInsertionPointToStart(newBlock); 410 Value newArg = blockInfo.converter->materializeSourceConversion( 411 rewriter, origArg.getLoc(), origArg.getType(), 412 isDroppedArg ? ValueRange() : ValueRange(argReplacementValue)); 413 if (!newArg) { 414 InFlightDiagnostic diag = 415 emitError(origArg.getLoc()) 416 << "failed to materialize conversion for block argument #" << i 417 << " that remained live after conversion, type was " 418 << origArg.getType(); 419 if (!isDroppedArg) 420 diag << ", with target type " << argReplacementValue.getType(); 421 diag.attachNote(liveUser->getLoc()) 422 << "see existing live user here: " << *liveUser; 423 return failure(); 424 } 425 mapping.map(origArg, newArg); 426 } 427 } 428 return success(); 429 } 430 431 //===----------------------------------------------------------------------===// 432 // Conversion 433 434 FailureOr<Block *> ArgConverter::convertSignature( 435 Block *block, TypeConverter &converter, ConversionValueMapping &mapping, 436 SmallVectorImpl<BlockArgument> &argReplacements) { 437 // Check if the block was already converted. If the block is detached, 438 // conservatively assume it is going to be deleted. 439 if (hasBeenConverted(block) || !block->getParent()) 440 return block; 441 442 // Try to convert the signature for the block with the provided converter. 443 if (auto conversion = converter.convertBlockSignature(block)) 444 return applySignatureConversion(block, converter, *conversion, mapping, 445 argReplacements); 446 return failure(); 447 } 448 449 Block *ArgConverter::applySignatureConversion( 450 Block *block, TypeConverter &converter, 451 TypeConverter::SignatureConversion &signatureConversion, 452 ConversionValueMapping &mapping, 453 SmallVectorImpl<BlockArgument> &argReplacements) { 454 // If no arguments are being changed or added, there is nothing to do. 455 unsigned origArgCount = block->getNumArguments(); 456 auto convertedTypes = signatureConversion.getConvertedTypes(); 457 if (origArgCount == 0 && convertedTypes.empty()) 458 return block; 459 460 // Split the block at the beginning to get a new block to use for the updated 461 // signature. 462 Block *newBlock = block->splitBlock(block->begin()); 463 block->replaceAllUsesWith(newBlock); 464 465 SmallVector<Value, 4> newArgRange(newBlock->addArguments(convertedTypes)); 466 ArrayRef<Value> newArgs(newArgRange); 467 468 // Remap each of the original arguments as determined by the signature 469 // conversion. 470 ConvertedBlockInfo info(block, converter); 471 info.argInfo.resize(origArgCount); 472 473 OpBuilder::InsertionGuard guard(rewriter); 474 rewriter.setInsertionPointToStart(newBlock); 475 for (unsigned i = 0; i != origArgCount; ++i) { 476 auto inputMap = signatureConversion.getInputMapping(i); 477 if (!inputMap) 478 continue; 479 BlockArgument origArg = block->getArgument(i); 480 481 // If inputMap->replacementValue is not nullptr, then the argument is 482 // dropped and a replacement value is provided to be the remappedValue. 483 if (inputMap->replacementValue) { 484 assert(inputMap->size == 0 && 485 "invalid to provide a replacement value when the argument isn't " 486 "dropped"); 487 mapping.map(origArg, inputMap->replacementValue); 488 argReplacements.push_back(origArg); 489 continue; 490 } 491 492 // Otherwise, this is a 1->1+ mapping. Call into the provided type converter 493 // to pack the new values. For 1->1 mappings, if there is no materialization 494 // provided, use the argument directly instead. 495 auto replArgs = newArgs.slice(inputMap->inputNo, inputMap->size); 496 Value newArg; 497 498 // If this is a 1->1 mapping and the types of new and replacement arguments 499 // match (i.e. it's an identity map), then the argument is mapped to its 500 // original type. 501 if (replArgs.size() == 1 && replArgs[0].getType() == origArg.getType()) 502 newArg = replArgs[0]; 503 else 504 newArg = converter.materializeArgumentConversion( 505 rewriter, origArg.getLoc(), origArg.getType(), replArgs); 506 507 if (!newArg) { 508 assert(replArgs.size() == 1 && 509 "couldn't materialize the result of 1->N conversion"); 510 newArg = replArgs.front(); 511 } 512 mapping.map(origArg, newArg); 513 argReplacements.push_back(origArg); 514 info.argInfo[i] = 515 ConvertedArgInfo(inputMap->inputNo, inputMap->size, newArg); 516 } 517 518 // Remove the original block from the region and return the new one. 519 insertConversion(newBlock, std::move(info)); 520 return newBlock; 521 } 522 523 void ArgConverter::insertConversion(Block *newBlock, 524 ConvertedBlockInfo &&info) { 525 // Get a region to insert the old block. 526 Region *region = newBlock->getParent(); 527 std::unique_ptr<Region> &mappedRegion = regionMapping[region]; 528 if (!mappedRegion) 529 mappedRegion = std::make_unique<Region>(region->getParentOp()); 530 531 // Move the original block to the mapped region and emplace the conversion. 532 mappedRegion->getBlocks().splice(mappedRegion->end(), region->getBlocks(), 533 info.origBlock->getIterator()); 534 convertedBlocks.insert(info.origBlock); 535 conversionInfo.insert({newBlock, std::move(info)}); 536 } 537 538 //===----------------------------------------------------------------------===// 539 // Rewriter and Translation State 540 //===----------------------------------------------------------------------===// 541 namespace { 542 /// This class contains a snapshot of the current conversion rewriter state. 543 /// This is useful when saving and undoing a set of rewrites. 544 struct RewriterState { 545 RewriterState(unsigned numCreatedOps, unsigned numReplacements, 546 unsigned numArgReplacements, unsigned numBlockActions, 547 unsigned numIgnoredOperations, unsigned numRootUpdates) 548 : numCreatedOps(numCreatedOps), numReplacements(numReplacements), 549 numArgReplacements(numArgReplacements), 550 numBlockActions(numBlockActions), 551 numIgnoredOperations(numIgnoredOperations), 552 numRootUpdates(numRootUpdates) {} 553 554 /// The current number of created operations. 555 unsigned numCreatedOps; 556 557 /// The current number of replacements queued. 558 unsigned numReplacements; 559 560 /// The current number of argument replacements queued. 561 unsigned numArgReplacements; 562 563 /// The current number of block actions performed. 564 unsigned numBlockActions; 565 566 /// The current number of ignored operations. 567 unsigned numIgnoredOperations; 568 569 /// The current number of operations that were updated in place. 570 unsigned numRootUpdates; 571 }; 572 573 /// The state of an operation that was updated by a pattern in-place. This 574 /// contains all of the necessary information to reconstruct an operation that 575 /// was updated in place. 576 class OperationTransactionState { 577 public: 578 OperationTransactionState() = default; 579 OperationTransactionState(Operation *op) 580 : op(op), loc(op->getLoc()), attrs(op->getAttrDictionary()), 581 operands(op->operand_begin(), op->operand_end()), 582 successors(op->successor_begin(), op->successor_end()) {} 583 584 /// Discard the transaction state and reset the state of the original 585 /// operation. 586 void resetOperation() const { 587 op->setLoc(loc); 588 op->setAttrs(attrs); 589 op->setOperands(operands); 590 for (auto it : llvm::enumerate(successors)) 591 op->setSuccessor(it.value(), it.index()); 592 } 593 594 /// Return the original operation of this state. 595 Operation *getOperation() const { return op; } 596 597 private: 598 Operation *op; 599 LocationAttr loc; 600 DictionaryAttr attrs; 601 SmallVector<Value, 8> operands; 602 SmallVector<Block *, 2> successors; 603 }; 604 605 /// This class represents one requested operation replacement via 'replaceOp' or 606 /// 'eraseOp`. 607 struct OpReplacement { 608 OpReplacement() = default; 609 OpReplacement(TypeConverter *converter) : converter(converter) {} 610 611 /// An optional type converter that can be used to materialize conversions 612 /// between the new and old values if necessary. 613 TypeConverter *converter = nullptr; 614 }; 615 616 /// The kind of the block action performed during the rewrite. Actions can be 617 /// undone if the conversion fails. 618 enum class BlockActionKind { 619 Create, 620 Erase, 621 Merge, 622 Move, 623 Split, 624 TypeConversion 625 }; 626 627 /// Original position of the given block in its parent region. During undo 628 /// actions, the block needs to be placed after `insertAfterBlock`. 629 struct BlockPosition { 630 Region *region; 631 Block *insertAfterBlock; 632 }; 633 634 /// Information needed to undo the merge actions. 635 /// - the source block, and 636 /// - the Operation that was the last operation in the dest block before the 637 /// merge (could be null if the dest block was empty). 638 struct MergeInfo { 639 Block *sourceBlock; 640 Operation *destBlockLastInst; 641 }; 642 643 /// The storage class for an undoable block action (one of BlockActionKind), 644 /// contains the information necessary to undo this action. 645 struct BlockAction { 646 static BlockAction getCreate(Block *block) { 647 return {BlockActionKind::Create, block, {}}; 648 } 649 static BlockAction getErase(Block *block, BlockPosition originalPosition) { 650 return {BlockActionKind::Erase, block, {originalPosition}}; 651 } 652 static BlockAction getMerge(Block *block, Block *sourceBlock) { 653 BlockAction action{BlockActionKind::Merge, block, {}}; 654 action.mergeInfo = {sourceBlock, block->empty() ? nullptr : &block->back()}; 655 return action; 656 } 657 static BlockAction getMove(Block *block, BlockPosition originalPosition) { 658 return {BlockActionKind::Move, block, {originalPosition}}; 659 } 660 static BlockAction getSplit(Block *block, Block *originalBlock) { 661 BlockAction action{BlockActionKind::Split, block, {}}; 662 action.originalBlock = originalBlock; 663 return action; 664 } 665 static BlockAction getTypeConversion(Block *block) { 666 return BlockAction{BlockActionKind::TypeConversion, block, {}}; 667 } 668 669 // The action kind. 670 BlockActionKind kind; 671 672 // A pointer to the block that was created by the action. 673 Block *block; 674 675 union { 676 // In use if kind == BlockActionKind::Move or BlockActionKind::Erase, and 677 // contains a pointer to the region that originally contained the block as 678 // well as the position of the block in that region. 679 BlockPosition originalPosition; 680 // In use if kind == BlockActionKind::Split and contains a pointer to the 681 // block that was split into two parts. 682 Block *originalBlock; 683 // In use if kind == BlockActionKind::Merge, and contains the information 684 // needed to undo the merge. 685 MergeInfo mergeInfo; 686 }; 687 }; 688 } // end anonymous namespace 689 690 //===----------------------------------------------------------------------===// 691 // ConversionPatternRewriterImpl 692 //===----------------------------------------------------------------------===// 693 namespace mlir { 694 namespace detail { 695 struct ConversionPatternRewriterImpl { 696 ConversionPatternRewriterImpl(PatternRewriter &rewriter) 697 : argConverter(rewriter) {} 698 699 /// Cleanup and destroy any generated rewrite operations. This method is 700 /// invoked when the conversion process fails. 701 void discardRewrites(); 702 703 /// Apply all requested operation rewrites. This method is invoked when the 704 /// conversion process succeeds. 705 void applyRewrites(); 706 707 //===--------------------------------------------------------------------===// 708 // State Management 709 //===--------------------------------------------------------------------===// 710 711 /// Return the current state of the rewriter. 712 RewriterState getCurrentState(); 713 714 /// Reset the state of the rewriter to a previously saved point. 715 void resetState(RewriterState state); 716 717 /// Erase any blocks that were unlinked from their regions and stored in block 718 /// actions. 719 void eraseDanglingBlocks(); 720 721 /// Undo the block actions (motions, splits) one by one in reverse order until 722 /// "numActionsToKeep" actions remains. 723 void undoBlockActions(unsigned numActionsToKeep = 0); 724 725 /// Remap the given operands to those with potentially different types. The 726 /// provided type converter is used to ensure that the remapped types are 727 /// legal. Returns success if the operands could be remapped, failure 728 /// otherwise. 729 LogicalResult remapValues(Location loc, PatternRewriter &rewriter, 730 TypeConverter *converter, 731 Operation::operand_range operands, 732 SmallVectorImpl<Value> &remapped); 733 734 /// Returns true if the given operation is ignored, and does not need to be 735 /// converted. 736 bool isOpIgnored(Operation *op) const; 737 738 /// Recursively marks the nested operations under 'op' as ignored. This 739 /// removes them from being considered for legalization. 740 void markNestedOpsIgnored(Operation *op); 741 742 //===--------------------------------------------------------------------===// 743 // Type Conversion 744 //===--------------------------------------------------------------------===// 745 746 /// Convert the signature of the given block. 747 FailureOr<Block *> convertBlockSignature( 748 Block *block, TypeConverter &converter, 749 TypeConverter::SignatureConversion *conversion = nullptr); 750 751 /// Apply a signature conversion on the given region, using `converter` for 752 /// materializations if not null. 753 Block * 754 applySignatureConversion(Region *region, 755 TypeConverter::SignatureConversion &conversion, 756 TypeConverter *converter); 757 758 /// Convert the types of block arguments within the given region. 759 FailureOr<Block *> 760 convertRegionTypes(Region *region, TypeConverter &converter, 761 TypeConverter::SignatureConversion *entryConversion); 762 763 /// Convert the types of non-entry block arguments within the given region. 764 LogicalResult convertNonEntryRegionTypes( 765 Region *region, TypeConverter &converter, 766 ArrayRef<TypeConverter::SignatureConversion> blockConversions = {}); 767 768 //===--------------------------------------------------------------------===// 769 // Rewriter Notification Hooks 770 //===--------------------------------------------------------------------===// 771 772 /// PatternRewriter hook for replacing the results of an operation. 773 void notifyOpReplaced(Operation *op, ValueRange newValues); 774 775 /// Notifies that a block is about to be erased. 776 void notifyBlockIsBeingErased(Block *block); 777 778 /// Notifies that a block was created. 779 void notifyCreatedBlock(Block *block); 780 781 /// Notifies that a block was split. 782 void notifySplitBlock(Block *block, Block *continuation); 783 784 /// Notifies that `block` is being merged with `srcBlock`. 785 void notifyBlocksBeingMerged(Block *block, Block *srcBlock); 786 787 /// Notifies that the blocks of a region are about to be moved. 788 void notifyRegionIsBeingInlinedBefore(Region ®ion, Region &parent, 789 Region::iterator before); 790 791 /// Notifies that the blocks of a region were cloned into another. 792 void notifyRegionWasClonedBefore(iterator_range<Region::iterator> &blocks, 793 Location origRegionLoc); 794 795 /// Notifies that a pattern match failed for the given reason. 796 LogicalResult 797 notifyMatchFailure(Location loc, 798 function_ref<void(Diagnostic &)> reasonCallback); 799 800 //===--------------------------------------------------------------------===// 801 // State 802 //===--------------------------------------------------------------------===// 803 804 // Mapping between replaced values that differ in type. This happens when 805 // replacing a value with one of a different type. 806 ConversionValueMapping mapping; 807 808 /// Utility used to convert block arguments. 809 ArgConverter argConverter; 810 811 /// Ordered vector of all of the newly created operations during conversion. 812 std::vector<Operation *> createdOps; 813 814 /// Ordered map of requested operation replacements. 815 llvm::MapVector<Operation *, OpReplacement> replacements; 816 817 /// Ordered vector of any requested block argument replacements. 818 SmallVector<BlockArgument, 4> argReplacements; 819 820 /// Ordered list of block operations (creations, splits, motions). 821 SmallVector<BlockAction, 4> blockActions; 822 823 /// A set of operations that should no longer be considered for legalization, 824 /// but were not directly replace/erased/etc. by a pattern. These are 825 /// generally child operations of other operations who were 826 /// replaced/erased/etc. This is not meant to be an exhaustive list of all 827 /// operations, but the minimal set that can be used to detect if a given 828 /// operation should be `ignored`. For example, we may add the operations that 829 /// define non-empty regions to the set, but not any of the others. This 830 /// simplifies the amount of memory needed as we can query if the parent 831 /// operation was ignored. 832 SetVector<Operation *> ignoredOps; 833 834 /// A transaction state for each of operations that were updated in-place. 835 SmallVector<OperationTransactionState, 4> rootUpdates; 836 837 /// A vector of indices into `replacements` of operations that were replaced 838 /// with values with different result types than the original operation, e.g. 839 /// 1->N conversion of some kind. 840 SmallVector<unsigned, 4> operationsWithChangedResults; 841 842 /// A default type converter, used when block conversions do not have one 843 /// explicitly provided. 844 TypeConverter defaultTypeConverter; 845 846 /// The current conversion pattern that is being rewritten, or nullptr if 847 /// called from outside of a conversion pattern rewrite. 848 const ConversionPattern *currentConversionPattern = nullptr; 849 850 #ifndef NDEBUG 851 /// A set of operations that have pending updates. This tracking isn't 852 /// strictly necessary, and is thus only active during debug builds for extra 853 /// verification. 854 SmallPtrSet<Operation *, 1> pendingRootUpdates; 855 856 /// A logger used to emit diagnostics during the conversion process. 857 llvm::ScopedPrinter logger{llvm::dbgs()}; 858 #endif 859 }; 860 } // end namespace detail 861 } // end namespace mlir 862 863 /// Detach any operations nested in the given operation from their parent 864 /// blocks, and erase the given operation. This can be used when the nested 865 /// operations are scheduled for erasure themselves, so deleting the regions of 866 /// the given operation together with their content would result in double-free. 867 /// This happens, for example, when rolling back op creation in the reverse 868 /// order and if the nested ops were created before the parent op. This function 869 /// does not need to collect nested ops recursively because it is expected to 870 /// also be called for each nested op when it is about to be deleted. 871 static void detachNestedAndErase(Operation *op) { 872 for (Region ®ion : op->getRegions()) { 873 for (Block &block : region.getBlocks()) { 874 while (!block.getOperations().empty()) 875 block.getOperations().remove(block.getOperations().begin()); 876 block.dropAllDefinedValueUses(); 877 } 878 } 879 op->dropAllUses(); 880 op->erase(); 881 } 882 883 void ConversionPatternRewriterImpl::discardRewrites() { 884 // Reset any operations that were updated in place. 885 for (auto &state : rootUpdates) 886 state.resetOperation(); 887 888 undoBlockActions(); 889 890 // Remove any newly created ops. 891 for (auto *op : llvm::reverse(createdOps)) 892 detachNestedAndErase(op); 893 } 894 895 void ConversionPatternRewriterImpl::applyRewrites() { 896 // Apply all of the rewrites replacements requested during conversion. 897 for (auto &repl : replacements) { 898 for (OpResult result : repl.first->getResults()) 899 if (Value newValue = mapping.lookupOrNull(result)) 900 result.replaceAllUsesWith(newValue); 901 902 // If this operation defines any regions, drop any pending argument 903 // rewrites. 904 if (repl.first->getNumRegions()) 905 argConverter.notifyOpRemoved(repl.first); 906 } 907 908 // Apply all of the requested argument replacements. 909 for (BlockArgument arg : argReplacements) { 910 Value repl = mapping.lookupOrDefault(arg); 911 if (repl.isa<BlockArgument>()) { 912 arg.replaceAllUsesWith(repl); 913 continue; 914 } 915 916 // If the replacement value is an operation, we check to make sure that we 917 // don't replace uses that are within the parent operation of the 918 // replacement value. 919 Operation *replOp = repl.cast<OpResult>().getOwner(); 920 Block *replBlock = replOp->getBlock(); 921 arg.replaceUsesWithIf(repl, [&](OpOperand &operand) { 922 Operation *user = operand.getOwner(); 923 return user->getBlock() != replBlock || replOp->isBeforeInBlock(user); 924 }); 925 } 926 927 // In a second pass, erase all of the replaced operations in reverse. This 928 // allows processing nested operations before their parent region is 929 // destroyed. Because we process in reverse order, producers may be deleted 930 // before their users (a pattern deleting a producer and then the consumer) 931 // so we first drop all uses explicitly. 932 for (auto &repl : llvm::reverse(replacements)) { 933 repl.first->dropAllUses(); 934 repl.first->erase(); 935 } 936 937 argConverter.applyRewrites(mapping); 938 939 // Now that the ops have been erased, also erase dangling blocks. 940 eraseDanglingBlocks(); 941 } 942 943 //===----------------------------------------------------------------------===// 944 // State Management 945 946 RewriterState ConversionPatternRewriterImpl::getCurrentState() { 947 return RewriterState(createdOps.size(), replacements.size(), 948 argReplacements.size(), blockActions.size(), 949 ignoredOps.size(), rootUpdates.size()); 950 } 951 952 void ConversionPatternRewriterImpl::resetState(RewriterState state) { 953 // Reset any operations that were updated in place. 954 for (unsigned i = state.numRootUpdates, e = rootUpdates.size(); i != e; ++i) 955 rootUpdates[i].resetOperation(); 956 rootUpdates.resize(state.numRootUpdates); 957 958 // Reset any replaced arguments. 959 for (BlockArgument replacedArg : 960 llvm::drop_begin(argReplacements, state.numArgReplacements)) 961 mapping.erase(replacedArg); 962 argReplacements.resize(state.numArgReplacements); 963 964 // Undo any block actions. 965 undoBlockActions(state.numBlockActions); 966 967 // Reset any replaced operations and undo any saved mappings. 968 for (auto &repl : llvm::drop_begin(replacements, state.numReplacements)) 969 for (auto result : repl.first->getResults()) 970 mapping.erase(result); 971 while (replacements.size() != state.numReplacements) 972 replacements.pop_back(); 973 974 // Pop all of the newly created operations. 975 while (createdOps.size() != state.numCreatedOps) { 976 detachNestedAndErase(createdOps.back()); 977 createdOps.pop_back(); 978 } 979 980 // Pop all of the recorded ignored operations that are no longer valid. 981 while (ignoredOps.size() != state.numIgnoredOperations) 982 ignoredOps.pop_back(); 983 984 // Reset operations with changed results. 985 while (!operationsWithChangedResults.empty() && 986 operationsWithChangedResults.back() >= state.numReplacements) 987 operationsWithChangedResults.pop_back(); 988 } 989 990 void ConversionPatternRewriterImpl::eraseDanglingBlocks() { 991 for (auto &action : blockActions) 992 if (action.kind == BlockActionKind::Erase) 993 delete action.block; 994 } 995 996 void ConversionPatternRewriterImpl::undoBlockActions( 997 unsigned numActionsToKeep) { 998 for (auto &action : 999 llvm::reverse(llvm::drop_begin(blockActions, numActionsToKeep))) { 1000 switch (action.kind) { 1001 // Delete the created block. 1002 case BlockActionKind::Create: { 1003 // Unlink all of the operations within this block, they will be deleted 1004 // separately. 1005 auto &blockOps = action.block->getOperations(); 1006 while (!blockOps.empty()) 1007 blockOps.remove(blockOps.begin()); 1008 action.block->dropAllDefinedValueUses(); 1009 action.block->erase(); 1010 break; 1011 } 1012 // Put the block (owned by action) back into its original position. 1013 case BlockActionKind::Erase: { 1014 auto &blockList = action.originalPosition.region->getBlocks(); 1015 Block *insertAfterBlock = action.originalPosition.insertAfterBlock; 1016 blockList.insert((insertAfterBlock 1017 ? std::next(Region::iterator(insertAfterBlock)) 1018 : blockList.begin()), 1019 action.block); 1020 break; 1021 } 1022 // Split the block at the position which was originally the end of the 1023 // destination block (owned by action), and put the instructions back into 1024 // the block used before the merge. 1025 case BlockActionKind::Merge: { 1026 Block *sourceBlock = action.mergeInfo.sourceBlock; 1027 Block::iterator splitPoint = 1028 (action.mergeInfo.destBlockLastInst 1029 ? ++Block::iterator(action.mergeInfo.destBlockLastInst) 1030 : action.block->begin()); 1031 sourceBlock->getOperations().splice(sourceBlock->begin(), 1032 action.block->getOperations(), 1033 splitPoint, action.block->end()); 1034 break; 1035 } 1036 // Move the block back to its original position. 1037 case BlockActionKind::Move: { 1038 Region *originalRegion = action.originalPosition.region; 1039 Block *insertAfterBlock = action.originalPosition.insertAfterBlock; 1040 originalRegion->getBlocks().splice( 1041 (insertAfterBlock ? std::next(Region::iterator(insertAfterBlock)) 1042 : originalRegion->end()), 1043 action.block->getParent()->getBlocks(), action.block); 1044 break; 1045 } 1046 // Merge back the block that was split out. 1047 case BlockActionKind::Split: { 1048 action.originalBlock->getOperations().splice( 1049 action.originalBlock->end(), action.block->getOperations()); 1050 action.block->dropAllDefinedValueUses(); 1051 action.block->erase(); 1052 break; 1053 } 1054 // Undo the type conversion. 1055 case BlockActionKind::TypeConversion: { 1056 argConverter.discardRewrites(action.block); 1057 break; 1058 } 1059 } 1060 } 1061 blockActions.resize(numActionsToKeep); 1062 } 1063 1064 LogicalResult ConversionPatternRewriterImpl::remapValues( 1065 Location loc, PatternRewriter &rewriter, TypeConverter *converter, 1066 Operation::operand_range operands, SmallVectorImpl<Value> &remapped) { 1067 remapped.reserve(llvm::size(operands)); 1068 1069 SmallVector<Type, 1> legalTypes; 1070 for (auto it : llvm::enumerate(operands)) { 1071 Value operand = it.value(); 1072 Type origType = operand.getType(); 1073 1074 // If a converter was provided, get the desired legal types for this 1075 // operand. 1076 Type desiredType; 1077 if (converter) { 1078 // If there is no legal conversion, fail to match this pattern. 1079 legalTypes.clear(); 1080 if (failed(converter->convertType(origType, legalTypes))) { 1081 return notifyMatchFailure(loc, [=](Diagnostic &diag) { 1082 diag << "unable to convert type for operand #" << it.index() 1083 << ", type was " << origType; 1084 }); 1085 } 1086 // TODO: There currently isn't any mechanism to do 1->N type conversion 1087 // via the PatternRewriter replacement API, so for now we just ignore it. 1088 if (legalTypes.size() == 1) 1089 desiredType = legalTypes.front(); 1090 } else { 1091 // TODO: What we should do here is just set `desiredType` to `origType` 1092 // and then handle the necessary type conversions after the conversion 1093 // process has finished. Unfortunately a lot of patterns currently rely on 1094 // receiving the new operands even if the types change, so we keep the 1095 // original behavior here for now until all of the patterns relying on 1096 // this get updated. 1097 } 1098 Value newOperand = mapping.lookupOrDefault(operand, desiredType); 1099 1100 // Handle the case where the conversion was 1->1 and the new operand type 1101 // isn't legal. 1102 Type newOperandType = newOperand.getType(); 1103 if (converter && desiredType && newOperandType != desiredType) { 1104 // Attempt to materialize a conversion for this new value. 1105 newOperand = converter->materializeTargetConversion( 1106 rewriter, loc, desiredType, newOperand); 1107 if (!newOperand) { 1108 return notifyMatchFailure(loc, [=](Diagnostic &diag) { 1109 diag << "unable to materialize a conversion for " 1110 "operand #" 1111 << it.index() << ", from " << newOperandType << " to " 1112 << desiredType; 1113 }); 1114 } 1115 } 1116 remapped.push_back(newOperand); 1117 } 1118 return success(); 1119 } 1120 1121 bool ConversionPatternRewriterImpl::isOpIgnored(Operation *op) const { 1122 // Check to see if this operation was replaced or its parent ignored. 1123 return replacements.count(op) || ignoredOps.count(op->getParentOp()); 1124 } 1125 1126 void ConversionPatternRewriterImpl::markNestedOpsIgnored(Operation *op) { 1127 // Walk this operation and collect nested operations that define non-empty 1128 // regions. We mark such operations as 'ignored' so that we know we don't have 1129 // to convert them, or their nested ops. 1130 if (op->getNumRegions() == 0) 1131 return; 1132 op->walk([&](Operation *op) { 1133 if (llvm::any_of(op->getRegions(), 1134 [](Region ®ion) { return !region.empty(); })) 1135 ignoredOps.insert(op); 1136 }); 1137 } 1138 1139 //===----------------------------------------------------------------------===// 1140 // Type Conversion 1141 1142 FailureOr<Block *> ConversionPatternRewriterImpl::convertBlockSignature( 1143 Block *block, TypeConverter &converter, 1144 TypeConverter::SignatureConversion *conversion) { 1145 FailureOr<Block *> result = 1146 conversion ? argConverter.applySignatureConversion( 1147 block, converter, *conversion, mapping, argReplacements) 1148 : argConverter.convertSignature(block, converter, mapping, 1149 argReplacements); 1150 if (Block *newBlock = result.getValue()) { 1151 if (newBlock != block) 1152 blockActions.push_back(BlockAction::getTypeConversion(newBlock)); 1153 } 1154 return result; 1155 } 1156 1157 Block *ConversionPatternRewriterImpl::applySignatureConversion( 1158 Region *region, TypeConverter::SignatureConversion &conversion, 1159 TypeConverter *converter) { 1160 if (!region->empty()) { 1161 return *convertBlockSignature(®ion->front(), 1162 converter ? *converter : defaultTypeConverter, 1163 &conversion); 1164 } 1165 return nullptr; 1166 } 1167 1168 FailureOr<Block *> ConversionPatternRewriterImpl::convertRegionTypes( 1169 Region *region, TypeConverter &converter, 1170 TypeConverter::SignatureConversion *entryConversion) { 1171 argConverter.setConverter(region, &converter); 1172 if (region->empty()) 1173 return nullptr; 1174 1175 if (failed(convertNonEntryRegionTypes(region, converter))) 1176 return failure(); 1177 1178 FailureOr<Block *> newEntry = 1179 convertBlockSignature(®ion->front(), converter, entryConversion); 1180 return newEntry; 1181 } 1182 1183 LogicalResult ConversionPatternRewriterImpl::convertNonEntryRegionTypes( 1184 Region *region, TypeConverter &converter, 1185 ArrayRef<TypeConverter::SignatureConversion> blockConversions) { 1186 argConverter.setConverter(region, &converter); 1187 if (region->empty()) 1188 return success(); 1189 1190 // Convert the arguments of each block within the region. 1191 int blockIdx = 0; 1192 assert((blockConversions.empty() || 1193 blockConversions.size() == region->getBlocks().size() - 1) && 1194 "expected either to provide no SignatureConversions at all or to " 1195 "provide a SignatureConversion for each non-entry block"); 1196 1197 for (Block &block : 1198 llvm::make_early_inc_range(llvm::drop_begin(*region, 1))) { 1199 TypeConverter::SignatureConversion *blockConversion = 1200 blockConversions.empty() 1201 ? nullptr 1202 : const_cast<TypeConverter::SignatureConversion *>( 1203 &blockConversions[blockIdx++]); 1204 1205 if (failed(convertBlockSignature(&block, converter, blockConversion))) 1206 return failure(); 1207 } 1208 return success(); 1209 } 1210 1211 //===----------------------------------------------------------------------===// 1212 // Rewriter Notification Hooks 1213 1214 void ConversionPatternRewriterImpl::notifyOpReplaced(Operation *op, 1215 ValueRange newValues) { 1216 assert(newValues.size() == op->getNumResults()); 1217 assert(!replacements.count(op) && "operation was already replaced"); 1218 1219 // Track if any of the results changed, e.g. erased and replaced with null. 1220 bool resultChanged = false; 1221 1222 // Create mappings for each of the new result values. 1223 Value newValue, result; 1224 for (auto it : llvm::zip(newValues, op->getResults())) { 1225 std::tie(newValue, result) = it; 1226 if (!newValue) { 1227 resultChanged = true; 1228 continue; 1229 } 1230 // Remap, and check for any result type changes. 1231 mapping.map(result, newValue); 1232 resultChanged |= (newValue.getType() != result.getType()); 1233 } 1234 if (resultChanged) 1235 operationsWithChangedResults.push_back(replacements.size()); 1236 1237 // Record the requested operation replacement. 1238 TypeConverter *converter = nullptr; 1239 if (currentConversionPattern) 1240 converter = currentConversionPattern->getTypeConverter(); 1241 replacements.insert(std::make_pair(op, OpReplacement(converter))); 1242 1243 // Mark this operation as recursively ignored so that we don't need to 1244 // convert any nested operations. 1245 markNestedOpsIgnored(op); 1246 } 1247 1248 void ConversionPatternRewriterImpl::notifyBlockIsBeingErased(Block *block) { 1249 Region *region = block->getParent(); 1250 Block *origPrevBlock = block->getPrevNode(); 1251 blockActions.push_back(BlockAction::getErase(block, {region, origPrevBlock})); 1252 } 1253 1254 void ConversionPatternRewriterImpl::notifyCreatedBlock(Block *block) { 1255 blockActions.push_back(BlockAction::getCreate(block)); 1256 } 1257 1258 void ConversionPatternRewriterImpl::notifySplitBlock(Block *block, 1259 Block *continuation) { 1260 blockActions.push_back(BlockAction::getSplit(continuation, block)); 1261 } 1262 1263 void ConversionPatternRewriterImpl::notifyBlocksBeingMerged(Block *block, 1264 Block *srcBlock) { 1265 blockActions.push_back(BlockAction::getMerge(block, srcBlock)); 1266 } 1267 1268 void ConversionPatternRewriterImpl::notifyRegionIsBeingInlinedBefore( 1269 Region ®ion, Region &parent, Region::iterator before) { 1270 if (region.empty()) 1271 return; 1272 Block *laterBlock = ®ion.back(); 1273 for (auto &earlierBlock : llvm::drop_begin(llvm::reverse(region), 1)) { 1274 blockActions.push_back( 1275 BlockAction::getMove(laterBlock, {®ion, &earlierBlock})); 1276 laterBlock = &earlierBlock; 1277 } 1278 blockActions.push_back(BlockAction::getMove(laterBlock, {®ion, nullptr})); 1279 } 1280 1281 void ConversionPatternRewriterImpl::notifyRegionWasClonedBefore( 1282 iterator_range<Region::iterator> &blocks, Location origRegionLoc) { 1283 for (Block &block : blocks) 1284 blockActions.push_back(BlockAction::getCreate(&block)); 1285 1286 // Compute the conversion set for the inlined region. 1287 auto result = computeConversionSet(blocks, origRegionLoc, createdOps); 1288 1289 // This original region has already had its conversion set computed, so there 1290 // shouldn't be any new failures. 1291 (void)result; 1292 assert(succeeded(result) && "expected region to have no unreachable blocks"); 1293 } 1294 1295 LogicalResult ConversionPatternRewriterImpl::notifyMatchFailure( 1296 Location loc, function_ref<void(Diagnostic &)> reasonCallback) { 1297 LLVM_DEBUG({ 1298 Diagnostic diag(loc, DiagnosticSeverity::Remark); 1299 reasonCallback(diag); 1300 logger.startLine() << "** Failure : " << diag.str() << "\n"; 1301 }); 1302 return failure(); 1303 } 1304 1305 //===----------------------------------------------------------------------===// 1306 // ConversionPatternRewriter 1307 //===----------------------------------------------------------------------===// 1308 1309 ConversionPatternRewriter::ConversionPatternRewriter(MLIRContext *ctx) 1310 : PatternRewriter(ctx), 1311 impl(new detail::ConversionPatternRewriterImpl(*this)) {} 1312 ConversionPatternRewriter::~ConversionPatternRewriter() {} 1313 1314 /// PatternRewriter hook for replacing the results of an operation when the 1315 /// given functor returns true. 1316 void ConversionPatternRewriter::replaceOpWithIf( 1317 Operation *op, ValueRange newValues, bool *allUsesReplaced, 1318 llvm::unique_function<bool(OpOperand &) const> functor) { 1319 // TODO: To support this we will need to rework a bit of how replacements are 1320 // tracked, given that this isn't guranteed to replace all of the uses of an 1321 // operation. The main change is that now an operation can be replaced 1322 // multiple times, in parts. The current "set" based tracking is mainly useful 1323 // for tracking if a replaced operation should be ignored, i.e. if all of the 1324 // uses will be replaced. 1325 llvm_unreachable( 1326 "replaceOpWithIf is currently not supported by DialectConversion"); 1327 } 1328 1329 /// PatternRewriter hook for replacing the results of an operation. 1330 void ConversionPatternRewriter::replaceOp(Operation *op, ValueRange newValues) { 1331 LLVM_DEBUG({ 1332 impl->logger.startLine() 1333 << "** Replace : '" << op->getName() << "'(" << op << ")\n"; 1334 }); 1335 impl->notifyOpReplaced(op, newValues); 1336 } 1337 1338 /// PatternRewriter hook for erasing a dead operation. The uses of this 1339 /// operation *must* be made dead by the end of the conversion process, 1340 /// otherwise an assert will be issued. 1341 void ConversionPatternRewriter::eraseOp(Operation *op) { 1342 LLVM_DEBUG({ 1343 impl->logger.startLine() 1344 << "** Erase : '" << op->getName() << "'(" << op << ")\n"; 1345 }); 1346 SmallVector<Value, 1> nullRepls(op->getNumResults(), nullptr); 1347 impl->notifyOpReplaced(op, nullRepls); 1348 } 1349 1350 void ConversionPatternRewriter::eraseBlock(Block *block) { 1351 impl->notifyBlockIsBeingErased(block); 1352 1353 // Mark all ops for erasure. 1354 for (Operation &op : *block) 1355 eraseOp(&op); 1356 1357 // Unlink the block from its parent region. The block is kept in the block 1358 // action and will be actually destroyed when rewrites are applied. This 1359 // allows us to keep the operations in the block live and undo the removal by 1360 // re-inserting the block. 1361 block->getParent()->getBlocks().remove(block); 1362 } 1363 1364 Block *ConversionPatternRewriter::applySignatureConversion( 1365 Region *region, TypeConverter::SignatureConversion &conversion, 1366 TypeConverter *converter) { 1367 return impl->applySignatureConversion(region, conversion, converter); 1368 } 1369 1370 FailureOr<Block *> ConversionPatternRewriter::convertRegionTypes( 1371 Region *region, TypeConverter &converter, 1372 TypeConverter::SignatureConversion *entryConversion) { 1373 return impl->convertRegionTypes(region, converter, entryConversion); 1374 } 1375 1376 LogicalResult ConversionPatternRewriter::convertNonEntryRegionTypes( 1377 Region *region, TypeConverter &converter, 1378 ArrayRef<TypeConverter::SignatureConversion> blockConversions) { 1379 return impl->convertNonEntryRegionTypes(region, converter, blockConversions); 1380 } 1381 1382 void ConversionPatternRewriter::replaceUsesOfBlockArgument(BlockArgument from, 1383 Value to) { 1384 LLVM_DEBUG({ 1385 Operation *parentOp = from.getOwner()->getParentOp(); 1386 impl->logger.startLine() << "** Replace Argument : '" << from 1387 << "'(in region of '" << parentOp->getName() 1388 << "'(" << from.getOwner()->getParentOp() << ")\n"; 1389 }); 1390 impl->argReplacements.push_back(from); 1391 impl->mapping.map(impl->mapping.lookupOrDefault(from), to); 1392 } 1393 1394 /// Return the converted value that replaces 'key'. Return 'key' if there is 1395 /// no such a converted value. 1396 Value ConversionPatternRewriter::getRemappedValue(Value key) { 1397 return impl->mapping.lookupOrDefault(key); 1398 } 1399 1400 /// PatternRewriter hook for creating a new block with the given arguments. 1401 void ConversionPatternRewriter::notifyBlockCreated(Block *block) { 1402 impl->notifyCreatedBlock(block); 1403 } 1404 1405 /// PatternRewriter hook for splitting a block into two parts. 1406 Block *ConversionPatternRewriter::splitBlock(Block *block, 1407 Block::iterator before) { 1408 auto *continuation = PatternRewriter::splitBlock(block, before); 1409 impl->notifySplitBlock(block, continuation); 1410 return continuation; 1411 } 1412 1413 /// PatternRewriter hook for merging a block into another. 1414 void ConversionPatternRewriter::mergeBlocks(Block *source, Block *dest, 1415 ValueRange argValues) { 1416 impl->notifyBlocksBeingMerged(dest, source); 1417 assert(llvm::all_of(source->getPredecessors(), 1418 [dest](Block *succ) { return succ == dest; }) && 1419 "expected 'source' to have no predecessors or only 'dest'"); 1420 assert(argValues.size() == source->getNumArguments() && 1421 "incorrect # of argument replacement values"); 1422 for (auto it : llvm::zip(source->getArguments(), argValues)) 1423 replaceUsesOfBlockArgument(std::get<0>(it), std::get<1>(it)); 1424 dest->getOperations().splice(dest->end(), source->getOperations()); 1425 eraseBlock(source); 1426 } 1427 1428 /// PatternRewriter hook for moving blocks out of a region. 1429 void ConversionPatternRewriter::inlineRegionBefore(Region ®ion, 1430 Region &parent, 1431 Region::iterator before) { 1432 impl->notifyRegionIsBeingInlinedBefore(region, parent, before); 1433 PatternRewriter::inlineRegionBefore(region, parent, before); 1434 } 1435 1436 /// PatternRewriter hook for cloning blocks of one region into another. 1437 void ConversionPatternRewriter::cloneRegionBefore( 1438 Region ®ion, Region &parent, Region::iterator before, 1439 BlockAndValueMapping &mapping) { 1440 if (region.empty()) 1441 return; 1442 PatternRewriter::cloneRegionBefore(region, parent, before, mapping); 1443 1444 // Collect the range of the cloned blocks. 1445 auto clonedBeginIt = mapping.lookup(®ion.front())->getIterator(); 1446 auto clonedBlocks = llvm::make_range(clonedBeginIt, before); 1447 impl->notifyRegionWasClonedBefore(clonedBlocks, region.getLoc()); 1448 } 1449 1450 /// PatternRewriter hook for creating a new operation. 1451 void ConversionPatternRewriter::notifyOperationInserted(Operation *op) { 1452 LLVM_DEBUG({ 1453 impl->logger.startLine() 1454 << "** Insert : '" << op->getName() << "'(" << op << ")\n"; 1455 }); 1456 impl->createdOps.push_back(op); 1457 } 1458 1459 /// PatternRewriter hook for updating the root operation in-place. 1460 void ConversionPatternRewriter::startRootUpdate(Operation *op) { 1461 #ifndef NDEBUG 1462 impl->pendingRootUpdates.insert(op); 1463 #endif 1464 impl->rootUpdates.emplace_back(op); 1465 } 1466 1467 /// PatternRewriter hook for updating the root operation in-place. 1468 void ConversionPatternRewriter::finalizeRootUpdate(Operation *op) { 1469 // There is nothing to do here, we only need to track the operation at the 1470 // start of the update. 1471 #ifndef NDEBUG 1472 assert(impl->pendingRootUpdates.erase(op) && 1473 "operation did not have a pending in-place update"); 1474 #endif 1475 } 1476 1477 /// PatternRewriter hook for updating the root operation in-place. 1478 void ConversionPatternRewriter::cancelRootUpdate(Operation *op) { 1479 #ifndef NDEBUG 1480 assert(impl->pendingRootUpdates.erase(op) && 1481 "operation did not have a pending in-place update"); 1482 #endif 1483 // Erase the last update for this operation. 1484 auto stateHasOp = [op](const auto &it) { return it.getOperation() == op; }; 1485 auto &rootUpdates = impl->rootUpdates; 1486 auto it = llvm::find_if(llvm::reverse(rootUpdates), stateHasOp); 1487 rootUpdates.erase(rootUpdates.begin() + (rootUpdates.rend() - it)); 1488 } 1489 1490 /// PatternRewriter hook for notifying match failure reasons. 1491 LogicalResult ConversionPatternRewriter::notifyMatchFailure( 1492 Operation *op, function_ref<void(Diagnostic &)> reasonCallback) { 1493 return impl->notifyMatchFailure(op->getLoc(), reasonCallback); 1494 } 1495 1496 /// Return a reference to the internal implementation. 1497 detail::ConversionPatternRewriterImpl &ConversionPatternRewriter::getImpl() { 1498 return *impl; 1499 } 1500 1501 //===----------------------------------------------------------------------===// 1502 // ConversionPattern 1503 //===----------------------------------------------------------------------===// 1504 1505 /// Attempt to match and rewrite the IR root at the specified operation. 1506 LogicalResult 1507 ConversionPattern::matchAndRewrite(Operation *op, 1508 PatternRewriter &rewriter) const { 1509 auto &dialectRewriter = static_cast<ConversionPatternRewriter &>(rewriter); 1510 auto &rewriterImpl = dialectRewriter.getImpl(); 1511 1512 // Track the current conversion pattern in the rewriter. 1513 assert(!rewriterImpl.currentConversionPattern && 1514 "already inside of a pattern rewrite"); 1515 llvm::SaveAndRestore<const ConversionPattern *> currentPatternGuard( 1516 rewriterImpl.currentConversionPattern, this); 1517 1518 // Remap the operands of the operation. 1519 SmallVector<Value, 4> operands; 1520 if (failed(rewriterImpl.remapValues(op->getLoc(), rewriter, 1521 getTypeConverter(), op->getOperands(), 1522 operands))) { 1523 return failure(); 1524 } 1525 return matchAndRewrite(op, operands, dialectRewriter); 1526 } 1527 1528 //===----------------------------------------------------------------------===// 1529 // OperationLegalizer 1530 //===----------------------------------------------------------------------===// 1531 1532 namespace { 1533 /// A set of rewrite patterns that can be used to legalize a given operation. 1534 using LegalizationPatterns = SmallVector<const Pattern *, 1>; 1535 1536 /// This class defines a recursive operation legalizer. 1537 class OperationLegalizer { 1538 public: 1539 using LegalizationAction = ConversionTarget::LegalizationAction; 1540 1541 OperationLegalizer(ConversionTarget &targetInfo, 1542 const FrozenRewritePatternSet &patterns); 1543 1544 /// Returns true if the given operation is known to be illegal on the target. 1545 bool isIllegal(Operation *op) const; 1546 1547 /// Attempt to legalize the given operation. Returns success if the operation 1548 /// was legalized, failure otherwise. 1549 LogicalResult legalize(Operation *op, ConversionPatternRewriter &rewriter); 1550 1551 /// Returns the conversion target in use by the legalizer. 1552 ConversionTarget &getTarget() { return target; } 1553 1554 private: 1555 /// Attempt to legalize the given operation by folding it. 1556 LogicalResult legalizeWithFold(Operation *op, 1557 ConversionPatternRewriter &rewriter); 1558 1559 /// Attempt to legalize the given operation by applying a pattern. Returns 1560 /// success if the operation was legalized, failure otherwise. 1561 LogicalResult legalizeWithPattern(Operation *op, 1562 ConversionPatternRewriter &rewriter); 1563 1564 /// Return true if the given pattern may be applied to the given operation, 1565 /// false otherwise. 1566 bool canApplyPattern(Operation *op, const Pattern &pattern, 1567 ConversionPatternRewriter &rewriter); 1568 1569 /// Legalize the resultant IR after successfully applying the given pattern. 1570 LogicalResult legalizePatternResult(Operation *op, const Pattern &pattern, 1571 ConversionPatternRewriter &rewriter, 1572 RewriterState &curState); 1573 1574 /// Legalizes the actions registered during the execution of a pattern. 1575 LogicalResult legalizePatternBlockActions(Operation *op, 1576 ConversionPatternRewriter &rewriter, 1577 ConversionPatternRewriterImpl &impl, 1578 RewriterState &state, 1579 RewriterState &newState); 1580 LogicalResult legalizePatternCreatedOperations( 1581 ConversionPatternRewriter &rewriter, ConversionPatternRewriterImpl &impl, 1582 RewriterState &state, RewriterState &newState); 1583 LogicalResult legalizePatternRootUpdates(ConversionPatternRewriter &rewriter, 1584 ConversionPatternRewriterImpl &impl, 1585 RewriterState &state, 1586 RewriterState &newState); 1587 1588 //===--------------------------------------------------------------------===// 1589 // Cost Model 1590 //===--------------------------------------------------------------------===// 1591 1592 /// Build an optimistic legalization graph given the provided patterns. This 1593 /// function populates 'anyOpLegalizerPatterns' and 'legalizerPatterns' with 1594 /// patterns for operations that are not directly legal, but may be 1595 /// transitively legal for the current target given the provided patterns. 1596 void buildLegalizationGraph( 1597 LegalizationPatterns &anyOpLegalizerPatterns, 1598 DenseMap<OperationName, LegalizationPatterns> &legalizerPatterns); 1599 1600 /// Compute the benefit of each node within the computed legalization graph. 1601 /// This orders the patterns within 'legalizerPatterns' based upon two 1602 /// criteria: 1603 /// 1) Prefer patterns that have the lowest legalization depth, i.e. 1604 /// represent the more direct mapping to the target. 1605 /// 2) When comparing patterns with the same legalization depth, prefer the 1606 /// pattern with the highest PatternBenefit. This allows for users to 1607 /// prefer specific legalizations over others. 1608 void computeLegalizationGraphBenefit( 1609 LegalizationPatterns &anyOpLegalizerPatterns, 1610 DenseMap<OperationName, LegalizationPatterns> &legalizerPatterns); 1611 1612 /// Compute the legalization depth when legalizing an operation of the given 1613 /// type. 1614 unsigned computeOpLegalizationDepth( 1615 OperationName op, DenseMap<OperationName, unsigned> &minOpPatternDepth, 1616 DenseMap<OperationName, LegalizationPatterns> &legalizerPatterns); 1617 1618 /// Apply the conversion cost model to the given set of patterns, and return 1619 /// the smallest legalization depth of any of the patterns. See 1620 /// `computeLegalizationGraphBenefit` for the breakdown of the cost model. 1621 unsigned applyCostModelToPatterns( 1622 LegalizationPatterns &patterns, 1623 DenseMap<OperationName, unsigned> &minOpPatternDepth, 1624 DenseMap<OperationName, LegalizationPatterns> &legalizerPatterns); 1625 1626 /// The current set of patterns that have been applied. 1627 SmallPtrSet<const Pattern *, 8> appliedPatterns; 1628 1629 /// The legalization information provided by the target. 1630 ConversionTarget ⌖ 1631 1632 /// The pattern applicator to use for conversions. 1633 PatternApplicator applicator; 1634 }; 1635 } // namespace 1636 1637 OperationLegalizer::OperationLegalizer(ConversionTarget &targetInfo, 1638 const FrozenRewritePatternSet &patterns) 1639 : target(targetInfo), applicator(patterns) { 1640 // The set of patterns that can be applied to illegal operations to transform 1641 // them into legal ones. 1642 DenseMap<OperationName, LegalizationPatterns> legalizerPatterns; 1643 LegalizationPatterns anyOpLegalizerPatterns; 1644 1645 buildLegalizationGraph(anyOpLegalizerPatterns, legalizerPatterns); 1646 computeLegalizationGraphBenefit(anyOpLegalizerPatterns, legalizerPatterns); 1647 } 1648 1649 bool OperationLegalizer::isIllegal(Operation *op) const { 1650 // Check if the target explicitly marked this operation as illegal. 1651 return target.getOpAction(op->getName()) == LegalizationAction::Illegal; 1652 } 1653 1654 LogicalResult 1655 OperationLegalizer::legalize(Operation *op, 1656 ConversionPatternRewriter &rewriter) { 1657 #ifndef NDEBUG 1658 const char *logLineComment = 1659 "//===-------------------------------------------===//\n"; 1660 1661 auto &rewriterImpl = rewriter.getImpl(); 1662 #endif 1663 LLVM_DEBUG({ 1664 auto &os = rewriterImpl.logger; 1665 os.getOStream() << "\n"; 1666 os.startLine() << logLineComment; 1667 os.startLine() << "Legalizing operation : '" << op->getName() << "'(" << op 1668 << ") {\n"; 1669 os.indent(); 1670 1671 // If the operation has no regions, just print it here. 1672 if (op->getNumRegions() == 0) { 1673 op->print(os.startLine(), OpPrintingFlags().printGenericOpForm()); 1674 os.getOStream() << "\n\n"; 1675 } 1676 }); 1677 1678 // Check if this operation is legal on the target. 1679 if (auto legalityInfo = target.isLegal(op)) { 1680 LLVM_DEBUG({ 1681 logSuccess( 1682 rewriterImpl.logger, "operation marked legal by the target{0}", 1683 legalityInfo->isRecursivelyLegal 1684 ? "; NOTE: operation is recursively legal; skipping internals" 1685 : ""); 1686 rewriterImpl.logger.startLine() << logLineComment; 1687 }); 1688 1689 // If this operation is recursively legal, mark its children as ignored so 1690 // that we don't consider them for legalization. 1691 if (legalityInfo->isRecursivelyLegal) 1692 rewriter.getImpl().markNestedOpsIgnored(op); 1693 return success(); 1694 } 1695 1696 // Check to see if the operation is ignored and doesn't need to be converted. 1697 if (rewriter.getImpl().isOpIgnored(op)) { 1698 LLVM_DEBUG({ 1699 logSuccess(rewriterImpl.logger, 1700 "operation marked 'ignored' during conversion"); 1701 rewriterImpl.logger.startLine() << logLineComment; 1702 }); 1703 return success(); 1704 } 1705 1706 // If the operation isn't legal, try to fold it in-place. 1707 // TODO: Should we always try to do this, even if the op is 1708 // already legal? 1709 if (succeeded(legalizeWithFold(op, rewriter))) { 1710 LLVM_DEBUG({ 1711 logSuccess(rewriterImpl.logger, "operation was folded"); 1712 rewriterImpl.logger.startLine() << logLineComment; 1713 }); 1714 return success(); 1715 } 1716 1717 // Otherwise, we need to apply a legalization pattern to this operation. 1718 if (succeeded(legalizeWithPattern(op, rewriter))) { 1719 LLVM_DEBUG({ 1720 logSuccess(rewriterImpl.logger, ""); 1721 rewriterImpl.logger.startLine() << logLineComment; 1722 }); 1723 return success(); 1724 } 1725 1726 LLVM_DEBUG({ 1727 logFailure(rewriterImpl.logger, "no matched legalization pattern"); 1728 rewriterImpl.logger.startLine() << logLineComment; 1729 }); 1730 return failure(); 1731 } 1732 1733 LogicalResult 1734 OperationLegalizer::legalizeWithFold(Operation *op, 1735 ConversionPatternRewriter &rewriter) { 1736 auto &rewriterImpl = rewriter.getImpl(); 1737 RewriterState curState = rewriterImpl.getCurrentState(); 1738 1739 LLVM_DEBUG({ 1740 rewriterImpl.logger.startLine() << "* Fold {\n"; 1741 rewriterImpl.logger.indent(); 1742 }); 1743 1744 // Try to fold the operation. 1745 SmallVector<Value, 2> replacementValues; 1746 rewriter.setInsertionPoint(op); 1747 if (failed(rewriter.tryFold(op, replacementValues))) { 1748 LLVM_DEBUG(logFailure(rewriterImpl.logger, "unable to fold")); 1749 return failure(); 1750 } 1751 1752 // Insert a replacement for 'op' with the folded replacement values. 1753 rewriter.replaceOp(op, replacementValues); 1754 1755 // Recursively legalize any new constant operations. 1756 for (unsigned i = curState.numCreatedOps, e = rewriterImpl.createdOps.size(); 1757 i != e; ++i) { 1758 Operation *cstOp = rewriterImpl.createdOps[i]; 1759 if (failed(legalize(cstOp, rewriter))) { 1760 LLVM_DEBUG(logFailure(rewriterImpl.logger, 1761 "generated constant '{0}' was illegal", 1762 cstOp->getName())); 1763 rewriterImpl.resetState(curState); 1764 return failure(); 1765 } 1766 } 1767 1768 LLVM_DEBUG(logSuccess(rewriterImpl.logger, "")); 1769 return success(); 1770 } 1771 1772 LogicalResult 1773 OperationLegalizer::legalizeWithPattern(Operation *op, 1774 ConversionPatternRewriter &rewriter) { 1775 auto &rewriterImpl = rewriter.getImpl(); 1776 1777 // Functor that returns if the given pattern may be applied. 1778 auto canApply = [&](const Pattern &pattern) { 1779 return canApplyPattern(op, pattern, rewriter); 1780 }; 1781 1782 // Functor that cleans up the rewriter state after a pattern failed to match. 1783 RewriterState curState = rewriterImpl.getCurrentState(); 1784 auto onFailure = [&](const Pattern &pattern) { 1785 LLVM_DEBUG(logFailure(rewriterImpl.logger, "pattern failed to match")); 1786 rewriterImpl.resetState(curState); 1787 appliedPatterns.erase(&pattern); 1788 }; 1789 1790 // Functor that performs additional legalization when a pattern is 1791 // successfully applied. 1792 auto onSuccess = [&](const Pattern &pattern) { 1793 auto result = legalizePatternResult(op, pattern, rewriter, curState); 1794 appliedPatterns.erase(&pattern); 1795 if (failed(result)) 1796 rewriterImpl.resetState(curState); 1797 return result; 1798 }; 1799 1800 // Try to match and rewrite a pattern on this operation. 1801 return applicator.matchAndRewrite(op, rewriter, canApply, onFailure, 1802 onSuccess); 1803 } 1804 1805 bool OperationLegalizer::canApplyPattern(Operation *op, const Pattern &pattern, 1806 ConversionPatternRewriter &rewriter) { 1807 LLVM_DEBUG({ 1808 auto &os = rewriter.getImpl().logger; 1809 os.getOStream() << "\n"; 1810 os.startLine() << "* Pattern : '" << op->getName() << " -> ("; 1811 llvm::interleaveComma(pattern.getGeneratedOps(), llvm::dbgs()); 1812 os.getOStream() << ")' {\n"; 1813 os.indent(); 1814 }); 1815 1816 // Ensure that we don't cycle by not allowing the same pattern to be 1817 // applied twice in the same recursion stack if it is not known to be safe. 1818 if (!pattern.hasBoundedRewriteRecursion() && 1819 !appliedPatterns.insert(&pattern).second) { 1820 LLVM_DEBUG( 1821 logFailure(rewriter.getImpl().logger, "pattern was already applied")); 1822 return false; 1823 } 1824 return true; 1825 } 1826 1827 LogicalResult 1828 OperationLegalizer::legalizePatternResult(Operation *op, const Pattern &pattern, 1829 ConversionPatternRewriter &rewriter, 1830 RewriterState &curState) { 1831 auto &impl = rewriter.getImpl(); 1832 1833 #ifndef NDEBUG 1834 assert(impl.pendingRootUpdates.empty() && "dangling root updates"); 1835 #endif 1836 1837 // Check that the root was either replaced or updated in place. 1838 auto replacedRoot = [&] { 1839 return llvm::any_of( 1840 llvm::drop_begin(impl.replacements, curState.numReplacements), 1841 [op](auto &it) { return it.first == op; }); 1842 }; 1843 auto updatedRootInPlace = [&] { 1844 return llvm::any_of( 1845 llvm::drop_begin(impl.rootUpdates, curState.numRootUpdates), 1846 [op](auto &state) { return state.getOperation() == op; }); 1847 }; 1848 (void)replacedRoot; 1849 (void)updatedRootInPlace; 1850 assert((replacedRoot() || updatedRootInPlace()) && 1851 "expected pattern to replace the root operation"); 1852 1853 // Legalize each of the actions registered during application. 1854 RewriterState newState = impl.getCurrentState(); 1855 if (failed(legalizePatternBlockActions(op, rewriter, impl, curState, 1856 newState)) || 1857 failed(legalizePatternRootUpdates(rewriter, impl, curState, newState)) || 1858 failed(legalizePatternCreatedOperations(rewriter, impl, curState, 1859 newState))) { 1860 return failure(); 1861 } 1862 1863 LLVM_DEBUG(logSuccess(impl.logger, "pattern applied successfully")); 1864 return success(); 1865 } 1866 1867 LogicalResult OperationLegalizer::legalizePatternBlockActions( 1868 Operation *op, ConversionPatternRewriter &rewriter, 1869 ConversionPatternRewriterImpl &impl, RewriterState &state, 1870 RewriterState &newState) { 1871 SmallPtrSet<Operation *, 16> operationsToIgnore; 1872 1873 // If the pattern moved or created any blocks, make sure the types of block 1874 // arguments get legalized. 1875 for (int i = state.numBlockActions, e = newState.numBlockActions; i != e; 1876 ++i) { 1877 auto &action = impl.blockActions[i]; 1878 if (action.kind == BlockActionKind::TypeConversion || 1879 action.kind == BlockActionKind::Erase) 1880 continue; 1881 // Only check blocks outside of the current operation. 1882 Operation *parentOp = action.block->getParentOp(); 1883 if (!parentOp || parentOp == op || action.block->getNumArguments() == 0) 1884 continue; 1885 1886 // If the region of the block has a type converter, try to convert the block 1887 // directly. 1888 if (auto *converter = 1889 impl.argConverter.getConverter(action.block->getParent())) { 1890 if (failed(impl.convertBlockSignature(action.block, *converter))) { 1891 LLVM_DEBUG(logFailure(impl.logger, "failed to convert types of moved " 1892 "block")); 1893 return failure(); 1894 } 1895 continue; 1896 } 1897 1898 // Otherwise, check that this operation isn't one generated by this pattern. 1899 // This is because we will attempt to legalize the parent operation, and 1900 // blocks in regions created by this pattern will already be legalized later 1901 // on. If we haven't built the set yet, build it now. 1902 if (operationsToIgnore.empty()) { 1903 auto createdOps = ArrayRef<Operation *>(impl.createdOps) 1904 .drop_front(state.numCreatedOps); 1905 operationsToIgnore.insert(createdOps.begin(), createdOps.end()); 1906 } 1907 1908 // If this operation should be considered for re-legalization, try it. 1909 if (operationsToIgnore.insert(parentOp).second && 1910 failed(legalize(parentOp, rewriter))) { 1911 LLVM_DEBUG(logFailure( 1912 impl.logger, "operation '{0}'({1}) became illegal after block action", 1913 parentOp->getName(), parentOp)); 1914 return failure(); 1915 } 1916 } 1917 return success(); 1918 } 1919 LogicalResult OperationLegalizer::legalizePatternCreatedOperations( 1920 ConversionPatternRewriter &rewriter, ConversionPatternRewriterImpl &impl, 1921 RewriterState &state, RewriterState &newState) { 1922 for (int i = state.numCreatedOps, e = newState.numCreatedOps; i != e; ++i) { 1923 Operation *op = impl.createdOps[i]; 1924 if (failed(legalize(op, rewriter))) { 1925 LLVM_DEBUG(logFailure(impl.logger, 1926 "generated operation '{0}'({1}) was illegal", 1927 op->getName(), op)); 1928 return failure(); 1929 } 1930 } 1931 return success(); 1932 } 1933 LogicalResult OperationLegalizer::legalizePatternRootUpdates( 1934 ConversionPatternRewriter &rewriter, ConversionPatternRewriterImpl &impl, 1935 RewriterState &state, RewriterState &newState) { 1936 for (int i = state.numRootUpdates, e = newState.numRootUpdates; i != e; ++i) { 1937 Operation *op = impl.rootUpdates[i].getOperation(); 1938 if (failed(legalize(op, rewriter))) { 1939 LLVM_DEBUG(logFailure(impl.logger, 1940 "operation updated in-place '{0}' was illegal", 1941 op->getName())); 1942 return failure(); 1943 } 1944 } 1945 return success(); 1946 } 1947 1948 //===----------------------------------------------------------------------===// 1949 // Cost Model 1950 1951 void OperationLegalizer::buildLegalizationGraph( 1952 LegalizationPatterns &anyOpLegalizerPatterns, 1953 DenseMap<OperationName, LegalizationPatterns> &legalizerPatterns) { 1954 // A mapping between an operation and a set of operations that can be used to 1955 // generate it. 1956 DenseMap<OperationName, SmallPtrSet<OperationName, 2>> parentOps; 1957 // A mapping between an operation and any currently invalid patterns it has. 1958 DenseMap<OperationName, SmallPtrSet<const Pattern *, 2>> invalidPatterns; 1959 // A worklist of patterns to consider for legality. 1960 SetVector<const Pattern *> patternWorklist; 1961 1962 // Build the mapping from operations to the parent ops that may generate them. 1963 applicator.walkAllPatterns([&](const Pattern &pattern) { 1964 Optional<OperationName> root = pattern.getRootKind(); 1965 1966 // If the pattern has no specific root, we can't analyze the relationship 1967 // between the root op and generated operations. Given that, add all such 1968 // patterns to the legalization set. 1969 if (!root) { 1970 anyOpLegalizerPatterns.push_back(&pattern); 1971 return; 1972 } 1973 1974 // Skip operations that are always known to be legal. 1975 if (target.getOpAction(*root) == LegalizationAction::Legal) 1976 return; 1977 1978 // Add this pattern to the invalid set for the root op and record this root 1979 // as a parent for any generated operations. 1980 invalidPatterns[*root].insert(&pattern); 1981 for (auto op : pattern.getGeneratedOps()) 1982 parentOps[op].insert(*root); 1983 1984 // Add this pattern to the worklist. 1985 patternWorklist.insert(&pattern); 1986 }); 1987 1988 // If there are any patterns that don't have a specific root kind, we can't 1989 // make direct assumptions about what operations will never be legalized. 1990 // Note: Technically we could, but it would require an analysis that may 1991 // recurse into itself. It would be better to perform this kind of filtering 1992 // at a higher level than here anyways. 1993 if (!anyOpLegalizerPatterns.empty()) { 1994 for (const Pattern *pattern : patternWorklist) 1995 legalizerPatterns[*pattern->getRootKind()].push_back(pattern); 1996 return; 1997 } 1998 1999 while (!patternWorklist.empty()) { 2000 auto *pattern = patternWorklist.pop_back_val(); 2001 2002 // Check to see if any of the generated operations are invalid. 2003 if (llvm::any_of(pattern->getGeneratedOps(), [&](OperationName op) { 2004 Optional<LegalizationAction> action = target.getOpAction(op); 2005 return !legalizerPatterns.count(op) && 2006 (!action || action == LegalizationAction::Illegal); 2007 })) 2008 continue; 2009 2010 // Otherwise, if all of the generated operation are valid, this op is now 2011 // legal so add all of the child patterns to the worklist. 2012 legalizerPatterns[*pattern->getRootKind()].push_back(pattern); 2013 invalidPatterns[*pattern->getRootKind()].erase(pattern); 2014 2015 // Add any invalid patterns of the parent operations to see if they have now 2016 // become legal. 2017 for (auto op : parentOps[*pattern->getRootKind()]) 2018 patternWorklist.set_union(invalidPatterns[op]); 2019 } 2020 } 2021 2022 void OperationLegalizer::computeLegalizationGraphBenefit( 2023 LegalizationPatterns &anyOpLegalizerPatterns, 2024 DenseMap<OperationName, LegalizationPatterns> &legalizerPatterns) { 2025 // The smallest pattern depth, when legalizing an operation. 2026 DenseMap<OperationName, unsigned> minOpPatternDepth; 2027 2028 // For each operation that is transitively legal, compute a cost for it. 2029 for (auto &opIt : legalizerPatterns) 2030 if (!minOpPatternDepth.count(opIt.first)) 2031 computeOpLegalizationDepth(opIt.first, minOpPatternDepth, 2032 legalizerPatterns); 2033 2034 // Apply the cost model to the patterns that can match any operation. Those 2035 // with a specific operation type are already resolved when computing the op 2036 // legalization depth. 2037 if (!anyOpLegalizerPatterns.empty()) 2038 applyCostModelToPatterns(anyOpLegalizerPatterns, minOpPatternDepth, 2039 legalizerPatterns); 2040 2041 // Apply a cost model to the pattern applicator. We order patterns first by 2042 // depth then benefit. `legalizerPatterns` contains per-op patterns by 2043 // decreasing benefit. 2044 applicator.applyCostModel([&](const Pattern &pattern) { 2045 ArrayRef<const Pattern *> orderedPatternList; 2046 if (Optional<OperationName> rootName = pattern.getRootKind()) 2047 orderedPatternList = legalizerPatterns[*rootName]; 2048 else 2049 orderedPatternList = anyOpLegalizerPatterns; 2050 2051 // If the pattern is not found, then it was removed and cannot be matched. 2052 auto it = llvm::find(orderedPatternList, &pattern); 2053 if (it == orderedPatternList.end()) 2054 return PatternBenefit::impossibleToMatch(); 2055 2056 // Patterns found earlier in the list have higher benefit. 2057 return PatternBenefit(std::distance(it, orderedPatternList.end())); 2058 }); 2059 } 2060 2061 unsigned OperationLegalizer::computeOpLegalizationDepth( 2062 OperationName op, DenseMap<OperationName, unsigned> &minOpPatternDepth, 2063 DenseMap<OperationName, LegalizationPatterns> &legalizerPatterns) { 2064 // Check for existing depth. 2065 auto depthIt = minOpPatternDepth.find(op); 2066 if (depthIt != minOpPatternDepth.end()) 2067 return depthIt->second; 2068 2069 // If a mapping for this operation does not exist, then this operation 2070 // is always legal. Return 0 as the depth for a directly legal operation. 2071 auto opPatternsIt = legalizerPatterns.find(op); 2072 if (opPatternsIt == legalizerPatterns.end() || opPatternsIt->second.empty()) 2073 return 0u; 2074 2075 // Record this initial depth in case we encounter this op again when 2076 // recursively computing the depth. 2077 minOpPatternDepth.try_emplace(op, std::numeric_limits<unsigned>::max()); 2078 2079 // Apply the cost model to the operation patterns, and update the minimum 2080 // depth. 2081 unsigned minDepth = applyCostModelToPatterns( 2082 opPatternsIt->second, minOpPatternDepth, legalizerPatterns); 2083 minOpPatternDepth[op] = minDepth; 2084 return minDepth; 2085 } 2086 2087 unsigned OperationLegalizer::applyCostModelToPatterns( 2088 LegalizationPatterns &patterns, 2089 DenseMap<OperationName, unsigned> &minOpPatternDepth, 2090 DenseMap<OperationName, LegalizationPatterns> &legalizerPatterns) { 2091 unsigned minDepth = std::numeric_limits<unsigned>::max(); 2092 2093 // Compute the depth for each pattern within the set. 2094 SmallVector<std::pair<const Pattern *, unsigned>, 4> patternsByDepth; 2095 patternsByDepth.reserve(patterns.size()); 2096 for (const Pattern *pattern : patterns) { 2097 unsigned depth = 0; 2098 for (auto generatedOp : pattern->getGeneratedOps()) { 2099 unsigned generatedOpDepth = computeOpLegalizationDepth( 2100 generatedOp, minOpPatternDepth, legalizerPatterns); 2101 depth = std::max(depth, generatedOpDepth + 1); 2102 } 2103 patternsByDepth.emplace_back(pattern, depth); 2104 2105 // Update the minimum depth of the pattern list. 2106 minDepth = std::min(minDepth, depth); 2107 } 2108 2109 // If the operation only has one legalization pattern, there is no need to 2110 // sort them. 2111 if (patternsByDepth.size() == 1) 2112 return minDepth; 2113 2114 // Sort the patterns by those likely to be the most beneficial. 2115 llvm::array_pod_sort(patternsByDepth.begin(), patternsByDepth.end(), 2116 [](const std::pair<const Pattern *, unsigned> *lhs, 2117 const std::pair<const Pattern *, unsigned> *rhs) { 2118 // First sort by the smaller pattern legalization 2119 // depth. 2120 if (lhs->second != rhs->second) 2121 return llvm::array_pod_sort_comparator<unsigned>( 2122 &lhs->second, &rhs->second); 2123 2124 // Then sort by the larger pattern benefit. 2125 auto lhsBenefit = lhs->first->getBenefit(); 2126 auto rhsBenefit = rhs->first->getBenefit(); 2127 return llvm::array_pod_sort_comparator<PatternBenefit>( 2128 &rhsBenefit, &lhsBenefit); 2129 }); 2130 2131 // Update the legalization pattern to use the new sorted list. 2132 patterns.clear(); 2133 for (auto &patternIt : patternsByDepth) 2134 patterns.push_back(patternIt.first); 2135 return minDepth; 2136 } 2137 2138 //===----------------------------------------------------------------------===// 2139 // OperationConverter 2140 //===----------------------------------------------------------------------===// 2141 namespace { 2142 enum OpConversionMode { 2143 // In this mode, the conversion will ignore failed conversions to allow 2144 // illegal operations to co-exist in the IR. 2145 Partial, 2146 2147 // In this mode, all operations must be legal for the given target for the 2148 // conversion to succeed. 2149 Full, 2150 2151 // In this mode, operations are analyzed for legality. No actual rewrites are 2152 // applied to the operations on success. 2153 Analysis, 2154 }; 2155 2156 // This class converts operations to a given conversion target via a set of 2157 // rewrite patterns. The conversion behaves differently depending on the 2158 // conversion mode. 2159 struct OperationConverter { 2160 explicit OperationConverter(ConversionTarget &target, 2161 const FrozenRewritePatternSet &patterns, 2162 OpConversionMode mode, 2163 DenseSet<Operation *> *trackedOps = nullptr) 2164 : opLegalizer(target, patterns), mode(mode), trackedOps(trackedOps) {} 2165 2166 /// Converts the given operations to the conversion target. 2167 LogicalResult convertOperations(ArrayRef<Operation *> ops); 2168 2169 private: 2170 /// Converts an operation with the given rewriter. 2171 LogicalResult convert(ConversionPatternRewriter &rewriter, Operation *op); 2172 2173 /// This method is called after the conversion process to legalize any 2174 /// remaining artifacts and complete the conversion. 2175 LogicalResult finalize(ConversionPatternRewriter &rewriter); 2176 2177 /// Legalize the types of converted block arguments. 2178 LogicalResult 2179 legalizeConvertedArgumentTypes(ConversionPatternRewriter &rewriter, 2180 ConversionPatternRewriterImpl &rewriterImpl); 2181 2182 /// Legalize an operation result that was marked as "erased". 2183 LogicalResult 2184 legalizeErasedResult(Operation *op, OpResult result, 2185 ConversionPatternRewriterImpl &rewriterImpl); 2186 2187 /// Legalize an operation result that was replaced with a value of a different 2188 /// type. 2189 LogicalResult 2190 legalizeChangedResultType(Operation *op, OpResult result, Value newValue, 2191 TypeConverter *replConverter, 2192 ConversionPatternRewriter &rewriter, 2193 ConversionPatternRewriterImpl &rewriterImpl, 2194 const BlockAndValueMapping &inverseMapping); 2195 2196 /// The legalizer to use when converting operations. 2197 OperationLegalizer opLegalizer; 2198 2199 /// The conversion mode to use when legalizing operations. 2200 OpConversionMode mode; 2201 2202 /// A set of pre-existing operations. When mode == OpConversionMode::Analysis, 2203 /// this is populated with ops found to be legalizable to the target. 2204 /// When mode == OpConversionMode::Partial, this is populated with ops found 2205 /// *not* to be legalizable to the target. 2206 DenseSet<Operation *> *trackedOps; 2207 }; 2208 } // end anonymous namespace 2209 2210 LogicalResult OperationConverter::convert(ConversionPatternRewriter &rewriter, 2211 Operation *op) { 2212 // Legalize the given operation. 2213 if (failed(opLegalizer.legalize(op, rewriter))) { 2214 // Handle the case of a failed conversion for each of the different modes. 2215 // Full conversions expect all operations to be converted. 2216 if (mode == OpConversionMode::Full) 2217 return op->emitError() 2218 << "failed to legalize operation '" << op->getName() << "'"; 2219 // Partial conversions allow conversions to fail iff the operation was not 2220 // explicitly marked as illegal. If the user provided a nonlegalizableOps 2221 // set, non-legalizable ops are included. 2222 if (mode == OpConversionMode::Partial) { 2223 if (opLegalizer.isIllegal(op)) 2224 return op->emitError() 2225 << "failed to legalize operation '" << op->getName() 2226 << "' that was explicitly marked illegal"; 2227 if (trackedOps) 2228 trackedOps->insert(op); 2229 } 2230 } else if (mode == OpConversionMode::Analysis) { 2231 // Analysis conversions don't fail if any operations fail to legalize, 2232 // they are only interested in the operations that were successfully 2233 // legalized. 2234 trackedOps->insert(op); 2235 } 2236 return success(); 2237 } 2238 2239 LogicalResult OperationConverter::convertOperations(ArrayRef<Operation *> ops) { 2240 if (ops.empty()) 2241 return success(); 2242 ConversionTarget &target = opLegalizer.getTarget(); 2243 2244 // Compute the set of operations and blocks to convert. 2245 std::vector<Operation *> toConvert; 2246 for (auto *op : ops) { 2247 toConvert.emplace_back(op); 2248 for (auto ®ion : op->getRegions()) 2249 if (failed(computeConversionSet(region.getBlocks(), region.getLoc(), 2250 toConvert, &target))) 2251 return failure(); 2252 } 2253 2254 // Convert each operation and discard rewrites on failure. 2255 ConversionPatternRewriter rewriter(ops.front()->getContext()); 2256 ConversionPatternRewriterImpl &rewriterImpl = rewriter.getImpl(); 2257 for (auto *op : toConvert) 2258 if (failed(convert(rewriter, op))) 2259 return rewriterImpl.discardRewrites(), failure(); 2260 2261 // Now that all of the operations have been converted, finalize the conversion 2262 // process to ensure any lingering conversion artifacts are cleaned up and 2263 // legalized. 2264 if (failed(finalize(rewriter))) 2265 return rewriterImpl.discardRewrites(), failure(); 2266 // After a successful conversion, apply rewrites if this is not an analysis 2267 // conversion. 2268 if (mode == OpConversionMode::Analysis) 2269 rewriterImpl.discardRewrites(); 2270 else { 2271 rewriterImpl.applyRewrites(); 2272 2273 // It is possible for a later pattern to erase an op that was originally 2274 // identified as illegal and added to the trackedOps, remove it now after 2275 // replacements have been computed. 2276 if (trackedOps) 2277 for (auto &repl : rewriterImpl.replacements) 2278 trackedOps->erase(repl.first); 2279 } 2280 return success(); 2281 } 2282 2283 LogicalResult 2284 OperationConverter::finalize(ConversionPatternRewriter &rewriter) { 2285 ConversionPatternRewriterImpl &rewriterImpl = rewriter.getImpl(); 2286 2287 // Legalize converted block arguments. 2288 if (failed(legalizeConvertedArgumentTypes(rewriter, rewriterImpl))) 2289 return failure(); 2290 2291 if (rewriterImpl.operationsWithChangedResults.empty()) 2292 return success(); 2293 2294 Optional<BlockAndValueMapping> inverseMapping; 2295 2296 // Process requested operation replacements. 2297 for (unsigned i = 0, e = rewriterImpl.operationsWithChangedResults.size(); 2298 i != e; ++i) { 2299 unsigned replIdx = rewriterImpl.operationsWithChangedResults[i]; 2300 auto &repl = *(rewriterImpl.replacements.begin() + replIdx); 2301 for (OpResult result : repl.first->getResults()) { 2302 Value newValue = rewriterImpl.mapping.lookupOrNull(result); 2303 2304 // If the operation result was replaced with null, all of the uses of this 2305 // value should be replaced. 2306 if (!newValue) { 2307 if (failed(legalizeErasedResult(repl.first, result, rewriterImpl))) 2308 return failure(); 2309 continue; 2310 } 2311 2312 // Otherwise, check to see if the type of the result changed. 2313 if (result.getType() == newValue.getType()) 2314 continue; 2315 2316 // Compute the inverse mapping only if it is really needed. 2317 if (!inverseMapping) 2318 inverseMapping = rewriterImpl.mapping.getInverse(); 2319 2320 // Legalize this result. 2321 rewriter.setInsertionPoint(repl.first); 2322 if (failed(legalizeChangedResultType(repl.first, result, newValue, 2323 repl.second.converter, rewriter, 2324 rewriterImpl, *inverseMapping))) 2325 return failure(); 2326 2327 // Update the end iterator for this loop in the case it was updated 2328 // when legalizing generated conversion operations. 2329 e = rewriterImpl.operationsWithChangedResults.size(); 2330 } 2331 } 2332 return success(); 2333 } 2334 2335 LogicalResult OperationConverter::legalizeConvertedArgumentTypes( 2336 ConversionPatternRewriter &rewriter, 2337 ConversionPatternRewriterImpl &rewriterImpl) { 2338 // Functor used to check if all users of a value will be dead after 2339 // conversion. 2340 auto findLiveUser = [&](Value val) { 2341 auto liveUserIt = llvm::find_if_not(val.getUsers(), [&](Operation *user) { 2342 return rewriterImpl.isOpIgnored(user); 2343 }); 2344 return liveUserIt == val.user_end() ? nullptr : *liveUserIt; 2345 }; 2346 2347 // Materialize any necessary conversions for converted block arguments that 2348 // are still live. 2349 size_t numCreatedOps = rewriterImpl.createdOps.size(); 2350 if (failed(rewriterImpl.argConverter.materializeLiveConversions( 2351 rewriterImpl.mapping, rewriter, findLiveUser))) 2352 return failure(); 2353 2354 // Legalize any newly created operations during argument materialization. 2355 for (int i : llvm::seq<int>(numCreatedOps, rewriterImpl.createdOps.size())) { 2356 if (failed(opLegalizer.legalize(rewriterImpl.createdOps[i], rewriter))) { 2357 return rewriterImpl.createdOps[i]->emitError() 2358 << "failed to legalize conversion operation generated for block " 2359 "argument that remained live after conversion"; 2360 } 2361 } 2362 return success(); 2363 } 2364 2365 LogicalResult OperationConverter::legalizeErasedResult( 2366 Operation *op, OpResult result, 2367 ConversionPatternRewriterImpl &rewriterImpl) { 2368 // If the operation result was replaced with null, all of the uses of this 2369 // value should be replaced. 2370 auto liveUserIt = llvm::find_if_not(result.getUsers(), [&](Operation *user) { 2371 return rewriterImpl.isOpIgnored(user); 2372 }); 2373 if (liveUserIt != result.user_end()) { 2374 InFlightDiagnostic diag = op->emitError("failed to legalize operation '") 2375 << op->getName() << "' marked as erased"; 2376 diag.attachNote(liveUserIt->getLoc()) 2377 << "found live user of result #" << result.getResultNumber() << ": " 2378 << *liveUserIt; 2379 return failure(); 2380 } 2381 return success(); 2382 } 2383 2384 /// Finds a user of the given value, or of any other value that the given value 2385 /// replaced, that was not replaced in the conversion process. 2386 static Operation * 2387 findLiveUserOfReplaced(Value value, ConversionPatternRewriterImpl &rewriterImpl, 2388 const BlockAndValueMapping &inverseMapping) { 2389 do { 2390 // Walk the users of this value to see if there are any live users that 2391 // weren't replaced during conversion. 2392 auto liveUserIt = llvm::find_if_not(value.getUsers(), [&](Operation *user) { 2393 return rewriterImpl.isOpIgnored(user); 2394 }); 2395 if (liveUserIt != value.user_end()) 2396 return *liveUserIt; 2397 value = inverseMapping.lookupOrNull(value); 2398 } while (value != nullptr); 2399 return nullptr; 2400 } 2401 2402 LogicalResult OperationConverter::legalizeChangedResultType( 2403 Operation *op, OpResult result, Value newValue, 2404 TypeConverter *replConverter, ConversionPatternRewriter &rewriter, 2405 ConversionPatternRewriterImpl &rewriterImpl, 2406 const BlockAndValueMapping &inverseMapping) { 2407 Operation *liveUser = 2408 findLiveUserOfReplaced(result, rewriterImpl, inverseMapping); 2409 if (!liveUser) 2410 return success(); 2411 2412 // If the replacement has a type converter, attempt to materialize a 2413 // conversion back to the original type. 2414 if (!replConverter) { 2415 // TODO: We should emit an error here, similarly to the case where the 2416 // result is replaced with null. Unfortunately a lot of existing 2417 // patterns rely on this behavior, so until those patterns are updated 2418 // we keep the legacy behavior here of just forwarding the new value. 2419 return success(); 2420 } 2421 2422 // Track the number of created operations so that new ones can be legalized. 2423 size_t numCreatedOps = rewriterImpl.createdOps.size(); 2424 2425 // Materialize a conversion for this live result value. 2426 Type resultType = result.getType(); 2427 Value convertedValue = replConverter->materializeSourceConversion( 2428 rewriter, op->getLoc(), resultType, newValue); 2429 if (!convertedValue) { 2430 InFlightDiagnostic diag = op->emitError() 2431 << "failed to materialize conversion for result #" 2432 << result.getResultNumber() << " of operation '" 2433 << op->getName() 2434 << "' that remained live after conversion"; 2435 diag.attachNote(liveUser->getLoc()) 2436 << "see existing live user here: " << *liveUser; 2437 return failure(); 2438 } 2439 2440 // Legalize all of the newly created conversion operations. 2441 for (int i : llvm::seq<int>(numCreatedOps, rewriterImpl.createdOps.size())) { 2442 if (failed(opLegalizer.legalize(rewriterImpl.createdOps[i], rewriter))) { 2443 return op->emitError("failed to legalize conversion operation generated ") 2444 << "for result #" << result.getResultNumber() << " of operation '" 2445 << op->getName() << "' that remained live after conversion"; 2446 } 2447 } 2448 2449 rewriterImpl.mapping.map(result, convertedValue); 2450 return success(); 2451 } 2452 2453 //===----------------------------------------------------------------------===// 2454 // Type Conversion 2455 //===----------------------------------------------------------------------===// 2456 2457 /// Remap an input of the original signature with a new set of types. The 2458 /// new types are appended to the new signature conversion. 2459 void TypeConverter::SignatureConversion::addInputs(unsigned origInputNo, 2460 ArrayRef<Type> types) { 2461 assert(!types.empty() && "expected valid types"); 2462 remapInput(origInputNo, /*newInputNo=*/argTypes.size(), types.size()); 2463 addInputs(types); 2464 } 2465 2466 /// Append new input types to the signature conversion, this should only be 2467 /// used if the new types are not intended to remap an existing input. 2468 void TypeConverter::SignatureConversion::addInputs(ArrayRef<Type> types) { 2469 assert(!types.empty() && 2470 "1->0 type remappings don't need to be added explicitly"); 2471 argTypes.append(types.begin(), types.end()); 2472 } 2473 2474 /// Remap an input of the original signature with a range of types in the 2475 /// new signature. 2476 void TypeConverter::SignatureConversion::remapInput(unsigned origInputNo, 2477 unsigned newInputNo, 2478 unsigned newInputCount) { 2479 assert(!remappedInputs[origInputNo] && "input has already been remapped"); 2480 assert(newInputCount != 0 && "expected valid input count"); 2481 remappedInputs[origInputNo] = 2482 InputMapping{newInputNo, newInputCount, /*replacementValue=*/nullptr}; 2483 } 2484 2485 /// Remap an input of the original signature to another `replacementValue` 2486 /// value. This would make the signature converter drop this argument. 2487 void TypeConverter::SignatureConversion::remapInput(unsigned origInputNo, 2488 Value replacementValue) { 2489 assert(!remappedInputs[origInputNo] && "input has already been remapped"); 2490 remappedInputs[origInputNo] = 2491 InputMapping{origInputNo, /*size=*/0, replacementValue}; 2492 } 2493 2494 /// This hooks allows for converting a type. 2495 LogicalResult TypeConverter::convertType(Type t, 2496 SmallVectorImpl<Type> &results) { 2497 auto existingIt = cachedDirectConversions.find(t); 2498 if (existingIt != cachedDirectConversions.end()) { 2499 if (existingIt->second) 2500 results.push_back(existingIt->second); 2501 return success(existingIt->second != nullptr); 2502 } 2503 auto multiIt = cachedMultiConversions.find(t); 2504 if (multiIt != cachedMultiConversions.end()) { 2505 results.append(multiIt->second.begin(), multiIt->second.end()); 2506 return success(); 2507 } 2508 2509 // Walk the added converters in reverse order to apply the most recently 2510 // registered first. 2511 size_t currentCount = results.size(); 2512 for (ConversionCallbackFn &converter : llvm::reverse(conversions)) { 2513 if (Optional<LogicalResult> result = converter(t, results)) { 2514 if (!succeeded(*result)) { 2515 cachedDirectConversions.try_emplace(t, nullptr); 2516 return failure(); 2517 } 2518 auto newTypes = ArrayRef<Type>(results).drop_front(currentCount); 2519 if (newTypes.size() == 1) 2520 cachedDirectConversions.try_emplace(t, newTypes.front()); 2521 else 2522 cachedMultiConversions.try_emplace(t, llvm::to_vector<2>(newTypes)); 2523 return success(); 2524 } 2525 } 2526 return failure(); 2527 } 2528 2529 /// This hook simplifies defining 1-1 type conversions. This function returns 2530 /// the type to convert to on success, and a null type on failure. 2531 Type TypeConverter::convertType(Type t) { 2532 // Use the multi-type result version to convert the type. 2533 SmallVector<Type, 1> results; 2534 if (failed(convertType(t, results))) 2535 return nullptr; 2536 2537 // Check to ensure that only one type was produced. 2538 return results.size() == 1 ? results.front() : nullptr; 2539 } 2540 2541 /// Convert the given set of types, filling 'results' as necessary. This 2542 /// returns failure if the conversion of any of the types fails, success 2543 /// otherwise. 2544 LogicalResult TypeConverter::convertTypes(TypeRange types, 2545 SmallVectorImpl<Type> &results) { 2546 for (Type type : types) 2547 if (failed(convertType(type, results))) 2548 return failure(); 2549 return success(); 2550 } 2551 2552 /// Return true if the given type is legal for this type converter, i.e. the 2553 /// type converts to itself. 2554 bool TypeConverter::isLegal(Type type) { return convertType(type) == type; } 2555 /// Return true if the given operation has legal operand and result types. 2556 bool TypeConverter::isLegal(Operation *op) { 2557 return isLegal(op->getOperandTypes()) && isLegal(op->getResultTypes()); 2558 } 2559 2560 /// Return true if the types of block arguments within the region are legal. 2561 bool TypeConverter::isLegal(Region *region) { 2562 return llvm::all_of(*region, [this](Block &block) { 2563 return isLegal(block.getArgumentTypes()); 2564 }); 2565 } 2566 2567 /// Return true if the inputs and outputs of the given function type are 2568 /// legal. 2569 bool TypeConverter::isSignatureLegal(FunctionType ty) { 2570 return isLegal(llvm::concat<const Type>(ty.getInputs(), ty.getResults())); 2571 } 2572 2573 /// This hook allows for converting a specific argument of a signature. 2574 LogicalResult TypeConverter::convertSignatureArg(unsigned inputNo, Type type, 2575 SignatureConversion &result) { 2576 // Try to convert the given input type. 2577 SmallVector<Type, 1> convertedTypes; 2578 if (failed(convertType(type, convertedTypes))) 2579 return failure(); 2580 2581 // If this argument is being dropped, there is nothing left to do. 2582 if (convertedTypes.empty()) 2583 return success(); 2584 2585 // Otherwise, add the new inputs. 2586 result.addInputs(inputNo, convertedTypes); 2587 return success(); 2588 } 2589 LogicalResult TypeConverter::convertSignatureArgs(TypeRange types, 2590 SignatureConversion &result, 2591 unsigned origInputOffset) { 2592 for (unsigned i = 0, e = types.size(); i != e; ++i) 2593 if (failed(convertSignatureArg(origInputOffset + i, types[i], result))) 2594 return failure(); 2595 return success(); 2596 } 2597 2598 Value TypeConverter::materializeConversion( 2599 MutableArrayRef<MaterializationCallbackFn> materializations, 2600 OpBuilder &builder, Location loc, Type resultType, ValueRange inputs) { 2601 for (MaterializationCallbackFn &fn : llvm::reverse(materializations)) 2602 if (Optional<Value> result = fn(builder, resultType, inputs, loc)) 2603 return result.getValue(); 2604 return nullptr; 2605 } 2606 2607 /// This function converts the type signature of the given block, by invoking 2608 /// 'convertSignatureArg' for each argument. This function should return a valid 2609 /// conversion for the signature on success, None otherwise. 2610 auto TypeConverter::convertBlockSignature(Block *block) 2611 -> Optional<SignatureConversion> { 2612 SignatureConversion conversion(block->getNumArguments()); 2613 if (failed(convertSignatureArgs(block->getArgumentTypes(), conversion))) 2614 return llvm::None; 2615 return conversion; 2616 } 2617 2618 /// Create a default conversion pattern that rewrites the type signature of a 2619 /// FunctionLike op. This only supports FunctionLike ops which use FunctionType 2620 /// to represent their type. 2621 namespace { 2622 struct FunctionLikeSignatureConversion : public ConversionPattern { 2623 FunctionLikeSignatureConversion(StringRef functionLikeOpName, 2624 MLIRContext *ctx, TypeConverter &converter) 2625 : ConversionPattern(converter, functionLikeOpName, /*benefit=*/1, ctx) {} 2626 2627 /// Hook to implement combined matching and rewriting for FunctionLike ops. 2628 LogicalResult 2629 matchAndRewrite(Operation *op, ArrayRef<Value> operands, 2630 ConversionPatternRewriter &rewriter) const override { 2631 FunctionType type = function_like_impl::getFunctionType(op); 2632 2633 // Convert the original function types. 2634 TypeConverter::SignatureConversion result(type.getNumInputs()); 2635 SmallVector<Type, 1> newResults; 2636 if (failed(typeConverter->convertSignatureArgs(type.getInputs(), result)) || 2637 failed(typeConverter->convertTypes(type.getResults(), newResults)) || 2638 failed(rewriter.convertRegionTypes( 2639 &function_like_impl::getFunctionBody(op), *typeConverter, &result))) 2640 return failure(); 2641 2642 // Update the function signature in-place. 2643 auto newType = FunctionType::get(rewriter.getContext(), 2644 result.getConvertedTypes(), newResults); 2645 2646 rewriter.updateRootInPlace( 2647 op, [&] { function_like_impl::setFunctionType(op, newType); }); 2648 2649 return success(); 2650 } 2651 }; 2652 } // end anonymous namespace 2653 2654 void mlir::populateFunctionLikeTypeConversionPattern( 2655 StringRef functionLikeOpName, RewritePatternSet &patterns, 2656 TypeConverter &converter) { 2657 patterns.add<FunctionLikeSignatureConversion>( 2658 functionLikeOpName, patterns.getContext(), converter); 2659 } 2660 2661 void mlir::populateFuncOpTypeConversionPattern(RewritePatternSet &patterns, 2662 TypeConverter &converter) { 2663 populateFunctionLikeTypeConversionPattern<FuncOp>(patterns, converter); 2664 } 2665 2666 //===----------------------------------------------------------------------===// 2667 // ConversionTarget 2668 //===----------------------------------------------------------------------===// 2669 2670 /// Register a legality action for the given operation. 2671 void ConversionTarget::setOpAction(OperationName op, 2672 LegalizationAction action) { 2673 legalOperations[op] = {action, /*isRecursivelyLegal=*/false, llvm::None}; 2674 } 2675 2676 /// Register a legality action for the given dialects. 2677 void ConversionTarget::setDialectAction(ArrayRef<StringRef> dialectNames, 2678 LegalizationAction action) { 2679 for (StringRef dialect : dialectNames) 2680 legalDialects[dialect] = action; 2681 } 2682 2683 /// Get the legality action for the given operation. 2684 auto ConversionTarget::getOpAction(OperationName op) const 2685 -> Optional<LegalizationAction> { 2686 Optional<LegalizationInfo> info = getOpInfo(op); 2687 return info ? info->action : Optional<LegalizationAction>(); 2688 } 2689 2690 /// If the given operation instance is legal on this target, a structure 2691 /// containing legality information is returned. If the operation is not legal, 2692 /// None is returned. 2693 auto ConversionTarget::isLegal(Operation *op) const 2694 -> Optional<LegalOpDetails> { 2695 Optional<LegalizationInfo> info = getOpInfo(op->getName()); 2696 if (!info) 2697 return llvm::None; 2698 2699 // Returns true if this operation instance is known to be legal. 2700 auto isOpLegal = [&] { 2701 // Handle dynamic legality either with the provided legality function, or 2702 // the default hook on the derived instance. 2703 if (info->action == LegalizationAction::Dynamic) 2704 return info->legalityFn ? (*info->legalityFn)(op) 2705 : isDynamicallyLegal(op); 2706 2707 // Otherwise, the operation is only legal if it was marked 'Legal'. 2708 return info->action == LegalizationAction::Legal; 2709 }; 2710 if (!isOpLegal()) 2711 return llvm::None; 2712 2713 // This operation is legal, compute any additional legality information. 2714 LegalOpDetails legalityDetails; 2715 if (info->isRecursivelyLegal) { 2716 auto legalityFnIt = opRecursiveLegalityFns.find(op->getName()); 2717 if (legalityFnIt != opRecursiveLegalityFns.end()) 2718 legalityDetails.isRecursivelyLegal = legalityFnIt->second(op); 2719 else 2720 legalityDetails.isRecursivelyLegal = true; 2721 } 2722 return legalityDetails; 2723 } 2724 2725 /// Set the dynamic legality callback for the given operation. 2726 void ConversionTarget::setLegalityCallback( 2727 OperationName name, const DynamicLegalityCallbackFn &callback) { 2728 assert(callback && "expected valid legality callback"); 2729 auto infoIt = legalOperations.find(name); 2730 assert(infoIt != legalOperations.end() && 2731 infoIt->second.action == LegalizationAction::Dynamic && 2732 "expected operation to already be marked as dynamically legal"); 2733 infoIt->second.legalityFn = callback; 2734 } 2735 2736 /// Set the recursive legality callback for the given operation and mark the 2737 /// operation as recursively legal. 2738 void ConversionTarget::markOpRecursivelyLegal( 2739 OperationName name, const DynamicLegalityCallbackFn &callback) { 2740 auto infoIt = legalOperations.find(name); 2741 assert(infoIt != legalOperations.end() && 2742 infoIt->second.action != LegalizationAction::Illegal && 2743 "expected operation to already be marked as legal"); 2744 infoIt->second.isRecursivelyLegal = true; 2745 if (callback) 2746 opRecursiveLegalityFns[name] = callback; 2747 else 2748 opRecursiveLegalityFns.erase(name); 2749 } 2750 2751 /// Set the dynamic legality callback for the given dialects. 2752 void ConversionTarget::setLegalityCallback( 2753 ArrayRef<StringRef> dialects, const DynamicLegalityCallbackFn &callback) { 2754 assert(callback && "expected valid legality callback"); 2755 for (StringRef dialect : dialects) 2756 dialectLegalityFns[dialect] = callback; 2757 } 2758 2759 /// Get the legalization information for the given operation. 2760 auto ConversionTarget::getOpInfo(OperationName op) const 2761 -> Optional<LegalizationInfo> { 2762 // Check for info for this specific operation. 2763 auto it = legalOperations.find(op); 2764 if (it != legalOperations.end()) 2765 return it->second; 2766 // Check for info for the parent dialect. 2767 auto dialectIt = legalDialects.find(op.getDialectNamespace()); 2768 if (dialectIt != legalDialects.end()) { 2769 Optional<DynamicLegalityCallbackFn> callback; 2770 auto dialectFn = dialectLegalityFns.find(op.getDialectNamespace()); 2771 if (dialectFn != dialectLegalityFns.end()) 2772 callback = dialectFn->second; 2773 return LegalizationInfo{dialectIt->second, /*isRecursivelyLegal=*/false, 2774 callback}; 2775 } 2776 // Otherwise, check if we mark unknown operations as dynamic. 2777 if (unknownOpsDynamicallyLegal) 2778 return LegalizationInfo{LegalizationAction::Dynamic, 2779 /*isRecursivelyLegal=*/false, unknownLegalityFn}; 2780 return llvm::None; 2781 } 2782 2783 //===----------------------------------------------------------------------===// 2784 // Op Conversion Entry Points 2785 //===----------------------------------------------------------------------===// 2786 2787 /// Apply a partial conversion on the given operations and all nested 2788 /// operations. This method converts as many operations to the target as 2789 /// possible, ignoring operations that failed to legalize. This method only 2790 /// returns failure if there ops explicitly marked as illegal. 2791 /// If an `unconvertedOps` set is provided, all operations that are found not 2792 /// to be legalizable to the given `target` are placed within that set. (Note 2793 /// that if there is an op explicitly marked as illegal, the conversion 2794 /// terminates and the `unconvertedOps` set will not necessarily be complete.) 2795 LogicalResult 2796 mlir::applyPartialConversion(ArrayRef<Operation *> ops, 2797 ConversionTarget &target, 2798 const FrozenRewritePatternSet &patterns, 2799 DenseSet<Operation *> *unconvertedOps) { 2800 OperationConverter opConverter(target, patterns, OpConversionMode::Partial, 2801 unconvertedOps); 2802 return opConverter.convertOperations(ops); 2803 } 2804 LogicalResult 2805 mlir::applyPartialConversion(Operation *op, ConversionTarget &target, 2806 const FrozenRewritePatternSet &patterns, 2807 DenseSet<Operation *> *unconvertedOps) { 2808 return applyPartialConversion(llvm::makeArrayRef(op), target, patterns, 2809 unconvertedOps); 2810 } 2811 2812 /// Apply a complete conversion on the given operations, and all nested 2813 /// operations. This method will return failure if the conversion of any 2814 /// operation fails. 2815 LogicalResult 2816 mlir::applyFullConversion(ArrayRef<Operation *> ops, ConversionTarget &target, 2817 const FrozenRewritePatternSet &patterns) { 2818 OperationConverter opConverter(target, patterns, OpConversionMode::Full); 2819 return opConverter.convertOperations(ops); 2820 } 2821 LogicalResult 2822 mlir::applyFullConversion(Operation *op, ConversionTarget &target, 2823 const FrozenRewritePatternSet &patterns) { 2824 return applyFullConversion(llvm::makeArrayRef(op), target, patterns); 2825 } 2826 2827 /// Apply an analysis conversion on the given operations, and all nested 2828 /// operations. This method analyzes which operations would be successfully 2829 /// converted to the target if a conversion was applied. All operations that 2830 /// were found to be legalizable to the given 'target' are placed within the 2831 /// provided 'convertedOps' set; note that no actual rewrites are applied to the 2832 /// operations on success and only pre-existing operations are added to the set. 2833 LogicalResult 2834 mlir::applyAnalysisConversion(ArrayRef<Operation *> ops, 2835 ConversionTarget &target, 2836 const FrozenRewritePatternSet &patterns, 2837 DenseSet<Operation *> &convertedOps) { 2838 OperationConverter opConverter(target, patterns, OpConversionMode::Analysis, 2839 &convertedOps); 2840 return opConverter.convertOperations(ops); 2841 } 2842 LogicalResult 2843 mlir::applyAnalysisConversion(Operation *op, ConversionTarget &target, 2844 const FrozenRewritePatternSet &patterns, 2845 DenseSet<Operation *> &convertedOps) { 2846 return applyAnalysisConversion(llvm::makeArrayRef(op), target, patterns, 2847 convertedOps); 2848 } 2849