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 not abstracted away the call+callee relationship. When the inlining
11// interface has this support, this pass should be removed.
12//
13//===----------------------------------------------------------------------===//
14
15#include "TestOpsCore.h"
16#include "mlir/Dialect/Func/IR/FuncOps.h"
17#include "mlir/IR/BuiltinOps.h"
18#include "mlir/IR/IRMapping.h"
19#include "mlir/Pass/Pass.h"
20#include "mlir/Transforms/Inliner.h"
21#include "mlir/Transforms/InliningUtils.h"
22#include "llvm/ADT/StringSet.h"
23
24using namespace mlir;
25using namespace test;
26
27namespace {
28struct InlinerTest
29 : public PassWrapper<InlinerTest, OperationPass<func::FuncOp>> {
30 MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(InlinerTest)
31
32 StringRef getArgument() const final { return "test-inline"; }
33 StringRef getDescription() const final {
34 return "Test inlining region calls";
35 }
36
37 void runOnOperation() override {
38 InlinerConfig config;
39
40 auto function = getOperation();
41
42 // Collect each of the direct function calls within the module.
43 SmallVector<func::CallIndirectOp, 16> callers;
44 function.walk(
45 callback: [&](func::CallIndirectOp caller) { callers.push_back(Elt: caller); });
46
47 // Build the inliner interface.
48 InlinerInterface interface(&getContext());
49
50 // Try to inline each of the call operations.
51 for (auto caller : callers) {
52 auto callee = dyn_cast_or_null<FunctionalRegionOp>(
53 caller.getCallee().getDefiningOp());
54 if (!callee)
55 continue;
56
57 // Inline the functional region operation, but only clone the internal
58 // region if there is more than one use.
59 if (failed(inlineRegion(
60 interface, config.getCloneCallback(), &callee.getBody(), caller,
61 caller.getArgOperands(), caller.getResults(), caller.getLoc(),
62 /*shouldCloneInlinedRegion=*/!callee.getResult().hasOneUse())))
63 continue;
64
65 // If the inlining was successful then erase the call and callee if
66 // possible.
67 caller.erase();
68 if (callee.use_empty())
69 callee.erase();
70 }
71 }
72};
73} // namespace
74
75namespace mlir {
76namespace test {
77void registerInliner() { PassRegistration<InlinerTest>(); }
78} // namespace test
79} // namespace mlir
80