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/Utils/StructuredOpsUtils.h"
20 #include "mlir/Dialect/Vector/VectorOps.h"
21 #include "mlir/IR/AffineExpr.h"
22 #include "mlir/IR/Matchers.h"
23 #include "mlir/Pass/Pass.h"
24 #include "mlir/Support/LLVM.h"
25 #include "mlir/Transforms/GreedyPatternRewriteDriver.h"
26 #include "llvm/ADT/ScopeExit.h"
27 #include "llvm/Support/Debug.h"
28 #include "llvm/Support/raw_ostream.h"
29 #include <type_traits>
30 
31 #define DEBUG_TYPE "linalg-transforms"
32 
33 using namespace mlir;
34 using namespace mlir::linalg;
35 
36 #define DBGS() (llvm::dbgs() << "[" DEBUG_TYPE << "]: ")
37 
38 //===----------------------------------------------------------------------===//
39 // Transformations exposed as rewrite patterns.
40 //===----------------------------------------------------------------------===//
41 // Marker used as attribute name in generated Linalg rewriting transformations.
42 const StringLiteral mlir::linalg::LinalgTransforms::kLinalgTransformMarker =
43     "__internal_linalg_transform__";
44 
45 mlir::linalg::LinalgTransformationFilter::LinalgTransformationFilter(
46     ArrayRef<Identifier> matchDisjunction, Optional<Identifier> replacement)
47     : matchDisjunction(matchDisjunction.begin(), matchDisjunction.end()),
48       replacement(replacement) {}
49 
50 mlir::linalg::LinalgTransformationFilter::LinalgTransformationFilter(
51     FilterFunction f, ArrayRef<Identifier> matchDisjunction,
52     Optional<Identifier> replacement)
53     : filters(),
54       matchDisjunction(matchDisjunction.begin(), matchDisjunction.end()),
55       replacement(replacement) {
56   if (f)
57     filters.push_back(f);
58 }
59 
60 LogicalResult mlir::linalg::LinalgTransformationFilter::checkAndNotify(
61     PatternRewriter &rewriter, Operation *op) const {
62   if (llvm::any_of(filters,
63                    [&](const FilterFunction &f) { return failed(f(op)); }))
64     return failure();
65 
66   auto attr = op->template getAttrOfType<StringAttr>(
67       LinalgTransforms::kLinalgTransformMarker);
68 
69   if (!attr) {
70     // 1. Has no filter case and matchDisjunction is empty.
71     if (matchDisjunction.empty())
72       return success();
73 
74     // 2. Has no filter but was expecting a filter.
75     return rewriter.notifyMatchFailure(op, [&](Diagnostic &diag) {
76       diag << " does not have any filter from list: ";
77       interleaveComma(matchDisjunction, diag);
78     });
79   }
80 
81   // 4. Match explicit filter.
82   for (auto filter : matchDisjunction)
83     if (attr.getValue() == filter)
84       return success();
85 
86   // 5. Fail to match.
87   return rewriter.notifyMatchFailure(op, [&](Diagnostic &diag) {
88     diag << " does not have any filter from list: ";
89     interleaveComma(matchDisjunction, diag);
90   });
91 }
92 
93 void mlir::linalg::LinalgTransformationFilter::
94     replaceLinalgTransformationFilter(PatternRewriter &rewriter,
95                                       Operation *op) const {
96   if (replacement.hasValue())
97     op->setAttr(LinalgTransforms::kLinalgTransformMarker,
98                 rewriter.getStringAttr(replacement.getValue().strref()));
99   else
100     op->removeAttr(Identifier::get(LinalgTransforms::kLinalgTransformMarker,
101                                    rewriter.getContext()));
102 }
103 
104 LinalgTilingOptions &
105 mlir::linalg::LinalgTilingOptions::setTileSizes(ArrayRef<int64_t> ts) {
106   SmallVector<int64_t, 4> tileSizes(ts.begin(), ts.end());
107   tileSizeComputationFunction = [tileSizes](OpBuilder &b, Operation *op) {
108     OpBuilder::InsertionGuard guard(b);
109     b.setInsertionPointToStart(
110         &op->getParentOfType<FuncOp>().getBody().front());
111     return llvm::to_vector<4>(map_range(tileSizes, [&](int64_t s) {
112       Value v = b.create<ConstantIndexOp>(op->getLoc(), s);
113       return v;
114     }));
115   };
116   return *this;
117 }
118 
119 /// Try to compute a static bounding box for `operand`
120 /// Return success if either:
121 ///   1. The operand is already statically shaped, `result` is left unchanged.
122 ///   2. The operand is (partially) dynamic, `result` is the result of a freshly
123 ///      created PadTensorOp.
124 /// Return failure if the operand cannot be padded to a static shape.
125 static LogicalResult padOperandToSmallestStaticBoundingBox(
126     PatternRewriter &rewriter, linalg::LinalgOp opToPad, OpOperand *opOperand,
127     const LinalgTilingOptions &options, Value &result) {
128   // Already static shape, no need to pad.
129   if (llvm::none_of(opToPad.getShape(opOperand), ShapedType::isDynamic))
130     return success();
131   auto subtensor = opOperand->get().getDefiningOp<SubTensorOp>();
132   // Not a subtensor, cannot construct a static bounding box.
133   if (!subtensor)
134     return failure();
135   SmallVector<int64_t> staticSizes;
136   staticSizes.reserve(opToPad.getRank(opOperand));
137   auto shapedOp =
138       cast<OffsetSizeAndStrideOpInterface>(subtensor.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().getType()));
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 subtensor out of the new static results. This keeps the
199   // original 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<SubTensorOp>(
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, initTensor, padValue).result();
680 
681   // Copy original contents into new tensor
682   // Uses linalg.generic, but could be done with std.subtensor_insert
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