1 //===- TestConstantFold.cpp - Pass to test constant folding ---------------===//
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 #include "mlir/Pass/Pass.h"
10 #include "mlir/Transforms/FoldUtils.h"
11 #include "mlir/Transforms/Passes.h"
12 #include "mlir/Transforms/Utils.h"
13 
14 using namespace mlir;
15 
16 namespace {
17 /// Simple constant folding pass.
18 struct TestConstantFold
19     : public PassWrapper<TestConstantFold, OperationPass<FuncOp>> {
20   StringRef getArgument() const final { return "test-constant-fold"; }
21   StringRef getDescription() const final {
22     return "Test operation constant folding";
23   }
24   // All constants in the function post folding.
25   SmallVector<Operation *, 8> existingConstants;
26 
27   void foldOperation(Operation *op, OperationFolder &helper);
28   void runOnOperation() override;
29 };
30 } // namespace
31 
32 void TestConstantFold::foldOperation(Operation *op, OperationFolder &helper) {
33   auto processGeneratedConstants = [this](Operation *op) {
34     existingConstants.push_back(op);
35   };
36 
37   // Attempt to fold the specified operation, including handling unused or
38   // duplicated constants.
39   (void)helper.tryToFold(op, processGeneratedConstants);
40 }
41 
42 // For now, we do a simple top-down pass over a function folding constants.  We
43 // don't handle conditional control flow, block arguments, folding conditional
44 // branches, or anything else fancy.
45 void TestConstantFold::runOnOperation() {
46   existingConstants.clear();
47 
48   // Collect and fold the operations within the function.
49   SmallVector<Operation *, 8> ops;
50   getOperation().walk([&](Operation *op) { ops.push_back(op); });
51 
52   // Fold the constants in reverse so that the last generated constants from
53   // folding are at the beginning. This creates somewhat of a linear ordering to
54   // the newly generated constants that matches the operation order and improves
55   // the readability of test cases.
56   OperationFolder helper(&getContext());
57   for (Operation *op : llvm::reverse(ops))
58     foldOperation(op, helper);
59 
60   // By the time we are done, we may have simplified a bunch of code, leaving
61   // around dead constants.  Check for them now and remove them.
62   for (auto *cst : existingConstants) {
63     if (cst->use_empty())
64       cst->erase();
65   }
66 }
67 
68 namespace mlir {
69 namespace test {
70 void registerTestConstantFold() { PassRegistration<TestConstantFold>(); }
71 } // namespace test
72 } // namespace mlir
73