1 //===- LinalgTransforms.cpp - Linalg transformations as patterns ----------===//
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 logic and helpers to expose Linalg transforms as rewrite
10 // patterns.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "mlir/Dialect/Linalg/Transforms/Transforms.h"
15 #include "mlir/Dialect/Affine/Utils.h"
16 #include "mlir/Dialect/Linalg/Analysis/DependenceAnalysis.h"
17 #include "mlir/Dialect/Linalg/IR/LinalgOps.h"
18 #include "mlir/Dialect/Linalg/Utils/Utils.h"
19 #include "mlir/Dialect/Tensor/IR/Tensor.h"
20 #include "mlir/Dialect/Utils/StructuredOpsUtils.h"
21 #include "mlir/Dialect/Vector/VectorOps.h"
22 #include "mlir/IR/AffineExpr.h"
23 #include "mlir/IR/Matchers.h"
24 #include "mlir/Pass/Pass.h"
25 #include "mlir/Support/LLVM.h"
26 #include "mlir/Transforms/GreedyPatternRewriteDriver.h"
27 #include "llvm/ADT/ScopeExit.h"
28 #include "llvm/Support/Debug.h"
29 #include "llvm/Support/raw_ostream.h"
30 #include <type_traits>
31 
32 #define DEBUG_TYPE "linalg-transforms"
33 
34 using namespace mlir;
35 using namespace mlir::linalg;
36 
37 #define DBGS() (llvm::dbgs() << "[" DEBUG_TYPE << "]: ")
38 
39 //===----------------------------------------------------------------------===//
40 // Transformations exposed as rewrite patterns.
41 //===----------------------------------------------------------------------===//
42 // Marker used as attribute name in generated Linalg rewriting transformations.
43 const StringLiteral mlir::linalg::LinalgTransforms::kLinalgTransformMarker =
44     "__internal_linalg_transform__";
45 
46 mlir::linalg::LinalgTransformationFilter::LinalgTransformationFilter(
47     ArrayRef<Identifier> matchDisjunction, Optional<Identifier> replacement)
48     : matchDisjunction(matchDisjunction.begin(), matchDisjunction.end()),
49       replacement(replacement) {}
50 
51 mlir::linalg::LinalgTransformationFilter::LinalgTransformationFilter(
52     FilterFunction f, ArrayRef<Identifier> matchDisjunction,
53     Optional<Identifier> replacement)
54     : filters(),
55       matchDisjunction(matchDisjunction.begin(), matchDisjunction.end()),
56       replacement(replacement) {
57   if (f)
58     filters.push_back(f);
59 }
60 
61 LogicalResult mlir::linalg::LinalgTransformationFilter::checkAndNotify(
62     PatternRewriter &rewriter, Operation *op) const {
63   if (llvm::any_of(filters,
64                    [&](const FilterFunction &f) { return failed(f(op)); }))
65     return failure();
66 
67   auto attr = op->template getAttrOfType<StringAttr>(
68       LinalgTransforms::kLinalgTransformMarker);
69 
70   if (!attr) {
71     // 1. Has no filter case and matchDisjunction is empty.
72     if (matchDisjunction.empty())
73       return success();
74 
75     // 2. Has no filter but was expecting a filter.
76     return rewriter.notifyMatchFailure(op, [&](Diagnostic &diag) {
77       diag << " does not have any filter from list: ";
78       interleaveComma(matchDisjunction, diag);
79     });
80   }
81 
82   // 4. Match explicit filter.
83   for (auto filter : matchDisjunction)
84     if (attr.getValue() == filter)
85       return success();
86 
87   // 5. Fail to match.
88   return rewriter.notifyMatchFailure(op, [&](Diagnostic &diag) {
89     diag << " does not have any filter from list: ";
90     interleaveComma(matchDisjunction, diag);
91   });
92 }
93 
94 void mlir::linalg::LinalgTransformationFilter::
95     replaceLinalgTransformationFilter(PatternRewriter &rewriter,
96                                       Operation *op) const {
97   if (replacement.hasValue())
98     op->setAttr(LinalgTransforms::kLinalgTransformMarker,
99                 rewriter.getStringAttr(replacement.getValue().strref()));
100   else
101     op->removeAttr(Identifier::get(LinalgTransforms::kLinalgTransformMarker,
102                                    rewriter.getContext()));
103 }
104 
105 LinalgTilingOptions &
106 mlir::linalg::LinalgTilingOptions::setTileSizes(ArrayRef<int64_t> ts) {
107   SmallVector<int64_t, 4> tileSizes(ts.begin(), ts.end());
108   tileSizeComputationFunction = [tileSizes](OpBuilder &b, Operation *op) {
109     OpBuilder::InsertionGuard guard(b);
110     b.setInsertionPointToStart(
111         &op->getParentOfType<FuncOp>().getBody().front());
112     return llvm::to_vector<4>(map_range(tileSizes, [&](int64_t s) {
113       Value v = b.create<ConstantIndexOp>(op->getLoc(), s);
114       return v;
115     }));
116   };
117   return *this;
118 }
119 
120 /// Try to compute a static bounding box for `operand`
121 /// Return success if either:
122 ///   1. The operand is already statically shaped, `result` is left unchanged.
123 ///   2. The operand is (partially) dynamic, `result` is the result of a freshly
124 ///      created PadTensorOp.
125 /// Return failure if the operand cannot be padded to a static shape.
126 static LogicalResult padOperandToSmallestStaticBoundingBox(
127     PatternRewriter &rewriter, linalg::LinalgOp opToPad, OpOperand *opOperand,
128     const LinalgTilingOptions &options, Value &result) {
129   // Already static shape, no need to pad.
130   if (llvm::none_of(opToPad.getShape(opOperand), ShapedType::isDynamic))
131     return success();
132   auto sliceOp = opOperand->get().getDefiningOp<tensor::ExtractSliceOp>();
133   // Not a slice op, cannot construct a static bounding box.
134   if (!sliceOp)
135     return failure();
136   SmallVector<int64_t> staticSizes;
137   staticSizes.reserve(opToPad.getRank(opOperand));
138   auto shapedOp = cast<OffsetSizeAndStrideOpInterface>(sliceOp.getOperation());
139   for (auto size : shapedOp.getMixedSizes()) {
140     auto indexAttr = size.is<Attribute>()
141                          ? size.get<Attribute>().dyn_cast<IntegerAttr>()
142                          : linalg::getSmallestBoundingIndex(size.get<Value>());
143     // SmallestBoundingIndex must exist for all sizes.
144     // For now return an error if we can't find it.
145     if (!indexAttr)
146       return rewriter.notifyMatchFailure(
147           opToPad, "No constant bounding box can be found for padding");
148     staticSizes.push_back(indexAttr.getInt());
149   }
150   Value pad = options.paddingValueComputationFunction(rewriter, *opOperand);
151   auto staticTensorType = RankedTensorType::get(
152       staticSizes, getElementTypeOrSelf(opOperand->get()));
153   result = linalg::PadTensorOp::createPadHighOp(
154       staticTensorType, opOperand->get(), pad, opToPad->getLoc(), rewriter);
155   return success();
156 }
157 
158 // Try to create a static bounding box around each operand of `res.op`.
159 // If successful, `res.op` is rewritten in static form with padded operands.
160 // `res.op` is updated to the cloned static form of the op on success.
161 static LogicalResult rewriteAsPaddedOp(PatternRewriter &rewriter,
162                                        TiledLinalgOp &res,
163                                        const LinalgTilingOptions &options) {
164   LinalgOp opToPad = res.op;
165   Location loc = opToPad->getLoc();
166 
167   // If the op is fully static, it does not need padding.
168   // TODO: there are cases where we may still want to pad to larger sizes.
169   assert(opToPad.hasTensorSemantics() &&
170          "expected operation to have tensor semantics");
171   if (!opToPad.hasDynamicShape())
172     return success();
173 
174   OpBuilder::InsertionGuard g(rewriter);
175   // Set IP after op because we also take the dims of the original output.
176   rewriter.setInsertionPointAfter(opToPad);
177   // Make a copy of the shaped operands and update it.
178   SmallVector<Value> newOperands;
179   newOperands.reserve(opToPad.getNumInputsAndOutputs());
180   for (OpOperand *opOperand : opToPad.getInputAndOutputOperands()) {
181     Value paddedOperand;
182     // If padding was requested but the shape cannot be bounded statically then
183     // the pattern fails to apply.
184     if (failed(padOperandToSmallestStaticBoundingBox(
185             rewriter, opToPad, opOperand, options, paddedOperand)))
186       return failure();
187     newOperands.push_back(paddedOperand ? paddedOperand : opOperand->get());
188   }
189 
190   // Clone `opToPad` to operate on the statically padded shapes.
191   auto resultTensorTypes =
192       ValueRange(newOperands).take_back(opToPad.getNumOutputs()).getTypes();
193   ValueRange otherOperands = opToPad.getAssumedNonShapedOperands();
194   newOperands.append(otherOperands.begin(), otherOperands.end());
195   linalg::LinalgOp paddedOp =
196       opToPad.clone(rewriter, loc, resultTensorTypes, newOperands);
197 
198   // Recover the slice out of the new static results. This keeps the original
199   // linalg op around because it uses the dims of the original results.
200   // This later folds away.
201   SmallVector<Value> paddedSubviewResults;
202   paddedSubviewResults.reserve(opToPad->getNumResults());
203   SetVector<Operation *> newUsersOfOpToPad;
204   for (auto it : llvm::zip(opToPad->getResults(), paddedOp->getResults())) {
205     auto rank = std::get<0>(it).getType().cast<RankedTensorType>().getRank();
206     SmallVector<OpFoldResult> offsets(rank, rewriter.getIndexAttr(0));
207     auto sizes = llvm::to_vector<4>(llvm::map_range(
208         llvm::seq<unsigned>(0, rank), [&](unsigned d) -> OpFoldResult {
209           auto dimOp = rewriter.create<memref::DimOp>(loc, std::get<0>(it), d);
210           newUsersOfOpToPad.insert(dimOp);
211           return dimOp.getResult();
212         }));
213     SmallVector<OpFoldResult> strides(rank, rewriter.getIndexAttr(1));
214     paddedSubviewResults.push_back(rewriter.create<tensor::ExtractSliceOp>(
215         loc, std::get<1>(it), offsets, sizes, strides));
216   }
217   // Replace the transient `opToPad` locally, except for uses that we just
218   // created for the purpose of extracting the dims.
219   rewriter.replaceOpWithIf(opToPad, paddedSubviewResults, [&](OpOperand &opOp) {
220     return !newUsersOfOpToPad.contains(opOp.getOwner());
221   });
222 
223   res = TiledLinalgOp{paddedOp, res.loops, res.tensorResults};
224   return success();
225 }
226 
227 /// Linalg base tiling pattern.
228 mlir::linalg::LinalgBaseTilingPattern::LinalgBaseTilingPattern(
229     StringRef opName, MLIRContext *context, LinalgTilingOptions options,
230     LinalgTransformationFilter filter, PatternBenefit benefit)
231     : RewritePattern(opName, benefit, context), filter(filter),
232       options(options) {}
233 
234 mlir::linalg::LinalgBaseTilingPattern::LinalgBaseTilingPattern(
235     MLIRContext *context, LinalgTilingOptions options,
236     LinalgTransformationFilter filter, PatternBenefit benefit)
237     : RewritePattern(MatchAnyOpTypeTag(), benefit, context), filter(filter),
238       options(options) {}
239 
240 LogicalResult mlir::linalg::LinalgBaseTilingPattern::matchAndRewriteBase(
241     Operation *op, PatternRewriter &rewriter, TiledLinalgOp &result) const {
242   LinalgOp linalgOp = dyn_cast<LinalgOp>(op);
243   if (!linalgOp)
244     return failure();
245   if (failed(filter.checkAndNotify(rewriter, linalgOp)))
246     return failure();
247 
248   Optional<TiledLinalgOp> res = tileLinalgOp(rewriter, linalgOp, options);
249 
250   if (!res)
251     return failure();
252 
253   // Setup RAII guard to return properly.
254   LinalgOp tiledOp = res->op;
255   auto guard = llvm::make_scope_exit([&]() {
256     // Return relevant information to derived pattern.
257     result = *res;
258     // Replace filter on both tiledOp and tiledAndPaddedOp, if necessary.
259     filter.replaceLinalgTransformationFilter(rewriter, tiledOp);
260     if (tiledOp != res->op)
261       filter.replaceLinalgTransformationFilter(rewriter, res->op);
262   });
263 
264   // Consider padding on the fly only if the op has tensor semantics.
265   if (!options.paddingValueComputationFunction ||
266       !linalgOp.hasTensorSemantics())
267     return success();
268 
269   // Try to pad on the fly by rewriting res->op as a padded op.
270   if (failed(rewriteAsPaddedOp(rewriter, *res, options))) {
271     // Set so RAII guard does not propagate TiledLinalgOp to `result`.
272     return failure();
273   }
274 
275   // Do not perform replacement of `linalgOp`, let the derived patterns
276   // do this as they see fit, from the resulting TiledLinalgOp.
277   return success();
278 }
279 
280 static ValueRange getTiledOpResult(TiledLinalgOp tiledOp) {
281   if (tiledOp.loops.empty())
282     return tiledOp.op.getOperation()->getResults();
283   return tiledOp.loops.front()->getResults();
284 }
285 
286 static ValueRange
287 getTiledAndFusedOpResult(TiledAndFusedLinalgOps tiledAndFusedOp) {
288   if (tiledAndFusedOp.fusedLoops.empty())
289     return tiledAndFusedOp.op.getOperation()->getResults();
290   return tiledAndFusedOp.fusedLoops.front()->getResults();
291 }
292 
293 mlir::linalg::LinalgBaseTileAndFusePattern::LinalgBaseTileAndFusePattern(
294     StringRef opName, MLIRContext *context,
295     const LinalgDependenceGraph &dependenceGraph,
296     LinalgTilingOptions tilingOptions, LinalgFusionOptions fusionOptions,
297     LinalgTransformationFilter filter, LinalgTransformationFilter fusedOpMarker,
298     LinalgTransformationFilter originalOpMarker, PatternBenefit benefit)
299     : RewritePattern(opName, benefit, context, {}),
300       dependenceGraph(dependenceGraph), tilingOptions(tilingOptions),
301       fusionOptions(fusionOptions), filter(filter),
302       fusedOpMarker(fusedOpMarker), originalOpMarker(originalOpMarker) {}
303 
304 LogicalResult mlir::linalg::LinalgBaseTileAndFusePattern::matchAndRewrite(
305     Operation *op, PatternRewriter &rewriter) const {
306   LinalgOp linalgOp = dyn_cast<LinalgOp>(op);
307   // TODO: remove hasIndexSemantics check once index ops are supported.
308   if (!linalgOp || linalgOp.hasIndexSemantics())
309     return failure();
310   if (failed(filter.checkAndNotify(rewriter, linalgOp)))
311     return failure();
312 
313   DenseSet<Operation *> producers;
314   producers.insert(linalgOp);
315   for (auto dependence : dependenceGraph.getDependentOperationsInto(linalgOp)) {
316     Optional<unsigned> operandNumber = dependence.getIndexingOpViewOperandNum();
317     // When looking at dependences into, indexingOp is always OpOperand. We
318     // could assert, but continue if this is not the case.
319     if (!operandNumber)
320       continue;
321     if (!fusionOptions.indicesToFuse.count(operandNumber.getValue()))
322       continue;
323     if (isa<LinalgOp>(dependence.getDependentOp()))
324       producers.insert(dependence.getDependentOp());
325   }
326 
327   SmallVector<LinalgOp, 1> fusionOps;
328   for (auto it = op->getBlock()->begin(), ie = Block::iterator(op); it != ie;
329        ++it) {
330     auto producerLinalgOp = dyn_cast<LinalgOp>(&(*it));
331     if (producerLinalgOp && producers.count(producerLinalgOp))
332       fusionOps.push_back(producerLinalgOp);
333   }
334   fusionOps.push_back(linalgOp);
335 
336   SmallVector<Value, 4> tileSizes =
337       tilingOptions.tileSizeComputationFunction(rewriter, op);
338   LinalgTilingOptions instanceTilingOptions = tilingOptions;
339   instanceTilingOptions.setTileSizes(tileSizes);
340   Optional<TiledAndFusedLinalgOps> tiledAndFusedOps = tileAndFuseLinalgOps(
341       rewriter, fusionOps, dependenceGraph, instanceTilingOptions);
342   if (!tiledAndFusedOps)
343     return failure();
344 
345   // Tile the unfused loops;
346   SmallVector<Value, 4> unfusedLoopTileSizes;
347   Value zero = rewriter.create<ConstantIndexOp>(op->getLoc(), 0);
348   for (auto tileSize : enumerate(tileSizes)) {
349     if (tiledAndFusedOps->fusedLoopDims.count(tileSize.index()))
350       unfusedLoopTileSizes.push_back(zero);
351     else
352       unfusedLoopTileSizes.push_back(tileSize.value());
353   }
354   // Tile the loop only if there is a non-zero tile size.
355   if (unfusedLoopTileSizes.size() > linalgOp.getNumLoops())
356     unfusedLoopTileSizes.resize(linalgOp.getNumLoops());
357   if (llvm::any_of(unfusedLoopTileSizes, [](Value val) {
358         if (auto cst = val.getDefiningOp<ConstantIndexOp>())
359           return cst.getValue() != 0;
360         return true;
361       })) {
362     LinalgTilingOptions unfusedTilingOptions = tilingOptions;
363     unfusedTilingOptions.setTileSizes(unfusedLoopTileSizes);
364     Optional<TiledLinalgOp> unfusedTiledOp =
365         tileLinalgOp(rewriter, tiledAndFusedOps->op, unfusedTilingOptions);
366     if (!unfusedTiledOp)
367       return failure();
368     rewriter.replaceOp(tiledAndFusedOps->op,
369                        getTiledOpResult(unfusedTiledOp.getValue()));
370     tiledAndFusedOps->op = unfusedTiledOp->op;
371   }
372   op->replaceAllUsesWith(getTiledAndFusedOpResult(tiledAndFusedOps.getValue()));
373 
374   filter.replaceLinalgTransformationFilter(rewriter,
375                                            tiledAndFusedOps->op.getOperation());
376   for (auto fusedOp : tiledAndFusedOps->fusedProducers) {
377     fusedOpMarker.replaceLinalgTransformationFilter(rewriter,
378                                                     fusedOp.getOperation());
379   }
380   for (auto origProducerOp : ArrayRef<LinalgOp>(fusionOps).drop_back()) {
381     originalOpMarker.replaceLinalgTransformationFilter(
382         rewriter, origProducerOp.getOperation());
383   }
384   rewriter.updateRootInPlace(op, [&]() {
385     originalOpMarker.replaceLinalgTransformationFilter(rewriter, op);
386   });
387   return success();
388 }
389 
390 /// Linalg generic interchange pattern.
391 mlir::linalg::GenericOpInterchangePattern::GenericOpInterchangePattern(
392     MLIRContext *context, ArrayRef<unsigned> interchangeVector,
393     LinalgTransformationFilter filter, PatternBenefit benefit)
394     : OpRewritePattern(context, benefit), filter(filter),
395       interchangeVector(interchangeVector.begin(), interchangeVector.end()) {}
396 
397 LogicalResult mlir::linalg::GenericOpInterchangePattern::matchAndRewrite(
398     GenericOp genericOp, PatternRewriter &rewriter) const {
399   if (failed(filter.checkAndNotify(rewriter, genericOp)))
400     return failure();
401   if (failed(interchangeGenericOpPrecondition(genericOp, interchangeVector)))
402     return failure();
403 
404   // TODO: figure out how this interplays with named ops. In particular this
405   // should break the named op property.
406   rewriter.updateRootInPlace(genericOp, [&]() {
407     interchangeGenericOp(rewriter, genericOp, interchangeVector);
408     // New filter if specified.
409     filter.replaceLinalgTransformationFilter(rewriter, genericOp);
410   });
411   return success();
412 }
413 
414 mlir::linalg::LinalgBasePromotionPattern::LinalgBasePromotionPattern(
415     StringRef opName, MLIRContext *context, LinalgPromotionOptions options,
416     LinalgTransformationFilter filter, PatternBenefit benefit)
417     : RewritePattern(opName, benefit, context, {}), filter(filter),
418       options(options) {}
419 
420 LogicalResult mlir::linalg::LinalgBasePromotionPattern::matchAndRewrite(
421     Operation *op, PatternRewriter &rewriter) const {
422   if (failed(filter.checkAndNotify(rewriter, op)))
423     return failure();
424   if (failed(promoteSubviewsPrecondition(op, options)))
425     return failure();
426 
427   // TODO: We cannot use root update here. This pattern is creating other ops,
428   // so if the promotion fails, those need to be cleaned up, which doesnt seem
429   // to be happening here. So to fail properly, we should be cloning the op and
430   // deleting the previous op. This needs more investigation.
431   rewriter.startRootUpdate(op);
432   Optional<LinalgOp> promotedOp = promoteSubViews(rewriter, op, options);
433   if (!promotedOp) {
434     rewriter.cancelRootUpdate(op);
435     return op->emitError("subview promotion failed");
436   }
437   rewriter.finalizeRootUpdate(op);
438   filter.replaceLinalgTransformationFilter(rewriter, op);
439   return success();
440 }
441 
442 mlir::linalg::LinalgBaseVectorizationPattern::LinalgBaseVectorizationPattern(
443     MLIRContext *context, LinalgTransformationFilter filter,
444     PatternBenefit benefit)
445     : RewritePattern(MatchAnyOpTypeTag(), benefit, context), filter(filter) {}
446 
447 mlir::linalg::LinalgBaseVectorizationPattern::LinalgBaseVectorizationPattern(
448     StringRef opName, MLIRContext *context, LinalgTransformationFilter filter,
449     PatternBenefit benefit)
450     : RewritePattern(opName, benefit, context, {}), filter(filter) {}
451 
452 LogicalResult mlir::linalg::LinalgBaseVectorizationPattern::matchAndRewrite(
453     Operation *op, PatternRewriter &rewriter) const {
454   LinalgOp linalgOp = dyn_cast<LinalgOp>(op);
455   if (!linalgOp)
456     return failure();
457   if (failed(filter.checkAndNotify(rewriter, linalgOp)))
458     return failure();
459   SmallVector<Value> newResults;
460   if (failed(vectorizeLinalgOp(rewriter, op, newResults)))
461     return failure();
462   if (!newResults.empty())
463     rewriter.replaceOp(op, newResults);
464   else
465     rewriter.eraseOp(op);
466   return success();
467 }
468 
469 LogicalResult mlir::linalg::applyStagedPatterns(
470     Operation *op, ArrayRef<FrozenRewritePatternSet> stage1Patterns,
471     const FrozenRewritePatternSet &stage2Patterns,
472     function_ref<LogicalResult(Operation *)> stage3Lambda) {
473   unsigned iteration = 0;
474   (void)iteration;
475   for (const auto &patterns : stage1Patterns) {
476     LLVM_DEBUG(DBGS() << "Before 1st stage, iter: " << ++iteration << "\n"
477                       << *op);
478     if (failed(applyPatternsAndFoldGreedily(op, patterns))) {
479       LLVM_DEBUG(DBGS() << "Underlying first stage rewrite did not converge");
480       return failure();
481     }
482     LLVM_DEBUG(DBGS() << "After 1st stage, iter: " << ++iteration << "\n"
483                       << *op);
484     if (failed(applyPatternsAndFoldGreedily(op, stage2Patterns))) {
485       LLVM_DEBUG(DBGS() << "Underlying 2nd stage rewrite did not converge");
486       return failure();
487     }
488     LLVM_DEBUG(DBGS() << "After 2nd stage, iter : " << iteration << "\n"
489                       << *op);
490     if (stage3Lambda) {
491       if (failed(stage3Lambda(op)))
492         return failure();
493       LLVM_DEBUG(DBGS() << "After 3rd stage, iter : " << iteration << "\n"
494                         << *op);
495     }
496   }
497   return success();
498 }
499 
500 /// Traverse the `dims` and substitute known min or max expressions returned by
501 /// the lambda |getMinMaxExpr|.
502 static AffineMap substitute(AffineMap map, SmallVectorImpl<Value> &dims,
503                             SmallVectorImpl<Value> &symbols,
504                             GetMinMaxExprFn getMinMaxExpr) {
505   auto exprs = llvm::to_vector<4>(map.getResults());
506   for (AffineExpr &expr : exprs) {
507     bool substituted = true;
508     while (substituted) {
509       substituted = false;
510       for (unsigned dimIdx = 0; dimIdx < dims.size(); ++dimIdx) {
511         Value dim = dims[dimIdx];
512         auto minMax = getMinMaxExpr(dim, dims, symbols);
513         if (!minMax)
514           continue;
515         AffineExpr dimExpr = getAffineDimExpr(dimIdx, expr.getContext());
516         LLVM_DEBUG(DBGS() << "Subst: " << dim << " @ " << dimExpr << "\n");
517         LLVM_DEBUG(DBGS() << "Before: " << expr << "\n");
518         // Substitute occurrences of `dimExpr` by either the min expression or
519         // the max expression depending on whether the value is used with a
520         // positive or negative  coefficient.
521         AffineExpr substitutedExpr =
522             substWithMin(expr, dimExpr, minMax->first, minMax->second);
523         LLVM_DEBUG(DBGS() << "After: " << substitutedExpr << "\n");
524         substituted = (substitutedExpr != expr);
525         expr = substitutedExpr;
526       }
527     }
528 
529     // Cleanup and simplify the results.
530     // This needs to happen outside of the loop iterating on dims.size() since
531     // it modifies dims.
532     SmallVector<Value, 4> operands(dims.begin(), dims.end());
533     operands.append(symbols.begin(), symbols.end());
534     auto map = AffineMap::get(dims.size(), symbols.size(), exprs,
535                               exprs.front().getContext());
536 
537     LLVM_DEBUG({
538       DBGS() << "Map to simplify: " << map << "\n";
539       DBGS() << "Operands:\n";
540       for (Value v : operands)
541         DBGS() << v << "\n";
542     });
543 
544     // Pull in affine.apply operations and compose them fully into the
545     // result.
546     fullyComposeAffineMapAndOperands(&map, &operands);
547     canonicalizeMapAndOperands(&map, &operands);
548     map = simplifyAffineMap(map);
549     // Assign the results.
550     exprs.assign(map.getResults().begin(), map.getResults().end());
551     dims.assign(operands.begin(), operands.begin() + map.getNumDims());
552     symbols.assign(operands.begin() + map.getNumDims(), operands.end());
553 
554     LLVM_DEBUG(DBGS() << "Map simplified: " << map << "\n");
555   }
556 
557   assert(!exprs.empty() && "Unexpected empty exprs");
558   return AffineMap::get(dims.size(), symbols.size(), exprs, map.getContext());
559 }
560 
561 /// Traverse the dims of the AffineMap of `affineMinOp` and substitute
562 /// dimensions with known range by new expressions involving the min or max
563 /// expression:
564 ///   - If the AffineDimExpr mapped to a known value has a positive sign, it
565 ///     is replaced by the min expression.
566 ///   - If the AffineDimExpr mapped to a known value has a negative sign, it is
567 ///     replaced by the max expression.
568 /// All known values are iteratively replaced.
569 /// This is used as an intermediate step in computing bounding boxes and
570 /// canonicalize AffineMinOps. All dim and symbol operands are assumed to have
571 /// positive values (positive orthant assumptions).
572 /// Return a new AffineMap, dims and symbols that have been canonicalized and
573 /// simplified.
574 AffineMapAndOperands
575 mlir::linalg::substituteMin(AffineMinOp affineMinOp,
576                             GetMinMaxExprFn getMinMaxExpr) {
577   AffineMapAndOperands res{affineMinOp.getAffineMap(),
578                            SmallVector<Value>(affineMinOp.getDimOperands()),
579                            SmallVector<Value>(affineMinOp.getSymbolOperands())};
580   res.map = substitute(affineMinOp.getAffineMap(), res.dims, res.symbols,
581                        getMinMaxExpr);
582   return res;
583 }
584 
585 LogicalResult AffineMinRangeCanonicalizationPattern::matchAndRewrite(
586     AffineMinOp minOp, PatternRewriter &rewriter) const {
587   LLVM_DEBUG(DBGS() << "Canonicalize AffineMinSCF: " << *minOp.getOperation()
588                     << "\n");
589 
590   auto affineMapAndOperands = substituteMin(minOp, getMinMaxFn);
591   AffineMap map = affineMapAndOperands.map;
592 
593   LLVM_DEBUG(DBGS() << "Resulting map: " << map << "\n");
594 
595   // Check whether any of the expressions, when subtracted from all other
596   // expressions, produces only >= 0 constants. If so, it is the min.
597   for (auto e : minOp.getAffineMap().getResults()) {
598     LLVM_DEBUG(DBGS() << "Candidate min: " << e << "\n");
599     if (!e.isSymbolicOrConstant())
600       continue;
601 
602     auto isNonPositive = [](AffineExpr e) {
603       if (auto cst = e.dyn_cast<AffineConstantExpr>())
604         return cst.getValue() < 0;
605       return true;
606     };
607 
608     // Build the subMap and check everything is statically known to be
609     // positive.
610     SmallVector<AffineExpr, 4> subExprs;
611     subExprs.reserve(map.getNumResults());
612     for (auto ee : map.getResults())
613       subExprs.push_back(ee - e);
614     MLIRContext *ctx = minOp.getContext();
615     AffineMap subMap = simplifyAffineMap(
616         AffineMap::get(map.getNumDims(), map.getNumSymbols(), subExprs, ctx));
617     LLVM_DEBUG(DBGS() << "simplified subMap: " << subMap << "\n");
618     if (llvm::any_of(subMap.getResults(), isNonPositive))
619       continue;
620 
621     // Static min found.
622     if (auto cst = e.dyn_cast<AffineConstantExpr>()) {
623       rewriter.replaceOpWithNewOp<ConstantIndexOp>(minOp, cst.getValue());
624     } else {
625       auto resultMap = AffineMap::get(0, map.getNumSymbols(), {e}, ctx);
626       SmallVector<Value> resultOperands = affineMapAndOperands.dims;
627       llvm::append_range(resultOperands, affineMapAndOperands.symbols);
628       canonicalizeMapAndOperands(&resultMap, &resultOperands);
629       resultMap = simplifyAffineMap(resultMap);
630       rewriter.replaceOpWithNewOp<AffineApplyOp>(minOp, resultMap,
631                                                  resultOperands);
632     }
633     return success();
634   }
635 
636   return failure();
637 }
638 
639 static SmallVector<StringRef> getNParallelLoopsAttrs(unsigned nParallelLoops) {
640   return SmallVector<StringRef>(nParallelLoops, getParallelIteratorTypeName());
641 }
642 
643 /// Rewrite a PadTensorOp into a sequence of InitTensorOp, FillOp (to initialize
644 /// with pad_val) and GenericOp (to copy contents).
645 LogicalResult PadTensorOpTransformationPattern::matchAndRewrite(
646     linalg::PadTensorOp padOp, PatternRewriter &rewriter) const {
647 
648   auto inputShapedType = padOp.source().getType().cast<ShapedType>();
649   auto resultShapedType = padOp.result().getType().cast<ShapedType>();
650 
651   // Bail on non-static shapes.
652   if (!inputShapedType.hasStaticShape())
653     return failure();
654   if (!resultShapedType.hasStaticShape())
655     return failure();
656 
657   // Only support padding with a constant for now, i.e. either:
658   //   1. A BBarg from a different block.
659   //   2. A value defined outside of the current block.
660   Block &block = padOp.region().front();
661   auto yieldOp = cast<YieldOp>(block.getTerminator());
662   assert(yieldOp.getNumOperands() == 1 && "expected single operand yield");
663   Value padValue = yieldOp.values().front();
664   Operation *definingOp = padValue.getDefiningOp();
665   if (definingOp && definingOp->getBlock() == &block)
666     return failure();
667   if (!definingOp && padValue.cast<BlockArgument>().getOwner() == &block)
668     return failure();
669 
670   // Create tensor with the padded shape
671   Location loc = padOp.getLoc();
672   SmallVector<Value> indices(resultShapedType.getRank(),
673                              rewriter.create<ConstantIndexOp>(loc, 0));
674   Value initTensor = rewriter.create<InitTensorOp>(
675       loc, resultShapedType.getShape(), resultShapedType.getElementType());
676 
677   // Initialize tensor with the pad value
678   Value tmpTensor =
679       rewriter.create<linalg::FillOp>(loc, padValue, initTensor).result();
680 
681   // Copy original contents into new tensor
682   // Uses linalg.generic, but could be done with tensor.insert_slice
683   SmallVector<AffineExpr, 4> outputExprs;
684   for (unsigned i = 0; i < resultShapedType.getRank(); ++i) {
685     outputExprs.push_back(getAffineDimExpr(i, rewriter.getContext()) +
686                           padOp.static_low()[i].cast<IntegerAttr>().getInt());
687   }
688 
689   SmallVector<AffineMap, 2> transferMaps = {
690       rewriter.getMultiDimIdentityMap(inputShapedType.getRank()),
691       AffineMap::get(resultShapedType.getRank(),
692                      /*symbolCount=*/0, outputExprs, rewriter.getContext())};
693 
694   rewriter.replaceOpWithNewOp<linalg::GenericOp>(
695       padOp, resultShapedType, padOp.source(), tmpTensor, transferMaps,
696       getNParallelLoopsAttrs(resultShapedType.getRank()),
697       [&](OpBuilder &nestedBuilder, Location nestedLoc, ValueRange args) {
698         nestedBuilder.create<linalg::YieldOp>(nestedLoc, args[0]);
699       });
700 
701   return success();
702 }
703 
704 /// Given an OpFoldResult, return a Value. If the OpFoldResult is an Attribute,
705 /// it must be of type Integer.
706 static Value asValue(OpBuilder &builder, Location loc, OpFoldResult ofr) {
707   if (auto val = ofr.dyn_cast<Value>())
708     return val;
709   auto intVal = getConstantIntValue(ofr);
710   assert(intVal && "expected Value or IntegerAttr");
711   return builder.create<ConstantIndexOp>(loc, *intVal);
712 }
713 
714 /// Given a value, try to extract a constant index-type integer as an Attribute.
715 /// If this fails, return the original value.
716 static OpFoldResult asOpFoldResult(OpBuilder &builder, Value val) {
717   if (auto constInt = getConstantIntValue(val))
718     return builder.getIndexAttr(*constInt);
719   return val;
720 }
721 
722 LogicalResult ExtractSliceOfPadTensorSwapPattern::matchAndRewrite(
723     tensor::ExtractSliceOp sliceOp, PatternRewriter &rewriter) const {
724   auto padOp = sliceOp.source().getDefiningOp<PadTensorOp>();
725   if (!padOp)
726     return failure();
727   // Only unit stride supported.
728   if (!sliceOp.hasUnitStride())
729     return failure();
730   // Only constant padding value supported.
731   Value padValue = padOp.getConstantPaddingValue();
732   if (!padValue)
733     return failure();
734 
735   // Helper variables and functions for various arithmetic operations. These are
736   // used extensively for computing new offset/length and padding values.
737   Location loc = sliceOp.getLoc();
738   AffineExpr dim0, dim1;
739   bindDims(rewriter.getContext(), dim0, dim1);
740   // Add two integers.
741   auto addMap = AffineMap::get(2, 0, {dim0 + dim1});
742   auto add = [&](Value v1, Value v2) {
743     return rewriter.createOrFold<AffineApplyOp>(loc, addMap,
744                                                 ValueRange{v1, v2});
745   };
746   // Subtract two integers.
747   auto subMap = AffineMap::get(2, 0, {dim0 - dim1});
748   auto sub = [&](Value v1, Value v2) {
749     return rewriter.createOrFold<AffineApplyOp>(loc, subMap,
750                                                 ValueRange{v1, v2});
751   };
752   // Take the minimum of two integers.
753   auto idMap = AffineMap::getMultiDimIdentityMap(2, rewriter.getContext());
754   auto min = [&](Value v1, Value v2) {
755     return rewriter.createOrFold<AffineMinOp>(loc, idMap, ValueRange{v1, v2});
756   };
757   // Take the maximum of two integers.
758   auto max = [&](Value v1, Value v2) {
759     return rewriter.createOrFold<AffineMaxOp>(loc, idMap, ValueRange{v1, v2});
760   };
761   // Zero index-typed integer.
762   auto zero = rewriter.create<ConstantIndexOp>(loc, 0);
763 
764   // Helper function for filling static/dynamic low/high padding indices vectors
765   // of PadTensorOp.
766   auto appendIndex = [&](Value val, SmallVector<Value> &dynIndices,
767                          SmallVector<int64_t> &staticIndices) {
768     if (auto constInt = getConstantIntValue(val)) {
769       staticIndices.push_back(*constInt);
770     } else {
771       staticIndices.push_back(ShapedType::kDynamicSize);
772       dynIndices.push_back(val);
773     }
774   };
775 
776   // Compute new offsets, lengths, low padding, high padding.
777   SmallVector<OpFoldResult> newOffsets, newLengths, newStrides;
778   SmallVector<Value> newLows, newHighs;
779   SmallVector<int64_t> staticNewLows, staticNewHighs;
780   // Set to true if the original data source is not read at all.
781   bool hasZeroLen = false;
782   // Same as hasZeroLen, but for dynamic dimension sizes. This condition
783   // is true if the original data source turns out to be unused at runtime.
784   Value dynHasZeroLenCond;
785 
786   int64_t rank = padOp.getSourceType().getRank();
787   for (unsigned dim = 0; dim < rank; ++dim) {
788     auto low = asValue(rewriter, loc, padOp.getMixedLowPad()[dim]);
789     auto offset = asValue(rewriter, loc, sliceOp.getMixedOffsets()[dim]);
790     auto length = asValue(rewriter, loc, sliceOp.getMixedSizes()[dim]);
791     auto srcSize = rewriter.createOrFold<memref::DimOp>(
792         loc, padOp.source(), dim);
793 
794     // The new amount of low padding is `low - offset`. Except for the case
795     // where none of the low padding is read. In that case, the new amount of
796     // low padding is zero.
797     Value newLow = max(zero, sub(low, offset));
798     appendIndex(newLow, newLows, staticNewLows);
799 
800     // Start reading the data from position `offset - low`. Since the original
801     // read may have started in the low padding zone, this value could be
802     // negative. Therefore, start reading from:
803     //
804     // max(offset - low, 0)
805     //
806     // The original read could also have started in the high padding zone.
807     // In that case, set the offset to the end of source tensor. The new
808     // ExtractSliceOp length will be zero in that case. (Effectively reading no
809     // data from the source.)
810     Value newOffset = min(max(sub(offset, low), zero), srcSize);
811     newOffsets.push_back(asOpFoldResult(rewriter, newOffset));
812 
813     // The original ExtractSliceOp was reading until position `offset + length`.
814     // Therefore, the corresponding position within the source tensor is:
815     //
816     // offset + length - low
817     //
818     // In case the original ExtractSliceOp stopped reading within the low
819     // padding zone, this value can be negative. In that case, the end position
820     // of the read should be zero. (Similar to newOffset.)
821     //
822     // The original read could also have stopped in the high padding zone.
823     // In that case, set the end positition of the read should be the end of the
824     // source tensor. (Similar to newOffset.)
825     //
826     // endLoc = min(max(offset - low + length, 0), srcSize)
827     //
828     // The new ExtractSliceOp length is `endLoc - newOffset`.
829     Value endLoc = min(max(add(sub(offset, low), length), zero), srcSize);
830     Value newLength = sub(endLoc, newOffset);
831     newLengths.push_back(asOpFoldResult(rewriter, newLength));
832 
833     // Check if newLength is zero. In that case, no SubTensorOp should be
834     // executed.
835     if (auto newLengthInt = getConstantIntValue(newLength)) {
836       hasZeroLen |= *newLengthInt == 0;
837     } else {
838       Value check = rewriter.create<CmpIOp>(
839           loc, CmpIPredicate::eq, newLength, zero);
840       dynHasZeroLenCond =
841           dynHasZeroLenCond
842               ? rewriter.create<OrOp>(loc, check, dynHasZeroLenCond)
843               : check;
844     }
845 
846     // The amount of high padding is simply the number of elements remaining,
847     // so that the result has the same length as the original ExtractSliceOp.
848     Value newHigh = sub(sub(length, newLength), newLow);
849     appendIndex(newHigh, newHighs, staticNewHighs);
850 
851     // Only unit stride supported.
852     newStrides.push_back(rewriter.getIndexAttr(1));
853   }
854 
855   // Insert cast to ensure that types match. (May be folded away.)
856   auto castResult = [&](Value val) -> Value {
857     auto castOp = rewriter.create<tensor::CastOp>(loc, sliceOp.getType(), val);
858     return castOp;
859   };
860 
861   // In cases where the original data source is unused: Emit a GenerateOp and
862   // do not generate a SliceOp. (The result shape of the SliceOp would
863   // have a dimension of size 0, the semantics of which is unclear.)
864   auto createGenerateOp = [&]() {
865     // The shape of the GenerateOp is the same as the existing SliceOp.
866     RankedTensorType type = sliceOp.getType();
867     SmallVector<Value> dynDims;
868     for (unsigned i = 0; i < type.getRank(); ++i) {
869       if (type.isDynamicDim(i))
870         dynDims.push_back(asValue(rewriter, loc, sliceOp.getMixedOffsets()[i]));
871     }
872 
873     // Create GenerateOp.
874     auto generateOp  = rewriter.create<tensor::GenerateOp>(loc, type, dynDims);
875 
876     // Copy region to new op.
877     BlockAndValueMapping bvm;
878     padOp.region().cloneInto(&generateOp.getRegion(), bvm);
879     // Rewrite linalg::YieldOp to tensor::YieldOp.
880     {
881       OpBuilder::InsertionGuard guard(rewriter);
882       auto yieldOp = dyn_cast<linalg::YieldOp>(
883           generateOp.getRegion().front().getTerminator());
884       assert(yieldOp && "malformed PadTensorOp: expected YieldOp terminator");
885       assert(yieldOp.values().size() == 1);
886       rewriter.setInsertionPoint(yieldOp);
887       rewriter.replaceOpWithNewOp<tensor::YieldOp>(
888           yieldOp, yieldOp.values()[0]);
889     }
890 
891     return castResult(generateOp);
892   };
893 
894   // Emit a SliceOp and a PadTensorOp. Should not be used in cases where
895   // the result shape of the new SliceOp has a zero dimension.
896   auto createPadTensorOfSubTensor = [&]() {
897     // Create pad_tensor(subtensor(x)).
898     auto newSliceOp = rewriter.create<tensor::ExtractSliceOp>(
899         loc, padOp.source(), newOffsets, newLengths, newStrides);
900     auto newPadTensorOp = rewriter.create<PadTensorOp>(
901         loc, newSliceOp, staticNewLows, staticNewHighs, newLows, newHighs);
902 
903     // Copy region to new PadTensorOp.
904     BlockAndValueMapping bvm;
905     padOp.region().cloneInto(&newPadTensorOp.getRegion(), bvm);
906 
907     // Cast result and return.
908     return castResult(newPadTensorOp);
909   };
910 
911   // Rewrite subtensor(pad_tensor(x)) into a GenerateOp it is statically known
912   // that the original data source x is not used.
913   if (hasZeroLen) {
914     rewriter.replaceOp(sliceOp, createGenerateOp());
915     return success();
916   }
917 
918   // If there are dynamic dimensions: Generate an scf.if check to avoid creating
919   // SliceOps with result dimensions of size 0 at runtime.
920   if (dynHasZeroLenCond) {
921     auto result = rewriter.create<scf::IfOp>(
922         loc, sliceOp.getType(), dynHasZeroLenCond,
923         /*thenBuilder=*/
924         [&](OpBuilder &b, Location loc) {
925           b.create<scf::YieldOp>(loc, createGenerateOp());
926         },
927         /*elseBuilder=*/
928         [&](OpBuilder &b, Location loc) {
929           b.create<scf::YieldOp>(loc, createPadTensorOfSubTensor());
930         });
931     rewriter.replaceOp(sliceOp, result.getResult(0));
932     return success();
933   }
934 
935   // All shapes are static and the data source is actually used. Rewrite into
936   // pad_tensor(subtensor(x)).
937   rewriter.replaceOp(sliceOp, createPadTensorOfSubTensor());
938   return success();
939 }
940