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