autogen.cpp 22.0 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13
#include <iostream>
#include <unordered_map>
#include <functional>

#include "./helper.h"

using llvm::raw_ostream;
using llvm::RecordKeeper;

enum ActionType {
    None,
    CppHeader,
    CppBody,
14 15
    Pybind,
    CPython
16 17 18 19 20 21 22 23 24 25
};

// NOLINTNEXTLINE
llvm::cl::opt<ActionType> action(
    llvm::cl::desc("Action to perform:"),
    llvm::cl::values(clEnumValN(CppHeader, "gen-cpp-header",
                                "Generate operator cpp header"),
                     clEnumValN(CppBody, "gen-cpp-body",
                                "Generate operator cpp body"),
                     clEnumValN(Pybind, "gen-python-binding",
26 27 28
                                "Generate pybind11 python bindings"),
                     clEnumValN(CPython, "gen-python-c-extension",
                                "Generate python c extensions")));
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 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115

using MgbAttrWrapper = mlir::tblgen::MgbAttrWrapperBase;
using MgbEnumAttr = mlir::tblgen::MgbEnumAttrMixin;
using MgbHashableAttr = mlir::tblgen::MgbHashableAttrMixin;
using MgbAliasAttr = mlir::tblgen::MgbAliasAttrMixin;
using MgbOp = mlir::tblgen::MgbOpBase;
using MgbHashableOp = mlir::tblgen::MgbHashableOpMixin;

llvm::StringRef attr_to_ctype(const mlir::tblgen::Attribute& attr_) {
    // Note: we have already registered the corresponding attr wrappers
    // for following basic ctypes so we needn't handle them here
    /* auto&& attr_type_name = attr.getAttrDefName();
    if (attr_type_name == "UI32Attr") {
        return "uint32_t";
    }
    if (attr_type_name == "UI64Attr") {
        return "uint64_t";
    }
    if (attr_type_name == "I32Attr") {
        return "int32_t";
    }
    if (attr_type_name == "F32Attr") {
        return "float";
    }
    if (attr_type_name == "F64Attr") {
        return "double";
    }
    if (attr_type_name == "StrAttr") {
        return "std::string";
    }
    if (attr_type_name == "BoolAttr") {
        return "bool";
    }*/

    auto&& attr = llvm::cast<MgbAttrWrapper>(attr_);
    if (auto e = llvm::dyn_cast<MgbEnumAttr>(&attr)) {
        return e->getEnumName();
    }
    return attr.getUnderlyingType();
}

static void gen_op_def_c_header_single(raw_ostream &os, MgbOp& op) {
    os << formatv(
        "class {0} : public OpDefImplBase<{0}> {{\n"
        "    MGB_DYN_TYPE_OBJ_FINAL_DECL;\n\n"
        "public:\n",
        op.getCppClassName()
    );
    // handle enum alias
    for (auto &&i : op.getMgbAttributes()) {
        if (auto attr = llvm::dyn_cast<MgbEnumAttr>(&i.attr)) {
            os << formatv(
                "    using {0} = {1};\n",
                attr->getEnumName(), attr->getUnderlyingType()
            );
        }
    }
    for (auto &&i : op.getMgbAttributes()) {
        auto defaultValue = i.attr.getDefaultValue().str();
        if (!defaultValue.empty()) {
            defaultValue = formatv(" = {0}", defaultValue);
        }
        os << formatv(
            "    {0} {1}{2};\n",
            attr_to_ctype(i.attr), i.name, defaultValue
        );
    }

    auto gen_ctor = [&](auto&& paramList, auto&& memInitList, auto&& body) {
        os << formatv(
            "    {0}({1}){2}{3}\n",
            op.getCppClassName(), paramList, memInitList, body
        );
    };

    gen_ctor("", "", " = default;");

    if (!op.getMgbAttributes().empty()) {
        std::vector<std::string> paramList, initList;
        for (auto &&i : op.getMgbAttributes()) {
            paramList.push_back(formatv(
                "{0} {1}_", attr_to_ctype(i.attr), i.name
            ));
            initList.push_back(formatv(
                "{0}({0}_)", i.name
            ));
        }
116
        paramList.push_back("std::string scope_ = {}");
117 118
        gen_ctor(llvm::join(paramList, ", "),
                 ": " + llvm::join(initList, ", "),
119
                 " { set_scope(scope_); }");
120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 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 packedParams = op.getPackedParams();
    if (!packedParams.empty()) {
        std::vector<std::string> paramList, initList;
        for (auto &&p : packedParams) {
            auto&& paramFields = p.getFields();
            auto&& paramType = p.getFullName();
            auto&& paramName = formatv("packed_param_{0}", paramList.size());
            paramList.push_back(
                paramFields.empty() ? paramType.str()
                    : formatv("{0} {1}", paramType, paramName)
            );
            for (auto&& i : paramFields) {
                initList.push_back(formatv(
                    "{0}({1}.{0})", i.name, paramName
                ));
            }
        }
        for (auto&& i : op.getExtraArguments()) {
            paramList.push_back(formatv(
                "{0} {1}_", attr_to_ctype(i.attr), i.name
            ));
            initList.push_back(formatv(
                "{0}({0}_)", i.name
            ));
        }
        gen_ctor(llvm::join(paramList, ", "),
                 initList.empty() ? "" : ": " + llvm::join(initList, ", "),
                 " {}");
    }

    if (!packedParams.empty()) {
        for (auto&& p : packedParams) {
            auto accessor = p.getAccessor();
            if (!accessor.empty()) {
                os << formatv(
                    "    {0} {1}() const {{\n",
                    p.getFullName(), accessor
                );
                std::vector<llvm::StringRef> fields;
                for (auto&& i : p.getFields()) {
                    fields.push_back(i.name);
                }
                os << formatv(
                    "        return {{{0}};\n",
                    llvm::join(fields, ", ")
                );
                os << "    }\n";
            }
        }
    }

    if (auto decl = op.getExtraOpdefDecl()) {
        os << decl.getValue();
    }

    os << formatv(
        "};\n\n"
    );
}

182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209
static void gen_to_string_trait_for_enum(raw_ostream &os, MgbOp& op) {
    for (auto &&i : op.getMgbAttributes()) {
        if (auto attr = llvm::dyn_cast<MgbEnumAttr>(&i.attr)) {
            if (attr->supportToString()) {
                std::vector<std::string> case_body;
                std::string ename = formatv("{0}::{1}",
                    op.getCppClassName(), attr->getEnumName());
                llvm::for_each(attr->getEnumMembers(), [&](auto&& v){
                    case_body.push_back(formatv(
                        "case {0}::{1}: return \"{1}\";", ename, v));
                });
                os << formatv(R"(
template <>
struct ToStringTrait<{0}> {
    std::string operator()({0} e) const {
        switch (e) {
            {1}
            default:
                return "{0}::Unknown";
        }
    }
};
)", ename, llvm::join(case_body, "\n"));
            }
        }
    }
}

210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230
static void gen_op_def_c_body_single(raw_ostream &os, MgbOp& op) {
    auto&& className = op.getCppClassName();
    os << formatv(
        "MGB_DYN_TYPE_OBJ_FINAL_IMPL({0});\n\n", className
    );
    auto formatMethImpl = [&](auto&& meth) {
        return formatv(
            "{0}_{1}_impl", className, meth
        );
    };
    std::vector<std::string> methods;
    if (auto hashable = llvm::dyn_cast<MgbHashableOp>(&op)) {
        os << "namespace {\n";

        // generate hash()
        mlir::tblgen::FmtContext ctx;
        os << formatv(
            "size_t {0}(const OpDef& def_) {{\n",
            formatMethImpl("hash")
        );
        os << formatv(
231
            "    auto&& op_ = def_.cast_final_safe<{0}>();\n"
232 233 234 235 236 237 238 239 240 241 242 243 244
            "    static_cast<void>(op_);\n",
            className
        );
        ctx.withSelf("op_");
        os << mlir::tblgen::tgfmt(hashable->getHashFunctionTemplate(), &ctx);
        os << "}\n";

        // generate is_same_st()
        os << formatv(
            "bool {0}(const OpDef& lhs_, const OpDef& rhs_) {{\n",
            formatMethImpl("is_same_st")
        );
        os << formatv(
245 246
            "    auto &&a_ = lhs_.cast_final_safe<{0}>(),\n"
            "         &&b_ = rhs_.cast_final_safe<{0}>();\n"
247 248 249 250 251 252 253
            "    static_cast<void>(a_);\n"
            "    static_cast<void>(b_);\n",
            className
        );
        os << mlir::tblgen::tgfmt(hashable->getCmpFunctionTemplate(), &ctx, "a_", "b_");
        os << "}\n";

254 255 256 257 258 259 260 261 262 263 264 265 266 267
        // generate props()
        os << formatv(
            "std::vector<std::pair<const char*, std::string>> {0}(const OpDef& def_) {{\n",
            formatMethImpl("props")
        );
        os << formatv(
            "    auto&& op_ = def_.cast_final_safe<{0}>();\n"
            "    static_cast<void>(op_);\n",
            className
        );
        ctx.withSelf("op_");
        os << mlir::tblgen::tgfmt(hashable->getPropsFunctionTemplate(), &ctx);
        os << "}\n";

268 269 270 271
        // generate make_name()
        os << formatv(
            "std::string {0}(const OpDef& def_) {{\n", formatMethImpl("make_name")
        );
272 273 274 275 276 277 278
        os << formatv(
            "    auto&& op_ = def_.cast_final_safe<{0}>();\n"
            "    static_cast<void>(op_);\n",
            className
        );
        ctx.withSelf("op_");
        os << mlir::tblgen::tgfmt(op.getNameFunctionTemplate(), &ctx);
279 280
        os << "}\n";

281 282 283 284
        os << "} // anonymous namespace\n";

        methods.push_back("hash");
        methods.push_back("is_same_st");
285
        methods.push_back("props");
286
        methods.push_back("make_name");
287 288 289 290 291 292 293 294 295 296 297 298 299 300
    }
    if (!methods.empty()) {
        os << formatv(
            "OP_TRAIT_REG({0}, {0})", op.getCppClassName()
        );
        for (auto&& i : methods) {
            os << formatv(
                "\n    .{0}({1})", i, formatMethImpl(i)
            );
        }
        os << ";\n\n";
    }
}

301 302
struct EnumContext {
    std::unordered_map<unsigned int, std::pair<llvm::StringRef, llvm::StringRef>> enumAlias;
303 304
};

305 306
static void gen_op_def_pybind11_single(raw_ostream &os, MgbOp& op, EnumContext& ctx) {
    auto className = op.getCppClassName();
307 308
    os << formatv(
        "py::class_<{0}, std::shared_ptr<{0}>, OpDef> {0}Inst(m, \"{0}\");\n\n",
309
        className
310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326
    );
    for (auto&& i : op.getMgbAttributes()) {
        if (auto attr = llvm::dyn_cast<MgbEnumAttr>(&i.attr)) {
            unsigned int enumID;
            if (auto alias = llvm::dyn_cast<MgbAliasAttr>(attr)) {
                auto&& aliasBase = alias->getAliasBase();
                enumID =
                    llvm::cast<MgbEnumAttr>(aliasBase)
                            .getBaseRecord()->getID();
            } else {
                enumID = attr->getBaseRecord()->getID();
            }
            auto&& enumAlias = ctx.enumAlias;
            auto&& iter = enumAlias.find(enumID);
            if (iter == enumAlias.end()) {
                os << formatv(
                    "py::enum_<{0}::{1}>({0}Inst, \"{1}\")",
327
                    className, attr->getEnumName()
328 329 330 331 332
                );
                std::vector<std::string> body;
                for (auto&& i: attr->getEnumMembers()) {
                    os << formatv(
                        "\n    .value(\"{2}\", {0}::{1}::{2})",
333
                        className, attr->getEnumName(), i
334 335 336
                    );
                    body.push_back(formatv(
                        "if (str == \"{2}\") return {0}::{1}::{2};",
337
                        className, attr->getEnumName(), i
338 339 340 341 342 343 344 345 346 347 348 349
                    ));
                }
                os << formatv(
                    "\n    .def(py::init([](const std::string& in) {"
                    "\n        auto&& str = normalize_enum(in);"
                    "\n        {0}"
                    "\n        throw py::cast_error(\"invalid enum value \" + in);"
                    "\n    }));\n",
                    llvm::join(body, "\n        ")
                );
                os << formatv(
                    "py::implicitly_convertible<std::string, {0}::{1}>();\n\n",
350
                    className, attr->getEnumName()
351
                );
352 353
                enumAlias.emplace(enumID,
                    std::make_pair(className, attr->getEnumName()));
354 355
            } else {
                os << formatv(
356 357 358
                    "{0}Inst.attr(\"{1}\") = {2}Inst.attr(\"{3}\");\n\n",
                    className, attr->getEnumName(),
                    iter->second.first, iter->second.second
359 360 361 362 363
                );
            }
        }
    }
    // generate op class binding
364
    os << formatv("{0}Inst", className);
365 366 367 368 369 370 371 372
    bool hasDefaultCtor = op.getMgbAttributes().empty();
    if (!hasDefaultCtor) {
        os << "\n    .def(py::init<";
        std::vector<llvm::StringRef> targs;
        for (auto &&i : op.getMgbAttributes()) {
            targs.push_back(i.attr.getReturnType());
        }
        os << llvm::join(targs, ", ");
373
        os << ", std::string>()";
374 375 376 377 378 379 380 381 382
        for (auto &&i : op.getMgbAttributes()) {
            os << formatv(", py::arg(\"{0}\")", i.name);
            auto defaultValue = i.attr.getDefaultValue();
            if (!defaultValue.empty()) {
                os << formatv(" = {0}", defaultValue);
            } else {
                hasDefaultCtor = true;
            }
        }
383
        os << ", py::arg(\"scope\") = {})";
384 385 386 387 388 389 390
    }
    if (hasDefaultCtor) {
        os << "\n    .def(py::init<>())";
    }
    for (auto &&i : op.getMgbAttributes()) {
        os << formatv(
            "\n    .def_readwrite(\"{0}\", &{1}::{0})",
391
            i.name, className
392 393 394 395 396
        );
    }
    os << ";\n\n";
}

397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483
static void gen_op_def_python_c_extension_single(raw_ostream &os, MgbOp& op, EnumContext& ctx) {
    auto className = op.getCppClassName();
    std::string body;

    // generate PyType for enum class member
    for (auto&& i : op.getMgbAttributes()) {
        if (auto attr = llvm::dyn_cast<MgbEnumAttr>(&i.attr)) {
            unsigned int enumID;
            if (auto alias = llvm::dyn_cast<MgbAliasAttr>(attr)) {
                auto&& aliasBase = alias->getAliasBase();
                enumID =
                    llvm::cast<MgbEnumAttr>(aliasBase)
                            .getBaseRecord()->getID();
            } else {
                enumID = attr->getBaseRecord()->getID();
            }
            auto&& enumAlias = ctx.enumAlias;
            auto&& iter = enumAlias.find(enumID);
            auto enumName = attr->getEnumName();
            body += "{\n";
            body += formatv(
                "auto& e_type = EnumWrapper<{0}::{1}>::type;", className, enumName
            );
            if (iter == enumAlias.end()) {
                os << formatv(
                    "template<> PyTypeObject EnumWrapper<{0}::{1}>::type={{};\n",
                    className, enumName);
                os << formatv(
                    "template<> const char* EnumWrapper<{0}::{1}>::name = \"{0}.{1}\";\n",
                    className, enumName);
                std::vector<std::string> pairStr;
                for (auto&& i: attr->getEnumMembers()) {
                    pairStr.push_back(formatv(
                        "{{normalize_enum(\"{2}\"), {0}::{1}::{2}}",
                        className, enumName, i));
                }
                os << formatv(R"(
template<> std::unordered_map<std::string, {0}::{1}>
EnumWrapper<{0}::{1}>::str2type = {{
    {2}
};
)", className, enumName, llvm::join(pairStr, ", "));
                pairStr.clear();
                for (auto&& i: attr->getEnumMembers()) {
                    pairStr.push_back(formatv(
                        "{{{0}::{1}::{2}, normalize_enum(\"{2}\")}",
                        className, enumName, i));
                }
                os << formatv(R"(
template<> std::unordered_map<{0}::{1}, std::string>
EnumWrapper<{0}::{1}>::type2str = {{
    {2}
};
)", className, enumName, llvm::join(pairStr, ", "));
                body += formatv(R"(
    e_type = {{PyVarObject_HEAD_INIT(NULL, 0)};
    e_type.tp_name = "megengine.core._imperative_rt.ops.{0}.{1}";
    e_type.tp_basicsize = sizeof(EnumWrapper<{0}::{1}>);
    e_type.tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE;
    e_type.tp_doc = "{0}.{1}";
    e_type.tp_base = &PyBaseObject_Type;
    e_type.tp_repr = EnumWrapper<{0}::{1}>::py_repr;
    e_type.tp_richcompare = EnumWrapper<{0}::{1}>::tp_richcompare;
    mgb_assert(PyType_Ready(&e_type) >= 0);
)", className, enumName);
                for (auto&& i: attr->getEnumMembers()) {
                    body += formatv(R"({{
    PyObject* inst = e_type.tp_alloc(&e_type, 0);
    reinterpret_cast<EnumWrapper<{0}::{1}>*>(inst)->value = {0}::{1}::{2};
    mgb_assert(PyDict_SetItemString(e_type.tp_dict, "{2}", inst) >= 0);
})", className, enumName, i);
                }
                enumAlias.emplace(enumID, std::make_pair(className, enumName));
            }
            body += formatv(R"(
    PyType_Modified(&e_type);
    mgb_assert(PyDict_SetItemString(
        py_type.tp_dict, "{0}", reinterpret_cast<PyObject*>(&e_type)) >= 0);
)", enumName);
            body += "}\n";
        }
    }

    // generate getsetters
    std::vector<std::string> getsetters;
    for (auto &&i : op.getMgbAttributes()) {
        getsetters.push_back(formatv(
484
            "{{const_cast<char*>(\"{1}\"), py_get_generic({0}, {1}), py_set_generic({0}, {1}), const_cast<char*>(\"{1}\"), NULL},",
485 486 487 488 489 490 491
            className, i.name));
    }

    // generate tp_init
    std::string initBody;
    if (!op.getMgbAttributes().empty()) {
        initBody += "static const char* kwlist[] = {";
492 493

        std::vector<llvm::StringRef> attr_name_list;
494
        llvm::for_each(op.getMgbAttributes(), [&](auto&& attr) {
495 496 497 498 499 500
            attr_name_list.push_back(attr.name);
        });
        attr_name_list.push_back("scope");

        llvm::for_each(attr_name_list, [&](auto&& attr) {
            initBody += formatv("\"{0}\", ", attr);
501 502 503
        });
        initBody += "NULL};\n";
        initBody += "    PyObject ";
504 505 506
        std::vector<std::string> attr_init;
        llvm::for_each(attr_name_list, [&](auto&& attr) {
            attr_init.push_back(formatv("*{0} = NULL", attr));
507
        });
508
        initBody += llvm::join(attr_init, ", ") + ";\n";
509
        initBody += "    if (!PyArg_ParseTupleAndKeywords(args, kwds, \"|";
510
        // an extra slot created for name
511
        initBody += std::string(attr_name_list.size(), 'O');
512
        initBody += "\", const_cast<char**>(kwlist)";
513 514
        llvm::for_each(attr_name_list, [&](auto&& attr) {
            initBody += formatv(", &{0}", attr);
515 516 517
        });
        initBody += "))\n";
        initBody += "    return -1;\n";
518

519 520 521 522 523 524
        llvm::for_each(op.getMgbAttributes(), [&](auto&& attr) {
            initBody += formatv(R"(
    if ({1}) {{
        try {{
            reinterpret_cast<PyOp({0})*>(self)->inst().{1} =
                pyobj_convert_generic<decltype({0}::{1})>::from({1});
525
        } CATCH_ALL(-1)
526 527 528
    }
)", className, attr.name);
        });
529 530 531 532

        initBody += formatv(R"(
    if (scope) {{
        try {{
533 534 535
            reinterpret_cast<PyOp(OpDef)*>(self)->op
                ->set_scope(pyobj_convert_generic<std::string>::from(scope));
        } CATCH_ALL(-1)
536 537 538
    }
)", className);

539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578
    }
    initBody += "\n    return 0;";

    os << formatv(R"(
PyOpDefBegin({0}) // {{
    static PyGetSetDef py_getsetters[];
    static int py_init(PyObject *self, PyObject *args, PyObject *kwds);
// };
PyOpDefEnd({0})
PyGetSetDef PyOp({0})::py_getsetters[] = {{
    {1}
    {{NULL}  /* Sentinel */
};
int PyOp({0})::py_init(PyObject *self, PyObject *args, PyObject *kwds) {{
    {2}
}

void _init_py_{0}(py::module m) {{
    using py_op = PyOp({0});
    auto& py_type = PyOpType({0});
    py_type = {{PyVarObject_HEAD_INIT(NULL, 0)};
    py_type.tp_name = "megengine.core._imperative_rt.ops.{0}";
    py_type.tp_basicsize = sizeof(PyOp({0}));
    py_type.tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE;
    py_type.tp_doc = "{0}";
    py_type.tp_base = &PyOpType(OpDef);
    py_type.tp_dealloc = py_dealloc_generic<py_op>;
    py_type.tp_new = py_new_generic<py_op>;
    py_type.tp_init = py_op::py_init;
    py_type.tp_getset = py_op::py_getsetters;
    mgb_assert(PyType_Ready(&py_type) >= 0);
    {3}
    PyType_Modified(&py_type);
    m.add_object("{0}", reinterpret_cast<PyObject*>(&py_type));
    mgb_assert(PyOp(OpDef)::ctype2pytype.emplace({0}::typeinfo(), &py_type).second);
}
)",
    op.getCppClassName(), llvm::join(getsetters, "\n    "), initBody, body);
}

579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596
static void for_each_operator(raw_ostream &os, RecordKeeper &keeper,
        std::function<void(raw_ostream&, MgbOp&)> callback) {
    auto op_base_class = keeper.getClass("Op");
    ASSERT(op_base_class, "could not find base class Op");
    for (auto&& i: keeper.getDefs()) {
        auto&& r = i.second;
        if (r->isSubClassOf(op_base_class)) {
            auto op = mlir::tblgen::Operator(r.get());
            if (op.getDialectName().str() == "mgb") {
                std::cerr << "\033[34;15m" << "Generating " << r->getName().str() << "\033[0m" << std::endl;
                callback(os, llvm::cast<MgbOp>(op));
            }
        }
    }
}

static bool gen_op_def_c_header(raw_ostream &os, RecordKeeper &keeper) {
    for_each_operator(os, keeper, gen_op_def_c_header_single);
597
    for_each_operator(os, keeper, gen_to_string_trait_for_enum);
598 599 600 601 602 603 604 605 606
    return false;
}

static bool gen_op_def_c_body(raw_ostream &os, RecordKeeper &keeper) {
    for_each_operator(os, keeper, gen_op_def_c_body_single);
    return false;
}

static bool gen_op_def_pybind11(raw_ostream &os, RecordKeeper &keeper) {
607
    EnumContext ctx;
608 609 610 611 612 613
    using namespace std::placeholders;
    for_each_operator(os, keeper,
        std::bind(gen_op_def_pybind11_single, _1, _2, std::ref(ctx)));
    return false;
}

614 615 616 617 618 619 620 621 622 623 624 625 626
static bool gen_op_def_python_c_extension(raw_ostream &os, RecordKeeper &keeper) {
    EnumContext ctx;
    using namespace std::placeholders;
    for_each_operator(os, keeper,
        std::bind(gen_op_def_python_c_extension_single, _1, _2, std::ref(ctx)));
    os << "#define INIT_ALL_OP(m)";
    for_each_operator(os, keeper, [&](raw_ostream& os, MgbOp& op) {
        os << formatv(" \\\n    _init_py_{0}(m);", op.getCppClassName());
    });
    os << "\n";
    return false;
}

627 628 629 630 631 632 633 634 635 636 637 638
int main(int argc, char **argv) {
    llvm::InitLLVM y(argc, argv);
    llvm::cl::ParseCommandLineOptions(argc, argv);
    if (action == ActionType::CppHeader) {
        return TableGenMain(argv[0], &gen_op_def_c_header);
    }
    if (action == ActionType::CppBody) {
        return TableGenMain(argv[0], &gen_op_def_c_body);
    }
    if (action == ActionType::Pybind) {
        return TableGenMain(argv[0], &gen_op_def_pybind11);
    }
639 640 641
    if (action == ActionType::CPython) {
        return TableGenMain(argv[0], &gen_op_def_python_c_extension);
    }
642
    return -1;
643
}