| 1 | //===- CSE.cpp - Common Sub-expression Elimination ------------------------===// |
| 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 the CSE pass. The actual CSE algorithm lives in |
| 10 | // mlir/lib/Transforms/Utils/CSE.cpp so that it can be invoked from other |
| 11 | // utilities (e.g. the greedy pattern rewrite driver). |
| 12 | // |
| 13 | //===----------------------------------------------------------------------===// |
| 14 | |
| 15 | #include "mlir/Transforms/CSE.h" |
| 16 | |
| 17 | #include "mlir/IR/Dominance.h" |
| 18 | #include "mlir/IR/PatternMatch.h" |
| 19 | #include "mlir/Pass/Pass.h" |
| 20 | |
| 21 | namespace mlir { |
| 22 | #define GEN_PASS_DEF_CSEPASS |
| 23 | #include "mlir/Transforms/Passes.h.inc" |
| 24 | } // namespace mlir |
| 25 | |
| 26 | using namespace mlir; |
| 27 | |
| 28 | namespace { |
| 29 | /// CSE pass. |
| 30 | struct CSE : public impl::CSEPassBase<CSE> { |
| 31 | void runOnOperation() override; |
| 32 | }; |
| 33 | } // namespace |
| 34 | |
| 35 | void CSE::runOnOperation() { |
| 36 | IRRewriter rewriter(&getContext()); |
| 37 | auto &domInfo = getAnalysis<DominanceInfo>(); |
| 38 | bool changed = false; |
| 39 | // `numCSE` / `numDCE` are `llvm::Statistic` objects, not raw `int64_t`, so |
| 40 | // the public API's out-parameters cannot point at them directly. |
| 41 | int64_t cseCount = 0; |
| 42 | int64_t dceCount = 0; |
| 43 | eliminateCommonSubExpressions(rewriter, domInfo, op: getOperation(), changed: &changed, |
| 44 | numCSE: &cseCount, numDCE: &dceCount); |
| 45 | |
| 46 | numCSE = cseCount; |
| 47 | numDCE = dceCount; |
| 48 | |
| 49 | // If there was no change to the IR, we mark all analyses as preserved. |
| 50 | if (!changed) |
| 51 | return markAllAnalysesPreserved(); |
| 52 | |
| 53 | // We only delete redundant operations without moving any operation to a |
| 54 | // different block, so the dominance tree structure remains unchanged and |
| 55 | // DominanceInfo/PostDominanceInfo can be safely preserved. |
| 56 | markAnalysesPreserved<DominanceInfo, PostDominanceInfo>(); |
| 57 | } |
| 58 | |