1 /* Copyright 2020 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 #include <algorithm>
17 #include <vector>
18 
19 #include "llvm/ADT/SetVector.h"
20 #include "llvm/ADT/SmallVector.h"
21 #include "mlir/Dialect/Func/IR/FuncOps.h"  // from @llvm-project
22 #include "mlir/IR/Builders.h"  // from @llvm-project
23 #include "mlir/IR/BuiltinOps.h"  // from @llvm-project
24 #include "mlir/IR/UseDefLists.h"  // from @llvm-project
25 #include "mlir/Pass/Pass.h"  // from @llvm-project
26 #include "mlir/Support/LLVM.h"  // from @llvm-project
27 #include "tensorflow/compiler/mlir/tensorflow/ir/tf_ops.h"
28 #include "tensorflow/compiler/mlir/tensorflow/ir/tf_saved_model.h"
29 #include "tensorflow/compiler/mlir/tensorflow/transforms/savedmodel_passes_detail.h"
30 
31 namespace mlir {
32 namespace tf_saved_model {
33 namespace {
34 using mlir::Operation;
35 using mlir::TF::VarHandleOp;
36 
37 class RemoveVariablesInSessionInitializerPass
38     : public RemoveVariablesInSessionInitializerPassBase<
39           RemoveVariablesInSessionInitializerPass> {
40  public:
41   void runOnOperation() override;
42 };
43 
RecursiveRemove(Operation * op,llvm::SmallVectorImpl<Operation * > & erase_list,llvm::SmallPtrSetImpl<Operation * > & dead_ops)44 void RecursiveRemove(Operation* op,
45                      llvm::SmallVectorImpl<Operation*>& erase_list,
46                      llvm::SmallPtrSetImpl<Operation*>& dead_ops) {
47   for (mlir::Value res : op->getResults()) {
48     for (Operation* user : res.getUsers()) {
49       if (!dead_ops.insert(user).second) continue;
50       RecursiveRemove(user, erase_list, dead_ops);
51     }
52   }
53 
54   erase_list.push_back(op);
55 
56   for (auto& use : op->getOpOperands()) {
57     if (auto op_result = use.get().dyn_cast<mlir::OpResult>()) {
58       Operation* def = op_result.getDefiningOp();
59       if (!dead_ops.insert(def).second) continue;
60       RecursiveRemove(def, erase_list, dead_ops);
61     }
62   }
63 }
64 
RemoveVariables(llvm::ArrayRef<VarHandleOp> vars)65 void RemoveVariables(llvm::ArrayRef<VarHandleOp> vars) {
66   // TODO(b/160906885): Repalce the following code with an non-recursive one.
67   llvm::SmallVector<Operation*, 4> erase_list;
68   llvm::SmallPtrSet<Operation*, 4> dead_ops;
69 
70   // Marks all the variables dead.
71   dead_ops.insert(vars.begin(), vars.end());
72 
73   // Removes relevant ops in topological order.
74   for (auto& op : vars) RecursiveRemove(op, erase_list, dead_ops);
75 
76   // Erases the ops.
77   for (auto op : erase_list) op->erase();
78 }
79 
runOnOperation()80 void RemoveVariablesInSessionInitializerPass::runOnOperation() {
81   ModuleOp module = getOperation();
82   SessionInitializerOp session_init_op = GetSessionInitializerOp(module);
83 
84   if (!session_init_op) return;
85 
86   SymbolTable symbol_table(module);
87 
88   for (auto sym_ref : session_init_op.initializers()) {
89     func::FuncOp init_func_op = symbol_table.lookup<mlir::func::FuncOp>(
90         sym_ref.cast<FlatSymbolRefAttr>().getValue());
91 
92     if (!init_func_op) {
93       module.emitError("no session initializer function found");
94       return signalPassFailure();
95     }
96 
97     if (init_func_op.getBlocks().size() != 1) {
98       init_func_op.emitError("expects exactly one block in the MLIR function");
99       return signalPassFailure();
100     }
101 
102     auto var_handle_ops =
103         init_func_op.getBlocks().front().getOps<VarHandleOp>();
104     llvm::SmallVector<VarHandleOp, 4> init_vars(var_handle_ops.begin(),
105                                                 var_handle_ops.end());
106     RemoveVariables(init_vars);
107   }
108 }
109 
110 }  // namespace
111 
112 std::unique_ptr<OperationPass<ModuleOp>>
CreateRemoveVariablesInSessionInitializerPass()113 CreateRemoveVariablesInSessionInitializerPass() {
114   return std::make_unique<RemoveVariablesInSessionInitializerPass>();
115 }
116 
117 }  // namespace tf_saved_model
118 }  // namespace mlir
119