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 #include "mlir/Dialect/Linalg/EDSC/Intrinsics.h"
15 #include "mlir/Dialect/Linalg/IR/LinalgTypes.h"
16 #include "mlir/Dialect/StandardOps/IR/Ops.h"
17 #include "mlir/IR/AffineExpr.h"
18 #include "mlir/IR/AffineMap.h"
19 #include "mlir/IR/Builders.h"
20 #include "mlir/IR/Function.h"
21 #include "mlir/IR/Matchers.h"
22 #include "mlir/IR/Module.h"
23 #include "mlir/IR/OpImplementation.h"
24 #include "mlir/IR/PatternMatch.h"
25 #include "mlir/IR/StandardTypes.h"
26 #include "mlir/Support/LLVM.h"
27 
28 #include "llvm/ADT/DenseMap.h"
29 #include "llvm/ADT/SetVector.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 template <typename NamedStructuredOpType>
40 static void buildNamedStructuredOpRegionAndAttributes(
41     OpBuilder &opBuilder, OperationState &result, TypeRange inputTypes,
42     TypeRange outputBufferTypes, TypeRange initTensorTypes,
43     TypeRange resultTypes);
44 
45 static ParseResult
46 parseCommonStructuredOpParts(OpAsmParser &parser, OperationState &result,
47                              SmallVectorImpl<Type> &inputTypes,
48                              SmallVectorImpl<Type> &outputBufferTypes,
49                              SmallVectorImpl<Type> &initTensorTypes);
50 
51 template <typename NamedStructuredOpType>
52 static ParseResult
53 parseNamedStructuredOpRegion(OpAsmParser &parser, Region &region,
54                              TypeRange inputTypes, TypeRange outputBufferTypes,
55                              TypeRange initTensorTypes, TypeRange resultTypes);
56 static ParseResult
57 parseNamedStructuredOpResults(OpAsmParser &parser,
58                               SmallVectorImpl<Type> &resultTypes);
59 
60 template <typename NamedStructuredOpType>
61 static ParseResult parseNamedStructuredOp(OpAsmParser &parser,
62                                           OperationState &result);
63 
64 template <typename NamedStructuredOpType>
65 static void printCommonStructuredOpParts(OpAsmPrinter &p,
66                                          NamedStructuredOpType op);
67 
68 static void printNamedStructuredOpResults(OpAsmPrinter &p,
69                                           TypeRange resultTypes);
70 
71 template <typename NamedStructuredOpType>
72 static void printNamedStructuredOp(OpAsmPrinter &p, NamedStructuredOpType op);
73 
74 template <typename NamedStructuredOpType>
75 static LogicalResult verifyNamedStructuredOp(NamedStructuredOpType op);
76 
77 /// This is a common class used for patterns of the form
78 /// ```
79 ///    someop(memrefcast) -> someop
80 /// ```
81 /// It folds the source of the memref_cast into the root operation directly.
82 static LogicalResult foldMemRefCast(Operation *op) {
83   bool folded = false;
84   for (OpOperand &operand : op->getOpOperands()) {
85     auto castOp = operand.get().getDefiningOp<MemRefCastOp>();
86     if (castOp && canFoldIntoConsumerOp(castOp)) {
87       operand.set(castOp.getOperand());
88       folded = true;
89     }
90   }
91   return success(folded);
92 }
93 
94 ///////////////////// Operations defined with Tablegen /////////////////////////
95 // For such operations that do not correspond to library calls (i.e. defined in
96 // LinalgOps.td), we define an overloaded `print` function and a
97 // parse`className` function.
98 
99 //===----------------------------------------------------------------------===//
100 // GenericOps
101 //===----------------------------------------------------------------------===//
102 void GenericOp::build(
103     OpBuilder &builder, OperationState &result, TypeRange resultTensorTypes,
104     ValueRange inputs, ValueRange outputBuffers, ValueRange initTensors,
105     ArrayRef<AffineMap> indexingMaps, ArrayRef<StringRef> iteratorTypes,
106     StringRef doc, StringRef libraryCall, IntegerAttr symbolSource,
107     function_ref<void(OpBuilder &, Location, ValueRange)> bodyBuild) {
108   build(builder, result, resultTensorTypes, inputs, outputBuffers, initTensors,
109         builder.getAffineMapArrayAttr(indexingMaps),
110         builder.getStrArrayAttr(iteratorTypes),
111         doc.empty() ? StringAttr() : builder.getStringAttr(doc),
112         libraryCall.empty() ? StringAttr() : builder.getStringAttr(libraryCall),
113         symbolSource);
114   if (!bodyBuild)
115     return;
116 
117   SmallVector<Type, 4> blockArgTypes;
118   for (ValueRange container : {inputs, outputBuffers, initTensors})
119     for (Value v : container)
120       blockArgTypes.push_back(v.getType().cast<ShapedType>().getElementType());
121 
122   OpBuilder::InsertionGuard guard(builder);
123   auto &region = *result.regions.front();
124   Block *bodyBlock = builder.createBlock(&region, region.end(), blockArgTypes);
125   bodyBuild(builder, result.location, bodyBlock->getArguments());
126 }
127 
128 void GenericOp::build(
129     OpBuilder &builder, OperationState &result, ValueRange inputs,
130     ValueRange outputBuffers, ArrayRef<AffineMap> indexingMaps,
131     ArrayRef<StringRef> iteratorTypes, StringRef doc, StringRef libraryCall,
132     IntegerAttr symbolSource,
133     function_ref<void(OpBuilder &, Location, ValueRange)> bodyBuild) {
134   build(builder, result, TypeRange{}, inputs, outputBuffers, ValueRange{},
135         indexingMaps, iteratorTypes, doc, libraryCall, symbolSource, bodyBuild);
136 }
137 
138 void GenericOp::build(
139     OpBuilder &builder, OperationState &result, ValueRange inputs,
140     ValueRange outputBuffers, ArrayRef<AffineMap> indexingMaps,
141     ArrayRef<StringRef> iteratorTypes,
142     function_ref<void(OpBuilder &, Location, ValueRange)> bodyBuild) {
143   build(builder, result, inputs, outputBuffers, indexingMaps, iteratorTypes,
144         /*doc=*/"",
145         /*libraryCall=*/"",
146         /*symbolSource=*/IntegerAttr(), bodyBuild);
147 }
148 
149 void GenericOp::build(
150     OpBuilder &builder, OperationState &result, TypeRange resultTensorTypes,
151     ValueRange inputs, ValueRange outputBuffers, ValueRange initTensors,
152     ArrayRef<AffineMap> indexingMaps, ArrayRef<StringRef> iteratorTypes,
153     function_ref<void(OpBuilder &, Location, ValueRange)> bodyBuild) {
154   build(builder, result, resultTensorTypes, inputs, outputBuffers, initTensors,
155         indexingMaps, iteratorTypes,
156         /*doc=*/"",
157         /*libraryCall=*/"",
158         /*symbolSource=*/IntegerAttr(), bodyBuild);
159 }
160 
161 void IndexedGenericOp::build(
162     OpBuilder &builder, OperationState &result, TypeRange resultTensorTypes,
163     ValueRange inputs, ValueRange outputBuffers, ValueRange initTensors,
164     ArrayRef<AffineMap> indexingMaps, ArrayRef<StringRef> iteratorTypes,
165     StringRef doc, StringRef libraryCall, IntegerAttr symbolSource,
166     function_ref<void(OpBuilder &, Location, ValueRange, ValueRange)>
167         bodyBuild) {
168   build(builder, result, resultTensorTypes, inputs, outputBuffers, initTensors,
169         builder.getAffineMapArrayAttr(indexingMaps),
170         builder.getStrArrayAttr(iteratorTypes),
171         doc.empty() ? StringAttr() : builder.getStringAttr(doc),
172         libraryCall.empty() ? StringAttr() : builder.getStringAttr(libraryCall),
173         symbolSource);
174   if (!bodyBuild)
175     return;
176 
177   unsigned nLoops = iteratorTypes.size();
178   SmallVector<Type, 4> blockArgTypes(nLoops, builder.getIndexType());
179   for (ValueRange container : {inputs, outputBuffers, initTensors})
180     for (Value v : container)
181       blockArgTypes.push_back(v.getType().cast<ShapedType>().getElementType());
182 
183   OpBuilder::InsertionGuard guard(builder);
184   auto &region = *result.regions.front();
185   Block *bodyBlock = builder.createBlock(&region, region.end(), blockArgTypes);
186   bodyBuild(builder, result.location,
187             bodyBlock->getArguments().take_front(nLoops),
188             bodyBlock->getArguments().drop_front(nLoops));
189 }
190 
191 void IndexedGenericOp::build(
192     OpBuilder &builder, OperationState &result, ValueRange inputs,
193     ValueRange outputBuffers, ArrayRef<AffineMap> indexingMaps,
194     ArrayRef<StringRef> iteratorTypes, StringRef doc, StringRef libraryCall,
195     IntegerAttr symbolSource,
196     function_ref<void(OpBuilder &, Location, ValueRange, ValueRange)>
197         bodyBuild) {
198   build(builder, result, TypeRange{}, inputs, outputBuffers, ValueRange{},
199         indexingMaps, iteratorTypes, doc, libraryCall, symbolSource, bodyBuild);
200 }
201 
202 void IndexedGenericOp::build(
203     OpBuilder &builder, OperationState &result, ValueRange inputs,
204     ValueRange outputBuffers, ArrayRef<AffineMap> indexingMaps,
205     ArrayRef<StringRef> iteratorTypes,
206     function_ref<void(OpBuilder &, Location, ValueRange, ValueRange)>
207         bodyBuild) {
208   build(builder, result, inputs, outputBuffers, indexingMaps, iteratorTypes,
209         /*doc=*/"",
210         /*libraryCall=*/"",
211         /*symbolSource=*/IntegerAttr(), bodyBuild);
212 }
213 
214 void IndexedGenericOp::build(
215     OpBuilder &builder, OperationState &result, TypeRange resultTensorTypes,
216     ValueRange inputs, ValueRange outputBuffers, ValueRange initTensors,
217     ArrayRef<AffineMap> indexingMaps, ArrayRef<StringRef> iteratorTypes,
218     function_ref<void(OpBuilder &, Location, ValueRange, ValueRange)>
219         bodyBuild) {
220   build(builder, result, resultTensorTypes, inputs, outputBuffers, initTensors,
221         indexingMaps, iteratorTypes,
222         /*doc=*/"",
223         /*libraryCall=*/"",
224         /*symbolSource=*/IntegerAttr(), bodyBuild);
225 }
226 
227 template <typename GenericOpType>
228 static void printGenericOp(OpAsmPrinter &p, GenericOpType op) {
229   p << op.getOperationName() << " ";
230 
231   // Print extra attributes.
232   auto genericAttrNames = op.linalgTraitAttrNames();
233 
234   llvm::StringSet<> genericAttrNamesSet;
235   genericAttrNamesSet.insert(genericAttrNames.begin(), genericAttrNames.end());
236   SmallVector<NamedAttribute, 8> genericAttrs;
237   for (auto attr : op.getAttrs())
238     if (genericAttrNamesSet.count(attr.first.strref()) > 0)
239       genericAttrs.push_back(attr);
240   if (!genericAttrs.empty()) {
241     auto genericDictAttr = DictionaryAttr::get(genericAttrs, op.getContext());
242     p << genericDictAttr;
243   }
244 
245   // Printing is shared with named ops, except for the region and attributes
246   printCommonStructuredOpParts(p, op);
247 
248   genericAttrNames.push_back("operand_segment_sizes");
249   genericAttrNamesSet.insert(genericAttrNames.back());
250 
251   bool hasExtraAttrs = false;
252   for (NamedAttribute n : op.getAttrs()) {
253     if ((hasExtraAttrs = !genericAttrNamesSet.contains(n.first.strref())))
254       break;
255   }
256   if (hasExtraAttrs) {
257     p << " attrs = ";
258     p.printOptionalAttrDict(op.getAttrs(), /*elidedAttrs=*/genericAttrNames);
259   }
260 
261   // Print region.
262   if (!op.region().empty())
263     p.printRegion(op.region());
264 
265   // Print results.
266   printNamedStructuredOpResults(p, op.result_tensors().getTypes());
267 }
268 
269 static void print(OpAsmPrinter &p, GenericOp op) { printGenericOp(p, op); }
270 
271 static void print(OpAsmPrinter &p, IndexedGenericOp op) {
272   printGenericOp(p, op);
273 }
274 
275 static ParseResult parseGenericOp(OpAsmParser &parser, OperationState &result) {
276   DictionaryAttr dictAttr;
277   // Parse the core linalg traits that must check into a dictAttr.
278   // The name is unimportant as we will overwrite result.attributes.
279   // The core linalg traits must contain the information necessary to pass the
280   // verifier.
281   if (parser.parseAttribute(dictAttr, "_", result.attributes))
282     return failure();
283   result.attributes.assign(dictAttr.getValue().begin(),
284                            dictAttr.getValue().end());
285 
286   // Parsing is shared with named ops, except for the region.
287   SmallVector<Type, 1> inputTypes, outputBufferTypes, initTensorTypes;
288   if (parseCommonStructuredOpParts(parser, result, inputTypes,
289                                    outputBufferTypes, initTensorTypes))
290     return failure();
291 
292   // Optional attributes may be added.
293   if (succeeded(parser.parseOptionalKeyword("attrs")))
294     if (failed(parser.parseEqual()) ||
295         failed(parser.parseOptionalAttrDict(result.attributes)))
296       return failure();
297 
298   SmallVector<OpAsmParser::OperandType, 8> regionOperands;
299   std::unique_ptr<Region> region = std::make_unique<Region>();
300   SmallVector<Type, 8> operandTypes, regionTypes;
301   if (parser.parseRegion(*region, regionOperands, regionTypes))
302     return failure();
303   result.addRegion(std::move(region));
304 
305   // Generic ops may specify that a subset of its outputs are tensors. Such
306   // outputs are specified in the result type.
307   // TODO: may need to move output parsing before region parsing.
308   // Need to wait for declarative assembly resolution to decide.
309   SmallVector<Type, 1> outputTensorsTypes;
310   if (parseNamedStructuredOpResults(parser, outputTensorsTypes))
311     return failure();
312   result.addTypes(outputTensorsTypes);
313 
314   return success();
315 }
316 
317 static void getGenericEffectsImpl(
318     SmallVectorImpl<SideEffects::EffectInstance<MemoryEffects::Effect>>
319         &effects,
320     ValueRange results, ValueRange inputBuffers, ValueRange outputBuffers) {
321   for (Value value : results) {
322     effects.emplace_back(MemoryEffects::Allocate::get(), value,
323                          SideEffects::DefaultResource::get());
324   }
325   for (Value value : inputBuffers) {
326     effects.emplace_back(MemoryEffects::Read::get(), value,
327                          SideEffects::DefaultResource::get());
328   }
329   for (Value value : outputBuffers) {
330     effects.emplace_back(MemoryEffects::Read::get(), value,
331                          SideEffects::DefaultResource::get());
332     effects.emplace_back(MemoryEffects::Write::get(), value,
333                          SideEffects::DefaultResource::get());
334   }
335 }
336 
337 void GenericOp::getEffects(
338     SmallVectorImpl<SideEffects::EffectInstance<MemoryEffects::Effect>>
339         &effects) {
340   getGenericEffectsImpl(effects, getOperation()->getResults(),
341                         getInputBuffers(), getOutputBuffers());
342 }
343 
344 void IndexedGenericOp::getEffects(
345     SmallVectorImpl<SideEffects::EffectInstance<MemoryEffects::Effect>>
346         &effects) {
347   getGenericEffectsImpl(effects, getOperation()->getResults(),
348                         getInputBuffers(), getOutputBuffers());
349 }
350 
351 namespace {
352 template <typename GenericOpType>
353 struct BlockArgsVerifier {
354   static LogicalResult verify(GenericOpType op, Block &block);
355 };
356 
357 template <typename GenericOpType>
358 LogicalResult BlockArgsVerifier<GenericOpType>::verify(GenericOpType op,
359                                                        Block &block) {
360   auto nOperands = op.getNumOperands();
361   if (block.getNumArguments() != nOperands)
362     return op.emitOpError("expected number of block arguments to match number "
363                           "of operands");
364 
365   // Note: the number and type of yield values are checked in the YieldOp.
366   auto nInputViews = op.getNumInputs();
367   for (unsigned i = 0; i < nOperands; ++i) {
368     auto viewType = op.getShapedType(i);
369     if (viewType.getElementType() != block.getArgument(i).getType())
370       return op.emitOpError("expected block argument ")
371              << (i + 1) << " of the same type as elemental type of "
372              << ((i < nInputViews) ? "input " : "output ")
373              << "operand: " << viewType;
374   }
375   return success();
376 }
377 
378 template <>
379 LogicalResult BlockArgsVerifier<IndexedGenericOp>::verify(IndexedGenericOp op,
380                                                           Block &block) {
381   auto nInputViews = op.getNumInputs();
382   auto nLoops = op.getNumLoops();
383   auto nOperands = op.getNumOperands();
384   if (block.getNumArguments() != nOperands + nLoops)
385     return op.emitOpError(
386         "expected number of block arguments to match number of operands + "
387         "number of loops");
388 
389   // Note: the number and type of yield values are checked in the YieldOp.
390   for (unsigned i = 0; i < nLoops; ++i)
391     if (!block.getArgument(i).getType().isIndex())
392       return op.emitOpError("expected block argument ")
393              << (i + 1) << " to be an index";
394 
395   for (unsigned i = 0; i < nOperands; ++i) {
396     unsigned memrefArgIndex = i + nLoops;
397     auto viewType = op.getShapedType(i);
398     if (viewType.getElementType() !=
399         block.getArgument(memrefArgIndex).getType())
400       return op.emitOpError("expected block argument ")
401              << (memrefArgIndex + 1)
402              << " of the same type as elemental type of "
403              << ((i < nInputViews) ? "input " : "output ")
404              << "operand: " << viewType;
405   }
406   return success();
407 }
408 } // namespace
409 
410 template <typename GenericOpType>
411 static LogicalResult verifyGenericOp(GenericOpType op) {
412   auto nLoops = op.getNumLoops();
413 
414   if (op.inputs().size() + op.output_buffers().size() +
415           op.init_tensors().size() + op.getNumResults() ==
416       0)
417     return op.emitOpError("expected at least 1 Shaped operand or return");
418 
419   auto &region = op.region();
420   if (!llvm::hasSingleElement(region))
421     return op.emitOpError("expected region with 1 block");
422   if (failed(BlockArgsVerifier<GenericOpType>::verify(op, region.front())))
423     return failure();
424 
425   auto symbolSourceAttr =
426       op.template getAttrOfType<IntegerAttr>("symbol_source");
427   int64_t expectedNumSymbols = 0;
428   if (symbolSourceAttr) {
429     unsigned index = symbolSourceAttr.getInt();
430     if (index >= op.getNumOperands())
431       return op.emitOpError("symbol_source index out of range");
432     expectedNumSymbols = op.getShapedType(index).getRank();
433   }
434 
435   if (op.indexing_maps().size() != op.getNumInputsAndOutputs())
436     return op.emitOpError("expected the number of indexing_map (")
437            << op.indexing_maps().size()
438            << ") to be equal to the number of inputs and outputs ("
439            << op.getNumInputsAndOutputs() << ")";
440 
441   SmallVector<AffineMap, 4> indexingMaps;
442   indexingMaps.reserve(op.indexing_maps().size());
443   for (auto en : llvm::enumerate(op.indexing_maps())) {
444     auto idx = en.index();
445     auto m = en.value().template cast<AffineMapAttr>().getValue();
446     indexingMaps.push_back(m); // Save reference to map for further checks.
447     auto view = op.getShapedType(idx);
448 
449     if (m.getNumSymbols() != expectedNumSymbols)
450       return op.emitOpError("expected the number of symbols in indexing_map #")
451              << idx << " to match rank of operand `symbol_source`";
452 
453     if (m.getNumDims() != nLoops)
454       return op.emitOpError("expected indexing_map #")
455              << idx << " to have " << nLoops
456              << " dim(s) to match the number of loops";
457 
458     if (m.getNumResults() != view.getRank())
459       return op.emitOpError("expected indexing_map #")
460              << idx << " results to match view rank: " << view;
461   }
462 
463   auto concatMap = concatAffineMaps(indexingMaps);
464   // TODO: Bound inference for maps with symbols
465   if (!concatMap.getNumSymbols() && !inversePermutation(concatMap))
466     return op.emitOpError("expected the concatenation of maps in indexing_map "
467                           "to be invertible");
468 
469   return success();
470 }
471 
472 static LogicalResult verify(GenericOp op) { return verifyGenericOp(op); }
473 
474 static LogicalResult verify(IndexedGenericOp op) { return verifyGenericOp(op); }
475 
476 //===----------------------------------------------------------------------===//
477 // ReshapeOp
478 //===----------------------------------------------------------------------===//
479 
480 /// Collapse reassociation maps that are used in pair of reshape ops where one
481 /// is a producer and other is the consumer. Only valid to use this method when
482 /// both the producer and consumer are collapsing dimensions or both are
483 /// expanding dimensions.
484 ///
485 /// For example,
486 ///   mapsProducer = [affine_map<(d0, d1, d2, d3, d4) -> (d0, d1)>,
487 ///                   affine_map<(d0, d1, d2, d3, d4) -> (d2)>,
488 ///                   affine_map<(d0, d1, d2, d3, d4) -> (d3, d4)>]
489 ///   mapsConsumer = [affine_map<(d0, d1, d2) -> (d0, d1)>,
490 ///                   affine_map<(d0, d1, d2) -> (d2)>]
491 ///
492 /// is folded into
493 ///
494 ///   result = [affine_map<(d0, d1, d2, d3, d4) -> (d0, d1, d2)>,
495 ///             affine_map<(d0, d1, d2, d3, d4) -> (d3, d4)>]
496 static ArrayAttr collapseReassociationMaps(ArrayRef<AffineMap> mapsProducer,
497                                            ArrayRef<AffineMap> mapsConsumer,
498                                            MLIRContext *context) {
499   // Handle the corner case of the result being a rank 0 shaped type. Return an
500   // emtpy ArrayAttr.
501   if (mapsConsumer.empty() && !mapsProducer.empty())
502     return ArrayAttr::get(ArrayRef<Attribute>(), context);
503   if (mapsProducer.empty() || mapsConsumer.empty() ||
504       mapsProducer[0].getNumDims() < mapsConsumer[0].getNumDims() ||
505       mapsProducer.size() != mapsConsumer[0].getNumDims())
506     return nullptr;
507   unsigned numLhsDims = mapsProducer[0].getNumDims();
508   unsigned currDim = 0;
509   SmallVector<AffineExpr, 4> reassociations;
510   SmallVector<Attribute, 4> reassociationMaps;
511   for (AffineMap rhs : mapsConsumer) {
512     for (AffineExpr rhsExpr : rhs.getResults()) {
513       AffineDimExpr dimExpr = rhsExpr.cast<AffineDimExpr>();
514       for (int i = 0, e = mapsProducer[dimExpr.getPosition()].getNumResults();
515            i < e; ++i) {
516         reassociations.push_back(getAffineDimExpr(currDim++, context));
517       }
518     }
519     reassociationMaps.push_back(AffineMapAttr::get(AffineMap::get(
520         numLhsDims, /*numSymbols =*/0, reassociations, context)));
521     reassociations.clear();
522   }
523   return ArrayAttr::get(reassociationMaps, context);
524 }
525 
526 namespace {
527 /// Pattern to collapse producer/consumer reshape ops that are both collapsing
528 /// dimensions or are both expanding dimensions.
529 template <typename ReshapeOpTy>
530 struct CollapseReshapeOps : public OpRewritePattern<ReshapeOpTy> {
531   using OpRewritePattern<ReshapeOpTy>::OpRewritePattern;
532   LogicalResult matchAndRewrite(ReshapeOpTy reshapeOp,
533                                 PatternRewriter &rewriter) const override {
534     auto srcReshapeOp = reshapeOp.src().template getDefiningOp<ReshapeOpTy>();
535     if (!srcReshapeOp)
536       return failure();
537 
538     auto areReshapeOpsFoldable = [](ShapedType largerType,
539                                     ShapedType intermediateType,
540                                     ShapedType smallerType) -> bool {
541       return largerType.getRank() > intermediateType.getRank() &&
542              intermediateType.getRank() > smallerType.getRank();
543     };
544     // Check if producer and consumer are both expanding dims.
545     if (areReshapeOpsFoldable(reshapeOp.getResultType(), reshapeOp.getSrcType(),
546                               srcReshapeOp.getSrcType())) {
547       rewriter.replaceOpWithNewOp<ReshapeOpTy>(
548           reshapeOp, reshapeOp.getResultType(), srcReshapeOp.src(),
549           collapseReassociationMaps(reshapeOp.getReassociationMaps(),
550                                     srcReshapeOp.getReassociationMaps(),
551                                     rewriter.getContext()));
552       return success();
553     }
554     // Check if producer and consumer are both collapsing dims.
555     if (areReshapeOpsFoldable(srcReshapeOp.getSrcType(), reshapeOp.getSrcType(),
556                               reshapeOp.getResultType())) {
557       rewriter.replaceOpWithNewOp<ReshapeOpTy>(
558           reshapeOp, reshapeOp.getResultType(), srcReshapeOp.src(),
559           collapseReassociationMaps(srcReshapeOp.getReassociationMaps(),
560                                     reshapeOp.getReassociationMaps(),
561                                     rewriter.getContext()));
562       return success();
563     }
564     return failure();
565   }
566 };
567 } // namespace
568 
569 template <typename ReshapeOpTy>
570 static OpFoldResult foldReshapeOp(ReshapeOpTy reshapeOp,
571                                   ArrayRef<Attribute> operands) {
572   // Fold producer-consumer reshape ops that where the operand type of the
573   // producer is same as the return type of the consumer. This can only be
574   // verified if the shapes in question are static.
575   ReshapeOpTy reshapeSrcOp =
576       reshapeOp.src().template getDefiningOp<ReshapeOpTy>();
577   if (reshapeSrcOp && reshapeSrcOp.getSrcType().hasStaticShape() &&
578       reshapeOp.getResultType().hasStaticShape() &&
579       reshapeSrcOp.getSrcType() == reshapeOp.getResultType())
580     return reshapeSrcOp.src();
581   // Reshape of a constant can be replaced with a new constant.
582   if (auto elements = operands.front().dyn_cast_or_null<DenseElementsAttr>()) {
583     return elements.reshape(
584         reshapeOp.getResult().getType().template cast<ShapedType>());
585   }
586   return nullptr;
587 }
588 
589 /// Return true if the reassociation specification is valid, false otherwise.
590 /// When false, the `invalidIndex` integer pointer is optionally filled with the
591 /// index of the offending reassociation map.
592 static bool isReassociationValid(ArrayRef<AffineMap> reassociation,
593                                  int *invalidIndex = nullptr) {
594   if (reassociation.empty())
595     return true;
596   unsigned nDims = reassociation[0].getNumDims();
597   unsigned nextExpectedDim = 0;
598   for (auto it : llvm::enumerate(reassociation)) {
599     auto m = it.value();
600     if (m.getNumDims() != nDims || m.getNumSymbols() != 0) {
601       if (invalidIndex)
602         *invalidIndex = it.index();
603       return false;
604     }
605     for (auto e : m.getResults()) {
606       auto d = e.dyn_cast<AffineDimExpr>();
607       if (!d || d.getPosition() != nextExpectedDim++) {
608         if (invalidIndex)
609           *invalidIndex = it.index();
610         return false;
611       }
612     }
613   }
614   if (nextExpectedDim != nDims) {
615     if (invalidIndex)
616       *invalidIndex = reassociation.size() - 1;
617     return false;
618   }
619   return true;
620 }
621 
622 /// Detect whether memref dims [dim, dim + extent) can be reshaped without
623 /// copies.
624 static bool isReshapableDimBand(unsigned dim, unsigned extent,
625                                 ArrayRef<int64_t> sizes,
626                                 ArrayRef<AffineExpr> strides) {
627   assert(sizes.size() == strides.size() && "mismatched ranks");
628   // off by 1 indexing to avoid out of bounds
629   //                       V
630   for (auto idx = dim, e = dim + extent; idx + 1 < e; ++idx) {
631     // Only bands of static shapes are reshapable. This is due to the fact that
632     // there is no relation between dynamic sizes and dynamic strides: we do not
633     // have enough information to know whether a "-1" size corresponds to the
634     // proper symbol in the AffineExpr of a stride.
635     if (ShapedType::isDynamic(sizes[dim + 1]))
636       return false;
637     // TODO: Refine this by passing the proper nDims and nSymbols so we can
638     // simplify on the fly and catch more reshapable cases.
639     if (strides[idx] != strides[idx + 1] * sizes[idx + 1])
640       return false;
641   }
642   return true;
643 }
644 
645 /// Compute the MemRefType obtained by applying the `reassociation` (which is
646 /// expected to be valid) to `type`.
647 /// If `type` is Contiguous MemRefType, this always produce a contiguous
648 /// MemRefType.
649 static MemRefType
650 computeReshapeCollapsedType(MemRefType type,
651                             ArrayRef<AffineMap> reassociation) {
652   auto sizes = type.getShape();
653   AffineExpr offset;
654   SmallVector<AffineExpr, 4> strides;
655   auto status = getStridesAndOffset(type, strides, offset);
656   (void)status;
657   assert(succeeded(status) && "expected strided memref");
658 
659   SmallVector<int64_t, 4> newSizes;
660   newSizes.reserve(reassociation.size());
661   SmallVector<AffineExpr, 4> newStrides;
662   newStrides.reserve(reassociation.size());
663 
664   // Use the fact that reassociation is valid to simplify the logic: only use
665   // each map's rank.
666   assert(isReassociationValid(reassociation) && "invalid reassociation");
667   unsigned currentDim = 0;
668   for (AffineMap m : reassociation) {
669     unsigned dim = m.getNumResults();
670     int64_t size = 1;
671     AffineExpr stride = strides[currentDim + dim - 1];
672     if (!isReshapableDimBand(currentDim, dim, sizes, strides)) {
673       size = ShapedType::kDynamicSize;
674       stride = AffineExpr();
675     } else {
676       for (unsigned d = 0; d < dim; ++d)
677         size *= sizes[currentDim + d];
678     }
679     newSizes.push_back(size);
680     newStrides.push_back(stride);
681     currentDim += dim;
682   }
683 
684   // Early-exit: if `type` is contiguous, the result must be contiguous.
685   if (canonicalizeStridedLayout(type).getAffineMaps().empty())
686     return MemRefType::Builder(type).setShape(newSizes).setAffineMaps({});
687 
688   // Convert back to int64_t because we don't have enough information to create
689   // new strided layouts from AffineExpr only. This corresponds to a case where
690   // copies may be necessary.
691   int64_t intOffset = ShapedType::kDynamicStrideOrOffset;
692   if (auto o = offset.dyn_cast<AffineConstantExpr>())
693     intOffset = o.getValue();
694   SmallVector<int64_t, 4> intStrides;
695   intStrides.reserve(strides.size());
696   for (auto stride : newStrides) {
697     if (auto cst = stride.dyn_cast_or_null<AffineConstantExpr>())
698       intStrides.push_back(cst.getValue());
699     else
700       intStrides.push_back(ShapedType::kDynamicStrideOrOffset);
701   }
702   auto layout =
703       makeStridedLinearLayoutMap(intStrides, intOffset, type.getContext());
704   return canonicalizeStridedLayout(
705       MemRefType::Builder(type).setShape(newSizes).setAffineMaps({layout}));
706 }
707 
708 /// Helper functions assert Attribute of the proper type in attr and returns the
709 /// corresponding vector.
710 /// TODO: this should be evolved into a generic
711 /// `getRangeOfType<AffineMap>(ArrayAttr attrs)` that does not copy.
712 static SmallVector<AffineMap, 4> getAffineMaps(ArrayAttr attrs) {
713   return llvm::to_vector<8>(llvm::map_range(
714       attrs, [](Attribute a) { return a.cast<AffineMapAttr>().getValue(); }));
715 }
716 
717 template <typename AffineExprTy>
718 unsigned getMaxPosOfType(ArrayRef<ReassociationExprs> exprArrays) {
719   unsigned pos = 0;
720   for (const auto &exprs : exprArrays) {
721     for (auto expr : exprs) {
722       expr.walk([&pos](AffineExpr e) {
723         if (auto d = e.dyn_cast<AffineExprTy>())
724           pos = std::max(pos, d.getPosition());
725       });
726     }
727   }
728   return pos;
729 }
730 
731 static SmallVector<AffineMap, 4>
732 getSymbolLessAffineMaps(ArrayRef<ReassociationExprs> reassociation) {
733   unsigned maxDim = getMaxPosOfType<AffineDimExpr>(reassociation);
734   assert(getMaxPosOfType<AffineSymbolExpr>(reassociation) == 0 &&
735          "Expected symbol-less expressions");
736   SmallVector<AffineMap, 4> maps;
737   maps.reserve(reassociation.size());
738   for (const auto &exprs : reassociation) {
739     assert(!exprs.empty());
740     maps.push_back(AffineMap::get(maxDim + 1, 0, exprs, exprs[0].getContext()));
741   }
742   return maps;
743 }
744 
745 static SmallVector<SmallVector<AffineExpr, 2>, 2>
746 convertReassociationIndicesToMaps(
747     OpBuilder &b, ArrayRef<ReassociationIndices> reassociationIndices) {
748   SmallVector<SmallVector<AffineExpr, 2>, 2> reassociationMaps;
749   for (const auto &indices : reassociationIndices) {
750     SmallVector<AffineExpr, 2> reassociationMap;
751     reassociationMap.reserve(indices.size());
752     for (int64_t index : indices)
753       reassociationMap.push_back(b.getAffineDimExpr(index));
754     reassociationMaps.push_back(std::move(reassociationMap));
755   }
756   return reassociationMaps;
757 }
758 
759 void mlir::linalg::ReshapeOp::build(OpBuilder &b, OperationState &result,
760                                     Value src,
761                                     ArrayRef<ReassociationExprs> reassociation,
762                                     ArrayRef<NamedAttribute> attrs) {
763   auto maps = getSymbolLessAffineMaps(reassociation);
764   auto memRefType = src.getType().cast<MemRefType>();
765   auto resultType = computeReshapeCollapsedType(memRefType, maps);
766   build(b, result, resultType, src, attrs);
767   result.addAttribute(ReshapeOp::getReassociationAttrName(),
768                       b.getAffineMapArrayAttr(maps));
769 }
770 
771 void mlir::linalg::ReshapeOp::build(OpBuilder &b, OperationState &result,
772                                     Type resultType, Value src,
773                                     ArrayRef<ReassociationExprs> reassociation,
774                                     ArrayRef<NamedAttribute> attrs) {
775   auto maps = getSymbolLessAffineMaps(reassociation);
776   build(b, result, resultType, src, attrs);
777   result.addAttribute(ReshapeOp::getReassociationAttrName(),
778                       b.getAffineMapArrayAttr(maps));
779 }
780 
781 Value mlir::linalg::ReshapeOp::getViewSource() { return src(); }
782 
783 // Common verifier for reshape-like types. Fills `expandedType` and
784 // `collapsedType` with the proper `src` or `result` type.
785 template <typename Op, typename T>
786 static LogicalResult verifyReshapeLikeTypes(Op op, T &expandedType,
787                                             T &collapsedType) {
788   expandedType = op.getSrcType();
789   collapsedType = op.getResultType();
790   unsigned expandedRank = expandedType.getRank();
791   unsigned collapsedRank = collapsedType.getRank();
792   bool isCollapse = expandedRank > collapsedRank;
793   if (!isCollapse) {
794     std::swap(expandedRank, collapsedRank);
795     std::swap(expandedType, collapsedType);
796   }
797   if (expandedRank == 0)
798     return op.emitOpError("expected non-zero memref ranks");
799   if (expandedRank == collapsedRank)
800     return op.emitOpError("expected to collapse or expand dims");
801 
802   if (collapsedRank == 0) {
803     // If collapsed rank is 0, then expanded type must be static shaped and of
804     // sizes 1.
805     if (llvm::any_of(expandedType.getShape(),
806                      [](int64_t dim) -> bool { return dim != 1; }))
807       return op.emitOpError(
808           "invalid to reshape tensor/memref with non-unit extent dimensions to "
809           "zero-rank tensor/memref");
810     return success();
811   }
812   if (collapsedRank != op.reassociation().size())
813     return op.emitOpError("expected rank of the collapsed type(")
814            << collapsedRank << ") to be the number of reassociation maps("
815            << op.reassociation().size() << ")";
816   auto maps = getAffineMaps(op.reassociation());
817   for (auto it : llvm::enumerate(maps))
818     if (it.value().getNumDims() != expandedRank)
819       return op.emitOpError("expected reassociation map #")
820              << it.index() << " of same rank as expanded memref("
821              << expandedRank << "), but got " << it.value().getNumDims();
822   int invalidIdx = 0;
823   if (!isReassociationValid(maps, &invalidIdx))
824     return op.emitOpError("expected reassociation map #")
825            << invalidIdx << " to be valid and contiguous";
826   return success();
827 }
828 
829 static LogicalResult verify(ReshapeOp op) {
830   MemRefType expandedType, collapsedType;
831   if (failed(verifyReshapeLikeTypes(op, expandedType, collapsedType)))
832     return failure();
833   auto maps = getAffineMaps(op.reassociation());
834   MemRefType expectedType = computeReshapeCollapsedType(expandedType, maps);
835   if (collapsedType != expectedType)
836     return op.emitOpError("expected collapsed type to be ")
837            << expectedType << ", but got " << collapsedType;
838   return success();
839 }
840 
841 void ReshapeOp::getCanonicalizationPatterns(OwningRewritePatternList &results,
842                                             MLIRContext *context) {
843   results.insert<CollapseReshapeOps<ReshapeOp>>(context);
844 }
845 
846 //===----------------------------------------------------------------------===//
847 // TensorReshapeOp
848 //===----------------------------------------------------------------------===//
849 
850 /// Compute the RankedTensorType obtained by applying `reassociation` to `type`.
851 static RankedTensorType
852 computeTensorReshapeCollapsedType(RankedTensorType type,
853                                   ArrayRef<AffineMap> reassociation) {
854   auto shape = type.getShape();
855   SmallVector<int64_t, 4> newShape;
856   newShape.reserve(reassociation.size());
857 
858   // Use the fact that reassociation is valid to simplify the logic: only use
859   // each map's rank.
860   assert(isReassociationValid(reassociation) && "invalid reassociation");
861   unsigned currentDim = 0;
862   for (AffineMap m : reassociation) {
863     unsigned dim = m.getNumResults();
864     auto band = shape.slice(currentDim, dim);
865     int64_t size = 1;
866     if (llvm::is_contained(band, ShapedType::kDynamicSize))
867       size = ShapedType::kDynamicSize;
868     else
869       for (unsigned d = 0; d < dim; ++d)
870         size *= shape[currentDim + d];
871     newShape.push_back(size);
872     currentDim += dim;
873   }
874 
875   return RankedTensorType::get(newShape, type.getElementType());
876 }
877 
878 void mlir::linalg::TensorReshapeOp::build(
879     OpBuilder &b, OperationState &result, Value src,
880     ArrayRef<ReassociationExprs> reassociation,
881     ArrayRef<NamedAttribute> attrs) {
882   auto maps = getSymbolLessAffineMaps(reassociation);
883   auto resultType = computeTensorReshapeCollapsedType(
884       src.getType().cast<RankedTensorType>(), maps);
885   build(b, result, resultType, src, attrs);
886   result.addAttribute(TensorReshapeOp::getReassociationAttrName(),
887                       b.getAffineMapArrayAttr(maps));
888 }
889 
890 void mlir::linalg::TensorReshapeOp::build(
891     OpBuilder &b, OperationState &result, Type resultType, Value src,
892     ArrayRef<ReassociationExprs> reassociation,
893     ArrayRef<NamedAttribute> attrs) {
894   auto maps = getSymbolLessAffineMaps(reassociation);
895   build(b, result, resultType, src, attrs);
896   result.addAttribute(TensorReshapeOp::getReassociationAttrName(),
897                       b.getAffineMapArrayAttr(maps));
898 }
899 
900 static LogicalResult verify(TensorReshapeOp op) {
901   RankedTensorType expandedType, collapsedType;
902   if (failed(verifyReshapeLikeTypes(op, expandedType, collapsedType)))
903     return failure();
904   auto maps = getAffineMaps(op.reassociation());
905   // TODO: expanding a ? with a non-constant is under-specified. Error
906   // out.
907   RankedTensorType expectedType =
908       computeTensorReshapeCollapsedType(expandedType, maps);
909   if (collapsedType != expectedType)
910     return op.emitOpError("expected collapsed type to be ")
911            << expectedType << ", but got " << collapsedType;
912   return success();
913 }
914 
915 namespace {
916 /// Reshape of a splat constant can be replaced with a constant of the result
917 /// type.
918 struct FoldReshapeWithConstant : OpRewritePattern<TensorReshapeOp> {
919   using OpRewritePattern<TensorReshapeOp>::OpRewritePattern;
920   LogicalResult matchAndRewrite(TensorReshapeOp reshapeOp,
921                                 PatternRewriter &rewriter) const override {
922     DenseElementsAttr attr;
923     if (!matchPattern(reshapeOp.src(), m_Constant(&attr)))
924       return failure();
925     if (!attr || !attr.isSplat())
926       return failure();
927     DenseElementsAttr newAttr = DenseElementsAttr::getFromRawBuffer(
928         reshapeOp.getResultType(), attr.getRawData(), true);
929     rewriter.replaceOpWithNewOp<ConstantOp>(reshapeOp, newAttr);
930     return success();
931   }
932 };
933 } // namespace
934 
935 void TensorReshapeOp::getCanonicalizationPatterns(
936     OwningRewritePatternList &results, MLIRContext *context) {
937   results.insert<CollapseReshapeOps<TensorReshapeOp>, FoldReshapeWithConstant>(
938       context);
939 }
940 
941 //===----------------------------------------------------------------------===//
942 // SliceOp
943 //===----------------------------------------------------------------------===//
944 void mlir::linalg::SliceOp::build(OpBuilder &b, OperationState &result,
945                                   Value base, ValueRange indexings) {
946   result.addOperands(base);
947   result.addOperands(indexings);
948 
949   auto memRefType = base.getType().cast<MemRefType>();
950   int64_t offset;
951   SmallVector<int64_t, 4> strides;
952   auto res = getStridesAndOffset(memRefType, strides, offset);
953   assert(succeeded(res) && strides.size() == indexings.size());
954   (void)res;
955 
956   unsigned rank = memRefType.getRank();
957   // TODO: propagate static size and stride information when available.
958   SmallVector<int64_t, 4> sizes(rank, -1); // -1 encodes dynamic size.
959   result.addTypes({MemRefType::Builder(memRefType)
960                        .setShape(sizes)
961                        .setAffineMaps(makeStridedLinearLayoutMap(
962                            strides, offset, b.getContext()))});
963 }
964 
965 static void print(OpAsmPrinter &p, SliceOp op) {
966   auto indexings = op.indexings();
967   p << SliceOp::getOperationName() << " " << op.view() << "[" << indexings
968     << "] ";
969   p.printOptionalAttrDict(op.getAttrs());
970   p << " : " << op.getBaseViewType();
971   if (!indexings.empty())
972     p << ", " << op.indexings().getTypes();
973   p << ", " << op.getType();
974 }
975 
976 static ParseResult parseSliceOp(OpAsmParser &parser, OperationState &result) {
977   OpAsmParser::OperandType baseInfo;
978   SmallVector<OpAsmParser::OperandType, 8> operands;
979   SmallVector<Type, 8> types;
980   if (parser.parseOperand(baseInfo) ||
981       parser.parseOperandList(operands, OpAsmParser::Delimiter::Square) ||
982       parser.parseOptionalAttrDict(result.attributes) ||
983       parser.parseColonTypeList(types))
984     return failure();
985 
986   if (types.size() < 2)
987     return parser.emitError(parser.getCurrentLocation(),
988                             "expected at least input and result view types");
989 
990   ArrayRef<Type> indexingTypes = ArrayRef<Type>(types).drop_front().drop_back();
991   return failure(
992       parser.resolveOperand(baseInfo, types.front(), result.operands) ||
993       (!operands.empty() &&
994        parser.resolveOperands(operands, indexingTypes,
995                               operands.front().location, result.operands)) ||
996       parser.addTypeToList(types.back(), result.types));
997 }
998 
999 static LogicalResult verify(SliceOp op) {
1000   unsigned rank = op.getBaseViewRank();
1001   if (rank != llvm::size(op.indexings()))
1002     return op.emitOpError("expected ")
1003            << rank << " indexings, got " << llvm::size(op.indexings());
1004   unsigned index = 0;
1005   for (auto indexing : op.indexings()) {
1006     if (indexing.getType().isa<IndexType>())
1007       --rank;
1008     ++index;
1009   }
1010   if (op.getRank() != rank)
1011     return op.emitOpError() << "expected rank of the view(" << op.getRank()
1012                             << ") to be the number of ranges(" << rank << ")";
1013   return success();
1014 }
1015 
1016 Value SliceOp::getViewSource() { return view(); }
1017 
1018 //===----------------------------------------------------------------------===//
1019 // YieldOp
1020 //===----------------------------------------------------------------------===//
1021 
1022 static void print(OpAsmPrinter &p, linalg::YieldOp op) {
1023   p << op.getOperationName();
1024   if (op.getNumOperands() > 0)
1025     p << ' ' << op.getOperands();
1026   p.printOptionalAttrDict(op.getAttrs());
1027   if (op.getNumOperands() > 0)
1028     p << " : " << op.getOperandTypes();
1029 }
1030 
1031 static ParseResult parseYieldOp(OpAsmParser &parser, OperationState &result) {
1032   SmallVector<OpAsmParser::OperandType, 2> opInfo;
1033   SmallVector<Type, 2> types;
1034   llvm::SMLoc loc = parser.getCurrentLocation();
1035   return failure(parser.parseOperandList(opInfo) ||
1036                  parser.parseOptionalAttrDict(result.attributes) ||
1037                  (!opInfo.empty() && parser.parseColonTypeList(types)) ||
1038                  parser.resolveOperands(opInfo, types, loc, result.operands));
1039 }
1040 
1041 // Check the operand number and types must match the element types of the
1042 // LinalgOp interface's shaped operands.
1043 static LogicalResult verifyYield(linalg::YieldOp op,
1044                                  LinalgOp linalgOpInterface) {
1045   auto nOutputs = linalgOpInterface.getNumOutputs();
1046   if (op.getNumOperands() != nOutputs)
1047     return op.emitOpError("expected number of yield values (")
1048            << nOutputs << ") to match the number of operands of the enclosing "
1049            << "LinalgOp (" << op.getNumOperands() << ")";
1050 
1051   for (unsigned i = 0; i != nOutputs; ++i) {
1052     auto elementType =
1053         linalgOpInterface.getOutputShapedType(i).getElementType();
1054     if (op.getOperand(i).getType() != elementType)
1055       return op.emitOpError("type of yield operand ")
1056              << (i + 1) << " (" << op.getOperand(i).getType()
1057              << ") doesn't match "
1058              << "the element type of the enclosing linalg.generic op ("
1059              << elementType << ")";
1060   }
1061   return success();
1062 }
1063 
1064 static LogicalResult verify(linalg::YieldOp op) {
1065   auto *parentOp = op.getParentOp();
1066   if (parentOp->getNumRegions() != 1 || parentOp->getRegion(0).empty())
1067     return op.emitOpError("expected single non-empty parent region");
1068 
1069   if (auto linalgOp = dyn_cast<LinalgOp>(parentOp))
1070     return verifyYield(op, cast<LinalgOp>(parentOp));
1071 
1072   return op.emitOpError("expected parent op with LinalgOp interface");
1073 }
1074 
1075 /////// Operations corresponding to library calls defined with Tablegen ////////
1076 
1077 void FillOp::getEffects(
1078     SmallVectorImpl<SideEffects::EffectInstance<MemoryEffects::Effect>>
1079         &effects) {
1080   effects.emplace_back(MemoryEffects::Write::get(), output(),
1081                        SideEffects::DefaultResource::get());
1082 }
1083 
1084 static LogicalResult verify(FillOp op) {
1085   auto viewType = op.getOutputShapedType(0);
1086   auto fillType = op.value().getType();
1087   if (viewType.getElementType() != fillType)
1088     return op.emitOpError("expects fill type to match view elemental type");
1089   return success();
1090 }
1091 
1092 void CopyOp::getEffects(
1093     SmallVectorImpl<SideEffects::EffectInstance<MemoryEffects::Effect>>
1094         &effects) {
1095   effects.emplace_back(MemoryEffects::Read::get(), input(),
1096                        SideEffects::DefaultResource::get());
1097   effects.emplace_back(MemoryEffects::Write::get(), output(),
1098                        SideEffects::DefaultResource::get());
1099 }
1100 
1101 static LogicalResult verify(CopyOp op) {
1102   auto outputViewType = op.getOutputShapedType(0);
1103   auto inputViewType = op.getInputShapedType(0);
1104   if (inputViewType.getElementType() != outputViewType.getElementType())
1105     return op.emitOpError("expects views of the same type");
1106   if (inputViewType.getRank() != outputViewType.getRank())
1107     return op.emitOpError("expects views of the same rank");
1108   auto rank = op.getNumParallelLoops();
1109   auto inputPermutationMap = op.inputPermutation();
1110   if (inputPermutationMap) {
1111     if (inputPermutationMap->getNumInputs() != rank)
1112       return op.emitOpError("expects optional input_permutation map of rank ")
1113              << rank;
1114     if (!inputPermutationMap->isPermutation())
1115       return op.emitOpError(
1116           "expects optional input_permutation map to be a permutation");
1117   }
1118   auto outputPermutationMap = op.outputPermutation();
1119   if (outputPermutationMap) {
1120     if (outputPermutationMap->getNumInputs() != rank)
1121       return op.emitOpError("expects optional output_permutation map of rank ")
1122              << rank;
1123     if (!outputPermutationMap->isPermutation())
1124       return op.emitOpError(
1125           "expects optional output_permutation map to be a permutation");
1126   }
1127   if (rank == 0 && inputPermutationMap)
1128     return op.emitOpError("expected no input permutation when rank == 0");
1129   if (rank == 0 && outputPermutationMap)
1130     return op.emitOpError("expected no output permutation when rank == 0");
1131   return success();
1132 }
1133 
1134 template <typename LinalgPoolingOp>
1135 static LogicalResult verifyStrideOrDilation(LinalgPoolingOp op,
1136                                             ArrayRef<Attribute> attrs,
1137                                             bool isStride) {
1138   auto strideOrDilation = isStride ? "stride" : "dilation";
1139   if (attrs.size() != op.getNumWindowLoops())
1140     return op.emitOpError("expects num ")
1141            << strideOrDilation
1142            << "s equal to number of window dimensions: " << attrs.size()
1143            << " vs " << op.getNumWindowLoops();
1144   return success();
1145 }
1146 
1147 void ConvOp::getEffects(
1148     SmallVectorImpl<SideEffects::EffectInstance<MemoryEffects::Effect>>
1149         &effects) {
1150   effects.emplace_back(MemoryEffects::Read::get(), input(),
1151                        SideEffects::DefaultResource::get());
1152   effects.emplace_back(MemoryEffects::Read::get(), filter(),
1153                        SideEffects::DefaultResource::get());
1154   effects.emplace_back(MemoryEffects::Write::get(), output(),
1155                        SideEffects::DefaultResource::get());
1156 }
1157 
1158 static LogicalResult verify(ConvOp op) {
1159   auto oType = op.output().getType().cast<MemRefType>();
1160   auto fType = op.filter().getType().cast<MemRefType>();
1161   auto iType = op.input().getType().cast<MemRefType>();
1162   if (oType.getElementType() != iType.getElementType() ||
1163       oType.getElementType() != fType.getElementType())
1164     return op.emitOpError("expects memref elemental types to match");
1165   if (oType.getRank() != iType.getRank() || oType.getRank() != fType.getRank())
1166     return op.emitOpError("expects memref ranks to match");
1167   if (oType.getRank() <= 2)
1168     return op.emitOpError("expects memref ranks to be greater than 2");
1169   if (auto strides = op.strides()) {
1170     if (failed(
1171             verifyStrideOrDilation(op, strides->getValue(), /*isStride=*/true)))
1172       return failure();
1173   }
1174   if (auto dilations = op.dilations()) {
1175     if (failed(verifyStrideOrDilation(op, dilations->getValue(),
1176                                       /*isStride=*/false)))
1177       return failure();
1178   }
1179   return success();
1180 }
1181 
1182 template <typename PoolingOp>
1183 static LogicalResult verifySingleInputPoolingOp(PoolingOp op) {
1184   auto inputType = op.input().getType().template cast<MemRefType>();
1185   auto outputType = op.output().getType().template cast<MemRefType>();
1186   if (outputType.getElementType() != inputType.getElementType())
1187     return op.emitOpError("expects memref elemental types to match");
1188 
1189   auto windowDimsType = op.windowDims().getType().template cast<MemRefType>();
1190   if (outputType.getRank() != inputType.getRank() ||
1191       outputType.getRank() != windowDimsType.getRank())
1192     return op.emitOpError("expects memref ranks to match");
1193 
1194   if (auto strides = op.strides()) {
1195     if (failed(
1196             verifyStrideOrDilation(op, strides->getValue(), /*isStride=*/true)))
1197       return failure();
1198   }
1199   if (auto dilations = op.dilations()) {
1200     if (failed(verifyStrideOrDilation(op, dilations->getValue(),
1201                                       /*isStride=*/false)))
1202       return failure();
1203   }
1204   return success();
1205 }
1206 
1207 #define DEFINE_POOLING_OP_GET_EFFECTS(OP_NAME)                                 \
1208   void OP_NAME::getEffects(                                                    \
1209       SmallVectorImpl<SideEffects::EffectInstance<MemoryEffects::Effect>>      \
1210           &effects) {                                                          \
1211     effects.emplace_back(MemoryEffects::Read::get(), input(),                  \
1212                          SideEffects::DefaultResource::get());                 \
1213     effects.emplace_back(MemoryEffects::Write::get(), output(),                \
1214                          SideEffects::DefaultResource::get());                 \
1215   }
1216 
1217 static LogicalResult verify(PoolingMaxOp op) {
1218   return verifySingleInputPoolingOp(op);
1219 }
1220 static LogicalResult verify(PoolingMinOp op) {
1221   return verifySingleInputPoolingOp(op);
1222 }
1223 static LogicalResult verify(PoolingSumOp op) {
1224   return verifySingleInputPoolingOp(op);
1225 }
1226 
1227 DEFINE_POOLING_OP_GET_EFFECTS(PoolingMaxOp)
1228 DEFINE_POOLING_OP_GET_EFFECTS(PoolingMinOp)
1229 DEFINE_POOLING_OP_GET_EFFECTS(PoolingSumOp)
1230 
1231 namespace {
1232 struct EraseDeadLinalgOp;
1233 struct FoldTensorCastOp;
1234 } // namespace
1235 
1236 #include "mlir/Dialect/Linalg/IR/LinalgStructuredOpsInterfaces.cpp.inc"
1237 
1238 #include "mlir/Dialect/Linalg/IR/LinalgNamedStructuredOps.cpp.inc"
1239 
1240 #define GET_OP_CLASSES
1241 #include "mlir/Dialect/Linalg/IR/LinalgOps.cpp.inc"
1242 
1243 #define GET_OP_CLASSES
1244 #include "mlir/Dialect/Linalg/IR/LinalgStructuredOps.cpp.inc"
1245 
1246 /// Return the dims that are `iteratorTypeName` loops in the LinalgOp `op`.
1247 /// Assumes `op` is a LinalgOp.
1248 void mlir::linalg::getDimsOfType(Operation *op, StringRef iteratorTypeName,
1249                                  SmallVectorImpl<AffineExpr> &res) {
1250   if (!cast<LinalgOp>(op).iterator_types())
1251     return;
1252 
1253   unsigned dim = 0;
1254   MLIRContext *ctx = op->getContext();
1255   for (auto tn :
1256        cast<LinalgOp>(op).iterator_types().getAsValueRange<StringAttr>()) {
1257     if (tn == iteratorTypeName)
1258       res.push_back(getAffineDimExpr(dim, ctx));
1259     ++dim;
1260   }
1261 }
1262 
1263 AffineMap mlir::linalg::extractOrIdentityMap(Optional<AffineMap> maybeMap,
1264                                              unsigned rank,
1265                                              MLIRContext *context) {
1266   if (maybeMap)
1267     return maybeMap.getValue();
1268   if (rank == 0)
1269     return AffineMap::get(context);
1270   return AffineMap::getMultiDimIdentityMap(rank, context);
1271 }
1272 
1273 SmallVector<AffineExpr, 4>
1274 mlir::linalg::makeAffineDimExprs(unsigned num, unsigned &startIdx,
1275                                  MLIRContext *context) {
1276   SmallVector<AffineExpr, 4> res;
1277   res.reserve(num);
1278   for (unsigned i = 0; i < num; ++i)
1279     res.push_back(getAffineDimExpr(startIdx++, context));
1280   return res;
1281 }
1282 
1283 template <typename PoolingOp>
1284 SmallVector<AffineExpr, 4>
1285 mlir::linalg::weightedPoolingInputIndex(PoolingOp op,
1286                                         ArrayRef<AffineExpr> outputDims,
1287                                         ArrayRef<AffineExpr> windowDims) {
1288   assert(outputDims.size() == windowDims.size());
1289   SmallVector<AffineExpr, 4> res;
1290   res.reserve(outputDims.size());
1291   for (unsigned i = 0, e = outputDims.size(); i < e; ++i) {
1292     // TODO: add a level of indirection to linalg.generic.
1293     auto expr = op.getStride(i) * outputDims[i] +
1294                 op.getDilation(i) * windowDims[i] - op.getLowPad(i);
1295     res.push_back(expr);
1296   }
1297   return res;
1298 }
1299 
1300 #define INSTANTIATE_WEIGHTED_POOLING_INPUT_INDEX(OP_TYPE)                      \
1301   template SmallVector<AffineExpr, 4>                                          \
1302   mlir::linalg::weightedPoolingInputIndex<OP_TYPE>(                            \
1303       OP_TYPE op, ArrayRef<AffineExpr> outputDims,                             \
1304       ArrayRef<AffineExpr> windowDims);
1305 
1306 INSTANTIATE_WEIGHTED_POOLING_INPUT_INDEX(ConvOp)
1307 INSTANTIATE_WEIGHTED_POOLING_INPUT_INDEX(PoolingMaxOp)
1308 INSTANTIATE_WEIGHTED_POOLING_INPUT_INDEX(PoolingMinOp)
1309 INSTANTIATE_WEIGHTED_POOLING_INPUT_INDEX(PoolingSumOp)
1310 
1311 SmallVector<AffineExpr, 4> mlir::linalg::concat(ArrayRef<AffineExpr> a,
1312                                                 ArrayRef<AffineExpr> b) {
1313   auto rangeA = llvm::make_range(a.begin(), a.end());
1314   auto rangeB = llvm::make_range(b.begin(), b.end());
1315   auto concatRanges = llvm::concat<const AffineExpr>(rangeA, rangeB);
1316   return llvm::to_vector<4>(concatRanges);
1317 }
1318 
1319 static void appendMangledType(llvm::raw_string_ostream &ss, Type t) {
1320   if (auto memref = t.dyn_cast<MemRefType>()) {
1321     ss << "view";
1322     for (auto size : memref.getShape())
1323       if (size < 0)
1324         ss << "sx";
1325       else
1326         ss << size << "x";
1327     appendMangledType(ss, memref.getElementType());
1328   } else if (auto vec = t.dyn_cast<VectorType>()) {
1329     ss << "vector";
1330     llvm::interleave(
1331         vec.getShape(), [&](int64_t i) { ss << i; }, [&]() { ss << "x"; });
1332     appendMangledType(ss, vec.getElementType());
1333   } else if (t.isSignlessIntOrIndexOrFloat()) {
1334     ss << t;
1335   } else {
1336     llvm_unreachable("Invalid type for linalg library name mangling");
1337   }
1338 }
1339 
1340 std::string mlir::linalg::generateLibraryCallName(Operation *op) {
1341   assert(isa<LinalgOp>(op));
1342   std::string name(op->getName().getStringRef().str());
1343   name.reserve(128);
1344   std::replace(name.begin(), name.end(), '.', '_');
1345   llvm::raw_string_ostream ss(name);
1346   ss << "_";
1347   auto types = op->getOperandTypes();
1348   llvm::interleave(
1349       types.begin(), types.end(), [&](Type t) { appendMangledType(ss, t); },
1350       [&]() { ss << "_"; });
1351   return ss.str();
1352 }
1353 
1354 // TODO: Consider making all this boilerplate easy to autogenerate
1355 // with Tablegen. This seems a desirable property in the context of
1356 // OpInterfaces where a Linalg "named" op **isa** LinalgOp.
1357 OpFoldResult ReshapeOp::fold(ArrayRef<Attribute> operands) {
1358   if (succeeded(foldMemRefCast(*this)))
1359     return getResult();
1360   return foldReshapeOp(*this, operands);
1361 }
1362 OpFoldResult SliceOp::fold(ArrayRef<Attribute>) {
1363   if (succeeded(foldMemRefCast(*this)))
1364     return getResult();
1365   return {};
1366 }
1367 OpFoldResult TensorReshapeOp::fold(ArrayRef<Attribute> operands) {
1368   return foldReshapeOp(*this, operands);
1369 }
1370 
1371 //===----------------------------------------------------------------------===//
1372 // Auto-generated Linalg named ops.
1373 //===----------------------------------------------------------------------===//
1374 
1375 template <typename NamedStructuredOpType>
1376 static void buildNamedStructuredOpRegionAndAttributesImpl(
1377     OpBuilder &opBuilder, Region &region, TypeRange inputTypes,
1378     TypeRange outputBufferTypes, TypeRange initTensorTypes,
1379     TypeRange resultTypes,
1380     std::function<void(unsigned, unsigned)> errorHandler) {
1381   // TODO: atm all operands go through getElementTypeOrSelf,
1382   // reconsider when we have evidence we need to.
1383   SmallVector<Type, 8> argTypes;
1384   for (auto containers : {inputTypes, outputBufferTypes, resultTypes})
1385     for (auto t : containers)
1386       argTypes.push_back(getElementTypeOrSelf(t));
1387 
1388   // RAII.
1389   OpBuilder::InsertionGuard guard(opBuilder);
1390   Block *body = opBuilder.createBlock(&region, {}, argTypes);
1391   unsigned actual = body->getNumArguments();
1392   unsigned expected = NamedStructuredOpType::getNumRegionArgs();
1393   if (expected != actual)
1394     return errorHandler(expected, actual);
1395 
1396   opBuilder.setInsertionPointToStart(body);
1397   mlir::edsc::ScopedContext scope(opBuilder, opBuilder.getUnknownLoc());
1398   NamedStructuredOpType::regionBuilder(*body);
1399 
1400   // indexing_maps is an auto-generated method.
1401 
1402   // iterator_types is an auto-generated method.
1403 }
1404 
1405 template <typename NamedStructuredOpType>
1406 void buildNamedStructuredOpRegionAndAttributes(OpBuilder &opBuilder,
1407                                                OperationState &result,
1408                                                TypeRange inputTypes,
1409                                                TypeRange outputBufferTypes,
1410                                                TypeRange initTensorTypes,
1411                                                TypeRange resultTypes) {
1412   Region &region = *result.addRegion();
1413   buildNamedStructuredOpRegionAndAttributesImpl<NamedStructuredOpType>(
1414       opBuilder, region, inputTypes, outputBufferTypes, initTensorTypes,
1415       resultTypes, [&](unsigned expected, unsigned actual) {
1416         llvm::errs() << "region expects " << expected << " args, got "
1417                      << actual;
1418         assert(expected != actual && "incorrect number of arguments");
1419       });
1420 }
1421 
1422 template <typename NamedStructuredOpType>
1423 static ParseResult
1424 parseNamedStructuredOpRegion(OpAsmParser &parser, Region &region,
1425                              TypeRange inputTypes, TypeRange outputBufferTypes,
1426                              TypeRange initTensorTypes, TypeRange resultTypes) {
1427   ParseResult res = success();
1428   OpBuilder opBuilder(parser.getBuilder().getContext());
1429   buildNamedStructuredOpRegionAndAttributesImpl<NamedStructuredOpType>(
1430       opBuilder, region, inputTypes, outputBufferTypes, initTensorTypes,
1431       resultTypes, [&](unsigned expected, unsigned actual) {
1432         res = parser.emitError(parser.getCurrentLocation(),
1433                                llvm::formatv("region expects {0} args, got {1}",
1434                                              expected, actual));
1435       });
1436   return res;
1437 }
1438 
1439 static ParseResult
1440 parseNamedStructuredOpResults(OpAsmParser &parser,
1441                               SmallVectorImpl<Type> &resultTypes) {
1442   if (succeeded(parser.parseOptionalArrow()))
1443     if (parser.parseTypeList(resultTypes))
1444       return failure();
1445   return success();
1446 }
1447 
1448 static ParseResult
1449 parseCommonStructuredOpParts(OpAsmParser &parser, OperationState &result,
1450                              SmallVectorImpl<Type> &inputTypes,
1451                              SmallVectorImpl<Type> &outputBufferTypes,
1452                              SmallVectorImpl<Type> &initTensorTypes) {
1453   llvm::SMLoc inputsOperandsLoc, outputBuffersOperandsLoc,
1454       initTensorsOperandsLoc;
1455   SmallVector<OpAsmParser::OperandType, 4> inputsOperands,
1456       outputBuffersOperands, initTensorsOperands;
1457 
1458   parser.parseOptionalAttrDict(result.attributes);
1459 
1460   if (succeeded(parser.parseOptionalKeyword("ins"))) {
1461     if (parser.parseLParen())
1462       return failure();
1463 
1464     inputsOperandsLoc = parser.getCurrentLocation();
1465     if (parser.parseOperandList(inputsOperands) ||
1466         parser.parseColonTypeList(inputTypes) || parser.parseRParen())
1467       return failure();
1468   }
1469 
1470   if (succeeded(parser.parseOptionalKeyword("outs"))) {
1471     outputBuffersOperandsLoc = parser.getCurrentLocation();
1472     if (parser.parseLParen() ||
1473         parser.parseOperandList(outputBuffersOperands) ||
1474         parser.parseColonTypeList(outputBufferTypes) || parser.parseRParen())
1475       return failure();
1476   }
1477   if (succeeded(parser.parseOptionalKeyword("init"))) {
1478     initTensorsOperandsLoc = parser.getCurrentLocation();
1479     if (parser.parseLParen() || parser.parseOperandList(initTensorsOperands) ||
1480         parser.parseColonTypeList(initTensorTypes) || parser.parseRParen())
1481       return failure();
1482   }
1483 
1484   if (parser.resolveOperands(inputsOperands, inputTypes, inputsOperandsLoc,
1485                              result.operands) ||
1486       parser.resolveOperands(outputBuffersOperands, outputBufferTypes,
1487                              outputBuffersOperandsLoc, result.operands) ||
1488       parser.resolveOperands(initTensorsOperands, initTensorTypes,
1489                              initTensorsOperandsLoc, result.operands))
1490     return failure();
1491 
1492   result.addAttribute("operand_segment_sizes",
1493                       parser.getBuilder().getI32VectorAttr(
1494                           {static_cast<int32_t>(inputsOperands.size()),
1495                            static_cast<int32_t>(outputBuffersOperands.size()),
1496                            static_cast<int32_t>(initTensorsOperands.size())}));
1497   return success();
1498 }
1499 
1500 template <typename NamedStructuredOpType>
1501 static ParseResult parseNamedStructuredOp(OpAsmParser &parser,
1502                                           OperationState &result) {
1503   SmallVector<Type, 1> inputTypes, outputBufferTypes, initTensorTypes;
1504   if (parseCommonStructuredOpParts(parser, result, inputTypes,
1505                                    outputBufferTypes, initTensorTypes))
1506     return failure();
1507 
1508   // TODO: consider merging results parsing into region parsing.
1509   // Need to wait for declarative assembly resolution to decide.
1510   SmallVector<Type, 1> outputTensorsTypes;
1511   if (parseNamedStructuredOpResults(parser, outputTensorsTypes))
1512     return failure();
1513   result.addTypes(outputTensorsTypes);
1514 
1515   std::unique_ptr<Region> region = std::make_unique<Region>();
1516   if (parseNamedStructuredOpRegion<NamedStructuredOpType>(
1517           parser, *region, inputTypes, outputBufferTypes, initTensorTypes,
1518           outputTensorsTypes))
1519     return failure();
1520   result.addRegion(std::move(region));
1521 
1522   return success();
1523 }
1524 
1525 static void printNamedStructuredOpResults(OpAsmPrinter &p,
1526                                           TypeRange resultTypes) {
1527   if (resultTypes.empty())
1528     return;
1529   p.printOptionalArrowTypeList(resultTypes);
1530 }
1531 
1532 template <typename NamedStructuredOpType>
1533 static void printCommonStructuredOpParts(OpAsmPrinter &p,
1534                                          NamedStructuredOpType op) {
1535   if (!op.inputs().empty())
1536     p << " ins(" << op.inputs() << " : " << op.inputs().getTypes() << ")";
1537   if (!op.output_buffers().empty())
1538     p << " outs(" << op.output_buffers() << " : "
1539       << op.output_buffers().getTypes() << ")";
1540   if (!op.init_tensors().empty())
1541     p << " init(" << op.init_tensors() << " : " << op.init_tensors().getTypes()
1542       << ") ";
1543 }
1544 
1545 template <typename NamedStructuredOpType>
1546 static void printNamedStructuredOp(OpAsmPrinter &p, NamedStructuredOpType op) {
1547   p << op.getOperationName();
1548   p.printOptionalAttrDict(op.getAttrs(),
1549                           /*elidedAttrs=*/{"operand_segment_sizes"});
1550 
1551   // Printing is shared with generic ops, except for the region and
1552   // attributes.
1553   printCommonStructuredOpParts(p, op);
1554 
1555   // Results printing.
1556   printNamedStructuredOpResults(p, op.result_tensors().getTypes());
1557 
1558   // Region is elided.
1559 }
1560 
1561 template <typename NamedStructuredOpType>
1562 static LogicalResult verifyNamedStructuredOp(NamedStructuredOpType op) {
1563   return verifyGenericOp<NamedStructuredOpType>(op);
1564 }
1565 
1566 namespace {
1567 struct EraseDeadLinalgOp : public RewritePattern {
1568   EraseDeadLinalgOp(PatternBenefit benefit = 1)
1569       : RewritePattern(benefit, MatchAnyOpTypeTag()) {}
1570 
1571   LogicalResult matchAndRewrite(Operation *op,
1572                                 PatternRewriter &rewriter) const override {
1573     auto linalgOp = dyn_cast<LinalgOp>(op);
1574     if (!linalgOp)
1575       return failure();
1576     for (Value v : linalgOp.getInputsAndOutputBuffers()) {
1577       // Linalg "inputs" may be either tensor or memref type.
1578       // tensor<0xelt_type> is a convention that may not always mean
1579       // "0 iterations". Only erase in cases we see memref<...x0x...>.
1580       auto mt = v.getType().dyn_cast<MemRefType>();
1581       if (!mt)
1582         continue;
1583       if (llvm::is_contained(mt.getShape(), 0)) {
1584         rewriter.eraseOp(linalgOp);
1585         return success();
1586       }
1587     }
1588     return failure();
1589   }
1590 };
1591 
1592 struct FoldTensorCastOp : public RewritePattern {
1593   FoldTensorCastOp(PatternBenefit benefit = 1)
1594       : RewritePattern(benefit, MatchAnyOpTypeTag()) {}
1595 
1596   LogicalResult matchAndRewrite(Operation *op,
1597                                 PatternRewriter &rewriter) const override {
1598     auto linalgOp = dyn_cast<LinalgOp>(op);
1599     if (!linalgOp)
1600       return failure();
1601 
1602     // If no operand comes from a TensorCastOp and can be folded then fail.
1603     bool hasTensorCastOperand =
1604         llvm::any_of(linalgOp.getShapedOperands(), [&](Value v) {
1605           if (v.isa<BlockArgument>())
1606             return false;
1607           auto castOp = v.getDefiningOp<TensorCastOp>();
1608           return castOp && canFoldIntoConsumerOp(castOp);
1609         });
1610     if (!hasTensorCastOperand)
1611       return failure();
1612 
1613     SmallVector<Type, 4> newResultTypes;
1614     newResultTypes.reserve(op->getNumResults());
1615     SmallVector<Value, 4> newOperands;
1616     newOperands.reserve(op->getNumOperands());
1617     // Inputs may fold.
1618     for (Value v : linalgOp.getInputs()) {
1619       auto tensorCastOp = v.getDefiningOp<TensorCastOp>();
1620       newOperands.push_back(
1621           canFoldIntoConsumerOp(tensorCastOp) ? tensorCastOp.source() : v);
1622     }
1623     // Output buffers are memrefs, they don't fold.
1624     newOperands.append(linalgOp.getOutputBuffers().begin(),
1625                        linalgOp.getOutputBuffers().end());
1626     // Init tensors may fold, in which case the resultType must also change.
1627     for (Value v : linalgOp.getInitTensors()) {
1628       auto tensorCastOp = v.getDefiningOp<TensorCastOp>();
1629       bool fold = canFoldIntoConsumerOp(tensorCastOp);
1630       newOperands.push_back(fold ? tensorCastOp.getOperand() : v);
1631       newResultTypes.push_back(newOperands.back().getType());
1632     }
1633     auto extraOperands = linalgOp.getAssumedNonShapedOperands();
1634     newOperands.append(extraOperands.begin(), extraOperands.end());
1635     // Clone op.
1636     Operation *newOp =
1637         linalgOp.clone(rewriter, op->getLoc(), newResultTypes, newOperands);
1638     rewriter.replaceOp(op, newOp->getResults());
1639 
1640     return success();
1641   }
1642 };
1643 } // namespace
1644 
1645 namespace {
1646 // Deduplicate redundant args of a linalg op.
1647 // An arg is redundant if it has the same Value and indexing map as another.
1648 struct DeduplicateInputs : public RewritePattern {
1649   DeduplicateInputs(PatternBenefit benefit = 1)
1650       : RewritePattern(benefit, MatchAnyOpTypeTag()) {}
1651 
1652   LogicalResult matchAndRewrite(Operation *op,
1653                                 PatternRewriter &rewriter) const override {
1654     // This pattern reduces the number of arguments of an op, which breaks
1655     // the invariants of semantically charged named ops.
1656     if (!isa<GenericOp, IndexedGenericOp>(op))
1657       return failure();
1658     auto linalgOp = cast<LinalgOp>(op);
1659 
1660     // Associate each input to an equivalent "canonical" input that has the same
1661     // Value and indexing map.
1662     //
1663     // In the non-duplicate case, input `i` will have canonical input `i`. But
1664     // in the case of duplicated inputs, the canonical input could be some other
1665     // input `< i`. That is, a later input will have some earlier input as its
1666     // canonical input.
1667     llvm::SmallDenseMap<std::pair<Value, AffineMap>, int> canonicalInput;
1668     // For later remapping tasks like deduplicating payload block arguments,
1669     // having a simple "inputIndex -> canonicalInputIndex" integer mapping is
1670     // convenient.
1671     SmallVector<int, 6> canonicalInputIndices;
1672     for (int i = 0, e = linalgOp.getNumInputs(); i != e; i++) {
1673       Value input = linalgOp.getInput(i);
1674       AffineMap indexingMap = linalgOp.getInputIndexingMap(i);
1675       // STL-like maps have a convenient behavior for our use case here. In the
1676       // case of duplicate keys, the insertion is rejected, and the returned
1677       // iterator gives access to the value already in the map.
1678       auto pair = canonicalInput.insert({{input, indexingMap}, i});
1679       canonicalInputIndices.push_back(pair.first->second);
1680     }
1681 
1682     // If there are no duplicate args, then bail out.
1683     if (canonicalInput.size() == linalgOp.getNumInputs())
1684       return failure();
1685 
1686     // The operands for the newly canonicalized op.
1687     SmallVector<Value, 6> newOperands;
1688     for (auto v : llvm::enumerate(linalgOp.getInputs()))
1689       if (canonicalInputIndices[v.index()] == static_cast<int>(v.index()))
1690         newOperands.push_back(v.value());
1691     llvm::append_range(newOperands, linalgOp.getOutputBuffers());
1692     llvm::append_range(newOperands, linalgOp.getInitTensors());
1693     llvm::append_range(newOperands, linalgOp.getAssumedNonShapedOperands());
1694 
1695     // Clone the old op with new operands.
1696     Operation *newOp = linalgOp.clone(rewriter, op->getLoc(),
1697                                       op->getResultTypes(), newOperands);
1698     auto newLinalgOp = cast<LinalgOp>(newOp);
1699 
1700     // Repair the indexing maps by filtering out the ones that have been
1701     // eliminated.
1702     SmallVector<AffineMap, 6> newIndexingMaps;
1703     for (int i = 0, e = newLinalgOp.getNumInputs(); i != e; i++)
1704       if (canonicalInputIndices[i] == i)
1705         newIndexingMaps.push_back(newLinalgOp.getIndexingMap(i));
1706     for (int i = 0, e = newLinalgOp.getNumOutputs(); i != e; i++)
1707       newIndexingMaps.push_back(newLinalgOp.getOutputIndexingMap(i));
1708     newOp->setAttr("indexing_maps",
1709                    rewriter.getAffineMapArrayAttr(newIndexingMaps));
1710 
1711     // Set the number of inputs to the new value. The `clone` call above kept
1712     // the value from the original op.
1713     newLinalgOp.setNumInputs(canonicalInput.size());
1714 
1715     // linalg.indexed_generic payloads have additional arguments prepended to
1716     // the block arg list. The number of such args is one per dimension of the
1717     // iteration space.
1718     int bbArgBaseOffset = 0;
1719     if (isa<IndexedGenericOp>(op))
1720       bbArgBaseOffset = newIndexingMaps[0].getNumInputs();
1721 
1722     // Repair the payload entry block by RAUW'ing redundant arguments and
1723     // erasing them.
1724     Block &payload = newOp->getRegion(0).front();
1725     for (int i = 0, e = linalgOp.getNumInputs(); i < e; i++) {
1726       // Iterate in reverse, so that we erase later args first, preventing the
1727       // argument list from shifting unexpectedly and invalidating all our
1728       // indices.
1729       int reversed = e - i - 1;
1730       int canonicalIndex = canonicalInputIndices[reversed];
1731       if (canonicalInputIndices[reversed] == reversed)
1732         continue;
1733       payload.getArgument(bbArgBaseOffset + reversed)
1734           .replaceAllUsesWith(
1735               payload.getArgument(bbArgBaseOffset + canonicalIndex));
1736       payload.eraseArgument(bbArgBaseOffset + reversed);
1737     }
1738 
1739     rewriter.replaceOp(op, newOp->getResults());
1740     return success();
1741   }
1742 };
1743 } // namespace
1744 
1745 #define CANONICALIZERS_AND_FOLDERS(XXX)                                        \
1746   void XXX::getCanonicalizationPatterns(OwningRewritePatternList &results,     \
1747                                         MLIRContext *context) {                \
1748     results.insert<EraseDeadLinalgOp>();                                       \
1749     results.insert<FoldTensorCastOp>();                                        \
1750     results.insert<DeduplicateInputs>();                                       \
1751   }                                                                            \
1752                                                                                \
1753   LogicalResult XXX::fold(ArrayRef<Attribute>,                                 \
1754                           SmallVectorImpl<OpFoldResult> &) {                   \
1755     return foldMemRefCast(*this);                                              \
1756   }
1757 
1758 CANONICALIZERS_AND_FOLDERS(ConvOp)
1759 CANONICALIZERS_AND_FOLDERS(PoolingMaxOp)
1760 CANONICALIZERS_AND_FOLDERS(PoolingMinOp)
1761 CANONICALIZERS_AND_FOLDERS(PoolingSumOp)
1762 CANONICALIZERS_AND_FOLDERS(CopyOp)
1763 CANONICALIZERS_AND_FOLDERS(FillOp)
1764 CANONICALIZERS_AND_FOLDERS(GenericOp)
1765 CANONICALIZERS_AND_FOLDERS(IndexedGenericOp)
1766 
1767 // All named ops canonicalizers and folders are auto-generated in the
1768 // .cpp.inc.
1769