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