program.cpp 18.4 KB
Newer Older
Paul's avatar
Paul committed
1
2
3
#include <migraphx/program.hpp>
#include <migraphx/stringutils.hpp>
#include <migraphx/instruction.hpp>
4
#include <migraphx/op/identity.hpp>
Paul's avatar
Paul committed
5
#include <migraphx/target.hpp>
Paul's avatar
Paul committed
6
7
8
9
#include <migraphx/env.hpp>
#include <migraphx/ranges.hpp>
#include <migraphx/time.hpp>
#include <migraphx/iterator_for.hpp>
Paul's avatar
Paul committed
10
#include <iostream>
Paul's avatar
Paul committed
11
#include <sstream>
Paul's avatar
Paul committed
12
#include <algorithm>
Paul's avatar
Paul committed
13
#include <utility>
Paul's avatar
Paul committed
14

Paul's avatar
Paul committed
15
namespace migraphx {
Paul's avatar
Paul committed
16
inline namespace MIGRAPHX_INLINE_NS {
Paul's avatar
Paul committed
17

Paul's avatar
Paul committed
18
19
20
21
struct program_impl
{
    // A list is used to keep references to an instruction stable
    std::list<instruction> instructions;
Paul's avatar
Paul committed
22
    context ctx;
Paul's avatar
Paul committed
23
24
};

25
const operation& get_operation(instruction_ref ins) { return ins->get_operator(); }
Paul's avatar
Paul committed
26

Paul's avatar
Paul committed
27
28
29
static void print_instruction(std::ostream& os,
                              instruction_ref ins,
                              const std::unordered_map<instruction_ref, std::string>& names)
Paul's avatar
Paul committed
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
{
    os << names.at(ins) << " = ";

    os << ins->get_operator();

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

    if(!ins->inputs().empty())
    {
        char delim = '(';
        for(auto&& arg : ins->inputs())
        {
            os << delim << names.at(arg);
            delim = ',';
        }
        os << ")";
    }
Paul's avatar
Paul committed
53

Paul's avatar
Paul committed
54
55
56
    os << " -> " << ins->get_shape();
}

Khalique's avatar
Khalique committed
57
static std::string enclose_name(const std::string& name) { return '"' + name + '"'; }
58
59

static void print_graph_node(std::ostream& os,
Khalique's avatar
Khalique committed
60
61
                             instruction_ref ins,
                             const std::unordered_map<instruction_ref, std::string>& names)
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
{
    os << "\t";

    if(!ins->inputs().empty())
    {
        char delim = '{';
        for(auto&& arg : ins->inputs())
        {
            os << delim << enclose_name(names.at(arg));
            delim = ' ';
        }
        os << '}';
        os << " -> ";
    }
    os << enclose_name(names.at(ins)) << ";";
    // if(ins->name() == "@literal")
    // {
    //     if(ins->get_literal().get_shape().elements() > 10)
    //         os << "{ ... }";
    //     else
    //         os << "{" << ins->get_literal() << "}";
    // }
}

Paul's avatar
Paul committed
86
template <class F>
Khalique's avatar
Khalique committed
87
88
89
90
91
92
93
static void print_program(
    std::ostream& os,
    const program& p,
    F annonate,
    std::function<void(
        std::ostream&, instruction_ref, const std::unordered_map<instruction_ref, std::string>&)>
        print_func = print_instruction)
Paul's avatar
Paul committed
94
{
95
    std::unordered_map<instruction_ref, std::string> names;
Paul's avatar
Paul committed
96
97
    int count = 0;

98
    for(auto ins : iterator_for(p))
Paul's avatar
Paul committed
99
100
    {
        std::string var_name = "@" + std::to_string(count);
Paul's avatar
Paul committed
101
        if(ins->name() == "@param")
Paul's avatar
Paul committed
102
        {
103
            var_name = any_cast<builtin::param>(ins->get_operator()).parameter;
Paul's avatar
Paul committed
104
        }
Paul's avatar
Paul committed
105
        names.emplace(ins, var_name);
Paul's avatar
Paul committed
106

Paul's avatar
Paul committed
107
108
        // TODO: Use all_of
        for(auto&& arg : ins->inputs())
Paul's avatar
Paul committed
109
        {
Paul's avatar
Paul committed
110
111
            assert(p.has_instruction(arg) && "Instruction not found");
            (void)arg;
Paul's avatar
Paul committed
112
113
        }

114
        print_func(os, ins, names);
Paul's avatar
Paul committed
115

Paul's avatar
Paul committed
116
        annonate(ins, names);
Paul's avatar
Paul committed
117
118
119
120
121
122
123

        os << std::endl;

        count++;
    }
}

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

Paul's avatar
Paul committed
126
program::program(program&&) noexcept = default;
Paul's avatar
Paul committed
127
128
program& program::operator=(program&&) noexcept = default;
program::~program() noexcept                    = default;
Paul's avatar
Paul committed
129

Paul's avatar
Paul committed
130
instruction_ref program::add_instruction(const operation& op, std::vector<instruction_ref> args)
Paul's avatar
Paul committed
131
{
Paul's avatar
Paul committed
132
    return insert_instruction(impl->instructions.end(), op, std::move(args));
Paul's avatar
Paul committed
133
}
Paul's avatar
Paul committed
134
135
136
instruction_ref program::insert_instruction(instruction_ref ins,
                                            const operation& op,
                                            std::vector<instruction_ref> args)
Paul's avatar
Paul committed
137
{
Paul's avatar
Paul committed
138
139
140
    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
141
    assert(not starts_with(op.name(), "@"));
Paul's avatar
Paul committed
142
    shape r     = compute_shape(op, args);
Paul's avatar
Paul committed
143
    auto result = impl->instructions.insert(ins, {op, r, std::move(args)});
Paul's avatar
Paul committed
144
    instruction::backreference(result);
Paul's avatar
Paul committed
145
    assert(result->valid(begin()));
Paul's avatar
Paul committed
146
    return result;
Paul's avatar
Paul committed
147
148
}

Paul's avatar
Paul committed
149
150
151
instruction_ref program::replace_instruction(instruction_ref ins,
                                             const operation& op,
                                             std::vector<instruction_ref> args)
Paul's avatar
Paul committed
152
153
154
155
{
    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
156
    assert(not starts_with(op.name(), "@"));
Paul's avatar
Paul committed
157

Paul's avatar
Paul committed
158
    shape r = compute_shape(op, args);
159
    instruction::replace(ins, op, r, std::move(args));
Paul's avatar
Paul committed
160
    assert(ins->valid(begin()));
Paul's avatar
Paul committed
161
162
163
    return ins;
}

Paul's avatar
Paul committed
164
instruction_ref program::replace_instruction(instruction_ref ins, instruction_ref rep)
Paul's avatar
Paul committed
165
{
Paul's avatar
Paul committed
166
167
168
    assert(has_instruction(ins));
    assert(has_instruction(rep));
    assert(ins != rep);
Shucai Xiao's avatar
Shucai Xiao committed
169

Shucai Xiao's avatar
Shucai Xiao committed
170
    if(ins == std::prev(this->end()))
Shucai Xiao's avatar
Shucai Xiao committed
171
    {
Shucai Xiao's avatar
Shucai Xiao committed
172
        return replace_instruction(ins, op::identity{}, rep);
Shucai Xiao's avatar
Shucai Xiao committed
173
174
    }

Paul's avatar
Paul committed
175
    // TODO: Should it be an error if the output is empty?
Paul's avatar
Paul committed
176
    if(ins->outputs().empty())
Paul's avatar
Paul committed
177
178
179
    {
        return rep;
    }
Paul's avatar
Paul committed
180
181
182
    // Make a copy of outputs which can be changed when calling replace_argument
    auto outputs = ins->outputs();
    for(auto out : outputs)
Paul's avatar
Paul committed
183
    {
Paul's avatar
Paul committed
184
185
        // TODO: Check for possible cycles
        if(out != rep)
Paul's avatar
Paul committed
186
        {
Paul's avatar
Paul committed
187
            instruction::replace_argument(out, ins, rep);
Paul's avatar
Paul committed
188
        }
Paul's avatar
Paul committed
189
        assert(out->valid(begin()));
Paul's avatar
Paul committed
190
    }
Paul's avatar
Paul committed
191
    // Replacement should not be dead code unless its the last instruction
Paul's avatar
Paul committed
192
    assert(!rep->outputs().empty() or rep == std::prev(end()));
Paul's avatar
Paul committed
193
    // Output of the original instruction should only be the replacement or empty
Paul's avatar
Paul committed
194
195
196
    assert(ins->outputs().empty() or std::all_of(ins->outputs().begin(),
                                                 ins->outputs().end(),
                                                 [&](auto i) { return i == rep; }));
Paul's avatar
Paul committed
197
    assert(ins->valid(begin()));
Paul's avatar
Paul committed
198
    assert(rep->valid(begin()));
Paul's avatar
Paul committed
199
200
201
    return rep;
}

Paul's avatar
Paul committed
202
instruction_ref program::remove_instruction(instruction_ref ins)
Paul's avatar
Paul committed
203
204
{
    assert(has_instruction(ins));
Paul's avatar
Paul committed
205
    assert(ins->outputs().empty());
Paul's avatar
Paul committed
206
207
208
209
    ins->clear_arguments();
    return impl->instructions.erase(ins);
}

210
211
instruction_ref program::remove_instructions(instruction_ref first, instruction_ref last)
{
Paul's avatar
Paul committed
212
213
    if(first == last)
        return first;
Paul's avatar
Paul committed
214
    // TODO: Check every element
215
    assert(has_instruction(first));
Paul's avatar
Paul committed
216
    std::for_each(first, last, [&](instruction& ins) { ins.clear_arguments(); });
Paul's avatar
Paul committed
217
    assert(std::all_of(first, last, [&](instruction& ins) { return ins.outputs().empty(); }));
218
219
220
221
222
223
224
225
226
    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
227
instruction_ref program::add_literal(literal l)
Paul's avatar
Paul committed
228
{
Paul's avatar
Paul committed
229
230
231
232
    impl->instructions.emplace_front(std::move(l));
    return impl->instructions.begin();
}

Paul's avatar
Paul committed
233
instruction_ref program::add_outline(const shape& s)
Paul's avatar
Paul committed
234
235
236
{
    impl->instructions.push_front({builtin::outline{s}, s, {}});
    return impl->instructions.begin();
Paul's avatar
Paul committed
237
238
}

Paul's avatar
Paul committed
239
instruction_ref program::add_parameter(std::string name, shape s)
Paul's avatar
Paul committed
240
{
241
    assert(get_parameter_shape(name) == shape{});
Paul's avatar
Paul committed
242
    impl->instructions.push_front({builtin::param{std::move(name)}, std::move(s), {}});
Paul's avatar
Paul committed
243
244
245
    return impl->instructions.begin();
}

Paul's avatar
Paul committed
246
shape program::get_parameter_shape(std::string name) const
Paul's avatar
Paul committed
247
248
{
    auto ins = std::find_if(
Paul's avatar
Paul committed
249
        impl->instructions.begin(), impl->instructions.end(), [&](const instruction& x) {
Paul's avatar
Paul committed
250
            if(x.name() == "@param")
Paul's avatar
Paul committed
251
            {
252
                return any_cast<builtin::param>(x.get_operator()).parameter == name;
Paul's avatar
Paul committed
253
254
255
256
257
258
259
            }
            else
            {
                return false;
            }
        });
    if(ins != this->end())
Paul's avatar
Paul committed
260
        return ins->get_shape();
Paul's avatar
Paul committed
261
262
    else
        return {};
Paul's avatar
Paul committed
263
264
}

mei-ye's avatar
mei-ye committed
265
266
267
268
instruction_ref program::get_parameter(std::string name) const
{
    auto ins = std::find_if(
        impl->instructions.begin(), impl->instructions.end(), [&](const instruction& x) {
Paul's avatar
Paul committed
269
            if(x.name() == "@param")
mei-ye's avatar
mei-ye committed
270
            {
Paul's avatar
Paul committed
271
                return any_cast<builtin::param>(x.get_operator()).parameter == name;
mei-ye's avatar
mei-ye committed
272
273
274
275
276
277
278
279
280
            }
            else
            {
                return false;
            }
        });
    if(ins != this->end())
        return ins;
    else
mei-ye's avatar
mei-ye committed
281
        return this->end();
mei-ye's avatar
mei-ye committed
282
283
}

Paul's avatar
Paul committed
284
285
286
std::unordered_map<std::string, shape> program::get_parameter_shapes() const
{
    std::unordered_map<std::string, shape> result;
Paul's avatar
Paul committed
287
    for(auto&& ins : impl->instructions)
Paul's avatar
Paul committed
288
    {
Paul's avatar
Paul committed
289
        if(ins.name() == "@param")
Paul's avatar
Paul committed
290
        {
291
            auto&& name  = any_cast<builtin::param>(ins.get_operator()).parameter;
Paul's avatar
Paul committed
292
            result[name] = ins.get_shape();
Paul's avatar
Paul committed
293
294
295
296
297
        }
    }
    return result;
}

Paul's avatar
Paul committed
298
bool program::has_instruction(instruction_ref ins) const
Paul's avatar
Paul committed
299
{
Paul's avatar
Paul committed
300
301
302
303
    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
304
305
}

Paul's avatar
Paul committed
306
std::size_t program::size() const { return impl->instructions.size(); }
Paul's avatar
Paul committed
307
308
instruction_ref program::begin() const { return impl->instructions.begin(); }
instruction_ref program::end() const { return impl->instructions.end(); }
309

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

Paul's avatar
Paul committed
312
313
context& program::get_context() const { return impl->ctx; }

Paul's avatar
Paul committed
314
315
instruction_ref program::validate() const
{
Paul's avatar
Paul committed
316
317
    return std::find_if(impl->instructions.begin(),
                        impl->instructions.end(),
Paul's avatar
Paul committed
318
                        [&](const instruction& i) { return !i.valid(impl->instructions.begin()); });
Paul's avatar
Paul committed
319
320
}

mei-ye's avatar
mei-ye committed
321
void program::compile(const target& t, tracer trace)
Paul's avatar
Paul committed
322
{
Paul's avatar
Paul committed
323
    assert(this->validate() == impl->instructions.end());
mei-ye's avatar
mei-ye committed
324
    this->impl->ctx = t.get_context();
Paul's avatar
Paul committed
325
    if(enabled(MIGRAPHX_TRACE_COMPILE{}))
Paul's avatar
Paul committed
326
327
328
        trace = tracer{std::cout};
    trace(*this);
    trace();
Paul's avatar
Paul committed
329
    for(auto&& p : t.get_passes(this->impl->ctx))
Paul's avatar
Paul committed
330
    {
Paul's avatar
Paul committed
331
        trace("Pass: ", p.name());
Paul's avatar
Paul committed
332
        p.apply(*this);
Paul's avatar
Paul committed
333
        trace(*this);
Paul's avatar
Paul committed
334
#ifndef NDEBUG
Paul's avatar
Paul committed
335
        trace("Validate ...");
Paul's avatar
Paul committed
336
        auto invalid = this->validate();
Paul's avatar
Paul committed
337
338
        if(invalid != impl->instructions.end())
        {
Paul's avatar
Paul committed
339
            auto index = std::distance(impl->instructions.begin(), invalid);
Paul's avatar
Paul committed
340
            MIGRAPHX_THROW(p.name() + " pass produces invalid program at instruction " +
Paul's avatar
Paul committed
341
                           std::to_string(index) + ": " + invalid->name());
Paul's avatar
Paul committed
342
        }
Paul's avatar
Paul committed
343
        trace();
Paul's avatar
Paul committed
344
345
#endif
    }
Paul's avatar
Paul committed
346
    auto invalid = this->validate();
Paul's avatar
Paul committed
347
348
    if(invalid != impl->instructions.end())
    {
Paul's avatar
Paul committed
349
        auto index = std::distance(impl->instructions.begin(), invalid);
Paul's avatar
Paul committed
350
        MIGRAPHX_THROW("Invalid program from compilation at instruction " + std::to_string(index));
Paul's avatar
Paul committed
351
    }
Paul's avatar
Paul committed
352
353
354
355
356
357
358
359
360
    this->finalize();
}

void program::finalize()
{
    for(auto ins : iterator_for(*this))
    {
        ins->finalize(this->impl->ctx);
    }
Paul's avatar
Paul committed
361
362
}

Paul's avatar
Paul committed
363
364
365
366
367
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
368
{
Paul's avatar
Paul committed
369
    assert(p.validate() == p.end());
370
    std::unordered_map<instruction_ref, argument> results;
Paul's avatar
Paul committed
371
    results.reserve(p.size() * 2);
Paul's avatar
Paul committed
372
373
    std::vector<argument> values;
    values.reserve(16);
374
    for(auto ins : iterator_for(p))
Paul's avatar
Paul committed
375
    {
Paul's avatar
Paul committed
376
        if(ins->name() == "@literal")
Paul's avatar
Paul committed
377
        {
Paul's avatar
Paul committed
378
            results.emplace(ins, trace(ins, [&] { return ins->get_literal().get_argument(); }));
Paul's avatar
Paul committed
379
        }
Paul's avatar
Paul committed
380
        else if(ins->name() == "@param")
Paul's avatar
Paul committed
381
        {
Paul's avatar
Paul committed
382
383
384
385
386
387
388
389
390
391
392
            results.emplace(
                ins, trace(ins, [&] {
                    auto param_name = any_cast<builtin::param>(ins->get_operator()).parameter;
                    if(not contains(params, param_name))
                        MIGRAPHX_THROW("Parameter not found: " + param_name);
                    auto param = params.at(param_name);
                    if(param.get_shape() != ins->get_shape())
                        MIGRAPHX_THROW("Incorrect shape {" + to_string(param.get_shape()) +
                                       "} for parameter: " + param_name);
                    return param;
                }));
Paul's avatar
Paul committed
393
        }
Paul's avatar
Paul committed
394
        else if(ins->name() == "@outline")
Paul's avatar
Paul committed
395
        {
Paul's avatar
Paul committed
396
            results.emplace(ins, trace(ins, [&] { return argument{ins->get_shape(), nullptr}; }));
Paul's avatar
Paul committed
397
        }
Paul's avatar
Paul committed
398
399
        else
        {
Paul's avatar
Paul committed
400
            values.resize(ins->inputs().size());
Paul's avatar
Paul committed
401
402
403
404
405
            std::transform(
                ins->inputs().begin(), ins->inputs().end(), values.begin(), [&](instruction_ref i) {
                    assert(results.find(i) != results.end());
                    return results[i];
                });
Paul's avatar
Paul committed
406
407
408
            results.emplace(ins, trace(ins, [&] {
                                return ins->get_operator().compute(ctx, ins->get_shape(), values);
                            }));
Paul's avatar
Paul committed
409
        }
410
        assert(results.find(ins) != results.end());
Paul's avatar
Paul committed
411
    }
412
    return results.at(std::prev(p.end()));
Paul's avatar
Paul committed
413
414
}

Paul's avatar
Paul committed
415
416
argument program::eval(std::unordered_map<std::string, argument> params) const
{
Paul's avatar
Paul committed
417
418
    auto& ctx = this->impl->ctx;
#ifndef NDEBUG
Paul's avatar
Paul committed
419
    auto sctx          = ctx;
Paul's avatar
Paul committed
420
421
422
    auto check_context = [&](auto f) {
        assert(is_shared(ctx, sctx));
        auto x = f();
Paul's avatar
Paul committed
423
        sctx   = ctx;
Paul's avatar
Paul committed
424
425
426
        return x;
    };
#else
Paul's avatar
Paul committed
427
    auto check_context = [](auto f) { return f(); };
Paul's avatar
Paul committed
428
#endif
Paul's avatar
Paul committed
429
    if(enabled(MIGRAPHX_TRACE_EVAL{}))
Paul's avatar
Paul committed
430
    {
Paul's avatar
Paul committed
431
        return generic_eval(*this, ctx, std::move(params), [&](auto& ins, auto f) {
Paul's avatar
Paul committed
432
            ctx.finish();
Paul's avatar
Paul committed
433
434
            std::cout << "Run instruction: ";
            this->debug_print(ins);
Paul's avatar
Paul committed
435
            return check_context(f);
Paul's avatar
Paul committed
436
        });
Paul's avatar
Paul committed
437
438
439
440
    }
    else
    {
        return generic_eval(
Paul's avatar
Paul committed
441
            *this, ctx, std::move(params), [&](auto&, auto f) { return check_context(f); });
Paul's avatar
Paul committed
442
    }
Paul's avatar
Paul committed
443
444
}

Paul's avatar
Paul committed
445
446
447
double common_average(const std::vector<double>& v)
{
    std::size_t n = v.size() / 4;
Paul's avatar
Paul committed
448
449
    double total  = std::accumulate(v.begin() + n, v.end() - n, 0.0);
    return total / std::distance(v.begin() + n, v.end() - n);
Paul's avatar
Paul committed
450
451
}

Paul's avatar
Paul committed
452
453
454
void program::perf_report(std::ostream& os, std::size_t n, parameter_map params) const
{
    using milliseconds = std::chrono::duration<double, std::milli>;
Paul's avatar
Paul committed
455
    auto& ctx          = this->impl->ctx;
Paul's avatar
Paul committed
456
457
    // Run once by itself
    eval(params);
Paul's avatar
Paul committed
458
    ctx.finish();
Paul's avatar
Paul committed
459
    // Run and time entire program
Paul's avatar
Paul committed
460
461
    std::vector<double> total_vec;
    total_vec.reserve(n);
Paul's avatar
Paul committed
462
    for(std::size_t i = 0; i < n; i++)
Paul's avatar
Paul committed
463
    {
Paul's avatar
Paul committed
464
465
466
467
        total_vec.push_back(time<milliseconds>([&] {
            eval(params);
            ctx.finish();
        }));
Paul's avatar
Paul committed
468
    }
Paul's avatar
Paul committed
469
470
    std::sort(total_vec.begin(), total_vec.end());
    std::unordered_map<instruction_ref, std::vector<double>> ins_vec;
Paul's avatar
Paul committed
471
    // Fill the map
Paul's avatar
Paul committed
472
    generic_eval(*this, ctx, params, [&](auto ins, auto) {
Paul's avatar
Paul committed
473
        ins_vec[ins].reserve(n);
Paul's avatar
Paul committed
474
475
        return argument{};
    });
Paul's avatar
Paul committed
476
    // Run and time each instruction
Paul's avatar
Paul committed
477
    for(std::size_t i = 0; i < n; i++)
Paul's avatar
Paul committed
478
    {
Paul's avatar
Paul committed
479
        generic_eval(*this, ctx, params, [&](auto ins, auto f) {
480
            argument result;
Paul's avatar
Paul committed
481
482
483
484
            ins_vec[ins].push_back(time<milliseconds>([&] {
                result = f();
                ctx.finish();
            }));
485
            return result;
Paul's avatar
Paul committed
486
487
        });
    }
Paul's avatar
Paul committed
488
489
    for(auto&& p : ins_vec)
        std::sort(p.second.begin(), p.second.end());
Paul's avatar
Paul committed
490
    // Run and time implicit overhead
Paul's avatar
Paul committed
491
492
    std::vector<double> overhead_vec;
    overhead_vec.reserve(n);
Paul's avatar
Paul committed
493
    for(std::size_t i = 0; i < n; i++)
Paul's avatar
Paul committed
494
    {
Paul's avatar
Paul committed
495
        overhead_vec.push_back(time<milliseconds>([&] { dry_run(params); }));
Paul's avatar
Paul committed
496
497
    }

Paul's avatar
Paul committed
498
    double total_time             = common_average(total_vec);
Paul's avatar
Paul committed
499
    double rate                   = 1000.0 / total_time;
Paul's avatar
Paul committed
500
    double overhead_time          = common_average(overhead_vec);
Paul's avatar
Paul committed
501
    double overhead_percent       = overhead_time * 100.0 / total_time;
Paul's avatar
Paul committed
502
    double total_instruction_time = 0.0;
Paul's avatar
Paul committed
503
    std::unordered_map<std::string, double> op_times;
Paul's avatar
Paul committed
504
    for(auto&& p : ins_vec)
Paul's avatar
Paul committed
505
506
    {
        double avg = common_average(p.second);
Paul's avatar
Paul committed
507
        op_times[p.first->name()] += avg;
Paul's avatar
Paul committed
508
509
        total_instruction_time += avg;
    }
Paul's avatar
Paul committed
510
511
    double calculate_overhead_time    = total_time - total_instruction_time;
    double calculate_overhead_percent = calculate_overhead_time * 100.0 / total_time;
Paul's avatar
Paul committed
512

Paul's avatar
Paul committed
513
514
515
516
517
    print_program(os, *this, [&](auto ins, auto&&) {
        double avg     = common_average(ins_vec[ins]);
        double percent = std::ceil(100.0 * avg / total_instruction_time);
        os << ": " << avg << "ms, " << percent << "%";
    });
Paul's avatar
Paul committed
518
519
520

    os << std::endl;
    os << "Summary:" << std::endl;
Paul's avatar
Paul committed
521
    for(auto&& p : op_times)
Paul's avatar
Paul committed
522
    {
Paul's avatar
Paul committed
523
524
        auto&& name    = p.first;
        double avg     = p.second;
Paul's avatar
Paul committed
525
526
527
528
529
        double percent = std::ceil(100.0 * avg / total_instruction_time);
        os << name << ": " << avg << "ms, " << percent << "%" << std::endl;
    }

    os << std::endl;
Paul's avatar
Paul committed
530

Paul's avatar
Paul committed
531
    os << "Rate: " << rate << "/sec" << std::endl;
Paul's avatar
Paul committed
532
533
    os << "Total time: " << total_time << "ms" << std::endl;
    os << "Total instructions time: " << total_instruction_time << "ms" << std::endl;
Paul's avatar
Paul committed
534
535
536
537
    os << "Overhead time: " << overhead_time << "ms"
       << ", " << calculate_overhead_time << "ms" << std::endl;
    os << "Overhead: " << std::round(overhead_percent) << "%"
       << ", " << std::round(calculate_overhead_percent) << "%" << std::endl;
Paul's avatar
Paul committed
538
539
}

Paul's avatar
Paul committed
540
541
void program::debug_print() const { std::cout << *this << std::endl; }
void program::debug_print(instruction_ref ins) const
Paul's avatar
Paul committed
542
{
Paul's avatar
Paul committed
543
544
545
546
547
548
549
550
551
552
    if(ins == this->end())
    {
        std::cout << "End instruction" << std::endl;
        return;
    }
    if(not has_instruction(ins))
    {
        std::cout << "Instruction not part of program" << std::endl;
        return;
    }
Paul's avatar
Paul committed
553
554
    std::stringstream ss;
    print_program(ss, *this, [&](auto x, auto&& names) {
Paul's avatar
Paul committed
555
        if(x == ins)
Paul's avatar
Paul committed
556
557
558
559
560
561
        {
            print_instruction(std::cout, x, names);
            std::cout << std::endl;
        }
    });
}
Paul's avatar
Paul committed
562
void program::debug_print(const std::vector<instruction_ref>& inss) const
Paul's avatar
Paul committed
563
{
Paul's avatar
Paul committed
564
    for(auto ins : inss)
Paul's avatar
Paul committed
565
566
567
568
        debug_print(ins);
    std::cout << std::endl;
}

569
570
571
572
573
574
575
576
void program::print_graph(std::ostream& os) const
{
    os << "digraph {" << std::endl;
    os << "\trankdir=LR;" << std::endl;
    print_program(os, *this, [](auto&&...) {}, print_graph_node);
    os << "}" << std::endl;
}

Paul's avatar
Paul committed
577
578
void program::dry_run(std::unordered_map<std::string, argument> params) const
{
Paul's avatar
Paul committed
579
    auto& ctx = this->impl->ctx;
Paul's avatar
Paul committed
580
    generic_eval(*this, ctx, std::move(params), [](auto&&...) { return argument{}; });
Paul's avatar
Paul committed
581
582
}

Paul's avatar
Paul committed
583
584
585
586
587
void program::annotate(std::ostream& os, std::function<void(instruction_ref)> a) const
{
    print_program(os, *this, [&](auto ins, auto&&) { a(ins); });
}

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

Paul's avatar
Paul committed
590
std::ostream& operator<<(std::ostream& os, const program& p)
Paul's avatar
Paul committed
591
{
Paul's avatar
Paul committed
592
    print_program(os, p, [](auto&&...) {});
Paul's avatar
Paul committed
593
    return os;
Paul's avatar
Paul committed
594
}
Paul's avatar
Paul committed
595

Paul's avatar
Paul committed
596
} // namespace MIGRAPHX_INLINE_NS
Paul's avatar
Paul committed
597
} // namespace migraphx