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