dead_code_elimination.cpp 1.02 KB
Newer Older
Paul's avatar
Paul committed
1
2
3
4
5
6
7
8
9
10
#include <migraph/dead_code_elimination.hpp>
#include <migraph/program.hpp>
#include <migraph/instruction.hpp>
#include <migraph/iterator_for.hpp>
#include <migraph/functional.hpp>

namespace migraph {

void dead_code_elimination::apply(program& p) const
{
11
12
    auto last = std::prev(p.end());
    for(auto ins : iterator_for(p))
Paul's avatar
Paul committed
13
    {
Paul's avatar
Paul committed
14
15
16
17
        // Skip the first instruction, since we always process the previous
        // instruction
        if(ins == p.begin())
            continue;
Paul's avatar
Paul committed
18
        // Skip the last instruction
Paul's avatar
Paul committed
19
        if(std::prev(ins) == last)
Paul's avatar
Paul committed
20
            break;
21
22
23
        fix([&](auto self, auto leaf) {
            assert(p.has_instruction(leaf));
            if(leaf->output.empty())
Paul's avatar
Paul committed
24
            {
25
                auto args = leaf->arguments;
Paul's avatar
Paul committed
26
                leaf->clear_arguments();
27
                p.move_instruction(leaf, p.end());
Paul's avatar
Paul committed
28
                for(auto arg : args)
Paul's avatar
Paul committed
29
30
                    self(arg);
            }
Paul's avatar
Paul committed
31
        })(std::prev(ins));
Paul's avatar
Paul committed
32
    }
33
    p.remove_instructions(std::next(last), p.end());
Paul's avatar
Paul committed
34
35
36
}

} // namespace migraph