Elffuss BraidHub

kikocis/ncnn public

master · 2.3 KiBRawPermalink
1// Tencent is pleased to support the open source community by making ncnn available.
2//
3// Copyright (C) 2022 THL A29 Limited, a Tencent company. All rights reserved.
4//
5// Licensed under the BSD 3-Clause License (the "License"); you may not use this file except
6// in compliance with the License. You may obtain a copy of the License at
7//
8// https://opensource.org/licenses/BSD-3-Clause
9//
10// Unless required by applicable law or agreed to in writing, software distributed
11// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
12// CONDITIONS OF ANY KIND, either express or implied. See the License for the
13// specific language governing permissions and limitations under the License.
14
15#include "eliminate_noop_expression.h"
16
17#include <algorithm>
18#include "pass_level2.h"
19
20namespace pnnx {
21
22void eliminate_noop_expression(Graph& graph)
23{
24 while (1)
25 {
26 bool matched = false;
27
28 for (size_t i = 0; i < graph.ops.size(); i++)
29 {
30 Operator* op = graph.ops[i];
31
32 if (op->type != "pnnx.Expression")
33 continue;
34
35 if (op->inputs.size() != 1 || op->outputs.size() != 1)
36 continue;
37
38 const std::string& expr = op->params.at("expr").s;
39 if (expr != "@0")
40 continue;
41
42 // delete noop-like expr
43 matched = true;
44
45 for (auto& x : op->inputs)
46 {
47 x->remove_consumer(op);
48 }
49
50 Operand* expr_out = op->outputs[0];
51
52 for (auto& x : expr_out->consumers)
53 {
54 for (size_t j = 0; j < x->inputs.size(); j++)
55 {
56 if (x->inputs[j] == expr_out)
57 x->inputs[j] = op->inputs[0];
58 }
59
60 op->inputs[0]->consumers.push_back(x);
61 }
62
63 op->inputs[0]->name = expr_out->name;
64
65 expr_out->producer = 0;
66 expr_out->consumers.clear();
67
68 graph.operands.erase(std::find(graph.operands.begin(), graph.operands.end(), expr_out));
69 delete expr_out;
70
71 op->inputs.clear();
72 op->outputs.clear();
73
74 graph.ops.erase(graph.ops.begin() + i);
75 delete op;
76
77 break;
78 }
79
80 if (!matched)
81 break;
82 }
83}
84
85} // namespace pnnx