1 //===- DynamicPass.cpp - Implementation of a dynamic configurable pass ----===//
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 a configurable pass that can apply patterns liberally
10 // and be plugged in a pass pipeline.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "PassDetail.h"
15 #include "mlir/Analysis/SliceAnalysis.h"
16 #include "mlir/Dialect/Affine/IR/AffineOps.h"
17 #include "mlir/Dialect/Linalg/IR/LinalgOps.h"
18 #include "mlir/Dialect/Linalg/IR/LinalgTypes.h"
19 #include "mlir/Dialect/Linalg/Passes.h"
20 #include "mlir/Dialect/Linalg/Transforms/Hoisting.h"
21 #include "mlir/Dialect/Linalg/Transforms/Transforms.h"
22 #include "mlir/Dialect/Linalg/Utils/Utils.h"
23 #include "mlir/Dialect/SCF/Transforms.h"
24 #include "mlir/Dialect/Tensor/IR/Tensor.h"
25 #include "mlir/Dialect/Vector/VectorTransforms.h"
26 #include "mlir/IR/AffineExpr.h"
27 #include "mlir/IR/AffineMap.h"
28 #include "mlir/Pass/PassManager.h"
29 #include "mlir/Support/LLVM.h"
30 #include "mlir/Transforms/GreedyPatternRewriteDriver.h"
31 #include "mlir/Transforms/LoopUtils.h"
32 #include "mlir/Transforms/Passes.h"
33 #include "mlir/Transforms/Utils.h"
34 
35 using namespace mlir;
36 using namespace mlir::vector;
37 using namespace linalg;
38 
39 namespace {
40 
41 /// Configurable pass to apply pattern-based tiling and fusion.
42 struct LinalgStrategyTileAndFusePass
43     : public LinalgStrategyTileAndFusePassBase<LinalgStrategyTileAndFusePass> {
44 
45   LinalgStrategyTileAndFusePass() = default;
46 
47   LinalgStrategyTileAndFusePass(StringRef opName,
48                                 LinalgTilingAndFusionOptions opt,
49                                 LinalgTransformationFilter filt)
50       : options(opt), filter(filt) {
51     this->anchorOpName.setValue(opName.str());
52   }
53 
54   void runOnFunction() override {
55     auto funcOp = getFunction();
56     if (!anchorFuncName.empty() && funcOp.getName() != anchorFuncName)
57       return;
58 
59     RewritePatternSet tilingAndFusionPattern(funcOp.getContext());
60     if (!anchorOpName.empty()) {
61       tilingAndFusionPattern.add<LinalgTileAndFuseTensorOpsPattern>(
62           anchorOpName, funcOp.getContext(), options, filter);
63     } else {
64       tilingAndFusionPattern.add<LinalgTileAndFuseTensorOpsPattern>(
65           funcOp.getContext(), options, filter);
66     }
67     // Search the root operation using bottom up traversal.
68     GreedyRewriteConfig config;
69     config.useTopDownTraversal = false;
70     (void)applyPatternsAndFoldGreedily(
71         funcOp, std::move(tilingAndFusionPattern), config);
72   }
73 
74   LinalgTilingAndFusionOptions options;
75   LinalgTransformationFilter filter;
76 };
77 
78 /// Configurable pass to apply pattern-based linalg tiling.
79 struct LinalgStrategyTilePass
80     : public LinalgStrategyTilePassBase<LinalgStrategyTilePass> {
81 
82   LinalgStrategyTilePass() = default;
83 
84   LinalgStrategyTilePass(StringRef opName, LinalgTilingOptions opt,
85                          LinalgTransformationFilter filt)
86       : options(opt), filter(filt) {
87     this->anchorOpName.setValue(opName.str());
88   }
89 
90   void runOnFunction() override {
91     auto funcOp = getFunction();
92     if (!anchorFuncName.empty() && funcOp.getName() != anchorFuncName)
93       return;
94 
95     RewritePatternSet tilingPattern(funcOp.getContext());
96     if (!anchorOpName.empty()) {
97       tilingPattern.add<LinalgGenericTilingPattern>(
98           anchorOpName, funcOp.getContext(), options, filter);
99     } else {
100       tilingPattern.add<LinalgGenericTilingPattern>(funcOp.getContext(), filter,
101                                                     options);
102     }
103     (void)applyPatternsAndFoldGreedily(funcOp, std::move(tilingPattern));
104   }
105 
106   LinalgTilingOptions options;
107   LinalgTransformationFilter filter;
108 };
109 
110 /// Configurable pass to apply hoisting and padding.
111 struct LinalgStrategyPadPass
112     : public LinalgStrategyPadPassBase<LinalgStrategyPadPass> {
113 
114   LinalgStrategyPadPass() = default;
115 
116   LinalgStrategyPadPass(StringRef opName, LinalgPaddingOptions opt,
117                         LinalgTransformationFilter filt)
118       : options(opt), filter(filt) {
119     this->anchorOpName.setValue(opName.str());
120   }
121 
122   void runOnFunction() override {
123     auto funcOp = getFunction();
124     if (!anchorFuncName.empty() && funcOp.getName() != anchorFuncName)
125       return;
126 
127     RewritePatternSet paddingPattern(funcOp.getContext());
128     if (!anchorOpName.empty()) {
129       paddingPattern.add<LinalgPaddingPattern>(
130           anchorOpName, funcOp.getContext(), options, filter);
131     } else {
132       paddingPattern.add<LinalgPaddingPattern>(funcOp.getContext(), options,
133                                                filter);
134     }
135     (void)applyPatternsAndFoldGreedily(funcOp, std::move(paddingPattern));
136   }
137 
138   LinalgPaddingOptions options;
139   LinalgTransformationFilter filter;
140 };
141 
142 /// Configurable pass to apply pattern-based linalg generalization.
143 struct LinalgStrategyGeneralizePass
144     : public LinalgStrategyGeneralizePassBase<LinalgStrategyGeneralizePass> {
145 
146   LinalgStrategyGeneralizePass() = default;
147 
148   LinalgStrategyGeneralizePass(StringRef opName,
149                                LinalgTransformationFilter filter)
150       : filter(filter) {
151     this->anchorOpName.setValue(opName.str());
152   }
153 
154   void runOnFunction() override {
155     auto funcOp = getFunction();
156     if (!anchorFuncName.empty() && funcOp.getName() != anchorFuncName)
157       return;
158 
159     RewritePatternSet generalizationPattern(funcOp.getContext());
160     if (!anchorOpName.empty()) {
161       generalizationPattern.add<LinalgGeneralizationPattern>(
162           anchorOpName, funcOp.getContext(), filter);
163     } else {
164       generalizationPattern.add<LinalgGeneralizationPattern>(
165           funcOp.getContext(), filter);
166     }
167     if (failed(applyPatternsAndFoldGreedily(funcOp,
168                                             std::move(generalizationPattern))))
169       signalPassFailure();
170   }
171 
172   LinalgTransformationFilter filter;
173 };
174 
175 /// Configurable pass to apply lowering of coarser-grained named linalg ops into
176 /// finer-grained named versions.
177 struct LinalgStrategyDecomposePass
178     : public LinalgStrategyDecomposePassBase<LinalgStrategyDecomposePass> {
179 
180   LinalgStrategyDecomposePass() = default;
181 
182   LinalgStrategyDecomposePass(LinalgTransformationFilter filter)
183       : filter(filter) {}
184 
185   void runOnFunction() override {
186     auto funcOp = getFunction();
187     if (!anchorFuncName.empty() && funcOp.getName() != anchorFuncName)
188       return;
189     RewritePatternSet decompositionPattern(funcOp.getContext());
190     populateDecomposeConvolutionPatterns(decompositionPattern, filter);
191     if (failed(applyPatternsAndFoldGreedily(funcOp,
192                                             std::move(decompositionPattern))))
193       signalPassFailure();
194   }
195 
196   LinalgTransformationFilter filter;
197 };
198 
199 /// Configurable pass to apply pattern-based linalg generalization.
200 struct LinalgStrategyInterchangePass
201     : public LinalgStrategyInterchangePassBase<LinalgStrategyInterchangePass> {
202 
203   LinalgStrategyInterchangePass() = default;
204 
205   LinalgStrategyInterchangePass(ArrayRef<int64_t> iteratorInterchange,
206                                 LinalgTransformationFilter filter)
207       : iteratorInterchange(iteratorInterchange.begin(),
208                             iteratorInterchange.end()),
209         filter(filter) {}
210 
211   void runOnFunction() override {
212     auto funcOp = getFunction();
213     if (!anchorFuncName.empty() && funcOp.getName() != anchorFuncName)
214       return;
215 
216     SmallVector<unsigned> interchangeVector(iteratorInterchange.begin(),
217                                             iteratorInterchange.end());
218     RewritePatternSet interchangePattern(funcOp.getContext());
219     interchangePattern.add<GenericOpInterchangePattern>(
220         funcOp.getContext(), interchangeVector, filter);
221     if (failed(applyPatternsAndFoldGreedily(funcOp,
222                                             std::move(interchangePattern))))
223       signalPassFailure();
224   }
225 
226   SmallVector<int64_t> iteratorInterchange;
227   LinalgTransformationFilter filter;
228 };
229 
230 /// Configurable pass to apply pattern-based linalg promotion.
231 struct LinalgStrategyPromotePass
232     : public LinalgStrategyPromotePassBase<LinalgStrategyPromotePass> {
233 
234   LinalgStrategyPromotePass() = default;
235 
236   LinalgStrategyPromotePass(StringRef opName, LinalgPromotionOptions opt,
237                             LinalgTransformationFilter filt)
238       : options(opt), filter(filt) {
239     this->anchorOpName.setValue(opName.str());
240   }
241 
242   void runOnFunction() override {
243     auto funcOp = getFunction();
244     if (!anchorFuncName.empty() && funcOp.getName() != anchorFuncName)
245       return;
246 
247     RewritePatternSet promotionPattern(funcOp.getContext());
248     if (!anchorOpName.empty()) {
249       promotionPattern.add<LinalgBasePromotionPattern>(
250           anchorOpName, funcOp.getContext(), options, filter);
251     } else {
252       promotionPattern.add<LinalgBasePromotionPattern>(funcOp.getContext(),
253                                                        filter, options);
254     }
255     (void)applyPatternsAndFoldGreedily(funcOp, std::move(promotionPattern));
256   }
257 
258   LinalgPromotionOptions options;
259   LinalgTransformationFilter filter;
260 };
261 
262 /// Configurable pass to apply pattern-based linalg vectorization.
263 struct LinalgStrategyVectorizePass
264     : public LinalgStrategyVectorizePassBase<LinalgStrategyVectorizePass> {
265 
266   LinalgStrategyVectorizePass() = default;
267 
268   LinalgStrategyVectorizePass(StringRef opName, LinalgVectorizationOptions opt,
269                               LinalgTransformationFilter filt,
270                               bool padVectorize = false)
271       : options(opt), filter(filt) {
272     this->anchorOpName.setValue(opName.str());
273     this->vectorizePadding.setValue(padVectorize);
274   }
275 
276   void runOnFunction() override {
277     auto funcOp = getFunction();
278     if (!anchorFuncName.empty() && funcOp.getName() != anchorFuncName)
279       return;
280 
281     RewritePatternSet vectorizationPatterns(funcOp.getContext());
282     if (!anchorOpName.empty()) {
283       vectorizationPatterns.add<LinalgVectorizationPattern>(
284           anchorOpName, funcOp.getContext(), options, filter);
285     } else {
286       vectorizationPatterns.add<LinalgVectorizationPattern>(funcOp.getContext(),
287                                                             filter, options);
288     }
289     vector::populateVectorTransferPermutationMapLoweringPatterns(
290         vectorizationPatterns);
291     vector::populateVectorReductionToContractPatterns(vectorizationPatterns);
292     vectorizationPatterns.add<linalg::LinalgCopyVTRForwardingPattern,
293                               linalg::LinalgCopyVTWForwardingPattern>(
294         funcOp.getContext(), /*benefit=*/2);
295     if (vectorizePadding) {
296       linalg::populatePadTensorOpVectorizationPatterns(vectorizationPatterns);
297     }
298     (void)applyPatternsAndFoldGreedily(funcOp,
299                                        std::move(vectorizationPatterns));
300   }
301 
302   LinalgVectorizationOptions options;
303   LinalgTransformationFilter filter;
304 };
305 
306 /// Configurable pass to enable the application of other pattern-based linalg
307 /// passes.
308 struct LinalgStrategyEnablePass
309     : public LinalgStrategyEnablePassBase<LinalgStrategyEnablePass> {
310 
311   LinalgStrategyEnablePass(LinalgEnablingOptions opt,
312                            LinalgTransformationFilter filt)
313       : options(opt), filter(filt) {}
314 
315   void runOnFunction() override {
316     auto funcOp = getFunction();
317     if (!anchorFuncName.empty() && funcOp.getName() != anchorFuncName)
318       return;
319 
320     MLIRContext *context = funcOp.getContext();
321     RewritePatternSet patterns =
322         linalg::getLinalgTilingCanonicalizationPatterns(context);
323     scf::populateSCFForLoopCanonicalizationPatterns(patterns);
324     if (failed(applyPatternsAndFoldGreedily(funcOp, std::move(patterns))))
325       return signalPassFailure();
326 
327     if (options.licm) {
328       if (funcOp
329               ->walk([&](LoopLikeOpInterface loopLike) {
330                 if (failed(moveLoopInvariantCode(loopLike)))
331                   return WalkResult::interrupt();
332                 return WalkResult::advance();
333               })
334               .wasInterrupted())
335         return signalPassFailure();
336     }
337 
338     promoteSingleIterationLoops(funcOp);
339     if (options.hoistRedundantVectorTransfers)
340       hoistRedundantVectorTransfers(funcOp);
341 
342     if (options.hoistRedundantVectorTransfersOnTensor)
343       hoistRedundantVectorTransfersOnTensor(funcOp);
344 
345     // Run CSE to cleanup after canonicalization.
346     OpPassManager dynamicPM("builtin.func");
347     dynamicPM.addPass(createCSEPass());
348     if (failed(runPipeline(dynamicPM, funcOp)))
349       return signalPassFailure();
350   }
351 
352   LinalgEnablingOptions options;
353   LinalgTransformationFilter filter;
354 };
355 
356 /// Configurable pass to lower vector operations.
357 struct LinalgStrategyLowerVectorsPass
358     : public LinalgStrategyLowerVectorsPassBase<
359           LinalgStrategyLowerVectorsPass> {
360 
361   LinalgStrategyLowerVectorsPass(LinalgVectorLoweringOptions opt,
362                                  LinalgTransformationFilter filt)
363       : options(opt), filter(filt) {}
364 
365   void runOnFunction() override {
366     auto funcOp = getFunction();
367     if (!anchorFuncName.empty() && funcOp.getName() != anchorFuncName)
368       return;
369 
370     MLIRContext *context = funcOp.getContext();
371     RewritePatternSet patterns(context);
372     vector::populateVectorToVectorCanonicalizationPatterns(patterns);
373     // In a progressive lowering of vectors, this would be the 1st step.
374     if (options.contractionLowering) {
375       patterns.add<ContractionOpToOuterProductOpLowering,
376                    ContractionOpToMatmulOpLowering, ContractionOpLowering>(
377           options.vectorTransformOptions, context);
378       vector::populateVectorTransferPermutationMapLoweringPatterns(patterns);
379     }
380     // In a progressive lowering of vectors, this would be the 2nd step.
381     if (options.multiReductionLowering) {
382       vector::populateVectorMultiReductionLoweringPatterns(
383           patterns,
384           options.vectorTransformOptions.vectorMultiReductionLowering);
385     }
386     // In a progressive lowering of vectors, this would be the 3rd step.
387     if (options.transferPartialRewrite) {
388       patterns.add<vector::VectorTransferFullPartialRewriter>(
389           context, options.vectorTransformOptions);
390     }
391     // In a progressive lowering of vectors, this would be the 4th step.
392     if (options.transferLowering) {
393       vector::populateVectorTransferLoweringPatterns(patterns,
394                                                      options.maxTransferRank);
395     }
396     // In a progressive lowering of vectors, this would be the 5th step.
397     if (options.transferToSCFConversion) {
398       populateVectorToSCFConversionPatterns(
399           patterns, options.vectorTransferToSCFOptions.setTargetRank(
400                         options.maxTransferRank));
401     }
402     // In a progressive lowering of vectors, this would be the 6th step.
403     if (options.shapeCastLowering) {
404       vector::populateVectorShapeCastLoweringPatterns(patterns);
405     }
406     // In a progressive lowering of vectors, this would be the 7th step.
407     if (options.transposeLowering) {
408       vector::populateVectorTransposeLoweringPatterns(
409           patterns, options.vectorTransformOptions);
410       if (options.avx2Lowering)
411         x86vector::avx2::populateSpecializedTransposeLoweringPatterns(
412             patterns, options.avx2LoweringOptions, /*benefit=*/10);
413     }
414     (void)applyPatternsAndFoldGreedily(funcOp, std::move(patterns));
415   }
416 
417   LinalgVectorLoweringOptions options;
418   LinalgTransformationFilter filter;
419 };
420 
421 /// Configurable pass to lower vector operations.
422 struct LinalgStrategyRemoveMarkersPass
423     : public LinalgStrategyRemoveMarkersPassBase<
424           LinalgStrategyRemoveMarkersPass> {
425 
426   void runOnFunction() override {
427     auto funcOp = getFunction();
428     if (!anchorFuncName.empty() && funcOp.getName() != anchorFuncName)
429       return;
430     funcOp.walk([](LinalgOp op) {
431       op->removeAttr(LinalgTransforms::kLinalgTransformMarker);
432     });
433   }
434 };
435 } // namespace
436 
437 /// Create a LinalgStrategyTileAndFusePass.
438 std::unique_ptr<OperationPass<FuncOp>>
439 mlir::createLinalgStrategyTileAndFusePass(StringRef opName,
440                                           LinalgTilingAndFusionOptions options,
441                                           LinalgTransformationFilter filter) {
442   return std::make_unique<LinalgStrategyTileAndFusePass>(opName, options,
443                                                          filter);
444 }
445 
446 /// Create a LinalgStrategyTilePass.
447 std::unique_ptr<OperationPass<FuncOp>>
448 mlir::createLinalgStrategyTilePass(StringRef opName, LinalgTilingOptions opt,
449                                    LinalgTransformationFilter filter) {
450   return std::make_unique<LinalgStrategyTilePass>(opName, opt, filter);
451 }
452 
453 /// Create a LinalgStrategyPadPass.
454 std::unique_ptr<OperationPass<FuncOp>>
455 mlir::createLinalgStrategyPadPass(StringRef opName, LinalgPaddingOptions opt,
456                                   LinalgTransformationFilter filter) {
457   return std::make_unique<LinalgStrategyPadPass>(opName, opt, filter);
458 }
459 
460 /// Create a LinalgStrategyPromotePass.
461 std::unique_ptr<OperationPass<FuncOp>>
462 mlir::createLinalgStrategyPromotePass(StringRef opName,
463                                       LinalgPromotionOptions opt,
464                                       LinalgTransformationFilter filter) {
465   return std::make_unique<LinalgStrategyPromotePass>(opName, opt, filter);
466 }
467 
468 /// Create a LinalgStrategyGeneralizePass.
469 std::unique_ptr<OperationPass<FuncOp>>
470 mlir::createLinalgStrategyGeneralizePass(StringRef opName,
471                                          LinalgTransformationFilter filter) {
472   return std::make_unique<LinalgStrategyGeneralizePass>(opName, filter);
473 }
474 
475 /// Create a LinalgStrategyDecomposePass.
476 // TODO: if/when we need finer control add an `opName` parameter.
477 std::unique_ptr<OperationPass<FuncOp>>
478 mlir::createLinalgStrategyDecomposePass(LinalgTransformationFilter filter) {
479   return std::make_unique<LinalgStrategyDecomposePass>(filter);
480 }
481 
482 /// Create a LinalgStrategyInterchangePass.
483 std::unique_ptr<OperationPass<FuncOp>>
484 mlir::createLinalgStrategyInterchangePass(ArrayRef<int64_t> iteratorInterchange,
485                                           LinalgTransformationFilter filter) {
486   return std::make_unique<LinalgStrategyInterchangePass>(iteratorInterchange,
487                                                          filter);
488 }
489 
490 /// Create a LinalgStrategyVectorizePass.
491 std::unique_ptr<OperationPass<FuncOp>> mlir::createLinalgStrategyVectorizePass(
492     StringRef opName, LinalgVectorizationOptions opt,
493     LinalgTransformationFilter filter, bool padVectorize) {
494   return std::make_unique<LinalgStrategyVectorizePass>(opName, opt, filter,
495                                                        padVectorize);
496 }
497 
498 /// Create a LinalgStrategyEnablePass.
499 std::unique_ptr<OperationPass<FuncOp>>
500 mlir::createLinalgStrategyEnablePass(LinalgEnablingOptions opt,
501                                      LinalgTransformationFilter filter) {
502   return std::make_unique<LinalgStrategyEnablePass>(opt, filter);
503 }
504 
505 /// Create a LinalgStrategyLowerVectorsPass.
506 std::unique_ptr<OperationPass<FuncOp>>
507 mlir::createLinalgStrategyLowerVectorsPass(LinalgVectorLoweringOptions opt,
508                                            LinalgTransformationFilter filter) {
509   return std::make_unique<LinalgStrategyLowerVectorsPass>(opt, filter);
510 }
511 
512 /// Create a LinalgStrategyRemoveMarkersPass.
513 std::unique_ptr<OperationPass<FuncOp>>
514 mlir::createLinalgStrategyRemoveMarkersPass() {
515   return std::make_unique<LinalgStrategyRemoveMarkersPass>();
516 }
517