1 //===- DialectConversion.cpp - MLIR dialect conversion generic pass -------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 9 #include "mlir/Transforms/DialectConversion.h" 10 #include "mlir/IR/Block.h" 11 #include "mlir/IR/BlockAndValueMapping.h" 12 #include "mlir/IR/Builders.h" 13 #include "mlir/IR/BuiltinOps.h" 14 #include "mlir/IR/FunctionSupport.h" 15 #include "mlir/Rewrite/PatternApplicator.h" 16 #include "mlir/Transforms/Utils.h" 17 #include "llvm/ADT/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 } // end anonymous 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 (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 } // end anonymous 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 } // end anonymous 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 SmallVector<Value, 4> newArgRange(newBlock->addArguments(convertedTypes)); 767 ArrayRef<Value> newArgs(newArgRange); 768 769 // Remap each of the original arguments as determined by the signature 770 // conversion. 771 ConvertedBlockInfo info(block, converter); 772 info.argInfo.resize(origArgCount); 773 774 OpBuilder::InsertionGuard guard(rewriter); 775 rewriter.setInsertionPointToStart(newBlock); 776 for (unsigned i = 0; i != origArgCount; ++i) { 777 auto inputMap = signatureConversion.getInputMapping(i); 778 if (!inputMap) 779 continue; 780 BlockArgument origArg = block->getArgument(i); 781 782 // If inputMap->replacementValue is not nullptr, then the argument is 783 // dropped and a replacement value is provided to be the remappedValue. 784 if (inputMap->replacementValue) { 785 assert(inputMap->size == 0 && 786 "invalid to provide a replacement value when the argument isn't " 787 "dropped"); 788 mapping.map(origArg, inputMap->replacementValue); 789 argReplacements.push_back(origArg); 790 continue; 791 } 792 793 // Otherwise, this is a 1->1+ mapping. 794 auto replArgs = newArgs.slice(inputMap->inputNo, inputMap->size); 795 Value newArg; 796 797 // If this is a 1->1 mapping and the types of new and replacement arguments 798 // match (i.e. it's an identity map), then the argument is mapped to its 799 // original type. 800 // FIXME: We simply pass through the replacement argument if there wasn't a 801 // converter, which isn't great as it allows implicit type conversions to 802 // appear. We should properly restructure this code to handle cases where a 803 // converter isn't provided and also to properly handle the case where an 804 // argument materialization is actually a temporary source materialization 805 // (e.g. in the case of 1->N). 806 if (replArgs.size() == 1 && 807 (!converter || replArgs[0].getType() == origArg.getType())) { 808 newArg = replArgs.front(); 809 } else { 810 Type origOutputType = origArg.getType(); 811 812 // Legalize the argument output type. 813 Type outputType = origOutputType; 814 if (Type legalOutputType = converter->convertType(outputType)) 815 outputType = legalOutputType; 816 817 newArg = buildUnresolvedArgumentMaterialization( 818 rewriter, origArg.getLoc(), replArgs, origOutputType, outputType, 819 converter, unresolvedMaterializations); 820 } 821 822 mapping.map(origArg, newArg); 823 argReplacements.push_back(origArg); 824 info.argInfo[i] = 825 ConvertedArgInfo(inputMap->inputNo, inputMap->size, newArg); 826 } 827 828 // Remove the original block from the region and return the new one. 829 insertConversion(newBlock, std::move(info)); 830 return newBlock; 831 } 832 833 void ArgConverter::insertConversion(Block *newBlock, 834 ConvertedBlockInfo &&info) { 835 // Get a region to insert the old block. 836 Region *region = newBlock->getParent(); 837 std::unique_ptr<Region> &mappedRegion = regionMapping[region]; 838 if (!mappedRegion) 839 mappedRegion = std::make_unique<Region>(region->getParentOp()); 840 841 // Move the original block to the mapped region and emplace the conversion. 842 mappedRegion->getBlocks().splice(mappedRegion->end(), region->getBlocks(), 843 info.origBlock->getIterator()); 844 convertedBlocks.insert(info.origBlock); 845 conversionInfo.insert({newBlock, std::move(info)}); 846 } 847 848 //===----------------------------------------------------------------------===// 849 // ConversionPatternRewriterImpl 850 //===----------------------------------------------------------------------===// 851 namespace mlir { 852 namespace detail { 853 struct ConversionPatternRewriterImpl { 854 ConversionPatternRewriterImpl(PatternRewriter &rewriter) 855 : argConverter(rewriter, unresolvedMaterializations) {} 856 857 /// Cleanup and destroy any generated rewrite operations. This method is 858 /// invoked when the conversion process fails. 859 void discardRewrites(); 860 861 /// Apply all requested operation rewrites. This method is invoked when the 862 /// conversion process succeeds. 863 void applyRewrites(); 864 865 //===--------------------------------------------------------------------===// 866 // State Management 867 //===--------------------------------------------------------------------===// 868 869 /// Return the current state of the rewriter. 870 RewriterState getCurrentState(); 871 872 /// Reset the state of the rewriter to a previously saved point. 873 void resetState(RewriterState state); 874 875 /// Erase any blocks that were unlinked from their regions and stored in block 876 /// actions. 877 void eraseDanglingBlocks(); 878 879 /// Undo the block actions (motions, splits) one by one in reverse order until 880 /// "numActionsToKeep" actions remains. 881 void undoBlockActions(unsigned numActionsToKeep = 0); 882 883 /// Remap the given values to those with potentially different types. Returns 884 /// success if the values could be remapped, failure otherwise. `valueDiagTag` 885 /// is the tag used when describing a value within a diagnostic, e.g. 886 /// "operand". 887 LogicalResult remapValues(StringRef valueDiagTag, Optional<Location> inputLoc, 888 PatternRewriter &rewriter, ValueRange values, 889 SmallVectorImpl<Value> &remapped); 890 891 /// Returns true if the given operation is ignored, and does not need to be 892 /// converted. 893 bool isOpIgnored(Operation *op) const; 894 895 /// Recursively marks the nested operations under 'op' as ignored. This 896 /// removes them from being considered for legalization. 897 void markNestedOpsIgnored(Operation *op); 898 899 //===--------------------------------------------------------------------===// 900 // Type Conversion 901 //===--------------------------------------------------------------------===// 902 903 /// Convert the signature of the given block. 904 FailureOr<Block *> convertBlockSignature( 905 Block *block, TypeConverter *converter, 906 TypeConverter::SignatureConversion *conversion = nullptr); 907 908 /// Apply a signature conversion on the given region, using `converter` for 909 /// materializations if not null. 910 Block * 911 applySignatureConversion(Region *region, 912 TypeConverter::SignatureConversion &conversion, 913 TypeConverter *converter); 914 915 /// Convert the types of block arguments within the given region. 916 FailureOr<Block *> 917 convertRegionTypes(Region *region, TypeConverter &converter, 918 TypeConverter::SignatureConversion *entryConversion); 919 920 /// Convert the types of non-entry block arguments within the given region. 921 LogicalResult convertNonEntryRegionTypes( 922 Region *region, TypeConverter &converter, 923 ArrayRef<TypeConverter::SignatureConversion> blockConversions = {}); 924 925 //===--------------------------------------------------------------------===// 926 // Rewriter Notification Hooks 927 //===--------------------------------------------------------------------===// 928 929 /// PatternRewriter hook for replacing the results of an operation. 930 void notifyOpReplaced(Operation *op, ValueRange newValues); 931 932 /// Notifies that a block is about to be erased. 933 void notifyBlockIsBeingErased(Block *block); 934 935 /// Notifies that a block was created. 936 void notifyCreatedBlock(Block *block); 937 938 /// Notifies that a block was split. 939 void notifySplitBlock(Block *block, Block *continuation); 940 941 /// Notifies that `block` is being merged with `srcBlock`. 942 void notifyBlocksBeingMerged(Block *block, Block *srcBlock); 943 944 /// Notifies that the blocks of a region are about to be moved. 945 void notifyRegionIsBeingInlinedBefore(Region ®ion, Region &parent, 946 Region::iterator before); 947 948 /// Notifies that the blocks of a region were cloned into another. 949 void notifyRegionWasClonedBefore(iterator_range<Region::iterator> &blocks, 950 Location origRegionLoc); 951 952 /// Notifies that a pattern match failed for the given reason. 953 LogicalResult 954 notifyMatchFailure(Location loc, 955 function_ref<void(Diagnostic &)> reasonCallback); 956 957 //===--------------------------------------------------------------------===// 958 // State 959 //===--------------------------------------------------------------------===// 960 961 // Mapping between replaced values that differ in type. This happens when 962 // replacing a value with one of a different type. 963 ConversionValueMapping mapping; 964 965 /// Utility used to convert block arguments. 966 ArgConverter argConverter; 967 968 /// Ordered vector of all of the newly created operations during conversion. 969 SmallVector<Operation *> createdOps; 970 971 /// Ordered vector of all unresolved type conversion materializations during 972 /// conversion. 973 SmallVector<UnresolvedMaterialization> unresolvedMaterializations; 974 975 /// Ordered map of requested operation replacements. 976 llvm::MapVector<Operation *, OpReplacement> replacements; 977 978 /// Ordered vector of any requested block argument replacements. 979 SmallVector<BlockArgument, 4> argReplacements; 980 981 /// Ordered list of block operations (creations, splits, motions). 982 SmallVector<BlockAction, 4> blockActions; 983 984 /// A set of operations that should no longer be considered for legalization, 985 /// but were not directly replace/erased/etc. by a pattern. These are 986 /// generally child operations of other operations who were 987 /// replaced/erased/etc. This is not meant to be an exhaustive list of all 988 /// operations, but the minimal set that can be used to detect if a given 989 /// operation should be `ignored`. For example, we may add the operations that 990 /// define non-empty regions to the set, but not any of the others. This 991 /// simplifies the amount of memory needed as we can query if the parent 992 /// operation was ignored. 993 SetVector<Operation *> ignoredOps; 994 995 /// A transaction state for each of operations that were updated in-place. 996 SmallVector<OperationTransactionState, 4> rootUpdates; 997 998 /// A vector of indices into `replacements` of operations that were replaced 999 /// with values with different result types than the original operation, e.g. 1000 /// 1->N conversion of some kind. 1001 SmallVector<unsigned, 4> operationsWithChangedResults; 1002 1003 /// The current type converter, or nullptr if no type converter is currently 1004 /// active. 1005 TypeConverter *currentTypeConverter = nullptr; 1006 1007 #ifndef NDEBUG 1008 /// A set of operations that have pending updates. This tracking isn't 1009 /// strictly necessary, and is thus only active during debug builds for extra 1010 /// verification. 1011 SmallPtrSet<Operation *, 1> pendingRootUpdates; 1012 1013 /// A logger used to emit diagnostics during the conversion process. 1014 llvm::ScopedPrinter logger{llvm::dbgs()}; 1015 #endif 1016 }; 1017 } // end namespace detail 1018 } // end namespace mlir 1019 1020 /// Detach any operations nested in the given operation from their parent 1021 /// blocks, and erase the given operation. This can be used when the nested 1022 /// operations are scheduled for erasure themselves, so deleting the regions of 1023 /// the given operation together with their content would result in double-free. 1024 /// This happens, for example, when rolling back op creation in the reverse 1025 /// order and if the nested ops were created before the parent op. This function 1026 /// does not need to collect nested ops recursively because it is expected to 1027 /// also be called for each nested op when it is about to be deleted. 1028 static void detachNestedAndErase(Operation *op) { 1029 for (Region ®ion : op->getRegions()) { 1030 for (Block &block : region.getBlocks()) { 1031 while (!block.getOperations().empty()) 1032 block.getOperations().remove(block.getOperations().begin()); 1033 block.dropAllDefinedValueUses(); 1034 } 1035 } 1036 op->dropAllUses(); 1037 op->erase(); 1038 } 1039 1040 void ConversionPatternRewriterImpl::discardRewrites() { 1041 // Reset any operations that were updated in place. 1042 for (auto &state : rootUpdates) 1043 state.resetOperation(); 1044 1045 undoBlockActions(); 1046 1047 // Remove any newly created ops. 1048 for (UnresolvedMaterialization &materialization : unresolvedMaterializations) 1049 detachNestedAndErase(materialization.getOp()); 1050 for (auto *op : llvm::reverse(createdOps)) 1051 detachNestedAndErase(op); 1052 } 1053 1054 void ConversionPatternRewriterImpl::applyRewrites() { 1055 // Apply all of the rewrites replacements requested during conversion. 1056 for (auto &repl : replacements) { 1057 for (OpResult result : repl.first->getResults()) 1058 if (Value newValue = mapping.lookupOrNull(result, result.getType())) 1059 result.replaceAllUsesWith(newValue); 1060 1061 // If this operation defines any regions, drop any pending argument 1062 // rewrites. 1063 if (repl.first->getNumRegions()) 1064 argConverter.notifyOpRemoved(repl.first); 1065 } 1066 1067 // Apply all of the requested argument replacements. 1068 for (BlockArgument arg : argReplacements) { 1069 Value repl = mapping.lookupOrNull(arg, arg.getType()); 1070 if (!repl) 1071 continue; 1072 1073 if (repl.isa<BlockArgument>()) { 1074 arg.replaceAllUsesWith(repl); 1075 continue; 1076 } 1077 1078 // If the replacement value is an operation, we check to make sure that we 1079 // don't replace uses that are within the parent operation of the 1080 // replacement value. 1081 Operation *replOp = repl.cast<OpResult>().getOwner(); 1082 Block *replBlock = replOp->getBlock(); 1083 arg.replaceUsesWithIf(repl, [&](OpOperand &operand) { 1084 Operation *user = operand.getOwner(); 1085 return user->getBlock() != replBlock || replOp->isBeforeInBlock(user); 1086 }); 1087 } 1088 1089 // Drop all of the unresolved materialization operations created during 1090 // conversion. 1091 for (auto &mat : unresolvedMaterializations) { 1092 mat.getOp()->dropAllUses(); 1093 mat.getOp()->erase(); 1094 } 1095 1096 // In a second pass, erase all of the replaced operations in reverse. This 1097 // allows processing nested operations before their parent region is 1098 // destroyed. Because we process in reverse order, producers may be deleted 1099 // before their users (a pattern deleting a producer and then the consumer) 1100 // so we first drop all uses explicitly. 1101 for (auto &repl : llvm::reverse(replacements)) { 1102 repl.first->dropAllUses(); 1103 repl.first->erase(); 1104 } 1105 1106 argConverter.applyRewrites(mapping); 1107 1108 // Now that the ops have been erased, also erase dangling blocks. 1109 eraseDanglingBlocks(); 1110 } 1111 1112 //===----------------------------------------------------------------------===// 1113 // State Management 1114 1115 RewriterState ConversionPatternRewriterImpl::getCurrentState() { 1116 return RewriterState(createdOps.size(), unresolvedMaterializations.size(), 1117 replacements.size(), argReplacements.size(), 1118 blockActions.size(), ignoredOps.size(), 1119 rootUpdates.size()); 1120 } 1121 1122 void ConversionPatternRewriterImpl::resetState(RewriterState state) { 1123 // Reset any operations that were updated in place. 1124 for (unsigned i = state.numRootUpdates, e = rootUpdates.size(); i != e; ++i) 1125 rootUpdates[i].resetOperation(); 1126 rootUpdates.resize(state.numRootUpdates); 1127 1128 // Reset any replaced arguments. 1129 for (BlockArgument replacedArg : 1130 llvm::drop_begin(argReplacements, state.numArgReplacements)) 1131 mapping.erase(replacedArg); 1132 argReplacements.resize(state.numArgReplacements); 1133 1134 // Undo any block actions. 1135 undoBlockActions(state.numBlockActions); 1136 1137 // Reset any replaced operations and undo any saved mappings. 1138 for (auto &repl : llvm::drop_begin(replacements, state.numReplacements)) 1139 for (auto result : repl.first->getResults()) 1140 mapping.erase(result); 1141 while (replacements.size() != state.numReplacements) 1142 replacements.pop_back(); 1143 1144 // Pop all of the newly inserted materializations. 1145 while (unresolvedMaterializations.size() != 1146 state.numUnresolvedMaterializations) { 1147 UnresolvedMaterialization mat = unresolvedMaterializations.pop_back_val(); 1148 UnrealizedConversionCastOp op = mat.getOp(); 1149 1150 // If this was a target materialization, drop the mapping that was inserted. 1151 if (mat.getKind() == UnresolvedMaterialization::Target) { 1152 for (Value input : op->getOperands()) 1153 mapping.erase(input); 1154 } 1155 detachNestedAndErase(op); 1156 } 1157 1158 // Pop all of the newly created operations. 1159 while (createdOps.size() != state.numCreatedOps) { 1160 detachNestedAndErase(createdOps.back()); 1161 createdOps.pop_back(); 1162 } 1163 1164 // Pop all of the recorded ignored operations that are no longer valid. 1165 while (ignoredOps.size() != state.numIgnoredOperations) 1166 ignoredOps.pop_back(); 1167 1168 // Reset operations with changed results. 1169 while (!operationsWithChangedResults.empty() && 1170 operationsWithChangedResults.back() >= state.numReplacements) 1171 operationsWithChangedResults.pop_back(); 1172 } 1173 1174 void ConversionPatternRewriterImpl::eraseDanglingBlocks() { 1175 for (auto &action : blockActions) 1176 if (action.kind == BlockActionKind::Erase) 1177 delete action.block; 1178 } 1179 1180 void ConversionPatternRewriterImpl::undoBlockActions( 1181 unsigned numActionsToKeep) { 1182 for (auto &action : 1183 llvm::reverse(llvm::drop_begin(blockActions, numActionsToKeep))) { 1184 switch (action.kind) { 1185 // Delete the created block. 1186 case BlockActionKind::Create: { 1187 // Unlink all of the operations within this block, they will be deleted 1188 // separately. 1189 auto &blockOps = action.block->getOperations(); 1190 while (!blockOps.empty()) 1191 blockOps.remove(blockOps.begin()); 1192 action.block->dropAllDefinedValueUses(); 1193 action.block->erase(); 1194 break; 1195 } 1196 // Put the block (owned by action) back into its original position. 1197 case BlockActionKind::Erase: { 1198 auto &blockList = action.originalPosition.region->getBlocks(); 1199 Block *insertAfterBlock = action.originalPosition.insertAfterBlock; 1200 blockList.insert((insertAfterBlock 1201 ? std::next(Region::iterator(insertAfterBlock)) 1202 : blockList.begin()), 1203 action.block); 1204 break; 1205 } 1206 // Split the block at the position which was originally the end of the 1207 // destination block (owned by action), and put the instructions back into 1208 // the block used before the merge. 1209 case BlockActionKind::Merge: { 1210 Block *sourceBlock = action.mergeInfo.sourceBlock; 1211 Block::iterator splitPoint = 1212 (action.mergeInfo.destBlockLastInst 1213 ? ++Block::iterator(action.mergeInfo.destBlockLastInst) 1214 : action.block->begin()); 1215 sourceBlock->getOperations().splice(sourceBlock->begin(), 1216 action.block->getOperations(), 1217 splitPoint, action.block->end()); 1218 break; 1219 } 1220 // Move the block back to its original position. 1221 case BlockActionKind::Move: { 1222 Region *originalRegion = action.originalPosition.region; 1223 Block *insertAfterBlock = action.originalPosition.insertAfterBlock; 1224 originalRegion->getBlocks().splice( 1225 (insertAfterBlock ? std::next(Region::iterator(insertAfterBlock)) 1226 : originalRegion->end()), 1227 action.block->getParent()->getBlocks(), action.block); 1228 break; 1229 } 1230 // Merge back the block that was split out. 1231 case BlockActionKind::Split: { 1232 action.originalBlock->getOperations().splice( 1233 action.originalBlock->end(), action.block->getOperations()); 1234 action.block->dropAllDefinedValueUses(); 1235 action.block->erase(); 1236 break; 1237 } 1238 // Undo the type conversion. 1239 case BlockActionKind::TypeConversion: { 1240 argConverter.discardRewrites(action.block); 1241 break; 1242 } 1243 } 1244 } 1245 blockActions.resize(numActionsToKeep); 1246 } 1247 1248 LogicalResult ConversionPatternRewriterImpl::remapValues( 1249 StringRef valueDiagTag, Optional<Location> inputLoc, 1250 PatternRewriter &rewriter, ValueRange values, 1251 SmallVectorImpl<Value> &remapped) { 1252 remapped.reserve(llvm::size(values)); 1253 1254 SmallVector<Type, 1> legalTypes; 1255 for (auto it : llvm::enumerate(values)) { 1256 Value operand = it.value(); 1257 Type origType = operand.getType(); 1258 1259 // If a converter was provided, get the desired legal types for this 1260 // operand. 1261 Type desiredType; 1262 if (currentTypeConverter) { 1263 // If there is no legal conversion, fail to match this pattern. 1264 legalTypes.clear(); 1265 if (failed(currentTypeConverter->convertType(origType, legalTypes))) { 1266 Location operandLoc = inputLoc ? *inputLoc : operand.getLoc(); 1267 return notifyMatchFailure(operandLoc, [=](Diagnostic &diag) { 1268 diag << "unable to convert type for " << valueDiagTag << " #" 1269 << it.index() << ", type was " << origType; 1270 }); 1271 } 1272 // TODO: There currently isn't any mechanism to do 1->N type conversion 1273 // via the PatternRewriter replacement API, so for now we just ignore it. 1274 if (legalTypes.size() == 1) 1275 desiredType = legalTypes.front(); 1276 } else { 1277 // TODO: What we should do here is just set `desiredType` to `origType` 1278 // and then handle the necessary type conversions after the conversion 1279 // process has finished. Unfortunately a lot of patterns currently rely on 1280 // receiving the new operands even if the types change, so we keep the 1281 // original behavior here for now until all of the patterns relying on 1282 // this get updated. 1283 } 1284 Value newOperand = mapping.lookupOrDefault(operand, desiredType); 1285 1286 // Handle the case where the conversion was 1->1 and the new operand type 1287 // isn't legal. 1288 Type newOperandType = newOperand.getType(); 1289 if (currentTypeConverter && desiredType && newOperandType != desiredType) { 1290 Location operandLoc = inputLoc ? *inputLoc : operand.getLoc(); 1291 Value castValue = buildUnresolvedTargetMaterialization( 1292 operandLoc, newOperand, desiredType, currentTypeConverter, 1293 unresolvedMaterializations); 1294 mapping.map(mapping.lookupOrDefault(newOperand), castValue); 1295 newOperand = castValue; 1296 } 1297 remapped.push_back(newOperand); 1298 } 1299 return success(); 1300 } 1301 1302 bool ConversionPatternRewriterImpl::isOpIgnored(Operation *op) const { 1303 // Check to see if this operation was replaced or its parent ignored. 1304 return replacements.count(op) || ignoredOps.count(op->getParentOp()); 1305 } 1306 1307 void ConversionPatternRewriterImpl::markNestedOpsIgnored(Operation *op) { 1308 // Walk this operation and collect nested operations that define non-empty 1309 // regions. We mark such operations as 'ignored' so that we know we don't have 1310 // to convert them, or their nested ops. 1311 if (op->getNumRegions() == 0) 1312 return; 1313 op->walk([&](Operation *op) { 1314 if (llvm::any_of(op->getRegions(), 1315 [](Region ®ion) { return !region.empty(); })) 1316 ignoredOps.insert(op); 1317 }); 1318 } 1319 1320 //===----------------------------------------------------------------------===// 1321 // Type Conversion 1322 1323 FailureOr<Block *> ConversionPatternRewriterImpl::convertBlockSignature( 1324 Block *block, TypeConverter *converter, 1325 TypeConverter::SignatureConversion *conversion) { 1326 FailureOr<Block *> result = 1327 conversion ? argConverter.applySignatureConversion( 1328 block, converter, *conversion, mapping, argReplacements) 1329 : argConverter.convertSignature(block, converter, mapping, 1330 argReplacements); 1331 if (failed(result)) 1332 return failure(); 1333 if (Block *newBlock = result.getValue()) { 1334 if (newBlock != block) 1335 blockActions.push_back(BlockAction::getTypeConversion(newBlock)); 1336 } 1337 return result; 1338 } 1339 1340 Block *ConversionPatternRewriterImpl::applySignatureConversion( 1341 Region *region, TypeConverter::SignatureConversion &conversion, 1342 TypeConverter *converter) { 1343 if (!region->empty()) 1344 return *convertBlockSignature(®ion->front(), converter, &conversion); 1345 return nullptr; 1346 } 1347 1348 FailureOr<Block *> ConversionPatternRewriterImpl::convertRegionTypes( 1349 Region *region, TypeConverter &converter, 1350 TypeConverter::SignatureConversion *entryConversion) { 1351 argConverter.setConverter(region, &converter); 1352 if (region->empty()) 1353 return nullptr; 1354 1355 if (failed(convertNonEntryRegionTypes(region, converter))) 1356 return failure(); 1357 1358 FailureOr<Block *> newEntry = 1359 convertBlockSignature(®ion->front(), &converter, entryConversion); 1360 return newEntry; 1361 } 1362 1363 LogicalResult ConversionPatternRewriterImpl::convertNonEntryRegionTypes( 1364 Region *region, TypeConverter &converter, 1365 ArrayRef<TypeConverter::SignatureConversion> blockConversions) { 1366 argConverter.setConverter(region, &converter); 1367 if (region->empty()) 1368 return success(); 1369 1370 // Convert the arguments of each block within the region. 1371 int blockIdx = 0; 1372 assert((blockConversions.empty() || 1373 blockConversions.size() == region->getBlocks().size() - 1) && 1374 "expected either to provide no SignatureConversions at all or to " 1375 "provide a SignatureConversion for each non-entry block"); 1376 1377 for (Block &block : 1378 llvm::make_early_inc_range(llvm::drop_begin(*region, 1))) { 1379 TypeConverter::SignatureConversion *blockConversion = 1380 blockConversions.empty() 1381 ? nullptr 1382 : const_cast<TypeConverter::SignatureConversion *>( 1383 &blockConversions[blockIdx++]); 1384 1385 if (failed(convertBlockSignature(&block, &converter, blockConversion))) 1386 return failure(); 1387 } 1388 return success(); 1389 } 1390 1391 //===----------------------------------------------------------------------===// 1392 // Rewriter Notification Hooks 1393 1394 void ConversionPatternRewriterImpl::notifyOpReplaced(Operation *op, 1395 ValueRange newValues) { 1396 assert(newValues.size() == op->getNumResults()); 1397 assert(!replacements.count(op) && "operation was already replaced"); 1398 1399 // Track if any of the results changed, e.g. erased and replaced with null. 1400 bool resultChanged = false; 1401 1402 // Create mappings for each of the new result values. 1403 Value newValue, result; 1404 for (auto it : llvm::zip(newValues, op->getResults())) { 1405 std::tie(newValue, result) = it; 1406 if (!newValue) { 1407 resultChanged = true; 1408 continue; 1409 } 1410 // Remap, and check for any result type changes. 1411 mapping.map(result, newValue); 1412 resultChanged |= (newValue.getType() != result.getType()); 1413 } 1414 if (resultChanged) 1415 operationsWithChangedResults.push_back(replacements.size()); 1416 1417 // Record the requested operation replacement. 1418 replacements.insert(std::make_pair(op, OpReplacement(currentTypeConverter))); 1419 1420 // Mark this operation as recursively ignored so that we don't need to 1421 // convert any nested operations. 1422 markNestedOpsIgnored(op); 1423 } 1424 1425 void ConversionPatternRewriterImpl::notifyBlockIsBeingErased(Block *block) { 1426 Region *region = block->getParent(); 1427 Block *origPrevBlock = block->getPrevNode(); 1428 blockActions.push_back(BlockAction::getErase(block, {region, origPrevBlock})); 1429 } 1430 1431 void ConversionPatternRewriterImpl::notifyCreatedBlock(Block *block) { 1432 blockActions.push_back(BlockAction::getCreate(block)); 1433 } 1434 1435 void ConversionPatternRewriterImpl::notifySplitBlock(Block *block, 1436 Block *continuation) { 1437 blockActions.push_back(BlockAction::getSplit(continuation, block)); 1438 } 1439 1440 void ConversionPatternRewriterImpl::notifyBlocksBeingMerged(Block *block, 1441 Block *srcBlock) { 1442 blockActions.push_back(BlockAction::getMerge(block, srcBlock)); 1443 } 1444 1445 void ConversionPatternRewriterImpl::notifyRegionIsBeingInlinedBefore( 1446 Region ®ion, Region &parent, Region::iterator before) { 1447 if (region.empty()) 1448 return; 1449 Block *laterBlock = ®ion.back(); 1450 for (auto &earlierBlock : llvm::drop_begin(llvm::reverse(region), 1)) { 1451 blockActions.push_back( 1452 BlockAction::getMove(laterBlock, {®ion, &earlierBlock})); 1453 laterBlock = &earlierBlock; 1454 } 1455 blockActions.push_back(BlockAction::getMove(laterBlock, {®ion, nullptr})); 1456 } 1457 1458 void ConversionPatternRewriterImpl::notifyRegionWasClonedBefore( 1459 iterator_range<Region::iterator> &blocks, Location origRegionLoc) { 1460 for (Block &block : blocks) 1461 blockActions.push_back(BlockAction::getCreate(&block)); 1462 1463 // Compute the conversion set for the inlined region. 1464 auto result = computeConversionSet(blocks, origRegionLoc, createdOps); 1465 1466 // This original region has already had its conversion set computed, so there 1467 // shouldn't be any new failures. 1468 (void)result; 1469 assert(succeeded(result) && "expected region to have no unreachable blocks"); 1470 } 1471 1472 LogicalResult ConversionPatternRewriterImpl::notifyMatchFailure( 1473 Location loc, function_ref<void(Diagnostic &)> reasonCallback) { 1474 LLVM_DEBUG({ 1475 Diagnostic diag(loc, DiagnosticSeverity::Remark); 1476 reasonCallback(diag); 1477 logger.startLine() << "** Failure : " << diag.str() << "\n"; 1478 }); 1479 return failure(); 1480 } 1481 1482 //===----------------------------------------------------------------------===// 1483 // ConversionPatternRewriter 1484 //===----------------------------------------------------------------------===// 1485 1486 ConversionPatternRewriter::ConversionPatternRewriter(MLIRContext *ctx) 1487 : PatternRewriter(ctx), 1488 impl(new detail::ConversionPatternRewriterImpl(*this)) {} 1489 ConversionPatternRewriter::~ConversionPatternRewriter() {} 1490 1491 void ConversionPatternRewriter::replaceOpWithIf( 1492 Operation *op, ValueRange newValues, bool *allUsesReplaced, 1493 llvm::unique_function<bool(OpOperand &) const> functor) { 1494 // TODO: To support this we will need to rework a bit of how replacements are 1495 // tracked, given that this isn't guranteed to replace all of the uses of an 1496 // operation. The main change is that now an operation can be replaced 1497 // multiple times, in parts. The current "set" based tracking is mainly useful 1498 // for tracking if a replaced operation should be ignored, i.e. if all of the 1499 // uses will be replaced. 1500 llvm_unreachable( 1501 "replaceOpWithIf is currently not supported by DialectConversion"); 1502 } 1503 1504 void ConversionPatternRewriter::replaceOp(Operation *op, ValueRange newValues) { 1505 LLVM_DEBUG({ 1506 impl->logger.startLine() 1507 << "** Replace : '" << op->getName() << "'(" << op << ")\n"; 1508 }); 1509 impl->notifyOpReplaced(op, newValues); 1510 } 1511 1512 void ConversionPatternRewriter::eraseOp(Operation *op) { 1513 LLVM_DEBUG({ 1514 impl->logger.startLine() 1515 << "** Erase : '" << op->getName() << "'(" << op << ")\n"; 1516 }); 1517 SmallVector<Value, 1> nullRepls(op->getNumResults(), nullptr); 1518 impl->notifyOpReplaced(op, nullRepls); 1519 } 1520 1521 void ConversionPatternRewriter::eraseBlock(Block *block) { 1522 impl->notifyBlockIsBeingErased(block); 1523 1524 // Mark all ops for erasure. 1525 for (Operation &op : *block) 1526 eraseOp(&op); 1527 1528 // Unlink the block from its parent region. The block is kept in the block 1529 // action and will be actually destroyed when rewrites are applied. This 1530 // allows us to keep the operations in the block live and undo the removal by 1531 // re-inserting the block. 1532 block->getParent()->getBlocks().remove(block); 1533 } 1534 1535 Block *ConversionPatternRewriter::applySignatureConversion( 1536 Region *region, TypeConverter::SignatureConversion &conversion, 1537 TypeConverter *converter) { 1538 return impl->applySignatureConversion(region, conversion, converter); 1539 } 1540 1541 FailureOr<Block *> ConversionPatternRewriter::convertRegionTypes( 1542 Region *region, TypeConverter &converter, 1543 TypeConverter::SignatureConversion *entryConversion) { 1544 return impl->convertRegionTypes(region, converter, entryConversion); 1545 } 1546 1547 LogicalResult ConversionPatternRewriter::convertNonEntryRegionTypes( 1548 Region *region, TypeConverter &converter, 1549 ArrayRef<TypeConverter::SignatureConversion> blockConversions) { 1550 return impl->convertNonEntryRegionTypes(region, converter, blockConversions); 1551 } 1552 1553 void ConversionPatternRewriter::replaceUsesOfBlockArgument(BlockArgument from, 1554 Value to) { 1555 LLVM_DEBUG({ 1556 Operation *parentOp = from.getOwner()->getParentOp(); 1557 impl->logger.startLine() << "** Replace Argument : '" << from 1558 << "'(in region of '" << parentOp->getName() 1559 << "'(" << from.getOwner()->getParentOp() << ")\n"; 1560 }); 1561 impl->argReplacements.push_back(from); 1562 impl->mapping.map(impl->mapping.lookupOrDefault(from), to); 1563 } 1564 1565 Value ConversionPatternRewriter::getRemappedValue(Value key) { 1566 SmallVector<Value> remappedValues; 1567 if (failed(impl->remapValues("value", /*inputLoc=*/llvm::None, *this, key, 1568 remappedValues))) 1569 return nullptr; 1570 return remappedValues.front(); 1571 } 1572 1573 LogicalResult 1574 ConversionPatternRewriter::getRemappedValues(ValueRange keys, 1575 SmallVectorImpl<Value> &results) { 1576 if (keys.empty()) 1577 return success(); 1578 return impl->remapValues("value", /*inputLoc=*/llvm::None, *this, keys, 1579 results); 1580 } 1581 1582 void ConversionPatternRewriter::notifyBlockCreated(Block *block) { 1583 impl->notifyCreatedBlock(block); 1584 } 1585 1586 Block *ConversionPatternRewriter::splitBlock(Block *block, 1587 Block::iterator before) { 1588 auto *continuation = PatternRewriter::splitBlock(block, before); 1589 impl->notifySplitBlock(block, continuation); 1590 return continuation; 1591 } 1592 1593 void ConversionPatternRewriter::mergeBlocks(Block *source, Block *dest, 1594 ValueRange argValues) { 1595 impl->notifyBlocksBeingMerged(dest, source); 1596 assert(llvm::all_of(source->getPredecessors(), 1597 [dest](Block *succ) { return succ == dest; }) && 1598 "expected 'source' to have no predecessors or only 'dest'"); 1599 assert(argValues.size() == source->getNumArguments() && 1600 "incorrect # of argument replacement values"); 1601 for (auto it : llvm::zip(source->getArguments(), argValues)) 1602 replaceUsesOfBlockArgument(std::get<0>(it), std::get<1>(it)); 1603 dest->getOperations().splice(dest->end(), source->getOperations()); 1604 eraseBlock(source); 1605 } 1606 1607 void ConversionPatternRewriter::inlineRegionBefore(Region ®ion, 1608 Region &parent, 1609 Region::iterator before) { 1610 impl->notifyRegionIsBeingInlinedBefore(region, parent, before); 1611 PatternRewriter::inlineRegionBefore(region, parent, before); 1612 } 1613 1614 void ConversionPatternRewriter::cloneRegionBefore( 1615 Region ®ion, Region &parent, Region::iterator before, 1616 BlockAndValueMapping &mapping) { 1617 if (region.empty()) 1618 return; 1619 PatternRewriter::cloneRegionBefore(region, parent, before, mapping); 1620 1621 // Collect the range of the cloned blocks. 1622 auto clonedBeginIt = mapping.lookup(®ion.front())->getIterator(); 1623 auto clonedBlocks = llvm::make_range(clonedBeginIt, before); 1624 impl->notifyRegionWasClonedBefore(clonedBlocks, region.getLoc()); 1625 } 1626 1627 void ConversionPatternRewriter::notifyOperationInserted(Operation *op) { 1628 LLVM_DEBUG({ 1629 impl->logger.startLine() 1630 << "** Insert : '" << op->getName() << "'(" << op << ")\n"; 1631 }); 1632 impl->createdOps.push_back(op); 1633 } 1634 1635 void ConversionPatternRewriter::startRootUpdate(Operation *op) { 1636 #ifndef NDEBUG 1637 impl->pendingRootUpdates.insert(op); 1638 #endif 1639 impl->rootUpdates.emplace_back(op); 1640 } 1641 1642 void ConversionPatternRewriter::finalizeRootUpdate(Operation *op) { 1643 // There is nothing to do here, we only need to track the operation at the 1644 // start of the update. 1645 #ifndef NDEBUG 1646 assert(impl->pendingRootUpdates.erase(op) && 1647 "operation did not have a pending in-place update"); 1648 #endif 1649 } 1650 1651 void ConversionPatternRewriter::cancelRootUpdate(Operation *op) { 1652 #ifndef NDEBUG 1653 assert(impl->pendingRootUpdates.erase(op) && 1654 "operation did not have a pending in-place update"); 1655 #endif 1656 // Erase the last update for this operation. 1657 auto stateHasOp = [op](const auto &it) { return it.getOperation() == op; }; 1658 auto &rootUpdates = impl->rootUpdates; 1659 auto it = llvm::find_if(llvm::reverse(rootUpdates), stateHasOp); 1660 assert(it != rootUpdates.rend() && "no root update started on op"); 1661 (*it).resetOperation(); 1662 int updateIdx = std::prev(rootUpdates.rend()) - it; 1663 rootUpdates.erase(rootUpdates.begin() + updateIdx); 1664 } 1665 1666 LogicalResult ConversionPatternRewriter::notifyMatchFailure( 1667 Operation *op, function_ref<void(Diagnostic &)> reasonCallback) { 1668 return impl->notifyMatchFailure(op->getLoc(), reasonCallback); 1669 } 1670 1671 detail::ConversionPatternRewriterImpl &ConversionPatternRewriter::getImpl() { 1672 return *impl; 1673 } 1674 1675 //===----------------------------------------------------------------------===// 1676 // ConversionPattern 1677 //===----------------------------------------------------------------------===// 1678 1679 LogicalResult 1680 ConversionPattern::matchAndRewrite(Operation *op, 1681 PatternRewriter &rewriter) const { 1682 auto &dialectRewriter = static_cast<ConversionPatternRewriter &>(rewriter); 1683 auto &rewriterImpl = dialectRewriter.getImpl(); 1684 1685 // Track the current conversion pattern type converter in the rewriter. 1686 llvm::SaveAndRestore<TypeConverter *> currentConverterGuard( 1687 rewriterImpl.currentTypeConverter, getTypeConverter()); 1688 1689 // Remap the operands of the operation. 1690 SmallVector<Value, 4> operands; 1691 if (failed(rewriterImpl.remapValues("operand", op->getLoc(), rewriter, 1692 op->getOperands(), operands))) { 1693 return failure(); 1694 } 1695 return matchAndRewrite(op, operands, dialectRewriter); 1696 } 1697 1698 //===----------------------------------------------------------------------===// 1699 // OperationLegalizer 1700 //===----------------------------------------------------------------------===// 1701 1702 namespace { 1703 /// A set of rewrite patterns that can be used to legalize a given operation. 1704 using LegalizationPatterns = SmallVector<const Pattern *, 1>; 1705 1706 /// This class defines a recursive operation legalizer. 1707 class OperationLegalizer { 1708 public: 1709 using LegalizationAction = ConversionTarget::LegalizationAction; 1710 1711 OperationLegalizer(ConversionTarget &targetInfo, 1712 const FrozenRewritePatternSet &patterns); 1713 1714 /// Returns true if the given operation is known to be illegal on the target. 1715 bool isIllegal(Operation *op) const; 1716 1717 /// Attempt to legalize the given operation. Returns success if the operation 1718 /// was legalized, failure otherwise. 1719 LogicalResult legalize(Operation *op, ConversionPatternRewriter &rewriter); 1720 1721 /// Returns the conversion target in use by the legalizer. 1722 ConversionTarget &getTarget() { return target; } 1723 1724 private: 1725 /// Attempt to legalize the given operation by folding it. 1726 LogicalResult legalizeWithFold(Operation *op, 1727 ConversionPatternRewriter &rewriter); 1728 1729 /// Attempt to legalize the given operation by applying a pattern. Returns 1730 /// success if the operation was legalized, failure otherwise. 1731 LogicalResult legalizeWithPattern(Operation *op, 1732 ConversionPatternRewriter &rewriter); 1733 1734 /// Return true if the given pattern may be applied to the given operation, 1735 /// false otherwise. 1736 bool canApplyPattern(Operation *op, const Pattern &pattern, 1737 ConversionPatternRewriter &rewriter); 1738 1739 /// Legalize the resultant IR after successfully applying the given pattern. 1740 LogicalResult legalizePatternResult(Operation *op, const Pattern &pattern, 1741 ConversionPatternRewriter &rewriter, 1742 RewriterState &curState); 1743 1744 /// Legalizes the actions registered during the execution of a pattern. 1745 LogicalResult legalizePatternBlockActions(Operation *op, 1746 ConversionPatternRewriter &rewriter, 1747 ConversionPatternRewriterImpl &impl, 1748 RewriterState &state, 1749 RewriterState &newState); 1750 LogicalResult legalizePatternCreatedOperations( 1751 ConversionPatternRewriter &rewriter, ConversionPatternRewriterImpl &impl, 1752 RewriterState &state, RewriterState &newState); 1753 LogicalResult legalizePatternRootUpdates(ConversionPatternRewriter &rewriter, 1754 ConversionPatternRewriterImpl &impl, 1755 RewriterState &state, 1756 RewriterState &newState); 1757 1758 //===--------------------------------------------------------------------===// 1759 // Cost Model 1760 //===--------------------------------------------------------------------===// 1761 1762 /// Build an optimistic legalization graph given the provided patterns. This 1763 /// function populates 'anyOpLegalizerPatterns' and 'legalizerPatterns' with 1764 /// patterns for operations that are not directly legal, but may be 1765 /// transitively legal for the current target given the provided patterns. 1766 void buildLegalizationGraph( 1767 LegalizationPatterns &anyOpLegalizerPatterns, 1768 DenseMap<OperationName, LegalizationPatterns> &legalizerPatterns); 1769 1770 /// Compute the benefit of each node within the computed legalization graph. 1771 /// This orders the patterns within 'legalizerPatterns' based upon two 1772 /// criteria: 1773 /// 1) Prefer patterns that have the lowest legalization depth, i.e. 1774 /// represent the more direct mapping to the target. 1775 /// 2) When comparing patterns with the same legalization depth, prefer the 1776 /// pattern with the highest PatternBenefit. This allows for users to 1777 /// prefer specific legalizations over others. 1778 void computeLegalizationGraphBenefit( 1779 LegalizationPatterns &anyOpLegalizerPatterns, 1780 DenseMap<OperationName, LegalizationPatterns> &legalizerPatterns); 1781 1782 /// Compute the legalization depth when legalizing an operation of the given 1783 /// type. 1784 unsigned computeOpLegalizationDepth( 1785 OperationName op, DenseMap<OperationName, unsigned> &minOpPatternDepth, 1786 DenseMap<OperationName, LegalizationPatterns> &legalizerPatterns); 1787 1788 /// Apply the conversion cost model to the given set of patterns, and return 1789 /// the smallest legalization depth of any of the patterns. See 1790 /// `computeLegalizationGraphBenefit` for the breakdown of the cost model. 1791 unsigned applyCostModelToPatterns( 1792 LegalizationPatterns &patterns, 1793 DenseMap<OperationName, unsigned> &minOpPatternDepth, 1794 DenseMap<OperationName, LegalizationPatterns> &legalizerPatterns); 1795 1796 /// The current set of patterns that have been applied. 1797 SmallPtrSet<const Pattern *, 8> appliedPatterns; 1798 1799 /// The legalization information provided by the target. 1800 ConversionTarget ⌖ 1801 1802 /// The pattern applicator to use for conversions. 1803 PatternApplicator applicator; 1804 }; 1805 } // namespace 1806 1807 OperationLegalizer::OperationLegalizer(ConversionTarget &targetInfo, 1808 const FrozenRewritePatternSet &patterns) 1809 : target(targetInfo), applicator(patterns) { 1810 // The set of patterns that can be applied to illegal operations to transform 1811 // them into legal ones. 1812 DenseMap<OperationName, LegalizationPatterns> legalizerPatterns; 1813 LegalizationPatterns anyOpLegalizerPatterns; 1814 1815 buildLegalizationGraph(anyOpLegalizerPatterns, legalizerPatterns); 1816 computeLegalizationGraphBenefit(anyOpLegalizerPatterns, legalizerPatterns); 1817 } 1818 1819 bool OperationLegalizer::isIllegal(Operation *op) const { 1820 return target.isIllegal(op); 1821 } 1822 1823 LogicalResult 1824 OperationLegalizer::legalize(Operation *op, 1825 ConversionPatternRewriter &rewriter) { 1826 #ifndef NDEBUG 1827 const char *logLineComment = 1828 "//===-------------------------------------------===//\n"; 1829 1830 auto &logger = rewriter.getImpl().logger; 1831 #endif 1832 LLVM_DEBUG({ 1833 logger.getOStream() << "\n"; 1834 logger.startLine() << logLineComment; 1835 logger.startLine() << "Legalizing operation : '" << op->getName() << "'(" 1836 << op << ") {\n"; 1837 logger.indent(); 1838 1839 // If the operation has no regions, just print it here. 1840 if (op->getNumRegions() == 0) { 1841 op->print(logger.startLine(), OpPrintingFlags().printGenericOpForm()); 1842 logger.getOStream() << "\n\n"; 1843 } 1844 }); 1845 1846 // Check if this operation is legal on the target. 1847 if (auto legalityInfo = target.isLegal(op)) { 1848 LLVM_DEBUG({ 1849 logSuccess( 1850 logger, "operation marked legal by the target{0}", 1851 legalityInfo->isRecursivelyLegal 1852 ? "; NOTE: operation is recursively legal; skipping internals" 1853 : ""); 1854 logger.startLine() << logLineComment; 1855 }); 1856 1857 // If this operation is recursively legal, mark its children as ignored so 1858 // that we don't consider them for legalization. 1859 if (legalityInfo->isRecursivelyLegal) 1860 rewriter.getImpl().markNestedOpsIgnored(op); 1861 return success(); 1862 } 1863 1864 // Check to see if the operation is ignored and doesn't need to be converted. 1865 if (rewriter.getImpl().isOpIgnored(op)) { 1866 LLVM_DEBUG({ 1867 logSuccess(logger, "operation marked 'ignored' during conversion"); 1868 logger.startLine() << logLineComment; 1869 }); 1870 return success(); 1871 } 1872 1873 // If the operation isn't legal, try to fold it in-place. 1874 // TODO: Should we always try to do this, even if the op is 1875 // already legal? 1876 if (succeeded(legalizeWithFold(op, rewriter))) { 1877 LLVM_DEBUG({ 1878 logSuccess(logger, "operation was folded"); 1879 logger.startLine() << logLineComment; 1880 }); 1881 return success(); 1882 } 1883 1884 // Otherwise, we need to apply a legalization pattern to this operation. 1885 if (succeeded(legalizeWithPattern(op, rewriter))) { 1886 LLVM_DEBUG({ 1887 logSuccess(logger, ""); 1888 logger.startLine() << logLineComment; 1889 }); 1890 return success(); 1891 } 1892 1893 LLVM_DEBUG({ 1894 logFailure(logger, "no matched legalization pattern"); 1895 logger.startLine() << logLineComment; 1896 }); 1897 return failure(); 1898 } 1899 1900 LogicalResult 1901 OperationLegalizer::legalizeWithFold(Operation *op, 1902 ConversionPatternRewriter &rewriter) { 1903 auto &rewriterImpl = rewriter.getImpl(); 1904 RewriterState curState = rewriterImpl.getCurrentState(); 1905 1906 LLVM_DEBUG({ 1907 rewriterImpl.logger.startLine() << "* Fold {\n"; 1908 rewriterImpl.logger.indent(); 1909 }); 1910 1911 // Try to fold the operation. 1912 SmallVector<Value, 2> replacementValues; 1913 rewriter.setInsertionPoint(op); 1914 if (failed(rewriter.tryFold(op, replacementValues))) { 1915 LLVM_DEBUG(logFailure(rewriterImpl.logger, "unable to fold")); 1916 return failure(); 1917 } 1918 1919 // Insert a replacement for 'op' with the folded replacement values. 1920 rewriter.replaceOp(op, replacementValues); 1921 1922 // Recursively legalize any new constant operations. 1923 for (unsigned i = curState.numCreatedOps, e = rewriterImpl.createdOps.size(); 1924 i != e; ++i) { 1925 Operation *cstOp = rewriterImpl.createdOps[i]; 1926 if (failed(legalize(cstOp, rewriter))) { 1927 LLVM_DEBUG(logFailure(rewriterImpl.logger, 1928 "generated constant '{0}' was illegal", 1929 cstOp->getName())); 1930 rewriterImpl.resetState(curState); 1931 return failure(); 1932 } 1933 } 1934 1935 LLVM_DEBUG(logSuccess(rewriterImpl.logger, "")); 1936 return success(); 1937 } 1938 1939 LogicalResult 1940 OperationLegalizer::legalizeWithPattern(Operation *op, 1941 ConversionPatternRewriter &rewriter) { 1942 auto &rewriterImpl = rewriter.getImpl(); 1943 1944 // Functor that returns if the given pattern may be applied. 1945 auto canApply = [&](const Pattern &pattern) { 1946 return canApplyPattern(op, pattern, rewriter); 1947 }; 1948 1949 // Functor that cleans up the rewriter state after a pattern failed to match. 1950 RewriterState curState = rewriterImpl.getCurrentState(); 1951 auto onFailure = [&](const Pattern &pattern) { 1952 LLVM_DEBUG(logFailure(rewriterImpl.logger, "pattern failed to match")); 1953 rewriterImpl.resetState(curState); 1954 appliedPatterns.erase(&pattern); 1955 }; 1956 1957 // Functor that performs additional legalization when a pattern is 1958 // successfully applied. 1959 auto onSuccess = [&](const Pattern &pattern) { 1960 auto result = legalizePatternResult(op, pattern, rewriter, curState); 1961 appliedPatterns.erase(&pattern); 1962 if (failed(result)) 1963 rewriterImpl.resetState(curState); 1964 return result; 1965 }; 1966 1967 // Try to match and rewrite a pattern on this operation. 1968 return applicator.matchAndRewrite(op, rewriter, canApply, onFailure, 1969 onSuccess); 1970 } 1971 1972 bool OperationLegalizer::canApplyPattern(Operation *op, const Pattern &pattern, 1973 ConversionPatternRewriter &rewriter) { 1974 LLVM_DEBUG({ 1975 auto &os = rewriter.getImpl().logger; 1976 os.getOStream() << "\n"; 1977 os.startLine() << "* Pattern : '" << op->getName() << " -> ("; 1978 llvm::interleaveComma(pattern.getGeneratedOps(), os.getOStream()); 1979 os.getOStream() << ")' {\n"; 1980 os.indent(); 1981 }); 1982 1983 // Ensure that we don't cycle by not allowing the same pattern to be 1984 // applied twice in the same recursion stack if it is not known to be safe. 1985 if (!pattern.hasBoundedRewriteRecursion() && 1986 !appliedPatterns.insert(&pattern).second) { 1987 LLVM_DEBUG( 1988 logFailure(rewriter.getImpl().logger, "pattern was already applied")); 1989 return false; 1990 } 1991 return true; 1992 } 1993 1994 LogicalResult 1995 OperationLegalizer::legalizePatternResult(Operation *op, const Pattern &pattern, 1996 ConversionPatternRewriter &rewriter, 1997 RewriterState &curState) { 1998 auto &impl = rewriter.getImpl(); 1999 2000 #ifndef NDEBUG 2001 assert(impl.pendingRootUpdates.empty() && "dangling root updates"); 2002 #endif 2003 2004 // Check that the root was either replaced or updated in place. 2005 auto replacedRoot = [&] { 2006 return llvm::any_of( 2007 llvm::drop_begin(impl.replacements, curState.numReplacements), 2008 [op](auto &it) { return it.first == op; }); 2009 }; 2010 auto updatedRootInPlace = [&] { 2011 return llvm::any_of( 2012 llvm::drop_begin(impl.rootUpdates, curState.numRootUpdates), 2013 [op](auto &state) { return state.getOperation() == op; }); 2014 }; 2015 (void)replacedRoot; 2016 (void)updatedRootInPlace; 2017 assert((replacedRoot() || updatedRootInPlace()) && 2018 "expected pattern to replace the root operation"); 2019 2020 // Legalize each of the actions registered during application. 2021 RewriterState newState = impl.getCurrentState(); 2022 if (failed(legalizePatternBlockActions(op, rewriter, impl, curState, 2023 newState)) || 2024 failed(legalizePatternRootUpdates(rewriter, impl, curState, newState)) || 2025 failed(legalizePatternCreatedOperations(rewriter, impl, curState, 2026 newState))) { 2027 return failure(); 2028 } 2029 2030 LLVM_DEBUG(logSuccess(impl.logger, "pattern applied successfully")); 2031 return success(); 2032 } 2033 2034 LogicalResult OperationLegalizer::legalizePatternBlockActions( 2035 Operation *op, ConversionPatternRewriter &rewriter, 2036 ConversionPatternRewriterImpl &impl, RewriterState &state, 2037 RewriterState &newState) { 2038 SmallPtrSet<Operation *, 16> operationsToIgnore; 2039 2040 // If the pattern moved or created any blocks, make sure the types of block 2041 // arguments get legalized. 2042 for (int i = state.numBlockActions, e = newState.numBlockActions; i != e; 2043 ++i) { 2044 auto &action = impl.blockActions[i]; 2045 if (action.kind == BlockActionKind::TypeConversion || 2046 action.kind == BlockActionKind::Erase) 2047 continue; 2048 // Only check blocks outside of the current operation. 2049 Operation *parentOp = action.block->getParentOp(); 2050 if (!parentOp || parentOp == op || action.block->getNumArguments() == 0) 2051 continue; 2052 2053 // If the region of the block has a type converter, try to convert the block 2054 // directly. 2055 if (auto *converter = 2056 impl.argConverter.getConverter(action.block->getParent())) { 2057 if (failed(impl.convertBlockSignature(action.block, converter))) { 2058 LLVM_DEBUG(logFailure(impl.logger, "failed to convert types of moved " 2059 "block")); 2060 return failure(); 2061 } 2062 continue; 2063 } 2064 2065 // Otherwise, check that this operation isn't one generated by this pattern. 2066 // This is because we will attempt to legalize the parent operation, and 2067 // blocks in regions created by this pattern will already be legalized later 2068 // on. If we haven't built the set yet, build it now. 2069 if (operationsToIgnore.empty()) { 2070 auto createdOps = ArrayRef<Operation *>(impl.createdOps) 2071 .drop_front(state.numCreatedOps); 2072 operationsToIgnore.insert(createdOps.begin(), createdOps.end()); 2073 } 2074 2075 // If this operation should be considered for re-legalization, try it. 2076 if (operationsToIgnore.insert(parentOp).second && 2077 failed(legalize(parentOp, rewriter))) { 2078 LLVM_DEBUG(logFailure( 2079 impl.logger, "operation '{0}'({1}) became illegal after block action", 2080 parentOp->getName(), parentOp)); 2081 return failure(); 2082 } 2083 } 2084 return success(); 2085 } 2086 2087 LogicalResult OperationLegalizer::legalizePatternCreatedOperations( 2088 ConversionPatternRewriter &rewriter, ConversionPatternRewriterImpl &impl, 2089 RewriterState &state, RewriterState &newState) { 2090 for (int i = state.numCreatedOps, e = newState.numCreatedOps; i != e; ++i) { 2091 Operation *op = impl.createdOps[i]; 2092 if (failed(legalize(op, rewriter))) { 2093 LLVM_DEBUG(logFailure(impl.logger, 2094 "generated operation '{0}'({1}) was illegal", 2095 op->getName(), op)); 2096 return failure(); 2097 } 2098 } 2099 return success(); 2100 } 2101 2102 LogicalResult OperationLegalizer::legalizePatternRootUpdates( 2103 ConversionPatternRewriter &rewriter, ConversionPatternRewriterImpl &impl, 2104 RewriterState &state, RewriterState &newState) { 2105 for (int i = state.numRootUpdates, e = newState.numRootUpdates; i != e; ++i) { 2106 Operation *op = impl.rootUpdates[i].getOperation(); 2107 if (failed(legalize(op, rewriter))) { 2108 LLVM_DEBUG(logFailure(impl.logger, 2109 "operation updated in-place '{0}' was illegal", 2110 op->getName())); 2111 return failure(); 2112 } 2113 } 2114 return success(); 2115 } 2116 2117 //===----------------------------------------------------------------------===// 2118 // Cost Model 2119 2120 void OperationLegalizer::buildLegalizationGraph( 2121 LegalizationPatterns &anyOpLegalizerPatterns, 2122 DenseMap<OperationName, LegalizationPatterns> &legalizerPatterns) { 2123 // A mapping between an operation and a set of operations that can be used to 2124 // generate it. 2125 DenseMap<OperationName, SmallPtrSet<OperationName, 2>> parentOps; 2126 // A mapping between an operation and any currently invalid patterns it has. 2127 DenseMap<OperationName, SmallPtrSet<const Pattern *, 2>> invalidPatterns; 2128 // A worklist of patterns to consider for legality. 2129 SetVector<const Pattern *> patternWorklist; 2130 2131 // Build the mapping from operations to the parent ops that may generate them. 2132 applicator.walkAllPatterns([&](const Pattern &pattern) { 2133 Optional<OperationName> root = pattern.getRootKind(); 2134 2135 // If the pattern has no specific root, we can't analyze the relationship 2136 // between the root op and generated operations. Given that, add all such 2137 // patterns to the legalization set. 2138 if (!root) { 2139 anyOpLegalizerPatterns.push_back(&pattern); 2140 return; 2141 } 2142 2143 // Skip operations that are always known to be legal. 2144 if (target.getOpAction(*root) == LegalizationAction::Legal) 2145 return; 2146 2147 // Add this pattern to the invalid set for the root op and record this root 2148 // as a parent for any generated operations. 2149 invalidPatterns[*root].insert(&pattern); 2150 for (auto op : pattern.getGeneratedOps()) 2151 parentOps[op].insert(*root); 2152 2153 // Add this pattern to the worklist. 2154 patternWorklist.insert(&pattern); 2155 }); 2156 2157 // If there are any patterns that don't have a specific root kind, we can't 2158 // make direct assumptions about what operations will never be legalized. 2159 // Note: Technically we could, but it would require an analysis that may 2160 // recurse into itself. It would be better to perform this kind of filtering 2161 // at a higher level than here anyways. 2162 if (!anyOpLegalizerPatterns.empty()) { 2163 for (const Pattern *pattern : patternWorklist) 2164 legalizerPatterns[*pattern->getRootKind()].push_back(pattern); 2165 return; 2166 } 2167 2168 while (!patternWorklist.empty()) { 2169 auto *pattern = patternWorklist.pop_back_val(); 2170 2171 // Check to see if any of the generated operations are invalid. 2172 if (llvm::any_of(pattern->getGeneratedOps(), [&](OperationName op) { 2173 Optional<LegalizationAction> action = target.getOpAction(op); 2174 return !legalizerPatterns.count(op) && 2175 (!action || action == LegalizationAction::Illegal); 2176 })) 2177 continue; 2178 2179 // Otherwise, if all of the generated operation are valid, this op is now 2180 // legal so add all of the child patterns to the worklist. 2181 legalizerPatterns[*pattern->getRootKind()].push_back(pattern); 2182 invalidPatterns[*pattern->getRootKind()].erase(pattern); 2183 2184 // Add any invalid patterns of the parent operations to see if they have now 2185 // become legal. 2186 for (auto op : parentOps[*pattern->getRootKind()]) 2187 patternWorklist.set_union(invalidPatterns[op]); 2188 } 2189 } 2190 2191 void OperationLegalizer::computeLegalizationGraphBenefit( 2192 LegalizationPatterns &anyOpLegalizerPatterns, 2193 DenseMap<OperationName, LegalizationPatterns> &legalizerPatterns) { 2194 // The smallest pattern depth, when legalizing an operation. 2195 DenseMap<OperationName, unsigned> minOpPatternDepth; 2196 2197 // For each operation that is transitively legal, compute a cost for it. 2198 for (auto &opIt : legalizerPatterns) 2199 if (!minOpPatternDepth.count(opIt.first)) 2200 computeOpLegalizationDepth(opIt.first, minOpPatternDepth, 2201 legalizerPatterns); 2202 2203 // Apply the cost model to the patterns that can match any operation. Those 2204 // with a specific operation type are already resolved when computing the op 2205 // legalization depth. 2206 if (!anyOpLegalizerPatterns.empty()) 2207 applyCostModelToPatterns(anyOpLegalizerPatterns, minOpPatternDepth, 2208 legalizerPatterns); 2209 2210 // Apply a cost model to the pattern applicator. We order patterns first by 2211 // depth then benefit. `legalizerPatterns` contains per-op patterns by 2212 // decreasing benefit. 2213 applicator.applyCostModel([&](const Pattern &pattern) { 2214 ArrayRef<const Pattern *> orderedPatternList; 2215 if (Optional<OperationName> rootName = pattern.getRootKind()) 2216 orderedPatternList = legalizerPatterns[*rootName]; 2217 else 2218 orderedPatternList = anyOpLegalizerPatterns; 2219 2220 // If the pattern is not found, then it was removed and cannot be matched. 2221 auto *it = llvm::find(orderedPatternList, &pattern); 2222 if (it == orderedPatternList.end()) 2223 return PatternBenefit::impossibleToMatch(); 2224 2225 // Patterns found earlier in the list have higher benefit. 2226 return PatternBenefit(std::distance(it, orderedPatternList.end())); 2227 }); 2228 } 2229 2230 unsigned OperationLegalizer::computeOpLegalizationDepth( 2231 OperationName op, DenseMap<OperationName, unsigned> &minOpPatternDepth, 2232 DenseMap<OperationName, LegalizationPatterns> &legalizerPatterns) { 2233 // Check for existing depth. 2234 auto depthIt = minOpPatternDepth.find(op); 2235 if (depthIt != minOpPatternDepth.end()) 2236 return depthIt->second; 2237 2238 // If a mapping for this operation does not exist, then this operation 2239 // is always legal. Return 0 as the depth for a directly legal operation. 2240 auto opPatternsIt = legalizerPatterns.find(op); 2241 if (opPatternsIt == legalizerPatterns.end() || opPatternsIt->second.empty()) 2242 return 0u; 2243 2244 // Record this initial depth in case we encounter this op again when 2245 // recursively computing the depth. 2246 minOpPatternDepth.try_emplace(op, std::numeric_limits<unsigned>::max()); 2247 2248 // Apply the cost model to the operation patterns, and update the minimum 2249 // depth. 2250 unsigned minDepth = applyCostModelToPatterns( 2251 opPatternsIt->second, minOpPatternDepth, legalizerPatterns); 2252 minOpPatternDepth[op] = minDepth; 2253 return minDepth; 2254 } 2255 2256 unsigned OperationLegalizer::applyCostModelToPatterns( 2257 LegalizationPatterns &patterns, 2258 DenseMap<OperationName, unsigned> &minOpPatternDepth, 2259 DenseMap<OperationName, LegalizationPatterns> &legalizerPatterns) { 2260 unsigned minDepth = std::numeric_limits<unsigned>::max(); 2261 2262 // Compute the depth for each pattern within the set. 2263 SmallVector<std::pair<const Pattern *, unsigned>, 4> patternsByDepth; 2264 patternsByDepth.reserve(patterns.size()); 2265 for (const Pattern *pattern : patterns) { 2266 unsigned depth = 1; 2267 for (auto generatedOp : pattern->getGeneratedOps()) { 2268 unsigned generatedOpDepth = computeOpLegalizationDepth( 2269 generatedOp, minOpPatternDepth, legalizerPatterns); 2270 depth = std::max(depth, generatedOpDepth + 1); 2271 } 2272 patternsByDepth.emplace_back(pattern, depth); 2273 2274 // Update the minimum depth of the pattern list. 2275 minDepth = std::min(minDepth, depth); 2276 } 2277 2278 // If the operation only has one legalization pattern, there is no need to 2279 // sort them. 2280 if (patternsByDepth.size() == 1) 2281 return minDepth; 2282 2283 // Sort the patterns by those likely to be the most beneficial. 2284 llvm::array_pod_sort(patternsByDepth.begin(), patternsByDepth.end(), 2285 [](const std::pair<const Pattern *, unsigned> *lhs, 2286 const std::pair<const Pattern *, unsigned> *rhs) { 2287 // First sort by the smaller pattern legalization 2288 // depth. 2289 if (lhs->second != rhs->second) 2290 return llvm::array_pod_sort_comparator<unsigned>( 2291 &lhs->second, &rhs->second); 2292 2293 // Then sort by the larger pattern benefit. 2294 auto lhsBenefit = lhs->first->getBenefit(); 2295 auto rhsBenefit = rhs->first->getBenefit(); 2296 return llvm::array_pod_sort_comparator<PatternBenefit>( 2297 &rhsBenefit, &lhsBenefit); 2298 }); 2299 2300 // Update the legalization pattern to use the new sorted list. 2301 patterns.clear(); 2302 for (auto &patternIt : patternsByDepth) 2303 patterns.push_back(patternIt.first); 2304 return minDepth; 2305 } 2306 2307 //===----------------------------------------------------------------------===// 2308 // OperationConverter 2309 //===----------------------------------------------------------------------===// 2310 namespace { 2311 enum OpConversionMode { 2312 /// In this mode, the conversion will ignore failed conversions to allow 2313 /// illegal operations to co-exist in the IR. 2314 Partial, 2315 2316 /// In this mode, all operations must be legal for the given target for the 2317 /// conversion to succeed. 2318 Full, 2319 2320 /// In this mode, operations are analyzed for legality. No actual rewrites are 2321 /// applied to the operations on success. 2322 Analysis, 2323 }; 2324 2325 // This class converts operations to a given conversion target via a set of 2326 // rewrite patterns. The conversion behaves differently depending on the 2327 // conversion mode. 2328 struct OperationConverter { 2329 explicit OperationConverter(ConversionTarget &target, 2330 const FrozenRewritePatternSet &patterns, 2331 OpConversionMode mode, 2332 DenseSet<Operation *> *trackedOps = nullptr) 2333 : opLegalizer(target, patterns), mode(mode), trackedOps(trackedOps) {} 2334 2335 /// Converts the given operations to the conversion target. 2336 LogicalResult convertOperations(ArrayRef<Operation *> ops); 2337 2338 private: 2339 /// Converts an operation with the given rewriter. 2340 LogicalResult convert(ConversionPatternRewriter &rewriter, Operation *op); 2341 2342 /// This method is called after the conversion process to legalize any 2343 /// remaining artifacts and complete the conversion. 2344 LogicalResult finalize(ConversionPatternRewriter &rewriter); 2345 2346 /// Legalize the types of converted block arguments. 2347 LogicalResult 2348 legalizeConvertedArgumentTypes(ConversionPatternRewriter &rewriter, 2349 ConversionPatternRewriterImpl &rewriterImpl); 2350 2351 /// Legalize any unresolved type materializations. 2352 LogicalResult legalizeUnresolvedMaterializations( 2353 ConversionPatternRewriter &rewriter, 2354 ConversionPatternRewriterImpl &rewriterImpl, 2355 Optional<DenseMap<Value, SmallVector<Value>>> &inverseMapping); 2356 2357 /// Legalize an operation result that was marked as "erased". 2358 LogicalResult 2359 legalizeErasedResult(Operation *op, OpResult result, 2360 ConversionPatternRewriterImpl &rewriterImpl); 2361 2362 /// Legalize an operation result that was replaced with a value of a different 2363 /// type. 2364 LogicalResult legalizeChangedResultType( 2365 Operation *op, OpResult result, Value newValue, 2366 TypeConverter *replConverter, ConversionPatternRewriter &rewriter, 2367 ConversionPatternRewriterImpl &rewriterImpl, 2368 const DenseMap<Value, SmallVector<Value>> &inverseMapping); 2369 2370 /// The legalizer to use when converting operations. 2371 OperationLegalizer opLegalizer; 2372 2373 /// The conversion mode to use when legalizing operations. 2374 OpConversionMode mode; 2375 2376 /// A set of pre-existing operations. When mode == OpConversionMode::Analysis, 2377 /// this is populated with ops found to be legalizable to the target. 2378 /// When mode == OpConversionMode::Partial, this is populated with ops found 2379 /// *not* to be legalizable to the target. 2380 DenseSet<Operation *> *trackedOps; 2381 }; 2382 } // end anonymous namespace 2383 2384 LogicalResult OperationConverter::convert(ConversionPatternRewriter &rewriter, 2385 Operation *op) { 2386 // Legalize the given operation. 2387 if (failed(opLegalizer.legalize(op, rewriter))) { 2388 // Handle the case of a failed conversion for each of the different modes. 2389 // Full conversions expect all operations to be converted. 2390 if (mode == OpConversionMode::Full) 2391 return op->emitError() 2392 << "failed to legalize operation '" << op->getName() << "'"; 2393 // Partial conversions allow conversions to fail iff the operation was not 2394 // explicitly marked as illegal. If the user provided a nonlegalizableOps 2395 // set, non-legalizable ops are included. 2396 if (mode == OpConversionMode::Partial) { 2397 if (opLegalizer.isIllegal(op)) 2398 return op->emitError() 2399 << "failed to legalize operation '" << op->getName() 2400 << "' that was explicitly marked illegal"; 2401 if (trackedOps) 2402 trackedOps->insert(op); 2403 } 2404 } else if (mode == OpConversionMode::Analysis) { 2405 // Analysis conversions don't fail if any operations fail to legalize, 2406 // they are only interested in the operations that were successfully 2407 // legalized. 2408 trackedOps->insert(op); 2409 } 2410 return success(); 2411 } 2412 2413 LogicalResult OperationConverter::convertOperations(ArrayRef<Operation *> ops) { 2414 if (ops.empty()) 2415 return success(); 2416 ConversionTarget &target = opLegalizer.getTarget(); 2417 2418 // Compute the set of operations and blocks to convert. 2419 SmallVector<Operation *> toConvert; 2420 for (auto *op : ops) { 2421 toConvert.emplace_back(op); 2422 for (auto ®ion : op->getRegions()) 2423 if (failed(computeConversionSet(region.getBlocks(), region.getLoc(), 2424 toConvert, &target))) 2425 return failure(); 2426 } 2427 2428 // Convert each operation and discard rewrites on failure. 2429 ConversionPatternRewriter rewriter(ops.front()->getContext()); 2430 ConversionPatternRewriterImpl &rewriterImpl = rewriter.getImpl(); 2431 for (auto *op : toConvert) 2432 if (failed(convert(rewriter, op))) 2433 return rewriterImpl.discardRewrites(), failure(); 2434 2435 // Now that all of the operations have been converted, finalize the conversion 2436 // process to ensure any lingering conversion artifacts are cleaned up and 2437 // legalized. 2438 if (failed(finalize(rewriter))) 2439 return rewriterImpl.discardRewrites(), failure(); 2440 2441 // After a successful conversion, apply rewrites if this is not an analysis 2442 // conversion. 2443 if (mode == OpConversionMode::Analysis) { 2444 rewriterImpl.discardRewrites(); 2445 } else { 2446 rewriterImpl.applyRewrites(); 2447 2448 // It is possible for a later pattern to erase an op that was originally 2449 // identified as illegal and added to the trackedOps, remove it now after 2450 // replacements have been computed. 2451 if (trackedOps) 2452 for (auto &repl : rewriterImpl.replacements) 2453 trackedOps->erase(repl.first); 2454 } 2455 return success(); 2456 } 2457 2458 LogicalResult 2459 OperationConverter::finalize(ConversionPatternRewriter &rewriter) { 2460 Optional<DenseMap<Value, SmallVector<Value>>> inverseMapping; 2461 ConversionPatternRewriterImpl &rewriterImpl = rewriter.getImpl(); 2462 if (failed(legalizeUnresolvedMaterializations(rewriter, rewriterImpl, 2463 inverseMapping)) || 2464 failed(legalizeConvertedArgumentTypes(rewriter, rewriterImpl))) 2465 return failure(); 2466 2467 if (rewriterImpl.operationsWithChangedResults.empty()) 2468 return success(); 2469 2470 // Process requested operation replacements. 2471 for (unsigned i = 0, e = rewriterImpl.operationsWithChangedResults.size(); 2472 i != e; ++i) { 2473 unsigned replIdx = rewriterImpl.operationsWithChangedResults[i]; 2474 auto &repl = *(rewriterImpl.replacements.begin() + replIdx); 2475 for (OpResult result : repl.first->getResults()) { 2476 Value newValue = rewriterImpl.mapping.lookupOrNull(result); 2477 2478 // If the operation result was replaced with null, all of the uses of this 2479 // value should be replaced. 2480 if (!newValue) { 2481 if (failed(legalizeErasedResult(repl.first, result, rewriterImpl))) 2482 return failure(); 2483 continue; 2484 } 2485 2486 // Otherwise, check to see if the type of the result changed. 2487 if (result.getType() == newValue.getType()) 2488 continue; 2489 2490 // Compute the inverse mapping only if it is really needed. 2491 if (!inverseMapping) 2492 inverseMapping = rewriterImpl.mapping.getInverse(); 2493 2494 // Legalize this result. 2495 rewriter.setInsertionPoint(repl.first); 2496 if (failed(legalizeChangedResultType(repl.first, result, newValue, 2497 repl.second.converter, rewriter, 2498 rewriterImpl, *inverseMapping))) 2499 return failure(); 2500 2501 // Update the end iterator for this loop in the case it was updated 2502 // when legalizing generated conversion operations. 2503 e = rewriterImpl.operationsWithChangedResults.size(); 2504 } 2505 } 2506 return success(); 2507 } 2508 2509 LogicalResult OperationConverter::legalizeConvertedArgumentTypes( 2510 ConversionPatternRewriter &rewriter, 2511 ConversionPatternRewriterImpl &rewriterImpl) { 2512 // Functor used to check if all users of a value will be dead after 2513 // conversion. 2514 auto findLiveUser = [&](Value val) { 2515 auto liveUserIt = llvm::find_if_not(val.getUsers(), [&](Operation *user) { 2516 return rewriterImpl.isOpIgnored(user); 2517 }); 2518 return liveUserIt == val.user_end() ? nullptr : *liveUserIt; 2519 }; 2520 return rewriterImpl.argConverter.materializeLiveConversions( 2521 rewriterImpl.mapping, rewriter, findLiveUser); 2522 } 2523 2524 /// Replace the results of a materialization operation with the given values. 2525 static void 2526 replaceMaterialization(ConversionPatternRewriterImpl &rewriterImpl, 2527 ResultRange matResults, ValueRange values, 2528 DenseMap<Value, SmallVector<Value>> &inverseMapping) { 2529 matResults.replaceAllUsesWith(values); 2530 2531 // For each of the materialization results, update the inverse mappings to 2532 // point to the replacement values. 2533 for (auto it : llvm::zip(matResults, values)) { 2534 Value matResult, newValue; 2535 std::tie(matResult, newValue) = it; 2536 auto inverseMapIt = inverseMapping.find(matResult); 2537 if (inverseMapIt == inverseMapping.end()) 2538 continue; 2539 2540 // Update the reverse mapping, or remove the mapping if we couldn't update 2541 // it. Not being able to update signals that the mapping would have become 2542 // circular (i.e. %foo -> newValue -> %foo), which may occur as values are 2543 // propagated through temporary materializations. We simply drop the 2544 // mapping, and let the post-conversion replacement logic handle updating 2545 // uses. 2546 for (Value inverseMapVal : inverseMapIt->second) 2547 if (!rewriterImpl.mapping.tryMap(inverseMapVal, newValue)) 2548 rewriterImpl.mapping.erase(inverseMapVal); 2549 } 2550 } 2551 2552 /// Compute all of the unresolved materializations that will persist beyond the 2553 /// conversion process, and require inserting a proper user materialization for. 2554 static void computeNecessaryMaterializations( 2555 DenseMap<Operation *, UnresolvedMaterialization *> &materializationOps, 2556 ConversionPatternRewriter &rewriter, 2557 ConversionPatternRewriterImpl &rewriterImpl, 2558 DenseMap<Value, SmallVector<Value>> &inverseMapping, 2559 SetVector<UnresolvedMaterialization *> &necessaryMaterializations) { 2560 auto isLive = [&](Value value) { 2561 auto findFn = [&](Operation *user) { 2562 auto matIt = materializationOps.find(user); 2563 if (matIt != materializationOps.end()) 2564 return !necessaryMaterializations.count(matIt->second); 2565 return rewriterImpl.isOpIgnored(user); 2566 }; 2567 return llvm::find_if_not(value.getUsers(), findFn) != value.user_end(); 2568 }; 2569 2570 llvm::unique_function<Value(Value, Value, Type)> lookupRemappedValue = 2571 [&](Value invalidRoot, Value value, Type type) { 2572 // Check to see if the input operation was remapped to a variant of the 2573 // output. 2574 Value remappedValue = rewriterImpl.mapping.lookupOrDefault(value, type); 2575 if (remappedValue.getType() == type && remappedValue != invalidRoot) 2576 return remappedValue; 2577 2578 // Check to see if the input is a materialization operation that 2579 // provides an inverse conversion. We just check blindly for 2580 // UnrealizedConversionCastOp here, but it has no effect on correctness. 2581 auto inputCastOp = value.getDefiningOp<UnrealizedConversionCastOp>(); 2582 if (inputCastOp && inputCastOp->getNumOperands() == 1) 2583 return lookupRemappedValue(invalidRoot, inputCastOp->getOperand(0), 2584 type); 2585 2586 return Value(); 2587 }; 2588 2589 SetVector<UnresolvedMaterialization *> worklist; 2590 for (auto &mat : rewriterImpl.unresolvedMaterializations) { 2591 materializationOps.try_emplace(mat.getOp(), &mat); 2592 worklist.insert(&mat); 2593 } 2594 while (!worklist.empty()) { 2595 UnresolvedMaterialization *mat = worklist.pop_back_val(); 2596 UnrealizedConversionCastOp op = mat->getOp(); 2597 2598 // We currently only handle target materializations here. 2599 assert(op->getNumResults() == 1 && "unexpected materialization type"); 2600 OpResult opResult = op->getOpResult(0); 2601 Type outputType = opResult.getType(); 2602 Operation::operand_range inputOperands = op.getOperands(); 2603 2604 // Try to forward propagate operands for user conversion casts that result 2605 // in the input types of the current cast. 2606 for (Operation *user : llvm::make_early_inc_range(opResult.getUsers())) { 2607 auto castOp = dyn_cast<UnrealizedConversionCastOp>(user); 2608 if (!castOp) 2609 continue; 2610 if (castOp->getResultTypes() == inputOperands.getTypes()) { 2611 replaceMaterialization(rewriterImpl, opResult, inputOperands, 2612 inverseMapping); 2613 necessaryMaterializations.remove(materializationOps.lookup(user)); 2614 } 2615 } 2616 2617 // Try to avoid materializing a resolved materialization if possible. 2618 // Handle the case of a 1-1 materialization. 2619 if (inputOperands.size() == 1) { 2620 // Check to see if the input operation was remapped to a variant of the 2621 // output. 2622 Value remappedValue = 2623 lookupRemappedValue(opResult, inputOperands[0], outputType); 2624 if (remappedValue && remappedValue != opResult) { 2625 replaceMaterialization(rewriterImpl, opResult, remappedValue, 2626 inverseMapping); 2627 necessaryMaterializations.remove(mat); 2628 continue; 2629 } 2630 } else { 2631 // TODO: Avoid materializing other types of conversions here. 2632 } 2633 2634 // Check to see if this is an argument materialization. 2635 auto isBlockArg = [](Value v) { return v.isa<BlockArgument>(); }; 2636 if (llvm::any_of(op->getOperands(), isBlockArg) || 2637 llvm::any_of(inverseMapping[op->getResult(0)], isBlockArg)) { 2638 mat->setKind(UnresolvedMaterialization::Argument); 2639 } 2640 2641 // If the materialization does not have any live users, we don't need to 2642 // generate a user materialization for it. 2643 // FIXME: For argument materializations, we currently need to check if any 2644 // of the inverse mapped values are used because some patterns expect blind 2645 // value replacement even if the types differ in some cases. When those 2646 // patterns are fixed, we can drop the argument special case here. 2647 bool isMaterializationLive = isLive(opResult); 2648 if (mat->getKind() == UnresolvedMaterialization::Argument) 2649 isMaterializationLive |= llvm::any_of(inverseMapping[opResult], isLive); 2650 if (!isMaterializationLive) 2651 continue; 2652 if (!necessaryMaterializations.insert(mat)) 2653 continue; 2654 2655 // Reprocess input materializations to see if they have an updated status. 2656 for (Value input : inputOperands) { 2657 if (auto parentOp = input.getDefiningOp<UnrealizedConversionCastOp>()) { 2658 if (auto *mat = materializationOps.lookup(parentOp)) 2659 worklist.insert(mat); 2660 } 2661 } 2662 } 2663 } 2664 2665 /// Legalize the given unresolved materialization. Returns success if the 2666 /// materialization was legalized, failure otherise. 2667 static LogicalResult legalizeUnresolvedMaterialization( 2668 UnresolvedMaterialization &mat, 2669 DenseMap<Operation *, UnresolvedMaterialization *> &materializationOps, 2670 ConversionPatternRewriter &rewriter, 2671 ConversionPatternRewriterImpl &rewriterImpl, 2672 DenseMap<Value, SmallVector<Value>> &inverseMapping) { 2673 auto findLiveUser = [&](auto &&users) { 2674 auto liveUserIt = llvm::find_if_not( 2675 users, [&](Operation *user) { return rewriterImpl.isOpIgnored(user); }); 2676 return liveUserIt == users.end() ? nullptr : *liveUserIt; 2677 }; 2678 2679 llvm::unique_function<Value(Value, Type)> lookupRemappedValue = 2680 [&](Value value, Type type) { 2681 // Check to see if the input operation was remapped to a variant of the 2682 // output. 2683 Value remappedValue = rewriterImpl.mapping.lookupOrDefault(value, type); 2684 if (remappedValue.getType() == type) 2685 return remappedValue; 2686 return Value(); 2687 }; 2688 2689 UnrealizedConversionCastOp op = mat.getOp(); 2690 if (!rewriterImpl.ignoredOps.insert(op)) 2691 return success(); 2692 2693 // We currently only handle target materializations here. 2694 OpResult opResult = op->getOpResult(0); 2695 Operation::operand_range inputOperands = op.getOperands(); 2696 Type outputType = opResult.getType(); 2697 2698 // If any input to this materialization is another materialization, resolve 2699 // the input first. 2700 for (Value value : op->getOperands()) { 2701 auto valueCast = value.getDefiningOp<UnrealizedConversionCastOp>(); 2702 if (!valueCast) 2703 continue; 2704 2705 auto matIt = materializationOps.find(valueCast); 2706 if (matIt != materializationOps.end()) 2707 if (failed(legalizeUnresolvedMaterialization( 2708 *matIt->second, materializationOps, rewriter, rewriterImpl, 2709 inverseMapping))) 2710 return failure(); 2711 } 2712 2713 // Perform a last ditch attempt to avoid materializing a resolved 2714 // materialization if possible. 2715 // Handle the case of a 1-1 materialization. 2716 if (inputOperands.size() == 1) { 2717 // Check to see if the input operation was remapped to a variant of the 2718 // output. 2719 Value remappedValue = lookupRemappedValue(inputOperands[0], outputType); 2720 if (remappedValue && remappedValue != opResult) { 2721 replaceMaterialization(rewriterImpl, opResult, remappedValue, 2722 inverseMapping); 2723 return success(); 2724 } 2725 } else { 2726 // TODO: Avoid materializing other types of conversions here. 2727 } 2728 2729 // Try to materialize the conversion. 2730 if (TypeConverter *converter = mat.getConverter()) { 2731 // FIXME: Determine a suitable insertion location when there are multiple 2732 // inputs. 2733 if (inputOperands.size() == 1) 2734 rewriter.setInsertionPointAfterValue(inputOperands.front()); 2735 else 2736 rewriter.setInsertionPoint(op); 2737 2738 Value newMaterialization; 2739 switch (mat.getKind()) { 2740 case UnresolvedMaterialization::Argument: 2741 // Try to materialize an argument conversion. 2742 // FIXME: The current argument materialization hook expects the original 2743 // output type, even though it doesn't use that as the actual output type 2744 // of the generated IR. The output type is just used as an indicator of 2745 // the type of materialization to do. This behavior is really awkward in 2746 // that it diverges from the behavior of the other hooks, and can be 2747 // easily misunderstood. We should clean up the argument hooks to better 2748 // represent the desired invariants we actually care about. 2749 newMaterialization = converter->materializeArgumentConversion( 2750 rewriter, op->getLoc(), mat.getOrigOutputType(), inputOperands); 2751 if (newMaterialization) 2752 break; 2753 2754 // If an argument materialization failed, fallback to trying a target 2755 // materialization. 2756 LLVM_FALLTHROUGH; 2757 case UnresolvedMaterialization::Target: 2758 newMaterialization = converter->materializeTargetConversion( 2759 rewriter, op->getLoc(), outputType, inputOperands); 2760 break; 2761 } 2762 if (newMaterialization) { 2763 replaceMaterialization(rewriterImpl, opResult, newMaterialization, 2764 inverseMapping); 2765 return success(); 2766 } 2767 } 2768 2769 InFlightDiagnostic diag = op->emitError() 2770 << "failed to legalize unresolved materialization " 2771 "from " 2772 << inputOperands.getTypes() << " to " << outputType 2773 << " that remained live after conversion"; 2774 if (Operation *liveUser = findLiveUser(op->getUsers())) { 2775 diag.attachNote(liveUser->getLoc()) 2776 << "see existing live user here: " << *liveUser; 2777 } 2778 return failure(); 2779 } 2780 2781 LogicalResult OperationConverter::legalizeUnresolvedMaterializations( 2782 ConversionPatternRewriter &rewriter, 2783 ConversionPatternRewriterImpl &rewriterImpl, 2784 Optional<DenseMap<Value, SmallVector<Value>>> &inverseMapping) { 2785 if (rewriterImpl.unresolvedMaterializations.empty()) 2786 return success(); 2787 inverseMapping = rewriterImpl.mapping.getInverse(); 2788 2789 // As an initial step, compute all of the inserted materializations that we 2790 // expect to persist beyond the conversion process. 2791 DenseMap<Operation *, UnresolvedMaterialization *> materializationOps; 2792 SetVector<UnresolvedMaterialization *> necessaryMaterializations; 2793 computeNecessaryMaterializations(materializationOps, rewriter, rewriterImpl, 2794 *inverseMapping, necessaryMaterializations); 2795 2796 // Once computed, legalize any necessary materializations. 2797 for (auto *mat : necessaryMaterializations) { 2798 if (failed(legalizeUnresolvedMaterialization( 2799 *mat, materializationOps, rewriter, rewriterImpl, *inverseMapping))) 2800 return failure(); 2801 } 2802 return success(); 2803 } 2804 2805 LogicalResult OperationConverter::legalizeErasedResult( 2806 Operation *op, OpResult result, 2807 ConversionPatternRewriterImpl &rewriterImpl) { 2808 // If the operation result was replaced with null, all of the uses of this 2809 // value should be replaced. 2810 auto liveUserIt = llvm::find_if_not(result.getUsers(), [&](Operation *user) { 2811 return rewriterImpl.isOpIgnored(user); 2812 }); 2813 if (liveUserIt != result.user_end()) { 2814 InFlightDiagnostic diag = op->emitError("failed to legalize operation '") 2815 << op->getName() << "' marked as erased"; 2816 diag.attachNote(liveUserIt->getLoc()) 2817 << "found live user of result #" << result.getResultNumber() << ": " 2818 << *liveUserIt; 2819 return failure(); 2820 } 2821 return success(); 2822 } 2823 2824 /// Finds a user of the given value, or of any other value that the given value 2825 /// replaced, that was not replaced in the conversion process. 2826 static Operation *findLiveUserOfReplaced( 2827 Value initialValue, ConversionPatternRewriterImpl &rewriterImpl, 2828 const DenseMap<Value, SmallVector<Value>> &inverseMapping) { 2829 SmallVector<Value> worklist(1, initialValue); 2830 while (!worklist.empty()) { 2831 Value value = worklist.pop_back_val(); 2832 2833 // Walk the users of this value to see if there are any live users that 2834 // weren't replaced during conversion. 2835 auto liveUserIt = llvm::find_if_not(value.getUsers(), [&](Operation *user) { 2836 return rewriterImpl.isOpIgnored(user); 2837 }); 2838 if (liveUserIt != value.user_end()) 2839 return *liveUserIt; 2840 auto mapIt = inverseMapping.find(value); 2841 if (mapIt != inverseMapping.end()) 2842 worklist.append(mapIt->second); 2843 } 2844 return nullptr; 2845 } 2846 2847 LogicalResult OperationConverter::legalizeChangedResultType( 2848 Operation *op, OpResult result, Value newValue, 2849 TypeConverter *replConverter, ConversionPatternRewriter &rewriter, 2850 ConversionPatternRewriterImpl &rewriterImpl, 2851 const DenseMap<Value, SmallVector<Value>> &inverseMapping) { 2852 Operation *liveUser = 2853 findLiveUserOfReplaced(result, rewriterImpl, inverseMapping); 2854 if (!liveUser) 2855 return success(); 2856 2857 // Functor used to emit a conversion error for a failed materialization. 2858 auto emitConversionError = [&] { 2859 InFlightDiagnostic diag = op->emitError() 2860 << "failed to materialize conversion for result #" 2861 << result.getResultNumber() << " of operation '" 2862 << op->getName() 2863 << "' that remained live after conversion"; 2864 diag.attachNote(liveUser->getLoc()) 2865 << "see existing live user here: " << *liveUser; 2866 return failure(); 2867 }; 2868 2869 // If the replacement has a type converter, attempt to materialize a 2870 // conversion back to the original type. 2871 if (!replConverter) 2872 return emitConversionError(); 2873 2874 // Materialize a conversion for this live result value. 2875 Type resultType = result.getType(); 2876 Value convertedValue = replConverter->materializeSourceConversion( 2877 rewriter, op->getLoc(), resultType, newValue); 2878 if (!convertedValue) 2879 return emitConversionError(); 2880 2881 rewriterImpl.mapping.map(result, convertedValue); 2882 return success(); 2883 } 2884 2885 //===----------------------------------------------------------------------===// 2886 // Type Conversion 2887 //===----------------------------------------------------------------------===// 2888 2889 void TypeConverter::SignatureConversion::addInputs(unsigned origInputNo, 2890 ArrayRef<Type> types) { 2891 assert(!types.empty() && "expected valid types"); 2892 remapInput(origInputNo, /*newInputNo=*/argTypes.size(), types.size()); 2893 addInputs(types); 2894 } 2895 2896 void TypeConverter::SignatureConversion::addInputs(ArrayRef<Type> types) { 2897 assert(!types.empty() && 2898 "1->0 type remappings don't need to be added explicitly"); 2899 argTypes.append(types.begin(), types.end()); 2900 } 2901 2902 void TypeConverter::SignatureConversion::remapInput(unsigned origInputNo, 2903 unsigned newInputNo, 2904 unsigned newInputCount) { 2905 assert(!remappedInputs[origInputNo] && "input has already been remapped"); 2906 assert(newInputCount != 0 && "expected valid input count"); 2907 remappedInputs[origInputNo] = 2908 InputMapping{newInputNo, newInputCount, /*replacementValue=*/nullptr}; 2909 } 2910 2911 void TypeConverter::SignatureConversion::remapInput(unsigned origInputNo, 2912 Value replacementValue) { 2913 assert(!remappedInputs[origInputNo] && "input has already been remapped"); 2914 remappedInputs[origInputNo] = 2915 InputMapping{origInputNo, /*size=*/0, replacementValue}; 2916 } 2917 2918 LogicalResult TypeConverter::convertType(Type t, 2919 SmallVectorImpl<Type> &results) { 2920 auto existingIt = cachedDirectConversions.find(t); 2921 if (existingIt != cachedDirectConversions.end()) { 2922 if (existingIt->second) 2923 results.push_back(existingIt->second); 2924 return success(existingIt->second != nullptr); 2925 } 2926 auto multiIt = cachedMultiConversions.find(t); 2927 if (multiIt != cachedMultiConversions.end()) { 2928 results.append(multiIt->second.begin(), multiIt->second.end()); 2929 return success(); 2930 } 2931 2932 // Walk the added converters in reverse order to apply the most recently 2933 // registered first. 2934 size_t currentCount = results.size(); 2935 conversionCallStack.push_back(t); 2936 auto popConversionCallStack = 2937 llvm::make_scope_exit([this]() { conversionCallStack.pop_back(); }); 2938 for (ConversionCallbackFn &converter : llvm::reverse(conversions)) { 2939 if (Optional<LogicalResult> result = 2940 converter(t, results, conversionCallStack)) { 2941 if (!succeeded(*result)) { 2942 cachedDirectConversions.try_emplace(t, nullptr); 2943 return failure(); 2944 } 2945 auto newTypes = ArrayRef<Type>(results).drop_front(currentCount); 2946 if (newTypes.size() == 1) 2947 cachedDirectConversions.try_emplace(t, newTypes.front()); 2948 else 2949 cachedMultiConversions.try_emplace(t, llvm::to_vector<2>(newTypes)); 2950 return success(); 2951 } 2952 } 2953 return failure(); 2954 } 2955 2956 Type TypeConverter::convertType(Type t) { 2957 // Use the multi-type result version to convert the type. 2958 SmallVector<Type, 1> results; 2959 if (failed(convertType(t, results))) 2960 return nullptr; 2961 2962 // Check to ensure that only one type was produced. 2963 return results.size() == 1 ? results.front() : nullptr; 2964 } 2965 2966 LogicalResult TypeConverter::convertTypes(TypeRange types, 2967 SmallVectorImpl<Type> &results) { 2968 for (Type type : types) 2969 if (failed(convertType(type, results))) 2970 return failure(); 2971 return success(); 2972 } 2973 2974 bool TypeConverter::isLegal(Type type) { return convertType(type) == type; } 2975 bool TypeConverter::isLegal(Operation *op) { 2976 return isLegal(op->getOperandTypes()) && isLegal(op->getResultTypes()); 2977 } 2978 2979 bool TypeConverter::isLegal(Region *region) { 2980 return llvm::all_of(*region, [this](Block &block) { 2981 return isLegal(block.getArgumentTypes()); 2982 }); 2983 } 2984 2985 bool TypeConverter::isSignatureLegal(FunctionType ty) { 2986 return isLegal(llvm::concat<const Type>(ty.getInputs(), ty.getResults())); 2987 } 2988 2989 LogicalResult TypeConverter::convertSignatureArg(unsigned inputNo, Type type, 2990 SignatureConversion &result) { 2991 // Try to convert the given input type. 2992 SmallVector<Type, 1> convertedTypes; 2993 if (failed(convertType(type, convertedTypes))) 2994 return failure(); 2995 2996 // If this argument is being dropped, there is nothing left to do. 2997 if (convertedTypes.empty()) 2998 return success(); 2999 3000 // Otherwise, add the new inputs. 3001 result.addInputs(inputNo, convertedTypes); 3002 return success(); 3003 } 3004 LogicalResult TypeConverter::convertSignatureArgs(TypeRange types, 3005 SignatureConversion &result, 3006 unsigned origInputOffset) { 3007 for (unsigned i = 0, e = types.size(); i != e; ++i) 3008 if (failed(convertSignatureArg(origInputOffset + i, types[i], result))) 3009 return failure(); 3010 return success(); 3011 } 3012 3013 Value TypeConverter::materializeConversion( 3014 MutableArrayRef<MaterializationCallbackFn> materializations, 3015 OpBuilder &builder, Location loc, Type resultType, ValueRange inputs) { 3016 for (MaterializationCallbackFn &fn : llvm::reverse(materializations)) 3017 if (Optional<Value> result = fn(builder, resultType, inputs, loc)) 3018 return result.getValue(); 3019 return nullptr; 3020 } 3021 3022 auto TypeConverter::convertBlockSignature(Block *block) 3023 -> Optional<SignatureConversion> { 3024 SignatureConversion conversion(block->getNumArguments()); 3025 if (failed(convertSignatureArgs(block->getArgumentTypes(), conversion))) 3026 return llvm::None; 3027 return conversion; 3028 } 3029 3030 //===----------------------------------------------------------------------===// 3031 // FunctionLikeSignatureConversion 3032 //===----------------------------------------------------------------------===// 3033 3034 /// Create a default conversion pattern that rewrites the type signature of a 3035 /// FunctionLike op. This only supports FunctionLike ops which use FunctionType 3036 /// to represent their type. 3037 namespace { 3038 struct FunctionLikeSignatureConversion : public ConversionPattern { 3039 FunctionLikeSignatureConversion(StringRef functionLikeOpName, 3040 MLIRContext *ctx, TypeConverter &converter) 3041 : ConversionPattern(converter, functionLikeOpName, /*benefit=*/1, ctx) {} 3042 3043 /// Hook to implement combined matching and rewriting for FunctionLike ops. 3044 LogicalResult 3045 matchAndRewrite(Operation *op, ArrayRef<Value> operands, 3046 ConversionPatternRewriter &rewriter) const override { 3047 FunctionType type = function_like_impl::getFunctionType(op); 3048 3049 // Convert the original function types. 3050 TypeConverter::SignatureConversion result(type.getNumInputs()); 3051 SmallVector<Type, 1> newResults; 3052 if (failed(typeConverter->convertSignatureArgs(type.getInputs(), result)) || 3053 failed(typeConverter->convertTypes(type.getResults(), newResults)) || 3054 failed(rewriter.convertRegionTypes( 3055 &function_like_impl::getFunctionBody(op), *typeConverter, &result))) 3056 return failure(); 3057 3058 // Update the function signature in-place. 3059 auto newType = FunctionType::get(rewriter.getContext(), 3060 result.getConvertedTypes(), newResults); 3061 3062 rewriter.updateRootInPlace( 3063 op, [&] { function_like_impl::setFunctionType(op, newType); }); 3064 3065 return success(); 3066 } 3067 }; 3068 } // end anonymous namespace 3069 3070 void mlir::populateFunctionLikeTypeConversionPattern( 3071 StringRef functionLikeOpName, RewritePatternSet &patterns, 3072 TypeConverter &converter) { 3073 patterns.add<FunctionLikeSignatureConversion>( 3074 functionLikeOpName, patterns.getContext(), converter); 3075 } 3076 3077 void mlir::populateFuncOpTypeConversionPattern(RewritePatternSet &patterns, 3078 TypeConverter &converter) { 3079 populateFunctionLikeTypeConversionPattern<FuncOp>(patterns, converter); 3080 } 3081 3082 //===----------------------------------------------------------------------===// 3083 // ConversionTarget 3084 //===----------------------------------------------------------------------===// 3085 3086 void ConversionTarget::setOpAction(OperationName op, 3087 LegalizationAction action) { 3088 legalOperations[op].action = action; 3089 } 3090 3091 void ConversionTarget::setDialectAction(ArrayRef<StringRef> dialectNames, 3092 LegalizationAction action) { 3093 for (StringRef dialect : dialectNames) 3094 legalDialects[dialect] = action; 3095 } 3096 3097 auto ConversionTarget::getOpAction(OperationName op) const 3098 -> Optional<LegalizationAction> { 3099 Optional<LegalizationInfo> info = getOpInfo(op); 3100 return info ? info->action : Optional<LegalizationAction>(); 3101 } 3102 3103 auto ConversionTarget::isLegal(Operation *op) const 3104 -> Optional<LegalOpDetails> { 3105 Optional<LegalizationInfo> info = getOpInfo(op->getName()); 3106 if (!info) 3107 return llvm::None; 3108 3109 // Returns true if this operation instance is known to be legal. 3110 auto isOpLegal = [&] { 3111 // Handle dynamic legality either with the provided legality function. 3112 if (info->action == LegalizationAction::Dynamic) { 3113 Optional<bool> result = info->legalityFn(op); 3114 if (result) 3115 return *result; 3116 } 3117 3118 // Otherwise, the operation is only legal if it was marked 'Legal'. 3119 return info->action == LegalizationAction::Legal; 3120 }; 3121 if (!isOpLegal()) 3122 return llvm::None; 3123 3124 // This operation is legal, compute any additional legality information. 3125 LegalOpDetails legalityDetails; 3126 if (info->isRecursivelyLegal) { 3127 auto legalityFnIt = opRecursiveLegalityFns.find(op->getName()); 3128 if (legalityFnIt != opRecursiveLegalityFns.end()) { 3129 legalityDetails.isRecursivelyLegal = 3130 legalityFnIt->second(op).getValueOr(true); 3131 } else { 3132 legalityDetails.isRecursivelyLegal = true; 3133 } 3134 } 3135 return legalityDetails; 3136 } 3137 3138 bool ConversionTarget::isIllegal(Operation *op) const { 3139 Optional<LegalizationInfo> info = getOpInfo(op->getName()); 3140 if (!info) 3141 return false; 3142 3143 if (info->action == LegalizationAction::Dynamic) { 3144 Optional<bool> result = info->legalityFn(op); 3145 if (!result) 3146 return false; 3147 3148 return !(*result); 3149 } 3150 3151 return info->action == LegalizationAction::Illegal; 3152 } 3153 3154 static ConversionTarget::DynamicLegalityCallbackFn composeLegalityCallbacks( 3155 ConversionTarget::DynamicLegalityCallbackFn oldCallback, 3156 ConversionTarget::DynamicLegalityCallbackFn newCallback) { 3157 if (!oldCallback) 3158 return newCallback; 3159 3160 auto chain = [oldCl = std::move(oldCallback), newCl = std::move(newCallback)]( 3161 Operation *op) -> Optional<bool> { 3162 if (Optional<bool> result = newCl(op)) 3163 return *result; 3164 3165 return oldCl(op); 3166 }; 3167 return chain; 3168 } 3169 3170 void ConversionTarget::setLegalityCallback( 3171 OperationName name, const DynamicLegalityCallbackFn &callback) { 3172 assert(callback && "expected valid legality callback"); 3173 auto infoIt = legalOperations.find(name); 3174 assert(infoIt != legalOperations.end() && 3175 infoIt->second.action == LegalizationAction::Dynamic && 3176 "expected operation to already be marked as dynamically legal"); 3177 infoIt->second.legalityFn = 3178 composeLegalityCallbacks(std::move(infoIt->second.legalityFn), callback); 3179 } 3180 3181 void ConversionTarget::markOpRecursivelyLegal( 3182 OperationName name, const DynamicLegalityCallbackFn &callback) { 3183 auto infoIt = legalOperations.find(name); 3184 assert(infoIt != legalOperations.end() && 3185 infoIt->second.action != LegalizationAction::Illegal && 3186 "expected operation to already be marked as legal"); 3187 infoIt->second.isRecursivelyLegal = true; 3188 if (callback) 3189 opRecursiveLegalityFns[name] = composeLegalityCallbacks( 3190 std::move(opRecursiveLegalityFns[name]), callback); 3191 else 3192 opRecursiveLegalityFns.erase(name); 3193 } 3194 3195 void ConversionTarget::setLegalityCallback( 3196 ArrayRef<StringRef> dialects, const DynamicLegalityCallbackFn &callback) { 3197 assert(callback && "expected valid legality callback"); 3198 for (StringRef dialect : dialects) 3199 dialectLegalityFns[dialect] = composeLegalityCallbacks( 3200 std::move(dialectLegalityFns[dialect]), callback); 3201 } 3202 3203 void ConversionTarget::setLegalityCallback( 3204 const DynamicLegalityCallbackFn &callback) { 3205 assert(callback && "expected valid legality callback"); 3206 unknownLegalityFn = composeLegalityCallbacks(unknownLegalityFn, callback); 3207 } 3208 3209 auto ConversionTarget::getOpInfo(OperationName op) const 3210 -> Optional<LegalizationInfo> { 3211 // Check for info for this specific operation. 3212 auto it = legalOperations.find(op); 3213 if (it != legalOperations.end()) 3214 return it->second; 3215 // Check for info for the parent dialect. 3216 auto dialectIt = legalDialects.find(op.getDialectNamespace()); 3217 if (dialectIt != legalDialects.end()) { 3218 DynamicLegalityCallbackFn callback; 3219 auto dialectFn = dialectLegalityFns.find(op.getDialectNamespace()); 3220 if (dialectFn != dialectLegalityFns.end()) 3221 callback = dialectFn->second; 3222 return LegalizationInfo{dialectIt->second, /*isRecursivelyLegal=*/false, 3223 callback}; 3224 } 3225 // Otherwise, check if we mark unknown operations as dynamic. 3226 if (unknownLegalityFn) 3227 return LegalizationInfo{LegalizationAction::Dynamic, 3228 /*isRecursivelyLegal=*/false, unknownLegalityFn}; 3229 return llvm::None; 3230 } 3231 3232 //===----------------------------------------------------------------------===// 3233 // Op Conversion Entry Points 3234 //===----------------------------------------------------------------------===// 3235 3236 //===----------------------------------------------------------------------===// 3237 // Partial Conversion 3238 3239 LogicalResult 3240 mlir::applyPartialConversion(ArrayRef<Operation *> ops, 3241 ConversionTarget &target, 3242 const FrozenRewritePatternSet &patterns, 3243 DenseSet<Operation *> *unconvertedOps) { 3244 OperationConverter opConverter(target, patterns, OpConversionMode::Partial, 3245 unconvertedOps); 3246 return opConverter.convertOperations(ops); 3247 } 3248 LogicalResult 3249 mlir::applyPartialConversion(Operation *op, ConversionTarget &target, 3250 const FrozenRewritePatternSet &patterns, 3251 DenseSet<Operation *> *unconvertedOps) { 3252 return applyPartialConversion(llvm::makeArrayRef(op), target, patterns, 3253 unconvertedOps); 3254 } 3255 3256 //===----------------------------------------------------------------------===// 3257 // Full Conversion 3258 3259 LogicalResult 3260 mlir::applyFullConversion(ArrayRef<Operation *> ops, ConversionTarget &target, 3261 const FrozenRewritePatternSet &patterns) { 3262 OperationConverter opConverter(target, patterns, OpConversionMode::Full); 3263 return opConverter.convertOperations(ops); 3264 } 3265 LogicalResult 3266 mlir::applyFullConversion(Operation *op, ConversionTarget &target, 3267 const FrozenRewritePatternSet &patterns) { 3268 return applyFullConversion(llvm::makeArrayRef(op), target, patterns); 3269 } 3270 3271 //===----------------------------------------------------------------------===// 3272 // Analysis Conversion 3273 3274 LogicalResult 3275 mlir::applyAnalysisConversion(ArrayRef<Operation *> ops, 3276 ConversionTarget &target, 3277 const FrozenRewritePatternSet &patterns, 3278 DenseSet<Operation *> &convertedOps) { 3279 OperationConverter opConverter(target, patterns, OpConversionMode::Analysis, 3280 &convertedOps); 3281 return opConverter.convertOperations(ops); 3282 } 3283 LogicalResult 3284 mlir::applyAnalysisConversion(Operation *op, ConversionTarget &target, 3285 const FrozenRewritePatternSet &patterns, 3286 DenseSet<Operation *> &convertedOps) { 3287 return applyAnalysisConversion(llvm::makeArrayRef(op), target, patterns, 3288 convertedOps); 3289 } 3290