1 /** 2 * Copyright 2022-2023 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 #include "include/backend/optimizer/graph_optimizer.h" 17 #include "backend/common/optimizer/cache_manager.h" 18 19 namespace mindspore { 20 namespace opt { AddPassManager(const PassManagerPtr & pass_manager)21void GraphOptimizer::AddPassManager(const PassManagerPtr &pass_manager) { 22 if (pass_manager != nullptr) { 23 pass_managers_.push_back(pass_manager); 24 } 25 } 26 Optimize(const FuncGraphPtr & func_graph,bool run_only_once)27FuncGraphPtr GraphOptimizer::Optimize(const FuncGraphPtr &func_graph, bool run_only_once) { 28 run_only_once_ = (pass_managers_.size() == 1) ? true : run_only_once; 29 MS_EXCEPTION_IF_NULL(func_graph); 30 // cppcheck-suppress * 31 auto manager = func_graph->manager(); 32 if (manager == nullptr) { 33 manager = Manage(func_graph, true); 34 MS_EXCEPTION_IF_NULL(manager); 35 manager->AddFuncGraph(func_graph); 36 func_graph->set_manager(manager); 37 } 38 39 bool changed = true; 40 while (changed) { 41 changed = false; 42 for (size_t i = 0; i < pass_managers_.size(); ++i) { 43 const PassManagerPtr &pm = pass_managers_[i]; 44 MS_EXCEPTION_IF_NULL(pm); 45 if (pm != nullptr && pm->Run(func_graph)) { 46 changed = true; 47 } 48 } 49 if (run_only_once_) { 50 break; 51 } 52 } 53 54 std::vector<FuncGraphPtr> func_graphs; 55 func_graphs.push_back(func_graph); 56 (void)TopoSort(func_graph->get_return()); 57 if (!func_graph->has_user_data<FuncGraphPassIndex>()) { 58 func_graph->set_user_data<FuncGraphPassIndex>(std::make_shared<FuncGraphPassIndex>()); 59 } 60 auto func_graph_index = func_graph->user_data<FuncGraphPassIndex>(); 61 MS_EXCEPTION_IF_NULL(func_graph_index); 62 func_graph_index->set_has_gen_index(false); 63 64 return func_graph; 65 } 66 } // namespace opt 67 } // namespace mindspore 68