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