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