1 /* Copyright 2019 The TensorFlow Authors. All Rights Reserved.
2 
3 Licensed under the Apache License, Version 2.0 (the "License");
4 you may not use this file except in compliance with the License.
5 You may obtain a copy of the License at
6 
7     http://www.apache.org/licenses/LICENSE-2.0
8 
9 Unless required by applicable law or agreed to in writing, software
10 distributed under the License is distributed on an "AS IS" BASIS,
11 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 See the License for the specific language governing permissions and
13 limitations under the License.
14 ==============================================================================*/
15 
16 // This pass remove Cluster ops by inlining Cluster ops.
17 
18 #include "llvm/ADT/SmallVector.h"
19 #include "tensorflow/compiler/mlir/tensorflow/ir/tf_device.h"
20 #include "tensorflow/compiler/mlir/tensorflow/ir/tf_ops.h"
21 #include "tensorflow/compiler/mlir/tensorflow/ir/tf_types.h"
22 #include "tensorflow/compiler/mlir/tensorflow/transforms/passes.h"
23 #include "tensorflow/compiler/mlir/tensorflow/transforms/tf_device_passes_detail.h"
24 
25 namespace mlir {
26 
27 namespace {
28 // XlaInlineDeviceOps Pass will inline cluster op based in the parent region.
29 struct XlaInlineDeviceOpsPass
30     : public TFDevice::XlaInlineDeviceOpsPassBase<XlaInlineDeviceOpsPass> {
31   void runOnOperation() override;
32 };
33 
InlineDeviceOp(tf_device::ClusterOp cluster_op)34 void InlineDeviceOp(tf_device::ClusterOp cluster_op) {
35   auto& block = cluster_op.GetBody();
36 
37   llvm::SmallVector<Operation*, 4> non_terminator_ops;
38   for (Operation& op : block.without_terminator()) {
39     non_terminator_ops.push_back(&op);
40   }
41   for (auto op : non_terminator_ops) {
42     op->moveBefore(cluster_op);
43   }
44 
45   auto& return_op = cluster_op.GetBody().front();
46   // This is the last op, should be tf_device::ReturnOp.
47   assert(mlir::isa<mlir::tf_device::ReturnOp>(return_op));
48 
49   Value old_val, new_val;
50   for (auto it : llvm::zip(cluster_op.getResults(), return_op.getOperands())) {
51     std::tie(old_val, new_val) = it;
52     old_val.replaceAllUsesExcept(new_val, &return_op);
53   }
54 
55   cluster_op.erase();
56 }
57 
runOnOperation()58 void XlaInlineDeviceOpsPass::runOnOperation() {
59   ModuleOp module = getOperation();
60 
61   llvm::SmallVector<tf_device::ClusterOp, 4> ops;
62   module.walk(
63       [&](tf_device::ClusterOp cluster_op) { ops.push_back(cluster_op); });
64 
65   for (auto cluster_op : ops) {
66     InlineDeviceOp(cluster_op);
67   }
68 }
69 
70 }  // namespace
71 
72 namespace TFDevice {
CreateXlaInlineDeviceOpsPass()73 std::unique_ptr<OperationPass<ModuleOp>> CreateXlaInlineDeviceOpsPass() {
74   return std::make_unique<XlaInlineDeviceOpsPass>();
75 }
76 }  // namespace TFDevice
77 
78 }  // namespace mlir
79