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