"vscode:/vscode.git/clone" did not exist on "568a6a55794a96aa284b2955c396eef7e2e0d7e5"
common_subexpression_elimination.cpp 1.1 KB
Newer Older
Paul's avatar
Paul committed
1
2
3
4
5
6
7
#include <migraph/common_subexpression_elimination.hpp>
#include <migraph/program.hpp>
#include <migraph/instruction.hpp>
#include <migraph/iterator_for.hpp>
#include <migraph/ranges.hpp>
#include <migraph/functional.hpp>

Paul's avatar
Paul committed
8
9
#include <unordered_set>

Paul's avatar
Paul committed
10
namespace migraph {
11
inline namespace version_1 {
Paul's avatar
Paul committed
12

Paul's avatar
Paul committed
13
template <class Range>
Paul's avatar
Paul committed
14
15
16
17
18
19
20
21
22
23
void cse_range(program& p, Range&& r)
{
    std::unordered_multimap<std::string, instruction_ref> instructions;
    for(auto ins : r)
    {
        // Skip dead instructions
        if(ins->outputs().empty())
            continue;
        // Find instruction with the same name
        auto found_instructions = range(instructions.equal_range(ins->name()));
Paul's avatar
Paul committed
24
        for(const auto& pp : found_instructions)
Paul's avatar
Paul committed
25
26
27
28
29
30
31
32
33
34
35
        {
            auto eq = pp.second;
            if(*eq != *ins)
                continue;
            p.replace_instruction(ins, eq);
            cse_range(p, eq->outputs());
        }
        instructions.emplace(ins->name(), ins);
    }
}

Paul's avatar
Paul committed
36
void common_subexpression_elimination::apply(program& p) const { cse_range(p, iterator_for(p)); }
Paul's avatar
Paul committed
37

38
} // namespace version_1
Paul's avatar
Paul committed
39
} // namespace migraph