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