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/Linalg.h"
14 
15 #include "mlir/Dialect/Arithmetic/Utils/Utils.h"
16 #include "mlir/Dialect/SCF/SCF.h"
17 #include "mlir/Dialect/Utils/ReshapeOpsUtils.h"
18 #include "mlir/Dialect/Utils/StaticValueUtils.h"
19 #include "mlir/IR/AffineExprVisitor.h"
20 #include "mlir/IR/Matchers.h"
21 #include "mlir/IR/OpImplementation.h"
22 #include "mlir/IR/PatternMatch.h"
23 #include "mlir/Interfaces/InferTypeOpInterface.h"
24 #include "mlir/Parser.h"
25 
26 #include "llvm/ADT/DenseMap.h"
27 #include "llvm/ADT/SetVector.h"
28 #include "llvm/ADT/SmallSet.h"
29 #include "llvm/ADT/StringSet.h"
30 #include "llvm/ADT/TypeSwitch.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 #include "mlir/Dialect/Linalg/IR/LinalgOpsDialect.cpp.inc"
39 
40 /// Forward declarations.
41 
42 /// Generic entry point to create the block for the region of a LinalgOp.
43 /// This is used by both named structured ops created by ods-gen and by manually
44 /// defined C++ ops.
45 /// This is used by both builders and parsers.
46 /// This function creates the block in the region with arguments corresponding
47 /// to the elemental types of `inputTypes` and `outputTypes`. The latter are
48 /// asserted to be of ShapedType.
49 template <typename NamedStructuredOpType>
50 static void fillStructuredOpRegion(
51     OpBuilder &opBuilder, Region &region, TypeRange inputTypes,
52     TypeRange outputTypes, ArrayRef<NamedAttribute> attrs,
53     llvm::function_ref<void(unsigned, unsigned)> errorHandler = nullptr);
54 
55 /// Generic entry point to create both the region and the block of a LinalgOp.
56 template <typename NamedStructuredOpType>
57 static void
58 createAndFillStructuredOpRegion(OpBuilder &opBuilder, OperationState &result,
59                                 TypeRange inputTypes, TypeRange outputTypes);
60 
61 /// Common parsing and printing used for both named structured ops created by
62 /// ods-gen and by manually defined C++ ops. Does not handle regions.
63 static ParseResult
64 parseCommonStructuredOpParts(OpAsmParser &parser, OperationState &result,
65                              SmallVectorImpl<Type> &inputTypes,
66                              SmallVectorImpl<Type> &outputTypes);
67 template <typename NamedStructuredOpType>
68 static void printCommonStructuredOpParts(OpAsmPrinter &p,
69                                          NamedStructuredOpType op);
70 
71 /// Specific parsing and printing for named structured ops created by ods-gen.
72 template <typename NamedStructuredOpType>
73 static ParseResult
74 parseNamedStructuredOpRegion(OpAsmParser &parser, Region &region,
75                              TypeRange inputTypes, TypeRange outputTypes,
76                              ArrayRef<NamedAttribute> attrs);
77 
78 static ParseResult
79 parseNamedStructuredOpResults(OpAsmParser &parser,
80                               SmallVectorImpl<Type> &resultTypes);
81 
82 template <typename NamedStructuredOpType>
83 static ParseResult parseNamedStructuredOp(OpAsmParser &parser,
84                                           OperationState &result);
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 /// This is a common class used for patterns of the form
93 /// ```
94 ///    someop(memrefcast(%src)) -> someop(%src)
95 /// ```
96 /// It folds the source of the memref.cast into the root operation directly.
97 static LogicalResult foldMemRefCast(Operation *op) {
98   bool folded = false;
99   for (OpOperand &operand : op->getOpOperands()) {
100     auto castOp = operand.get().getDefiningOp<memref::CastOp>();
101     if (castOp && memref::CastOp::canFoldIntoConsumerOp(castOp)) {
102       operand.set(castOp.getOperand());
103       folded = true;
104     }
105   }
106   return success(folded);
107 }
108 
109 /// This is a specialization of `foldMemRefCast` used for patterns of the form
110 /// ```
111 ///    tiled_loop(memrefcast(%src)) -> tiled_loop(%src)
112 /// ```
113 /// It folds the source of the memref.cast into the root operation directly.
114 static LogicalResult foldMemRefCastInTiledLoopOp(TiledLoopOp op) {
115   bool folded = false;
116   Location loc = op->getLoc();
117 
118   Block *body = op.getBody();
119   OpBuilder b = OpBuilder::atBlockBegin(body);
120 
121   // Update `input` and `output` operands and block arguments if necessary.
122   // Operands list: [lbs, ubs, steps, inputs, outputs].
123   // Block args list: [ivs, inputs, outputs].
124   for (size_t operandIndex = op.getNumControlOperands(),
125               bbArgIndex = op.getNumLoops(), e = op.getNumOperands();
126        operandIndex < e; ++operandIndex, ++bbArgIndex) {
127     OpOperand &operand = op->getOpOperand(operandIndex);
128 
129     auto castOp = operand.get().getDefiningOp<memref::CastOp>();
130     if (castOp && memref::CastOp::canFoldIntoConsumerOp(castOp)) {
131       operand.set(castOp.getOperand());
132       BlockArgument newBbArg = body->insertArgument(
133           bbArgIndex, castOp.getOperand().getType(), op.getLoc());
134       BlockArgument oldBbArg = body->getArgument(newBbArg.getArgNumber() + 1);
135 
136       // Insert memref.cast back to the original type.
137       oldBbArg.replaceAllUsesWith(
138           b.create<memref::CastOp>(loc, oldBbArg.getType(), newBbArg));
139       body->eraseArgument(oldBbArg.getArgNumber());
140 
141       folded = true;
142     }
143   }
144   return success(folded);
145 }
146 
147 //===----------------------------------------------------------------------===//
148 // Region builder helper.
149 // TODO: Move this to a utility library.
150 // The public methods on this class are referenced directly from generated code
151 // and bind by name to math and type conversion functions in the DSL as:
152 //   `arithfn__{fnName}`
153 //   `typefn__{fnName}`
154 // Examples:
155 //   `arithfn__add`
156 //   `arithfn__mul`
157 //   `typefn__cast`
158 // The naming convention is intentional in order to match snake-cased DSL names.
159 // See mlir-linalg-ods-yaml-gen.cpp for the code that mates to this class.
160 //
161 // Implementations of the math functions must be polymorphic over numeric types,
162 // internally performing necessary casts. If the function application makes no
163 // sense, then the only recourse is to assert and return nullptr. This can be
164 // extended later if it becomes possible to fail construction of the region. The
165 // invariant should be enforced at a higher level.
166 //
167 // TODO: These helpers are currently type polymorphic over the class of integer
168 // and floating point types, but they will not internally cast within bit
169 // widths of a class (mixed precision such as i8->i32) or across classes
170 // (i.e. mixed float and integer). Many such combinations are ambiguous or need
171 // to be handled with care and work is being considered to extend the op
172 // language to make such cases explicit. In the mean-time, violating this will
173 // fail verification, which is deemed acceptable.
174 //===----------------------------------------------------------------------===//
175 
176 namespace {
177 
178 class RegionBuilderHelper {
179 public:
180   RegionBuilderHelper(MLIRContext *context, Block &block)
181       : context(context), block(block) {}
182 
183   // Generates operations to cast the given operand to a specified type.
184   // If the cast cannot be performed, a warning will be issued and the
185   // operand returned as-is (which will presumably yield a verification
186   // issue downstream).
187   Value cast(Type toType, Value operand, bool isUnsignedCast) {
188     OpBuilder builder = getBuilder();
189     auto loc = operand.getLoc();
190 
191     if (operand.getType() == toType)
192       return operand;
193     if (auto toIntType = toType.dyn_cast<IntegerType>()) {
194       // If operand is floating point, cast directly to the int type.
195       if (operand.getType().isa<FloatType>()) {
196         if (isUnsignedCast)
197           return builder.create<arith::FPToUIOp>(loc, toType, operand);
198         return builder.create<arith::FPToSIOp>(loc, toType, operand);
199       }
200       // Cast index operands directly to the int type.
201       if (operand.getType().isIndex())
202         return builder.create<arith::IndexCastOp>(loc, toType, operand);
203       if (auto fromIntType = operand.getType().dyn_cast<IntegerType>()) {
204         // Either extend or truncate.
205         if (toIntType.getWidth() > fromIntType.getWidth()) {
206           if (isUnsignedCast)
207             return builder.create<arith::ExtUIOp>(loc, toType, operand);
208           return builder.create<arith::ExtSIOp>(loc, toType, operand);
209         }
210         if (toIntType.getWidth() < fromIntType.getWidth())
211           return builder.create<arith::TruncIOp>(loc, toType, operand);
212       }
213     } else if (auto toFloatType = toType.dyn_cast<FloatType>()) {
214       // If operand is integer, cast directly to the float type.
215       // Note that it is unclear how to cast from BF16<->FP16.
216       if (operand.getType().isa<IntegerType>()) {
217         if (isUnsignedCast)
218           return builder.create<arith::UIToFPOp>(loc, toFloatType, operand);
219         return builder.create<arith::SIToFPOp>(loc, toFloatType, operand);
220       }
221       if (auto fromFloatType = operand.getType().dyn_cast<FloatType>()) {
222         if (toFloatType.getWidth() > fromFloatType.getWidth())
223           return builder.create<arith::ExtFOp>(loc, toFloatType, operand);
224         if (toFloatType.getWidth() < fromFloatType.getWidth())
225           return builder.create<arith::TruncFOp>(loc, toFloatType, operand);
226       }
227     }
228 
229     emitWarning(operand.getLoc()) << "could not cast operand of type "
230                                   << operand.getType() << " to " << toType;
231     return operand;
232   }
233 
234   // NOLINTNEXTLINE(*-identifier-naming): externally called.
235   Value typefn__cast(Type toType, Value operand) {
236     return cast(toType, operand, false);
237   }
238 
239   // NOLINTNEXTLINE(*-identifier-naming): externally called.
240   Value typefn__cast_unsigned(Type toType, Value operand) {
241     return cast(toType, operand, true);
242   }
243 
244   // NOLINTNEXTLINE(*-identifier-naming): externally called.
245   Value arithfn__add(Value lhs, Value rhs) {
246     OpBuilder builder = getBuilder();
247     if (isFloatingPoint(lhs))
248       return builder.create<arith::AddFOp>(lhs.getLoc(), lhs, rhs);
249     if (isInteger(lhs))
250       return builder.create<arith::AddIOp>(lhs.getLoc(), lhs, rhs);
251     llvm_unreachable("unsupported non numeric type");
252   }
253 
254   // NOLINTNEXTLINE(*-identifier-naming): externally called.
255   Value arithfn__exp(Value x) {
256     OpBuilder builder = getBuilder();
257     if (isFloatingPoint(x))
258       return builder.create<math::ExpOp>(x.getLoc(), x);
259     llvm_unreachable("unsupported non numeric type");
260   }
261 
262   // NOLINTNEXTLINE(*-identifier-naming): externally called.
263   Value arithfn__log(Value x) {
264     OpBuilder builder = getBuilder();
265     if (isFloatingPoint(x))
266       return builder.create<math::LogOp>(x.getLoc(), x);
267     llvm_unreachable("unsupported non numeric type");
268   }
269 
270   // NOLINTNEXTLINE(*-identifier-naming): externally called.
271   Value arithfn__sub(Value lhs, Value rhs) {
272     OpBuilder builder = getBuilder();
273     if (isFloatingPoint(lhs))
274       return builder.create<arith::SubFOp>(lhs.getLoc(), lhs, rhs);
275     if (isInteger(lhs))
276       return builder.create<arith::SubIOp>(lhs.getLoc(), lhs, rhs);
277     llvm_unreachable("unsupported non numeric type");
278   }
279 
280   // NOLINTNEXTLINE(*-identifier-naming): externally called.
281   Value arithfn__mul(Value lhs, Value rhs) {
282     OpBuilder builder = getBuilder();
283     if (isFloatingPoint(lhs))
284       return builder.create<arith::MulFOp>(lhs.getLoc(), lhs, rhs);
285     if (isInteger(lhs))
286       return builder.create<arith::MulIOp>(lhs.getLoc(), lhs, rhs);
287     llvm_unreachable("unsupported non numeric type");
288   }
289 
290   // NOLINTNEXTLINE(*-identifier-naming): externally called.
291   Value arithfn__max(Value lhs, Value rhs) {
292     OpBuilder builder = getBuilder();
293     if (isFloatingPoint(lhs))
294       return builder.create<arith::MaxFOp>(lhs.getLoc(), lhs, rhs);
295     if (isInteger(lhs))
296       return builder.create<arith::MaxSIOp>(lhs.getLoc(), lhs, rhs);
297     llvm_unreachable("unsupported non numeric type");
298   }
299 
300   // NOLINTNEXTLINE(*-identifier-naming): externally called.
301   Value arithfn__max_unsigned(Value lhs, Value rhs) {
302     OpBuilder builder = getBuilder();
303     if (isFloatingPoint(lhs))
304       return builder.create<arith::MaxFOp>(lhs.getLoc(), lhs, rhs);
305     if (isInteger(lhs))
306       return builder.create<arith::MaxUIOp>(lhs.getLoc(), lhs, rhs);
307     llvm_unreachable("unsupported non numeric type");
308   }
309 
310   // NOLINTNEXTLINE(*-identifier-naming): externally called.
311   Value arithfn__min(Value lhs, Value rhs) {
312     OpBuilder builder = getBuilder();
313     if (isFloatingPoint(lhs))
314       return builder.create<arith::MinFOp>(lhs.getLoc(), lhs, rhs);
315     if (isInteger(lhs))
316       return builder.create<arith::MinSIOp>(lhs.getLoc(), lhs, rhs);
317     llvm_unreachable("unsupported non numeric type");
318   }
319 
320   // NOLINTNEXTLINE(*-identifier-naming): externally called.
321   Value arithfn__min_unsigned(Value lhs, Value rhs) {
322     OpBuilder builder = getBuilder();
323     if (isFloatingPoint(lhs))
324       return builder.create<arith::MinFOp>(lhs.getLoc(), lhs, rhs);
325     if (isInteger(lhs))
326       return builder.create<arith::MinUIOp>(lhs.getLoc(), lhs, rhs);
327     llvm_unreachable("unsupported non numeric type");
328   }
329 
330   void yieldOutputs(ValueRange values) {
331     assert(!values.empty() && "linalg ops must yield outputs");
332     if (values.empty())
333       return;
334     Value first = values.front();
335     OpBuilder builder = getBuilder();
336     builder.create<YieldOp>(first.getLoc(), values);
337   }
338 
339   Value constant(const std::string &value) {
340     OpBuilder builder = getBuilder();
341     Location loc = builder.getUnknownLoc();
342     Attribute valueAttr = parseAttribute(value, builder.getContext());
343     return builder.create<arith::ConstantOp>(loc, valueAttr.getType(),
344                                              valueAttr);
345   }
346 
347   Value index(int64_t dim) {
348     OpBuilder builder = getBuilder();
349     return builder.create<IndexOp>(builder.getUnknownLoc(), dim);
350   }
351 
352   Type getIntegerType(unsigned width) {
353     return IntegerType::get(context, width);
354   }
355 
356   Type getFloat32Type() { return Float32Type::get(context); }
357 
358   Type getFloat64Type() { return Float64Type::get(context); }
359 
360 private:
361   MLIRContext *context;
362   Block &block;
363 
364   bool isFloatingPoint(Value value) { return value.getType().isa<FloatType>(); }
365   bool isInteger(Value value) { return value.getType().isa<IntegerType>(); }
366 
367   OpBuilder getBuilder() {
368     OpBuilder builder(context);
369     builder.setInsertionPointToEnd(&block);
370     return builder;
371   }
372 };
373 
374 } // namespace
375 
376 //===----------------------------------------------------------------------===//
377 // FillOp
378 //===----------------------------------------------------------------------===//
379 void FillOp::regionBuilder(ImplicitLocOpBuilder &b, Block &block,
380                            ArrayRef<NamedAttribute> attrs) {
381   assert(block.getNumArguments() == 2 && "FillOp regionBuilder expects 2 args");
382   b.create<linalg::YieldOp>(block.getArgument(0));
383 }
384 
385 void FillOp::build(OpBuilder &builder, OperationState &result, Value value,
386                    Value output) {
387   build(builder, result, output.getType().dyn_cast<RankedTensorType>(), value,
388         output);
389   fillStructuredOpRegion<FillOp>(
390       builder, *result.regions.front(), TypeRange{value.getType()},
391       TypeRange{output.getType()}, result.attributes.getAttrs(), {});
392 }
393 
394 ParseResult parseFillOpRegion(OpAsmParser &parser, Region &r, Type valueType,
395                               Type outputType) {
396   OpBuilder opBuilder(parser.getContext());
397   fillStructuredOpRegion<FillOp>(opBuilder, r, TypeRange{valueType},
398                                  TypeRange{outputType}, {});
399   return success();
400 }
401 
402 /// FillOp region is elided when printing.
403 void printFillOpRegion(OpAsmPrinter &, Operation *, Region &, Type, Type) {}
404 
405 LogicalResult FillOp::verify() {
406   OpOperand *output = getOutputOperand(0);
407   Type fillType = value().getType();
408   if (getElementTypeOrSelf(output->get()) != fillType)
409     return emitOpError("expects fill type to match view elemental type");
410   return success();
411 }
412 
413 void FillOp::getEffects(
414     SmallVectorImpl<SideEffects::EffectInstance<MemoryEffects::Effect>>
415         &effects) {
416   if (output().getType().isa<MemRefType>())
417     effects.emplace_back(MemoryEffects::Write::get(), output(),
418                          SideEffects::DefaultResource::get());
419 }
420 
421 namespace {
422 
423 /// Fold linalg.fill -> tensor.expand/collapse_shape chain.
424 ///
425 /// For such op chains, we can create new linalg.fill ops with the result
426 /// type of the tensor.expand/collapse_shape op.
427 template <typename TensorReshapeOp>
428 struct FoldFillWithTensorReshape : OpRewritePattern<TensorReshapeOp> {
429   using OpRewritePattern<TensorReshapeOp>::OpRewritePattern;
430   LogicalResult matchAndRewrite(TensorReshapeOp reshapeOp,
431                                 PatternRewriter &rewriter) const override {
432     auto oldFill = reshapeOp.src().template getDefiningOp<FillOp>();
433     if (!oldFill)
434       return failure();
435 
436     Location loc = oldFill.getLoc();
437     auto newInit = rewriter.create<TensorReshapeOp>(
438         loc, reshapeOp.getResultType(), oldFill.output(),
439         reshapeOp.reassociation());
440     rewriter.replaceOpWithNewOp<FillOp>(reshapeOp, oldFill.value(), newInit);
441 
442     return success();
443   }
444 };
445 
446 /// Fold tensor.pad(linalg.fill) into linalg.fill if the padding value and the
447 /// filling value are the same.
448 struct FoldFillWithPad final : public OpRewritePattern<tensor::PadOp> {
449   using OpRewritePattern::OpRewritePattern;
450 
451   LogicalResult matchAndRewrite(tensor::PadOp padOp,
452                                 PatternRewriter &rewriter) const override {
453     auto fillOp = padOp.source().getDefiningOp<linalg::FillOp>();
454     if (!fillOp)
455       return failure();
456 
457     // We can only fold if the padding value is the same as the original
458     // filling value.
459     Value padValue = padOp.getConstantPaddingValue();
460     if (!padValue || fillOp.value() != padValue)
461       return failure();
462 
463     ReifiedRankedShapedTypeDims reifiedShape;
464     ReifyRankedShapedTypeOpInterface interface =
465         cast<ReifyRankedShapedTypeOpInterface>(padOp.getOperation());
466     if (failed(interface.reifyResultShapes(rewriter, reifiedShape)))
467       return rewriter.notifyMatchFailure(
468           padOp, "failed to reify tensor.pad op result shape");
469 
470     auto oldResultType = padOp.getResultType();
471     SmallVector<int64_t, 4> staticShape(oldResultType.getRank(),
472                                         ShapedType::kDynamicSize);
473     auto newInitOp = rewriter.create<InitTensorOp>(
474         padOp.getLoc(), reifiedShape.front(), staticShape,
475         oldResultType.getElementType());
476     auto newFillOp =
477         rewriter.create<FillOp>(fillOp.getLoc(), padValue, newInitOp);
478     rewriter.replaceOpWithNewOp<tensor::CastOp>(padOp, oldResultType,
479                                                 newFillOp.result());
480 
481     return success();
482   }
483 };
484 
485 } // namespace
486 
487 void FillOp::getCanonicalizationPatterns(RewritePatternSet &results,
488                                          MLIRContext *context) {
489   results
490       .add<FoldFillWithPad, FoldFillWithTensorReshape<tensor::CollapseShapeOp>,
491            FoldFillWithTensorReshape<tensor::ExpandShapeOp>>(context);
492 }
493 
494 //===----------------------------------------------------------------------===//
495 // GenericOps
496 //===----------------------------------------------------------------------===//
497 void GenericOp::build(
498     OpBuilder &builder, OperationState &result, TypeRange resultTensorTypes,
499     ValueRange inputs, ValueRange outputs, ArrayRef<AffineMap> indexingMaps,
500     ArrayRef<StringRef> iteratorTypes, StringRef doc, StringRef libraryCall,
501     function_ref<void(OpBuilder &, Location, ValueRange)> bodyBuild,
502     ArrayRef<NamedAttribute> attributes) {
503   build(builder, result, resultTensorTypes, inputs, outputs,
504         builder.getAffineMapArrayAttr(indexingMaps),
505         builder.getStrArrayAttr(iteratorTypes),
506         doc.empty() ? StringAttr() : builder.getStringAttr(doc),
507         libraryCall.empty() ? StringAttr()
508                             : builder.getStringAttr(libraryCall));
509   result.addAttributes(attributes);
510   if (!bodyBuild)
511     return;
512 
513   SmallVector<Type, 4> blockArgTypes;
514   SmallVector<Location, 4> blockArgLocs;
515   for (ValueRange container : {inputs, outputs}) {
516     for (Value v : container) {
517       blockArgTypes.push_back(getElementTypeOrSelf(v));
518       blockArgLocs.push_back(v.getLoc());
519     }
520   }
521 
522   OpBuilder::InsertionGuard guard(builder);
523   auto &region = *result.regions.front();
524   Block *bodyBlock =
525       builder.createBlock(&region, region.end(), blockArgTypes, blockArgLocs);
526   bodyBuild(builder, result.location, bodyBlock->getArguments());
527 }
528 
529 void GenericOp::build(
530     OpBuilder &builder, OperationState &result, ValueRange inputs,
531     ValueRange outputs, ArrayRef<AffineMap> indexingMaps,
532     ArrayRef<StringRef> iteratorTypes, StringRef doc, StringRef libraryCall,
533     function_ref<void(OpBuilder &, Location, ValueRange)> bodyBuild,
534     ArrayRef<NamedAttribute> attributes) {
535   build(builder, result, TypeRange{}, inputs, outputs, indexingMaps,
536         iteratorTypes, doc, libraryCall, bodyBuild, attributes);
537 }
538 
539 void GenericOp::build(
540     OpBuilder &builder, OperationState &result, ValueRange inputs,
541     ValueRange outputs, ArrayRef<AffineMap> indexingMaps,
542     ArrayRef<StringRef> iteratorTypes,
543     function_ref<void(OpBuilder &, Location, ValueRange)> bodyBuild,
544     ArrayRef<NamedAttribute> attributes) {
545   build(builder, result, inputs, outputs, indexingMaps, iteratorTypes,
546         /*doc=*/"",
547         /*libraryCall=*/"", bodyBuild, attributes);
548 }
549 
550 void GenericOp::build(
551     OpBuilder &builder, OperationState &result, TypeRange resultTensorTypes,
552     ValueRange inputs, ValueRange outputs, ArrayRef<AffineMap> indexingMaps,
553     ArrayRef<StringRef> iteratorTypes,
554     function_ref<void(OpBuilder &, Location, ValueRange)> bodyBuild,
555     ArrayRef<NamedAttribute> attributes) {
556   build(builder, result, resultTensorTypes, inputs, outputs, indexingMaps,
557         iteratorTypes,
558         /*doc=*/"",
559         /*libraryCall=*/"", bodyBuild, attributes);
560 }
561 
562 void GenericOp::print(OpAsmPrinter &p) {
563   p << " ";
564 
565   // Print extra attributes.
566   auto genericAttrNames = linalgTraitAttrNames();
567 
568   llvm::StringSet<> genericAttrNamesSet;
569   genericAttrNamesSet.insert(genericAttrNames.begin(), genericAttrNames.end());
570   SmallVector<NamedAttribute, 8> genericAttrs;
571   for (auto attr : (*this)->getAttrs())
572     if (genericAttrNamesSet.count(attr.getName().strref()) > 0)
573       genericAttrs.push_back(attr);
574   if (!genericAttrs.empty()) {
575     auto genericDictAttr = DictionaryAttr::get(getContext(), genericAttrs);
576     p << genericDictAttr;
577   }
578 
579   // Printing is shared with named ops, except for the region and attributes
580   printCommonStructuredOpParts(p, *this);
581 
582   genericAttrNames.push_back("operand_segment_sizes");
583   genericAttrNamesSet.insert(genericAttrNames.back());
584 
585   bool hasExtraAttrs = false;
586   for (NamedAttribute n : (*this)->getAttrs()) {
587     if ((hasExtraAttrs = !genericAttrNamesSet.contains(n.getName().strref())))
588       break;
589   }
590   if (hasExtraAttrs) {
591     p << " attrs = ";
592     p.printOptionalAttrDict((*this)->getAttrs(),
593                             /*elidedAttrs=*/genericAttrNames);
594   }
595 
596   // Print region.
597   if (!region().empty()) {
598     p << ' ';
599     p.printRegion(region());
600   }
601 
602   // Print results.
603   printNamedStructuredOpResults(p, result_tensors().getTypes());
604 }
605 
606 ParseResult GenericOp::parse(OpAsmParser &parser, OperationState &result) {
607   DictionaryAttr dictAttr;
608   // Parse the core linalg traits that must check into a dictAttr.
609   // The name is unimportant as we will overwrite result.attributes.
610   // The core linalg traits must contain the information necessary to pass the
611   // verifier.
612   if (parser.parseAttribute(dictAttr, "_", result.attributes))
613     return failure();
614   result.attributes.assign(dictAttr.getValue().begin(),
615                            dictAttr.getValue().end());
616 
617   // Parsing is shared with named ops, except for the region.
618   SmallVector<Type, 1> inputTypes, outputTypes;
619   if (parseCommonStructuredOpParts(parser, result, inputTypes, outputTypes))
620     return failure();
621 
622   // Optional attributes may be added.
623   if (succeeded(parser.parseOptionalKeyword("attrs")))
624     if (failed(parser.parseEqual()) ||
625         failed(parser.parseOptionalAttrDict(result.attributes)))
626       return failure();
627 
628   SmallVector<OpAsmParser::OperandType, 8> regionOperands;
629   std::unique_ptr<Region> region = std::make_unique<Region>();
630   SmallVector<Type, 8> operandTypes, regionTypes;
631   if (parser.parseRegion(*region, regionOperands, regionTypes))
632     return failure();
633   result.addRegion(std::move(region));
634 
635   // Generic ops may specify that a subset of its outputs are tensors. Such
636   // outputs are specified in the result type.
637   // TODO: may need to move output parsing before region parsing.
638   // Need to wait for declarative assembly resolution to decide.
639   SmallVector<Type, 1> outputTensorsTypes;
640   if (parseNamedStructuredOpResults(parser, outputTensorsTypes))
641     return failure();
642   result.addTypes(outputTensorsTypes);
643 
644   return success();
645 }
646 
647 static void getGenericEffectsImpl(
648     SmallVectorImpl<SideEffects::EffectInstance<MemoryEffects::Effect>>
649         &effects,
650     ValueRange results, ValueRange inputBuffers, ValueRange outputs) {
651   for (Value value : results) {
652     effects.emplace_back(MemoryEffects::Allocate::get(), value,
653                          SideEffects::DefaultResource::get());
654   }
655   for (Value value : inputBuffers) {
656     effects.emplace_back(MemoryEffects::Read::get(), value,
657                          SideEffects::DefaultResource::get());
658   }
659   for (Value value : outputs) {
660     effects.emplace_back(MemoryEffects::Read::get(), value,
661                          SideEffects::DefaultResource::get());
662     effects.emplace_back(MemoryEffects::Write::get(), value,
663                          SideEffects::DefaultResource::get());
664   }
665 }
666 
667 void GenericOp::getEffects(
668     SmallVectorImpl<SideEffects::EffectInstance<MemoryEffects::Effect>>
669         &effects) {
670   SmallVector<Value> inputBuffers = getInputBufferOperands();
671   SmallVector<Value> outputBuffers = getOutputBufferOperands();
672   getGenericEffectsImpl(effects, getOperation()->getResults(), inputBuffers,
673                         outputBuffers);
674 }
675 
676 template <typename GenericOpType>
677 static LogicalResult verifyGenericOp(GenericOpType op) {
678   return success();
679 }
680 
681 LogicalResult GenericOp::verify() { return verifyGenericOp(*this); }
682 
683 namespace {
684 // Deduplicate redundant args of a linalg generic op.
685 // An arg is redundant if it has the same Value and indexing map as another.
686 struct DeduplicateGenericOpInputs : public OpRewritePattern<GenericOp> {
687   using OpRewritePattern<GenericOp>::OpRewritePattern;
688 
689   LogicalResult matchAndRewrite(GenericOp genericOp,
690                                 PatternRewriter &rewriter) const override {
691     // Associate each input to an equivalent "canonical" input that has the same
692     // Value and indexing map.
693     //
694     // In the non-duplicate case, input `i` will have canonical input `i`. But
695     // in the case of duplicated inputs, the canonical input could be some other
696     // input `< i`. That is, a later input will have some earlier input as its
697     // canonical input.
698     llvm::SmallDenseMap<std::pair<Value, AffineMap>, unsigned> canonicalInput;
699     // For later remapping tasks like deduplicating payload block arguments,
700     // having a simple "inputIndex -> canonicalInputIndex" integer mapping is
701     // convenient.
702     SmallVector<unsigned> canonicalInputIndices;
703     for (OpOperand *opOperand : genericOp.getInputOperands()) {
704       AffineMap indexingMap = genericOp.getTiedIndexingMap(opOperand);
705       // STL-like maps have a convenient behavior for our use case here. In the
706       // case of duplicate keys, the insertion is rejected, and the returned
707       // iterator gives access to the value already in the map.
708       auto pair = canonicalInput.insert(
709           {{opOperand->get(), indexingMap}, opOperand->getOperandNumber()});
710       canonicalInputIndices.push_back(pair.first->second);
711     }
712 
713     // If there are no duplicate args, then bail out.
714     if (canonicalInput.size() == genericOp.getNumInputs())
715       return failure();
716 
717     // The operands for the newly canonicalized op.
718     SmallVector<Value> newInputOperands;
719     for (OpOperand *opOperand : genericOp.getInputOperands())
720       if (canonicalInputIndices[opOperand->getOperandNumber()] ==
721           opOperand->getOperandNumber())
722         newInputOperands.push_back(opOperand->get());
723 
724     // Repair the indexing maps by filtering out the ones that have been
725     // eliminated.
726     SmallVector<AffineMap> newIndexingMaps;
727     for (OpOperand *opOperand : genericOp.getInputOperands())
728       if (canonicalInputIndices[opOperand->getOperandNumber()] ==
729           opOperand->getOperandNumber())
730         newIndexingMaps.push_back(genericOp.getTiedIndexingMap(opOperand));
731     for (OpOperand *opOperand : genericOp.getOutputOperands())
732       newIndexingMaps.push_back(genericOp.getTiedIndexingMap(opOperand));
733 
734     // Clone the old op with new operands.
735     SmallVector<Value> outputOperands = genericOp.getOutputOperands();
736     auto newOp = rewriter.create<GenericOp>(
737         genericOp.getLoc(), genericOp->getResultTypes(), newInputOperands,
738         outputOperands, rewriter.getAffineMapArrayAttr(newIndexingMaps),
739         genericOp.iterator_types(), genericOp.docAttr(),
740         genericOp.library_callAttr());
741 
742     // Copy over unknown attributes. They might be load bearing for some flow.
743     ArrayRef<StringRef> odsAttrs = genericOp.getAttributeNames();
744     for (NamedAttribute kv : genericOp->getAttrs()) {
745       if (!llvm::is_contained(odsAttrs, kv.getName().getValue())) {
746         newOp->setAttr(kv.getName(), kv.getValue());
747       }
748     }
749 
750     rewriter.inlineRegionBefore(genericOp.region(), newOp.region(),
751                                 newOp.region().begin());
752 
753     // Repair the payload entry block by RAUW'ing redundant arguments and
754     // erasing them.
755     Block &payload = newOp.region().front();
756     SmallVector<OpOperand *> inputOperands = genericOp.getInputOperands();
757     for (OpOperand *opOperand : llvm::reverse(inputOperands)) {
758       // Iterate in reverse, so that we erase later args first, preventing the
759       // argument list from shifting unexpectedly and invalidating all our
760       // indices.
761       unsigned operandNumber = opOperand->getOperandNumber();
762       if (canonicalInputIndices[operandNumber] == operandNumber)
763         continue;
764       payload.getArgument(operandNumber)
765           .replaceAllUsesWith(
766               payload.getArgument(canonicalInputIndices[operandNumber]));
767       payload.eraseArgument(operandNumber);
768     }
769 
770     rewriter.replaceOp(genericOp, newOp->getResults());
771     return success();
772   }
773 };
774 
775 /// Remove generic operations (on tensors) that are just copying
776 /// the values from inputs to the results. Requirements are
777 /// 1) All iterator types are parallel
778 /// 2) The body contains just a yield operation with the yielded values being
779 ///    the arguments corresponding to the operands.
780 struct EraseIdentityGenericOp : public OpRewritePattern<GenericOp> {
781   using OpRewritePattern<GenericOp>::OpRewritePattern;
782 
783   LogicalResult matchAndRewrite(GenericOp genericOp,
784                                 PatternRewriter &rewriter) const override {
785     // Check all indexing maps are identity.
786     if (llvm::any_of(genericOp.getIndexingMaps(),
787                      [](AffineMap map) { return !map.isIdentity(); }))
788       return failure();
789 
790     // Check that the body of the linalg operation is just a linalg.yield
791     // operation.
792     Block &body = genericOp.region().front();
793     if (!llvm::hasSingleElement(body))
794       return failure();
795     auto yieldOp = dyn_cast<linalg::YieldOp>(body.getTerminator());
796     if (!yieldOp)
797       return failure();
798 
799     // In the buffer case, we need to check exact buffer equality.
800     if (genericOp.hasBufferSemantics()) {
801       if (genericOp.getNumInputs() == 1 && genericOp.getNumOutputs() == 1 &&
802           genericOp.getInputOperand(0)->get() ==
803               genericOp.getOutputOperand(0)->get()) {
804         rewriter.eraseOp(genericOp);
805         return success();
806       }
807       return failure();
808     }
809 
810     // Get the argument number of the returned values. That is the operand
811     // number to use for replacing uses of this operation.
812     SmallVector<Value> returnedArgs;
813     for (const auto &yieldVal : llvm::enumerate(yieldOp.values())) {
814       auto yieldArg = yieldVal.value().dyn_cast<BlockArgument>();
815       if (!yieldArg || yieldArg.getOwner() != &body)
816         return failure();
817       unsigned argumentNumber = yieldArg.getArgNumber();
818       Value returnedArg = genericOp->getOperand(argumentNumber);
819       Type resultType = genericOp->getResult(yieldVal.index()).getType();
820       // The input can have a different type than the result, e.g. a dynamic
821       // input dimension can be turned into a static output dimension.
822       if (returnedArg.getType() != resultType)
823         returnedArg = rewriter.create<tensor::CastOp>(genericOp.getLoc(),
824                                                       resultType, returnedArg);
825       returnedArgs.push_back(returnedArg);
826     }
827 
828     if (returnedArgs.size() != genericOp->getNumResults())
829       return failure();
830     rewriter.replaceOp(genericOp, returnedArgs);
831     return success();
832   }
833 };
834 } // namespace
835 
836 void GenericOp::getCanonicalizationPatterns(RewritePatternSet &results,
837                                             MLIRContext *context) {
838   results.add<DeduplicateGenericOpInputs, EraseIdentityGenericOp>(context);
839 }
840 
841 //===----------------------------------------------------------------------===//
842 // InitTensorOp
843 //===----------------------------------------------------------------------===//
844 
845 void InitTensorOp::build(OpBuilder &b, OperationState &result,
846                          ArrayRef<OpFoldResult> sizes, Type elementType,
847                          ArrayRef<NamedAttribute> attrs) {
848   SmallVector<Value, 4> dynamicSizes;
849   SmallVector<int64_t, 4> staticSizes;
850   dispatchIndexOpFoldResults(sizes, dynamicSizes, staticSizes,
851                              ShapedType::kDynamicSize);
852   auto resultType = RankedTensorType ::get(staticSizes, elementType);
853   build(b, result, resultType, dynamicSizes, b.getI64ArrayAttr(staticSizes));
854   result.addAttributes(attrs);
855 }
856 
857 LogicalResult InitTensorOp::verify() {
858   RankedTensorType resultType = getType();
859   SmallVector<int64_t, 4> staticSizes = llvm::to_vector<4>(llvm::map_range(
860       static_sizes().cast<ArrayAttr>(),
861       [](Attribute a) -> int64_t { return a.cast<IntegerAttr>().getInt(); }));
862 
863   if (failed(verifyListOfOperandsOrIntegers(
864           *this, "sizes", resultType.getRank(), static_sizes(), sizes(),
865           ShapedType::isDynamic)))
866     return failure();
867 
868   if (static_sizes().size() != static_cast<unsigned>(resultType.getRank()))
869     return emitError("expected ") << resultType.getRank() << " sizes values";
870 
871   Type expectedType = InitTensorOp::inferResultType(
872       staticSizes, resultType.getElementType(), resultType.getEncoding());
873   if (resultType != expectedType) {
874     return emitError("specified type ")
875            << resultType << " does not match the inferred type "
876            << expectedType;
877   }
878   return success();
879 }
880 
881 Type InitTensorOp::inferResultType(ArrayRef<int64_t> staticSizes,
882                                    Type elementType, Attribute encoding) {
883   return RankedTensorType::get(staticSizes, elementType, encoding);
884 }
885 
886 namespace {
887 /// Change the type of the result of a `linalg.init_tensor` by making the result
888 /// type statically sized along dimension that in the original operation where
889 /// defined as dynamic, but the size was defined using a `constant` op. For
890 /// example
891 ///
892 ///  %c5 = arith.constant 5: index
893 ///  %0 = linalg.init_tensor [%arg0, %c5] : tensor<?x?xf32>
894 ///
895 ///  to
896 ///
897 ///  %0 = linalg.init_tensor [%arg0, 5] : tensor<?x5xf32>
898 struct ReplaceStaticShapeDims : OpRewritePattern<InitTensorOp> {
899   using OpRewritePattern<InitTensorOp>::OpRewritePattern;
900 
901   LogicalResult matchAndRewrite(InitTensorOp op,
902                                 PatternRewriter &rewriter) const override {
903     SmallVector<Value, 4> dynamicSizes;
904     SmallVector<int64_t, 4> staticSizes;
905     for (unsigned i = 0, e = op.getType().getRank(); i != e; ++i) {
906       // If the size is already static, nothing to do.
907       if (!op.isDynamicSize(i)) {
908         staticSizes.push_back(op.getStaticSize(i));
909         continue;
910       }
911 
912       // If the size is dynamic but defined using a `constant` op, get the
913       // constant value to find the static size to use.
914       unsigned operandNum = op.getIndexOfDynamicSize(i);
915       Value sizeOperand = op.getOperand(operandNum);
916       if (auto constantIndexOp =
917               sizeOperand.getDefiningOp<arith::ConstantIndexOp>()) {
918         staticSizes.push_back(constantIndexOp.value());
919         continue;
920       }
921 
922       // Fallback case. Keep the size dynamic.
923       dynamicSizes.push_back(sizeOperand);
924       staticSizes.push_back(ShapedType::kDynamicSize);
925     }
926     RankedTensorType newType =
927         RankedTensorType::get(staticSizes, op.getType().getElementType());
928     if (newType == op.getType())
929       return failure();
930     auto newOp =
931         rewriter.create<InitTensorOp>(op.getLoc(), newType, dynamicSizes,
932                                       rewriter.getI64ArrayAttr(staticSizes));
933     rewriter.replaceOpWithNewOp<tensor::CastOp>(op, op.getType(), newOp);
934     return success();
935   }
936 };
937 } // namespace
938 
939 namespace {
940 /// Since `init_tensor` operation creates a tensor needed only for its shape, a
941 /// slice of this is also needed only for its shape. The result can be
942 /// replaced by a new init_tensor operation of the same size as the extract
943 /// slice op.
944 struct FoldInitTensorWithExtractSliceOp
945     : public OpRewritePattern<tensor::ExtractSliceOp> {
946   using OpRewritePattern<tensor::ExtractSliceOp>::OpRewritePattern;
947 
948   LogicalResult matchAndRewrite(tensor::ExtractSliceOp sliceOp,
949                                 PatternRewriter &rewriter) const override {
950     if (!sliceOp.source().getDefiningOp<linalg::InitTensorOp>())
951       return failure();
952     // ExtractSliceOp may be rank-reducing; its dynamic sizes must be preserved
953     // as well as its result type.
954     rewriter.replaceOpWithNewOp<linalg::InitTensorOp>(
955         sliceOp, sliceOp.sizes(),
956         sliceOp.result().getType().cast<RankedTensorType>().getShape(),
957         sliceOp.getSourceType().getElementType());
958     return success();
959   }
960 };
961 
962 template <typename TensorReshapeOp>
963 struct FoldInitTensorWithTensorReshapeOp
964     : public OpRewritePattern<TensorReshapeOp> {
965   using OpRewritePattern<TensorReshapeOp>::OpRewritePattern;
966 
967   LogicalResult matchAndRewrite(TensorReshapeOp reshapeOp,
968                                 PatternRewriter &rewriter) const override {
969     if (!reshapeOp.src().template getDefiningOp<InitTensorOp>())
970       return failure();
971     Location loc = reshapeOp.getLoc();
972     ReifiedRankedShapedTypeDims resultShapes;
973     ReifyRankedShapedTypeOpInterface reifyShapedTypeInterface =
974         cast<ReifyRankedShapedTypeOpInterface>(reshapeOp.getOperation());
975     if (failed(reifyShapedTypeInterface.reifyResultShapes(rewriter,
976                                                           resultShapes)) ||
977         !llvm::hasSingleElement(resultShapes))
978       return failure();
979     Value initTensor = rewriter.create<InitTensorOp>(
980         loc, getAsOpFoldResult(resultShapes[0]),
981         reshapeOp.getResultType().getElementType());
982     if (initTensor.getType() != reshapeOp.getResultType()) {
983       rewriter.replaceOpWithNewOp<tensor::CastOp>(
984           reshapeOp, reshapeOp.getResultType(), initTensor);
985     } else {
986       rewriter.replaceOp(reshapeOp, initTensor);
987     }
988     return success();
989   }
990 };
991 
992 struct FoldInitTensorWithDimOp : public OpRewritePattern<tensor::DimOp> {
993   using OpRewritePattern<tensor::DimOp>::OpRewritePattern;
994 
995   LogicalResult matchAndRewrite(tensor::DimOp dimOp,
996                                 PatternRewriter &rewriter) const override {
997     Optional<int64_t> maybeConstantIndex = dimOp.getConstantIndex();
998     auto initTensorOp = dimOp.source().getDefiningOp<linalg::InitTensorOp>();
999     if (!initTensorOp || !maybeConstantIndex)
1000       return failure();
1001     if (!initTensorOp.isDynamicSize(*maybeConstantIndex))
1002       return failure();
1003     rewriter.replaceOp(dimOp, initTensorOp.getDynamicSize(*maybeConstantIndex));
1004     return success();
1005   }
1006 };
1007 } // namespace
1008 
1009 void InitTensorOp::getCanonicalizationPatterns(RewritePatternSet &results,
1010                                                MLIRContext *context) {
1011   results.add<FoldInitTensorWithDimOp, FoldInitTensorWithExtractSliceOp,
1012               FoldInitTensorWithTensorReshapeOp<tensor::ExpandShapeOp>,
1013               FoldInitTensorWithTensorReshapeOp<tensor::CollapseShapeOp>,
1014               ReplaceStaticShapeDims>(context);
1015 }
1016 
1017 LogicalResult InitTensorOp::reifyResultShapes(
1018     OpBuilder &builder, ReifiedRankedShapedTypeDims &reifiedReturnShapes) {
1019   auto shapes = llvm::to_vector<4>(llvm::map_range(
1020       llvm::seq<int64_t>(0, getType().getRank()), [&](int64_t dim) -> Value {
1021         if (isDynamicSize(dim))
1022           return getDynamicSize(dim);
1023         return builder.create<arith::ConstantIndexOp>(getLoc(),
1024                                                       getStaticSize(dim));
1025       }));
1026   reifiedReturnShapes.emplace_back(std::move(shapes));
1027   return success();
1028 }
1029 
1030 //===----------------------------------------------------------------------===//
1031 // YieldOp
1032 //===----------------------------------------------------------------------===//
1033 
1034 void linalg::YieldOp::print(OpAsmPrinter &p) {
1035   if (getNumOperands() > 0)
1036     p << ' ' << getOperands();
1037   p.printOptionalAttrDict((*this)->getAttrs());
1038   if (getNumOperands() > 0)
1039     p << " : " << getOperandTypes();
1040 }
1041 
1042 ParseResult YieldOp::parse(OpAsmParser &parser, OperationState &result) {
1043   SmallVector<OpAsmParser::OperandType, 2> opInfo;
1044   SmallVector<Type, 2> types;
1045   SMLoc loc = parser.getCurrentLocation();
1046   return failure(parser.parseOperandList(opInfo) ||
1047                  parser.parseOptionalAttrDict(result.attributes) ||
1048                  (!opInfo.empty() && parser.parseColonTypeList(types)) ||
1049                  parser.resolveOperands(opInfo, types, loc, result.operands));
1050 }
1051 
1052 // Check the operand number and types must match the element types of the
1053 // LinalgOp interface's shaped operands.
1054 static LogicalResult verifyYield(linalg::YieldOp op, LinalgOp linalgOp) {
1055   if (op.getNumOperands() != linalgOp.getNumOutputs())
1056     return op.emitOpError("expected number of yield values (")
1057            << linalgOp.getNumOutputs()
1058            << ") to match the number of operands of the enclosing "
1059            << "LinalgOp (" << op.getNumOperands() << ")";
1060 
1061   for (OpOperand &opOperand : op->getOpOperands()) {
1062     OpOperand *outputOperand =
1063         linalgOp.getOutputOperand(opOperand.getOperandNumber());
1064     Type elementType = getElementTypeOrSelf(outputOperand->get().getType());
1065     if (opOperand.get().getType() != elementType)
1066       return op.emitOpError("type of yield operand ")
1067              << (opOperand.getOperandNumber() + 1) << " ("
1068              << opOperand.get().getType() << ") doesn't match "
1069              << "the element type of the enclosing linalg.generic op ("
1070              << elementType << ")";
1071   }
1072   return success();
1073 }
1074 
1075 LogicalResult linalg::YieldOp::verify() {
1076   auto *parentOp = (*this)->getParentOp();
1077   if (parentOp->getNumRegions() != 1 || parentOp->getRegion(0).empty())
1078     return emitOpError("expected single non-empty parent region");
1079 
1080   if (auto linalgOp = dyn_cast<LinalgOp>(parentOp))
1081     return verifyYield(*this, cast<LinalgOp>(parentOp));
1082 
1083   if (auto tiledLoopOp = dyn_cast<linalg::TiledLoopOp>(parentOp)) {
1084     // Check if output args with tensor types match results types.
1085     SmallVector<Value, 2> tensorOuts;
1086     llvm::copy_if(
1087         tiledLoopOp.outputs(), std::back_inserter(tensorOuts),
1088         [&](Value out) { return out.getType().isa<RankedTensorType>(); });
1089     if (tensorOuts.size() != values().size())
1090       return emitOpError("expected number of tensor output args = ")
1091              << tensorOuts.size()
1092              << " to match the number of yield operands = " << values().size();
1093 
1094     TypeRange tensorTypes(llvm::makeArrayRef(tensorOuts));
1095     for (auto &item :
1096          llvm::enumerate(llvm::zip(tensorTypes, getOperandTypes()))) {
1097       Type outType, resultType;
1098       unsigned index = item.index();
1099       std::tie(outType, resultType) = item.value();
1100       if (outType != resultType)
1101         return emitOpError("expected yield operand ")
1102                << index << " with type = " << resultType
1103                << " to match output arg type = " << outType;
1104     }
1105     return success();
1106   }
1107   return emitOpError("expected parent op with LinalgOp interface");
1108 }
1109 
1110 //===----------------------------------------------------------------------===//
1111 // TiledLoopOp
1112 //===----------------------------------------------------------------------===//
1113 
1114 void TiledLoopOp::build(OpBuilder &builder, OperationState &result,
1115                         ValueRange lowerBounds, ValueRange upperBounds,
1116                         ValueRange steps, ValueRange inputs, ValueRange outputs,
1117                         ArrayAttr iteratorTypes,
1118                         function_ref<void(OpBuilder &, Location, ValueRange,
1119                                           ValueRange, ValueRange)>
1120                             bodyBuilderFn) {
1121   build(builder, result, lowerBounds, upperBounds, steps, inputs, outputs,
1122         iteratorTypes, llvm::None, bodyBuilderFn);
1123 }
1124 
1125 void TiledLoopOp::build(OpBuilder &builder, OperationState &result,
1126                         ValueRange lowerBounds, ValueRange upperBounds,
1127                         ValueRange steps, ValueRange inputs, ValueRange outputs,
1128                         ArrayAttr iteratorTypes,
1129                         Optional<ArrayAttr> distributionTypes,
1130                         function_ref<void(OpBuilder &, Location, ValueRange,
1131                                           ValueRange, ValueRange)>
1132                             bodyBuilderFn) {
1133   result.addOperands(lowerBounds);
1134   result.addOperands(upperBounds);
1135   result.addOperands(steps);
1136   result.addOperands(inputs);
1137   result.addOperands(outputs);
1138   result.addAttribute(
1139       TiledLoopOp::getOperandSegmentSizeAttr(),
1140       builder.getI32VectorAttr({static_cast<int32_t>(lowerBounds.size()),
1141                                 static_cast<int32_t>(upperBounds.size()),
1142                                 static_cast<int32_t>(steps.size()),
1143                                 static_cast<int32_t>(inputs.size()),
1144                                 static_cast<int32_t>(outputs.size())}));
1145   result.addAttribute(getIteratorTypesAttrName(), iteratorTypes);
1146 
1147   if (distributionTypes.hasValue())
1148     result.addAttribute(getDistributionTypesAttrName(),
1149                         distributionTypes.getValue());
1150 
1151   // Add output types for `RankedTensorType` output arguments.
1152   for (Value output : outputs) {
1153     Type outputType = output.getType();
1154     if (outputType.isa<RankedTensorType>())
1155       result.addTypes(outputType);
1156   }
1157 
1158   OpBuilder::InsertionGuard guard(builder);
1159   unsigned numIVs = steps.size();
1160   SmallVector<Type, 8> argTypes(numIVs, builder.getIndexType());
1161   SmallVector<Location, 8> argLocs(numIVs, result.location);
1162   for (Value input : inputs) {
1163     argTypes.push_back(input.getType());
1164     argLocs.push_back(input.getLoc());
1165   }
1166   for (Value output : outputs) {
1167     argTypes.push_back(output.getType());
1168     argLocs.push_back(output.getLoc());
1169   }
1170   Region *bodyRegion = result.addRegion();
1171   Block *bodyBlock = builder.createBlock(bodyRegion, {}, argTypes, argLocs);
1172 
1173   if (bodyBuilderFn) {
1174     builder.setInsertionPointToStart(bodyBlock);
1175     bodyBuilderFn(builder, result.location,
1176                   bodyBlock->getArguments().take_front(numIVs),
1177                   bodyBlock->getArguments().slice(numIVs, inputs.size()),
1178                   bodyBlock->getArguments().take_back(outputs.size()));
1179     TiledLoopOp::ensureTerminator(*bodyRegion, builder, result.location);
1180   }
1181 }
1182 
1183 void TiledLoopOp::print(OpAsmPrinter &p) {
1184   p << " (" << getInductionVars() << ") = (" << lowerBound() << ") to ("
1185     << upperBound() << ") step (" << step() << ")";
1186 
1187   if (!inputs().empty()) {
1188     p << " ins (";
1189     llvm::interleaveComma(llvm::zip(getRegionInputArgs(), inputs()), p,
1190                           [&](auto it) {
1191                             p << std::get<0>(it) << " = " << std::get<1>(it)
1192                               << ": " << std::get<1>(it).getType();
1193                           });
1194     p << ")";
1195   }
1196   if (!outputs().empty()) {
1197     p << " outs (";
1198     llvm::interleaveComma(llvm::zip(getRegionOutputArgs(), outputs()), p,
1199                           [&](auto it) {
1200                             p << std::get<0>(it) << " = " << std::get<1>(it)
1201                               << ": " << std::get<1>(it).getType();
1202                           });
1203     p << ")";
1204   }
1205 
1206   if (llvm::any_of(iterator_types(), [](Attribute attr) {
1207         return attr.cast<StringAttr>().getValue() !=
1208                getParallelIteratorTypeName();
1209       }))
1210     p << " iterators" << iterator_types();
1211 
1212   if (distribution_types().hasValue())
1213     p << " distribution" << distribution_types().getValue();
1214 
1215   p << ' ';
1216   p.printRegion(region(), /*printEntryBlockArgs=*/false);
1217   p.printOptionalAttrDict((*this)->getAttrs(), /*elidedAttrs=*/{
1218                               TiledLoopOp::getOperandSegmentSizeAttr(),
1219                               getIteratorTypesAttrName(),
1220                               getDistributionTypesAttrName()});
1221 }
1222 
1223 ParseResult TiledLoopOp::parse(OpAsmParser &parser, OperationState &result) {
1224   auto &builder = parser.getBuilder();
1225   // Parse an opening `(` followed by induction variables followed by `)`
1226   SmallVector<OpAsmParser::OperandType, 4> ivs;
1227   if (parser.parseRegionArgumentList(ivs, /*requiredOperandCount=*/-1,
1228                                      OpAsmParser::Delimiter::Paren))
1229     return failure();
1230 
1231   // Parse loop bounds.
1232   SmallVector<OpAsmParser::OperandType, 4> lower;
1233   if (parser.parseEqual() ||
1234       parser.parseOperandList(lower, ivs.size(),
1235                               OpAsmParser::Delimiter::Paren) ||
1236       parser.resolveOperands(lower, builder.getIndexType(), result.operands))
1237     return failure();
1238 
1239   SmallVector<OpAsmParser::OperandType, 4> upper;
1240   if (parser.parseKeyword("to") ||
1241       parser.parseOperandList(upper, ivs.size(),
1242                               OpAsmParser::Delimiter::Paren) ||
1243       parser.resolveOperands(upper, builder.getIndexType(), result.operands))
1244     return failure();
1245 
1246   // Parse step values.
1247   SmallVector<OpAsmParser::OperandType, 4> steps;
1248   if (parser.parseKeyword("step") ||
1249       parser.parseOperandList(steps, ivs.size(),
1250                               OpAsmParser::Delimiter::Paren) ||
1251       parser.resolveOperands(steps, builder.getIndexType(), result.operands))
1252     return failure();
1253 
1254   // Parse input tensors.
1255   SmallVector<OpAsmParser::OperandType, 4> inputs, inputRegionArgs;
1256   SmallVector<Type, 4> inputTypes;
1257   if (succeeded(parser.parseOptionalKeyword("ins"))) {
1258     SMLoc inputsOperandsLoc = parser.getCurrentLocation();
1259 
1260     if (parser.parseAssignmentListWithTypes(inputRegionArgs, inputs,
1261                                             inputTypes))
1262       return failure();
1263 
1264     if (parser.resolveOperands(inputs, inputTypes, inputsOperandsLoc,
1265                                result.operands))
1266       return failure();
1267   }
1268 
1269   // Parse output tensors.
1270   SmallVector<OpAsmParser::OperandType, 4> outputs, outputRegionArgs;
1271   SmallVector<Type, 4> outputTypes;
1272   if (succeeded(parser.parseOptionalKeyword("outs"))) {
1273     SMLoc outputsOperandsLoc = parser.getCurrentLocation();
1274 
1275     if (parser.parseAssignmentListWithTypes(outputRegionArgs, outputs,
1276                                             outputTypes))
1277       return failure();
1278 
1279     if (parser.resolveOperands(outputs, outputTypes, outputsOperandsLoc,
1280                                result.operands))
1281       return failure();
1282     for (Type outputType : outputTypes)
1283       if (outputType.isa<RankedTensorType>())
1284         result.addTypes(outputType);
1285   }
1286 
1287   // Parse attributes.
1288   SmallVector<Attribute, 4> iterTypes, distributionTypes;
1289   auto parseAttr = [&](StringRef keyword, SmallVector<Attribute, 4> *attrs) {
1290     if (succeeded(parser.parseOptionalKeyword(keyword))) {
1291       StringAttr attr;
1292 
1293       if (parser.parseLSquare() || parser.parseAttribute(attr))
1294         return failure();
1295       attrs->push_back(attr);
1296       for (int i = 1, e = ivs.size(); i < e; ++i) {
1297         if (parser.parseComma() || parser.parseAttribute(attr))
1298           return failure();
1299         attrs->push_back(attr);
1300       }
1301       if (parser.parseRSquare())
1302         return failure();
1303     }
1304     return success();
1305   };
1306   if (failed(parseAttr("iterators", &iterTypes)) ||
1307       failed(parseAttr("distribution", &distributionTypes)))
1308     return failure();
1309 
1310   // Set all loop iterator types to "parallel" if they are not printed in IR.
1311   if (iterTypes.empty()) {
1312     auto parallelIter = builder.getStringAttr(getParallelIteratorTypeName());
1313     iterTypes = SmallVector<Attribute, 4>(ivs.size(), parallelIter);
1314   }
1315   result.addAttribute(getIteratorTypesAttrName(),
1316                       builder.getArrayAttr(iterTypes));
1317   if (!distributionTypes.empty())
1318     result.addAttribute(getDistributionTypesAttrName(),
1319                         builder.getArrayAttr(distributionTypes));
1320   result.addAttribute(
1321       TiledLoopOp::getOperandSegmentSizeAttr(),
1322       builder.getI32VectorAttr({static_cast<int32_t>(lower.size()),
1323                                 static_cast<int32_t>(upper.size()),
1324                                 static_cast<int32_t>(steps.size()),
1325                                 static_cast<int32_t>(inputs.size()),
1326                                 static_cast<int32_t>(outputs.size())}));
1327 
1328   // Parse the body.
1329   Region *body = result.addRegion();
1330 
1331   SmallVector<Type, 4> regionTypes(ivs.size(), builder.getIndexType());
1332   regionTypes.append(inputTypes);
1333   regionTypes.append(outputTypes);
1334 
1335   SmallVector<OpAsmParser::OperandType, 4> regionArgs(ivs);
1336   regionArgs.append(inputRegionArgs);
1337   regionArgs.append(outputRegionArgs);
1338 
1339   if (parser.parseRegion(*body, regionArgs, regionTypes))
1340     return failure();
1341 
1342   // Parse optional attributes.
1343   parser.parseOptionalAttrDict(result.attributes);
1344 
1345   return success();
1346 }
1347 
1348 Region &TiledLoopOp::getLoopBody() { return region(); }
1349 
1350 LogicalResult TiledLoopOp::moveOutOfLoop(ArrayRef<Operation *> ops) {
1351   for (auto *op : ops)
1352     op->moveBefore(*this);
1353   return success();
1354 }
1355 
1356 bool TiledLoopOp::isDefinedOutsideOfLoop(Value value) {
1357   return !region().isAncestor(value.getParentRegion());
1358 }
1359 
1360 LogicalResult TiledLoopOp::verify() {
1361   // Check if iterator types are provided for every loop dimension.
1362   if (iterator_types().size() != getNumLoops())
1363     return emitOpError("expected iterator types array attribute size = ")
1364            << iterator_types().size()
1365            << " to match the number of loops = " << getNumLoops();
1366 
1367   // Check if types of input arguments match region args types.
1368   for (auto &item :
1369        llvm::enumerate(llvm::zip(inputs(), getRegionInputArgs()))) {
1370     Value input, inputRegionArg;
1371     unsigned index = item.index();
1372     std::tie(input, inputRegionArg) = item.value();
1373     if (input.getType() != inputRegionArg.getType())
1374       return emitOpError("expected input arg ")
1375              << index << " with type = " << input.getType()
1376              << " to match region arg " << index + getNumLoops()
1377              << " type = " << inputRegionArg.getType();
1378   }
1379 
1380   // Check if types of input arguments match region args types.
1381   for (auto &item :
1382        llvm::enumerate(llvm::zip(outputs(), getRegionOutputArgs()))) {
1383     Value output, outputRegionArg;
1384     unsigned index = item.index();
1385     std::tie(output, outputRegionArg) = item.value();
1386     if (output.getType() != outputRegionArg.getType())
1387       return emitOpError("expected output arg ")
1388              << index << " with type = " << output.getType()
1389              << " to match region arg "
1390              << index + getNumLoops() + inputs().size()
1391              << " type = " << outputRegionArg.getType();
1392   }
1393   return success();
1394 }
1395 
1396 namespace {
1397 
1398 static constexpr int64_t kNoMatch = -1;
1399 
1400 // Folds away TiledLoopOp inputs if they have no uses within the body.
1401 //
1402 // Example:
1403 //
1404 // %0 = linalg.tiled_loop ...  ins (%in_ = %in: tensor<...>,
1405 //                                  %in_buf_ = %in_buf: memref<...>) {...}
1406 // Becomes
1407 //
1408 // linalg.tiled_loop ...  ins (%in_buf_ = %in_buf: memref<...>) {...}
1409 struct TiledLoopInputsFolder : public OpRewritePattern<linalg::TiledLoopOp> {
1410   using OpRewritePattern<linalg::TiledLoopOp>::OpRewritePattern;
1411 
1412   LogicalResult matchAndRewrite(linalg::TiledLoopOp tiledLoop,
1413                                 PatternRewriter &rewriter) const final {
1414     SmallVector<Value, 2> newInputs, regionInputTensorArgs;
1415     // Store ids of the corresponding old and new input operands.
1416     SmallVector<int64_t, 2> oldInputIdToNew(tiledLoop.inputs().size(),
1417                                             kNoMatch);
1418     for (const auto &en : llvm::enumerate(
1419              llvm::zip(tiledLoop.inputs(), tiledLoop.getRegionInputArgs()))) {
1420       Value in, bbArg;
1421       size_t index = en.index();
1422       std::tie(in, bbArg) = en.value();
1423       if (!bbArg.use_empty()) {
1424         oldInputIdToNew[index] = newInputs.size();
1425         newInputs.push_back(in);
1426       }
1427     }
1428     if (newInputs.size() == tiledLoop.inputs().size())
1429       return failure();
1430     Location loc = tiledLoop.getLoc();
1431     auto newTiledLoop = rewriter.create<TiledLoopOp>(
1432         loc, tiledLoop.lowerBound(), tiledLoop.upperBound(), tiledLoop.step(),
1433         newInputs, tiledLoop.outputs(), tiledLoop.iterator_types(),
1434         tiledLoop.distribution_types());
1435 
1436     // Clone the region.
1437     BlockAndValueMapping bvm;
1438     bvm.map(tiledLoop.getInductionVars(), newTiledLoop.getInductionVars());
1439     bvm.map(tiledLoop.getRegionOutputArgs(),
1440             newTiledLoop.getRegionOutputArgs());
1441     for (const auto &en : llvm::enumerate(oldInputIdToNew))
1442       if (en.value() != kNoMatch)
1443         bvm.map(tiledLoop.getRegionInputArgs()[en.index()],
1444                 newTiledLoop.getRegionInputArgs()[en.value()]);
1445     OpBuilder innerBuilder =
1446         OpBuilder::atBlockEnd(newTiledLoop.getBody(), rewriter.getListener());
1447     for (auto &op : *tiledLoop.getBody())
1448       innerBuilder.clone(op, bvm);
1449     rewriter.replaceOp(tiledLoop, newTiledLoop.getResults());
1450 
1451     return success();
1452   }
1453 };
1454 
1455 } // namespace
1456 
1457 /// A simple, conservative analysis to determine if the loop is shape
1458 /// conserving. I.e., the type of the arg-th yielded value is the same as the
1459 /// type of the corresponding basic block argument of the loop.
1460 /// Note: This function handles only simple cases. Expand as needed.
1461 static bool isShapePreserving(TiledLoopOp loopOp, int64_t arg) {
1462   auto yieldOp = cast<YieldOp>(loopOp.getLoopBody().front().getTerminator());
1463   if (yieldOp.values().empty())
1464     // Tiled loop either has no outputs or is a "memref-based version". In
1465     // either case, the loop is shape conserving.
1466     return true;
1467   assert(arg < static_cast<int64_t>(yieldOp.values().size()) &&
1468          "arg is out of bounds");
1469   Value value = yieldOp.values()[arg];
1470   while (value) {
1471     if (value == loopOp.getRegionOutputArgs()[arg])
1472       return true;
1473     OpResult opResult = value.dyn_cast<OpResult>();
1474     if (!opResult)
1475       return false;
1476 
1477     using tensor::InsertSliceOp;
1478     value = llvm::TypeSwitch<Operation *, Value>(opResult.getOwner())
1479                 .template Case<InsertSliceOp>(
1480                     [&](InsertSliceOp op) { return op.dest(); })
1481                 .template Case<TiledLoopOp>([&](TiledLoopOp loopOp) {
1482                   return isShapePreserving(loopOp, opResult.getResultNumber())
1483                              ? loopOp.outputs()[opResult.getResultNumber()]
1484                              : Value();
1485                 })
1486                 .Default([&](auto op) { return Value(); });
1487   }
1488   return false;
1489 }
1490 
1491 namespace {
1492 
1493 /// Fold dim(x) where `x` is an input/output argument of a TiledLoopOp block
1494 /// to dim(y) where `y` is the initial input/output value of the argument.
1495 ///
1496 /// E.g.:
1497 /// %y = ... : tensor<...>
1498 /// linalg.tiled_loop ... ins(%x = %y : tensor<...>) {
1499 ///   tensor.dim %x, %c0 : tensor<...>
1500 /// }
1501 ///
1502 /// is folded to:
1503 /// %y = ... : tensor<...>
1504 /// linalg.tiled_loop ... ins(%x = %y : tensor<...>) {
1505 ///   tensor.dim %y, %c0 : tensor<...>
1506 /// }
1507 ///
1508 /// Note: Dim ops are folded only if it can be proven that the runtime type of
1509 /// the yielded value (in case of outputs) does not change with loop iterations.
1510 template <typename OpTy>
1511 struct DimOfTiledLoopInsOutsFolder : public OpRewritePattern<OpTy> {
1512   using OpRewritePattern<OpTy>::OpRewritePattern;
1513 
1514   LogicalResult matchAndRewrite(OpTy dimOp,
1515                                 PatternRewriter &rewriter) const final {
1516     auto src = dimOp.source().template dyn_cast<BlockArgument>();
1517     if (!src)
1518       return failure();
1519     auto loopOp =
1520         dyn_cast<TiledLoopOp>(src.getOwner()->getParent()->getParentOp());
1521     if (!loopOp)
1522       return failure();
1523     unsigned numLoops = loopOp.getNumLoops();
1524     unsigned numInputArgs = loopOp.getRegionInputArgs().size();
1525     if (src.getArgNumber() >= numInputArgs + numLoops &&
1526         !isShapePreserving(loopOp,
1527                            src.getArgNumber() - numInputArgs - numLoops))
1528       return failure();
1529 
1530     auto inputArgs = loopOp.getRegionInputArgs();
1531     auto it1 = llvm::find(inputArgs, src);
1532     if (it1 != inputArgs.end()) {
1533       rewriter.updateRootInPlace(dimOp, [&] {
1534         dimOp.sourceMutable().assign(loopOp.inputs()[it1 - inputArgs.begin()]);
1535       });
1536       return success();
1537     }
1538 
1539     auto outputArgs = loopOp.getRegionOutputArgs();
1540     auto it2 = llvm::find(outputArgs, src);
1541     if (it2 != outputArgs.end()) {
1542       rewriter.updateRootInPlace(dimOp, [&] {
1543         dimOp.sourceMutable().assign(
1544             loopOp.outputs()[it2 - outputArgs.begin()]);
1545       });
1546       return success();
1547     }
1548 
1549     return failure();
1550   }
1551 };
1552 
1553 /// Fold dim(r) where `r` is the result of a TiledLoopOp to dim(y) where `y`
1554 /// is the initial output value of the loop.
1555 ///
1556 /// E.g.:
1557 /// %y = ... : tensor<...>
1558 /// %r = linalg.tiled_loop ... outs(%i = %y : tensor<...>) {
1559 ///   ...
1560 /// }
1561 /// %0 = tensor.dim %r, %c0 : tensor<...>
1562 ///
1563 /// is folded to:
1564 /// %y = ... : tensor<...>
1565 /// linalg.tiled_loop ... outs(%i = %y : tensor<...>) {
1566 ///   ...
1567 /// }
1568 /// %0 = tensor.dim %y, %c0 : tensor<...>
1569 ///
1570 /// Note: Dim ops are folded only if it can be proven that the runtime type of
1571 /// the yielded value (in case of outputs) does not change with loop iterations.
1572 template <typename OpTy>
1573 struct DimOfTiledLoopResultFolder : public OpRewritePattern<OpTy> {
1574   using OpRewritePattern<OpTy>::OpRewritePattern;
1575 
1576   LogicalResult matchAndRewrite(OpTy dimOp,
1577                                 PatternRewriter &rewriter) const final {
1578     auto loopOp = dimOp.source().template getDefiningOp<TiledLoopOp>();
1579     if (!loopOp)
1580       return failure();
1581     auto opResult = dimOp.source().template cast<OpResult>();
1582     unsigned resultNumber = opResult.getResultNumber();
1583     if (!isShapePreserving(loopOp, resultNumber))
1584       return failure();
1585     rewriter.updateRootInPlace(dimOp, [&]() {
1586       dimOp.sourceMutable().assign(loopOp.outputs()[resultNumber]);
1587     });
1588     return success();
1589   }
1590 };
1591 
1592 // Folds away TiledLoopOp output tensors when the following conditions are met:
1593 // * result of `linalg.tiled_loop` has no uses
1594 // * output tensor is the argument of `linalg.yield`
1595 //
1596 // Example:
1597 //
1598 // %0 = linalg.tiled_loop ...  outs (%o_ = %out: tensor<...>,
1599 //                                   %obuf_ = %out_buf: memref<...>) {
1600 //   ...
1601 //   linalg.yield %o_ : tensor ...
1602 // }
1603 //
1604 // Becomes
1605 //
1606 // linalg.tiled_loop ...  outs (%obuf_ = %out_buf: memref<...>) {
1607 //   ...
1608 //   linalg.yield
1609 // }
1610 struct TiledLoopResultsFolder : public OpRewritePattern<linalg::TiledLoopOp> {
1611   using OpRewritePattern<linalg::TiledLoopOp>::OpRewritePattern;
1612 
1613   LogicalResult matchAndRewrite(linalg::TiledLoopOp tiledLoop,
1614                                 PatternRewriter &rewriter) const final {
1615     if (tiledLoop.getNumResults() == 0)
1616       return failure();
1617 
1618     Block *block = tiledLoop.getBody();
1619     auto yieldOp = cast<linalg::YieldOp>(block->getTerminator());
1620 
1621     // Match the pattern and collect output buffers that will replace the output
1622     // tensors and also the ops that will be ignored when cloning the body.
1623     SmallVector<Value, 2> newOutputOperands, newYieldArgs;
1624     int resultId = 0;
1625     // Store ids of the corresponding old and new output operands.
1626     SmallVector<int64_t, 2> oldOutputIdToNew(tiledLoop.outputs().size(),
1627                                              kNoMatch);
1628     // Store ids of the corresponding old and new results.
1629     SmallVector<int64_t, 2> oldResultIdToNew(tiledLoop.getNumResults(),
1630                                              kNoMatch);
1631     SmallVector<Value, 2> resultReplacement(tiledLoop.getNumResults());
1632     for (const auto &en : llvm::enumerate(
1633              llvm::zip(tiledLoop.outputs(), tiledLoop.getRegionOutputArgs()))) {
1634       size_t index = en.index();
1635       Value out = std::get<0>(en.value());
1636       Value outRegionArg = std::get<1>(en.value());
1637 
1638       if (!out.getType().isa<RankedTensorType>()) {
1639         oldOutputIdToNew[index] = newOutputOperands.size();
1640         newOutputOperands.push_back(out);
1641         continue;
1642       }
1643       Value result = tiledLoop.getResult(resultId);
1644       Value yieldArg = yieldOp.getOperand(resultId);
1645       if (yieldArg != outRegionArg || !result.use_empty()) {
1646         oldOutputIdToNew[index] = newOutputOperands.size();
1647         oldResultIdToNew[resultId] = newYieldArgs.size();
1648         resultReplacement[resultId] = out;
1649         newOutputOperands.push_back(out);
1650         newYieldArgs.push_back(yieldArg);
1651       }
1652       ++resultId;
1653     }
1654     if (newOutputOperands.size() == tiledLoop.outputs().size())
1655       return failure();
1656 
1657     Location loc = tiledLoop.getLoc();
1658     auto newTiledLoop = rewriter.create<TiledLoopOp>(
1659         loc, tiledLoop.lowerBound(), tiledLoop.upperBound(), tiledLoop.step(),
1660         tiledLoop.inputs(), newOutputOperands, tiledLoop.iterator_types(),
1661         tiledLoop.distribution_types());
1662 
1663     // Clone the region.
1664     BlockAndValueMapping bvm;
1665     bvm.map(tiledLoop.getInductionVars(), newTiledLoop.getInductionVars());
1666     bvm.map(tiledLoop.getRegionInputArgs(), newTiledLoop.getRegionInputArgs());
1667     for (const auto &en : llvm::enumerate(oldOutputIdToNew)) {
1668       if (en.value() != kNoMatch)
1669         bvm.map(tiledLoop.getRegionOutputArgs()[en.index()],
1670                 newTiledLoop.getRegionOutputArgs()[en.value()]);
1671       else
1672         bvm.map(tiledLoop.getRegionOutputArgs()[en.index()],
1673                 tiledLoop.outputs()[en.index()]);
1674     }
1675     OpBuilder innerBuilder =
1676         OpBuilder::atBlockEnd(newTiledLoop.getBody(), rewriter.getListener());
1677     for (auto &op : tiledLoop.getBody()->without_terminator())
1678       innerBuilder.clone(op, bvm);
1679     innerBuilder.create<linalg::YieldOp>(
1680         loc, llvm::to_vector<2>(llvm::map_range(
1681                  newYieldArgs, [&](Value arg) { return bvm.lookup(arg); })));
1682 
1683     for (const auto &en : llvm::enumerate(oldResultIdToNew))
1684       if (en.value() != kNoMatch)
1685         resultReplacement[en.index()] = newTiledLoop.getResult(en.value());
1686     rewriter.replaceOp(tiledLoop, resultReplacement);
1687 
1688     return success();
1689   }
1690 };
1691 } // namespace
1692 
1693 void TiledLoopOp::getCanonicalizationPatterns(RewritePatternSet &results,
1694                                               MLIRContext *context) {
1695   results.insert<TiledLoopInputsFolder, TiledLoopResultsFolder,
1696                  DimOfTiledLoopInsOutsFolder<tensor::DimOp>,
1697                  DimOfTiledLoopInsOutsFolder<memref::DimOp>,
1698                  DimOfTiledLoopResultFolder<tensor::DimOp>,
1699                  DimOfTiledLoopResultFolder<memref::DimOp>>(context);
1700 }
1701 
1702 LogicalResult TiledLoopOp::fold(ArrayRef<Attribute>,
1703                                 SmallVectorImpl<OpFoldResult> &) {
1704   return foldMemRefCastInTiledLoopOp(*this);
1705 }
1706 
1707 //===----------------------------------------------------------------------===//
1708 // IndexOp
1709 //===----------------------------------------------------------------------===//
1710 
1711 LogicalResult IndexOp::verify() {
1712   auto linalgOp = dyn_cast<LinalgOp>((*this)->getParentOp());
1713   if (!linalgOp)
1714     return emitOpError("expected parent op with LinalgOp interface");
1715   if (linalgOp.getNumLoops() <= dim())
1716     return emitOpError("expected dim (")
1717            << dim() << ") to be lower than the number of loops ("
1718            << linalgOp.getNumLoops() << ") of the enclosing LinalgOp";
1719   return success();
1720 }
1721 
1722 /////// Operations corresponding to library calls defined with Tablegen ////////
1723 
1724 #include "mlir/Dialect/Linalg/IR/LinalgNamedStructuredOps.yamlgen.cpp.inc"
1725 
1726 #define GET_OP_CLASSES
1727 #include "mlir/Dialect/Linalg/IR/LinalgOps.cpp.inc"
1728 
1729 #define GET_OP_CLASSES
1730 #include "mlir/Dialect/Linalg/IR/LinalgStructuredOps.cpp.inc"
1731 
1732 /// Return the dims that are `iteratorTypeName` loops in the LinalgOp `op`.
1733 /// Assumes `op` is a LinalgOp.
1734 void mlir::linalg::getDimsOfType(Operation *op, StringRef iteratorTypeName,
1735                                  SmallVectorImpl<unsigned> &res) {
1736   if (!cast<LinalgOp>(op).iterator_types())
1737     return;
1738 
1739   unsigned dim = 0;
1740   for (auto tn :
1741        cast<LinalgOp>(op).iterator_types().getAsValueRange<StringAttr>()) {
1742     if (tn == iteratorTypeName)
1743       res.push_back(dim);
1744     ++dim;
1745   }
1746 }
1747 
1748 AffineMap mlir::linalg::extractOrIdentityMap(Optional<AffineMap> maybeMap,
1749                                              unsigned rank,
1750                                              MLIRContext *context) {
1751   if (maybeMap)
1752     return maybeMap.getValue();
1753   if (rank == 0)
1754     return AffineMap::get(context);
1755   return AffineMap::getMultiDimIdentityMap(rank, context);
1756 }
1757 
1758 SmallVector<AffineExpr, 4>
1759 mlir::linalg::makeAffineDimExprs(unsigned num, unsigned &startIdx,
1760                                  MLIRContext *context) {
1761   SmallVector<AffineExpr, 4> res;
1762   res.reserve(num);
1763   for (unsigned i = 0; i < num; ++i)
1764     res.push_back(getAffineDimExpr(startIdx++, context));
1765   return res;
1766 }
1767 
1768 SmallVector<AffineExpr, 4> mlir::linalg::concat(ArrayRef<AffineExpr> a,
1769                                                 ArrayRef<AffineExpr> b) {
1770   auto rangeA = llvm::make_range(a.begin(), a.end());
1771   auto rangeB = llvm::make_range(b.begin(), b.end());
1772   auto concatRanges = llvm::concat<const AffineExpr>(rangeA, rangeB);
1773   return llvm::to_vector<4>(concatRanges);
1774 }
1775 
1776 static void appendMangledType(llvm::raw_string_ostream &ss, Type t) {
1777   if (auto memref = t.dyn_cast<MemRefType>()) {
1778     ss << "view";
1779     for (auto size : memref.getShape())
1780       if (size < 0)
1781         ss << "sx";
1782       else
1783         ss << size << "x";
1784     appendMangledType(ss, memref.getElementType());
1785   } else if (auto vec = t.dyn_cast<VectorType>()) {
1786     ss << "vector";
1787     llvm::interleave(
1788         vec.getShape(), [&](int64_t i) { ss << i; }, [&]() { ss << "x"; });
1789     appendMangledType(ss, vec.getElementType());
1790   } else if (t.isSignlessIntOrIndexOrFloat()) {
1791     ss << t;
1792   } else {
1793     llvm_unreachable("Invalid type for linalg library name mangling");
1794   }
1795 }
1796 
1797 std::string mlir::linalg::generateLibraryCallName(Operation *op) {
1798   assert(isa<LinalgOp>(op));
1799   std::string name(op->getName().getStringRef().str());
1800   name.reserve(128);
1801   std::replace(name.begin(), name.end(), '.', '_');
1802   llvm::raw_string_ostream ss(name);
1803   ss << "_";
1804   auto types = op->getOperandTypes();
1805   llvm::interleave(
1806       types.begin(), types.end(), [&](Type t) { appendMangledType(ss, t); },
1807       [&]() { ss << "_"; });
1808   return ss.str();
1809 }
1810 
1811 //===----------------------------------------------------------------------===//
1812 // Support for named Linalg ops defined in ods-gen.
1813 //===----------------------------------------------------------------------===//
1814 
1815 /// Generic entry point to create the block for the region of a LinalgOp.
1816 /// This is used by both named structured ops created by ods-gen and by manually
1817 /// defined C++ ops.
1818 /// This is used by both builders and parsers.
1819 /// This function creates the block in the region with arguments corresponding
1820 /// to the elemental types of `inputTypes` and `outputTypes`, which are asserted
1821 /// to be ShapedType.
1822 template <typename NamedStructuredOpType>
1823 static void fillStructuredOpRegion(
1824     OpBuilder &opBuilder, Region &region, TypeRange inputTypes,
1825     TypeRange outputTypes, ArrayRef<NamedAttribute> attrs,
1826     llvm::function_ref<void(unsigned, unsigned)> errorHandler) {
1827   assert(llvm::all_of(outputTypes, [](Type t) { return t.isa<ShapedType>(); }));
1828 
1829   // TODO: atm all operands go through getElementTypeOrSelf,
1830   // reconsider when we have evidence we need to.
1831   SmallVector<Type, 8> argTypes;
1832   SmallVector<Location, 8> argLocs;
1833   for (auto containers : {inputTypes, outputTypes}) {
1834     for (auto t : containers) {
1835       argTypes.push_back(getElementTypeOrSelf(t));
1836 
1837       // TODO: Pass in a proper location here.
1838       argLocs.push_back(opBuilder.getUnknownLoc());
1839     }
1840   }
1841 
1842   // RAII.
1843   OpBuilder::InsertionGuard guard(opBuilder);
1844   Block *body =
1845       opBuilder.createBlock(&region, /*insertPt=*/{}, argTypes, argLocs);
1846   unsigned actual = body->getNumArguments();
1847   unsigned expected = NamedStructuredOpType::getNumRegionArgs();
1848   if (expected != actual) {
1849     if (errorHandler)
1850       errorHandler(expected, actual);
1851     return;
1852   }
1853 
1854   opBuilder.setInsertionPointToStart(body);
1855   ImplicitLocOpBuilder b(opBuilder.getUnknownLoc(), opBuilder);
1856   NamedStructuredOpType::regionBuilder(b, *body, attrs);
1857 
1858   // indexing_maps is an auto-generated method.
1859 
1860   // iterator_types is an auto-generated method.
1861 }
1862 
1863 /// Generic entry point to create both the region and the block of a LinalgOp.
1864 template <typename NamedStructuredOpType>
1865 void createAndFillStructuredOpRegion(OpBuilder &opBuilder,
1866                                      OperationState &result,
1867                                      TypeRange inputTypes,
1868                                      TypeRange outputTypes) {
1869   Region &region = *result.addRegion();
1870   fillStructuredOpRegion<NamedStructuredOpType>(
1871       opBuilder, region, inputTypes, outputTypes, result.attributes.getAttrs(),
1872       [&](unsigned expected, unsigned actual) {
1873         assert(expected != actual && "incorrect number of arguments");
1874       });
1875 }
1876 
1877 /// Common parsing used for both named structured ops created by ods-gen and by
1878 /// manually defined C++ ops. Does not handle regions.
1879 static ParseResult
1880 parseCommonStructuredOpParts(OpAsmParser &parser, OperationState &result,
1881                              SmallVectorImpl<Type> &inputTypes,
1882                              SmallVectorImpl<Type> &outputTypes) {
1883   SMLoc inputsOperandsLoc, outputsOperandsLoc;
1884   SmallVector<OpAsmParser::OperandType, 4> inputsOperands, outputsOperands;
1885 
1886   parser.parseOptionalAttrDict(result.attributes);
1887 
1888   if (succeeded(parser.parseOptionalKeyword("ins"))) {
1889     if (parser.parseLParen())
1890       return failure();
1891 
1892     inputsOperandsLoc = parser.getCurrentLocation();
1893     if (parser.parseOperandList(inputsOperands) ||
1894         parser.parseColonTypeList(inputTypes) || parser.parseRParen())
1895       return failure();
1896   }
1897 
1898   if (succeeded(parser.parseOptionalKeyword("outs"))) {
1899     outputsOperandsLoc = parser.getCurrentLocation();
1900     if (parser.parseLParen() || parser.parseOperandList(outputsOperands) ||
1901         parser.parseColonTypeList(outputTypes) || parser.parseRParen())
1902       return failure();
1903   }
1904 
1905   if (parser.resolveOperands(inputsOperands, inputTypes, inputsOperandsLoc,
1906                              result.operands) ||
1907       parser.resolveOperands(outputsOperands, outputTypes, outputsOperandsLoc,
1908                              result.operands))
1909     return failure();
1910 
1911   result.addAttribute("operand_segment_sizes",
1912                       parser.getBuilder().getI32VectorAttr(
1913                           {static_cast<int32_t>(inputsOperands.size()),
1914                            static_cast<int32_t>(outputsOperands.size())}));
1915   return success();
1916 }
1917 
1918 template <typename NamedStructuredOpType>
1919 static void printCommonStructuredOpParts(OpAsmPrinter &p,
1920                                          NamedStructuredOpType op) {
1921   if (!op.inputs().empty())
1922     p << " ins(" << op.inputs() << " : " << op.inputs().getTypes() << ")";
1923   if (!op.outputs().empty())
1924     p << " outs(" << op.outputs() << " : " << op.outputs().getTypes() << ")";
1925 }
1926 
1927 //===----------------------------------------------------------------------===//
1928 // Specific parsing and printing for named structured ops created by ods-gen.
1929 //===----------------------------------------------------------------------===//
1930 
1931 template <typename NamedStructuredOpType>
1932 static ParseResult
1933 parseNamedStructuredOpRegion(OpAsmParser &parser, Region &region,
1934                              TypeRange inputTypes, TypeRange outputTypes,
1935                              ArrayRef<NamedAttribute> attrs) {
1936   ParseResult res = success();
1937   OpBuilder opBuilder(parser.getContext());
1938   // Resolve `captures` into `capturedValues` at parse time so we can build the
1939   // region with captures.
1940   SmallVector<Value> capturedValues;
1941   fillStructuredOpRegion<NamedStructuredOpType>(
1942       opBuilder, region, inputTypes, outputTypes, attrs,
1943       [&](unsigned expected, unsigned actual) {
1944         res = parser.emitError(
1945             parser.getCurrentLocation(),
1946             llvm::formatv("[parseNamedStructuredOpRegion] ods-gen generated "
1947                           "region expects {0} args, got {1}",
1948                           expected, actual));
1949         region.front().dump();
1950       });
1951   return res;
1952 }
1953 
1954 static ParseResult
1955 parseNamedStructuredOpResults(OpAsmParser &parser,
1956                               SmallVectorImpl<Type> &resultTypes) {
1957   if (parser.parseOptionalArrowTypeList(resultTypes))
1958     return failure();
1959   return success();
1960 }
1961 
1962 template <typename NamedStructuredOpType>
1963 static ParseResult parseNamedStructuredOp(OpAsmParser &parser,
1964                                           OperationState &result) {
1965   // TODO: Enable when ods-gen supports captures.
1966   SmallVector<Type, 1> inputTypes, outputTypes;
1967   if (parseCommonStructuredOpParts(parser, result, inputTypes, outputTypes))
1968     return failure();
1969 
1970   // TODO: consider merging results parsing into region parsing.
1971   // Need to wait for declarative assembly resolution to decide.
1972   SmallVector<Type, 1> outputTensorsTypes;
1973   if (parseNamedStructuredOpResults(parser, outputTensorsTypes))
1974     return failure();
1975   result.addTypes(outputTensorsTypes);
1976 
1977   std::unique_ptr<Region> region = std::make_unique<Region>();
1978   if (parseNamedStructuredOpRegion<NamedStructuredOpType>(
1979           parser, *region, inputTypes, outputTypes,
1980           result.attributes.getAttrs()))
1981     return failure();
1982   result.addRegion(std::move(region));
1983 
1984   return success();
1985 }
1986 
1987 static void printNamedStructuredOpResults(OpAsmPrinter &p,
1988                                           TypeRange resultTypes) {
1989   if (resultTypes.empty())
1990     return;
1991   p.printOptionalArrowTypeList(resultTypes);
1992 }
1993 
1994 template <typename NamedStructuredOpType>
1995 static void printNamedStructuredOp(OpAsmPrinter &p, NamedStructuredOpType op) {
1996   p.printOptionalAttrDict(
1997       op->getAttrs(),
1998       /*elidedAttrs=*/{"operand_segment_sizes",
1999                        // See generated code in mlir-linalg-yaml-gen.cpp
2000                        "linalg.memoized_indexing_maps"});
2001 
2002   // Printing is shared with generic ops, except for the region and
2003   // attributes.
2004   printCommonStructuredOpParts(p, op);
2005 
2006   // Results printing.
2007   printNamedStructuredOpResults(p, op.result_tensors().getTypes());
2008 
2009   // Region is elided.
2010 }
2011 
2012 template <typename NamedStructuredOpType>
2013 static LogicalResult verifyNamedStructuredOp(NamedStructuredOpType op) {
2014   return verifyGenericOp<NamedStructuredOpType>(op);
2015 }
2016 
2017 //===----------------------------------------------------------------------===//
2018 // Canonicalizers and Folders.
2019 //===----------------------------------------------------------------------===//
2020 
2021 namespace {
2022 struct EraseDeadLinalgOp : public OpInterfaceRewritePattern<LinalgOp> {
2023   using OpInterfaceRewritePattern<LinalgOp>::OpInterfaceRewritePattern;
2024 
2025   LogicalResult matchAndRewrite(LinalgOp op,
2026                                 PatternRewriter &rewriter) const override {
2027     for (OpOperand *opOperand : op.getInputAndOutputOperands()) {
2028       // Linalg "inputs" may be either tensor or memref type.
2029       // tensor<0xelt_type> is a convention that may not always mean
2030       // "0 iterations". Only erase in cases we see memref<...x0x...>.
2031       auto mt = opOperand->get().getType().dyn_cast<MemRefType>();
2032       if (!mt)
2033         continue;
2034       if (llvm::is_contained(op.getShape(opOperand), 0)) {
2035         rewriter.eraseOp(op);
2036         return success();
2037       }
2038     }
2039     return failure();
2040   }
2041 };
2042 
2043 struct FoldTensorCastOp : public OpInterfaceRewritePattern<LinalgOp> {
2044   using OpInterfaceRewritePattern<LinalgOp>::OpInterfaceRewritePattern;
2045 
2046   LogicalResult matchAndRewrite(LinalgOp op,
2047                                 PatternRewriter &rewriter) const override {
2048     // If no operand comes from a tensor::CastOp and can be folded then fail.
2049     bool hasTensorCastOperand =
2050         llvm::any_of(op.getInputAndOutputOperands(), [&](OpOperand *opOperand) {
2051           if (opOperand->get().isa<BlockArgument>())
2052             return false;
2053           auto castOp = opOperand->get().getDefiningOp<tensor::CastOp>();
2054           return castOp && canFoldIntoConsumerOp(castOp);
2055         });
2056     if (!hasTensorCastOperand)
2057       return failure();
2058 
2059     SmallVector<Type, 4> newResultTypes;
2060     newResultTypes.reserve(op->getNumResults());
2061     SmallVector<Value, 4> newOperands;
2062     newOperands.reserve(op->getNumOperands());
2063     // Inputs may fold.
2064     for (OpOperand *opOperand : op.getInputOperands()) {
2065       auto tensorCastOp = opOperand->get().getDefiningOp<tensor::CastOp>();
2066       newOperands.push_back(canFoldIntoConsumerOp(tensorCastOp)
2067                                 ? tensorCastOp.source()
2068                                 : opOperand->get());
2069     }
2070     // Init tensors may fold, in which case the resultType must also change.
2071     for (OpOperand *opOperand : op.getOutputOperands()) {
2072       auto tensorCastOp = opOperand->get().getDefiningOp<tensor::CastOp>();
2073       bool fold = canFoldIntoConsumerOp(tensorCastOp);
2074       newOperands.push_back(fold ? tensorCastOp.getOperand()
2075                                  : opOperand->get());
2076       newResultTypes.push_back(newOperands.back().getType());
2077     }
2078     // Clone op.
2079     Operation *newOp =
2080         op.clone(rewriter, op->getLoc(), newResultTypes, newOperands);
2081     SmallVector<Value, 4> replacements;
2082     replacements.reserve(newOp->getNumResults());
2083     for (auto result : llvm::zip(op->getResults(), newOp->getResults())) {
2084       Value oldResult = std::get<0>(result);
2085       Value newResult = std::get<1>(result);
2086       if (newResult.getType() != oldResult.getType()) {
2087         replacements.push_back(rewriter.create<tensor::CastOp>(
2088             op->getLoc(), oldResult.getType(), newResult));
2089       } else {
2090         replacements.push_back(newResult);
2091       }
2092     }
2093     rewriter.replaceOp(op, replacements);
2094 
2095     return success();
2096   }
2097 };
2098 
2099 } // namespace
2100 
2101 #define LINALGOP_FOLDERS(XXX)                                                  \
2102   LogicalResult XXX::fold(ArrayRef<Attribute>,                                 \
2103                           SmallVectorImpl<OpFoldResult> &) {                   \
2104     return foldMemRefCast(*this);                                              \
2105   }
2106 
2107 LINALGOP_FOLDERS(FillOp)
2108 LINALGOP_FOLDERS(GenericOp)
2109 
2110 // All named ops canonicalizers and folders are auto-generated in the
2111 // .cpp.inc.
2112 
2113 //===----------------------------------------------------------------------===//
2114 // LinalgDialect
2115 //===----------------------------------------------------------------------===//
2116 
2117 void LinalgDialect::getCanonicalizationPatterns(
2118     RewritePatternSet &results) const {
2119   results.add<EraseDeadLinalgOp, FoldTensorCastOp>(getContext());
2120 }
2121 
2122 Operation *LinalgDialect::materializeConstant(OpBuilder &builder,
2123                                               Attribute value, Type type,
2124                                               Location loc) {
2125   return builder.create<arith::ConstantOp>(loc, type, value);
2126 }
2127