"host/driver_offline/conv_fwd_driver_offline.cpp" did not exist on "81c942cd7e198b46f55be31451d51f27459d34ab"
dead_code_elimination.cpp 1.84 KB
Newer Older
Paul's avatar
Paul committed
1
2
3
4
5
#include <migraph/dead_code_elimination.hpp>
#include <migraph/program.hpp>
#include <migraph/instruction.hpp>
#include <migraph/iterator_for.hpp>
#include <migraph/functional.hpp>
Paul's avatar
Paul committed
6
#include <migraph/ranges.hpp>
Paul's avatar
Paul committed
7
8
9

namespace migraph {

Paul's avatar
Paul committed
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
template<class Range, class Iterator>
std::ptrdiff_t bidistance(const Range& r, Iterator start, Iterator last)
{
    auto start_forward = start;
    auto start_backwards = start;
    std::size_t n = 0;
    while(start_forward != last and start_backwards != last)
    {
        n++;
        if(start_forward != r.end()) start_forward++;
        if(start_backwards != r.begin()) start_backwards--;
    }
    if(start_forward == last)
        return n;
    else
        return -n;

}

Paul's avatar
Paul committed
29
30
void dead_code_elimination::apply(program& p) const
{
31
32
    auto last = std::prev(p.end());
    for(auto ins : iterator_for(p))
Paul's avatar
Paul committed
33
    {
Paul's avatar
Paul committed
34
35
36
37
        // Skip the first instruction, since we always process the previous
        // instruction
        if(ins == p.begin())
            continue;
38
        const auto i = std::prev(ins);
Paul's avatar
Paul committed
39
        // Skip the last instruction
40
        if(i == last)
Paul's avatar
Paul committed
41
            break;
Paul's avatar
Paul committed
42
43
44
45
        // Skip instruction with empty shape as output unless its a builtin
        if(i->get_shape().elements() == 0 and not(i->name().front() == '@'))
            continue;
        assert(bidistance(p, i, last) > 0);
46
47
        fix([&](auto self, auto leaf) {
            assert(p.has_instruction(leaf));
Paul's avatar
Paul committed
48
            if(leaf->outputs().empty())
Paul's avatar
Paul committed
49
            {
Paul's avatar
Paul committed
50
                auto args = leaf->inputs();
Paul's avatar
Paul committed
51
                leaf->clear_arguments();
Paul's avatar
Paul committed
52
53
                assert(bidistance(p, last, leaf) < 0);
                assert(leaf != ins);
54
                p.move_instruction(leaf, p.end());
Paul's avatar
Paul committed
55
                for(auto arg : args)
Paul's avatar
Paul committed
56
57
                    self(arg);
            }
58
        })(i);
Paul's avatar
Paul committed
59
    }
60
    p.remove_instructions(std::next(last), p.end());
Paul's avatar
Paul committed
61
62
63
}

} // namespace migraph