eliminate_common_subexpression.cpp 1.47 KB
Newer Older
Paul's avatar
Paul committed
1
#include <migraphx/eliminate_common_subexpression.hpp>
Paul's avatar
Paul committed
2
3
4
5
6
#include <migraphx/program.hpp>
#include <migraphx/instruction.hpp>
#include <migraphx/iterator_for.hpp>
#include <migraphx/ranges.hpp>
#include <migraphx/functional.hpp>
Paul's avatar
Paul committed
7

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

Paul's avatar
Paul committed
10
namespace migraphx {
Paul's avatar
Paul committed
11
inline namespace MIGRAPHX_INLINE_NS {
Paul's avatar
Paul committed
12

Paul's avatar
Paul committed
13
template <class Range>
14
void cse_range(module& p, Range&& r)
Paul's avatar
Paul committed
15
16
{
    std::unordered_multimap<std::string, instruction_ref> instructions;
kahmed10's avatar
kahmed10 committed
17
    std::unordered_set<instruction_ref> processed_ins;
Paul's avatar
Paul committed
18
19
20
21
22
    for(auto ins : r)
    {
        // Skip dead instructions
        if(ins->outputs().empty())
            continue;
kahmed10's avatar
kahmed10 committed
23

Paul's avatar
Paul committed
24
25
        // Find instruction with the same name
        auto found_instructions = range(instructions.equal_range(ins->name()));
Paul's avatar
Paul committed
26
        for(const auto& pp : found_instructions)
Paul's avatar
Paul committed
27
28
        {
            auto eq = pp.second;
kahmed10's avatar
kahmed10 committed
29
30
            if(contains(processed_ins, eq))
                continue;
Paul's avatar
Paul committed
31
32
33
            if(*eq != *ins)
                continue;
            p.replace_instruction(ins, eq);
kahmed10's avatar
kahmed10 committed
34
            processed_ins.emplace(ins);
Paul's avatar
Paul committed
35
36
37
38
39
            auto outputs = eq->outputs();
            std::sort(outputs.begin(), outputs.end(), [&](auto x, auto y) {
                return std::distance(eq, x) < std::distance(eq, y);
            });
            cse_range(p, outputs);
Paul's avatar
Paul committed
40
41
42
43
44
        }
        instructions.emplace(ins->name(), ins);
    }
}

45
void eliminate_common_subexpression::apply(module& p) const { cse_range(p, iterator_for(p)); }
Paul's avatar
Paul committed
46

Paul's avatar
Paul committed
47
} // namespace MIGRAPHX_INLINE_NS
Paul's avatar
Paul committed
48
} // namespace migraphx