1 //===- LinalgOps.cpp - Implementation of the linalg operations ------------===//
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 // This file implements the Linalg operations.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "mlir/Dialect/Linalg/IR/LinalgOps.h"
14 
15 #include "mlir/Dialect/Affine/IR/AffineOps.h"
16 #include "mlir/Dialect/Linalg/EDSC/Intrinsics.h"
17 #include "mlir/Dialect/Linalg/IR/LinalgTypes.h"
18 #include "mlir/Dialect/MemRef/IR/MemRef.h"
19 #include "mlir/Dialect/StandardOps/IR/Ops.h"
20 #include "mlir/IR/AffineExprVisitor.h"
21 #include "mlir/IR/Matchers.h"
22 #include "mlir/IR/OpImplementation.h"
23 #include "mlir/IR/PatternMatch.h"
24 #include "mlir/Interfaces/InferTypeOpInterface.h"
25 #include "mlir/Parser.h"
26 
27 #include "llvm/ADT/DenseMap.h"
28 #include "llvm/ADT/SetVector.h"
29 #include "llvm/ADT/SmallSet.h"
30 #include "llvm/ADT/StringSet.h"
31 #include "llvm/Support/FormatVariadic.h"
32 #include "llvm/Support/MathExtras.h"
33 #include "llvm/Support/raw_ostream.h"
34 
35 using namespace mlir;
36 using namespace mlir::linalg;
37 
38 /// Forward declarations.
39 
40 /// Generic entry point to create the block for the region of a LinalgOp.
41 /// This is used by both named structured ops created by ods-gen and by manually
42 /// defined C++ ops.
43 /// This is used by both builders and parsers.
44 /// This function creates the block in the region with arguments corresponding
45 /// to the elemental types of `inputTypes` and `outputTypes`, which are asserted
46 /// to be ShapedType.
47 template <typename NamedStructuredOpType>
48 static void fillStructuredOpRegion(
49     OpBuilder &opBuilder, Region &region, TypeRange inputTypes,
50     TypeRange outputTypes, ValueRange captures = {},
51     std::function<void(unsigned, unsigned)> errorHandler = nullptr);
52 
53 /// Generic entry point to create both the region and the block of a LinalgOp.
54 template <typename NamedStructuredOpType>
55 static void
56 createAndFillStructuredOpRegion(OpBuilder &opBuilder, OperationState &result,
57                                 TypeRange inputTypes, TypeRange outputTypes,
58                                 ValueRange captures = {});
59 
60 /// Common parsing and printing used for both named structured ops created by
61 /// ods-gen and by manually defined C++ ops. Does not handle regions.
62 static ParseResult
63 parseCommonStructuredOpParts(OpAsmParser &parser, OperationState &result,
64                              SmallVectorImpl<Type> &inputTypes,
65                              SmallVectorImpl<Type> &outputTypes);
66 template <typename NamedStructuredOpType>
67 static void printCommonStructuredOpParts(OpAsmPrinter &p,
68                                          NamedStructuredOpType op);
69 
70 /// Specific parsing and printing for named structured ops created by ods-gen.
71 template <typename NamedStructuredOpType>
72 static ParseResult
73 parseNamedStructuredOpRegion(OpAsmParser &parser, Region &region,
74                              TypeRange inputTypes, TypeRange outputTypes,
75                              ArrayRef<OpAsmParser::OperandType> captures = {});
76 
77 static ParseResult
78 parseNamedStructuredOpResults(OpAsmParser &parser,
79                               SmallVectorImpl<Type> &resultTypes);
80 
81 template <typename NamedStructuredOpType>
82 static ParseResult
83 parseNamedStructuredOp(OpAsmParser &parser, OperationState &result,
84                        ArrayRef<OpAsmParser::OperandType> captures = {});
85 
86 static void printNamedStructuredOpResults(OpAsmPrinter &p,
87                                           TypeRange resultTypes);
88 
89 template <typename NamedStructuredOpType>
90 static void printNamedStructuredOp(OpAsmPrinter &p, NamedStructuredOpType op);
91 
92 /// Helper function to convert a Value into an OpFoldResult, if the Value is
93 /// known to be a constant index value.
94 static SmallVector<OpFoldResult> getAsOpFoldResult(ArrayRef<Value> values) {
95   return llvm::to_vector<4>(
96       llvm::map_range(values, [](Value v) -> OpFoldResult {
97         APInt intValue;
98         if (v.getType().isa<IndexType>() &&
99             matchPattern(v, m_ConstantInt(&intValue))) {
100           return IntegerAttr::get(v.getType(), intValue.getSExtValue());
101         }
102         return v;
103       }));
104 }
105 
106 /// Helper function to convert a vector of `OpFoldResult`s into a vector of
107 /// `Value`s.
108 static SmallVector<Value> getAsValues(OpBuilder &b, Location loc,
109                                       ArrayRef<OpFoldResult> valueOrAttrVec) {
110   return llvm::to_vector<4>(
111       llvm::map_range(valueOrAttrVec, [&](OpFoldResult value) -> Value {
112         if (auto attr = value.dyn_cast<Attribute>())
113           return b.create<ConstantIndexOp>(loc,
114                                            attr.cast<IntegerAttr>().getInt());
115         return value.get<Value>();
116       }));
117 }
118 
119 /// Helper function to dispatch an OpFoldResult into either the `dynamicVec` if
120 /// it is a Value or into `staticVec` if it is an IntegerAttr.
121 /// In the case of a Value, a copy of the `sentinel` value is also pushed to
122 /// `staticVec`. This is useful to extract mixed static and dynamic entries that
123 /// come from an AttrSizedOperandSegments trait.
124 static void dispatchIndexOpFoldResult(OpFoldResult ofr,
125                                       SmallVectorImpl<Value> &dynamicVec,
126                                       SmallVectorImpl<int64_t> &staticVec,
127                                       int64_t sentinel) {
128   if (auto v = ofr.dyn_cast<Value>()) {
129     dynamicVec.push_back(v);
130     staticVec.push_back(sentinel);
131     return;
132   }
133   APInt apInt = ofr.dyn_cast<Attribute>().cast<IntegerAttr>().getValue();
134   staticVec.push_back(apInt.getSExtValue());
135 }
136 
137 /// This is a common class used for patterns of the form
138 /// ```
139 ///    someop(memrefcast) -> someop
140 /// ```
141 /// It folds the source of the memref.cast into the root operation directly.
142 static LogicalResult foldMemRefCast(Operation *op) {
143   bool folded = false;
144   for (OpOperand &operand : op->getOpOperands()) {
145     auto castOp = operand.get().getDefiningOp<memref::CastOp>();
146     if (castOp && memref::CastOp::canFoldIntoConsumerOp(castOp)) {
147       operand.set(castOp.getOperand());
148       folded = true;
149     }
150   }
151   return success(folded);
152 }
153 
154 //===----------------------------------------------------------------------===//
155 // Region builder helper.
156 // TODO: Move this to a utility library.
157 // The public methods on this class are referenced directly from generated code
158 // and bind by name to math functions in the DSL as:
159 //   `applyfn__{fnName}`
160 // Examples:
161 //   `applyfn__add`
162 //   `applyfn__mul`
163 // The naming convention is intentional in order to match snake-cased DSL names.
164 // See mlir-linalg-ods-yaml-gen.cpp for the code that mates to this class.
165 //
166 // Implementations of the math functions must be polymorphic over numeric types,
167 // internally performing necessary casts. If the function application makes no
168 // sense, then the only recourse is to assert and return nullptr. This can be
169 // extended later if it becomes possible to fail construction of the region. The
170 // invariant should be enforced at a higher level.
171 //
172 // TODO: These helpers are currently type polymorphic over the class of integer
173 // and floating point types, but they will not internally cast within bit
174 // widths of a class (mixed precision such as i8->i32) or across classes
175 // (i.e. mixed float and integer). Many such combinations are ambiguous or need
176 // to be handled with care and work is being considered to extend the op
177 // language to make such cases explicit. In the mean-time, violating this will
178 // fail verification, which is deemed acceptable.
179 //===----------------------------------------------------------------------===//
180 
181 namespace {
182 
183 class RegionBuilderHelper {
184 public:
185   RegionBuilderHelper(Block &block) : block(block) {}
186 
187   // Generates operations to cast the given operand to a specified type.
188   // If the cast cannot be performed, a warning will be issued and the
189   // operand returned as-is (which will presumably yield a verification
190   // issue downstream).
191   Value cast(Type toType, Value operand) {
192     OpBuilder builder = getBuilder(operand);
193     auto loc = operand.getLoc();
194 
195     if (operand.getType() == toType)
196       return operand;
197     if (auto toIntType = toType.dyn_cast<IntegerType>()) {
198       // If operand is floating point, cast directly to the int type.
199       if (operand.getType().isa<FloatType>())
200         return builder.create<FPToSIOp>(loc, toType, operand);
201       if (auto fromIntType = operand.getType().dyn_cast<IntegerType>()) {
202         // Either sign extend or truncate.
203         if (toIntType.getWidth() > fromIntType.getWidth())
204           return builder.create<SignExtendIOp>(loc, toType, operand);
205         else if (toIntType.getWidth() < fromIntType.getWidth())
206           return builder.create<TruncateIOp>(loc, toType, operand);
207       }
208     } else if (auto toFloatType = toType.dyn_cast<FloatType>()) {
209       // If operand is integer, cast directly to the float type.
210       // Note that it is unclear how to cast from BF16<->FP16.
211       if (operand.getType().isa<IntegerType>())
212         return builder.create<SIToFPOp>(loc, toFloatType, operand);
213       if (auto fromFloatType = operand.getType().dyn_cast<FloatType>()) {
214         if (toFloatType.getWidth() > fromFloatType.getWidth())
215           return builder.create<FPExtOp>(loc, toFloatType, operand);
216         else if (toFloatType.getWidth() < fromFloatType.getWidth())
217           return builder.create<FPTruncOp>(loc, toFloatType, operand);
218       }
219     }
220 
221     emitWarning(operand.getLoc()) << "could not cast operand of type "
222                                   << operand.getType() << " to " << toType;
223     return operand;
224   }
225 
226   Value applyfn__add(Value lhs, Value rhs) {
227     OpBuilder builder = getBuilder(lhs);
228     if (isFloatingPoint(lhs))
229       return builder.create<AddFOp>(lhs.getLoc(), lhs, rhs);
230     else if (isInteger(lhs))
231       return builder.create<AddIOp>(lhs.getLoc(), lhs, rhs);
232     llvm_unreachable("unsupported non numeric type");
233   }
234 
235   Value applyfn__mul(Value lhs, Value rhs) {
236     OpBuilder builder = getBuilder(lhs);
237     if (isFloatingPoint(lhs))
238       return builder.create<MulFOp>(lhs.getLoc(), lhs, rhs);
239     else if (isInteger(lhs))
240       return builder.create<MulIOp>(lhs.getLoc(), lhs, rhs);
241     llvm_unreachable("unsupported non numeric type");
242   }
243 
244   void yieldOutputs(ValueRange values) {
245     assert(!values.empty() && "linalg ops must yield outputs");
246     if (values.empty())
247       return;
248     Value first = values.front();
249     OpBuilder builder = getBuilder(first);
250     builder.create<YieldOp>(first.getLoc(), values);
251   }
252 
253 private:
254   Block &block;
255 
256   bool isFloatingPoint(Value value) { return value.getType().isa<FloatType>(); }
257   bool isInteger(Value value) { return value.getType().isa<IntegerType>(); }
258 
259   OpBuilder getBuilder(Value value) {
260     OpBuilder builder(value.getContext());
261     builder.setInsertionPointToEnd(&block);
262     return builder;
263   }
264 };
265 
266 } // namespace
267 
268 //===----------------------------------------------------------------------===//
269 // CopyOp
270 //===----------------------------------------------------------------------===//
271 void CopyOp::regionBuilder(Block &block, ValueRange captures) {
272   using namespace edsc::intrinsics;
273   assert(block.getNumArguments() == 2 && "CopyOp regionBuilder expects 2 args");
274   (linalg_yield(block.getArgument(0)));
275 }
276 
277 void CopyOp::build(OpBuilder &builder, OperationState &result, Value input,
278                    Value output, AffineMap inputPermutation,
279                    AffineMap outputPermutation,
280                    ArrayRef<NamedAttribute> namedAttrs) {
281   result.addOperands({input, output});
282   result.addAttributes(namedAttrs);
283   if (inputPermutation)
284     result.addAttribute("inputPermutation",
285                         AffineMapAttr::get(inputPermutation));
286   if (outputPermutation)
287     result.addAttribute("outputPermutation",
288                         AffineMapAttr::get(outputPermutation));
289   result.addRegion();
290   fillStructuredOpRegion<CopyOp>(builder, *result.regions.front(),
291                                  TypeRange{input.getType()},
292                                  TypeRange{output.getType()});
293 }
294 
295 ParseResult parseCopyOpRegion(OpAsmParser &parser, Region &r, Type inputType,
296                               Type outputType) {
297   OpBuilder opBuilder(parser.getBuilder().getContext());
298   fillStructuredOpRegion<CopyOp>(opBuilder, r, TypeRange{inputType},
299                                  TypeRange{outputType});
300   return success();
301 }
302 
303 /// CopyOp region is elided when printing.
304 void printCopyOpRegion(OpAsmPrinter &, Operation *, Region &, Type, Type) {}
305 
306 static LogicalResult verify(CopyOp op) {
307   auto outputViewType = op.getOutputShapedType(0);
308   auto inputViewType = op.getInputShapedType(0);
309   if (inputViewType.getElementType() != outputViewType.getElementType())
310     return op.emitOpError("expects views of the same type");
311   if (inputViewType.getRank() != outputViewType.getRank())
312     return op.emitOpError("expects views of the same rank");
313   auto rank = op.getNumParallelLoops();
314   auto inputPermutationMap = op.inputPermutation();
315   if (inputPermutationMap) {
316     if (inputPermutationMap->getNumInputs() != rank)
317       return op.emitOpError("expects optional input_permutation map of rank ")
318              << rank;
319     if (!inputPermutationMap->isPermutation())
320       return op.emitOpError(
321           "expects optional input_permutation map to be a permutation");
322   }
323   auto outputPermutationMap = op.outputPermutation();
324   if (outputPermutationMap) {
325     if (outputPermutationMap->getNumInputs() != rank)
326       return op.emitOpError("expects optional output_permutation map of rank ")
327              << rank;
328     if (!outputPermutationMap->isPermutation())
329       return op.emitOpError(
330           "expects optional output_permutation map to be a permutation");
331   }
332   if (rank == 0 && inputPermutationMap)
333     return op.emitOpError("expected no input permutation when rank == 0");
334   if (rank == 0 && outputPermutationMap)
335     return op.emitOpError("expected no output permutation when rank == 0");
336   return success();
337 }
338 
339 void CopyOp::getEffects(
340     SmallVectorImpl<SideEffects::EffectInstance<MemoryEffects::Effect>>
341         &effects) {
342   effects.emplace_back(MemoryEffects::Read::get(), input(),
343                        SideEffects::DefaultResource::get());
344   effects.emplace_back(MemoryEffects::Write::get(), output(),
345                        SideEffects::DefaultResource::get());
346 }
347 
348 //===----------------------------------------------------------------------===//
349 // FillOp
350 //===----------------------------------------------------------------------===//
351 void FillOp::regionBuilder(Block &block, ValueRange captures) {
352   using namespace edsc::intrinsics;
353   assert(captures.size() == 1 && "FillOp regionBuilder expects 1 capture");
354   (linalg_yield(captures));
355 }
356 
357 void FillOp::build(OpBuilder &builder, OperationState &result, Value output,
358                    Value value) {
359   build(builder, result, output.getType().dyn_cast<RankedTensorType>(), output,
360         value);
361   fillStructuredOpRegion<FillOp>(builder, *result.regions.front(), TypeRange{},
362                                  TypeRange{output.getType()}, value);
363 }
364 
365 ParseResult parseFillOpRegion(OpAsmParser &parser, Region &r, Type outputType,
366                               OpAsmParser::OperandType valueRef) {
367   OpBuilder opBuilder(parser.getBuilder().getContext());
368   // Resolve `valueRef` into `value` at parse time so we can build the region
369   // with captures.
370   SmallVector<Value> value;
371   parser.resolveOperand(valueRef, getElementTypeOrSelf(outputType), value);
372   fillStructuredOpRegion<FillOp>(opBuilder, r, TypeRange{},
373                                  TypeRange{outputType}, value);
374   return success();
375 }
376 
377 /// FillOp region is elided when printing.
378 void printFillOpRegion(OpAsmPrinter &, Operation *, Region &, Type, Value) {}
379 
380 static LogicalResult verify(FillOp op) {
381   auto viewType = op.getOutputShapedType(0);
382   auto fillType = op.value().getType();
383   if (viewType.getElementType() != fillType)
384     return op.emitOpError("expects fill type to match view elemental type");
385   if (!op.getNumResults() && !viewType.isa<MemRefType>()) {
386     return op.emitOpError(
387         "expected fill op with no result value to use memref type");
388   }
389   return success();
390 }
391 
392 void FillOp::getEffects(
393     SmallVectorImpl<SideEffects::EffectInstance<MemoryEffects::Effect>>
394         &effects) {
395   if (output().getType().isa<MemRefType>())
396     effects.emplace_back(MemoryEffects::Write::get(), output(),
397                          SideEffects::DefaultResource::get());
398 }
399 
400 //===----------------------------------------------------------------------===//
401 // GenericOps
402 //===----------------------------------------------------------------------===//
403 void GenericOp::build(
404     OpBuilder &builder, OperationState &result, TypeRange resultTensorTypes,
405     ValueRange inputs, ValueRange outputs, ArrayRef<AffineMap> indexingMaps,
406     ArrayRef<StringRef> iteratorTypes, StringRef doc, StringRef libraryCall,
407     function_ref<void(OpBuilder &, Location, ValueRange)> bodyBuild) {
408   build(builder, result, resultTensorTypes, inputs, outputs,
409         builder.getAffineMapArrayAttr(indexingMaps),
410         builder.getStrArrayAttr(iteratorTypes),
411         doc.empty() ? StringAttr() : builder.getStringAttr(doc),
412         libraryCall.empty() ? StringAttr() : builder.getStringAttr(libraryCall),
413         ArrayAttr());
414   if (!bodyBuild)
415     return;
416 
417   SmallVector<Type, 4> blockArgTypes;
418   for (ValueRange container : {inputs, outputs})
419     for (Value v : container)
420       blockArgTypes.push_back(v.getType().cast<ShapedType>().getElementType());
421 
422   OpBuilder::InsertionGuard guard(builder);
423   auto &region = *result.regions.front();
424   Block *bodyBlock = builder.createBlock(&region, region.end(), blockArgTypes);
425   bodyBuild(builder, result.location, bodyBlock->getArguments());
426 }
427 
428 void GenericOp::build(
429     OpBuilder &builder, OperationState &result, ValueRange inputs,
430     ValueRange outputs, ArrayRef<AffineMap> indexingMaps,
431     ArrayRef<StringRef> iteratorTypes, StringRef doc, StringRef libraryCall,
432     function_ref<void(OpBuilder &, Location, ValueRange)> bodyBuild) {
433   build(builder, result, TypeRange{}, inputs, outputs, indexingMaps,
434         iteratorTypes, doc, libraryCall, bodyBuild);
435 }
436 
437 void GenericOp::build(
438     OpBuilder &builder, OperationState &result, ValueRange inputs,
439     ValueRange outputs, ArrayRef<AffineMap> indexingMaps,
440     ArrayRef<StringRef> iteratorTypes,
441     function_ref<void(OpBuilder &, Location, ValueRange)> bodyBuild) {
442   build(builder, result, inputs, outputs, indexingMaps, iteratorTypes,
443         /*doc=*/"",
444         /*libraryCall=*/"", bodyBuild);
445 }
446 
447 void GenericOp::build(
448     OpBuilder &builder, OperationState &result, TypeRange resultTensorTypes,
449     ValueRange inputs, ValueRange outputs, ArrayRef<AffineMap> indexingMaps,
450     ArrayRef<StringRef> iteratorTypes,
451     function_ref<void(OpBuilder &, Location, ValueRange)> bodyBuild) {
452   build(builder, result, resultTensorTypes, inputs, outputs, indexingMaps,
453         iteratorTypes,
454         /*doc=*/"",
455         /*libraryCall=*/"", bodyBuild);
456 }
457 void IndexedGenericOp::build(
458     OpBuilder &builder, OperationState &result, TypeRange resultTensorTypes,
459     ValueRange inputs, ValueRange outputs, ArrayRef<AffineMap> indexingMaps,
460     ArrayRef<StringRef> iteratorTypes, StringRef doc, StringRef libraryCall,
461     function_ref<void(OpBuilder &, Location, ValueRange, ValueRange)>
462         bodyBuild) {
463   build(builder, result, resultTensorTypes, inputs, outputs,
464         builder.getAffineMapArrayAttr(indexingMaps),
465         builder.getStrArrayAttr(iteratorTypes),
466         doc.empty() ? StringAttr() : builder.getStringAttr(doc),
467         libraryCall.empty() ? StringAttr() : builder.getStringAttr(libraryCall),
468         ArrayAttr());
469   if (!bodyBuild)
470     return;
471 
472   unsigned nLoops = iteratorTypes.size();
473   SmallVector<Type, 4> blockArgTypes(nLoops, builder.getIndexType());
474   for (ValueRange container : {inputs, outputs})
475     for (Value v : container)
476       blockArgTypes.push_back(v.getType().cast<ShapedType>().getElementType());
477 
478   OpBuilder::InsertionGuard guard(builder);
479   auto &region = *result.regions.front();
480   Block *bodyBlock = builder.createBlock(&region, region.end(), blockArgTypes);
481   bodyBuild(builder, result.location,
482             bodyBlock->getArguments().take_front(nLoops),
483             bodyBlock->getArguments().drop_front(nLoops));
484 }
485 
486 void IndexedGenericOp::build(
487     OpBuilder &builder, OperationState &result, ValueRange inputs,
488     ValueRange outputs, ArrayRef<AffineMap> indexingMaps,
489     ArrayRef<StringRef> iteratorTypes, StringRef doc, StringRef libraryCall,
490     function_ref<void(OpBuilder &, Location, ValueRange, ValueRange)>
491         bodyBuild) {
492   build(builder, result, TypeRange{}, inputs, outputs, indexingMaps,
493         iteratorTypes, doc, libraryCall, bodyBuild);
494 }
495 
496 void IndexedGenericOp::build(
497     OpBuilder &builder, OperationState &result, ValueRange inputs,
498     ValueRange outputs, ArrayRef<AffineMap> indexingMaps,
499     ArrayRef<StringRef> iteratorTypes,
500     function_ref<void(OpBuilder &, Location, ValueRange, ValueRange)>
501         bodyBuild) {
502   build(builder, result, inputs, outputs, indexingMaps, iteratorTypes,
503         /*doc=*/"", /*libraryCall=*/"", bodyBuild);
504 }
505 
506 void IndexedGenericOp::build(
507     OpBuilder &builder, OperationState &result, TypeRange resultTensorTypes,
508     ValueRange inputs, ValueRange outputs, ArrayRef<AffineMap> indexingMaps,
509     ArrayRef<StringRef> iteratorTypes,
510     function_ref<void(OpBuilder &, Location, ValueRange, ValueRange)>
511         bodyBuild) {
512   build(builder, result, resultTensorTypes, inputs, outputs, indexingMaps,
513         iteratorTypes,
514         /*doc=*/"",
515         /*libraryCall=*/"", bodyBuild);
516 }
517 
518 template <typename GenericOpType>
519 static void printGenericOp(OpAsmPrinter &p, GenericOpType op) {
520   p << op.getOperationName() << " ";
521 
522   // Print extra attributes.
523   auto genericAttrNames = op.linalgTraitAttrNames();
524 
525   llvm::StringSet<> genericAttrNamesSet;
526   genericAttrNamesSet.insert(genericAttrNames.begin(), genericAttrNames.end());
527   SmallVector<NamedAttribute, 8> genericAttrs;
528   for (auto attr : op->getAttrs())
529     if (genericAttrNamesSet.count(attr.first.strref()) > 0)
530       genericAttrs.push_back(attr);
531   if (!genericAttrs.empty()) {
532     auto genericDictAttr = DictionaryAttr::get(op.getContext(), genericAttrs);
533     p << genericDictAttr;
534   }
535 
536   // Printing is shared with named ops, except for the region and attributes
537   printCommonStructuredOpParts(p, op);
538 
539   genericAttrNames.push_back("operand_segment_sizes");
540   genericAttrNamesSet.insert(genericAttrNames.back());
541 
542   bool hasExtraAttrs = false;
543   for (NamedAttribute n : op->getAttrs()) {
544     if ((hasExtraAttrs = !genericAttrNamesSet.contains(n.first.strref())))
545       break;
546   }
547   if (hasExtraAttrs) {
548     p << " attrs = ";
549     p.printOptionalAttrDict(op->getAttrs(), /*elidedAttrs=*/genericAttrNames);
550   }
551 
552   // Print region.
553   if (!op.region().empty())
554     p.printRegion(op.region());
555 
556   // Print results.
557   printNamedStructuredOpResults(p, op.result_tensors().getTypes());
558 }
559 
560 static void print(OpAsmPrinter &p, GenericOp op) { printGenericOp(p, op); }
561 
562 static void print(OpAsmPrinter &p, IndexedGenericOp op) {
563   printGenericOp(p, op);
564 }
565 
566 static ParseResult parseGenericOp(OpAsmParser &parser, OperationState &result) {
567   DictionaryAttr dictAttr;
568   // Parse the core linalg traits that must check into a dictAttr.
569   // The name is unimportant as we will overwrite result.attributes.
570   // The core linalg traits must contain the information necessary to pass the
571   // verifier.
572   if (parser.parseAttribute(dictAttr, "_", result.attributes))
573     return failure();
574   result.attributes.assign(dictAttr.getValue().begin(),
575                            dictAttr.getValue().end());
576 
577   // Parsing is shared with named ops, except for the region.
578   SmallVector<Type, 1> inputTypes, outputTypes;
579   if (parseCommonStructuredOpParts(parser, result, inputTypes, outputTypes))
580     return failure();
581 
582   // Optional attributes may be added.
583   if (succeeded(parser.parseOptionalKeyword("attrs")))
584     if (failed(parser.parseEqual()) ||
585         failed(parser.parseOptionalAttrDict(result.attributes)))
586       return failure();
587 
588   SmallVector<OpAsmParser::OperandType, 8> regionOperands;
589   std::unique_ptr<Region> region = std::make_unique<Region>();
590   SmallVector<Type, 8> operandTypes, regionTypes;
591   if (parser.parseRegion(*region, regionOperands, regionTypes))
592     return failure();
593   result.addRegion(std::move(region));
594 
595   // Generic ops may specify that a subset of its outputs are tensors. Such
596   // outputs are specified in the result type.
597   // TODO: may need to move output parsing before region parsing.
598   // Need to wait for declarative assembly resolution to decide.
599   SmallVector<Type, 1> outputTensorsTypes;
600   if (parseNamedStructuredOpResults(parser, outputTensorsTypes))
601     return failure();
602   result.addTypes(outputTensorsTypes);
603 
604   return success();
605 }
606 
607 static void getGenericEffectsImpl(
608     SmallVectorImpl<SideEffects::EffectInstance<MemoryEffects::Effect>>
609         &effects,
610     ValueRange results, ValueRange inputBuffers, ValueRange outputs) {
611   for (Value value : results) {
612     effects.emplace_back(MemoryEffects::Allocate::get(), value,
613                          SideEffects::DefaultResource::get());
614   }
615   for (Value value : inputBuffers) {
616     effects.emplace_back(MemoryEffects::Read::get(), value,
617                          SideEffects::DefaultResource::get());
618   }
619   for (Value value : outputs) {
620     effects.emplace_back(MemoryEffects::Read::get(), value,
621                          SideEffects::DefaultResource::get());
622     effects.emplace_back(MemoryEffects::Write::get(), value,
623                          SideEffects::DefaultResource::get());
624   }
625 }
626 
627 void GenericOp::getEffects(
628     SmallVectorImpl<SideEffects::EffectInstance<MemoryEffects::Effect>>
629         &effects) {
630   getGenericEffectsImpl(effects, getOperation()->getResults(),
631                         getInputBuffers(), getOutputBuffers());
632 }
633 
634 void IndexedGenericOp::getEffects(
635     SmallVectorImpl<SideEffects::EffectInstance<MemoryEffects::Effect>>
636         &effects) {
637   getGenericEffectsImpl(effects, getOperation()->getResults(),
638                         getInputBuffers(), getOutputBuffers());
639 }
640 
641 namespace {
642 
643 template <typename GenericOpType>
644 struct AnnotationsVerifier {
645   static LogicalResult verify(GenericOpType op) { return success(); }
646 };
647 
648 template <>
649 LogicalResult AnnotationsVerifier<GenericOp>::verify(GenericOp op) {
650   ArrayAttr sparseAttr = op.sparseAttr();
651   if (!sparseAttr)
652     return success();
653   // Verify consistency of sparse annotations.
654   if (!op.hasTensorSemantics())
655     return op.emitOpError("expected sparse annotations on tensors only");
656   if (op.getNumOutputs() != 1)
657     return op.emitOpError("expected single output tensor");
658   unsigned numTensors = op.getNumShapedOperands();
659   if (sparseAttr.size() != numTensors)
660     return op.emitOpError("expected one sparse annotation for each tensor");
661   for (unsigned t = 0; t < numTensors; t++) {
662     auto dimAttr = sparseAttr[t].dyn_cast_or_null<ArrayAttr>();
663     if (!dimAttr)
664       return op.emitOpError("expected sparse annotation array for tensor ")
665              << t;
666     unsigned rank = op.getShapedType(t).getRank();
667     if (dimAttr.size() != rank)
668       return op.emitOpError("expected sparse annotation with rank ")
669              << rank << " for tensor " << t;
670     // Per-dimension annotations for each tensor consist of only "D" or "S".
671     for (unsigned d = 0; d < rank; d++) {
672       if (isDenseDim(dimAttr[d])) {
673         continue;
674       } else if (isSparseDim(dimAttr[d])) {
675         if (t == numTensors - 1)
676           return op.emitOpError("sparse output tensors not supported (yet)");
677         continue;
678       }
679       return op.emitOpError("expected sparse annotation at position ")
680              << d << " for tensor " << t;
681     }
682   }
683   return success();
684 }
685 
686 } // namespace
687 
688 template <typename GenericOpType>
689 static LogicalResult verifyGenericOp(GenericOpType op) {
690   if (failed(AnnotationsVerifier<GenericOpType>::verify(op)))
691     return failure();
692 
693   return success();
694 }
695 
696 static LogicalResult verify(GenericOp op) { return verifyGenericOp(op); }
697 
698 static LogicalResult verify(IndexedGenericOp op) { return verifyGenericOp(op); }
699 
700 //===----------------------------------------------------------------------===//
701 // InitTensorOp
702 //===----------------------------------------------------------------------===//
703 void InitTensorOp::build(OpBuilder &b, OperationState &result,
704                          ArrayRef<OpFoldResult> sizes, Type elementType,
705                          ArrayRef<NamedAttribute> attrs) {
706   unsigned rank = sizes.size();
707   SmallVector<Value, 4> dynamicSizes;
708   SmallVector<int64_t, 4> staticSizes;
709   for (unsigned i = 0; i < rank; ++i) {
710     dispatchIndexOpFoldResult(sizes[i], dynamicSizes, staticSizes,
711                               ShapedType::kDynamicSize);
712   }
713   auto resultType = RankedTensorType ::get(staticSizes, elementType);
714   build(b, result, resultType, dynamicSizes, b.getI64ArrayAttr(staticSizes));
715   result.addAttributes(attrs);
716 }
717 
718 static LogicalResult verify(InitTensorOp op) {
719   RankedTensorType resultType = op.getType();
720   SmallVector<int64_t, 4> staticSizes = llvm::to_vector<4>(llvm::map_range(
721       op.static_sizes().cast<ArrayAttr>(),
722       [](Attribute a) -> int64_t { return a.cast<IntegerAttr>().getInt(); }));
723 
724   if (failed(verifyListOfOperandsOrIntegers(op, "sizes", resultType.getRank(),
725                                             op.static_sizes(), op.sizes(),
726                                             ShapedType::isDynamic)))
727     return failure();
728 
729   if (op.static_sizes().size() != static_cast<unsigned>(resultType.getRank()))
730     return op->emitError("expected ")
731            << resultType.getRank() << " sizes values";
732 
733   Type expectedType =
734       InitTensorOp::inferResultType(staticSizes, resultType.getElementType());
735   if (resultType != expectedType) {
736     return op.emitError("specified type ")
737            << resultType << " does not match the inferred type "
738            << expectedType;
739   }
740   return success();
741 }
742 
743 Type InitTensorOp::inferResultType(ArrayRef<int64_t> staticSizes,
744                                    Type elementType) {
745   return RankedTensorType::get(staticSizes, elementType);
746 }
747 
748 namespace {
749 /// Change the type of the result of a `linalg.init_tensor` by making the result
750 /// type statically sized along dimension that in the original operation where
751 /// defined as dynamic, but the size was defined using a `constant` op. For
752 /// example
753 ///
754 ///  %c5 = constant 5: index
755 ///  %0 = linalg.init_tensor [%arg0, %c5] : tensor<?x?xf32>
756 ///
757 ///  to
758 ///
759 ///  %0 = linalg.init_tensor [%arg0, 5] : tensor<?x5xf32>
760 struct ReplaceStaticShapeDims : OpRewritePattern<InitTensorOp> {
761   using OpRewritePattern<InitTensorOp>::OpRewritePattern;
762 
763   LogicalResult matchAndRewrite(InitTensorOp op,
764                                 PatternRewriter &rewriter) const override {
765     SmallVector<Value, 4> dynamicSizes;
766     SmallVector<int64_t, 4> staticSizes;
767     for (unsigned i = 0, e = op.getType().getRank(); i != e; ++i) {
768       // If the size is already static, nothing to do.
769       if (!op.isDynamicSize(i)) {
770         staticSizes.push_back(op.getStaticSize(i));
771         continue;
772       }
773 
774       // If the size is dynamic but defined using a `constant` op, get the
775       // constant value to find the static size to use.
776       unsigned operandNum = op.getIndexOfDynamicSize(i);
777       Value sizeOperand = op.getOperand(operandNum);
778       if (auto constantIndexOp = sizeOperand.getDefiningOp<ConstantIndexOp>()) {
779         staticSizes.push_back(constantIndexOp.getValue());
780         continue;
781       }
782 
783       // Fallback case. Keep the size dynamic.
784       dynamicSizes.push_back(sizeOperand);
785       staticSizes.push_back(ShapedType::kDynamicSize);
786     }
787     RankedTensorType newType =
788         RankedTensorType::get(staticSizes, op.getType().getElementType());
789     if (newType == op.getType())
790       return failure();
791     auto newOp =
792         rewriter.create<InitTensorOp>(op.getLoc(), newType, dynamicSizes,
793                                       rewriter.getI64ArrayAttr(staticSizes));
794     rewriter.replaceOpWithNewOp<tensor::CastOp>(op, op.getType(), newOp);
795     return success();
796   }
797 };
798 } // namespace
799 
800 namespace {
801 /// Since `init_tensor` operation creates a tensor needed only for its shape, a
802 /// subtensor of this is also needed only for its shape. The result can be
803 /// replaced by a new init_tensor operation of the same size as the subtensor
804 /// op.
805 struct FoldInitTensorWithSubTensorOp : public OpRewritePattern<SubTensorOp> {
806   using OpRewritePattern<SubTensorOp>::OpRewritePattern;
807 
808   LogicalResult matchAndRewrite(SubTensorOp subtensorOp,
809                                 PatternRewriter &rewriter) const override {
810     if (!subtensorOp.source().getDefiningOp<linalg::InitTensorOp>())
811       return failure();
812     rewriter.replaceOpWithNewOp<linalg::InitTensorOp>(
813         subtensorOp, subtensorOp.sizes(),
814         llvm::to_vector<4>(llvm::map_range(
815             subtensorOp.static_sizes(),
816             [](Attribute attr) { return attr.cast<IntegerAttr>().getInt(); })),
817         subtensorOp.getSourceType().getElementType());
818     return success();
819   }
820 };
821 
822 struct FoldInitTensorWithTensorReshapeOp
823     : public OpRewritePattern<TensorReshapeOp> {
824   using OpRewritePattern<TensorReshapeOp>::OpRewritePattern;
825 
826   LogicalResult matchAndRewrite(TensorReshapeOp reshapeOp,
827                                 PatternRewriter &rewriter) const override {
828     if (!reshapeOp.src().getDefiningOp<InitTensorOp>())
829       return failure();
830     Location loc = reshapeOp.getLoc();
831     SmallVector<SmallVector<Value>, 4> resultShapes;
832     if (failed(reshapeOp.reifyReturnTypeShapesPerResultDim(rewriter,
833                                                            resultShapes)) ||
834         !llvm::hasSingleElement(resultShapes))
835       return failure();
836     Value initTensor = rewriter.create<InitTensorOp>(
837         loc, getAsOpFoldResult(resultShapes[0]),
838         reshapeOp.getResultType().getElementType());
839     if (initTensor.getType() != reshapeOp.getResultType()) {
840       rewriter.replaceOpWithNewOp<tensor::CastOp>(
841           reshapeOp, reshapeOp.getResultType(), initTensor);
842     } else {
843       rewriter.replaceOp(reshapeOp, initTensor);
844     }
845     return success();
846   }
847 };
848 } // namespace
849 
850 void InitTensorOp::getCanonicalizationPatterns(RewritePatternSet &results,
851                                                MLIRContext *context) {
852   results.add<FoldInitTensorWithSubTensorOp, FoldInitTensorWithTensorReshapeOp,
853               ReplaceStaticShapeDims>(context);
854 }
855 
856 LogicalResult InitTensorOp::reifyReturnTypeShapesPerResultDim(
857     OpBuilder &builder,
858     SmallVectorImpl<SmallVector<Value>> &reifiedReturnShapes) {
859   auto shapes = llvm::to_vector<4>(llvm::map_range(
860       llvm::seq<int64_t>(0, getType().getRank()), [&](int64_t dim) -> Value {
861         if (isDynamicSize(dim))
862           return getDynamicSize(dim);
863         return builder.create<ConstantIndexOp>(getLoc(), getStaticSize(dim));
864       }));
865   reifiedReturnShapes.emplace_back(std::move(shapes));
866   return success();
867 }
868 
869 //===----------------------------------------------------------------------===//
870 // PadTensorOp
871 //===----------------------------------------------------------------------===//
872 
873 /// Extract int64_t values from the assumed ArrayAttr of IntegerAttr.
874 static SmallVector<int64_t, 4> extractFromI64ArrayAttr(Attribute attr) {
875   return llvm::to_vector<4>(
876       llvm::map_range(attr.cast<ArrayAttr>(), [](Attribute a) -> int64_t {
877         return a.cast<IntegerAttr>().getInt();
878       }));
879 }
880 
881 static LogicalResult verify(PadTensorOp op) {
882   auto sourceType = op.source().getType().cast<RankedTensorType>();
883   auto resultType = op.result().getType().cast<RankedTensorType>();
884   auto expectedType = PadTensorOp::inferResultType(
885       sourceType, extractFromI64ArrayAttr(op.static_low()),
886       extractFromI64ArrayAttr(op.static_high()));
887   for (int i = 0, e = sourceType.getRank(); i < e; ++i) {
888     if (resultType.getDimSize(i) == expectedType.getDimSize(i))
889       continue;
890     if (expectedType.isDynamicDim(i))
891       continue;
892     return op.emitError("specified type ")
893            << resultType << " does not match the inferred type "
894            << expectedType;
895   }
896 
897   auto &region = op.region();
898   unsigned rank = resultType.getRank();
899   Block &block = region.front();
900   if (block.getNumArguments() != rank)
901     return op.emitError("expected the block to have ") << rank << " arguments";
902 
903   // Note: the number and type of yield values are checked in the YieldOp.
904   for (auto en : llvm::enumerate(block.getArgumentTypes())) {
905     if (!en.value().isIndex())
906       return op.emitOpError("expected block argument ")
907              << (en.index() + 1) << " to be an index";
908   }
909 
910   return success();
911 }
912 
913 RankedTensorType PadTensorOp::inferResultType(RankedTensorType sourceType,
914                                               ArrayRef<int64_t> staticLow,
915                                               ArrayRef<int64_t> staticHigh) {
916   unsigned rank = sourceType.getRank();
917   assert(staticLow.size() == rank && "unexpected staticLow size mismatch");
918   assert(staticHigh.size() == rank && "unexpected staticHigh size mismatch");
919 
920   SmallVector<int64_t, 4> resultShape;
921   for (auto i : llvm::seq<unsigned>(0, rank)) {
922     if (sourceType.isDynamicDim(i) ||
923         staticLow[i] == ShapedType::kDynamicSize ||
924         staticHigh[i] == ShapedType::kDynamicSize) {
925       resultShape.push_back(ShapedType::kDynamicSize);
926     } else {
927       int64_t size = sourceType.getDimSize(i) + staticLow[i] + staticHigh[i];
928       resultShape.push_back(size);
929     }
930   }
931 
932   return RankedTensorType::get(resultShape, sourceType.getElementType());
933 }
934 
935 void PadTensorOp::build(OpBuilder &b, OperationState &result, Value source,
936                         ArrayRef<int64_t> staticLow,
937                         ArrayRef<int64_t> staticHigh, ValueRange low,
938                         ValueRange high, ArrayRef<NamedAttribute> attrs) {
939   auto sourceType = source.getType().cast<RankedTensorType>();
940   auto resultType = inferResultType(sourceType, staticLow, staticHigh);
941   build(b, result, resultType, source, low, high, b.getI64ArrayAttr(staticLow),
942         b.getI64ArrayAttr(staticHigh));
943   result.addAttributes(attrs);
944 }
945 
946 void PadTensorOp::build(OpBuilder &b, OperationState &result, Value source,
947                         ValueRange low, ValueRange high,
948                         ArrayRef<NamedAttribute> attrs) {
949   auto sourceType = source.getType().cast<RankedTensorType>();
950   unsigned rank = sourceType.getRank();
951   SmallVector<int64_t, 4> staticVector(ShapedType::kDynamicSize, rank);
952   build(b, result, source, staticVector, staticVector, low, high, attrs);
953 }
954 
955 void PadTensorOp::build(OpBuilder &b, OperationState &result, Type resultType,
956                         Value source, ArrayRef<OpFoldResult> low,
957                         ArrayRef<OpFoldResult> high,
958                         ArrayRef<NamedAttribute> attrs) {
959   assert(resultType.isa<RankedTensorType>());
960   auto sourceType = source.getType().cast<RankedTensorType>();
961   unsigned rank = sourceType.getRank();
962   SmallVector<Value, 4> dynamicLow, dynamicHigh;
963   SmallVector<int64_t, 4> staticLow, staticHigh;
964   for (unsigned i = 0; i < rank; ++i) {
965     // staticLow and staticHigh have full information of the padding config.
966     // This will grow staticLow and staticHigh with 1 value. If the config is
967     // dynamic (ie not a constant), dynamicLow and dynamicHigh will grow with 1
968     // value as well.
969     dispatchIndexOpFoldResult(low[i], dynamicLow, staticLow,
970                               ShapedType::kDynamicSize);
971     dispatchIndexOpFoldResult(high[i], dynamicHigh, staticHigh,
972                               ShapedType::kDynamicSize);
973   }
974   if (!resultType) {
975     resultType =
976         PadTensorOp::inferResultType(sourceType, staticLow, staticHigh);
977   }
978   build(b, result, resultType, source, dynamicLow, dynamicHigh,
979         b.getI64ArrayAttr(staticLow), b.getI64ArrayAttr(staticHigh));
980 }
981 
982 PadTensorOp PadTensorOp::createPadScalarOp(Type type, Value source, Value pad,
983                                            ArrayRef<OpFoldResult> low,
984                                            ArrayRef<OpFoldResult> high,
985                                            Location loc, OpBuilder &builder) {
986   auto padTensorOp =
987       builder.create<linalg::PadTensorOp>(loc, type, source, low, high);
988   int rank = padTensorOp.getResultType().getRank();
989   SmallVector<Type, 4> blockArgTypes;
990   blockArgTypes.assign(rank, builder.getIndexType());
991   auto &region = padTensorOp.region();
992   // `builder.createBlock` changes the insertion point within the block. Create
993   // a guard to reset the insertion point of the builder after it is destroyed.
994   OpBuilder::InsertionGuard guard(builder);
995   builder.createBlock(&region, region.end(), blockArgTypes);
996   builder.create<linalg::YieldOp>(loc, pad);
997   return padTensorOp;
998 }
999 
1000 PadTensorOp PadTensorOp::createPadHighOp(Type type, Value source, Value pad,
1001                                          Location loc, OpBuilder &builder) {
1002   SmallVector<OpFoldResult, 4> low, high;
1003   auto rankedTensorType = type.cast<RankedTensorType>();
1004   assert(rankedTensorType.hasStaticShape());
1005   int rank = rankedTensorType.getRank();
1006   for (int i = 0; i < rank; ++i) {
1007     auto dimOp = builder.createOrFold<memref::DimOp>(loc, source, i);
1008     auto resultDimSize = builder.createOrFold<ConstantIndexOp>(
1009         loc, rankedTensorType.getDimSize(i));
1010     auto highValue = builder.createOrFold<SubIOp>(loc, resultDimSize, dimOp);
1011     high.push_back(highValue);
1012     low.push_back(builder.createOrFold<ConstantIndexOp>(loc, 0));
1013   }
1014   return PadTensorOp::createPadScalarOp(type, source, pad, low, high, loc,
1015                                         builder);
1016 }
1017 
1018 LogicalResult PadTensorOp::reifyReturnTypeShapesPerResultDim(
1019     OpBuilder &b, SmallVectorImpl<SmallVector<Value>> &reifiedReturnShapes) {
1020   Location loc = getLoc();
1021   auto lowPad = getMixedLowPad();
1022   auto highPad = getMixedHighPad();
1023   SmallVector<Value> shapes;
1024   for (auto dim : llvm::seq<int64_t>(0, getSourceType().getRank())) {
1025     // Shape along each dimension is source dim + low pad + high pad.
1026     SmallVector<Value> mapOperands;
1027     mapOperands.push_back(b.createOrFold<memref::DimOp>(loc, source(), dim));
1028     AffineExpr expr = b.getAffineDimExpr(0);
1029     unsigned numSymbols = 0;
1030     auto addOpFoldResult = [&](OpFoldResult valueOrAttr) {
1031       if (Value v = valueOrAttr.dyn_cast<Value>()) {
1032         expr = expr + b.getAffineSymbolExpr(numSymbols++);
1033         mapOperands.push_back(v);
1034         return;
1035       }
1036       int64_t staticValue =
1037           valueOrAttr.get<Attribute>().cast<IntegerAttr>().getInt();
1038       expr = expr + staticValue;
1039     };
1040     addOpFoldResult(lowPad[dim]);
1041     addOpFoldResult(highPad[dim]);
1042     shapes.push_back(applyMapToValues(
1043         b, loc, AffineMap::get(1, numSymbols, expr), mapOperands)[0]);
1044   }
1045   reifiedReturnShapes.emplace_back(std::move(shapes));
1046   return success();
1047 }
1048 
1049 //===----------------------------------------------------------------------===//
1050 // ReshapeOp
1051 //===----------------------------------------------------------------------===//
1052 
1053 /// Collapse reassociation maps that are used in pair of reshape ops where one
1054 /// is a producer and other is the consumer. Only valid to use this method when
1055 /// both the producer and consumer are collapsing dimensions or both are
1056 /// expanding dimensions.
1057 ///
1058 /// For example,
1059 ///   mapsProducer = [affine_map<(d0, d1, d2, d3, d4) -> (d0, d1)>,
1060 ///                   affine_map<(d0, d1, d2, d3, d4) -> (d2)>,
1061 ///                   affine_map<(d0, d1, d2, d3, d4) -> (d3, d4)>]
1062 ///   mapsConsumer = [affine_map<(d0, d1, d2) -> (d0, d1)>,
1063 ///                   affine_map<(d0, d1, d2) -> (d2)>]
1064 ///
1065 /// is folded into
1066 ///
1067 ///   result = [affine_map<(d0, d1, d2, d3, d4) -> (d0, d1, d2)>,
1068 ///             affine_map<(d0, d1, d2, d3, d4) -> (d3, d4)>]
1069 static ArrayAttr collapseReassociationMaps(ArrayRef<AffineMap> mapsProducer,
1070                                            ArrayRef<AffineMap> mapsConsumer,
1071                                            MLIRContext *context) {
1072   // Handle the corner case of the result being a rank 0 shaped type. Return an
1073   // emtpy ArrayAttr.
1074   if (mapsConsumer.empty() && !mapsProducer.empty())
1075     return ArrayAttr::get(context, ArrayRef<Attribute>());
1076   if (mapsProducer.empty() || mapsConsumer.empty() ||
1077       mapsProducer[0].getNumDims() < mapsConsumer[0].getNumDims() ||
1078       mapsProducer.size() != mapsConsumer[0].getNumDims())
1079     return nullptr;
1080   unsigned numLhsDims = mapsProducer[0].getNumDims();
1081   unsigned currDim = 0;
1082   SmallVector<AffineExpr, 4> reassociations;
1083   SmallVector<Attribute, 4> reassociationMaps;
1084   for (AffineMap rhs : mapsConsumer) {
1085     for (AffineExpr rhsExpr : rhs.getResults()) {
1086       AffineDimExpr dimExpr = rhsExpr.cast<AffineDimExpr>();
1087       for (int i = 0, e = mapsProducer[dimExpr.getPosition()].getNumResults();
1088            i < e; ++i) {
1089         reassociations.push_back(getAffineDimExpr(currDim++, context));
1090       }
1091     }
1092     reassociationMaps.push_back(AffineMapAttr::get(AffineMap::get(
1093         numLhsDims, /*numSymbols =*/0, reassociations, context)));
1094     reassociations.clear();
1095   }
1096   return ArrayAttr::get(context, reassociationMaps);
1097 }
1098 
1099 namespace {
1100 /// Pattern to collapse producer/consumer reshape ops that are both collapsing
1101 /// dimensions or are both expanding dimensions.
1102 template <typename ReshapeOpTy>
1103 struct CollapseReshapeOps : public OpRewritePattern<ReshapeOpTy> {
1104   using OpRewritePattern<ReshapeOpTy>::OpRewritePattern;
1105   LogicalResult matchAndRewrite(ReshapeOpTy reshapeOp,
1106                                 PatternRewriter &rewriter) const override {
1107     auto srcReshapeOp = reshapeOp.src().template getDefiningOp<ReshapeOpTy>();
1108     if (!srcReshapeOp)
1109       return failure();
1110 
1111     auto areReshapeOpsFoldable = [](ShapedType largerType,
1112                                     ShapedType intermediateType,
1113                                     ShapedType smallerType) -> bool {
1114       return largerType.getRank() > intermediateType.getRank() &&
1115              intermediateType.getRank() > smallerType.getRank();
1116     };
1117     // Check if producer and consumer are both expanding dims.
1118     if (areReshapeOpsFoldable(reshapeOp.getResultType(), reshapeOp.getSrcType(),
1119                               srcReshapeOp.getSrcType())) {
1120       rewriter.replaceOpWithNewOp<ReshapeOpTy>(
1121           reshapeOp, reshapeOp.getResultType(), srcReshapeOp.src(),
1122           collapseReassociationMaps(reshapeOp.getReassociationMaps(),
1123                                     srcReshapeOp.getReassociationMaps(),
1124                                     rewriter.getContext()));
1125       return success();
1126     }
1127     // Check if producer and consumer are both collapsing dims.
1128     if (areReshapeOpsFoldable(srcReshapeOp.getSrcType(), reshapeOp.getSrcType(),
1129                               reshapeOp.getResultType())) {
1130       rewriter.replaceOpWithNewOp<ReshapeOpTy>(
1131           reshapeOp, reshapeOp.getResultType(), srcReshapeOp.src(),
1132           collapseReassociationMaps(srcReshapeOp.getReassociationMaps(),
1133                                     reshapeOp.getReassociationMaps(),
1134                                     rewriter.getContext()));
1135       return success();
1136     }
1137     return failure();
1138   }
1139 };
1140 } // namespace
1141 
1142 template <typename ReshapeOpTy>
1143 static OpFoldResult foldReshapeOp(ReshapeOpTy reshapeOp,
1144                                   ArrayRef<Attribute> operands) {
1145   // Fold producer-consumer reshape ops that where the operand type of the
1146   // producer is same as the return type of the consumer.
1147   ReshapeOpTy reshapeSrcOp =
1148       reshapeOp.src().template getDefiningOp<ReshapeOpTy>();
1149   if (reshapeSrcOp && reshapeSrcOp.getSrcType() == reshapeOp.getResultType())
1150     return reshapeSrcOp.src();
1151   // Reshape of a constant can be replaced with a new constant.
1152   if (auto elements = operands.front().dyn_cast_or_null<DenseElementsAttr>()) {
1153     return elements.reshape(
1154         reshapeOp.getResult().getType().template cast<ShapedType>());
1155   }
1156   return nullptr;
1157 }
1158 
1159 /// Return true if the reassociation specification is valid, false otherwise.
1160 /// When false, the `invalidIndex` integer pointer is optionally filled with the
1161 /// index of the offending reassociation map.
1162 static bool isReassociationValid(ArrayRef<AffineMap> reassociation,
1163                                  int *invalidIndex = nullptr) {
1164   if (reassociation.empty())
1165     return true;
1166   unsigned nDims = reassociation[0].getNumDims();
1167   unsigned nextExpectedDim = 0;
1168   for (auto it : llvm::enumerate(reassociation)) {
1169     auto m = it.value();
1170     if (m.getNumDims() != nDims || m.getNumSymbols() != 0) {
1171       if (invalidIndex)
1172         *invalidIndex = it.index();
1173       return false;
1174     }
1175     for (auto e : m.getResults()) {
1176       auto d = e.dyn_cast<AffineDimExpr>();
1177       if (!d || d.getPosition() != nextExpectedDim++) {
1178         if (invalidIndex)
1179           *invalidIndex = it.index();
1180         return false;
1181       }
1182     }
1183   }
1184   if (nextExpectedDim != nDims) {
1185     if (invalidIndex)
1186       *invalidIndex = reassociation.size() - 1;
1187     return false;
1188   }
1189   return true;
1190 }
1191 
1192 /// Detect whether memref dims [dim, dim + extent) can be reshaped without
1193 /// copies.
1194 static bool isReshapableDimBand(unsigned dim, unsigned extent,
1195                                 ArrayRef<int64_t> sizes,
1196                                 ArrayRef<AffineExpr> strides) {
1197   assert(sizes.size() == strides.size() && "mismatched ranks");
1198   // off by 1 indexing to avoid out of bounds
1199   //                       V
1200   for (auto idx = dim, e = dim + extent; idx + 1 < e; ++idx) {
1201     // Only bands of static shapes are reshapable. This is due to the fact that
1202     // there is no relation between dynamic sizes and dynamic strides: we do not
1203     // have enough information to know whether a "-1" size corresponds to the
1204     // proper symbol in the AffineExpr of a stride.
1205     if (ShapedType::isDynamic(sizes[dim + 1]))
1206       return false;
1207     // TODO: Refine this by passing the proper nDims and nSymbols so we can
1208     // simplify on the fly and catch more reshapable cases.
1209     if (strides[idx] != strides[idx + 1] * sizes[idx + 1])
1210       return false;
1211   }
1212   return true;
1213 }
1214 
1215 /// Compute the MemRefType obtained by applying the `reassociation` (which is
1216 /// expected to be valid) to `type`.
1217 /// If `type` is Contiguous MemRefType, this always produce a contiguous
1218 /// MemRefType.
1219 static MemRefType
1220 computeReshapeCollapsedType(MemRefType type,
1221                             ArrayRef<AffineMap> reassociation) {
1222   auto sizes = type.getShape();
1223   AffineExpr offset;
1224   SmallVector<AffineExpr, 4> strides;
1225   auto status = getStridesAndOffset(type, strides, offset);
1226   (void)status;
1227   assert(succeeded(status) && "expected strided memref");
1228 
1229   SmallVector<int64_t, 4> newSizes;
1230   newSizes.reserve(reassociation.size());
1231   SmallVector<AffineExpr, 4> newStrides;
1232   newStrides.reserve(reassociation.size());
1233 
1234   // Use the fact that reassociation is valid to simplify the logic: only use
1235   // each map's rank.
1236   assert(isReassociationValid(reassociation) && "invalid reassociation");
1237   unsigned currentDim = 0;
1238   for (AffineMap m : reassociation) {
1239     unsigned dim = m.getNumResults();
1240     int64_t size = 1;
1241     AffineExpr stride = strides[currentDim + dim - 1];
1242     if (!isReshapableDimBand(currentDim, dim, sizes, strides)) {
1243       size = ShapedType::kDynamicSize;
1244       stride = AffineExpr();
1245     } else {
1246       for (unsigned d = 0; d < dim; ++d)
1247         size *= sizes[currentDim + d];
1248     }
1249     newSizes.push_back(size);
1250     newStrides.push_back(stride);
1251     currentDim += dim;
1252   }
1253 
1254   // Early-exit: if `type` is contiguous, the result must be contiguous.
1255   if (canonicalizeStridedLayout(type).getAffineMaps().empty())
1256     return MemRefType::Builder(type).setShape(newSizes).setAffineMaps({});
1257 
1258   // Convert back to int64_t because we don't have enough information to create
1259   // new strided layouts from AffineExpr only. This corresponds to a case where
1260   // copies may be necessary.
1261   int64_t intOffset = ShapedType::kDynamicStrideOrOffset;
1262   if (auto o = offset.dyn_cast<AffineConstantExpr>())
1263     intOffset = o.getValue();
1264   SmallVector<int64_t, 4> intStrides;
1265   intStrides.reserve(strides.size());
1266   for (auto stride : newStrides) {
1267     if (auto cst = stride.dyn_cast_or_null<AffineConstantExpr>())
1268       intStrides.push_back(cst.getValue());
1269     else
1270       intStrides.push_back(ShapedType::kDynamicStrideOrOffset);
1271   }
1272   auto layout =
1273       makeStridedLinearLayoutMap(intStrides, intOffset, type.getContext());
1274   return canonicalizeStridedLayout(
1275       MemRefType::Builder(type).setShape(newSizes).setAffineMaps({layout}));
1276 }
1277 
1278 /// Helper functions assert Attribute of the proper type in attr and returns the
1279 /// corresponding vector.
1280 /// TODO: this should be evolved into a generic
1281 /// `getRangeOfType<AffineMap>(ArrayAttr attrs)` that does not copy.
1282 static SmallVector<AffineMap, 4> getAffineMaps(ArrayAttr attrs) {
1283   return llvm::to_vector<8>(llvm::map_range(
1284       attrs, [](Attribute a) { return a.cast<AffineMapAttr>().getValue(); }));
1285 }
1286 
1287 template <typename AffineExprTy>
1288 unsigned getMaxPosOfType(ArrayRef<ReassociationExprs> exprArrays) {
1289   unsigned pos = 0;
1290   for (const auto &exprs : exprArrays) {
1291     for (auto expr : exprs) {
1292       expr.walk([&pos](AffineExpr e) {
1293         if (auto d = e.dyn_cast<AffineExprTy>())
1294           pos = std::max(pos, d.getPosition());
1295       });
1296     }
1297   }
1298   return pos;
1299 }
1300 
1301 static SmallVector<AffineMap, 4>
1302 getSymbolLessAffineMaps(ArrayRef<ReassociationExprs> reassociation) {
1303   unsigned maxDim = getMaxPosOfType<AffineDimExpr>(reassociation);
1304   assert(getMaxPosOfType<AffineSymbolExpr>(reassociation) == 0 &&
1305          "Expected symbol-less expressions");
1306   SmallVector<AffineMap, 4> maps;
1307   maps.reserve(reassociation.size());
1308   for (const auto &exprs : reassociation) {
1309     assert(!exprs.empty());
1310     maps.push_back(AffineMap::get(maxDim + 1, 0, exprs, exprs[0].getContext()));
1311   }
1312   return maps;
1313 }
1314 
1315 static SmallVector<SmallVector<AffineExpr, 2>, 2>
1316 convertReassociationIndicesToMaps(
1317     OpBuilder &b, ArrayRef<ReassociationIndices> reassociationIndices) {
1318   SmallVector<SmallVector<AffineExpr, 2>, 2> reassociationMaps;
1319   for (const auto &indices : reassociationIndices) {
1320     SmallVector<AffineExpr, 2> reassociationMap;
1321     reassociationMap.reserve(indices.size());
1322     for (int64_t index : indices)
1323       reassociationMap.push_back(b.getAffineDimExpr(index));
1324     reassociationMaps.push_back(std::move(reassociationMap));
1325   }
1326   return reassociationMaps;
1327 }
1328 
1329 /// For reshape op compute the shape at dimension `dimIndex` of the output in
1330 /// terms of shape of the `src`, when the reshape op is a collapsing
1331 /// operation. It is the product of the shape of the collapsed dimensions of the
1332 /// `src`.
1333 static OpFoldResult
1334 getCollapsedOutputDimFromInputShape(OpBuilder &builder, Location loc,
1335                                     int64_t dimIndex, Value src,
1336                                     ArrayRef<AffineMap> reassociationMap) {
1337   AffineMap map = reassociationMap[dimIndex];
1338   unsigned startPos =
1339       map.getResults().front().cast<AffineDimExpr>().getPosition();
1340   unsigned endPos = map.getResults().back().cast<AffineDimExpr>().getPosition();
1341   AffineExpr expr;
1342   SmallVector<Value, 2> dynamicDims;
1343   for (auto dim : llvm::seq(startPos, endPos + 1)) {
1344     dynamicDims.push_back(builder.createOrFold<memref::DimOp>(loc, src, dim));
1345     AffineExpr currExpr = builder.getAffineSymbolExpr(dim - startPos);
1346     expr = (expr ? expr * currExpr : currExpr);
1347   }
1348   return applyMapToValues(builder, loc,
1349                           AffineMap::get(0, endPos - startPos + 1, expr),
1350                           dynamicDims)[0];
1351 }
1352 
1353 /// Given the `src` of a collapsing reshape op and its reassociation maps,
1354 /// compute the shape of the result of the reshape.
1355 static SmallVector<OpFoldResult, 4> getCollapsedOutputShapeFromInputShape(
1356     OpBuilder &builder, Location loc, Value src,
1357     ArrayRef<int64_t> dstStaticShape, ArrayRef<AffineMap> reassociation) {
1358   return llvm::to_vector<4>(llvm::map_range(
1359       llvm::seq<int64_t>(0, dstStaticShape.size()), [&](int64_t dim) {
1360         return getCollapsedOutputDimFromInputShape(builder, loc, dim, src,
1361                                                    reassociation);
1362       }));
1363 }
1364 
1365 /// Compute a map that for a given dimension of the expanded type gives the
1366 /// dimension in the collapsed type it maps to. Essentially its the inverse of
1367 /// the `reassocation` maps.
1368 static llvm::DenseMap<int64_t, int64_t>
1369 getExpandedDimToCollapsedDimMap(ArrayRef<AffineMap> reassociation) {
1370   llvm::DenseMap<int64_t, int64_t> expandedDimToCollapsedDim;
1371   for (auto map : enumerate(reassociation)) {
1372     unsigned startPos =
1373         map.value().getResults().front().cast<AffineDimExpr>().getPosition();
1374     unsigned endPos =
1375         map.value().getResults().back().cast<AffineDimExpr>().getPosition();
1376     for (auto dim : llvm::seq(startPos, endPos + 1)) {
1377       expandedDimToCollapsedDim[dim] = map.index();
1378     }
1379   }
1380   return expandedDimToCollapsedDim;
1381 }
1382 
1383 /// For an expanding reshape op, compute the value for a dimension of the output
1384 /// from the shape of the input.
1385 static OpFoldResult getExpandedOutputDimFromInputShape(
1386     OpBuilder &builder, Location loc, int64_t dimIndex, Value src,
1387     ArrayRef<int64_t> dstStaticShape, ArrayRef<AffineMap> reassociation,
1388     llvm::DenseMap<int64_t, int64_t> &expandedDimToCollapsedDim) {
1389   if (!ShapedType::isDynamic(dstStaticShape[dimIndex])) {
1390     return builder.getI64IntegerAttr(dstStaticShape[dimIndex]);
1391   }
1392   unsigned sourceDimPos = expandedDimToCollapsedDim[dimIndex];
1393   unsigned startPos = reassociation[sourceDimPos]
1394                           .getResults()
1395                           .front()
1396                           .cast<AffineDimExpr>()
1397                           .getPosition();
1398   unsigned endPos = reassociation[sourceDimPos]
1399                         .getResults()
1400                         .back()
1401                         .cast<AffineDimExpr>()
1402                         .getPosition();
1403   int64_t linearizedStaticDim = 1;
1404   for (auto d :
1405        llvm::enumerate(dstStaticShape.slice(startPos, endPos - startPos + 1))) {
1406     if (d.index() + startPos == static_cast<unsigned>(dimIndex))
1407       continue;
1408     assert(!ShapedType::isDynamic(d.value()) &&
1409            "single dimension cannot be expanded into multiple dynamic "
1410            "dimensions");
1411     linearizedStaticDim *= d.value();
1412   }
1413   Value sourceDim = builder.create<memref::DimOp>(loc, src, sourceDimPos);
1414   return applyMapToValues(
1415       builder, loc,
1416       AffineMap::get(
1417           0, 1, builder.getAffineSymbolExpr(0).floorDiv(linearizedStaticDim)),
1418       sourceDim)[0];
1419 }
1420 
1421 /// Given the `src` of an expanding reshape op, the reassociation maps and the
1422 /// result type, compute the shape of the result of the reshape.
1423 static SmallVector<OpFoldResult, 4> getExpandedOutputShapeFromInputShape(
1424     OpBuilder &builder, Location loc, Value src,
1425     ArrayRef<int64_t> dstStaticShape, ArrayRef<AffineMap> reassociation) {
1426   llvm::DenseMap<int64_t, int64_t> expandedDimToCollapsedDim =
1427       getExpandedDimToCollapsedDimMap(reassociation);
1428   return llvm::to_vector<4>(llvm::map_range(
1429       llvm::seq<int64_t>(0, dstStaticShape.size()), [&](int64_t dim) {
1430         return getExpandedOutputDimFromInputShape(builder, loc, dim, src,
1431                                                   dstStaticShape, reassociation,
1432                                                   expandedDimToCollapsedDim);
1433       }));
1434 }
1435 
1436 static SmallVector<OpFoldResult, 4>
1437 getReshapeOutputShapeFromInputShape(OpBuilder &builder, Location loc, Value src,
1438                                     ArrayRef<int64_t> dstStaticShape,
1439                                     ArrayRef<AffineMap> reassocation) {
1440   return dstStaticShape.size() >
1441                  static_cast<size_t>(src.getType().cast<ShapedType>().getRank())
1442              ? getExpandedOutputShapeFromInputShape(
1443                    builder, loc, src, dstStaticShape, reassocation)
1444              : getCollapsedOutputShapeFromInputShape(
1445                    builder, loc, src, dstStaticShape, reassocation);
1446 }
1447 
1448 void mlir::linalg::ReshapeOp::build(OpBuilder &b, OperationState &result,
1449                                     Value src,
1450                                     ArrayRef<ReassociationExprs> reassociation,
1451                                     ArrayRef<NamedAttribute> attrs) {
1452   auto maps = getSymbolLessAffineMaps(reassociation);
1453   auto memRefType = src.getType().cast<MemRefType>();
1454   auto resultType = computeReshapeCollapsedType(memRefType, maps);
1455   build(b, result, resultType, src, attrs);
1456   result.addAttribute(ReshapeOp::getReassociationAttrName(),
1457                       b.getAffineMapArrayAttr(maps));
1458 }
1459 
1460 void mlir::linalg::ReshapeOp::build(OpBuilder &b, OperationState &result,
1461                                     Type resultType, Value src,
1462                                     ArrayRef<ReassociationExprs> reassociation,
1463                                     ArrayRef<NamedAttribute> attrs) {
1464   auto maps = getSymbolLessAffineMaps(reassociation);
1465   build(b, result, resultType, src, attrs);
1466   result.addAttribute(ReshapeOp::getReassociationAttrName(),
1467                       b.getAffineMapArrayAttr(maps));
1468 }
1469 
1470 Value mlir::linalg::ReshapeOp::getViewSource() { return src(); }
1471 
1472 /// Verify that shapes of the reshaped types using following rules
1473 /// 1) if a dimension in the collapsed type is static, then the corresponding
1474 ///    dimensions in the expanded shape should be
1475 ///    a) static
1476 ///    b) the product should be same as the collaped shape.
1477 /// 2) if a dimension in the collaped type is dynamic, one and only one of the
1478 ///    corresponding dimensions in the expanded type should be dynamic. This
1479 ///    rule is only needed with reshape operations that are expanding.
1480 template <typename OpTy>
1481 static LogicalResult verifyReshapeLikeShapes(OpTy op, ShapedType collapsedType,
1482                                              ShapedType expandedType,
1483                                              bool isExpandingReshape) {
1484   ArrayRef<int64_t> collapsedShape = collapsedType.getShape();
1485   ArrayRef<int64_t> expandedShape = expandedType.getShape();
1486   unsigned expandedDimStart = 0;
1487   for (auto map : llvm::enumerate(op.getReassociationMaps())) {
1488     Optional<int64_t> dynamicShape;
1489     int64_t linearizedStaticShape = 1;
1490     for (auto dim : llvm::enumerate(expandedShape.slice(
1491              expandedDimStart, map.value().getNumResults()))) {
1492       if (ShapedType::isDynamic(dim.value())) {
1493         if (isExpandingReshape && dynamicShape) {
1494           return op->emitOpError("invalid to have a single dimension (")
1495                  << map.index() << ") expanded into multiple dynamic dims ("
1496                  << expandedDimStart + dynamicShape.getValue() << ","
1497                  << expandedDimStart + dim.index() << ")";
1498         }
1499         dynamicShape = dim.index();
1500       } else {
1501         linearizedStaticShape *= dim.value();
1502       }
1503     }
1504     if (dynamicShape) {
1505       if (!ShapedType::isDynamic(collapsedShape[map.index()])) {
1506         return op->emitOpError("expected dimension ")
1507                << map.index()
1508                << " of collapsed type to be dynamic since one or more of the "
1509                   "corresponding dimensions in the expanded type is dynamic";
1510       }
1511     } else {
1512       if (collapsedShape[map.index()] != linearizedStaticShape) {
1513         return op->emitOpError("expected dimension ")
1514                << map.index() << " of collapsed type to be static value of "
1515                << linearizedStaticShape << " ";
1516       }
1517     }
1518     expandedDimStart += map.value().getNumResults();
1519   }
1520   return success();
1521 }
1522 
1523 // Common verifier for reshape-like types. Fills `expandedType` and
1524 // `collapsedType` with the proper `src` or `result` type.
1525 template <typename Op, typename T>
1526 static LogicalResult verifyReshapeLikeTypes(Op op, T &expandedType,
1527                                             T &collapsedType) {
1528   expandedType = op.getSrcType();
1529   collapsedType = op.getResultType();
1530   unsigned expandedRank = expandedType.getRank();
1531   unsigned collapsedRank = collapsedType.getRank();
1532   bool isCollapse = expandedRank > collapsedRank;
1533   if (!isCollapse) {
1534     std::swap(expandedRank, collapsedRank);
1535     std::swap(expandedType, collapsedType);
1536   }
1537   if (expandedRank == 0)
1538     return op.emitOpError("expected non-zero memref ranks");
1539   if (expandedRank == collapsedRank)
1540     return op.emitOpError("expected to collapse or expand dims");
1541 
1542   if (collapsedRank == 0) {
1543     // If collapsed rank is 0, then expanded type must be static shaped and of
1544     // sizes 1.
1545     if (llvm::any_of(expandedType.getShape(),
1546                      [](int64_t dim) -> bool { return dim != 1; }))
1547       return op.emitOpError(
1548           "invalid to reshape tensor/memref with non-unit extent dimensions to "
1549           "zero-rank tensor/memref");
1550     return success();
1551   }
1552   if (collapsedRank != op.reassociation().size())
1553     return op.emitOpError("expected rank of the collapsed type(")
1554            << collapsedRank << ") to be the number of reassociation maps("
1555            << op.reassociation().size() << ")";
1556   auto maps = getAffineMaps(op.reassociation());
1557   for (auto it : llvm::enumerate(maps))
1558     if (it.value().getNumDims() != expandedRank)
1559       return op.emitOpError("expected reassociation map #")
1560              << it.index() << " of same rank as expanded memref("
1561              << expandedRank << "), but got " << it.value().getNumDims();
1562   int invalidIdx = 0;
1563   if (!isReassociationValid(maps, &invalidIdx))
1564     return op.emitOpError("expected reassociation map #")
1565            << invalidIdx << " to be valid and contiguous";
1566   return verifyReshapeLikeShapes(op, collapsedType, expandedType, !isCollapse);
1567 }
1568 
1569 static LogicalResult verify(ReshapeOp op) {
1570   MemRefType expandedType, collapsedType;
1571   if (failed(verifyReshapeLikeTypes(op, expandedType, collapsedType)))
1572     return failure();
1573   auto maps = getAffineMaps(op.reassociation());
1574   MemRefType expectedType = computeReshapeCollapsedType(expandedType, maps);
1575   if (collapsedType != expectedType)
1576     return op.emitOpError("expected collapsed type to be ")
1577            << expectedType << ", but got " << collapsedType;
1578   return success();
1579 }
1580 
1581 void ReshapeOp::getCanonicalizationPatterns(RewritePatternSet &results,
1582                                             MLIRContext *context) {
1583   results.add<CollapseReshapeOps<ReshapeOp>>(context);
1584 }
1585 
1586 //===----------------------------------------------------------------------===//
1587 // TensorReshapeOp
1588 //===----------------------------------------------------------------------===//
1589 
1590 /// Compute the RankedTensorType obtained by applying `reassociation` to `type`.
1591 static RankedTensorType
1592 computeTensorReshapeCollapsedType(RankedTensorType type,
1593                                   ArrayRef<AffineMap> reassociation) {
1594   auto shape = type.getShape();
1595   SmallVector<int64_t, 4> newShape;
1596   newShape.reserve(reassociation.size());
1597 
1598   // Use the fact that reassociation is valid to simplify the logic: only use
1599   // each map's rank.
1600   assert(isReassociationValid(reassociation) && "invalid reassociation");
1601   unsigned currentDim = 0;
1602   for (AffineMap m : reassociation) {
1603     unsigned dim = m.getNumResults();
1604     auto band = shape.slice(currentDim, dim);
1605     int64_t size = 1;
1606     if (llvm::is_contained(band, ShapedType::kDynamicSize))
1607       size = ShapedType::kDynamicSize;
1608     else
1609       for (unsigned d = 0; d < dim; ++d)
1610         size *= shape[currentDim + d];
1611     newShape.push_back(size);
1612     currentDim += dim;
1613   }
1614 
1615   return RankedTensorType::get(newShape, type.getElementType());
1616 }
1617 
1618 void mlir::linalg::TensorReshapeOp::build(
1619     OpBuilder &b, OperationState &result, Value src,
1620     ArrayRef<ReassociationExprs> reassociation,
1621     ArrayRef<NamedAttribute> attrs) {
1622   auto maps = getSymbolLessAffineMaps(reassociation);
1623   auto resultType = computeTensorReshapeCollapsedType(
1624       src.getType().cast<RankedTensorType>(), maps);
1625   build(b, result, resultType, src, attrs);
1626   result.addAttribute(TensorReshapeOp::getReassociationAttrName(),
1627                       b.getAffineMapArrayAttr(maps));
1628 }
1629 
1630 void mlir::linalg::TensorReshapeOp::build(
1631     OpBuilder &b, OperationState &result, Type resultType, Value src,
1632     ArrayRef<ReassociationExprs> reassociation,
1633     ArrayRef<NamedAttribute> attrs) {
1634   auto maps = getSymbolLessAffineMaps(reassociation);
1635   build(b, result, resultType, src, attrs);
1636   result.addAttribute(TensorReshapeOp::getReassociationAttrName(),
1637                       b.getAffineMapArrayAttr(maps));
1638 }
1639 
1640 static LogicalResult verify(TensorReshapeOp op) {
1641   RankedTensorType expandedType, collapsedType;
1642   if (failed(verifyReshapeLikeTypes(op, expandedType, collapsedType)))
1643     return failure();
1644   auto maps = getAffineMaps(op.reassociation());
1645   RankedTensorType expectedType =
1646       computeTensorReshapeCollapsedType(expandedType, maps);
1647   if (collapsedType != expectedType)
1648     return op.emitOpError("expected collapsed type to be ")
1649            << expectedType << ", but got " << collapsedType;
1650   return success();
1651 }
1652 
1653 namespace {
1654 /// Reshape of a splat constant can be replaced with a constant of the result
1655 /// type.
1656 struct FoldReshapeWithConstant : OpRewritePattern<TensorReshapeOp> {
1657   using OpRewritePattern<TensorReshapeOp>::OpRewritePattern;
1658   LogicalResult matchAndRewrite(TensorReshapeOp reshapeOp,
1659                                 PatternRewriter &rewriter) const override {
1660     DenseElementsAttr attr;
1661     if (!matchPattern(reshapeOp.src(), m_Constant(&attr)))
1662       return failure();
1663     if (!attr || !attr.isSplat())
1664       return failure();
1665     DenseElementsAttr newAttr = DenseElementsAttr::getFromRawBuffer(
1666         reshapeOp.getResultType(), attr.getRawData(), true);
1667     rewriter.replaceOpWithNewOp<ConstantOp>(reshapeOp, newAttr);
1668     return success();
1669   }
1670 };
1671 
1672 /// Fold linalg.fill -> linalg.tensor_reshape chain.
1673 ///
1674 /// For such op chains, we can create new linalg.fill ops with the result
1675 /// type of the linalg.tensor_reshape op.
1676 struct FoldFillWithTensorReshape : OpRewritePattern<TensorReshapeOp> {
1677   using OpRewritePattern<TensorReshapeOp>::OpRewritePattern;
1678   LogicalResult matchAndRewrite(TensorReshapeOp reshapeOp,
1679                                 PatternRewriter &rewriter) const override {
1680     auto oldFill = reshapeOp.src().getDefiningOp<FillOp>();
1681     if (!oldFill)
1682       return failure();
1683 
1684     Location loc = oldFill.getLoc();
1685     auto newInit = rewriter.create<TensorReshapeOp>(
1686         loc, reshapeOp.getResultType(), oldFill.output(),
1687         reshapeOp.reassociation());
1688     rewriter.replaceOpWithNewOp<FillOp>(reshapeOp, newInit, oldFill.value());
1689 
1690     return success();
1691   }
1692 };
1693 } // namespace
1694 
1695 void TensorReshapeOp::getCanonicalizationPatterns(RewritePatternSet &results,
1696                                                   MLIRContext *context) {
1697   results.add<CollapseReshapeOps<TensorReshapeOp>, FoldFillWithTensorReshape,
1698               FoldInitTensorWithTensorReshapeOp, FoldReshapeWithConstant>(
1699       context);
1700 }
1701 
1702 LogicalResult TensorReshapeOp::reifyReturnTypeShapesPerResultDim(
1703     OpBuilder &b, SmallVectorImpl<SmallVector<Value>> &reifiedReturnShapes) {
1704   auto resultShape =
1705       getAsValues(b, getLoc(),
1706                   getReshapeOutputShapeFromInputShape(
1707                       b, getLoc(), src(), getResultType().getShape(),
1708                       getReassociationMaps()));
1709   reifiedReturnShapes.emplace_back(std::move(resultShape));
1710   return success();
1711 }
1712 
1713 //===----------------------------------------------------------------------===//
1714 // YieldOp
1715 //===----------------------------------------------------------------------===//
1716 
1717 static void print(OpAsmPrinter &p, linalg::YieldOp op) {
1718   p << op.getOperationName();
1719   if (op.getNumOperands() > 0)
1720     p << ' ' << op.getOperands();
1721   p.printOptionalAttrDict(op->getAttrs());
1722   if (op.getNumOperands() > 0)
1723     p << " : " << op.getOperandTypes();
1724 }
1725 
1726 static ParseResult parseYieldOp(OpAsmParser &parser, OperationState &result) {
1727   SmallVector<OpAsmParser::OperandType, 2> opInfo;
1728   SmallVector<Type, 2> types;
1729   llvm::SMLoc loc = parser.getCurrentLocation();
1730   return failure(parser.parseOperandList(opInfo) ||
1731                  parser.parseOptionalAttrDict(result.attributes) ||
1732                  (!opInfo.empty() && parser.parseColonTypeList(types)) ||
1733                  parser.resolveOperands(opInfo, types, loc, result.operands));
1734 }
1735 
1736 // Check the operand number and types must match the element types of the
1737 // LinalgOp interface's shaped operands.
1738 static LogicalResult verifyYield(linalg::YieldOp op,
1739                                  LinalgOp linalgOpInterface) {
1740   auto nOutputs = linalgOpInterface.getNumOutputs();
1741   if (op.getNumOperands() != nOutputs)
1742     return op.emitOpError("expected number of yield values (")
1743            << nOutputs << ") to match the number of operands of the enclosing "
1744            << "LinalgOp (" << op.getNumOperands() << ")";
1745 
1746   for (unsigned i = 0; i != nOutputs; ++i) {
1747     auto elementType =
1748         linalgOpInterface.getOutputShapedType(i).getElementType();
1749     if (op.getOperand(i).getType() != elementType)
1750       return op.emitOpError("type of yield operand ")
1751              << (i + 1) << " (" << op.getOperand(i).getType()
1752              << ") doesn't match "
1753              << "the element type of the enclosing linalg.generic op ("
1754              << elementType << ")";
1755   }
1756   return success();
1757 }
1758 
1759 static LogicalResult verify(linalg::YieldOp op) {
1760   auto *parentOp = op->getParentOp();
1761   if (parentOp->getNumRegions() != 1 || parentOp->getRegion(0).empty())
1762     return op.emitOpError("expected single non-empty parent region");
1763 
1764   if (auto linalgOp = dyn_cast<LinalgOp>(parentOp))
1765     return verifyYield(op, cast<LinalgOp>(parentOp));
1766 
1767   if (auto padTensorOp = dyn_cast<linalg::PadTensorOp>(parentOp)) {
1768     if (op.getNumOperands() != 1)
1769       return op.emitOpError("expected single yield operand (got ")
1770              << op->getNumOperands() << ")";
1771     if (op.getOperand(0).getType() !=
1772         padTensorOp.getType().cast<ShapedType>().getElementType())
1773       return op.emitOpError("expected yield type to match shape element type");
1774     return success();
1775   }
1776 
1777   if (auto tiledLoopOp = dyn_cast<linalg::TiledLoopOp>(parentOp)) {
1778     return success();
1779   }
1780   return op.emitOpError("expected parent op with LinalgOp interface");
1781 }
1782 
1783 //===----------------------------------------------------------------------===//
1784 // TiledLoopOp
1785 //===----------------------------------------------------------------------===//
1786 
1787 void TiledLoopOp::build(
1788     OpBuilder &builder, OperationState &result, ValueRange lowerBounds,
1789     ValueRange upperBounds, ValueRange steps, ValueRange inputs,
1790     ValueRange outputs, ArrayAttr iteratorTypes,
1791     function_ref<void(OpBuilder &, Location, ValueRange)> bodyBuilderFn) {
1792   result.addOperands(lowerBounds);
1793   result.addOperands(upperBounds);
1794   result.addOperands(steps);
1795   result.addOperands(inputs);
1796   result.addOperands(outputs);
1797   result.addAttribute(
1798       TiledLoopOp::getOperandSegmentSizeAttr(),
1799       builder.getI32VectorAttr({static_cast<int32_t>(lowerBounds.size()),
1800                                 static_cast<int32_t>(upperBounds.size()),
1801                                 static_cast<int32_t>(steps.size()),
1802                                 static_cast<int32_t>(inputs.size()),
1803                                 static_cast<int32_t>(outputs.size())}));
1804   result.addAttribute(getIteratorTypesAttrName(), iteratorTypes);
1805 
1806   // Add output types for `RankedTensorType` output arguments.
1807   for (Value output : outputs) {
1808     Type outputType = output.getType();
1809     if (outputType.isa<RankedTensorType>())
1810       result.addTypes(outputType);
1811   }
1812 
1813   OpBuilder::InsertionGuard guard(builder);
1814   unsigned numIVs = steps.size();
1815   SmallVector<Type, 8> argTypes(numIVs, builder.getIndexType());
1816   Region *bodyRegion = result.addRegion();
1817   Block *bodyBlock = builder.createBlock(bodyRegion, {}, argTypes);
1818 
1819   if (bodyBuilderFn) {
1820     builder.setInsertionPointToStart(bodyBlock);
1821     bodyBuilderFn(builder, result.location, bodyBlock->getArguments());
1822     TiledLoopOp::ensureTerminator(*bodyRegion, builder, result.location);
1823   }
1824 }
1825 
1826 static void print(OpAsmPrinter &p, TiledLoopOp op) {
1827   p << op.getOperationName() << " (" << op.getBody()->getArguments() << ") = ("
1828     << op.lowerBound() << ") to (" << op.upperBound() << ") step (" << op.step()
1829     << ")";
1830 
1831   if (!op.inputs().empty())
1832     p << " ins (" << op.inputs() << ": " << TypeRange(op.inputs()) << ")";
1833   if (!op.outputs().empty())
1834     p << " outs (" << op.outputs() << ":" << TypeRange(op.outputs()) << ")";
1835 
1836   if (llvm::any_of(op.iterator_types(), [](Attribute attr) {
1837         return attr.cast<StringAttr>().getValue() !=
1838                getParallelIteratorTypeName();
1839       })) {
1840     p << " iterators" << op.iterator_types() << "";
1841   }
1842 
1843   p.printRegion(op.region(), /*printEntryBlockArgs=*/false);
1844   p.printOptionalAttrDict(
1845       op->getAttrs(), /*elidedAttrs=*/{TiledLoopOp::getOperandSegmentSizeAttr(),
1846                                        getIteratorTypesAttrName()});
1847 }
1848 
1849 static ParseResult parseTiledLoopOp(OpAsmParser &parser,
1850                                     OperationState &result) {
1851   auto &builder = parser.getBuilder();
1852   // Parse an opening `(` followed by induction variables followed by `)`
1853   SmallVector<OpAsmParser::OperandType, 4> ivs;
1854   if (parser.parseRegionArgumentList(ivs, /*requiredOperandCount=*/-1,
1855                                      OpAsmParser::Delimiter::Paren))
1856     return failure();
1857 
1858   // Parse loop bounds.
1859   SmallVector<OpAsmParser::OperandType, 4> lower;
1860   if (parser.parseEqual() ||
1861       parser.parseOperandList(lower, ivs.size(),
1862                               OpAsmParser::Delimiter::Paren) ||
1863       parser.resolveOperands(lower, builder.getIndexType(), result.operands))
1864     return failure();
1865 
1866   SmallVector<OpAsmParser::OperandType, 4> upper;
1867   if (parser.parseKeyword("to") ||
1868       parser.parseOperandList(upper, ivs.size(),
1869                               OpAsmParser::Delimiter::Paren) ||
1870       parser.resolveOperands(upper, builder.getIndexType(), result.operands))
1871     return failure();
1872 
1873   // Parse step values.
1874   SmallVector<OpAsmParser::OperandType, 4> steps;
1875   if (parser.parseKeyword("step") ||
1876       parser.parseOperandList(steps, ivs.size(),
1877                               OpAsmParser::Delimiter::Paren) ||
1878       parser.resolveOperands(steps, builder.getIndexType(), result.operands))
1879     return failure();
1880 
1881   // Parse input tensors.
1882   SmallVector<OpAsmParser::OperandType, 4> inputs;
1883   if (succeeded(parser.parseOptionalKeyword("ins"))) {
1884     SmallVector<Type, 4> inputTypes;
1885     llvm::SMLoc inputsOperandsLoc = parser.getCurrentLocation();
1886 
1887     if (parser.parseLParen() || parser.parseOperandList(inputs) ||
1888         parser.parseColonTypeList(inputTypes) || parser.parseRParen())
1889       return failure();
1890 
1891     if (parser.resolveOperands(inputs, inputTypes, inputsOperandsLoc,
1892                                result.operands))
1893       return failure();
1894   }
1895 
1896   // Parse output tensors.
1897   SmallVector<OpAsmParser::OperandType, 4> outputs;
1898   if (succeeded(parser.parseOptionalKeyword("outs"))) {
1899     SmallVector<Type, 4> outputTypes;
1900     llvm::SMLoc outputsOperandsLoc = parser.getCurrentLocation();
1901 
1902     if (parser.parseLParen() || parser.parseOperandList(outputs) ||
1903         parser.parseColonTypeList(outputTypes) || parser.parseRParen())
1904       return failure();
1905 
1906     if (parser.resolveOperands(outputs, outputTypes, outputsOperandsLoc,
1907                                result.operands))
1908       return failure();
1909     for (Type outputType : outputTypes)
1910       if (outputType.isa<RankedTensorType>())
1911         result.addTypes(outputType);
1912   }
1913 
1914   // Parse attributes.
1915   SmallVector<Attribute, 4> iterTypes;
1916   if (succeeded(parser.parseOptionalKeyword("iterators"))) {
1917     StringAttr iterType;
1918 
1919     if (parser.parseLSquare() || parser.parseAttribute(iterType))
1920       return failure();
1921     iterTypes.push_back(iterType);
1922     for (int i = 1, e = ivs.size(); i < e; ++i) {
1923       if (parser.parseComma() || parser.parseAttribute(iterType))
1924         return failure();
1925       iterTypes.push_back(iterType);
1926     }
1927     if (parser.parseRSquare())
1928       return failure();
1929   } else {
1930     auto parallelIter = builder.getStringAttr(getParallelIteratorTypeName());
1931     iterTypes = SmallVector<Attribute, 4>(ivs.size(), parallelIter);
1932   }
1933   result.addAttribute(getIteratorTypesAttrName(),
1934                       builder.getArrayAttr(iterTypes));
1935   result.addAttribute(
1936       TiledLoopOp::getOperandSegmentSizeAttr(),
1937       builder.getI32VectorAttr({static_cast<int32_t>(lower.size()),
1938                                 static_cast<int32_t>(upper.size()),
1939                                 static_cast<int32_t>(steps.size()),
1940                                 static_cast<int32_t>(inputs.size()),
1941                                 static_cast<int32_t>(outputs.size())}));
1942 
1943   // Parse the body.
1944   Region *body = result.addRegion();
1945   SmallVector<Type, 4> types(ivs.size(), builder.getIndexType());
1946   if (parser.parseRegion(*body, ivs, types))
1947     return failure();
1948 
1949   // Parse optional attributes.
1950   parser.parseOptionalAttrDict(result.attributes);
1951 
1952   return success();
1953 }
1954 
1955 Region &TiledLoopOp::getLoopBody() { return region(); }
1956 
1957 LogicalResult TiledLoopOp::moveOutOfLoop(ArrayRef<Operation *> ops) {
1958   for (auto *op : ops)
1959     op->moveBefore(*this);
1960   return success();
1961 }
1962 
1963 bool TiledLoopOp::isDefinedOutsideOfLoop(Value value) {
1964   return !region().isAncestor(value.getParentRegion());
1965 }
1966 
1967 static LogicalResult verify(TiledLoopOp op) { return success(); }
1968 
1969 namespace {
1970 
1971 // Folds away TiledLoopOp output tensors when the following conditions are met:
1972 // * result of `linalg.tiled_loop` has no uses
1973 // * output tensor is the argument of `linalg.yield`
1974 //
1975 // Example:
1976 //
1977 // %0 = linalg.tiled_loop ...  outs (%out, %out_buf:tensor<...>, memref<...>) {
1978 //   ...
1979 //   linalg.yield %out : tensor ...
1980 // }
1981 //
1982 // Becomes
1983 //
1984 // linalg.tiled_loop ...  outs (%out_buf:memref<...>) {
1985 //   ...
1986 //   linalg.yield
1987 // }
1988 struct TiledLoopResultsFolder : public OpRewritePattern<linalg::TiledLoopOp> {
1989   using OpRewritePattern<linalg::TiledLoopOp>::OpRewritePattern;
1990 
1991   LogicalResult matchAndRewrite(linalg::TiledLoopOp tiledLoop,
1992                                 PatternRewriter &rewriter) const final {
1993     if (tiledLoop.getNumResults() == 0)
1994       return failure();
1995 
1996     Block *block = tiledLoop.getBody();
1997     auto yieldOp = cast<linalg::YieldOp>(block->getTerminator());
1998 
1999     // Match the pattern and collect output buffers that will replace the output
2000     // tensors and also the ops that will be ignored when cloning the body.
2001     SmallVector<Value, 2> newOutputOperands, newYieldArgs;
2002     int resultId = 0;
2003     for (Value out : tiledLoop.outputs()) {
2004       if (!out.getType().isa<RankedTensorType>()) {
2005         newOutputOperands.push_back(out);
2006         continue;
2007       }
2008       Value result = tiledLoop.getResult(resultId);
2009       Value yieldArg = yieldOp.getOperand(resultId);
2010       if (yieldArg != out || !result.use_empty()) {
2011         newOutputOperands.push_back(out);
2012         newYieldArgs.push_back(yieldArg);
2013       }
2014       ++resultId;
2015     }
2016     if (newOutputOperands.size() == tiledLoop.outputs().size())
2017       return failure();
2018 
2019     Location loc = tiledLoop.getLoc();
2020     auto newTiledLoop = rewriter.create<TiledLoopOp>(
2021         loc, tiledLoop.lowerBound(), tiledLoop.upperBound(), tiledLoop.step(),
2022         tiledLoop.inputs(), newOutputOperands, tiledLoop.iterator_types());
2023 
2024     // Clone the region ignoring the def-chain for linalg.yield args:
2025     // unnecessary `subtensor_insert`, `tensor_load` and `cast` ops.
2026     BlockAndValueMapping bvm;
2027     bvm.map(tiledLoop.getInductionVars(), newTiledLoop.getInductionVars());
2028     OpBuilder innerBuilder =
2029         OpBuilder::atBlockEnd(newTiledLoop.getBody(), rewriter.getListener());
2030     for (auto &op : tiledLoop.getBody()->without_terminator())
2031       innerBuilder.clone(op, bvm);
2032     innerBuilder.create<linalg::YieldOp>(loc, newYieldArgs);
2033     rewriter.eraseOp(tiledLoop);
2034 
2035     return success();
2036   }
2037 };
2038 } // namespace
2039 
2040 void TiledLoopOp::getCanonicalizationPatterns(OwningRewritePatternList &results,
2041                                               MLIRContext *context) {
2042   results.insert<TiledLoopResultsFolder>(context);
2043 }
2044 
2045 LogicalResult TiledLoopOp::fold(ArrayRef<Attribute>,
2046                                 SmallVectorImpl<OpFoldResult> &) {
2047   return foldMemRefCast(*this);
2048 }
2049 
2050 /////// Operations corresponding to library calls defined with Tablegen ////////
2051 
2052 template <typename LinalgPoolingOp>
2053 static LogicalResult verifyStrideOrDilation(LinalgPoolingOp op,
2054                                             ArrayRef<Attribute> attrs,
2055                                             bool isStride) {
2056   auto strideOrDilation = isStride ? "stride" : "dilation";
2057   if (attrs.size() != op.getNumWindowLoops())
2058     return op.emitOpError("expects num ")
2059            << strideOrDilation
2060            << "s equal to number of window dimensions: " << attrs.size()
2061            << " vs " << op.getNumWindowLoops();
2062   return success();
2063 }
2064 
2065 void ConvOp::getEffects(
2066     SmallVectorImpl<SideEffects::EffectInstance<MemoryEffects::Effect>>
2067         &effects) {
2068   effects.emplace_back(MemoryEffects::Read::get(), input(),
2069                        SideEffects::DefaultResource::get());
2070   effects.emplace_back(MemoryEffects::Read::get(), filter(),
2071                        SideEffects::DefaultResource::get());
2072   effects.emplace_back(MemoryEffects::Write::get(), output(),
2073                        SideEffects::DefaultResource::get());
2074 }
2075 
2076 static LogicalResult verify(ConvOp op) {
2077   auto oType = op.output().getType().cast<MemRefType>();
2078   auto fType = op.filter().getType().cast<MemRefType>();
2079   auto iType = op.input().getType().cast<MemRefType>();
2080   if (oType.getElementType() != iType.getElementType() ||
2081       oType.getElementType() != fType.getElementType())
2082     return op.emitOpError("expects memref elemental types to match");
2083   if (oType.getRank() != iType.getRank() || oType.getRank() != fType.getRank())
2084     return op.emitOpError("expects memref ranks to match");
2085   if (auto strides = op.strides()) {
2086     if (failed(
2087             verifyStrideOrDilation(op, strides->getValue(), /*isStride=*/true)))
2088       return failure();
2089   }
2090   if (auto dilations = op.dilations()) {
2091     if (failed(verifyStrideOrDilation(op, dilations->getValue(),
2092                                       /*isStride=*/false)))
2093       return failure();
2094   }
2095   return success();
2096 }
2097 
2098 template <typename PoolingOp>
2099 static LogicalResult verifySingleInputPoolingOp(PoolingOp op) {
2100   auto inputType = op.input().getType().template cast<MemRefType>();
2101   auto outputType = op.output().getType().template cast<MemRefType>();
2102   if (outputType.getElementType() != inputType.getElementType())
2103     return op.emitOpError("expects memref elemental types to match");
2104 
2105   auto windowDimsType = op.windowDims().getType().template cast<MemRefType>();
2106   if (outputType.getRank() != inputType.getRank() ||
2107       outputType.getRank() != windowDimsType.getRank())
2108     return op.emitOpError("expects memref ranks to match");
2109 
2110   if (auto strides = op.strides()) {
2111     if (failed(
2112             verifyStrideOrDilation(op, strides->getValue(), /*isStride=*/true)))
2113       return failure();
2114   }
2115   if (auto dilations = op.dilations()) {
2116     if (failed(verifyStrideOrDilation(op, dilations->getValue(),
2117                                       /*isStride=*/false)))
2118       return failure();
2119   }
2120   return success();
2121 }
2122 
2123 #define DEFINE_POOLING_OP_GET_EFFECTS(OP_NAME)                                 \
2124   void OP_NAME::getEffects(                                                    \
2125       SmallVectorImpl<SideEffects::EffectInstance<MemoryEffects::Effect>>      \
2126           &effects) {                                                          \
2127     effects.emplace_back(MemoryEffects::Read::get(), input(),                  \
2128                          SideEffects::DefaultResource::get());                 \
2129     effects.emplace_back(MemoryEffects::Write::get(), output(),                \
2130                          SideEffects::DefaultResource::get());                 \
2131   }
2132 
2133 static LogicalResult verify(PoolingMaxOp op) {
2134   return verifySingleInputPoolingOp(op);
2135 }
2136 static LogicalResult verify(PoolingMinOp op) {
2137   return verifySingleInputPoolingOp(op);
2138 }
2139 static LogicalResult verify(PoolingSumOp op) {
2140   return verifySingleInputPoolingOp(op);
2141 }
2142 
2143 DEFINE_POOLING_OP_GET_EFFECTS(PoolingMaxOp)
2144 DEFINE_POOLING_OP_GET_EFFECTS(PoolingMinOp)
2145 DEFINE_POOLING_OP_GET_EFFECTS(PoolingSumOp)
2146 
2147 namespace {
2148 struct EraseDeadLinalgOp;
2149 struct FoldTensorCastOp;
2150 } // namespace
2151 
2152 #include "mlir/Dialect/Linalg/IR/LinalgNamedStructuredOps.tcgen.cpp.inc"
2153 #include "mlir/Dialect/Linalg/IR/LinalgNamedStructuredOps.yamlgen.cpp.inc"
2154 
2155 #define GET_OP_CLASSES
2156 #include "mlir/Dialect/Linalg/IR/LinalgOps.cpp.inc"
2157 
2158 #define GET_OP_CLASSES
2159 #include "mlir/Dialect/Linalg/IR/LinalgStructuredOps.cpp.inc"
2160 
2161 #define GET_OP_CLASSES
2162 #include "mlir/Dialect/Linalg/IR/LinalgSparseOps.cpp.inc"
2163 
2164 /// Return the dims that are `iteratorTypeName` loops in the LinalgOp `op`.
2165 /// Assumes `op` is a LinalgOp.
2166 void mlir::linalg::getDimsOfType(Operation *op, StringRef iteratorTypeName,
2167                                  SmallVectorImpl<AffineExpr> &res) {
2168   if (!cast<LinalgOp>(op).iterator_types())
2169     return;
2170 
2171   unsigned dim = 0;
2172   MLIRContext *ctx = op->getContext();
2173   for (auto tn :
2174        cast<LinalgOp>(op).iterator_types().getAsValueRange<StringAttr>()) {
2175     if (tn == iteratorTypeName)
2176       res.push_back(getAffineDimExpr(dim, ctx));
2177     ++dim;
2178   }
2179 }
2180 
2181 AffineMap mlir::linalg::extractOrIdentityMap(Optional<AffineMap> maybeMap,
2182                                              unsigned rank,
2183                                              MLIRContext *context) {
2184   if (maybeMap)
2185     return maybeMap.getValue();
2186   if (rank == 0)
2187     return AffineMap::get(context);
2188   return AffineMap::getMultiDimIdentityMap(rank, context);
2189 }
2190 
2191 SmallVector<AffineExpr, 4>
2192 mlir::linalg::makeAffineDimExprs(unsigned num, unsigned &startIdx,
2193                                  MLIRContext *context) {
2194   SmallVector<AffineExpr, 4> res;
2195   res.reserve(num);
2196   for (unsigned i = 0; i < num; ++i)
2197     res.push_back(getAffineDimExpr(startIdx++, context));
2198   return res;
2199 }
2200 
2201 template <typename PoolingOp>
2202 SmallVector<AffineExpr, 4>
2203 mlir::linalg::weightedPoolingInputIndex(PoolingOp op,
2204                                         ArrayRef<AffineExpr> outputDims,
2205                                         ArrayRef<AffineExpr> windowDims) {
2206   assert(outputDims.size() == windowDims.size());
2207   SmallVector<AffineExpr, 4> res;
2208   res.reserve(outputDims.size());
2209   for (unsigned i = 0, e = outputDims.size(); i < e; ++i) {
2210     // TODO: add a level of indirection to linalg.generic.
2211     auto expr = op.getStride(i) * outputDims[i] +
2212                 op.getDilation(i) * windowDims[i] - op.getLowPad(i);
2213     res.push_back(expr);
2214   }
2215   return res;
2216 }
2217 
2218 #define INSTANTIATE_WEIGHTED_POOLING_INPUT_INDEX(OP_TYPE)                      \
2219   template SmallVector<AffineExpr, 4>                                          \
2220   mlir::linalg::weightedPoolingInputIndex<OP_TYPE>(                            \
2221       OP_TYPE op, ArrayRef<AffineExpr> outputDims,                             \
2222       ArrayRef<AffineExpr> windowDims);
2223 
2224 INSTANTIATE_WEIGHTED_POOLING_INPUT_INDEX(ConvOp)
2225 INSTANTIATE_WEIGHTED_POOLING_INPUT_INDEX(PoolingMaxOp)
2226 INSTANTIATE_WEIGHTED_POOLING_INPUT_INDEX(PoolingMinOp)
2227 INSTANTIATE_WEIGHTED_POOLING_INPUT_INDEX(PoolingSumOp)
2228 
2229 SmallVector<AffineExpr, 4> mlir::linalg::concat(ArrayRef<AffineExpr> a,
2230                                                 ArrayRef<AffineExpr> b) {
2231   auto rangeA = llvm::make_range(a.begin(), a.end());
2232   auto rangeB = llvm::make_range(b.begin(), b.end());
2233   auto concatRanges = llvm::concat<const AffineExpr>(rangeA, rangeB);
2234   return llvm::to_vector<4>(concatRanges);
2235 }
2236 
2237 static void appendMangledType(llvm::raw_string_ostream &ss, Type t) {
2238   if (auto memref = t.dyn_cast<MemRefType>()) {
2239     ss << "view";
2240     for (auto size : memref.getShape())
2241       if (size < 0)
2242         ss << "sx";
2243       else
2244         ss << size << "x";
2245     appendMangledType(ss, memref.getElementType());
2246   } else if (auto vec = t.dyn_cast<VectorType>()) {
2247     ss << "vector";
2248     llvm::interleave(
2249         vec.getShape(), [&](int64_t i) { ss << i; }, [&]() { ss << "x"; });
2250     appendMangledType(ss, vec.getElementType());
2251   } else if (t.isSignlessIntOrIndexOrFloat()) {
2252     ss << t;
2253   } else {
2254     llvm_unreachable("Invalid type for linalg library name mangling");
2255   }
2256 }
2257 
2258 std::string mlir::linalg::generateLibraryCallName(Operation *op) {
2259   assert(isa<LinalgOp>(op));
2260   std::string name(op->getName().getStringRef().str());
2261   name.reserve(128);
2262   std::replace(name.begin(), name.end(), '.', '_');
2263   llvm::raw_string_ostream ss(name);
2264   ss << "_";
2265   auto types = op->getOperandTypes();
2266   llvm::interleave(
2267       types.begin(), types.end(), [&](Type t) { appendMangledType(ss, t); },
2268       [&]() { ss << "_"; });
2269   return ss.str();
2270 }
2271 
2272 // TODO: Consider making all this boilerplate easy to autogenerate
2273 // with Tablegen. This seems a desirable property in the context of
2274 // OpInterfaces where a Linalg "named" op **isa** LinalgOp.
2275 OpFoldResult ReshapeOp::fold(ArrayRef<Attribute> operands) {
2276   if (succeeded(foldMemRefCast(*this)))
2277     return getResult();
2278   return foldReshapeOp(*this, operands);
2279 }
2280 OpFoldResult TensorReshapeOp::fold(ArrayRef<Attribute> operands) {
2281   return foldReshapeOp(*this, operands);
2282 }
2283 
2284 //===----------------------------------------------------------------------===//
2285 // Support for named Linalg ops defined in ods-gen.
2286 //===----------------------------------------------------------------------===//
2287 
2288 /// Generic entry point to create the block for the region of a LinalgOp.
2289 /// This is used by both named structured ops created by ods-gen and by manually
2290 /// defined C++ ops.
2291 /// This is used by both builders and parsers.
2292 /// This function creates the block in the region with arguments corresponding
2293 /// to the elemental types of `inputTypes` and `outputTypes`, which are asserted
2294 /// to be ShapedType.
2295 template <typename NamedStructuredOpType>
2296 static void
2297 fillStructuredOpRegion(OpBuilder &opBuilder, Region &region,
2298                        TypeRange inputTypes, TypeRange outputTypes,
2299                        ValueRange captures,
2300                        std::function<void(unsigned, unsigned)> errorHandler) {
2301   assert(llvm::all_of(inputTypes, [](Type t) { return t.isa<ShapedType>(); }));
2302   assert(llvm::all_of(outputTypes, [](Type t) { return t.isa<ShapedType>(); }));
2303 
2304   // TODO: atm all operands go through getElementTypeOrSelf,
2305   // reconsider when we have evidence we need to.
2306   SmallVector<Type, 8> argTypes;
2307   for (auto containers : {inputTypes, outputTypes})
2308     for (auto t : containers)
2309       argTypes.push_back(getElementTypeOrSelf(t));
2310 
2311   // RAII.
2312   OpBuilder::InsertionGuard guard(opBuilder);
2313   Block *body = opBuilder.createBlock(&region, /*insertPt=*/{}, argTypes);
2314   unsigned actual = body->getNumArguments();
2315   unsigned expected = NamedStructuredOpType::getNumRegionArgs();
2316   if (expected != actual) {
2317     if (errorHandler)
2318       errorHandler(expected, actual);
2319     return;
2320   }
2321 
2322   opBuilder.setInsertionPointToStart(body);
2323   mlir::edsc::ScopedContext scope(opBuilder, opBuilder.getUnknownLoc());
2324   NamedStructuredOpType::regionBuilder(*body, captures);
2325 
2326   // indexing_maps is an auto-generated method.
2327 
2328   // iterator_types is an auto-generated method.
2329 }
2330 
2331 /// Generic entry point to create both the region and the block of a LinalgOp.
2332 template <typename NamedStructuredOpType>
2333 void createAndFillStructuredOpRegion(OpBuilder &opBuilder,
2334                                      OperationState &result,
2335                                      TypeRange inputTypes,
2336                                      TypeRange outputTypes,
2337                                      ValueRange captures) {
2338   Region &region = *result.addRegion();
2339   fillStructuredOpRegion<NamedStructuredOpType>(
2340       opBuilder, region, inputTypes, outputTypes, captures,
2341       [&](unsigned expected, unsigned actual) {
2342         assert(expected != actual && "incorrect number of arguments");
2343       });
2344 }
2345 
2346 /// Common parsing used for both named structured ops created by ods-gen and by
2347 /// manually defined C++ ops. Does not handle regions.
2348 static ParseResult
2349 parseCommonStructuredOpParts(OpAsmParser &parser, OperationState &result,
2350                              SmallVectorImpl<Type> &inputTypes,
2351                              SmallVectorImpl<Type> &outputTypes) {
2352   llvm::SMLoc inputsOperandsLoc, outputsOperandsLoc;
2353   SmallVector<OpAsmParser::OperandType, 4> inputsOperands, outputsOperands;
2354 
2355   parser.parseOptionalAttrDict(result.attributes);
2356 
2357   if (succeeded(parser.parseOptionalKeyword("ins"))) {
2358     if (parser.parseLParen())
2359       return failure();
2360 
2361     inputsOperandsLoc = parser.getCurrentLocation();
2362     if (parser.parseOperandList(inputsOperands) ||
2363         parser.parseColonTypeList(inputTypes) || parser.parseRParen())
2364       return failure();
2365   }
2366 
2367   if (succeeded(parser.parseOptionalKeyword("outs"))) {
2368     outputsOperandsLoc = parser.getCurrentLocation();
2369     if (parser.parseLParen() || parser.parseOperandList(outputsOperands) ||
2370         parser.parseColonTypeList(outputTypes) || parser.parseRParen())
2371       return failure();
2372   }
2373 
2374   if (parser.resolveOperands(inputsOperands, inputTypes, inputsOperandsLoc,
2375                              result.operands) ||
2376       parser.resolveOperands(outputsOperands, outputTypes, outputsOperandsLoc,
2377                              result.operands))
2378     return failure();
2379 
2380   result.addAttribute("operand_segment_sizes",
2381                       parser.getBuilder().getI32VectorAttr(
2382                           {static_cast<int32_t>(inputsOperands.size()),
2383                            static_cast<int32_t>(outputsOperands.size())}));
2384   return success();
2385 }
2386 
2387 template <typename NamedStructuredOpType>
2388 static void printCommonStructuredOpParts(OpAsmPrinter &p,
2389                                          NamedStructuredOpType op) {
2390   if (!op.inputs().empty())
2391     p << " ins(" << op.inputs() << " : " << op.inputs().getTypes() << ")";
2392   if (!op.outputs().empty())
2393     p << " outs(" << op.outputs() << " : " << op.outputs().getTypes() << ")";
2394 }
2395 
2396 //===----------------------------------------------------------------------===//
2397 // Specific parsing and printing for named structured ops created by ods-gen.
2398 //===----------------------------------------------------------------------===//
2399 
2400 template <typename NamedStructuredOpType>
2401 static ParseResult
2402 parseNamedStructuredOpRegion(OpAsmParser &parser, Region &region,
2403                              TypeRange inputTypes, TypeRange outputTypes,
2404                              ArrayRef<OpAsmParser::OperandType> captures) {
2405   ParseResult res = success();
2406   OpBuilder opBuilder(parser.getBuilder().getContext());
2407   // Resolve `captures` into `capturedValues` at parse time so we can build the
2408   // region with captures.
2409   SmallVector<Value> capturedValues;
2410   fillStructuredOpRegion<NamedStructuredOpType>(
2411       opBuilder, region, inputTypes, outputTypes, capturedValues,
2412       [&](unsigned expected, unsigned actual) {
2413         res = parser.emitError(
2414             parser.getCurrentLocation(),
2415             llvm::formatv("[parseNamedStructuredOpRegion] ods-gen generated "
2416                           "region expects {0} args, got {1}",
2417                           expected, actual));
2418         region.front().dump();
2419       });
2420   return res;
2421 }
2422 
2423 static ParseResult
2424 parseNamedStructuredOpResults(OpAsmParser &parser,
2425                               SmallVectorImpl<Type> &resultTypes) {
2426   if (succeeded(parser.parseOptionalArrow()))
2427     if (parser.parseTypeList(resultTypes))
2428       return failure();
2429   return success();
2430 }
2431 
2432 template <typename NamedStructuredOpType>
2433 static ParseResult
2434 parseNamedStructuredOp(OpAsmParser &parser, OperationState &result,
2435                        ArrayRef<OpAsmParser::OperandType> captures) {
2436   // TODO: Enable when ods-gen supports captures.
2437   assert(captures.empty() && "unexpected captures for named structured ops");
2438   SmallVector<Type, 1> inputTypes, outputTypes;
2439   if (parseCommonStructuredOpParts(parser, result, inputTypes, outputTypes))
2440     return failure();
2441 
2442   // TODO: consider merging results parsing into region parsing.
2443   // Need to wait for declarative assembly resolution to decide.
2444   SmallVector<Type, 1> outputTensorsTypes;
2445   if (parseNamedStructuredOpResults(parser, outputTensorsTypes))
2446     return failure();
2447   result.addTypes(outputTensorsTypes);
2448 
2449   std::unique_ptr<Region> region = std::make_unique<Region>();
2450   if (parseNamedStructuredOpRegion<NamedStructuredOpType>(
2451           parser, *region, inputTypes, outputTypes, captures))
2452     return failure();
2453   result.addRegion(std::move(region));
2454 
2455   return success();
2456 }
2457 
2458 static void printNamedStructuredOpResults(OpAsmPrinter &p,
2459                                           TypeRange resultTypes) {
2460   if (resultTypes.empty())
2461     return;
2462   p.printOptionalArrowTypeList(resultTypes);
2463 }
2464 
2465 template <typename NamedStructuredOpType>
2466 static void printNamedStructuredOp(OpAsmPrinter &p, NamedStructuredOpType op) {
2467   p << op.getOperationName();
2468   p.printOptionalAttrDict(
2469       op->getAttrs(),
2470       /*elidedAttrs=*/{"operand_segment_sizes",
2471                        // See generated code in mlir-linalg-yaml-gen.cpp
2472                        "linalg.memoized_indexing_maps"});
2473 
2474   // Printing is shared with generic ops, except for the region and
2475   // attributes.
2476   printCommonStructuredOpParts(p, op);
2477 
2478   // Results printing.
2479   printNamedStructuredOpResults(p, op.result_tensors().getTypes());
2480 
2481   // Region is elided.
2482 }
2483 
2484 template <typename NamedStructuredOpType>
2485 static LogicalResult verifyNamedStructuredOp(NamedStructuredOpType op) {
2486   return verifyGenericOp<NamedStructuredOpType>(op);
2487 }
2488 
2489 //===----------------------------------------------------------------------===//
2490 // Canonicalizers and Folders.
2491 //===----------------------------------------------------------------------===//
2492 
2493 namespace {
2494 struct EraseDeadLinalgOp : public OpInterfaceRewritePattern<LinalgOp> {
2495   using OpInterfaceRewritePattern<LinalgOp>::OpInterfaceRewritePattern;
2496 
2497   LogicalResult matchAndRewrite(LinalgOp op,
2498                                 PatternRewriter &rewriter) const override {
2499     for (Value v : op.getShapedOperands()) {
2500       // Linalg "inputs" may be either tensor or memref type.
2501       // tensor<0xelt_type> is a convention that may not always mean
2502       // "0 iterations". Only erase in cases we see memref<...x0x...>.
2503       auto mt = v.getType().dyn_cast<MemRefType>();
2504       if (!mt)
2505         continue;
2506       if (llvm::is_contained(mt.getShape(), 0)) {
2507         rewriter.eraseOp(op);
2508         return success();
2509       }
2510     }
2511     return failure();
2512   }
2513 };
2514 
2515 struct FoldTensorCastOp : public OpInterfaceRewritePattern<LinalgOp> {
2516   using OpInterfaceRewritePattern<LinalgOp>::OpInterfaceRewritePattern;
2517 
2518   LogicalResult matchAndRewrite(LinalgOp op,
2519                                 PatternRewriter &rewriter) const override {
2520     // If no operand comes from a tensor::CastOp and can be folded then fail.
2521     bool hasTensorCastOperand =
2522         llvm::any_of(op.getShapedOperands(), [&](Value v) {
2523           if (v.isa<BlockArgument>())
2524             return false;
2525           auto castOp = v.getDefiningOp<tensor::CastOp>();
2526           return castOp && canFoldIntoConsumerOp(castOp);
2527         });
2528     if (!hasTensorCastOperand)
2529       return failure();
2530 
2531     SmallVector<Type, 4> newResultTypes;
2532     newResultTypes.reserve(op->getNumResults());
2533     SmallVector<Value, 4> newOperands;
2534     newOperands.reserve(op->getNumOperands());
2535     // Inputs may fold.
2536     for (Value v : op.getInputs()) {
2537       auto tensorCastOp = v.getDefiningOp<tensor::CastOp>();
2538       newOperands.push_back(
2539           canFoldIntoConsumerOp(tensorCastOp) ? tensorCastOp.source() : v);
2540     }
2541     // Init tensors may fold, in which case the resultType must also change.
2542     for (Value v : op.getOutputs()) {
2543       auto tensorCastOp = v.getDefiningOp<tensor::CastOp>();
2544       bool fold = canFoldIntoConsumerOp(tensorCastOp);
2545       newOperands.push_back(fold ? tensorCastOp.getOperand() : v);
2546       newResultTypes.push_back(newOperands.back().getType());
2547     }
2548     auto extraOperands = op.getAssumedNonShapedOperands();
2549     newOperands.append(extraOperands.begin(), extraOperands.end());
2550     // Clone op.
2551     Operation *newOp =
2552         op.clone(rewriter, op->getLoc(), newResultTypes, newOperands);
2553     SmallVector<Value, 4> replacements;
2554     replacements.reserve(newOp->getNumResults());
2555     for (auto result : llvm::zip(op->getResults(), newOp->getResults())) {
2556       Value oldResult = std::get<0>(result);
2557       Value newResult = std::get<1>(result);
2558       if (newResult.getType() != oldResult.getType()) {
2559         replacements.push_back(rewriter.create<tensor::CastOp>(
2560             op->getLoc(), oldResult.getType(), newResult));
2561       } else {
2562         replacements.push_back(newResult);
2563       }
2564     }
2565     rewriter.replaceOp(op, replacements);
2566 
2567     return success();
2568   }
2569 };
2570 } // namespace
2571 
2572 namespace {
2573 // Deduplicate redundant args of a linalg op.
2574 // An arg is redundant if it has the same Value and indexing map as another.
2575 struct DeduplicateInputs : public OpInterfaceRewritePattern<LinalgOp> {
2576   using OpInterfaceRewritePattern<LinalgOp>::OpInterfaceRewritePattern;
2577 
2578   LogicalResult matchAndRewrite(LinalgOp op,
2579                                 PatternRewriter &rewriter) const override {
2580     // This pattern reduces the number of arguments of an op, which breaks
2581     // the invariants of semantically charged named ops.
2582     if (!isa<GenericOp, IndexedGenericOp>(op))
2583       return failure();
2584 
2585     // Associate each input to an equivalent "canonical" input that has the same
2586     // Value and indexing map.
2587     //
2588     // In the non-duplicate case, input `i` will have canonical input `i`. But
2589     // in the case of duplicated inputs, the canonical input could be some other
2590     // input `< i`. That is, a later input will have some earlier input as its
2591     // canonical input.
2592     llvm::SmallDenseMap<std::pair<Value, AffineMap>, int> canonicalInput;
2593     // For later remapping tasks like deduplicating payload block arguments,
2594     // having a simple "inputIndex -> canonicalInputIndex" integer mapping is
2595     // convenient.
2596     SmallVector<int, 6> canonicalInputIndices;
2597     for (int i = 0, e = op.getNumInputs(); i != e; i++) {
2598       Value input = op.getInput(i);
2599       AffineMap indexingMap = op.getInputIndexingMap(i);
2600       // STL-like maps have a convenient behavior for our use case here. In the
2601       // case of duplicate keys, the insertion is rejected, and the returned
2602       // iterator gives access to the value already in the map.
2603       auto pair = canonicalInput.insert({{input, indexingMap}, i});
2604       canonicalInputIndices.push_back(pair.first->second);
2605     }
2606 
2607     // If there are no duplicate args, then bail out.
2608     if (canonicalInput.size() == op.getNumInputs())
2609       return failure();
2610 
2611     // The operands for the newly canonicalized op.
2612     SmallVector<Value, 6> newOperands;
2613     for (auto v : llvm::enumerate(op.getInputs()))
2614       if (canonicalInputIndices[v.index()] == static_cast<int>(v.index()))
2615         newOperands.push_back(v.value());
2616     llvm::append_range(newOperands, op.getOutputs());
2617     llvm::append_range(newOperands, op.getAssumedNonShapedOperands());
2618 
2619     // Clone the old op with new operands.
2620     Operation *newOp =
2621         op.clone(rewriter, op->getLoc(), op->getResultTypes(), newOperands);
2622     auto newLinalgOp = cast<LinalgOp>(newOp);
2623 
2624     // Repair the indexing maps by filtering out the ones that have been
2625     // eliminated.
2626     SmallVector<AffineMap, 6> newIndexingMaps;
2627     for (int i = 0, e = newLinalgOp.getNumInputs(); i != e; i++)
2628       if (canonicalInputIndices[i] == i)
2629         newIndexingMaps.push_back(newLinalgOp.getIndexingMap(i));
2630     for (int i = 0, e = newLinalgOp.getNumOutputs(); i != e; i++)
2631       newIndexingMaps.push_back(newLinalgOp.getOutputIndexingMap(i));
2632     newOp->setAttr("indexing_maps",
2633                    rewriter.getAffineMapArrayAttr(newIndexingMaps));
2634 
2635     // Set the number of inputs to the new value. The `clone` call above kept
2636     // the value from the original op.
2637     newLinalgOp.setNumInputs(canonicalInput.size());
2638 
2639     // linalg.indexed_generic payloads have additional arguments prepended to
2640     // the block arg list.
2641     int bbArgBaseOffset = newLinalgOp.getNumPayloadInductionVariables();
2642 
2643     // Repair the payload entry block by RAUW'ing redundant arguments and
2644     // erasing them.
2645     Block &payload = newOp->getRegion(0).front();
2646     for (int i = 0, e = op.getNumInputs(); i < e; i++) {
2647       // Iterate in reverse, so that we erase later args first, preventing the
2648       // argument list from shifting unexpectedly and invalidating all our
2649       // indices.
2650       int reversed = e - i - 1;
2651       int canonicalIndex = canonicalInputIndices[reversed];
2652       if (canonicalInputIndices[reversed] == reversed)
2653         continue;
2654       payload.getArgument(bbArgBaseOffset + reversed)
2655           .replaceAllUsesWith(
2656               payload.getArgument(bbArgBaseOffset + canonicalIndex));
2657       payload.eraseArgument(bbArgBaseOffset + reversed);
2658     }
2659 
2660     rewriter.replaceOp(op, newOp->getResults());
2661     return success();
2662   }
2663 };
2664 
2665 /// Remove generic/indexed_generic operations (on tensors) that are just copying
2666 /// the values from inputs to the results. Requirements are
2667 /// 1) All iterator types are parallel
2668 /// 2) The body contains just a yield operation with the yielded values being
2669 ///    the arguments corresponding to the operands.
2670 struct RemoveIdentityLinalgOps : public OpInterfaceRewritePattern<LinalgOp> {
2671   using OpInterfaceRewritePattern<LinalgOp>::OpInterfaceRewritePattern;
2672 
2673   LogicalResult matchAndRewrite(LinalgOp op,
2674                                 PatternRewriter &rewriter) const override {
2675     if (auto copyOp = dyn_cast<CopyOp>(*op)) {
2676       assert(copyOp.hasBufferSemantics());
2677       if (copyOp.input() == copyOp.output() &&
2678           copyOp.inputPermutation() == copyOp.outputPermutation()) {
2679         rewriter.eraseOp(op);
2680         return success();
2681       }
2682     }
2683 
2684     if (!isa<GenericOp, IndexedGenericOp>(op))
2685       return failure();
2686     if (!op.hasTensorSemantics())
2687       return failure();
2688     // Check all indexing maps are identity.
2689     if (llvm::any_of(op.getIndexingMaps(),
2690                      [](AffineMap map) { return !map.isIdentity(); }))
2691       return failure();
2692 
2693     // Check that the body of the linalg operation is just a linalg.yield
2694     // operation.
2695     Block &body = op->getRegion(0).front();
2696     if (!llvm::hasSingleElement(body))
2697       return failure();
2698     auto yieldOp = dyn_cast<linalg::YieldOp>(body.getTerminator());
2699     if (!yieldOp)
2700       return failure();
2701 
2702     // Get the argument number of the returned values. That is the operand
2703     // number to use for replacing uses of this operation.
2704     unsigned numIndexArgs = op.getNumPayloadInductionVariables();
2705     SmallVector<Value, 4> returnedArgs;
2706     for (Value yieldVal : yieldOp.values()) {
2707       auto yieldArg = yieldVal.dyn_cast<BlockArgument>();
2708       if (!yieldArg || yieldArg.getOwner() != &body)
2709         return failure();
2710       unsigned argumentNumber = yieldArg.getArgNumber();
2711       if (argumentNumber < numIndexArgs)
2712         return failure();
2713       returnedArgs.push_back(op->getOperand(argumentNumber - numIndexArgs));
2714     }
2715     if (returnedArgs.size() != op.getOperation()->getNumResults())
2716       return failure();
2717     rewriter.replaceOp(op, returnedArgs);
2718     return success();
2719   }
2720 };
2721 } // namespace
2722 
2723 #define CANONICALIZERS_AND_FOLDERS(XXX)                                        \
2724   void XXX::getCanonicalizationPatterns(RewritePatternSet &results,            \
2725                                         MLIRContext *context) {                \
2726     results.add<DeduplicateInputs, EraseDeadLinalgOp, FoldTensorCastOp,        \
2727                 RemoveIdentityLinalgOps>(context);                             \
2728   }                                                                            \
2729                                                                                \
2730   LogicalResult XXX::fold(ArrayRef<Attribute>,                                 \
2731                           SmallVectorImpl<OpFoldResult> &) {                   \
2732     return foldMemRefCast(*this);                                              \
2733   }
2734 
2735 CANONICALIZERS_AND_FOLDERS(ConvOp)
2736 CANONICALIZERS_AND_FOLDERS(PoolingMaxOp)
2737 CANONICALIZERS_AND_FOLDERS(PoolingMinOp)
2738 CANONICALIZERS_AND_FOLDERS(PoolingSumOp)
2739 CANONICALIZERS_AND_FOLDERS(CopyOp)
2740 CANONICALIZERS_AND_FOLDERS(FillOp)
2741 CANONICALIZERS_AND_FOLDERS(GenericOp)
2742 CANONICALIZERS_AND_FOLDERS(IndexedGenericOp)
2743 
2744 // All named ops canonicalizers and folders are auto-generated in the
2745 // .cpp.inc.
2746