• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /**
2  * Copyright 2020 Huawei Technologies Co., Ltd
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include "tools/converter/optimizer.h"
18 #include "src/common/log_adapter.h"
19 #include "src/common/log_util.h"
20 
21 namespace mindspore {
22 namespace lite {
~Optimizer()23 Optimizer::~Optimizer() {
24   for (auto pass : graph_passes_) {
25     delete (pass);
26   }
27   graph_passes_.clear();
28   for (auto pass : node_passes_) {
29     delete (pass);
30   }
31   node_passes_.clear();
32 }
33 
AddPass(GraphPass * graph_pass)34 void Optimizer::AddPass(GraphPass *graph_pass) {
35   if (graph_pass != nullptr) {
36     this->graph_passes_.emplace_back(graph_pass);
37   }
38 }
39 
AddPass(NodePass * node_pass)40 void Optimizer::AddPass(NodePass *node_pass) {
41   if (node_pass != nullptr) {
42     this->node_passes_.emplace_back(node_pass);
43   }
44 }
45 
Run(schema::MetaGraphT * graph_defT)46 STATUS Optimizer::Run(schema::MetaGraphT *graph_defT) {
47   MS_ASSERT(graph_defT != nullptr);
48   STATUS status;
49   bool ifNotChanged = true;
50   // each node should go through all node pass not each node pass go through all node
51   for (auto &opDef : graph_defT->nodes) {
52     for (auto pass : this->node_passes_) {
53       auto graph_node = new (std::nothrow) GraphNode(graph_defT, opDef.get());
54       if (graph_node == nullptr) {
55         return RET_ERROR;
56       }
57       if (pass == nullptr) {
58         delete graph_node;
59         return RET_ERROR;
60       }
61       status = pass->Run(graph_node);
62       delete graph_node;
63       if (status != RET_OK && status != RET_NO_CHANGE && status != RET_INFER_INVALID) {
64         MS_LOG(ERROR) << "Run NodePass failed";
65         return status;
66       } else {
67         if (status == RET_OK) {
68           ifNotChanged = false;
69         }
70       }
71     }
72   }
73 
74   for (auto pass : this->graph_passes_) {
75     CHECK_NULL_RETURN(pass);
76     status = pass->Run(graph_defT);
77     if (status != RET_OK && status != RET_NO_CHANGE && status != RET_INFER_INVALID) {
78       MS_LOG(ERROR) << "Run GraphPass failed";
79       return status;
80     } else {
81       if (status == RET_OK) {
82         ifNotChanged = false;
83       }
84     }
85   }
86   return ifNotChanged ? RET_NO_CHANGE : RET_OK;
87 }
88 }  // namespace lite
89 }  // namespace mindspore
90