You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

node_pass.cc 2.4 kB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. /**
  2. * Copyright 2019 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 "backend/optimizer/common/node_pass.h"
  17. #include <unordered_set>
  18. #include <deque>
  19. #include "ir/anf.h"
  20. #include "ir/func_graph.h"
  21. #include "ir/manager.h"
  22. #include "backend/session/anf_runtime_algorithm.h"
  23. namespace mindspore {
  24. namespace opt {
  25. bool NodePass::Run(const FuncGraphPtr &func_graph) {
  26. MS_EXCEPTION_IF_NULL(func_graph);
  27. FuncGraphManagerPtr manager = func_graph->manager();
  28. MS_EXCEPTION_IF_NULL(manager);
  29. manager->AddFuncGraph(func_graph);
  30. std::unordered_set<AnfNodePtr> seen_node;
  31. std::deque<AnfNodePtr> todo{func_graph->output()};
  32. bool changes = false;
  33. while (!todo.empty()) {
  34. AnfNodePtr node = todo.front();
  35. todo.pop_front();
  36. if (seen_node.count(node) > 0 || !manager->all_nodes().contains(node)) {
  37. continue;
  38. }
  39. (void)seen_node.insert(node);
  40. AnfNodePtr new_node = Run(func_graph, node);
  41. bool change = (new_node != nullptr);
  42. if (new_node != nullptr && new_node != node) {
  43. (void)manager->Replace(node, new_node);
  44. (void)seen_node.erase(node);
  45. } else if (new_node == nullptr) {
  46. new_node = node;
  47. }
  48. if (new_node && IsValueNode<FuncGraph>(new_node)) {
  49. auto const_func_graph = GetValueNode<FuncGraphPtr>(new_node);
  50. MS_EXCEPTION_IF_NULL(const_func_graph);
  51. if (!const_func_graph->has_attr(FUNC_GRAPH_ATTR_GRAPH_KERNEL)) {
  52. todo.push_back(const_func_graph->output());
  53. }
  54. } else if (new_node && new_node->isa<CNode>()) {
  55. if (AnfAlgo::IsGraphKernel(new_node)) {
  56. todo.push_back(new_node);
  57. }
  58. auto cnode = new_node->cast<CNodePtr>();
  59. MS_EXCEPTION_IF_NULL(cnode);
  60. auto inputs = cnode->inputs();
  61. (void)todo.insert(todo.end(), inputs.begin(), inputs.end());
  62. }
  63. changes = changes || change;
  64. }
  65. return changes;
  66. }
  67. } // namespace opt
  68. } // namespace mindspore