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