cpp_generator.cpp 9.43 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/*
 * The MIT License (MIT)
 *
 * Copyright (c) 2015-2022 Advanced Micro Devices, Inc. All rights reserved.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
24
25
26
#include <migraphx/cpp_generator.hpp>
#include <migraphx/module.hpp>
#include <migraphx/operation.hpp>
27
#include <migraphx/ranges.hpp>
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
#include <migraphx/instruction.hpp>
#include <migraphx/builtin.hpp>
#include <migraphx/stringutils.hpp>
#include <migraphx/iterator_for.hpp>
#include <map>
#include <sstream>

namespace migraphx {
inline namespace MIGRAPHX_INLINE_NS {

cpp_generator::function&
cpp_generator::function::set_body(const module& m, const cpp_generator::generate_module_callback& g)
{
    std::unordered_map<migraphx::instruction_ref, std::string> names;
    std::stringstream ss;

    auto return_ins = std::prev(m.end());

    for(auto ins : iterator_for(m))
    {
        ss << "// " << ins->get_operator() << " -> " << ins->get_shape() << "\n";
        if(ins->name() == "@param")
        {
            names[ins] =
                migraphx::any_cast<migraphx::builtin::param>(ins->get_operator()).parameter;
        }
54
        else if(ins->name() == "@return")
55
56
57
58
        {
            assert(ins->inputs().size() == 1);
            return_ins = ins->inputs().front();
        }
59
60
61
62
63
64
        else
        {
            std::string n = "z" + std::to_string(names.size());
            names[ins]    = n;
            ss << "auto " << n << " = " << g(ins, names) << ";\n";
        }
65
66
67
68
69
70
71
72
73
74
75
76
77
    }
    ss << "return " << names.at(return_ins) << ";\n";
    body = ss.str();
    return *this;
}

cpp_generator::function& cpp_generator::function::set_types(const module& m)
{
    return cpp_generator::function::set_types(m, [](auto s) { return shape::cpp_type(s.type()); });
}
cpp_generator::function&
cpp_generator::function::set_types(const module& m, const std::function<std::string(shape)>& parse)
{
78
    this->params.clear();
79
80
81
82
83
84
85
86
87
88
89
90
    auto pmap = m.get_parameter_shapes();
    std::map<std::string, shape> input_map(pmap.begin(), pmap.end());
    std::transform(
        input_map.begin(), input_map.end(), std::back_inserter(this->params), [&](auto&& p) {
            return param{p.first, parse(p.second)};
        });
    auto output_shapes = m.get_output_shapes();
    assert(not output_shapes.empty());
    this->return_type = parse(output_shapes.front());
    return *this;
}

91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
cpp_generator::function& cpp_generator::function::set_generic_types(const module& m)
{
    this->params.clear();
    auto pmap = m.get_parameter_shapes();
    std::map<std::string, shape> input_map(pmap.begin(), pmap.end());
    std::transform(
        input_map.begin(), input_map.end(), std::back_inserter(this->params), [&](auto&& p) {
            return param{p.first, "T" + p.first};
        });

    std::transform(input_map.begin(),
                   input_map.end(),
                   std::back_inserter(this->tparams),
                   [&](auto&& p) { return "class T" + p.first; });
    this->return_type = "auto";
    return *this;
}

109
110
111
112
113
cpp_generator::function& cpp_generator::function::unused_param(const std::string& pname)
{
    body.insert(0, "(void)" + pname + ";\n");
    return *this;
}
Paul Fultz II's avatar
Paul Fultz II committed
114
115
116
117
118
119
120
cpp_generator::function& cpp_generator::function::add_generic_param(const std::string& pname)
{
    params.push_back({pname, "T" + pname});
    tparams.push_back("class T" + pname);
    return *this;
}

121
122
123
struct cpp_generator_impl
{
    std::stringstream fs{};
124
125
    std::size_t function_count                                = 0;
    std::function<std::string(std::string)> fmap              = nullptr;
126
    std::function<std::string(shape)> fresult                 = nullptr;
127
    std::unordered_map<std::string, std::string> point_op_map = {};
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
};
cpp_generator::cpp_generator() : impl(std::make_unique<cpp_generator_impl>()) {}

cpp_generator::cpp_generator(cpp_generator&&) noexcept = default;

cpp_generator& cpp_generator::operator=(cpp_generator rhs)
{
    std::swap(impl, rhs.impl);
    return *this;
}

cpp_generator::~cpp_generator() noexcept = default;

void cpp_generator::fmap(const std::function<std::string(std::string)>& f) { impl->fmap = f; }

143
144
void cpp_generator::fresult(const std::function<std::string(shape)>& f) { impl->fresult = f; }

145
146
147
148
149
void cpp_generator::add_point_op(const std::string& op_name, const std::string& code)
{
    impl->point_op_map[op_name] = code;
}

150
151
152
std::string cpp_generator::generate_point_op(const operation& op,
                                             const std::vector<std::string>& args)
{
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
    auto v = op.to_value();
    std::string code;
    if(contains(impl->point_op_map, op.name()))
    {
        code = impl->point_op_map.at(op.name());
    }
    else
    {
        auto attributes = op.attributes();
        if(not attributes.contains("point_op"))
            MIGRAPHX_THROW("op is missing point_op attribute: " + op.name());
        code = attributes["point_op"].to<std::string>();
    }
    return interpolate_string(code, [&](auto start, auto last) -> std::string {
        auto key = trim({start, last});
        if(key.empty())
            MIGRAPHX_THROW("Empty parameter");
        std::string fselector = "function:";
        if(starts_with(key, fselector))
        {
            auto fname = key.substr(fselector.size());
            if(impl->fmap == nullptr)
                return fname;
            else
                return impl->fmap(fname);
        }
        else if(with_char(::isdigit)(key[0]))
        {
            auto i = std::stoul(key);
182
183
            if(i >= args.size())
                MIGRAPHX_THROW("Invalid argument index: " + key);
184
185
186
187
188
189
190
191
192
193
194
            return args.at(i);
        }
        else if(v.contains(key))
        {
            return v[key].template to<std::string>();
        }
        else
        {
            return key;
        }
    });
195
196
197
198
}

std::string cpp_generator::str() const { return impl->fs.str(); }

Paul Fultz II's avatar
Paul Fultz II committed
199
200
cpp_generator::function cpp_generator::generate_module(const module& m,
                                                       const generate_module_callback& g)
201
202
{
    function f;
203
204
205
206
207
208
    auto name = transform_string(m.name(), [](char c) {
        if(with_char(::isalnum)(c) or c == '_')
            return c;
        return '_';
    });
    f.set_name(name).set_types(m).set_body(
209
210
        m, [&](instruction_ref ins, const auto& names) -> std::string {
            if(ins->name() == "@literal")
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
            {
                std::string string_literal;
                ins->get_literal().visit([&](auto v) {
                    assert(v.size() == 1);
                    auto x = v.front();
                    if(std::isinf(x))
                    {
                        string_literal = "__builtin_huge_val()";
                        if(x < 0)
                            string_literal = "-__builtin_huge_val()";
                    }
                    else if(std::isnan(x))
                        string_literal = "__builtin_nan()";
                    else
                        string_literal = ins->get_literal().to_string();
                });
                return shape::cpp_type(ins->get_shape().type()) + "(" + string_literal + ")";
            }
Paul Fultz II's avatar
Paul Fultz II committed
229
            auto s = g(ins, names);
230
231
232
233
            if(impl->fresult)
                return impl->fresult(ins->get_shape()) + '(' + s + ')';
            else
                return s;
234
235
236
237
        });
    return f;
}

Paul Fultz II's avatar
Paul Fultz II committed
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
std::vector<std::string>
cpp_generator::to_args(const std::vector<instruction_ref>& inputs,
                       const std::unordered_map<instruction_ref, std::string>& names)
{
    std::vector<std::string> args;
    std::transform(inputs.begin(), inputs.end(), std::back_inserter(args), [&](auto i) {
        return names.at(i);
    });
    return args;
}

cpp_generator::function cpp_generator::generate_module(const module& m)
{
    return this->generate_module(m, [&](auto ins, const auto& names) {
        return this->generate_point_op(ins->get_operator(), to_args(ins->inputs(), names));
    });
}

256
257
258
std::string cpp_generator::create_function(const cpp_generator::function& f)
{
    impl->function_count++;
259
260
    if(not f.tparams.empty())
        impl->fs << "template<" << join_strings(f.tparams, ", ") << ">\n";
261
262
263
    std::string name = f.name.empty() ? "f" + std::to_string(impl->function_count) : f.name;
    impl->fs << join_strings(f.attributes, " ") << " " << f.return_type << " " << name;
    char delim = '(';
264
265
    if(f.params.empty())
        impl->fs << delim;
266
267
268
269
270
271
272
273
274
275
276
    for(auto&& p : f.params)
    {
        impl->fs << delim << p.type << " " << p.name;
        delim = ',';
    }
    impl->fs << ") {\n" << f.body << "\n}\n";
    return name;
}

} // namespace MIGRAPHX_INLINE_NS
} // namespace migraphx