1 //===- TestInlining.cpp - Pass to inline calls in the test dialect --------===//
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 // TODO: This pass is only necessary because the main inlining pass
10 // has no abstracted away the call+callee relationship. When the inlining
11 // interface has this support, this pass should be removed.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "TestDialect.h"
16 #include "mlir/Dialect/StandardOps/IR/Ops.h"
17 #include "mlir/IR/BlockAndValueMapping.h"
18 #include "mlir/IR/Function.h"
19 #include "mlir/Pass/Pass.h"
20 #include "mlir/Transforms/InliningUtils.h"
21 #include "mlir/Transforms/Passes.h"
22 #include "llvm/ADT/StringSet.h"
23 
24 using namespace mlir;
25 
26 namespace {
27 struct Inliner : public PassWrapper<Inliner, FunctionPass> {
28   void runOnFunction() override {
29     auto function = getFunction();
30 
31     // Collect each of the direct function calls within the module.
32     SmallVector<CallIndirectOp, 16> callers;
33     function.walk([&](CallIndirectOp caller) { callers.push_back(caller); });
34 
35     // Build the inliner interface.
36     InlinerInterface interface(&getContext());
37 
38     // Try to inline each of the call operations.
39     for (auto caller : callers) {
40       auto callee = dyn_cast_or_null<FunctionalRegionOp>(
41           caller.getCallee().getDefiningOp());
42       if (!callee)
43         continue;
44 
45       // Inline the functional region operation, but only clone the internal
46       // region if there is more than one use.
47       if (failed(inlineRegion(
48               interface, &callee.body(), caller, caller.getArgOperands(),
49               caller.getResults(), caller.getLoc(),
50               /*shouldCloneInlinedRegion=*/!callee.getResult().hasOneUse())))
51         continue;
52 
53       // If the inlining was successful then erase the call and callee if
54       // possible.
55       caller.erase();
56       if (callee.use_empty())
57         callee.erase();
58     }
59   }
60 };
61 } // end anonymous namespace
62 
63 namespace mlir {
64 void registerInliner() {
65   PassRegistration<Inliner>("test-inline", "Test inlining region calls");
66 }
67 } // namespace mlir
68