xref: /llvm-project/mlir/lib/Conversion/ReconcileUnrealizedCasts/ReconcileUnrealizedCasts.cpp (revision a9f62244f28a64e7b7338c2299ba169df70fbb03)
1 //===- ReconcileUnrealizedCasts.cpp - Eliminate noop unrealized casts -----===//
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/Conversion/ReconcileUnrealizedCasts/ReconcileUnrealizedCasts.h"
10 
11 #include "mlir/IR/BuiltinOps.h"
12 #include "mlir/Pass/Pass.h"
13 #include "mlir/Transforms/DialectConversion.h"
14 
15 namespace mlir {
16 #define GEN_PASS_DEF_RECONCILEUNREALIZEDCASTS
17 #include "mlir/Conversion/Passes.h.inc"
18 } // namespace mlir
19 
20 using namespace mlir;
21 
22 namespace {
23 
24 /// Pass to simplify and eliminate unrealized conversion casts.
25 ///
26 /// This pass processes unrealized_conversion_cast ops in a worklist-driven
27 /// fashion. For each matched cast op, if the chain of input casts eventually
28 /// reaches a cast op where the input types match the output types of the
29 /// matched op, replace the matched op with the inputs.
30 ///
31 /// Example:
32 /// %1 = unrealized_conversion_cast %0 : !A to !B
33 /// %2 = unrealized_conversion_cast %1 : !B to !C
34 /// %3 = unrealized_conversion_cast %2 : !C to !A
35 ///
36 /// In the above example, %0 can be used instead of %3 and all cast ops are
37 /// folded away.
38 struct ReconcileUnrealizedCasts
39     : public impl::ReconcileUnrealizedCastsBase<ReconcileUnrealizedCasts> {
40   ReconcileUnrealizedCasts() = default;
41 
42   void runOnOperation() override {
43     SmallVector<UnrealizedConversionCastOp> ops;
44     getOperation()->walk(
45         [&](UnrealizedConversionCastOp castOp) { ops.push_back(castOp); });
46     reconcileUnrealizedCasts(ops);
47   }
48 };
49 
50 } // namespace
51 
52 std::unique_ptr<Pass> mlir::createReconcileUnrealizedCastsPass() {
53   return std::make_unique<ReconcileUnrealizedCasts>();
54 }
55