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.
920   for (auto &repl : llvm::reverse(replacements))
921     repl.first->erase();
922 
923   argConverter.applyRewrites(mapping);
924 
925   // Now that the ops have been erased, also erase dangling blocks.
926   eraseDanglingBlocks();
927 }
928 
929 //===----------------------------------------------------------------------===//
930 // State Management
931 
932 RewriterState ConversionPatternRewriterImpl::getCurrentState() {
933   return RewriterState(createdOps.size(), replacements.size(),
934                        argReplacements.size(), blockActions.size(),
935                        ignoredOps.size(), rootUpdates.size());
936 }
937 
938 void ConversionPatternRewriterImpl::resetState(RewriterState state) {
939   // Reset any operations that were updated in place.
940   for (unsigned i = state.numRootUpdates, e = rootUpdates.size(); i != e; ++i)
941     rootUpdates[i].resetOperation();
942   rootUpdates.resize(state.numRootUpdates);
943 
944   // Reset any replaced arguments.
945   for (BlockArgument replacedArg :
946        llvm::drop_begin(argReplacements, state.numArgReplacements))
947     mapping.erase(replacedArg);
948   argReplacements.resize(state.numArgReplacements);
949 
950   // Undo any block actions.
951   undoBlockActions(state.numBlockActions);
952 
953   // Reset any replaced operations and undo any saved mappings.
954   for (auto &repl : llvm::drop_begin(replacements, state.numReplacements))
955     for (auto result : repl.first->getResults())
956       mapping.erase(result);
957   while (replacements.size() != state.numReplacements)
958     replacements.pop_back();
959 
960   // Pop all of the newly created operations.
961   while (createdOps.size() != state.numCreatedOps) {
962     detachNestedAndErase(createdOps.back());
963     createdOps.pop_back();
964   }
965 
966   // Pop all of the recorded ignored operations that are no longer valid.
967   while (ignoredOps.size() != state.numIgnoredOperations)
968     ignoredOps.pop_back();
969 
970   // Reset operations with changed results.
971   while (!operationsWithChangedResults.empty() &&
972          operationsWithChangedResults.back() >= state.numReplacements)
973     operationsWithChangedResults.pop_back();
974 }
975 
976 void ConversionPatternRewriterImpl::eraseDanglingBlocks() {
977   for (auto &action : blockActions)
978     if (action.kind == BlockActionKind::Erase)
979       delete action.block;
980 }
981 
982 void ConversionPatternRewriterImpl::undoBlockActions(
983     unsigned numActionsToKeep) {
984   for (auto &action :
985        llvm::reverse(llvm::drop_begin(blockActions, numActionsToKeep))) {
986     switch (action.kind) {
987     // Delete the created block.
988     case BlockActionKind::Create: {
989       // Unlink all of the operations within this block, they will be deleted
990       // separately.
991       auto &blockOps = action.block->getOperations();
992       while (!blockOps.empty())
993         blockOps.remove(blockOps.begin());
994       action.block->dropAllDefinedValueUses();
995       action.block->erase();
996       break;
997     }
998     // Put the block (owned by action) back into its original position.
999     case BlockActionKind::Erase: {
1000       auto &blockList = action.originalPosition.region->getBlocks();
1001       Block *insertAfterBlock = action.originalPosition.insertAfterBlock;
1002       blockList.insert((insertAfterBlock
1003                             ? std::next(Region::iterator(insertAfterBlock))
1004                             : blockList.begin()),
1005                        action.block);
1006       break;
1007     }
1008     // Split the block at the position which was originally the end of the
1009     // destination block (owned by action), and put the instructions back into
1010     // the block used before the merge.
1011     case BlockActionKind::Merge: {
1012       Block *sourceBlock = action.mergeInfo.sourceBlock;
1013       Block::iterator splitPoint =
1014           (action.mergeInfo.destBlockLastInst
1015                ? ++Block::iterator(action.mergeInfo.destBlockLastInst)
1016                : action.block->begin());
1017       sourceBlock->getOperations().splice(sourceBlock->begin(),
1018                                           action.block->getOperations(),
1019                                           splitPoint, action.block->end());
1020       break;
1021     }
1022     // Move the block back to its original position.
1023     case BlockActionKind::Move: {
1024       Region *originalRegion = action.originalPosition.region;
1025       Block *insertAfterBlock = action.originalPosition.insertAfterBlock;
1026       originalRegion->getBlocks().splice(
1027           (insertAfterBlock ? std::next(Region::iterator(insertAfterBlock))
1028                             : originalRegion->end()),
1029           action.block->getParent()->getBlocks(), action.block);
1030       break;
1031     }
1032     // Merge back the block that was split out.
1033     case BlockActionKind::Split: {
1034       action.originalBlock->getOperations().splice(
1035           action.originalBlock->end(), action.block->getOperations());
1036       action.block->dropAllDefinedValueUses();
1037       action.block->erase();
1038       break;
1039     }
1040     // Undo the type conversion.
1041     case BlockActionKind::TypeConversion: {
1042       argConverter.discardRewrites(action.block);
1043       break;
1044     }
1045     }
1046   }
1047   blockActions.resize(numActionsToKeep);
1048 }
1049 
1050 LogicalResult ConversionPatternRewriterImpl::remapValues(
1051     Location loc, PatternRewriter &rewriter, TypeConverter *converter,
1052     Operation::operand_range operands, SmallVectorImpl<Value> &remapped) {
1053   remapped.reserve(llvm::size(operands));
1054 
1055   SmallVector<Type, 1> legalTypes;
1056   for (auto it : llvm::enumerate(operands)) {
1057     Value operand = it.value();
1058     Type origType = operand.getType();
1059 
1060     // If a converter was provided, get the desired legal types for this
1061     // operand.
1062     Type desiredType;
1063     if (converter) {
1064       // If there is no legal conversion, fail to match this pattern.
1065       legalTypes.clear();
1066       if (failed(converter->convertType(origType, legalTypes))) {
1067         return notifyMatchFailure(loc, [=](Diagnostic &diag) {
1068           diag << "unable to convert type for operand #" << it.index()
1069                << ", type was " << origType;
1070         });
1071       }
1072       // TODO: There currently isn't any mechanism to do 1->N type conversion
1073       // via the PatternRewriter replacement API, so for now we just ignore it.
1074       if (legalTypes.size() == 1)
1075         desiredType = legalTypes.front();
1076     } else {
1077       // TODO: What we should do here is just set `desiredType` to `origType`
1078       // and then handle the necessary type conversions after the conversion
1079       // process has finished. Unfortunately a lot of patterns currently rely on
1080       // receiving the new operands even if the types change, so we keep the
1081       // original behavior here for now until all of the patterns relying on
1082       // this get updated.
1083     }
1084     Value newOperand = mapping.lookupOrDefault(operand, desiredType);
1085 
1086     // Handle the case where the conversion was 1->1 and the new operand type
1087     // isn't legal.
1088     Type newOperandType = newOperand.getType();
1089     if (converter && desiredType && newOperandType != desiredType) {
1090       // Attempt to materialize a conversion for this new value.
1091       newOperand = converter->materializeTargetConversion(
1092           rewriter, loc, desiredType, newOperand);
1093       if (!newOperand) {
1094         return notifyMatchFailure(loc, [=](Diagnostic &diag) {
1095           diag << "unable to materialize a conversion for "
1096                   "operand #"
1097                << it.index() << ", from " << newOperandType << " to "
1098                << desiredType;
1099         });
1100       }
1101     }
1102     remapped.push_back(newOperand);
1103   }
1104   return success();
1105 }
1106 
1107 bool ConversionPatternRewriterImpl::isOpIgnored(Operation *op) const {
1108   // Check to see if this operation was replaced or its parent ignored.
1109   return replacements.count(op) || ignoredOps.count(op->getParentOp());
1110 }
1111 
1112 void ConversionPatternRewriterImpl::markNestedOpsIgnored(Operation *op) {
1113   // Walk this operation and collect nested operations that define non-empty
1114   // regions. We mark such operations as 'ignored' so that we know we don't have
1115   // to convert them, or their nested ops.
1116   if (op->getNumRegions() == 0)
1117     return;
1118   op->walk([&](Operation *op) {
1119     if (llvm::any_of(op->getRegions(),
1120                      [](Region &region) { return !region.empty(); }))
1121       ignoredOps.insert(op);
1122   });
1123 }
1124 
1125 //===----------------------------------------------------------------------===//
1126 // Type Conversion
1127 
1128 FailureOr<Block *> ConversionPatternRewriterImpl::convertBlockSignature(
1129     Block *block, TypeConverter &converter,
1130     TypeConverter::SignatureConversion *conversion) {
1131   FailureOr<Block *> result =
1132       conversion ? argConverter.applySignatureConversion(
1133                        block, converter, *conversion, mapping, argReplacements)
1134                  : argConverter.convertSignature(block, converter, mapping,
1135                                                  argReplacements);
1136   if (Block *newBlock = result.getValue()) {
1137     if (newBlock != block)
1138       blockActions.push_back(BlockAction::getTypeConversion(newBlock));
1139   }
1140   return result;
1141 }
1142 
1143 Block *ConversionPatternRewriterImpl::applySignatureConversion(
1144     Region *region, TypeConverter::SignatureConversion &conversion) {
1145   if (!region->empty()) {
1146     return *convertBlockSignature(&region->front(), defaultTypeConverter,
1147                                   &conversion);
1148   }
1149   return nullptr;
1150 }
1151 
1152 FailureOr<Block *> ConversionPatternRewriterImpl::convertRegionTypes(
1153     Region *region, TypeConverter &converter,
1154     TypeConverter::SignatureConversion *entryConversion) {
1155   argConverter.setConverter(region, &converter);
1156   if (region->empty())
1157     return nullptr;
1158 
1159   if (failed(convertNonEntryRegionTypes(region, converter)))
1160     return failure();
1161 
1162   FailureOr<Block *> newEntry =
1163       convertBlockSignature(&region->front(), converter, entryConversion);
1164   return newEntry;
1165 }
1166 
1167 LogicalResult ConversionPatternRewriterImpl::convertNonEntryRegionTypes(
1168     Region *region, TypeConverter &converter) {
1169   argConverter.setConverter(region, &converter);
1170   if (region->empty())
1171     return success();
1172 
1173   // Convert the arguments of each block within the region.
1174   for (Block &block : llvm::make_early_inc_range(llvm::drop_begin(*region, 1)))
1175     if (failed(convertBlockSignature(&block, converter)))
1176       return failure();
1177   return success();
1178 }
1179 
1180 //===----------------------------------------------------------------------===//
1181 // Rewriter Notification Hooks
1182 
1183 void ConversionPatternRewriterImpl::notifyOpReplaced(Operation *op,
1184                                                      ValueRange newValues) {
1185   assert(newValues.size() == op->getNumResults());
1186   assert(!replacements.count(op) && "operation was already replaced");
1187 
1188   // Track if any of the results changed, e.g. erased and replaced with null.
1189   bool resultChanged = false;
1190 
1191   // Create mappings for each of the new result values.
1192   Value newValue, result;
1193   for (auto it : llvm::zip(newValues, op->getResults())) {
1194     std::tie(newValue, result) = it;
1195     if (!newValue) {
1196       resultChanged = true;
1197       continue;
1198     }
1199     // Remap, and check for any result type changes.
1200     mapping.map(result, newValue);
1201     resultChanged |= (newValue.getType() != result.getType());
1202   }
1203   if (resultChanged)
1204     operationsWithChangedResults.push_back(replacements.size());
1205 
1206   // Record the requested operation replacement.
1207   TypeConverter *converter = nullptr;
1208   if (currentConversionPattern)
1209     converter = currentConversionPattern->getTypeConverter();
1210   replacements.insert(std::make_pair(op, OpReplacement(converter)));
1211 
1212   // Mark this operation as recursively ignored so that we don't need to
1213   // convert any nested operations.
1214   markNestedOpsIgnored(op);
1215 }
1216 
1217 void ConversionPatternRewriterImpl::notifyBlockIsBeingErased(Block *block) {
1218   Region *region = block->getParent();
1219   Block *origPrevBlock = block->getPrevNode();
1220   blockActions.push_back(BlockAction::getErase(block, {region, origPrevBlock}));
1221 }
1222 
1223 void ConversionPatternRewriterImpl::notifyCreatedBlock(Block *block) {
1224   blockActions.push_back(BlockAction::getCreate(block));
1225 }
1226 
1227 void ConversionPatternRewriterImpl::notifySplitBlock(Block *block,
1228                                                      Block *continuation) {
1229   blockActions.push_back(BlockAction::getSplit(continuation, block));
1230 }
1231 
1232 void ConversionPatternRewriterImpl::notifyBlocksBeingMerged(Block *block,
1233                                                             Block *srcBlock) {
1234   blockActions.push_back(BlockAction::getMerge(block, srcBlock));
1235 }
1236 
1237 void ConversionPatternRewriterImpl::notifyRegionIsBeingInlinedBefore(
1238     Region &region, Region &parent, Region::iterator before) {
1239   if (region.empty())
1240     return;
1241   Block *laterBlock = &region.back();
1242   for (auto &earlierBlock : llvm::drop_begin(llvm::reverse(region), 1)) {
1243     blockActions.push_back(
1244         BlockAction::getMove(laterBlock, {&region, &earlierBlock}));
1245     laterBlock = &earlierBlock;
1246   }
1247   blockActions.push_back(BlockAction::getMove(laterBlock, {&region, nullptr}));
1248 }
1249 
1250 void ConversionPatternRewriterImpl::notifyRegionWasClonedBefore(
1251     iterator_range<Region::iterator> &blocks, Location origRegionLoc) {
1252   for (Block &block : blocks)
1253     blockActions.push_back(BlockAction::getCreate(&block));
1254 
1255   // Compute the conversion set for the inlined region.
1256   auto result = computeConversionSet(blocks, origRegionLoc, createdOps);
1257 
1258   // This original region has already had its conversion set computed, so there
1259   // shouldn't be any new failures.
1260   (void)result;
1261   assert(succeeded(result) && "expected region to have no unreachable blocks");
1262 }
1263 
1264 LogicalResult ConversionPatternRewriterImpl::notifyMatchFailure(
1265     Location loc, function_ref<void(Diagnostic &)> reasonCallback) {
1266   LLVM_DEBUG({
1267     Diagnostic diag(loc, DiagnosticSeverity::Remark);
1268     reasonCallback(diag);
1269     logger.startLine() << "** Failure : " << diag.str() << "\n";
1270   });
1271   return failure();
1272 }
1273 
1274 //===----------------------------------------------------------------------===//
1275 // ConversionPatternRewriter
1276 //===----------------------------------------------------------------------===//
1277 
1278 ConversionPatternRewriter::ConversionPatternRewriter(MLIRContext *ctx)
1279     : PatternRewriter(ctx),
1280       impl(new detail::ConversionPatternRewriterImpl(*this)) {}
1281 ConversionPatternRewriter::~ConversionPatternRewriter() {}
1282 
1283 /// PatternRewriter hook for replacing the results of an operation when the
1284 /// given functor returns true.
1285 void ConversionPatternRewriter::replaceOpWithIf(
1286     Operation *op, ValueRange newValues, bool *allUsesReplaced,
1287     llvm::unique_function<bool(OpOperand &) const> functor) {
1288   // TODO: To support this we will need to rework a bit of how replacements are
1289   // tracked, given that this isn't guranteed to replace all of the uses of an
1290   // operation. The main change is that now an operation can be replaced
1291   // multiple times, in parts. The current "set" based tracking is mainly useful
1292   // for tracking if a replaced operation should be ignored, i.e. if all of the
1293   // uses will be replaced.
1294   llvm_unreachable(
1295       "replaceOpWithIf is currently not supported by DialectConversion");
1296 }
1297 
1298 /// PatternRewriter hook for replacing the results of an operation.
1299 void ConversionPatternRewriter::replaceOp(Operation *op, ValueRange newValues) {
1300   LLVM_DEBUG({
1301     impl->logger.startLine()
1302         << "** Replace : '" << op->getName() << "'(" << op << ")\n";
1303   });
1304   impl->notifyOpReplaced(op, newValues);
1305 }
1306 
1307 /// PatternRewriter hook for erasing a dead operation. The uses of this
1308 /// operation *must* be made dead by the end of the conversion process,
1309 /// otherwise an assert will be issued.
1310 void ConversionPatternRewriter::eraseOp(Operation *op) {
1311   LLVM_DEBUG({
1312     impl->logger.startLine()
1313         << "** Erase   : '" << op->getName() << "'(" << op << ")\n";
1314   });
1315   SmallVector<Value, 1> nullRepls(op->getNumResults(), nullptr);
1316   impl->notifyOpReplaced(op, nullRepls);
1317 }
1318 
1319 void ConversionPatternRewriter::eraseBlock(Block *block) {
1320   impl->notifyBlockIsBeingErased(block);
1321 
1322   // Mark all ops for erasure.
1323   for (Operation &op : *block)
1324     eraseOp(&op);
1325 
1326   // Unlink the block from its parent region. The block is kept in the block
1327   // action and will be actually destroyed when rewrites are applied. This
1328   // allows us to keep the operations in the block live and undo the removal by
1329   // re-inserting the block.
1330   block->getParent()->getBlocks().remove(block);
1331 }
1332 
1333 Block *ConversionPatternRewriter::applySignatureConversion(
1334     Region *region, TypeConverter::SignatureConversion &conversion) {
1335   return impl->applySignatureConversion(region, conversion);
1336 }
1337 
1338 FailureOr<Block *> ConversionPatternRewriter::convertRegionTypes(
1339     Region *region, TypeConverter &converter,
1340     TypeConverter::SignatureConversion *entryConversion) {
1341   return impl->convertRegionTypes(region, converter, entryConversion);
1342 }
1343 
1344 LogicalResult ConversionPatternRewriter::convertNonEntryRegionTypes(
1345     Region *region, TypeConverter &converter) {
1346   return impl->convertNonEntryRegionTypes(region, converter);
1347 }
1348 
1349 void ConversionPatternRewriter::replaceUsesOfBlockArgument(BlockArgument from,
1350                                                            Value to) {
1351   LLVM_DEBUG({
1352     Operation *parentOp = from.getOwner()->getParentOp();
1353     impl->logger.startLine() << "** Replace Argument : '" << from
1354                              << "'(in region of '" << parentOp->getName()
1355                              << "'(" << from.getOwner()->getParentOp() << ")\n";
1356   });
1357   impl->argReplacements.push_back(from);
1358   impl->mapping.map(impl->mapping.lookupOrDefault(from), to);
1359 }
1360 
1361 /// Return the converted value that replaces 'key'. Return 'key' if there is
1362 /// no such a converted value.
1363 Value ConversionPatternRewriter::getRemappedValue(Value key) {
1364   return impl->mapping.lookupOrDefault(key);
1365 }
1366 
1367 /// PatternRewriter hook for creating a new block with the given arguments.
1368 void ConversionPatternRewriter::notifyBlockCreated(Block *block) {
1369   impl->notifyCreatedBlock(block);
1370 }
1371 
1372 /// PatternRewriter hook for splitting a block into two parts.
1373 Block *ConversionPatternRewriter::splitBlock(Block *block,
1374                                              Block::iterator before) {
1375   auto *continuation = PatternRewriter::splitBlock(block, before);
1376   impl->notifySplitBlock(block, continuation);
1377   return continuation;
1378 }
1379 
1380 /// PatternRewriter hook for merging a block into another.
1381 void ConversionPatternRewriter::mergeBlocks(Block *source, Block *dest,
1382                                             ValueRange argValues) {
1383   impl->notifyBlocksBeingMerged(dest, source);
1384   assert(llvm::all_of(source->getPredecessors(),
1385                       [dest](Block *succ) { return succ == dest; }) &&
1386          "expected 'source' to have no predecessors or only 'dest'");
1387   assert(argValues.size() == source->getNumArguments() &&
1388          "incorrect # of argument replacement values");
1389   for (auto it : llvm::zip(source->getArguments(), argValues))
1390     replaceUsesOfBlockArgument(std::get<0>(it), std::get<1>(it));
1391   dest->getOperations().splice(dest->end(), source->getOperations());
1392   eraseBlock(source);
1393 }
1394 
1395 /// PatternRewriter hook for moving blocks out of a region.
1396 void ConversionPatternRewriter::inlineRegionBefore(Region &region,
1397                                                    Region &parent,
1398                                                    Region::iterator before) {
1399   impl->notifyRegionIsBeingInlinedBefore(region, parent, before);
1400   PatternRewriter::inlineRegionBefore(region, parent, before);
1401 }
1402 
1403 /// PatternRewriter hook for cloning blocks of one region into another.
1404 void ConversionPatternRewriter::cloneRegionBefore(
1405     Region &region, Region &parent, Region::iterator before,
1406     BlockAndValueMapping &mapping) {
1407   if (region.empty())
1408     return;
1409   PatternRewriter::cloneRegionBefore(region, parent, before, mapping);
1410 
1411   // Collect the range of the cloned blocks.
1412   auto clonedBeginIt = mapping.lookup(&region.front())->getIterator();
1413   auto clonedBlocks = llvm::make_range(clonedBeginIt, before);
1414   impl->notifyRegionWasClonedBefore(clonedBlocks, region.getLoc());
1415 }
1416 
1417 /// PatternRewriter hook for creating a new operation.
1418 void ConversionPatternRewriter::notifyOperationInserted(Operation *op) {
1419   LLVM_DEBUG({
1420     impl->logger.startLine()
1421         << "** Insert  : '" << op->getName() << "'(" << op << ")\n";
1422   });
1423   impl->createdOps.push_back(op);
1424 }
1425 
1426 /// PatternRewriter hook for updating the root operation in-place.
1427 void ConversionPatternRewriter::startRootUpdate(Operation *op) {
1428 #ifndef NDEBUG
1429   impl->pendingRootUpdates.insert(op);
1430 #endif
1431   impl->rootUpdates.emplace_back(op);
1432 }
1433 
1434 /// PatternRewriter hook for updating the root operation in-place.
1435 void ConversionPatternRewriter::finalizeRootUpdate(Operation *op) {
1436   // There is nothing to do here, we only need to track the operation at the
1437   // start of the update.
1438 #ifndef NDEBUG
1439   assert(impl->pendingRootUpdates.erase(op) &&
1440          "operation did not have a pending in-place update");
1441 #endif
1442 }
1443 
1444 /// PatternRewriter hook for updating the root operation in-place.
1445 void ConversionPatternRewriter::cancelRootUpdate(Operation *op) {
1446 #ifndef NDEBUG
1447   assert(impl->pendingRootUpdates.erase(op) &&
1448          "operation did not have a pending in-place update");
1449 #endif
1450   // Erase the last update for this operation.
1451   auto stateHasOp = [op](const auto &it) { return it.getOperation() == op; };
1452   auto &rootUpdates = impl->rootUpdates;
1453   auto it = llvm::find_if(llvm::reverse(rootUpdates), stateHasOp);
1454   rootUpdates.erase(rootUpdates.begin() + (rootUpdates.rend() - it));
1455 }
1456 
1457 /// PatternRewriter hook for notifying match failure reasons.
1458 LogicalResult ConversionPatternRewriter::notifyMatchFailure(
1459     Operation *op, function_ref<void(Diagnostic &)> reasonCallback) {
1460   return impl->notifyMatchFailure(op->getLoc(), reasonCallback);
1461 }
1462 
1463 /// Return a reference to the internal implementation.
1464 detail::ConversionPatternRewriterImpl &ConversionPatternRewriter::getImpl() {
1465   return *impl;
1466 }
1467 
1468 //===----------------------------------------------------------------------===//
1469 // ConversionPattern
1470 //===----------------------------------------------------------------------===//
1471 
1472 /// Attempt to match and rewrite the IR root at the specified operation.
1473 LogicalResult
1474 ConversionPattern::matchAndRewrite(Operation *op,
1475                                    PatternRewriter &rewriter) const {
1476   auto &dialectRewriter = static_cast<ConversionPatternRewriter &>(rewriter);
1477   auto &rewriterImpl = dialectRewriter.getImpl();
1478 
1479   // Track the current conversion pattern in the rewriter.
1480   assert(!rewriterImpl.currentConversionPattern &&
1481          "already inside of a pattern rewrite");
1482   llvm::SaveAndRestore<const ConversionPattern *> currentPatternGuard(
1483       rewriterImpl.currentConversionPattern, this);
1484 
1485   // Remap the operands of the operation.
1486   SmallVector<Value, 4> operands;
1487   if (failed(rewriterImpl.remapValues(op->getLoc(), rewriter,
1488                                       getTypeConverter(), op->getOperands(),
1489                                       operands))) {
1490     return failure();
1491   }
1492   return matchAndRewrite(op, operands, dialectRewriter);
1493 }
1494 
1495 //===----------------------------------------------------------------------===//
1496 // OperationLegalizer
1497 //===----------------------------------------------------------------------===//
1498 
1499 namespace {
1500 /// A set of rewrite patterns that can be used to legalize a given operation.
1501 using LegalizationPatterns = SmallVector<const Pattern *, 1>;
1502 
1503 /// This class defines a recursive operation legalizer.
1504 class OperationLegalizer {
1505 public:
1506   using LegalizationAction = ConversionTarget::LegalizationAction;
1507 
1508   OperationLegalizer(ConversionTarget &targetInfo,
1509                      const FrozenRewritePatternSet &patterns);
1510 
1511   /// Returns true if the given operation is known to be illegal on the target.
1512   bool isIllegal(Operation *op) const;
1513 
1514   /// Attempt to legalize the given operation. Returns success if the operation
1515   /// was legalized, failure otherwise.
1516   LogicalResult legalize(Operation *op, ConversionPatternRewriter &rewriter);
1517 
1518   /// Returns the conversion target in use by the legalizer.
1519   ConversionTarget &getTarget() { return target; }
1520 
1521 private:
1522   /// Attempt to legalize the given operation by folding it.
1523   LogicalResult legalizeWithFold(Operation *op,
1524                                  ConversionPatternRewriter &rewriter);
1525 
1526   /// Attempt to legalize the given operation by applying a pattern. Returns
1527   /// success if the operation was legalized, failure otherwise.
1528   LogicalResult legalizeWithPattern(Operation *op,
1529                                     ConversionPatternRewriter &rewriter);
1530 
1531   /// Return true if the given pattern may be applied to the given operation,
1532   /// false otherwise.
1533   bool canApplyPattern(Operation *op, const Pattern &pattern,
1534                        ConversionPatternRewriter &rewriter);
1535 
1536   /// Legalize the resultant IR after successfully applying the given pattern.
1537   LogicalResult legalizePatternResult(Operation *op, const Pattern &pattern,
1538                                       ConversionPatternRewriter &rewriter,
1539                                       RewriterState &curState);
1540 
1541   /// Legalizes the actions registered during the execution of a pattern.
1542   LogicalResult legalizePatternBlockActions(Operation *op,
1543                                             ConversionPatternRewriter &rewriter,
1544                                             ConversionPatternRewriterImpl &impl,
1545                                             RewriterState &state,
1546                                             RewriterState &newState);
1547   LogicalResult legalizePatternCreatedOperations(
1548       ConversionPatternRewriter &rewriter, ConversionPatternRewriterImpl &impl,
1549       RewriterState &state, RewriterState &newState);
1550   LogicalResult legalizePatternRootUpdates(ConversionPatternRewriter &rewriter,
1551                                            ConversionPatternRewriterImpl &impl,
1552                                            RewriterState &state,
1553                                            RewriterState &newState);
1554 
1555   //===--------------------------------------------------------------------===//
1556   // Cost Model
1557   //===--------------------------------------------------------------------===//
1558 
1559   /// Build an optimistic legalization graph given the provided patterns. This
1560   /// function populates 'anyOpLegalizerPatterns' and 'legalizerPatterns' with
1561   /// patterns for operations that are not directly legal, but may be
1562   /// transitively legal for the current target given the provided patterns.
1563   void buildLegalizationGraph(
1564       LegalizationPatterns &anyOpLegalizerPatterns,
1565       DenseMap<OperationName, LegalizationPatterns> &legalizerPatterns);
1566 
1567   /// Compute the benefit of each node within the computed legalization graph.
1568   /// This orders the patterns within 'legalizerPatterns' based upon two
1569   /// criteria:
1570   ///  1) Prefer patterns that have the lowest legalization depth, i.e.
1571   ///     represent the more direct mapping to the target.
1572   ///  2) When comparing patterns with the same legalization depth, prefer the
1573   ///     pattern with the highest PatternBenefit. This allows for users to
1574   ///     prefer specific legalizations over others.
1575   void computeLegalizationGraphBenefit(
1576       LegalizationPatterns &anyOpLegalizerPatterns,
1577       DenseMap<OperationName, LegalizationPatterns> &legalizerPatterns);
1578 
1579   /// Compute the legalization depth when legalizing an operation of the given
1580   /// type.
1581   unsigned computeOpLegalizationDepth(
1582       OperationName op, DenseMap<OperationName, unsigned> &minOpPatternDepth,
1583       DenseMap<OperationName, LegalizationPatterns> &legalizerPatterns);
1584 
1585   /// Apply the conversion cost model to the given set of patterns, and return
1586   /// the smallest legalization depth of any of the patterns. See
1587   /// `computeLegalizationGraphBenefit` for the breakdown of the cost model.
1588   unsigned applyCostModelToPatterns(
1589       LegalizationPatterns &patterns,
1590       DenseMap<OperationName, unsigned> &minOpPatternDepth,
1591       DenseMap<OperationName, LegalizationPatterns> &legalizerPatterns);
1592 
1593   /// The current set of patterns that have been applied.
1594   SmallPtrSet<const Pattern *, 8> appliedPatterns;
1595 
1596   /// The legalization information provided by the target.
1597   ConversionTarget &target;
1598 
1599   /// The pattern applicator to use for conversions.
1600   PatternApplicator applicator;
1601 };
1602 } // namespace
1603 
1604 OperationLegalizer::OperationLegalizer(ConversionTarget &targetInfo,
1605                                        const FrozenRewritePatternSet &patterns)
1606     : target(targetInfo), applicator(patterns) {
1607   // The set of patterns that can be applied to illegal operations to transform
1608   // them into legal ones.
1609   DenseMap<OperationName, LegalizationPatterns> legalizerPatterns;
1610   LegalizationPatterns anyOpLegalizerPatterns;
1611 
1612   buildLegalizationGraph(anyOpLegalizerPatterns, legalizerPatterns);
1613   computeLegalizationGraphBenefit(anyOpLegalizerPatterns, legalizerPatterns);
1614 }
1615 
1616 bool OperationLegalizer::isIllegal(Operation *op) const {
1617   // Check if the target explicitly marked this operation as illegal.
1618   return target.getOpAction(op->getName()) == LegalizationAction::Illegal;
1619 }
1620 
1621 LogicalResult
1622 OperationLegalizer::legalize(Operation *op,
1623                              ConversionPatternRewriter &rewriter) {
1624 #ifndef NDEBUG
1625   const char *logLineComment =
1626       "//===-------------------------------------------===//\n";
1627 
1628   auto &rewriterImpl = rewriter.getImpl();
1629 #endif
1630   LLVM_DEBUG({
1631     auto &os = rewriterImpl.logger;
1632     os.getOStream() << "\n";
1633     os.startLine() << logLineComment;
1634     os.startLine() << "Legalizing operation : '" << op->getName() << "'(" << op
1635                    << ") {\n";
1636     os.indent();
1637 
1638     // If the operation has no regions, just print it here.
1639     if (op->getNumRegions() == 0) {
1640       op->print(os.startLine(), OpPrintingFlags().printGenericOpForm());
1641       os.getOStream() << "\n\n";
1642     }
1643   });
1644 
1645   // Check if this operation is legal on the target.
1646   if (auto legalityInfo = target.isLegal(op)) {
1647     LLVM_DEBUG({
1648       logSuccess(
1649           rewriterImpl.logger, "operation marked legal by the target{0}",
1650           legalityInfo->isRecursivelyLegal
1651               ? "; NOTE: operation is recursively legal; skipping internals"
1652               : "");
1653       rewriterImpl.logger.startLine() << logLineComment;
1654     });
1655 
1656     // If this operation is recursively legal, mark its children as ignored so
1657     // that we don't consider them for legalization.
1658     if (legalityInfo->isRecursivelyLegal)
1659       rewriter.getImpl().markNestedOpsIgnored(op);
1660     return success();
1661   }
1662 
1663   // Check to see if the operation is ignored and doesn't need to be converted.
1664   if (rewriter.getImpl().isOpIgnored(op)) {
1665     LLVM_DEBUG({
1666       logSuccess(rewriterImpl.logger,
1667                  "operation marked 'ignored' during conversion");
1668       rewriterImpl.logger.startLine() << logLineComment;
1669     });
1670     return success();
1671   }
1672 
1673   // If the operation isn't legal, try to fold it in-place.
1674   // TODO: Should we always try to do this, even if the op is
1675   // already legal?
1676   if (succeeded(legalizeWithFold(op, rewriter))) {
1677     LLVM_DEBUG({
1678       logSuccess(rewriterImpl.logger, "operation was folded");
1679       rewriterImpl.logger.startLine() << logLineComment;
1680     });
1681     return success();
1682   }
1683 
1684   // Otherwise, we need to apply a legalization pattern to this operation.
1685   if (succeeded(legalizeWithPattern(op, rewriter))) {
1686     LLVM_DEBUG({
1687       logSuccess(rewriterImpl.logger, "");
1688       rewriterImpl.logger.startLine() << logLineComment;
1689     });
1690     return success();
1691   }
1692 
1693   LLVM_DEBUG({
1694     logFailure(rewriterImpl.logger, "no matched legalization pattern");
1695     rewriterImpl.logger.startLine() << logLineComment;
1696   });
1697   return failure();
1698 }
1699 
1700 LogicalResult
1701 OperationLegalizer::legalizeWithFold(Operation *op,
1702                                      ConversionPatternRewriter &rewriter) {
1703   auto &rewriterImpl = rewriter.getImpl();
1704   RewriterState curState = rewriterImpl.getCurrentState();
1705 
1706   LLVM_DEBUG({
1707     rewriterImpl.logger.startLine() << "* Fold {\n";
1708     rewriterImpl.logger.indent();
1709   });
1710 
1711   // Try to fold the operation.
1712   SmallVector<Value, 2> replacementValues;
1713   rewriter.setInsertionPoint(op);
1714   if (failed(rewriter.tryFold(op, replacementValues))) {
1715     LLVM_DEBUG(logFailure(rewriterImpl.logger, "unable to fold"));
1716     return failure();
1717   }
1718 
1719   // Insert a replacement for 'op' with the folded replacement values.
1720   rewriter.replaceOp(op, replacementValues);
1721 
1722   // Recursively legalize any new constant operations.
1723   for (unsigned i = curState.numCreatedOps, e = rewriterImpl.createdOps.size();
1724        i != e; ++i) {
1725     Operation *cstOp = rewriterImpl.createdOps[i];
1726     if (failed(legalize(cstOp, rewriter))) {
1727       LLVM_DEBUG(logFailure(rewriterImpl.logger,
1728                             "generated constant '{0}' was illegal",
1729                             cstOp->getName()));
1730       rewriterImpl.resetState(curState);
1731       return failure();
1732     }
1733   }
1734 
1735   LLVM_DEBUG(logSuccess(rewriterImpl.logger, ""));
1736   return success();
1737 }
1738 
1739 LogicalResult
1740 OperationLegalizer::legalizeWithPattern(Operation *op,
1741                                         ConversionPatternRewriter &rewriter) {
1742   auto &rewriterImpl = rewriter.getImpl();
1743 
1744   // Functor that returns if the given pattern may be applied.
1745   auto canApply = [&](const Pattern &pattern) {
1746     return canApplyPattern(op, pattern, rewriter);
1747   };
1748 
1749   // Functor that cleans up the rewriter state after a pattern failed to match.
1750   RewriterState curState = rewriterImpl.getCurrentState();
1751   auto onFailure = [&](const Pattern &pattern) {
1752     LLVM_DEBUG(logFailure(rewriterImpl.logger, "pattern failed to match"));
1753     rewriterImpl.resetState(curState);
1754     appliedPatterns.erase(&pattern);
1755   };
1756 
1757   // Functor that performs additional legalization when a pattern is
1758   // successfully applied.
1759   auto onSuccess = [&](const Pattern &pattern) {
1760     auto result = legalizePatternResult(op, pattern, rewriter, curState);
1761     appliedPatterns.erase(&pattern);
1762     if (failed(result))
1763       rewriterImpl.resetState(curState);
1764     return result;
1765   };
1766 
1767   // Try to match and rewrite a pattern on this operation.
1768   return applicator.matchAndRewrite(op, rewriter, canApply, onFailure,
1769                                     onSuccess);
1770 }
1771 
1772 bool OperationLegalizer::canApplyPattern(Operation *op, const Pattern &pattern,
1773                                          ConversionPatternRewriter &rewriter) {
1774   LLVM_DEBUG({
1775     auto &os = rewriter.getImpl().logger;
1776     os.getOStream() << "\n";
1777     os.startLine() << "* Pattern : '" << op->getName() << " -> (";
1778     llvm::interleaveComma(pattern.getGeneratedOps(), llvm::dbgs());
1779     os.getOStream() << ")' {\n";
1780     os.indent();
1781   });
1782 
1783   // Ensure that we don't cycle by not allowing the same pattern to be
1784   // applied twice in the same recursion stack if it is not known to be safe.
1785   if (!pattern.hasBoundedRewriteRecursion() &&
1786       !appliedPatterns.insert(&pattern).second) {
1787     LLVM_DEBUG(
1788         logFailure(rewriter.getImpl().logger, "pattern was already applied"));
1789     return false;
1790   }
1791   return true;
1792 }
1793 
1794 LogicalResult
1795 OperationLegalizer::legalizePatternResult(Operation *op, const Pattern &pattern,
1796                                           ConversionPatternRewriter &rewriter,
1797                                           RewriterState &curState) {
1798   auto &impl = rewriter.getImpl();
1799 
1800 #ifndef NDEBUG
1801   assert(impl.pendingRootUpdates.empty() && "dangling root updates");
1802 #endif
1803 
1804   // Check that the root was either replaced or updated in place.
1805   auto replacedRoot = [&] {
1806     return llvm::any_of(
1807         llvm::drop_begin(impl.replacements, curState.numReplacements),
1808         [op](auto &it) { return it.first == op; });
1809   };
1810   auto updatedRootInPlace = [&] {
1811     return llvm::any_of(
1812         llvm::drop_begin(impl.rootUpdates, curState.numRootUpdates),
1813         [op](auto &state) { return state.getOperation() == op; });
1814   };
1815   (void)replacedRoot;
1816   (void)updatedRootInPlace;
1817   assert((replacedRoot() || updatedRootInPlace()) &&
1818          "expected pattern to replace the root operation");
1819 
1820   // Legalize each of the actions registered during application.
1821   RewriterState newState = impl.getCurrentState();
1822   if (failed(legalizePatternBlockActions(op, rewriter, impl, curState,
1823                                          newState)) ||
1824       failed(legalizePatternRootUpdates(rewriter, impl, curState, newState)) ||
1825       failed(legalizePatternCreatedOperations(rewriter, impl, curState,
1826                                               newState))) {
1827     return failure();
1828   }
1829 
1830   LLVM_DEBUG(logSuccess(impl.logger, "pattern applied successfully"));
1831   return success();
1832 }
1833 
1834 LogicalResult OperationLegalizer::legalizePatternBlockActions(
1835     Operation *op, ConversionPatternRewriter &rewriter,
1836     ConversionPatternRewriterImpl &impl, RewriterState &state,
1837     RewriterState &newState) {
1838   SmallPtrSet<Operation *, 16> operationsToIgnore;
1839 
1840   // If the pattern moved or created any blocks, make sure the types of block
1841   // arguments get legalized.
1842   for (int i = state.numBlockActions, e = newState.numBlockActions; i != e;
1843        ++i) {
1844     auto &action = impl.blockActions[i];
1845     if (action.kind == BlockActionKind::TypeConversion ||
1846         action.kind == BlockActionKind::Erase)
1847       continue;
1848     // Only check blocks outside of the current operation.
1849     Operation *parentOp = action.block->getParentOp();
1850     if (!parentOp || parentOp == op || action.block->getNumArguments() == 0)
1851       continue;
1852 
1853     // If the region of the block has a type converter, try to convert the block
1854     // directly.
1855     if (auto *converter =
1856             impl.argConverter.getConverter(action.block->getParent())) {
1857       if (failed(impl.convertBlockSignature(action.block, *converter))) {
1858         LLVM_DEBUG(logFailure(impl.logger, "failed to convert types of moved "
1859                                            "block"));
1860         return failure();
1861       }
1862       continue;
1863     }
1864 
1865     // Otherwise, check that this operation isn't one generated by this pattern.
1866     // This is because we will attempt to legalize the parent operation, and
1867     // blocks in regions created by this pattern will already be legalized later
1868     // on. If we haven't built the set yet, build it now.
1869     if (operationsToIgnore.empty()) {
1870       auto createdOps = ArrayRef<Operation *>(impl.createdOps)
1871                             .drop_front(state.numCreatedOps);
1872       operationsToIgnore.insert(createdOps.begin(), createdOps.end());
1873     }
1874 
1875     // If this operation should be considered for re-legalization, try it.
1876     if (operationsToIgnore.insert(parentOp).second &&
1877         failed(legalize(parentOp, rewriter))) {
1878       LLVM_DEBUG(logFailure(
1879           impl.logger, "operation '{0}'({1}) became illegal after block action",
1880           parentOp->getName(), parentOp));
1881       return failure();
1882     }
1883   }
1884   return success();
1885 }
1886 LogicalResult OperationLegalizer::legalizePatternCreatedOperations(
1887     ConversionPatternRewriter &rewriter, ConversionPatternRewriterImpl &impl,
1888     RewriterState &state, RewriterState &newState) {
1889   for (int i = state.numCreatedOps, e = newState.numCreatedOps; i != e; ++i) {
1890     Operation *op = impl.createdOps[i];
1891     if (failed(legalize(op, rewriter))) {
1892       LLVM_DEBUG(logFailure(impl.logger,
1893                             "generated operation '{0}'({1}) was illegal",
1894                             op->getName(), op));
1895       return failure();
1896     }
1897   }
1898   return success();
1899 }
1900 LogicalResult OperationLegalizer::legalizePatternRootUpdates(
1901     ConversionPatternRewriter &rewriter, ConversionPatternRewriterImpl &impl,
1902     RewriterState &state, RewriterState &newState) {
1903   for (int i = state.numRootUpdates, e = newState.numRootUpdates; i != e; ++i) {
1904     Operation *op = impl.rootUpdates[i].getOperation();
1905     if (failed(legalize(op, rewriter))) {
1906       LLVM_DEBUG(logFailure(impl.logger,
1907                             "operation updated in-place '{0}' was illegal",
1908                             op->getName()));
1909       return failure();
1910     }
1911   }
1912   return success();
1913 }
1914 
1915 //===----------------------------------------------------------------------===//
1916 // Cost Model
1917 
1918 void OperationLegalizer::buildLegalizationGraph(
1919     LegalizationPatterns &anyOpLegalizerPatterns,
1920     DenseMap<OperationName, LegalizationPatterns> &legalizerPatterns) {
1921   // A mapping between an operation and a set of operations that can be used to
1922   // generate it.
1923   DenseMap<OperationName, SmallPtrSet<OperationName, 2>> parentOps;
1924   // A mapping between an operation and any currently invalid patterns it has.
1925   DenseMap<OperationName, SmallPtrSet<const Pattern *, 2>> invalidPatterns;
1926   // A worklist of patterns to consider for legality.
1927   llvm::SetVector<const Pattern *> patternWorklist;
1928 
1929   // Build the mapping from operations to the parent ops that may generate them.
1930   applicator.walkAllPatterns([&](const Pattern &pattern) {
1931     Optional<OperationName> root = pattern.getRootKind();
1932 
1933     // If the pattern has no specific root, we can't analyze the relationship
1934     // between the root op and generated operations. Given that, add all such
1935     // patterns to the legalization set.
1936     if (!root) {
1937       anyOpLegalizerPatterns.push_back(&pattern);
1938       return;
1939     }
1940 
1941     // Skip operations that are always known to be legal.
1942     if (target.getOpAction(*root) == LegalizationAction::Legal)
1943       return;
1944 
1945     // Add this pattern to the invalid set for the root op and record this root
1946     // as a parent for any generated operations.
1947     invalidPatterns[*root].insert(&pattern);
1948     for (auto op : pattern.getGeneratedOps())
1949       parentOps[op].insert(*root);
1950 
1951     // Add this pattern to the worklist.
1952     patternWorklist.insert(&pattern);
1953   });
1954 
1955   // If there are any patterns that don't have a specific root kind, we can't
1956   // make direct assumptions about what operations will never be legalized.
1957   // Note: Technically we could, but it would require an analysis that may
1958   // recurse into itself. It would be better to perform this kind of filtering
1959   // at a higher level than here anyways.
1960   if (!anyOpLegalizerPatterns.empty()) {
1961     for (const Pattern *pattern : patternWorklist)
1962       legalizerPatterns[*pattern->getRootKind()].push_back(pattern);
1963     return;
1964   }
1965 
1966   while (!patternWorklist.empty()) {
1967     auto *pattern = patternWorklist.pop_back_val();
1968 
1969     // Check to see if any of the generated operations are invalid.
1970     if (llvm::any_of(pattern->getGeneratedOps(), [&](OperationName op) {
1971           Optional<LegalizationAction> action = target.getOpAction(op);
1972           return !legalizerPatterns.count(op) &&
1973                  (!action || action == LegalizationAction::Illegal);
1974         }))
1975       continue;
1976 
1977     // Otherwise, if all of the generated operation are valid, this op is now
1978     // legal so add all of the child patterns to the worklist.
1979     legalizerPatterns[*pattern->getRootKind()].push_back(pattern);
1980     invalidPatterns[*pattern->getRootKind()].erase(pattern);
1981 
1982     // Add any invalid patterns of the parent operations to see if they have now
1983     // become legal.
1984     for (auto op : parentOps[*pattern->getRootKind()])
1985       patternWorklist.set_union(invalidPatterns[op]);
1986   }
1987 }
1988 
1989 void OperationLegalizer::computeLegalizationGraphBenefit(
1990     LegalizationPatterns &anyOpLegalizerPatterns,
1991     DenseMap<OperationName, LegalizationPatterns> &legalizerPatterns) {
1992   // The smallest pattern depth, when legalizing an operation.
1993   DenseMap<OperationName, unsigned> minOpPatternDepth;
1994 
1995   // For each operation that is transitively legal, compute a cost for it.
1996   for (auto &opIt : legalizerPatterns)
1997     if (!minOpPatternDepth.count(opIt.first))
1998       computeOpLegalizationDepth(opIt.first, minOpPatternDepth,
1999                                  legalizerPatterns);
2000 
2001   // Apply the cost model to the patterns that can match any operation. Those
2002   // with a specific operation type are already resolved when computing the op
2003   // legalization depth.
2004   if (!anyOpLegalizerPatterns.empty())
2005     applyCostModelToPatterns(anyOpLegalizerPatterns, minOpPatternDepth,
2006                              legalizerPatterns);
2007 
2008   // Apply a cost model to the pattern applicator. We order patterns first by
2009   // depth then benefit. `legalizerPatterns` contains per-op patterns by
2010   // decreasing benefit.
2011   applicator.applyCostModel([&](const Pattern &pattern) {
2012     ArrayRef<const Pattern *> orderedPatternList;
2013     if (Optional<OperationName> rootName = pattern.getRootKind())
2014       orderedPatternList = legalizerPatterns[*rootName];
2015     else
2016       orderedPatternList = anyOpLegalizerPatterns;
2017 
2018     // If the pattern is not found, then it was removed and cannot be matched.
2019     auto it = llvm::find(orderedPatternList, &pattern);
2020     if (it == orderedPatternList.end())
2021       return PatternBenefit::impossibleToMatch();
2022 
2023     // Patterns found earlier in the list have higher benefit.
2024     return PatternBenefit(std::distance(it, orderedPatternList.end()));
2025   });
2026 }
2027 
2028 unsigned OperationLegalizer::computeOpLegalizationDepth(
2029     OperationName op, DenseMap<OperationName, unsigned> &minOpPatternDepth,
2030     DenseMap<OperationName, LegalizationPatterns> &legalizerPatterns) {
2031   // Check for existing depth.
2032   auto depthIt = minOpPatternDepth.find(op);
2033   if (depthIt != minOpPatternDepth.end())
2034     return depthIt->second;
2035 
2036   // If a mapping for this operation does not exist, then this operation
2037   // is always legal. Return 0 as the depth for a directly legal operation.
2038   auto opPatternsIt = legalizerPatterns.find(op);
2039   if (opPatternsIt == legalizerPatterns.end() || opPatternsIt->second.empty())
2040     return 0u;
2041 
2042   // Record this initial depth in case we encounter this op again when
2043   // recursively computing the depth.
2044   minOpPatternDepth.try_emplace(op, std::numeric_limits<unsigned>::max());
2045 
2046   // Apply the cost model to the operation patterns, and update the minimum
2047   // depth.
2048   unsigned minDepth = applyCostModelToPatterns(
2049       opPatternsIt->second, minOpPatternDepth, legalizerPatterns);
2050   minOpPatternDepth[op] = minDepth;
2051   return minDepth;
2052 }
2053 
2054 unsigned OperationLegalizer::applyCostModelToPatterns(
2055     LegalizationPatterns &patterns,
2056     DenseMap<OperationName, unsigned> &minOpPatternDepth,
2057     DenseMap<OperationName, LegalizationPatterns> &legalizerPatterns) {
2058   unsigned minDepth = std::numeric_limits<unsigned>::max();
2059 
2060   // Compute the depth for each pattern within the set.
2061   SmallVector<std::pair<const Pattern *, unsigned>, 4> patternsByDepth;
2062   patternsByDepth.reserve(patterns.size());
2063   for (const Pattern *pattern : patterns) {
2064     unsigned depth = 0;
2065     for (auto generatedOp : pattern->getGeneratedOps()) {
2066       unsigned generatedOpDepth = computeOpLegalizationDepth(
2067           generatedOp, minOpPatternDepth, legalizerPatterns);
2068       depth = std::max(depth, generatedOpDepth + 1);
2069     }
2070     patternsByDepth.emplace_back(pattern, depth);
2071 
2072     // Update the minimum depth of the pattern list.
2073     minDepth = std::min(minDepth, depth);
2074   }
2075 
2076   // If the operation only has one legalization pattern, there is no need to
2077   // sort them.
2078   if (patternsByDepth.size() == 1)
2079     return minDepth;
2080 
2081   // Sort the patterns by those likely to be the most beneficial.
2082   llvm::array_pod_sort(patternsByDepth.begin(), patternsByDepth.end(),
2083                        [](const std::pair<const Pattern *, unsigned> *lhs,
2084                           const std::pair<const Pattern *, unsigned> *rhs) {
2085                          // First sort by the smaller pattern legalization
2086                          // depth.
2087                          if (lhs->second != rhs->second)
2088                            return llvm::array_pod_sort_comparator<unsigned>(
2089                                &lhs->second, &rhs->second);
2090 
2091                          // Then sort by the larger pattern benefit.
2092                          auto lhsBenefit = lhs->first->getBenefit();
2093                          auto rhsBenefit = rhs->first->getBenefit();
2094                          return llvm::array_pod_sort_comparator<PatternBenefit>(
2095                              &rhsBenefit, &lhsBenefit);
2096                        });
2097 
2098   // Update the legalization pattern to use the new sorted list.
2099   patterns.clear();
2100   for (auto &patternIt : patternsByDepth)
2101     patterns.push_back(patternIt.first);
2102   return minDepth;
2103 }
2104 
2105 //===----------------------------------------------------------------------===//
2106 // OperationConverter
2107 //===----------------------------------------------------------------------===//
2108 namespace {
2109 enum OpConversionMode {
2110   // In this mode, the conversion will ignore failed conversions to allow
2111   // illegal operations to co-exist in the IR.
2112   Partial,
2113 
2114   // In this mode, all operations must be legal for the given target for the
2115   // conversion to succeed.
2116   Full,
2117 
2118   // In this mode, operations are analyzed for legality. No actual rewrites are
2119   // applied to the operations on success.
2120   Analysis,
2121 };
2122 
2123 // This class converts operations to a given conversion target via a set of
2124 // rewrite patterns. The conversion behaves differently depending on the
2125 // conversion mode.
2126 struct OperationConverter {
2127   explicit OperationConverter(ConversionTarget &target,
2128                               const FrozenRewritePatternSet &patterns,
2129                               OpConversionMode mode,
2130                               DenseSet<Operation *> *trackedOps = nullptr)
2131       : opLegalizer(target, patterns), mode(mode), trackedOps(trackedOps) {}
2132 
2133   /// Converts the given operations to the conversion target.
2134   LogicalResult convertOperations(ArrayRef<Operation *> ops);
2135 
2136 private:
2137   /// Converts an operation with the given rewriter.
2138   LogicalResult convert(ConversionPatternRewriter &rewriter, Operation *op);
2139 
2140   /// This method is called after the conversion process to legalize any
2141   /// remaining artifacts and complete the conversion.
2142   LogicalResult finalize(ConversionPatternRewriter &rewriter);
2143 
2144   /// Legalize the types of converted block arguments.
2145   LogicalResult
2146   legalizeConvertedArgumentTypes(ConversionPatternRewriter &rewriter,
2147                                  ConversionPatternRewriterImpl &rewriterImpl);
2148 
2149   /// Legalize an operation result that was marked as "erased".
2150   LogicalResult
2151   legalizeErasedResult(Operation *op, OpResult result,
2152                        ConversionPatternRewriterImpl &rewriterImpl);
2153 
2154   /// Legalize an operation result that was replaced with a value of a different
2155   /// type.
2156   LogicalResult
2157   legalizeChangedResultType(Operation *op, OpResult result, Value newValue,
2158                             TypeConverter *replConverter,
2159                             ConversionPatternRewriter &rewriter,
2160                             ConversionPatternRewriterImpl &rewriterImpl,
2161                             const BlockAndValueMapping &inverseMapping);
2162 
2163   /// The legalizer to use when converting operations.
2164   OperationLegalizer opLegalizer;
2165 
2166   /// The conversion mode to use when legalizing operations.
2167   OpConversionMode mode;
2168 
2169   /// A set of pre-existing operations. When mode == OpConversionMode::Analysis,
2170   /// this is populated with ops found to be legalizable to the target.
2171   /// When mode == OpConversionMode::Partial, this is populated with ops found
2172   /// *not* to be legalizable to the target.
2173   DenseSet<Operation *> *trackedOps;
2174 };
2175 } // end anonymous namespace
2176 
2177 LogicalResult OperationConverter::convert(ConversionPatternRewriter &rewriter,
2178                                           Operation *op) {
2179   // Legalize the given operation.
2180   if (failed(opLegalizer.legalize(op, rewriter))) {
2181     // Handle the case of a failed conversion for each of the different modes.
2182     // Full conversions expect all operations to be converted.
2183     if (mode == OpConversionMode::Full)
2184       return op->emitError()
2185              << "failed to legalize operation '" << op->getName() << "'";
2186     // Partial conversions allow conversions to fail iff the operation was not
2187     // explicitly marked as illegal. If the user provided a nonlegalizableOps
2188     // set, non-legalizable ops are included.
2189     if (mode == OpConversionMode::Partial) {
2190       if (opLegalizer.isIllegal(op))
2191         return op->emitError()
2192                << "failed to legalize operation '" << op->getName()
2193                << "' that was explicitly marked illegal";
2194       if (trackedOps)
2195         trackedOps->insert(op);
2196     }
2197   } else if (mode == OpConversionMode::Analysis) {
2198     // Analysis conversions don't fail if any operations fail to legalize,
2199     // they are only interested in the operations that were successfully
2200     // legalized.
2201     trackedOps->insert(op);
2202   }
2203   return success();
2204 }
2205 
2206 LogicalResult OperationConverter::convertOperations(ArrayRef<Operation *> ops) {
2207   if (ops.empty())
2208     return success();
2209   ConversionTarget &target = opLegalizer.getTarget();
2210 
2211   // Compute the set of operations and blocks to convert.
2212   std::vector<Operation *> toConvert;
2213   for (auto *op : ops) {
2214     toConvert.emplace_back(op);
2215     for (auto &region : op->getRegions())
2216       if (failed(computeConversionSet(region.getBlocks(), region.getLoc(),
2217                                       toConvert, &target)))
2218         return failure();
2219   }
2220 
2221   // Convert each operation and discard rewrites on failure.
2222   ConversionPatternRewriter rewriter(ops.front()->getContext());
2223   ConversionPatternRewriterImpl &rewriterImpl = rewriter.getImpl();
2224   for (auto *op : toConvert)
2225     if (failed(convert(rewriter, op)))
2226       return rewriterImpl.discardRewrites(), failure();
2227 
2228   // Now that all of the operations have been converted, finalize the conversion
2229   // process to ensure any lingering conversion artifacts are cleaned up and
2230   // legalized.
2231   if (failed(finalize(rewriter)))
2232     return rewriterImpl.discardRewrites(), failure();
2233 
2234   // After a successful conversion, apply rewrites if this is not an analysis
2235   // conversion.
2236   if (mode == OpConversionMode::Analysis)
2237     rewriterImpl.discardRewrites();
2238   else
2239     rewriterImpl.applyRewrites();
2240   return success();
2241 }
2242 
2243 LogicalResult
2244 OperationConverter::finalize(ConversionPatternRewriter &rewriter) {
2245   ConversionPatternRewriterImpl &rewriterImpl = rewriter.getImpl();
2246 
2247   // Legalize converted block arguments.
2248   if (failed(legalizeConvertedArgumentTypes(rewriter, rewriterImpl)))
2249     return failure();
2250 
2251   if (rewriterImpl.operationsWithChangedResults.empty())
2252     return success();
2253 
2254   Optional<BlockAndValueMapping> inverseMapping;
2255 
2256   // Process requested operation replacements.
2257   for (unsigned i = 0, e = rewriterImpl.operationsWithChangedResults.size();
2258        i != e; ++i) {
2259     unsigned replIdx = rewriterImpl.operationsWithChangedResults[i];
2260     auto &repl = *(rewriterImpl.replacements.begin() + replIdx);
2261     for (OpResult result : repl.first->getResults()) {
2262       Value newValue = rewriterImpl.mapping.lookupOrNull(result);
2263 
2264       // If the operation result was replaced with null, all of the uses of this
2265       // value should be replaced.
2266       if (!newValue) {
2267         if (failed(legalizeErasedResult(repl.first, result, rewriterImpl)))
2268           return failure();
2269         continue;
2270       }
2271 
2272       // Otherwise, check to see if the type of the result changed.
2273       if (result.getType() == newValue.getType())
2274         continue;
2275 
2276       // Compute the inverse mapping only if it is really needed.
2277       if (!inverseMapping)
2278         inverseMapping = rewriterImpl.mapping.getInverse();
2279 
2280       // Legalize this result.
2281       rewriter.setInsertionPoint(repl.first);
2282       if (failed(legalizeChangedResultType(repl.first, result, newValue,
2283                                            repl.second.converter, rewriter,
2284                                            rewriterImpl, *inverseMapping)))
2285         return failure();
2286 
2287       // Update the end iterator for this loop in the case it was updated
2288       // when legalizing generated conversion operations.
2289       e = rewriterImpl.operationsWithChangedResults.size();
2290     }
2291   }
2292   return success();
2293 }
2294 
2295 LogicalResult OperationConverter::legalizeConvertedArgumentTypes(
2296     ConversionPatternRewriter &rewriter,
2297     ConversionPatternRewriterImpl &rewriterImpl) {
2298   // Functor used to check if all users of a value will be dead after
2299   // conversion.
2300   auto findLiveUser = [&](Value val) {
2301     auto liveUserIt = llvm::find_if_not(val.getUsers(), [&](Operation *user) {
2302       return rewriterImpl.isOpIgnored(user);
2303     });
2304     return liveUserIt == val.user_end() ? nullptr : *liveUserIt;
2305   };
2306 
2307   // Materialize any necessary conversions for converted block arguments that
2308   // are still live.
2309   size_t numCreatedOps = rewriterImpl.createdOps.size();
2310   if (failed(rewriterImpl.argConverter.materializeLiveConversions(
2311           rewriterImpl.mapping, rewriter, findLiveUser)))
2312     return failure();
2313 
2314   // Legalize any newly created operations during argument materialization.
2315   for (int i : llvm::seq<int>(numCreatedOps, rewriterImpl.createdOps.size())) {
2316     if (failed(opLegalizer.legalize(rewriterImpl.createdOps[i], rewriter))) {
2317       return rewriterImpl.createdOps[i]->emitError()
2318              << "failed to legalize conversion operation generated for block "
2319                 "argument that remained live after conversion";
2320     }
2321   }
2322   return success();
2323 }
2324 
2325 LogicalResult OperationConverter::legalizeErasedResult(
2326     Operation *op, OpResult result,
2327     ConversionPatternRewriterImpl &rewriterImpl) {
2328   // If the operation result was replaced with null, all of the uses of this
2329   // value should be replaced.
2330   auto liveUserIt = llvm::find_if_not(result.getUsers(), [&](Operation *user) {
2331     return rewriterImpl.isOpIgnored(user);
2332   });
2333   if (liveUserIt != result.user_end()) {
2334     InFlightDiagnostic diag = op->emitError("failed to legalize operation '")
2335                               << op->getName() << "' marked as erased";
2336     diag.attachNote(liveUserIt->getLoc())
2337         << "found live user of result #" << result.getResultNumber() << ": "
2338         << *liveUserIt;
2339     return failure();
2340   }
2341   return success();
2342 }
2343 
2344 /// Finds a user of the given value, or of any other value that the given value
2345 /// replaced, that was not replaced in the conversion process.
2346 static Operation *
2347 findLiveUserOfReplaced(Value value, ConversionPatternRewriterImpl &rewriterImpl,
2348                        const BlockAndValueMapping &inverseMapping) {
2349   do {
2350     // Walk the users of this value to see if there are any live users that
2351     // weren't replaced during conversion.
2352     auto liveUserIt = llvm::find_if_not(value.getUsers(), [&](Operation *user) {
2353       return rewriterImpl.isOpIgnored(user);
2354     });
2355     if (liveUserIt != value.user_end())
2356       return *liveUserIt;
2357     value = inverseMapping.lookupOrNull(value);
2358   } while (value != nullptr);
2359   return nullptr;
2360 }
2361 
2362 LogicalResult OperationConverter::legalizeChangedResultType(
2363     Operation *op, OpResult result, Value newValue,
2364     TypeConverter *replConverter, ConversionPatternRewriter &rewriter,
2365     ConversionPatternRewriterImpl &rewriterImpl,
2366     const BlockAndValueMapping &inverseMapping) {
2367   Operation *liveUser =
2368       findLiveUserOfReplaced(result, rewriterImpl, inverseMapping);
2369   if (!liveUser)
2370     return success();
2371 
2372   // If the replacement has a type converter, attempt to materialize a
2373   // conversion back to the original type.
2374   if (!replConverter) {
2375     // TODO: We should emit an error here, similarly to the case where the
2376     // result is replaced with null. Unfortunately a lot of existing
2377     // patterns rely on this behavior, so until those patterns are updated
2378     // we keep the legacy behavior here of just forwarding the new value.
2379     return success();
2380   }
2381 
2382   // Track the number of created operations so that new ones can be legalized.
2383   size_t numCreatedOps = rewriterImpl.createdOps.size();
2384 
2385   // Materialize a conversion for this live result value.
2386   Type resultType = result.getType();
2387   Value convertedValue = replConverter->materializeSourceConversion(
2388       rewriter, op->getLoc(), resultType, newValue);
2389   if (!convertedValue) {
2390     InFlightDiagnostic diag = op->emitError()
2391                               << "failed to materialize conversion for result #"
2392                               << result.getResultNumber() << " of operation '"
2393                               << op->getName()
2394                               << "' that remained live after conversion";
2395     diag.attachNote(liveUser->getLoc())
2396         << "see existing live user here: " << *liveUser;
2397     return failure();
2398   }
2399 
2400   // Legalize all of the newly created conversion operations.
2401   for (int i : llvm::seq<int>(numCreatedOps, rewriterImpl.createdOps.size())) {
2402     if (failed(opLegalizer.legalize(rewriterImpl.createdOps[i], rewriter))) {
2403       return op->emitError("failed to legalize conversion operation generated ")
2404              << "for result #" << result.getResultNumber() << " of operation '"
2405              << op->getName() << "' that remained live after conversion";
2406     }
2407   }
2408 
2409   rewriterImpl.mapping.map(result, convertedValue);
2410   return success();
2411 }
2412 
2413 //===----------------------------------------------------------------------===//
2414 // Type Conversion
2415 //===----------------------------------------------------------------------===//
2416 
2417 /// Remap an input of the original signature with a new set of types. The
2418 /// new types are appended to the new signature conversion.
2419 void TypeConverter::SignatureConversion::addInputs(unsigned origInputNo,
2420                                                    ArrayRef<Type> types) {
2421   assert(!types.empty() && "expected valid types");
2422   remapInput(origInputNo, /*newInputNo=*/argTypes.size(), types.size());
2423   addInputs(types);
2424 }
2425 
2426 /// Append new input types to the signature conversion, this should only be
2427 /// used if the new types are not intended to remap an existing input.
2428 void TypeConverter::SignatureConversion::addInputs(ArrayRef<Type> types) {
2429   assert(!types.empty() &&
2430          "1->0 type remappings don't need to be added explicitly");
2431   argTypes.append(types.begin(), types.end());
2432 }
2433 
2434 /// Remap an input of the original signature with a range of types in the
2435 /// new signature.
2436 void TypeConverter::SignatureConversion::remapInput(unsigned origInputNo,
2437                                                     unsigned newInputNo,
2438                                                     unsigned newInputCount) {
2439   assert(!remappedInputs[origInputNo] && "input has already been remapped");
2440   assert(newInputCount != 0 && "expected valid input count");
2441   remappedInputs[origInputNo] =
2442       InputMapping{newInputNo, newInputCount, /*replacementValue=*/nullptr};
2443 }
2444 
2445 /// Remap an input of the original signature to another `replacementValue`
2446 /// value. This would make the signature converter drop this argument.
2447 void TypeConverter::SignatureConversion::remapInput(unsigned origInputNo,
2448                                                     Value replacementValue) {
2449   assert(!remappedInputs[origInputNo] && "input has already been remapped");
2450   remappedInputs[origInputNo] =
2451       InputMapping{origInputNo, /*size=*/0, replacementValue};
2452 }
2453 
2454 /// This hooks allows for converting a type.
2455 LogicalResult TypeConverter::convertType(Type t,
2456                                          SmallVectorImpl<Type> &results) {
2457   auto existingIt = cachedDirectConversions.find(t);
2458   if (existingIt != cachedDirectConversions.end()) {
2459     if (existingIt->second)
2460       results.push_back(existingIt->second);
2461     return success(existingIt->second != nullptr);
2462   }
2463   auto multiIt = cachedMultiConversions.find(t);
2464   if (multiIt != cachedMultiConversions.end()) {
2465     results.append(multiIt->second.begin(), multiIt->second.end());
2466     return success();
2467   }
2468 
2469   // Walk the added converters in reverse order to apply the most recently
2470   // registered first.
2471   size_t currentCount = results.size();
2472   for (ConversionCallbackFn &converter : llvm::reverse(conversions)) {
2473     if (Optional<LogicalResult> result = converter(t, results)) {
2474       if (!succeeded(*result)) {
2475         cachedDirectConversions.try_emplace(t, nullptr);
2476         return failure();
2477       }
2478       auto newTypes = ArrayRef<Type>(results).drop_front(currentCount);
2479       if (newTypes.size() == 1)
2480         cachedDirectConversions.try_emplace(t, newTypes.front());
2481       else
2482         cachedMultiConversions.try_emplace(t, llvm::to_vector<2>(newTypes));
2483       return success();
2484     }
2485   }
2486   return failure();
2487 }
2488 
2489 /// This hook simplifies defining 1-1 type conversions. This function returns
2490 /// the type to convert to on success, and a null type on failure.
2491 Type TypeConverter::convertType(Type t) {
2492   // Use the multi-type result version to convert the type.
2493   SmallVector<Type, 1> results;
2494   if (failed(convertType(t, results)))
2495     return nullptr;
2496 
2497   // Check to ensure that only one type was produced.
2498   return results.size() == 1 ? results.front() : nullptr;
2499 }
2500 
2501 /// Convert the given set of types, filling 'results' as necessary. This
2502 /// returns failure if the conversion of any of the types fails, success
2503 /// otherwise.
2504 LogicalResult TypeConverter::convertTypes(TypeRange types,
2505                                           SmallVectorImpl<Type> &results) {
2506   for (Type type : types)
2507     if (failed(convertType(type, results)))
2508       return failure();
2509   return success();
2510 }
2511 
2512 /// Return true if the given type is legal for this type converter, i.e. the
2513 /// type converts to itself.
2514 bool TypeConverter::isLegal(Type type) { return convertType(type) == type; }
2515 /// Return true if the given operation has legal operand and result types.
2516 bool TypeConverter::isLegal(Operation *op) {
2517   return isLegal(op->getOperandTypes()) && isLegal(op->getResultTypes());
2518 }
2519 
2520 /// Return true if the types of block arguments within the region are legal.
2521 bool TypeConverter::isLegal(Region *region) {
2522   return llvm::all_of(*region, [this](Block &block) {
2523     return isLegal(block.getArgumentTypes());
2524   });
2525 }
2526 
2527 /// Return true if the inputs and outputs of the given function type are
2528 /// legal.
2529 bool TypeConverter::isSignatureLegal(FunctionType ty) {
2530   return isLegal(llvm::concat<const Type>(ty.getInputs(), ty.getResults()));
2531 }
2532 
2533 /// This hook allows for converting a specific argument of a signature.
2534 LogicalResult TypeConverter::convertSignatureArg(unsigned inputNo, Type type,
2535                                                  SignatureConversion &result) {
2536   // Try to convert the given input type.
2537   SmallVector<Type, 1> convertedTypes;
2538   if (failed(convertType(type, convertedTypes)))
2539     return failure();
2540 
2541   // If this argument is being dropped, there is nothing left to do.
2542   if (convertedTypes.empty())
2543     return success();
2544 
2545   // Otherwise, add the new inputs.
2546   result.addInputs(inputNo, convertedTypes);
2547   return success();
2548 }
2549 LogicalResult TypeConverter::convertSignatureArgs(TypeRange types,
2550                                                   SignatureConversion &result,
2551                                                   unsigned origInputOffset) {
2552   for (unsigned i = 0, e = types.size(); i != e; ++i)
2553     if (failed(convertSignatureArg(origInputOffset + i, types[i], result)))
2554       return failure();
2555   return success();
2556 }
2557 
2558 Value TypeConverter::materializeConversion(
2559     MutableArrayRef<MaterializationCallbackFn> materializations,
2560     OpBuilder &builder, Location loc, Type resultType, ValueRange inputs) {
2561   for (MaterializationCallbackFn &fn : llvm::reverse(materializations))
2562     if (Optional<Value> result = fn(builder, resultType, inputs, loc))
2563       return result.getValue();
2564   return nullptr;
2565 }
2566 
2567 /// This function converts the type signature of the given block, by invoking
2568 /// 'convertSignatureArg' for each argument. This function should return a valid
2569 /// conversion for the signature on success, None otherwise.
2570 auto TypeConverter::convertBlockSignature(Block *block)
2571     -> Optional<SignatureConversion> {
2572   SignatureConversion conversion(block->getNumArguments());
2573   if (failed(convertSignatureArgs(block->getArgumentTypes(), conversion)))
2574     return llvm::None;
2575   return conversion;
2576 }
2577 
2578 /// Create a default conversion pattern that rewrites the type signature of a
2579 /// FunctionLike op. This only supports FunctionLike ops which use FunctionType
2580 /// to represent their type.
2581 namespace {
2582 struct FunctionLikeSignatureConversion : public ConversionPattern {
2583   FunctionLikeSignatureConversion(StringRef functionLikeOpName,
2584                                   MLIRContext *ctx, TypeConverter &converter)
2585       : ConversionPattern(converter, functionLikeOpName, /*benefit=*/1, ctx) {}
2586 
2587   /// Hook to implement combined matching and rewriting for FunctionLike ops.
2588   LogicalResult
2589   matchAndRewrite(Operation *op, ArrayRef<Value> operands,
2590                   ConversionPatternRewriter &rewriter) const override {
2591     FunctionType type = mlir::impl::getFunctionType(op);
2592 
2593     // Convert the original function types.
2594     TypeConverter::SignatureConversion result(type.getNumInputs());
2595     SmallVector<Type, 1> newResults;
2596     if (failed(typeConverter->convertSignatureArgs(type.getInputs(), result)) ||
2597         failed(typeConverter->convertTypes(type.getResults(), newResults)) ||
2598         failed(rewriter.convertRegionTypes(&mlir::impl::getFunctionBody(op),
2599                                            *typeConverter, &result)))
2600       return failure();
2601 
2602     // Update the function signature in-place.
2603     auto newType = FunctionType::get(rewriter.getContext(),
2604                                      result.getConvertedTypes(), newResults);
2605 
2606     rewriter.updateRootInPlace(
2607         op, [&] { mlir::impl::setFunctionType(op, newType); });
2608 
2609     return success();
2610   }
2611 };
2612 } // end anonymous namespace
2613 
2614 void mlir::populateFunctionLikeTypeConversionPattern(
2615     StringRef functionLikeOpName, RewritePatternSet &patterns,
2616     TypeConverter &converter) {
2617   patterns.add<FunctionLikeSignatureConversion>(
2618       functionLikeOpName, patterns.getContext(), converter);
2619 }
2620 
2621 void mlir::populateFuncOpTypeConversionPattern(RewritePatternSet &patterns,
2622                                                TypeConverter &converter) {
2623   populateFunctionLikeTypeConversionPattern<FuncOp>(patterns, converter);
2624 }
2625 
2626 //===----------------------------------------------------------------------===//
2627 // ConversionTarget
2628 //===----------------------------------------------------------------------===//
2629 
2630 /// Register a legality action for the given operation.
2631 void ConversionTarget::setOpAction(OperationName op,
2632                                    LegalizationAction action) {
2633   legalOperations[op] = {action, /*isRecursivelyLegal=*/false, llvm::None};
2634 }
2635 
2636 /// Register a legality action for the given dialects.
2637 void ConversionTarget::setDialectAction(ArrayRef<StringRef> dialectNames,
2638                                         LegalizationAction action) {
2639   for (StringRef dialect : dialectNames)
2640     legalDialects[dialect] = action;
2641 }
2642 
2643 /// Get the legality action for the given operation.
2644 auto ConversionTarget::getOpAction(OperationName op) const
2645     -> Optional<LegalizationAction> {
2646   Optional<LegalizationInfo> info = getOpInfo(op);
2647   return info ? info->action : Optional<LegalizationAction>();
2648 }
2649 
2650 /// If the given operation instance is legal on this target, a structure
2651 /// containing legality information is returned. If the operation is not legal,
2652 /// None is returned.
2653 auto ConversionTarget::isLegal(Operation *op) const
2654     -> Optional<LegalOpDetails> {
2655   Optional<LegalizationInfo> info = getOpInfo(op->getName());
2656   if (!info)
2657     return llvm::None;
2658 
2659   // Returns true if this operation instance is known to be legal.
2660   auto isOpLegal = [&] {
2661     // Handle dynamic legality either with the provided legality function, or
2662     // the default hook on the derived instance.
2663     if (info->action == LegalizationAction::Dynamic)
2664       return info->legalityFn ? (*info->legalityFn)(op)
2665                               : isDynamicallyLegal(op);
2666 
2667     // Otherwise, the operation is only legal if it was marked 'Legal'.
2668     return info->action == LegalizationAction::Legal;
2669   };
2670   if (!isOpLegal())
2671     return llvm::None;
2672 
2673   // This operation is legal, compute any additional legality information.
2674   LegalOpDetails legalityDetails;
2675   if (info->isRecursivelyLegal) {
2676     auto legalityFnIt = opRecursiveLegalityFns.find(op->getName());
2677     if (legalityFnIt != opRecursiveLegalityFns.end())
2678       legalityDetails.isRecursivelyLegal = legalityFnIt->second(op);
2679     else
2680       legalityDetails.isRecursivelyLegal = true;
2681   }
2682   return legalityDetails;
2683 }
2684 
2685 /// Set the dynamic legality callback for the given operation.
2686 void ConversionTarget::setLegalityCallback(
2687     OperationName name, const DynamicLegalityCallbackFn &callback) {
2688   assert(callback && "expected valid legality callback");
2689   auto infoIt = legalOperations.find(name);
2690   assert(infoIt != legalOperations.end() &&
2691          infoIt->second.action == LegalizationAction::Dynamic &&
2692          "expected operation to already be marked as dynamically legal");
2693   infoIt->second.legalityFn = callback;
2694 }
2695 
2696 /// Set the recursive legality callback for the given operation and mark the
2697 /// operation as recursively legal.
2698 void ConversionTarget::markOpRecursivelyLegal(
2699     OperationName name, const DynamicLegalityCallbackFn &callback) {
2700   auto infoIt = legalOperations.find(name);
2701   assert(infoIt != legalOperations.end() &&
2702          infoIt->second.action != LegalizationAction::Illegal &&
2703          "expected operation to already be marked as legal");
2704   infoIt->second.isRecursivelyLegal = true;
2705   if (callback)
2706     opRecursiveLegalityFns[name] = callback;
2707   else
2708     opRecursiveLegalityFns.erase(name);
2709 }
2710 
2711 /// Set the dynamic legality callback for the given dialects.
2712 void ConversionTarget::setLegalityCallback(
2713     ArrayRef<StringRef> dialects, const DynamicLegalityCallbackFn &callback) {
2714   assert(callback && "expected valid legality callback");
2715   for (StringRef dialect : dialects)
2716     dialectLegalityFns[dialect] = callback;
2717 }
2718 
2719 /// Get the legalization information for the given operation.
2720 auto ConversionTarget::getOpInfo(OperationName op) const
2721     -> Optional<LegalizationInfo> {
2722   // Check for info for this specific operation.
2723   auto it = legalOperations.find(op);
2724   if (it != legalOperations.end())
2725     return it->second;
2726   // Check for info for the parent dialect.
2727   auto dialectIt = legalDialects.find(op.getDialectNamespace());
2728   if (dialectIt != legalDialects.end()) {
2729     Optional<DynamicLegalityCallbackFn> callback;
2730     auto dialectFn = dialectLegalityFns.find(op.getDialectNamespace());
2731     if (dialectFn != dialectLegalityFns.end())
2732       callback = dialectFn->second;
2733     return LegalizationInfo{dialectIt->second, /*isRecursivelyLegal=*/false,
2734                             callback};
2735   }
2736   // Otherwise, check if we mark unknown operations as dynamic.
2737   if (unknownOpsDynamicallyLegal)
2738     return LegalizationInfo{LegalizationAction::Dynamic,
2739                             /*isRecursivelyLegal=*/false, unknownLegalityFn};
2740   return llvm::None;
2741 }
2742 
2743 //===----------------------------------------------------------------------===//
2744 // Op Conversion Entry Points
2745 //===----------------------------------------------------------------------===//
2746 
2747 /// Apply a partial conversion on the given operations and all nested
2748 /// operations. This method converts as many operations to the target as
2749 /// possible, ignoring operations that failed to legalize. This method only
2750 /// returns failure if there ops explicitly marked as illegal.
2751 /// If an `unconvertedOps` set is provided, all operations that are found not
2752 /// to be legalizable to the given `target` are placed within that set. (Note
2753 /// that if there is an op explicitly marked as illegal, the conversion
2754 /// terminates and the `unconvertedOps` set will not necessarily be complete.)
2755 LogicalResult
2756 mlir::applyPartialConversion(ArrayRef<Operation *> ops,
2757                              ConversionTarget &target,
2758                              const FrozenRewritePatternSet &patterns,
2759                              DenseSet<Operation *> *unconvertedOps) {
2760   OperationConverter opConverter(target, patterns, OpConversionMode::Partial,
2761                                  unconvertedOps);
2762   return opConverter.convertOperations(ops);
2763 }
2764 LogicalResult
2765 mlir::applyPartialConversion(Operation *op, ConversionTarget &target,
2766                              const FrozenRewritePatternSet &patterns,
2767                              DenseSet<Operation *> *unconvertedOps) {
2768   return applyPartialConversion(llvm::makeArrayRef(op), target, patterns,
2769                                 unconvertedOps);
2770 }
2771 
2772 /// Apply a complete conversion on the given operations, and all nested
2773 /// operations. This method will return failure if the conversion of any
2774 /// operation fails.
2775 LogicalResult
2776 mlir::applyFullConversion(ArrayRef<Operation *> ops, ConversionTarget &target,
2777                           const FrozenRewritePatternSet &patterns) {
2778   OperationConverter opConverter(target, patterns, OpConversionMode::Full);
2779   return opConverter.convertOperations(ops);
2780 }
2781 LogicalResult
2782 mlir::applyFullConversion(Operation *op, ConversionTarget &target,
2783                           const FrozenRewritePatternSet &patterns) {
2784   return applyFullConversion(llvm::makeArrayRef(op), target, patterns);
2785 }
2786 
2787 /// Apply an analysis conversion on the given operations, and all nested
2788 /// operations. This method analyzes which operations would be successfully
2789 /// converted to the target if a conversion was applied. All operations that
2790 /// were found to be legalizable to the given 'target' are placed within the
2791 /// provided 'convertedOps' set; note that no actual rewrites are applied to the
2792 /// operations on success and only pre-existing operations are added to the set.
2793 LogicalResult
2794 mlir::applyAnalysisConversion(ArrayRef<Operation *> ops,
2795                               ConversionTarget &target,
2796                               const FrozenRewritePatternSet &patterns,
2797                               DenseSet<Operation *> &convertedOps) {
2798   OperationConverter opConverter(target, patterns, OpConversionMode::Analysis,
2799                                  &convertedOps);
2800   return opConverter.convertOperations(ops);
2801 }
2802 LogicalResult
2803 mlir::applyAnalysisConversion(Operation *op, ConversionTarget &target,
2804                               const FrozenRewritePatternSet &patterns,
2805                               DenseSet<Operation *> &convertedOps) {
2806   return applyAnalysisConversion(llvm::makeArrayRef(op), target, patterns,
2807                                  convertedOps);
2808 }
2809