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