program.cpp 9.47 KB
Newer Older
Paul's avatar
Paul committed
1
2
3
#include <migraph/program.hpp>
#include <migraph/stringutils.hpp>
#include <migraph/instruction.hpp>
Paul's avatar
Paul committed
4
#include <migraph/env.hpp>
Paul's avatar
Paul committed
5
#include <iostream>
Paul's avatar
Paul committed
6
#include <sstream>
Paul's avatar
Paul committed
7
8
#include <algorithm>

Paul's avatar
Paul committed
9
namespace migraph {
Paul's avatar
Paul committed
10

Paul's avatar
Paul committed
11
12
MIGRAPH_DECLARE_ENV_VAR(MIGRAPH_TRACE_COMPILE)

Paul's avatar
Paul committed
13
14
15
16
struct program_impl
{
    // A list is used to keep references to an instruction stable
    std::list<instruction> instructions;
Paul's avatar
Paul committed
17
    context ctx;
Paul's avatar
Paul committed
18
19
};

Paul's avatar
Paul committed
20
const operation& get_operation(instruction_ref ins) { return ins->op; }
Paul's avatar
Paul committed
21

Paul's avatar
Paul committed
22
template <class F>
Paul's avatar
Paul committed
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
static void print_program(std::ostream& os, const program& p, F annonate)
{
    std::unordered_map<const instruction*, std::string> names;
    int count = 0;

    for(auto& ins : p)
    {
        std::string var_name = "@" + std::to_string(count);
        if(ins.op.name() == "@param")
        {
            var_name = any_cast<builtin::param>(ins.op).parameter;
        }

        os << var_name << " = ";

        os << ins.op;

        if(ins.op.name() == "@literal")
        {
            if(ins.lit.get_shape().elements() > 10)
                os << "{ ... }";
            else
                os << "{" << ins.lit << "}";
        }

        if(!ins.arguments.empty())
        {
            char delim = '(';
            for(auto&& arg : ins.arguments)
            {
                assert(p.has_instruction(arg) && "Instruction not found");
                os << delim << names.at(std::addressof(*arg));
                delim = ',';
            }
            os << ")";
        }

        os << " -> " << ins.result;

        annonate(os, ins, names);

        os << std::endl;

        names.emplace(std::addressof(ins), var_name);
        count++;
    }
}

Paul's avatar
Paul committed
71
program::program() : impl(std::make_unique<program_impl>()) {}
Paul's avatar
Paul committed
72

Paul's avatar
Paul committed
73
program::program(program&&) noexcept = default;
Paul's avatar
Paul committed
74
75
program& program::operator=(program&&) noexcept = default;
program::~program() noexcept                    = default;
Paul's avatar
Paul committed
76

Paul's avatar
Paul committed
77
instruction_ref program::add_instruction(operation op, std::vector<instruction_ref> args)
Paul's avatar
Paul committed
78
79
80
{
    return insert_instruction(impl->instructions.end(), std::move(op), std::move(args));
}
Paul's avatar
Paul committed
81
82
instruction_ref
program::insert_instruction(instruction_ref ins, operation op, std::vector<instruction_ref> args)
Paul's avatar
Paul committed
83
{
Paul's avatar
Paul committed
84
85
86
    assert(std::all_of(
               args.begin(), args.end(), [&](instruction_ref x) { return has_instruction(x); }) &&
           "Argument is not an exisiting instruction");
Paul's avatar
Paul committed
87
    assert(not starts_with(op.name(), "@"));
Paul's avatar
Paul committed
88
89
    // TODO: Use move
    shape r     = compute_shape(op, args);
Paul's avatar
Paul committed
90
    auto result = impl->instructions.insert(ins, {op, r, args});
Paul's avatar
Paul committed
91
    backreference(result);
Paul's avatar
Paul committed
92
    assert(result->arguments == args);
Paul's avatar
Paul committed
93
    assert(result->valid(begin()));
Paul's avatar
Paul committed
94
    return result;
Paul's avatar
Paul committed
95
96
}

Paul's avatar
Paul committed
97
98
99
100
101
102
instruction_ref
program::replace_instruction(instruction_ref ins, operation op, std::vector<instruction_ref> args)
{
    assert(std::all_of(
               args.begin(), args.end(), [&](instruction_ref x) { return has_instruction(x); }) &&
           "Argument is not an exisiting instruction");
Paul's avatar
Paul committed
103
    assert(not starts_with(op.name(), "@"));
Paul's avatar
Paul committed
104

Paul's avatar
Paul committed
105
    shape r = compute_shape(op, args);
Paul's avatar
Paul committed
106
107
    ins->replace(op, r, args);
    backreference(ins);
Paul's avatar
Paul committed
108
    assert(ins->valid(begin()));
Paul's avatar
Paul committed
109
110
111
    return ins;
}

Paul's avatar
Paul committed
112
instruction_ref program::replace_instruction(instruction_ref ins, instruction_ref rep)
Paul's avatar
Paul committed
113
{
Paul's avatar
Paul committed
114
115
116
117
    assert(has_instruction(ins));
    assert(has_instruction(rep));
    assert(ins != rep);
    // TODO: Should it be an error if the output is empty?
Paul's avatar
Paul committed
118
    if(ins->output.empty())
Paul's avatar
Paul committed
119
120
121
    {
        return rep;
    }
Paul's avatar
Paul committed
122
    for(auto&& out : ins->output)
Paul's avatar
Paul committed
123
    {
Paul's avatar
Paul committed
124
125
        // TODO: Check for possible cycles
        if(out != rep)
Paul's avatar
Paul committed
126
        {
Paul's avatar
Paul committed
127
            replace_argument(out, ins, rep);
Paul's avatar
Paul committed
128
        }
Paul's avatar
Paul committed
129
        assert(out->valid(begin()));
Paul's avatar
Paul committed
130
    }
Paul's avatar
Paul committed
131
132
    // Replacement should not be dead code unless its the last instruction
    assert(!rep->output.empty() or rep == std::prev(end()));
Paul's avatar
Paul committed
133
    assert(ins->valid(begin()));
Paul's avatar
Paul committed
134
    assert(rep->valid(begin()));
Paul's avatar
Paul committed
135
136
137
    return rep;
}

Paul's avatar
Paul committed
138
instruction_ref program::remove_instruction(instruction_ref ins)
Paul's avatar
Paul committed
139
140
141
142
143
144
145
{
    assert(has_instruction(ins));
    assert(ins->output.empty());
    ins->clear_arguments();
    return impl->instructions.erase(ins);
}

146
147
instruction_ref program::remove_instructions(instruction_ref first, instruction_ref last)
{
Paul's avatar
Paul committed
148
149
    if(first == last)
        return first;
Paul's avatar
Paul committed
150
    // TODO: Check every element
151
    assert(has_instruction(first));
Paul's avatar
Paul committed
152
153
    std::for_each(first, last, [&](instruction& ins) { ins.clear_arguments(); });
    assert(std::all_of(first, last, [&](instruction& ins) { return ins.output.empty(); }));
154
155
156
157
158
159
160
161
162
    return impl->instructions.erase(first, last);
}

instruction_ref program::move_instruction(instruction_ref src, instruction_ref dst)
{
    impl->instructions.splice(dst, impl->instructions, src);
    return src;
}

Paul's avatar
Paul committed
163
instruction_ref program::add_literal(literal l)
Paul's avatar
Paul committed
164
{
Paul's avatar
Paul committed
165
166
167
168
169
170
171
172
    impl->instructions.emplace_front(std::move(l));
    return impl->instructions.begin();
}

instruction_ref program::add_outline(shape s)
{
    impl->instructions.push_front({builtin::outline{s}, s, {}});
    return impl->instructions.begin();
Paul's avatar
Paul committed
173
174
}

Paul's avatar
Paul committed
175
instruction_ref program::add_parameter(std::string name, shape s)
Paul's avatar
Paul committed
176
{
Paul's avatar
Paul committed
177
178
179
180
    impl->instructions.push_front({builtin::param{std::move(name)}, s, {}});
    return impl->instructions.begin();
}

Paul's avatar
Paul committed
181
shape program::get_parameter_shape(std::string name) const
Paul's avatar
Paul committed
182
183
{
    auto ins = std::find_if(
Paul's avatar
Paul committed
184
185
186
187
188
189
190
191
192
193
194
195
196
197
        impl->instructions.begin(), impl->instructions.end(), [&](const instruction& x) {
            if(x.op.name() == "@param")
            {
                return any_cast<builtin::param>(x.op).parameter == name;
            }
            else
            {
                return false;
            }
        });
    if(ins != this->end())
        return ins->result;
    else
        return {};
Paul's avatar
Paul committed
198
199
}

Paul's avatar
Paul committed
200
201
202
std::unordered_map<std::string, shape> program::get_parameter_shapes() const
{
    std::unordered_map<std::string, shape> result;
Paul's avatar
Paul committed
203
    for(auto&& ins : impl->instructions)
Paul's avatar
Paul committed
204
205
206
    {
        if(ins.op.name() == "@param")
        {
Paul's avatar
Paul committed
207
            auto&& name  = any_cast<builtin::param>(ins.op).parameter;
Paul's avatar
Paul committed
208
209
210
211
212
213
            result[name] = ins.result;
        }
    }
    return result;
}

Paul's avatar
Paul committed
214
bool program::has_instruction(instruction_ref ins) const
Paul's avatar
Paul committed
215
{
Paul's avatar
Paul committed
216
217
218
219
    return std::find_if(
               impl->instructions.begin(), impl->instructions.end(), [&](const instruction& x) {
                   return std::addressof(*ins) == std::addressof(x);
               }) != impl->instructions.end();
Paul's avatar
Paul committed
220
221
}

Paul's avatar
Paul committed
222
223
instruction_ref program::begin() const { return impl->instructions.begin(); }
instruction_ref program::end() const { return impl->instructions.end(); }
224

Paul's avatar
Paul committed
225
shape program::get_shape() const { return impl->instructions.back().result; }
Paul's avatar
Paul committed
226

Paul's avatar
Paul committed
227
228
instruction_ref program::validate() const
{
Paul's avatar
Paul committed
229
230
    return std::find_if(impl->instructions.begin(),
                        impl->instructions.end(),
Paul's avatar
Paul committed
231
                        [&](const instruction& i) { return !i.valid(impl->instructions.begin()); });
Paul's avatar
Paul committed
232
233
}

Paul's avatar
Paul committed
234
235
void program::compile(const target& t)
{
Paul's avatar
Paul committed
236
    assert(this->validate() == impl->instructions.end());
Paul's avatar
Paul committed
237
    this->impl->ctx = t.get_context();
Paul's avatar
Paul committed
238
    if(enabled(MIGRAPH_TRACE_COMPILE{}))
Paul's avatar
Paul committed
239
240
        std::cout << *this << std::endl << std::endl;
    ;
Paul's avatar
Paul committed
241
    for(auto&& p : t.get_passes(this->impl->ctx))
Paul's avatar
Paul committed
242
    {
Paul's avatar
Paul committed
243
244
        if(enabled(MIGRAPH_TRACE_COMPILE{}))
            std::cout << "Pass: " << p.name() << std::endl;
Paul's avatar
Paul committed
245
        p.apply(*this);
Paul's avatar
Paul committed
246
247
        if(enabled(MIGRAPH_TRACE_COMPILE{}))
            std::cout << *this << std::endl << std::endl;
Paul's avatar
Paul committed
248
#ifndef NDEBUG
Paul's avatar
Paul committed
249
        auto invalid = this->validate();
Paul's avatar
Paul committed
250
251
        if(invalid != impl->instructions.end())
        {
Paul's avatar
Paul committed
252
            auto index = std::distance(impl->instructions.begin(), invalid);
Paul's avatar
Paul committed
253
            MIGRAPH_THROW(p.name() + " pass produces invalid program at instruction " +
Paul's avatar
Paul committed
254
                          std::to_string(index) + ": " + invalid->op.name());
Paul's avatar
Paul committed
255
        }
Paul's avatar
Paul committed
256
257
#endif
    }
Paul's avatar
Paul committed
258
    auto invalid = this->validate();
Paul's avatar
Paul committed
259
260
    if(invalid != impl->instructions.end())
    {
Paul's avatar
Paul committed
261
262
263
        auto index = std::distance(impl->instructions.begin(), invalid);
        MIGRAPH_THROW("Invalid program from compilation at instruction " + std::to_string(index));
    }
Paul's avatar
Paul committed
264
265
}

Paul's avatar
Paul committed
266
267
268
269
270
template <class F>
argument generic_eval(const program& p,
                      context& ctx,
                      std::unordered_map<std::string, argument> params,
                      F trace)
Paul's avatar
Paul committed
271
{
Paul's avatar
Paul committed
272
    assert(p.validate() == p.end());
Paul's avatar
Paul committed
273
274
    std::unordered_map<const instruction*, argument> results;
    argument result;
Paul's avatar
Paul committed
275
    for(auto& ins : p)
Paul's avatar
Paul committed
276
    {
Paul's avatar
Paul committed
277
        if(ins.op.name() == "@literal")
Paul's avatar
Paul committed
278
        {
Paul's avatar
Paul committed
279
            trace(ins, [&] { result = ins.lit.get_argument(); });
Paul's avatar
Paul committed
280
        }
Paul's avatar
Paul committed
281
        else if(ins.op.name() == "@param")
Paul's avatar
Paul committed
282
        {
Paul's avatar
Paul committed
283
            trace(ins, [&] { result = params.at(any_cast<builtin::param>(ins.op).parameter); });
Paul's avatar
Paul committed
284
        }
Paul's avatar
Paul committed
285
286
        else if(ins.op.name() == "@outline")
        {
Paul's avatar
Paul committed
287
            trace(ins, [&] { result = argument{ins.result, nullptr}; });
Paul's avatar
Paul committed
288
        }
Paul's avatar
Paul committed
289
290
291
        else
        {
            std::vector<argument> values(ins.arguments.size());
Paul's avatar
Paul committed
292
293
294
            std::transform(ins.arguments.begin(),
                           ins.arguments.end(),
                           values.begin(),
Paul's avatar
Paul committed
295
                           [&](instruction_ref i) { return results.at(std::addressof(*i)); });
Paul's avatar
Paul committed
296
            trace(ins, [&] { result = ins.op.compute(ctx, ins.result, values); });
Paul's avatar
Paul committed
297
298
299
        }
        results.emplace(std::addressof(ins), result);
    }
300
    return result;
Paul's avatar
Paul committed
301
302
}

Paul's avatar
Paul committed
303
304
305
306
307
argument program::eval(std::unordered_map<std::string, argument> params) const
{
    return generic_eval(*this, this->impl->ctx, params, [](auto&, auto f) { f(); });
}

Paul's avatar
Paul committed
308
bool operator==(const program& x, const program& y) { return to_string(x) == to_string(y); }
Paul's avatar
Paul committed
309

Paul's avatar
Paul committed
310
std::ostream& operator<<(std::ostream& os, const program& p)
Paul's avatar
Paul committed
311
{
Paul's avatar
Paul committed
312
    print_program(os, p, [](auto&&...) {});
Paul's avatar
Paul committed
313
    return os;
Paul's avatar
Paul committed
314
315
}

Paul's avatar
Paul committed
316
} // namespace migraph