1 //===- Canonicalizer.cpp - Canonicalize MLIR operations -------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This transformation pass converts operations into their canonical forms by
10 // folding constants, applying operation identity transformations etc.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "mlir/IR/PatternMatch.h"
15 #include "mlir/Pass/Pass.h"
16 #include "mlir/Transforms/Passes.h"
17 
18 using namespace mlir;
19 
20 namespace {
21 /// Canonicalize operations in nested regions.
22 struct Canonicalizer : public OperationPass<Canonicalizer> {
23 /// Include the generated pass utilities.
24 #define GEN_PASS_Canonicalizer
25 #include "mlir/Transforms/Passes.h.inc"
26 
27   void runOnOperation() override {
28     OwningRewritePatternList patterns;
29 
30     // TODO: Instead of adding all known patterns from the whole system lazily
31     // add and cache the canonicalization patterns for ops we see in practice
32     // when building the worklist.  For now, we just grab everything.
33     auto *context = &getContext();
34     for (auto *op : context->getRegisteredOperations())
35       op->getCanonicalizationPatterns(patterns, context);
36 
37     Operation *op = getOperation();
38     applyPatternsGreedily(op->getRegions(), patterns);
39   }
40 };
41 } // end anonymous namespace
42 
43 /// Create a Canonicalizer pass.
44 std::unique_ptr<Pass> mlir::createCanonicalizerPass() {
45   return std::make_unique<Canonicalizer>();
46 }
47