1//===- OpInterfacesGen.cpp - MLIR op interface utility generator ----------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// OpInterfacesGen generates definitions for operation interfaces.
10//
11//===----------------------------------------------------------------------===//
12
13#include "CppGenUtilities.h"
14#include "DocGenUtilities.h"
15#include "mlir/TableGen/Format.h"
16#include "mlir/TableGen/GenInfo.h"
17#include "mlir/TableGen/Interfaces.h"
18#include "llvm/ADT/SmallVector.h"
19#include "llvm/ADT/StringExtras.h"
20#include "llvm/Support/FormatVariadic.h"
21#include "llvm/Support/raw_ostream.h"
22#include "llvm/TableGen/CodeGenHelpers.h"
23#include "llvm/TableGen/Error.h"
24#include "llvm/TableGen/Record.h"
25#include "llvm/TableGen/TableGenBackend.h"
26
27using namespace mlir;
28using llvm::Record;
29using llvm::RecordKeeper;
30using mlir::tblgen::Interface;
31using mlir::tblgen::InterfaceMethod;
32using mlir::tblgen::OpInterface;
33
34/// Emit a string corresponding to a C++ type, followed by a space if necessary.
35static raw_ostream &emitCPPType(StringRef type, raw_ostream &os) {
36 type = type.trim();
37 os << type;
38 if (type.back() != '&' && type.back() != '*')
39 os << " ";
40 return os;
41}
42
43/// Share an operation interface method body when it only needs the raw op.
44static bool hasSharedOpBody(const Interface &interface,
45 const InterfaceMethod &method) {
46 if (!isa<OpInterface>(Val: interface) || method.isStatic())
47 return false;
48 std::optional<StringRef> body = method.getBody();
49 return body && body->contains(Other: "$_raw_op") && !body->contains(Other: "ConcreteOp") &&
50 !body->contains(Other: "$_op") && !body->contains(Other: "$_self");
51}
52
53/// Emit the method name and argument list for the given method. If 'addThisArg'
54/// is true, then an argument is added to the beginning of the argument list for
55/// the concrete value.
56static void emitMethodNameAndArgs(const InterfaceMethod &method, StringRef name,
57 raw_ostream &os, StringRef valueType,
58 bool addThisArg, bool addConst) {
59 os << name << '(';
60 if (addThisArg) {
61 if (addConst)
62 os << "const ";
63 os << "const Concept *impl, ";
64 emitCPPType(type: valueType, os)
65 << "tablegen_opaque_val" << (method.arg_empty() ? "" : ", ");
66 }
67 llvm::interleaveComma(c: method.getArguments(), os,
68 each_fn: [&](const InterfaceMethod::Argument &arg) {
69 os << arg.type << " " << arg.name;
70 });
71 os << ')';
72 if (addConst)
73 os << " const";
74}
75
76/// Get an array of all OpInterface definitions but exclude those subclassing
77/// "DeclareOpInterfaceMethods".
78static std::vector<const Record *>
79getAllInterfaceDefinitions(const RecordKeeper &records, StringRef name) {
80 std::vector<const Record *> defs =
81 records.getAllDerivedDefinitions(ClassName: (name + "Interface").str());
82
83 std::string declareName = ("Declare" + name + "InterfaceMethods").str();
84 llvm::erase_if(C&: defs, P: [&](const Record *def) {
85 // Ignore any "declare methods" interfaces.
86 if (def->isSubClassOf(Name: declareName))
87 return true;
88 // Ignore interfaces defined outside of the top-level file.
89 return llvm::SrcMgr.FindBufferContainingLoc(Loc: def->getLoc()[0]) !=
90 llvm::SrcMgr.getMainFileID();
91 });
92 return defs;
93}
94
95namespace {
96/// This struct is the base generator used when processing tablegen interfaces.
97class InterfaceGenerator {
98public:
99 bool emitInterfaceDefs();
100 bool emitInterfaceDecls();
101 bool emitInterfaceDocs();
102
103protected:
104 InterfaceGenerator(std::vector<const Record *> &&defs, raw_ostream &os)
105 : defs(std::move(defs)), os(os) {}
106
107 void emitConceptDecl(const Interface &interface);
108 void emitModelDecl(const Interface &interface);
109 void emitModelMethodsDef(const Interface &interface);
110 void forwardDeclareInterface(const Interface &interface);
111 void emitInterfaceDecl(const Interface &interface);
112 void emitInterfaceTraitDecl(const Interface &interface);
113
114 /// The set of interface records to emit.
115 std::vector<const Record *> defs;
116 // The stream to emit to.
117 raw_ostream &os;
118 /// The C++ value type of the interface, e.g. Operation*.
119 StringRef valueType;
120 /// The C++ base interface type.
121 StringRef interfaceBaseType;
122 /// The header declaring the C++ base interface type.
123 StringRef interfaceBaseTypeInclude;
124 /// The name of the typename for the value template.
125 StringRef valueTemplate;
126 /// The name of the substituion variable for the value.
127 StringRef substVar;
128 /// The format context to use for methods.
129 tblgen::FmtContext nonStaticMethodFmt;
130 /// Refer to the raw operation in model methods shared by all concrete ops.
131 tblgen::FmtContext sharedOpMethodFmt;
132 tblgen::FmtContext traitMethodFmt;
133 tblgen::FmtContext extraDeclsFmt;
134};
135
136/// A specialized generator for attribute interfaces.
137struct AttrInterfaceGenerator : public InterfaceGenerator {
138 AttrInterfaceGenerator(const RecordKeeper &records, raw_ostream &os)
139 : InterfaceGenerator(getAllInterfaceDefinitions(records, name: "Attr"), os) {
140 valueType = "::mlir::Attribute";
141 interfaceBaseType = "AttributeInterface";
142 interfaceBaseTypeInclude = "mlir/IR/Attributes.h";
143 valueTemplate = "ConcreteAttr";
144 substVar = "_attr";
145 StringRef castCode = "(::llvm::cast<ConcreteAttr>(tablegen_opaque_val))";
146 nonStaticMethodFmt.addSubst(placeholder: substVar, subst: castCode).withSelf(subst: castCode);
147 traitMethodFmt.addSubst(placeholder: substVar,
148 subst: "(*static_cast<const ConcreteAttr *>(this))");
149 extraDeclsFmt.addSubst(placeholder: substVar, subst: "(*this)");
150 }
151};
152/// A specialized generator for operation interfaces.
153struct OpInterfaceGenerator : public InterfaceGenerator {
154 OpInterfaceGenerator(const RecordKeeper &records, raw_ostream &os)
155 : InterfaceGenerator(getAllInterfaceDefinitions(records, name: "Op"), os) {
156 valueType = "::mlir::Operation *";
157 interfaceBaseType = "OpInterface";
158 interfaceBaseTypeInclude = "mlir/IR/OpDefinition.h";
159 valueTemplate = "ConcreteOp";
160 substVar = "_op";
161 StringRef castCode = "(llvm::cast<ConcreteOp>(tablegen_opaque_val))";
162 nonStaticMethodFmt.addSubst(placeholder: "_this", subst: "impl")
163 .addSubst(placeholder: "_raw_op", subst: "tablegen_opaque_val")
164 .addSubst(placeholder: substVar, subst: castCode)
165 .withSelf(subst: castCode);
166 sharedOpMethodFmt.addSubst(placeholder: "_this", subst: "impl")
167 .addSubst(placeholder: "_raw_op", subst: "tablegen_opaque_val");
168 traitMethodFmt.addSubst(placeholder: substVar, subst: "(*static_cast<ConcreteOp *>(this))");
169 extraDeclsFmt.addSubst(placeholder: substVar, subst: "(*this)");
170 }
171};
172/// A specialized generator for type interfaces.
173struct TypeInterfaceGenerator : public InterfaceGenerator {
174 TypeInterfaceGenerator(const RecordKeeper &records, raw_ostream &os)
175 : InterfaceGenerator(getAllInterfaceDefinitions(records, name: "Type"), os) {
176 valueType = "::mlir::Type";
177 interfaceBaseType = "TypeInterface";
178 interfaceBaseTypeInclude = "mlir/IR/Types.h";
179 valueTemplate = "ConcreteType";
180 substVar = "_type";
181 StringRef castCode = "(::llvm::cast<ConcreteType>(tablegen_opaque_val))";
182 nonStaticMethodFmt.addSubst(placeholder: substVar, subst: castCode).withSelf(subst: castCode);
183 traitMethodFmt.addSubst(placeholder: substVar,
184 subst: "(*static_cast<const ConcreteType *>(this))");
185 extraDeclsFmt.addSubst(placeholder: substVar, subst: "(*this)");
186 }
187};
188} // namespace
189
190//===----------------------------------------------------------------------===//
191// GEN: Interface definitions
192//===----------------------------------------------------------------------===//
193
194static void emitInterfaceMethodDoc(const InterfaceMethod &method,
195 raw_ostream &os, StringRef prefix = "") {
196 if (std::optional<StringRef> description = method.getDescription())
197 tblgen::emitDescriptionComment(description: *description, os, prefix);
198}
199static void emitInterfaceDefMethods(StringRef interfaceQualName,
200 const Interface &interface,
201 StringRef valueType, const Twine &implValue,
202 raw_ostream &os, bool isOpInterface) {
203 for (auto &method : interface.getMethods()) {
204 emitInterfaceMethodDoc(method, os);
205 emitCPPType(type: method.getReturnType(), os);
206 os << interfaceQualName << "::";
207 emitMethodNameAndArgs(method, name: method.getName(), os, valueType,
208 /*addThisArg=*/false,
209 /*addConst=*/!isOpInterface);
210
211 // Forward to the method on the concrete operation type.
212 os << " {\n return " << implValue << "->" << method.getUniqueName()
213 << '(';
214 if (!method.isStatic()) {
215 os << implValue << ", ";
216 os << (isOpInterface ? "getOperation()" : "*this");
217 os << (method.arg_empty() ? "" : ", ");
218 }
219 llvm::interleaveComma(
220 c: method.getArguments(), os,
221 each_fn: [&](const InterfaceMethod::Argument &arg) { os << arg.name; });
222 os << ");\n }\n";
223 }
224}
225
226static void emitInterfaceDef(const Interface &interface, StringRef valueType,
227 raw_ostream &os) {
228 std::string interfaceQualNameStr = interface.getFullyQualifiedName();
229 StringRef interfaceQualName = interfaceQualNameStr;
230 interfaceQualName.consume_front(Prefix: "::");
231
232 // Insert the method definitions.
233 bool isOpInterface = isa<OpInterface>(Val: interface);
234 emitInterfaceDefMethods(interfaceQualName, interface, valueType, implValue: "getImpl()",
235 os, isOpInterface);
236
237 // Insert the method definitions for base classes.
238 for (auto &base : interface.getBaseInterfaces()) {
239 emitInterfaceDefMethods(interfaceQualName, interface: base, valueType,
240 implValue: "getImpl()->impl" + base.getName(), os,
241 isOpInterface);
242 }
243}
244
245bool InterfaceGenerator::emitInterfaceDefs() {
246 llvm::emitSourceFileHeader(Desc: "Interface Definitions", OS&: os);
247
248 for (const auto *def : defs)
249 emitInterfaceDef(interface: Interface(def), valueType, os);
250 return false;
251}
252
253//===----------------------------------------------------------------------===//
254// GEN: Interface declarations
255//===----------------------------------------------------------------------===//
256
257void InterfaceGenerator::emitConceptDecl(const Interface &interface) {
258 os << " struct Concept {\n";
259
260 // Insert each of the pure virtual concept methods.
261 os << " /// The methods defined by the interface.\n";
262 for (auto &method : interface.getMethods()) {
263 os << " ";
264 emitCPPType(type: method.getReturnType(), os);
265 os << "(*" << method.getUniqueName() << ")(";
266 if (!method.isStatic()) {
267 os << "const Concept *impl, ";
268 emitCPPType(type: valueType, os) << (method.arg_empty() ? "" : ", ");
269 }
270 llvm::interleaveComma(
271 c: method.getArguments(), os,
272 each_fn: [&](const InterfaceMethod::Argument &arg) { os << arg.type; });
273 os << ");\n";
274 }
275
276 // A shared body has no dependence on the concrete operation type.
277 for (auto &method : interface.getMethods()) {
278 if (!hasSharedOpBody(interface, method))
279 continue;
280 os << " static ";
281 emitCPPType(type: method.getReturnType(), os);
282 emitMethodNameAndArgs(method, name: ("shared_" + method.getUniqueName()).str(),
283 os, valueType, /*addThisArg=*/true,
284 /*addConst=*/false);
285 os << ";\n";
286 }
287
288 // Insert a field containing a concept for each of the base interfaces.
289 auto baseInterfaces = interface.getBaseInterfaces();
290 if (!baseInterfaces.empty()) {
291 os << " /// The base classes of this interface.\n";
292 for (const auto &base : interface.getBaseInterfaces()) {
293 os << " const " << base.getFullyQualifiedName() << "::Concept *impl"
294 << base.getName() << " = nullptr;\n";
295 }
296
297 // Define an "initialize" method that allows for the initialization of the
298 // base class concepts.
299 os << "\n void initializeInterfaceConcept(::mlir::detail::InterfaceMap "
300 "&interfaceMap) {\n";
301 std::string interfaceQualName = interface.getFullyQualifiedName();
302 for (const auto &base : interface.getBaseInterfaces()) {
303 StringRef baseName = base.getName();
304 std::string baseQualName = base.getFullyQualifiedName();
305 os << " impl" << baseName << " = interfaceMap.lookup<"
306 << baseQualName << ">();\n"
307 << " assert(impl" << baseName << " && \"`" << interfaceQualName
308 << "` expected its base interface `" << baseQualName
309 << "` to be registered\");\n";
310 }
311 os << " }\n";
312 }
313
314 os << " };\n";
315}
316
317void InterfaceGenerator::emitModelDecl(const Interface &interface) {
318 // Emit the basic model and the fallback model.
319 for (const char *modelClass : {"Model", "FallbackModel"}) {
320 os << " template<typename " << valueTemplate << ">\n";
321 os << " class " << modelClass << " : public Concept {\n public:\n";
322 os << " using Interface = " << interface.getFullyQualifiedName()
323 << ";\n";
324 if (StringRef(modelClass) == "Model")
325 os << " using GeneratedModel = Model;\n";
326 // The Concept's function-pointer members and these wrapper signatures are
327 // named by the unique name so that overloaded interface methods stay
328 // distinct here; only the forward target (the concrete model call) uses the
329 // shared source name. Do not collapse these to getName().
330 os << " ";
331 if (StringRef(modelClass) == "Model")
332 os << "constexpr ";
333 os << modelClass << "() : Concept{";
334 llvm::interleaveComma(
335 c: interface.getMethods(), os, each_fn: [&](const InterfaceMethod &method) {
336 if (StringRef(modelClass) == "Model" &&
337 hasSharedOpBody(interface, method))
338 os << "Concept::shared_" << method.getUniqueName();
339 else
340 os << method.getUniqueName();
341 });
342 os << "} {}\n\n";
343
344 // Insert each of the virtual method overrides.
345 for (auto &method : interface.getMethods()) {
346 if (StringRef(modelClass) == "Model" &&
347 hasSharedOpBody(interface, method))
348 continue;
349 emitCPPType(type: method.getReturnType(), os&: os << " static inline ");
350 emitMethodNameAndArgs(method, name: method.getUniqueName(), os, valueType,
351 /*addThisArg=*/!method.isStatic(),
352 /*addConst=*/false);
353 os << ";\n";
354 }
355 os << " };\n";
356 }
357
358 // Emit the template for the external model.
359 os << " template<typename ConcreteModel, typename " << valueTemplate
360 << ">\n";
361 os << " class ExternalModel : public FallbackModel<ConcreteModel> {\n";
362 os << " public:\n";
363 os << " using ConcreteEntity = " << valueTemplate << ";\n";
364
365 // Emit declarations for methods that have default implementations. Other
366 // methods are expected to be implemented by the concrete derived model.
367 for (auto &method : interface.getMethods()) {
368 if (!method.getDefaultImplementation())
369 continue;
370 os << " ";
371 if (method.isStatic())
372 os << "static ";
373 emitCPPType(type: method.getReturnType(), os);
374 // External models declare methods by their non-unique source names so that
375 // overloaded methods can be overridden by implementers.
376 os << method.getName() << "(";
377 if (!method.isStatic()) {
378 emitCPPType(type: valueType, os);
379 os << "tablegen_opaque_val";
380 if (!method.arg_empty())
381 os << ", ";
382 }
383 llvm::interleaveComma(c: method.getArguments(), os,
384 each_fn: [&](const InterfaceMethod::Argument &arg) {
385 emitCPPType(type: arg.type, os);
386 os << arg.name;
387 });
388 os << ")";
389 if (!method.isStatic())
390 os << " const";
391 os << ";\n";
392 }
393 os << " };\n";
394}
395
396void InterfaceGenerator::emitModelMethodsDef(const Interface &interface) {
397 llvm::NamespaceEmitter ns(os, interface.getCppNamespace());
398 for (auto &method : interface.getMethods()) {
399 if (hasSharedOpBody(interface, method)) {
400 StringRef body = *method.getBody();
401 os << "inline ";
402 emitCPPType(type: method.getReturnType(), os);
403 os << "detail::" << interface.getName() << "InterfaceTraits::Concept::";
404 emitMethodNameAndArgs(method, name: ("shared_" + method.getUniqueName()).str(),
405 os, valueType, /*addThisArg=*/true,
406 /*addConst=*/false);
407 os << " {\n " << tblgen::tgfmt(fmt: body.trim(), ctx: &sharedOpMethodFmt)
408 << "\n}\n";
409 continue;
410 }
411 os << "template<typename " << valueTemplate << ">\n";
412 emitCPPType(type: method.getReturnType(), os);
413 os << "detail::" << interface.getName() << "InterfaceTraits::Model<"
414 << valueTemplate << ">::";
415 emitMethodNameAndArgs(method, name: method.getUniqueName(), os, valueType,
416 /*addThisArg=*/!method.isStatic(),
417 /*addConst=*/false);
418 os << " {\n ";
419
420 // Check for a provided body to the function.
421 if (std::optional<StringRef> body = method.getBody()) {
422 if (method.isStatic())
423 os << body->trim();
424 else
425 os << tblgen::tgfmt(fmt: body->trim(), ctx: &nonStaticMethodFmt);
426 os << "\n}\n";
427 continue;
428 }
429
430 // Forward to the method on the concrete operation type.
431 if (method.isStatic())
432 os << "return " << valueTemplate << "::";
433 else
434 os << tblgen::tgfmt(fmt: "return $_self.", ctx: &nonStaticMethodFmt);
435
436 // Add the arguments to the call.
437 os << method.getName() << '(';
438 llvm::interleaveComma(
439 c: method.getArguments(), os,
440 each_fn: [&](const InterfaceMethod::Argument &arg) { os << arg.name; });
441 os << ");\n}\n";
442 }
443
444 for (auto &method : interface.getMethods()) {
445 os << "template<typename " << valueTemplate << ">\n";
446 emitCPPType(type: method.getReturnType(), os);
447 os << "detail::" << interface.getName() << "InterfaceTraits::FallbackModel<"
448 << valueTemplate << ">::";
449 emitMethodNameAndArgs(method, name: method.getUniqueName(), os, valueType,
450 /*addThisArg=*/!method.isStatic(),
451 /*addConst=*/false);
452 os << " {\n ";
453
454 // Forward to the method on the concrete Model implementation.
455 if (method.isStatic())
456 os << "return " << valueTemplate << "::";
457 else
458 os << "return static_cast<const " << valueTemplate << " *>(impl)->";
459
460 // Add the arguments to the call. Forward by the (possibly non-unique)
461 // method name so that overloaded interface methods resolve to the right
462 // concrete-model overload.
463 os << method.getName() << '(';
464 if (!method.isStatic())
465 os << "tablegen_opaque_val" << (method.arg_empty() ? "" : ", ");
466 llvm::interleaveComma(
467 c: method.getArguments(), os,
468 each_fn: [&](const InterfaceMethod::Argument &arg) { os << arg.name; });
469 os << ");\n}\n";
470 }
471
472 // Emit default implementations for the external model.
473 for (auto &method : interface.getMethods()) {
474 if (!method.getDefaultImplementation())
475 continue;
476 os << "template<typename ConcreteModel, typename " << valueTemplate
477 << ">\n";
478 emitCPPType(type: method.getReturnType(), os);
479 os << "detail::" << interface.getName()
480 << "InterfaceTraits::ExternalModel<ConcreteModel, " << valueTemplate
481 << ">::";
482 // External models expose (possibly overloaded) methods by their original
483 // source names, hiding the internal name mangling from implementers.
484 os << method.getName() << "(";
485 if (!method.isStatic()) {
486 emitCPPType(type: valueType, os);
487 os << "tablegen_opaque_val";
488 if (!method.arg_empty())
489 os << ", ";
490 }
491 llvm::interleaveComma(c: method.getArguments(), os,
492 each_fn: [&](const InterfaceMethod::Argument &arg) {
493 emitCPPType(type: arg.type, os);
494 os << arg.name;
495 });
496 os << ")";
497 if (!method.isStatic())
498 os << " const";
499
500 os << " {\n";
501
502 // Use the empty context for static methods.
503 tblgen::FmtContext ctx;
504 os << tblgen::tgfmt(fmt: method.getDefaultImplementation()->trim(),
505 ctx: method.isStatic() ? &ctx : &nonStaticMethodFmt);
506 os << "\n}\n";
507 }
508}
509
510void InterfaceGenerator::emitInterfaceTraitDecl(const Interface &interface) {
511 auto cppNamespace = (interface.getCppNamespace() + "::detail").str();
512 llvm::NamespaceEmitter ns(os, cppNamespace);
513
514 StringRef interfaceName = interface.getName();
515 auto interfaceTraitsName = (interfaceName + "InterfaceTraits").str();
516 os << llvm::formatv(Fmt: " template <typename {3}>\n"
517 " struct {0}Trait : public ::mlir::{2}<{0},"
518 " detail::{1}>::Trait<{3}> {{\n",
519 Vals&: interfaceName, Vals&: interfaceTraitsName, Vals&: interfaceBaseType,
520 Vals&: valueTemplate);
521
522 // Insert the default implementation for any methods.
523 bool isOpInterface = isa<OpInterface>(Val: interface);
524 for (auto &method : interface.getMethods()) {
525 // Flag interface methods named verifyTrait.
526 if (method.getName() == "verifyTrait")
527 PrintFatalError(
528 Msg: formatv(Fmt: "'verifyTrait' method cannot be specified as interface "
529 "method for '{0}'; use the 'verify' field instead",
530 Vals&: interfaceName));
531 auto defaultImpl = method.getDefaultImplementation();
532 if (!defaultImpl)
533 continue;
534
535 emitInterfaceMethodDoc(method, os, prefix: " ");
536 os << " " << (method.isStatic() ? "static " : "");
537 emitCPPType(type: method.getReturnType(), os);
538 emitMethodNameAndArgs(method, name: method.getName(), os, valueType,
539 /*addThisArg=*/false,
540 /*addConst=*/!isOpInterface && !method.isStatic());
541 os << " {\n " << tblgen::tgfmt(fmt: defaultImpl->trim(), ctx: &traitMethodFmt)
542 << "\n }\n";
543 }
544
545 if (auto verify = interface.getVerify()) {
546 assert(isa<OpInterface>(interface) && "only OpInterface supports 'verify'");
547
548 tblgen::FmtContext verifyCtx;
549 verifyCtx.addSubst(placeholder: "_op", subst: "op");
550 os << llvm::formatv(
551 Fmt: " static ::llvm::LogicalResult {0}(::mlir::Operation *op) ",
552 Vals: (interface.verifyWithRegions() ? "verifyRegionTrait"
553 : "verifyTrait"))
554 << "{\n " << tblgen::tgfmt(fmt: verify->trim(), ctx: &verifyCtx)
555 << "\n }\n";
556 }
557 if (auto extraTraitDecls = interface.getExtraTraitClassDeclaration())
558 os << tblgen::tgfmt(fmt: *extraTraitDecls, ctx: &traitMethodFmt) << "\n";
559 if (auto extraTraitDecls = interface.getExtraSharedClassDeclaration())
560 os << tblgen::tgfmt(fmt: *extraTraitDecls, ctx: &traitMethodFmt) << "\n";
561
562 os << " };\n";
563}
564
565static void emitInterfaceDeclMethods(const Interface &interface,
566 raw_ostream &os, StringRef valueType,
567 bool isOpInterface,
568 tblgen::FmtContext &extraDeclsFmt) {
569 for (auto &method : interface.getMethods()) {
570 emitInterfaceMethodDoc(method, os, prefix: " ");
571 emitCPPType(type: method.getReturnType(), os&: os << " ");
572 emitMethodNameAndArgs(method, name: method.getName(), os, valueType,
573 /*addThisArg=*/false,
574 /*addConst=*/!isOpInterface);
575 os << ";\n";
576 }
577
578 // Emit any extra declarations.
579 if (std::optional<StringRef> extraDecls =
580 interface.getExtraClassDeclaration())
581 os << extraDecls->rtrim() << "\n";
582 if (std::optional<StringRef> extraDecls =
583 interface.getExtraSharedClassDeclaration())
584 os << tblgen::tgfmt(fmt: extraDecls->rtrim(), ctx: &extraDeclsFmt) << "\n";
585}
586
587void InterfaceGenerator::forwardDeclareInterface(const Interface &interface) {
588 llvm::NamespaceEmitter ns(os, interface.getCppNamespace());
589
590 // Emit a forward declaration of the interface class so that it becomes usable
591 // in the signature of its methods.
592 tblgen::emitSummaryAndDescComments(os, summary: "",
593 description: interface.getDescription().value_or(u: ""));
594
595 StringRef interfaceName = interface.getName();
596 os << "class " << interfaceName << ";\n";
597}
598
599void InterfaceGenerator::emitInterfaceDecl(const Interface &interface) {
600 llvm::NamespaceEmitter ns(os, interface.getCppNamespace());
601
602 StringRef interfaceName = interface.getName();
603 auto interfaceTraitsName = (interfaceName + "InterfaceTraits").str();
604
605 // Emit a forward declaration of the interface class so that it becomes usable
606 // in the signature of its methods.
607 tblgen::emitSummaryAndDescComments(os, summary: "",
608 description: interface.getDescription().value_or(u: ""));
609
610 // Emit the traits struct containing the concept and model declarations.
611 os << "namespace detail {\n"
612 << "struct " << interfaceTraitsName << " {\n";
613 emitConceptDecl(interface);
614 emitModelDecl(interface);
615 os << "};\n";
616
617 // Emit the derived trait for the interface.
618 os << "template <typename " << valueTemplate << ">\n";
619 os << "struct " << interface.getName() << "Trait;\n";
620
621 os << "\n} // namespace detail\n";
622
623 // Emit the main interface class declaration.
624 os << llvm::formatv(Fmt: "class {0} : public ::mlir::{3}<{1}, detail::{2}> {\n"
625 "public:\n"
626 " using ::mlir::{3}<{1}, detail::{2}>::{3};\n",
627 Vals&: interfaceName, Vals&: interfaceName, Vals&: interfaceTraitsName,
628 Vals&: interfaceBaseType);
629
630 // Emit a utility wrapper trait class.
631 os << llvm::formatv(Fmt: " template <typename {1}>\n"
632 " struct Trait : public detail::{0}Trait<{1}> {{};\n",
633 Vals&: interfaceName, Vals&: valueTemplate);
634
635 // Insert the method declarations.
636 bool isOpInterface = isa<OpInterface>(Val: interface);
637 emitInterfaceDeclMethods(interface, os, valueType, isOpInterface,
638 extraDeclsFmt);
639
640 // Insert the method declarations for base classes.
641 for (auto &base : interface.getBaseInterfaces()) {
642 std::string baseQualName = base.getFullyQualifiedName();
643 os << " //"
644 "===---------------------------------------------------------------"
645 "-===//\n"
646 << " // Inherited from " << baseQualName << "\n"
647 << " //"
648 "===---------------------------------------------------------------"
649 "-===//\n\n";
650
651 // Allow implicit conversion to the base interface.
652 os << " operator " << baseQualName << " () const {\n"
653 << " if (!*this) return nullptr;\n"
654 << " return " << baseQualName << "(*this, getImpl()->impl"
655 << base.getName() << ");\n"
656 << " }\n\n";
657
658 // Inherit the base interface's methods.
659 emitInterfaceDeclMethods(interface: base, os, valueType, isOpInterface, extraDeclsFmt);
660 }
661
662 // Emit classof code if necessary.
663 if (std::optional<StringRef> extraClassOf = interface.getExtraClassOf()) {
664 auto extraClassOfFmt = tblgen::FmtContext();
665 extraClassOfFmt.addSubst(placeholder: substVar, subst: "odsInterfaceInstance");
666 os << " static bool classof(" << valueType << " base) {\n"
667 << " auto* interface = getInterfaceFor(base);\n"
668 << " if (!interface)\n"
669 " return false;\n"
670 " "
671 << interfaceName << " odsInterfaceInstance(base, interface);\n"
672 << " " << tblgen::tgfmt(fmt: extraClassOf->trim(), ctx: &extraClassOfFmt)
673 << "\n }\n";
674 }
675
676 os << "};\n";
677}
678
679bool InterfaceGenerator::emitInterfaceDecls() {
680 llvm::emitSourceFileHeader(Desc: "Interface Declarations", OS&: os);
681 // Sort according to ID, so defs are emitted in the order in which they appear
682 // in the Tablegen file.
683 std::vector<const Record *> sortedDefs(defs);
684 llvm::sort(C&: sortedDefs, Comp: [](const Record *lhs, const Record *rhs) {
685 return lhs->getID() < rhs->getID();
686 });
687 // Include the headers declaring the C++ base interface type and the base
688 // interfaces.
689 SmallVector<StringRef> includes;
690 if (!sortedDefs.empty())
691 includes.push_back(Elt: interfaceBaseTypeInclude);
692 for (const Record *def : sortedDefs) {
693 Interface interface(def);
694 for (const Interface &base : interface.getBaseInterfaces())
695 llvm::append_range(C&: includes, R: base.getCppIncludes());
696 }
697 tblgen::emitIncludes(os, headers: includes);
698
699 for (const Record *def : sortedDefs)
700 forwardDeclareInterface(interface: Interface(def));
701 for (const Record *def : sortedDefs)
702 emitInterfaceDecl(interface: Interface(def));
703 for (const Record *def : sortedDefs)
704 emitInterfaceTraitDecl(interface: Interface(def));
705 for (const Record *def : sortedDefs)
706 emitModelMethodsDef(interface: Interface(def));
707
708 return false;
709}
710
711//===----------------------------------------------------------------------===//
712// GEN: Interface documentation
713//===----------------------------------------------------------------------===//
714
715static void emitInterfaceDoc(const Record &interfaceDef, raw_ostream &os) {
716 Interface interface(&interfaceDef);
717
718 // Emit the interface name followed by the description.
719 os << "\n## " << interface.getName() << " (`" << interfaceDef.getName()
720 << "`)\n";
721 if (auto description = interface.getDescription())
722 mlir::tblgen::emitDescription(description: *description, os);
723
724 // Emit the methods required by the interface.
725 os << "\n### Methods:\n";
726 for (const auto &method : interface.getMethods()) {
727 // Emit the method name.
728 os << "\n#### `" << method.getName() << "`\n\n```c++\n";
729
730 // Emit the method signature.
731 if (method.isStatic())
732 os << "static ";
733 emitCPPType(type: method.getReturnType(), os) << method.getName() << '(';
734 llvm::interleaveComma(c: method.getArguments(), os,
735 each_fn: [&](const InterfaceMethod::Argument &arg) {
736 emitCPPType(type: arg.type, os) << arg.name;
737 });
738 os << ");\n```\n";
739
740 // Emit the description.
741 if (auto description = method.getDescription())
742 mlir::tblgen::emitDescription(description: *description, os);
743
744 // If the body is not provided, this method must be provided by the user.
745 if (!method.getBody())
746 os << "\nNOTE: This method *must* be implemented by the user.";
747
748 os << "\n";
749 }
750}
751
752bool InterfaceGenerator::emitInterfaceDocs() {
753 os << "<!-- Autogenerated by mlir-tblgen; don't manually edit -->\n";
754 os << "\n# " << interfaceBaseType << " definitions\n";
755
756 for (const auto *def : defs)
757 emitInterfaceDoc(interfaceDef: *def, os);
758 return false;
759}
760
761//===----------------------------------------------------------------------===//
762// GEN: Interface registration hooks
763//===----------------------------------------------------------------------===//
764
765namespace {
766template <typename GeneratorT>
767struct InterfaceGenRegistration {
768 InterfaceGenRegistration(StringRef genArg, StringRef genDesc)
769 : genDeclArg(("gen-" + genArg + "-interface-decls").str()),
770 genDefArg(("gen-" + genArg + "-interface-defs").str()),
771 genDocArg(("gen-" + genArg + "-interface-docs").str()),
772 genDeclDesc(("Generate " + genDesc + " interface declarations").str()),
773 genDefDesc(("Generate " + genDesc + " interface definitions").str()),
774 genDocDesc(("Generate " + genDesc + " interface documentation").str()),
775 genDecls(genDeclArg, genDeclDesc,
776 [](const RecordKeeper &records, raw_ostream &os) {
777 return GeneratorT(records, os).emitInterfaceDecls();
778 }),
779 genDefs(genDefArg, genDefDesc,
780 [](const RecordKeeper &records, raw_ostream &os) {
781 return GeneratorT(records, os).emitInterfaceDefs();
782 }),
783 genDocs(genDocArg, genDocDesc,
784 [](const RecordKeeper &records, raw_ostream &os) {
785 return GeneratorT(records, os).emitInterfaceDocs();
786 }) {}
787
788 std::string genDeclArg, genDefArg, genDocArg;
789 std::string genDeclDesc, genDefDesc, genDocDesc;
790 mlir::GenRegistration genDecls, genDefs, genDocs;
791};
792} // namespace
793
794static InterfaceGenRegistration<AttrInterfaceGenerator> attrGen("attr",
795 "attribute");
796static InterfaceGenRegistration<OpInterfaceGenerator> opGen("op", "op");
797static InterfaceGenRegistration<TypeInterfaceGenerator> typeGen("type", "type");
798