Imported Upstream version 1.7.0
[platform/core/ml/nnfw.git] / compiler / logo / src / Passes / RemoveDeadNodeWithQueryPass.cpp
1 /*
2  * Copyright (c) 2020 Samsung Electronics Co., Ltd. All Rights Reserved
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 <logo/RemoveDeadNodeWithQueryPass.h>
18 #include <logo/DeadNodeQueryService.h>
19
20 #include <loco/IR/Algorithm.h>
21 #include <loco/IR/CanonicalDialect.h>
22 #include <loco/IR/CanonicalNode.h>
23
24 #include <set>
25
26 namespace logo
27 {
28
29 bool RemoveDeadNodeWithQueryPass::run(loco::Graph *g)
30 {
31   // Let's enumerate nodes required to compute output nodes
32   auto active_nodes = loco::active_nodes(loco::output_nodes(g));
33
34   // List dead(= non-active) nodes candidates
35   std::set<loco::Node *> candidates;
36
37   for (auto node : loco::all_nodes(g))
38   {
39     if (active_nodes.find(node) == active_nodes.end())
40     {
41       candidates.insert(node);
42     }
43   }
44
45   // Find the nodes that should not be dead node in candidates
46   for (auto node : candidates)
47   {
48     if (auto service = node->dialect()->service<DeadNodeQueryService>())
49     {
50       if (!service->isDeadNode(node))
51       {
52         candidates.erase(node);
53       }
54     }
55   }
56
57   for (auto node : candidates)
58   {
59     node->drop();
60   }
61
62   for (auto node : candidates)
63   {
64     g->nodes()->destroy(node);
65   }
66
67   return candidates.size() > 0;
68 }
69
70 } // namespace logo