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