1//===- EnumsGen.cpp - MLIR enum 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// EnumsGen generates common utility functions for enums.
10//
11//===----------------------------------------------------------------------===//
12
13#include "CppGenUtilities.h"
14#include "FormatGen.h"
15#include "mlir/TableGen/Attribute.h"
16#include "mlir/TableGen/EnumInfo.h"
17#include "mlir/TableGen/Format.h"
18#include "mlir/TableGen/GenInfo.h"
19#include "llvm/ADT/BitVector.h"
20#include "llvm/ADT/SmallVector.h"
21#include "llvm/ADT/StringExtras.h"
22#include "llvm/Support/FormatVariadic.h"
23#include "llvm/Support/raw_ostream.h"
24#include "llvm/TableGen/CodeGenHelpers.h"
25#include "llvm/TableGen/Error.h"
26#include "llvm/TableGen/Record.h"
27#include "llvm/TableGen/TableGenBackend.h"
28
29using llvm::formatv;
30using llvm::isDigit;
31using llvm::PrintFatalError;
32using llvm::Record;
33using llvm::RecordKeeper;
34using namespace mlir;
35using mlir::tblgen::Attribute;
36using mlir::tblgen::EnumCase;
37using mlir::tblgen::EnumInfo;
38using mlir::tblgen::FmtContext;
39using mlir::tblgen::tgfmt;
40
41static std::string makeIdentifier(StringRef str) {
42 if (!str.empty() && isDigit(C: static_cast<unsigned char>(str.front()))) {
43 std::string newStr = std::string("_") + str.str();
44 return newStr;
45 }
46 return str.str();
47}
48
49static void emitEnumClass(const Record &enumDef, StringRef enumName,
50 StringRef underlyingType, StringRef description,
51 ArrayRef<EnumCase> enumerants, raw_ostream &os) {
52 os << "// " << description << "\n";
53 os << "enum class " << enumName;
54
55 if (!underlyingType.empty())
56 os << " : " << underlyingType;
57 os << " {\n";
58
59 for (const EnumCase &enumerant : enumerants) {
60 auto symbol = makeIdentifier(str: enumerant.getSymbol());
61 auto value = enumerant.getValue();
62 if (value >= 0)
63 os << formatv(Fmt: " {0} = {1},\n", Vals&: symbol, Vals&: value);
64 else
65 os << formatv(Fmt: " {0},\n", Vals&: symbol);
66 }
67 os << "};\n\n";
68}
69
70/// Returns a bit vector with a bit set for every case that cannot be printed
71/// as a keyword.
72static BitVector getNonKeywordCases(ArrayRef<EnumCase> cases) {
73 BitVector nonKeywordCases(cases.size());
74 for (auto [index, enumerant] : llvm::enumerate(First&: cases))
75 if (!tblgen::canFormatStringAsKeyword(value: enumerant.getStr()))
76 nonKeywordCases.set(index);
77 return nonKeywordCases;
78}
79
80/// Emits the declarations of the 'FieldParser' specializations of the enum.
81/// The definitions are emitted by 'emitFieldParserDefs' into the enum
82/// definitions file instead of inline in the header. The bodies would otherwise
83/// be type-checked and require instantiating the 'FailureOr' and
84/// 'std::optional' types in every translation unit including the header,
85/// despite rarely being used. The forward declarations of 'AsmParser' and
86/// 'FieldParser' are emitted once per file by 'emitEnumDecls'.
87static void emitFieldParserDecls(const EnumInfo &enumInfo, StringRef qualName,
88 raw_ostream &os) {
89 const char *const fieldParserDecls = R"(
90namespace mlir {
91template<>
92struct FieldParser<{0}, {0}> {{{1}
93 static FailureOr<{0}> parse(AsmParser &parser);
94};
95
96/// Support for std::optional, useful in attribute/type definition where the enum is
97/// used as:
98///
99/// let parameters = (ins OptionalParameter<"std::optional<TheEnumName>">:$value);
100template<>
101struct FieldParser<std::optional<{0}>, std::optional<{0}>> {{
102 static constexpr bool isKeyValueCompositional = false;
103
104 static FailureOr<std::optional<{0}>> parse(AsmParser &parser);
105};
106} // namespace mlir
107)";
108
109 std::string isKeyValueCompositional;
110 if (enumInfo.isNewStyleBitEnum()) {
111 isKeyValueCompositional =
112 formatv(Fmt: "\n static constexpr bool isKeyValueCompositional = {0};\n",
113 Vals: enumInfo.getBitEnumSeparatorKind() ==
114 EnumInfo::BitEnumSeparatorKind::Comma
115 ? "false"
116 : "true");
117 }
118 os << formatv(Fmt: fieldParserDecls, Vals&: qualName, Vals&: isKeyValueCompositional);
119}
120
121/// Emits the definitions of the 'FieldParser' specializations declared by
122/// 'emitFieldParserDecls'.
123static void emitFieldParserDefs(const EnumInfo &enumInfo, raw_ostream &os) {
124 std::string qualName = enumInfo.getQualifiedName();
125 StringRef cppNamespace = enumInfo.getCppNamespace();
126 auto cases = enumInfo.getAllCases();
127 BitVector nonKeywordCases = getNonKeywordCases(cases);
128
129 std::string casesList;
130 llvm::raw_string_ostream caseListOs(casesList);
131 caseListOs << "[";
132 llvm::interleaveComma(c: llvm::enumerate(First&: cases), os&: caseListOs,
133 each_fn: [&](auto enumerant) {
134 StringRef name = enumerant.value().getStr();
135 if (nonKeywordCases.test(enumerant.index()))
136 caseListOs << "\\\"" << name << "\\\"";
137 caseListOs << name;
138 });
139 caseListOs << "]";
140 std::string casesInitList;
141 llvm::raw_string_ostream casesInitListOs(casesInitList);
142 casesInitListOs << "{";
143 llvm::interleaveComma(c: llvm::enumerate(First&: cases), os&: casesInitListOs,
144 each_fn: [&](auto enumerant) {
145 StringRef name = enumerant.value().getStr();
146 casesInitListOs << "\"" << name << "\"";
147 });
148 casesInitListOs << "}";
149
150 // Generate the parser for the enum, excluding non-quoted bit enums.
151 const char *const fieldParserDefs = R"(
152namespace mlir {
153FailureOr<{0}> FieldParser<{0}, {0}>::parse(AsmParser &parser) {{
154 // Parse the keyword/string containing the enum.
155 std::string enumKeyword;
156 auto loc = parser.getCurrentLocation();
157 if (failed(parser.parseOptionalKeywordOrString(&enumKeyword)))
158 return parser.emitError(loc, "expected keyword for {2}");
159
160 // Symbolize the keyword.
161 if (::std::optional<{0}> attr = {1}::symbolizeEnum<{0}>(enumKeyword))
162 return *attr;
163 return parser.emitError(loc, "expected one of {3} for {2}, got: ") << enumKeyword;
164}
165
166FailureOr<std::optional<{0}>>
167FieldParser<std::optional<{0}>, std::optional<{0}>>::parse(AsmParser &parser) {{
168 // Parse the keyword/string containing the enum.
169 std::string enumKeyword;
170 auto loc = parser.getCurrentLocation();
171 if (failed(parser.parseOptionalKeywordOrString(&enumKeyword, {4})))
172 return std::optional<{0}>{{};
173
174 // Symbolize the keyword.
175 if (::std::optional<{0}> attr = {1}::symbolizeEnum<{0}>(enumKeyword))
176 return attr;
177 return parser.emitError(loc, "expected one of {3} for {2}, got: ") << enumKeyword;
178}
179} // namespace mlir
180)";
181
182 const char *const fieldParserDefsUnquotedBitEnum = R"(
183namespace mlir {
184FailureOr<{0}> FieldParser<{0}, {0}>::parse(AsmParser &parser) {{
185 {0} flags = {{};
186 do {{
187 // Parse the keyword containing a part of the enum.
188 ::llvm::StringRef enumKeyword;
189 auto loc = parser.getCurrentLocation();
190 if (failed(parser.parseOptionalKeyword(&enumKeyword))) {{
191 return parser.emitError(loc, "expected keyword for {2}");
192 }
193
194 // Symbolize the keyword.
195 if (::std::optional<{0}> flag = {1}::symbolizeEnum<{0}>(enumKeyword)) {{
196 flags = flags | *flag;
197 } else {{
198 return parser.emitError(loc, "expected one of {3} for {2}, got: ") << enumKeyword;
199 }
200 } while (::mlir::succeeded(parser.{5}()));
201 return flags;
202}
203
204FailureOr<std::optional<{0}>>
205FieldParser<std::optional<{0}>, std::optional<{0}>>::parse(AsmParser &parser) {{
206 {0} flags = {{};
207 bool firstIter = true;
208 do {{
209 // Parse the keyword containing a part of the enum.
210 ::llvm::StringRef enumKeyword;
211 auto loc = parser.getCurrentLocation();
212 if (failed(parser.parseOptionalKeyword(&enumKeyword, {6}))) {{
213 if (firstIter)
214 return std::optional<{0}>{{};
215 return parser.emitError(loc, "expected keyword for {2} after '{4}'");
216 }
217 firstIter = false;
218
219 // Symbolize the keyword.
220 if (::std::optional<{0}> flag = {1}::symbolizeEnum<{0}>(enumKeyword)) {{
221 flags = flags | *flag;
222 } else {{
223 return parser.emitError(loc, "expected one of {3} for {2}, got: ") << enumKeyword;
224 }
225 } while(::mlir::succeeded(parser.{5}()));
226 return std::optional<{0}>{{flags};
227}
228} // namespace mlir
229)";
230
231 // With a space separator, the flags are a run of case keywords that
232 // ends at the first token that is not one.
233 const char *const fieldParserDefsSpaceBitEnum = R"(
234namespace mlir {
235FailureOr<{0}> FieldParser<{0}, {0}>::parse(AsmParser &parser) {{
236 auto loc = parser.getCurrentLocation();
237 FailureOr<std::optional<{0}>> flags =
238 FieldParser<std::optional<{0}>>::parse(parser);
239 if (failed(flags))
240 return failure();
241 if (!*flags)
242 return parser.emitError(loc, "expected one of {3} for {2}");
243 return **flags;
244}
245
246FailureOr<std::optional<{0}>>
247FieldParser<std::optional<{0}>, std::optional<{0}>>::parse(AsmParser &parser) {{
248 std::optional<{0}> flags;
249 ::llvm::StringRef enumKeyword;
250 while (::mlir::succeeded(parser.parseOptionalKeyword(&enumKeyword, {4})))
251 flags = flags.value_or({0}{{}) | *{1}::symbolizeEnum<{0}>(enumKeyword);
252 return flags;
253}
254} // namespace mlir
255)";
256
257 if (enumInfo.isNewStyleBitEnum()) {
258 if (enumInfo.getBitEnumSeparatorKind() ==
259 EnumInfo::BitEnumSeparatorKind::Space) {
260 os << formatv(Fmt: fieldParserDefsSpaceBitEnum, Vals&: qualName, Vals&: cppNamespace,
261 Vals: enumInfo.getSummary(), Vals&: casesList, Vals&: casesInitList);
262 return;
263 }
264 StringRef parseSeparatorFn = enumInfo.getBitEnumSeparatorParser();
265 os << formatv(Fmt: fieldParserDefsUnquotedBitEnum, Vals&: qualName, Vals&: cppNamespace,
266 Vals: enumInfo.getSummary(), Vals&: casesList,
267 Vals: enumInfo.getBitEnumSeparator(), Vals&: parseSeparatorFn,
268 Vals&: casesInitList);
269 } else {
270 os << formatv(Fmt: fieldParserDefs, Vals&: qualName, Vals&: cppNamespace,
271 Vals: enumInfo.getSummary(), Vals&: casesList, Vals&: casesInitList);
272 }
273}
274
275static void emitParserPrinter(const EnumInfo &enumInfo, StringRef qualName,
276 raw_ostream &os,
277 SmallVectorImpl<StringRef> &includes) {
278 if (!enumInfo.hasParserPrinter())
279 return;
280
281 auto cases = enumInfo.getAllCases();
282 llvm::BitVector nonKeywordCases = getNonKeywordCases(cases);
283
284 if (enumInfo.isNewStyleBitEnum() && nonKeywordCases.any())
285 return PrintFatalError(
286 Msg: "bit enum " + qualName +
287 " cannot be printed unquoted with cases that cannot be keywords");
288
289 emitFieldParserDecls(enumInfo, qualName, os);
290 // `::llvm::raw_ostream`, used by the printer.
291 includes.push_back(Elt: "llvm/Support/raw_ostream.h");
292 // `::mlir::FailureOr`, used by the `FieldParser` specializations.
293 includes.push_back(Elt: "mlir/Support/LLVM.h");
294
295 // Generate the start of the printer for the enum.
296 const char *const printerStart = R"(
297namespace llvm {
298inline ::llvm::raw_ostream &operator<<(::llvm::raw_ostream &p, {0} value) {{
299 auto valueStr = stringifyEnum(value);
300)";
301 os << formatv(Fmt: printerStart, Vals&: qualName);
302
303 // If all cases require a string, always wrap.
304 if (nonKeywordCases.all()) {
305 os << " return p << '\"' << valueStr << '\"';\n"
306 "}\n"
307 "} // namespace llvm\n";
308 return;
309 }
310
311 // If there are any cases that can't be used with a keyword, switch on the
312 // case value to determine when to print in the string form.
313 if (nonKeywordCases.any()) {
314 os << " switch (value) {\n";
315 for (auto it : llvm::enumerate(First&: cases)) {
316 if (nonKeywordCases.test(Idx: it.index()))
317 continue;
318 StringRef symbol = it.value().getSymbol();
319 os << llvm::formatv(Fmt: " case {0}::{1}:\n", Vals&: qualName,
320 Vals: makeIdentifier(str: symbol));
321 }
322 os << " break;\n"
323 " default:\n"
324 " return p << '\"' << valueStr << '\"';\n"
325 " }\n";
326
327 // If this is a bit enum, conservatively print the string form if the value
328 // is not a power of two (i.e. not a single bit case) and not a known case.
329 // Only do this if we're using the old-style parser that parses the enum as
330 // one keyword, as opposed to the new form, where we can print the value
331 // as-is.
332 } else if (enumInfo.isBitEnum() && !enumInfo.isNewStyleBitEnum()) {
333 // Process the known multi-bit cases that use valid keywords.
334 SmallVector<EnumCase *> validMultiBitCases;
335 for (auto [index, caseVal] : llvm::enumerate(First&: cases)) {
336 uint64_t value = caseVal.getValue();
337 if (value && !llvm::has_single_bit(Value: value) && !nonKeywordCases.test(Idx: index))
338 validMultiBitCases.push_back(Elt: &caseVal);
339 }
340 if (!validMultiBitCases.empty()) {
341 os << " switch (value) {\n";
342 for (EnumCase *caseVal : validMultiBitCases) {
343 StringRef symbol = caseVal->getSymbol();
344 os << llvm::formatv(Fmt: " case {0}::{1}:\n", Vals&: qualName,
345 Vals: llvm::isDigit(C: symbol.front()) ? ("_" + symbol)
346 : symbol);
347 }
348 os << " return p << valueStr;\n"
349 " default:\n"
350 " break;\n"
351 " }\n";
352 }
353
354 // All other multi-bit cases should be printed as strings.
355 os << formatv(Fmt: " auto underlyingValue = "
356 "static_cast<std::make_unsigned_t<{0}>>(value);\n",
357 Vals&: qualName);
358 os << " if (underlyingValue && !llvm::has_single_bit(underlyingValue))\n"
359 " return p << '\"' << valueStr << '\"';\n";
360 // `::llvm::has_single_bit`.
361 includes.push_back(Elt: "llvm/ADT/bit.h");
362 }
363 os << " return p << valueStr;\n"
364 "}\n"
365 "} // namespace llvm\n";
366}
367
368static void emitDenseMapInfo(StringRef qualName, std::string underlyingType,
369 StringRef cppNamespace, raw_ostream &os) {
370 if (underlyingType.empty())
371 underlyingType =
372 std::string(formatv(Fmt: "std::underlying_type_t<{0}>", Vals&: qualName));
373
374 const char *const mapInfo = R"(
375namespace llvm {
376template<> struct DenseMapInfo<{0}> {{
377 using StorageInfo = ::llvm::DenseMapInfo<{1}>;
378
379 static unsigned getHashValue(const {0} &val) {{
380 return StorageInfo::getHashValue(static_cast<{1}>(val));
381 }
382
383 static bool isEqual(const {0} &lhs, const {0} &rhs) {{
384 return lhs == rhs;
385 }
386};
387})";
388 os << formatv(Fmt: mapInfo, Vals&: qualName, Vals&: underlyingType);
389 os << "\n\n";
390}
391
392static void emitMaxValueFn(const Record &enumDef, raw_ostream &os) {
393 EnumInfo enumInfo(enumDef);
394 StringRef maxEnumValFnName = enumInfo.getMaxEnumValFnName();
395 auto enumerants = enumInfo.getAllCases();
396
397 unsigned maxEnumVal = 0;
398 for (const auto &enumerant : enumerants) {
399 int64_t value = enumerant.getValue();
400 // Avoid generating the max value function if there is an enumerant without
401 // explicit value.
402 if (value < 0)
403 return;
404
405 maxEnumVal = std::max(a: maxEnumVal, b: static_cast<unsigned>(value));
406 }
407
408 // Emit the function to return the max enum value
409 os << formatv(Fmt: "inline constexpr unsigned {0}() {{\n", Vals&: maxEnumValFnName);
410 os << formatv(Fmt: " return {0};\n", Vals&: maxEnumVal);
411 os << "}\n\n";
412}
413
414// Returns the EnumCase whose value is zero if exists; returns std::nullopt
415// otherwise.
416static std::optional<EnumCase>
417getAllBitsUnsetCase(llvm::ArrayRef<EnumCase> cases) {
418 for (auto attrCase : cases) {
419 if (attrCase.getValue() == 0)
420 return attrCase;
421 }
422 return std::nullopt;
423}
424
425// Emits the following inline function for bit enums:
426//
427// inline constexpr <enum-type> operator|(<enum-type> a, <enum-type> b);
428// inline constexpr <enum-type> operator&(<enum-type> a, <enum-type> b);
429// inline constexpr <enum-type> operator^(<enum-type> a, <enum-type> b);
430// inline constexpr <enum-type> &operator|=(<enum-type> &a, <enum-type> b);
431// inline constexpr <enum-type> &operator&=(<enum-type> &a, <enum-type> b);
432// inline constexpr <enum-type> &operator^=(<enum-type> &a, <enum-type> b);
433// inline constexpr <enum-type> operator~(<enum-type> bits);
434// inline constexpr bool bitEnumContainsAll(<enum-type> bits, <enum-type> bit);
435// inline constexpr bool bitEnumContainsAny(<enum-type> bits, <enum-type> bit);
436// inline constexpr <enum-type> bitEnumClear(<enum-type> bits, <enum-type> bit);
437// inline constexpr <enum-type> bitEnumSet(<enum-type> bits, <enum-type> bit,
438// bool value=true);
439static void emitOperators(const Record &enumDef, raw_ostream &os) {
440 EnumInfo enumInfo(enumDef);
441 StringRef enumName = enumInfo.getEnumClassName();
442 std::string underlyingType = std::string(enumInfo.getUnderlyingType());
443 int64_t validBits = enumDef.getValueAsInt(FieldName: "validBits");
444 const char *const operators = R"(
445inline constexpr {0} operator|({0} a, {0} b) {{
446 return static_cast<{0}>(static_cast<{1}>(a) | static_cast<{1}>(b));
447}
448inline constexpr {0} operator&({0} a, {0} b) {{
449 return static_cast<{0}>(static_cast<{1}>(a) & static_cast<{1}>(b));
450}
451inline constexpr {0} operator^({0} a, {0} b) {{
452 return static_cast<{0}>(static_cast<{1}>(a) ^ static_cast<{1}>(b));
453}
454inline constexpr {0} &operator|=({0} &a, {0} b) {{
455 return a = a | b;
456}
457inline constexpr {0} &operator&=({0} &a, {0} b) {{
458 return a = a & b;
459}
460inline constexpr {0} &operator^=({0} &a, {0} b) {{
461 return a = a ^ b;
462}
463inline constexpr {0} operator~({0} bits) {{
464 // Ensure only bits that can be present in the enum are set
465 return static_cast<{0}>(~static_cast<{1}>(bits) & static_cast<{1}>({2}u));
466}
467inline constexpr bool bitEnumContainsAll({0} bits, {0} bit) {{
468 return (bits & bit) == bit;
469}
470inline constexpr bool bitEnumContainsAny({0} bits, {0} bit) {{
471 return (static_cast<{1}>(bits) & static_cast<{1}>(bit)) != 0;
472}
473inline constexpr {0} bitEnumClear({0} bits, {0} bit) {{
474 return bits & ~bit;
475}
476inline constexpr {0} bitEnumSet({0} bits, {0} bit, /*optional*/bool value=true) {{
477 return value ? (bits | bit) : bitEnumClear(bits, bit);
478}
479 )";
480 os << formatv(Fmt: operators, Vals&: enumName, Vals&: underlyingType, Vals&: validBits);
481}
482
483static void emitSymToStrFnForIntEnum(const Record &enumDef, raw_ostream &os) {
484 EnumInfo enumInfo(enumDef);
485 StringRef enumName = enumInfo.getEnumClassName();
486 StringRef symToStrFnName = enumInfo.getSymbolToStringFnName();
487 StringRef symToStrFnRetType = enumInfo.getSymbolToStringFnRetType();
488 auto enumerants = enumInfo.getAllCases();
489
490 os << formatv(Fmt: "{2} {1}({0} val) {{\n", Vals&: enumName, Vals&: symToStrFnName,
491 Vals&: symToStrFnRetType);
492 os << " switch (val) {\n";
493 for (const auto &enumerant : enumerants) {
494 auto symbol = enumerant.getSymbol();
495 auto str = enumerant.getStr();
496 os << formatv(Fmt: " case {0}::{1}: return \"{2}\";\n", Vals&: enumName,
497 Vals: makeIdentifier(str: symbol), Vals&: str);
498 }
499 os << " }\n";
500 os << " return \"\";\n";
501 os << "}\n\n";
502}
503
504static void emitSymToStrFnForBitEnum(const Record &enumDef, raw_ostream &os) {
505 EnumInfo enumInfo(enumDef);
506 StringRef enumName = enumInfo.getEnumClassName();
507 StringRef symToStrFnName = enumInfo.getSymbolToStringFnName();
508 StringRef symToStrFnRetType = enumInfo.getSymbolToStringFnRetType();
509 StringRef separator = enumInfo.getBitEnumSeparator();
510 auto enumerants = enumInfo.getAllCases();
511 auto allBitsUnsetCase = getAllBitsUnsetCase(cases: enumerants);
512
513 os << formatv(Fmt: "{2} {1}({0} symbol) {{\n", Vals&: enumName, Vals&: symToStrFnName,
514 Vals&: symToStrFnRetType);
515
516 os << formatv(Fmt: " auto val = static_cast<{0}>(symbol);\n",
517 Vals: enumInfo.getUnderlyingType());
518 // If we have unknown bit set, return an empty string to signal errors.
519 int64_t validBits = enumDef.getValueAsInt(FieldName: "validBits");
520 os << formatv(Fmt: " assert({0}u == ({0}u | val) && \"invalid bits set in bit "
521 "enum\");\n",
522 Vals&: validBits);
523 if (allBitsUnsetCase) {
524 os << " // Special case for all bits unset.\n";
525 os << formatv(Fmt: " if (val == 0) return \"{0}\";\n\n",
526 Vals: allBitsUnsetCase->getStr());
527 }
528 os << " ::llvm::SmallVector<::llvm::StringRef, 2> strs;\n";
529
530 // Add case string if the value has all case bits, and remove them to avoid
531 // printing again. Used only for groups, when printBitEnumPrimaryGroups is 1.
532 const char *const formatCompareRemove = R"(
533 if ({0}u == ({0}u & val)) {{
534 strs.push_back("{1}");
535 val &= ~static_cast<{2}>({0});
536 }
537)";
538 // Add case string if the value has all case bits. Used for individual bit
539 // cases, and for groups when printBitEnumPrimaryGroups is 0.
540 const char *const formatCompare = R"(
541 if ({0}u == ({0}u & val))
542 strs.push_back("{1}");
543)";
544 // Optionally elide bits that are members of groups that will also be printed
545 // for more concise output.
546 if (enumInfo.printBitEnumPrimaryGroups()) {
547 os << " // Print bit enum groups before individual bits\n";
548 // Emit comparisons for group bit cases in reverse tablegen declaration
549 // order, removing bits for groups with all bits present.
550 for (const auto &enumerant : llvm::reverse(C&: enumerants)) {
551 if ((enumerant.getValue() != 0) &&
552 (enumerant.getDef().isSubClassOf(Name: "BitEnumCaseGroup") ||
553 enumerant.getDef().isSubClassOf(Name: "BitEnumAttrCaseGroup"))) {
554 os << formatv(Fmt: formatCompareRemove, Vals: enumerant.getValue(),
555 Vals: enumerant.getStr(), Vals: enumInfo.getUnderlyingType());
556 }
557 }
558 // Emit comparisons for individual bit cases in tablegen declaration order.
559 for (const auto &enumerant : enumerants) {
560 if ((enumerant.getValue() != 0) &&
561 (enumerant.getDef().isSubClassOf(Name: "BitEnumCaseBit") ||
562 enumerant.getDef().isSubClassOf(Name: "BitEnumAttrCaseBit")))
563 os << formatv(Fmt: formatCompare, Vals: enumerant.getValue(), Vals: enumerant.getStr());
564 }
565 } else {
566 // Emit comparisons for ALL nonzero cases (individual bits and groups) in
567 // tablegen declaration order.
568 for (const auto &enumerant : enumerants) {
569 if (enumerant.getValue() != 0)
570 os << formatv(Fmt: formatCompare, Vals: enumerant.getValue(), Vals: enumerant.getStr());
571 }
572 }
573 os << formatv(Fmt: " return ::llvm::join(strs, \"{0}\");\n", Vals&: separator);
574
575 os << "}\n\n";
576}
577
578static void emitStrToSymFnForIntEnum(const Record &enumDef, raw_ostream &os) {
579 EnumInfo enumInfo(enumDef);
580 StringRef enumName = enumInfo.getEnumClassName();
581 StringRef strToSymFnName = enumInfo.getStringToSymbolFnName();
582 auto enumerants = enumInfo.getAllCases();
583
584 os << formatv(Fmt: "::std::optional<{0}> {1}(::llvm::StringRef str) {{\n",
585 Vals&: enumName, Vals&: strToSymFnName);
586 os << formatv(Fmt: " return ::llvm::StringSwitch<::std::optional<{0}>>(str)\n",
587 Vals&: enumName);
588 for (const auto &enumerant : enumerants) {
589 auto symbol = enumerant.getSymbol();
590 auto str = enumerant.getStr();
591 os << formatv(Fmt: " .Case(\"{1}\", {0}::{2})\n", Vals&: enumName, Vals&: str,
592 Vals: makeIdentifier(str: symbol));
593 }
594 os << " .Default(::std::nullopt);\n";
595 os << "}\n";
596}
597
598static void emitStrToSymFnForBitEnum(const Record &enumDef, raw_ostream &os) {
599 EnumInfo enumInfo(enumDef);
600 StringRef enumName = enumInfo.getEnumClassName();
601 std::string underlyingType = std::string(enumInfo.getUnderlyingType());
602 StringRef strToSymFnName = enumInfo.getStringToSymbolFnName();
603 StringRef separatorTrimmed = enumInfo.getBitEnumSeparator().trim();
604 auto enumerants = enumInfo.getAllCases();
605 auto allBitsUnsetCase = getAllBitsUnsetCase(cases: enumerants);
606
607 os << formatv(Fmt: "::std::optional<{0}> {1}(::llvm::StringRef str) {{\n",
608 Vals&: enumName, Vals&: strToSymFnName);
609
610 if (allBitsUnsetCase) {
611 os << " // Special case for all bits unset.\n";
612 StringRef caseSymbol = allBitsUnsetCase->getSymbol();
613 os << formatv(Fmt: " if (str == \"{1}\") return {0}::{2};\n\n", Vals&: enumName,
614 Vals: allBitsUnsetCase->getStr(), Vals: makeIdentifier(str: caseSymbol));
615 }
616
617 // Split the string to get symbols for all the bits.
618 os << " ::llvm::SmallVector<::llvm::StringRef, 2> symbols;\n";
619 // Remove whitespace from the separator string when parsing. A space
620 // separator splits on spaces and drops the empty pieces.
621 if (enumInfo.getBitEnumSeparatorKind() ==
622 EnumInfo::BitEnumSeparatorKind::Space)
623 os << " str.split(symbols, ' ', /*MaxSplit=*/-1, "
624 "/*KeepEmpty=*/false);\n\n";
625 else
626 os << formatv(Fmt: " str.split(symbols, \"{0}\");\n\n", Vals&: separatorTrimmed);
627
628 os << formatv(Fmt: " {0} val = 0;\n", Vals&: underlyingType);
629 os << " for (auto symbol : symbols) {\n";
630
631 // Convert each symbol to the bit ordinal and set the corresponding bit.
632 os << formatv(Fmt: " auto bit = "
633 "llvm::StringSwitch<::std::optional<{0}>>(symbol.trim())\n",
634 Vals&: underlyingType);
635 for (const auto &enumerant : enumerants) {
636 // Skip the special enumerant for None.
637 if (auto val = enumerant.getValue())
638 os.indent(NumSpaces: 6) << formatv(Fmt: ".Case(\"{0}\", {1})\n", Vals: enumerant.getStr(), Vals&: val);
639 }
640 os.indent(NumSpaces: 6) << ".Default(::std::nullopt);\n";
641
642 os << " if (bit) { val |= *bit; } else { return ::std::nullopt; }\n";
643 os << " }\n";
644
645 os << formatv(Fmt: " return static_cast<{0}>(val);\n", Vals&: enumName);
646 os << "}\n\n";
647}
648
649static void emitUnderlyingToSymFnForIntEnum(const Record &enumDef,
650 raw_ostream &os) {
651 EnumInfo enumInfo(enumDef);
652 StringRef enumName = enumInfo.getEnumClassName();
653 std::string underlyingType = std::string(enumInfo.getUnderlyingType());
654 StringRef underlyingToSymFnName = enumInfo.getUnderlyingToSymbolFnName();
655 auto enumerants = enumInfo.getAllCases();
656
657 // Avoid generating the underlying value to symbol conversion function if
658 // there is an enumerant without explicit value.
659 if (llvm::any_of(Range&: enumerants,
660 P: [](EnumCase enumerant) { return enumerant.getValue() < 0; }))
661 return;
662
663 os << formatv(Fmt: "::std::optional<{0}> {1}({2} value) {{\n", Vals&: enumName,
664 Vals&: underlyingToSymFnName,
665 Vals: underlyingType.empty() ? std::string("unsigned")
666 : underlyingType)
667 << " switch (value) {\n";
668 for (const auto &enumerant : enumerants) {
669 auto symbol = enumerant.getSymbol();
670 auto value = enumerant.getValue();
671 os << formatv(Fmt: " case {0}: return {1}::{2};\n", Vals&: value, Vals&: enumName,
672 Vals: makeIdentifier(str: symbol));
673 }
674 os << " default: return ::std::nullopt;\n"
675 << " }\n"
676 << "}\n\n";
677}
678
679static void emitSpecializedAttrDef(const Record &enumDef, raw_ostream &os) {
680 EnumInfo enumInfo(enumDef);
681 StringRef enumName = enumInfo.getEnumClassName();
682 StringRef attrClassName = enumInfo.getSpecializedAttrClassName();
683 const Record *baseAttrDef = enumInfo.getBaseAttrClass();
684 Attribute baseAttr(baseAttrDef);
685
686 // Emit classof method
687
688 os << formatv(Fmt: "bool {0}::classof(::mlir::Attribute attr) {{\n",
689 Vals&: attrClassName);
690
691 mlir::tblgen::Pred baseAttrPred = baseAttr.getPredicate();
692 if (baseAttrPred.isNull())
693 PrintFatalError(Msg: "ERROR: baseAttrClass for EnumAttr has no Predicate\n");
694
695 std::string condition = baseAttrPred.getCondition();
696 FmtContext verifyCtx;
697 verifyCtx.withSelf(subst: "attr");
698 os << tgfmt(fmt: " return $0;\n", /*ctx=*/nullptr, vals: tgfmt(fmt: condition, ctx: &verifyCtx));
699
700 os << "}\n";
701
702 // Emit get method
703
704 os << formatv(Fmt: "{0} {0}::get(::mlir::MLIRContext *context, {1} val) {{\n",
705 Vals&: attrClassName, Vals&: enumName);
706
707 StringRef underlyingType = enumInfo.getUnderlyingType();
708
709 // Assuming that it is IntegerAttr constraint
710 int64_t bitwidth = 64;
711 if (baseAttrDef->getValue(Name: "valueType")) {
712 auto *valueTypeDef = baseAttrDef->getValueAsDef(FieldName: "valueType");
713 if (valueTypeDef->getValue(Name: "bitwidth"))
714 bitwidth = valueTypeDef->getValueAsInt(FieldName: "bitwidth");
715 }
716
717 os << formatv(Fmt: " ::mlir::IntegerType intType = "
718 "::mlir::IntegerType::get(context, {0});\n",
719 Vals&: bitwidth);
720 os << formatv(Fmt: " ::mlir::IntegerAttr baseAttr = "
721 "::mlir::IntegerAttr::get(intType, static_cast<{0}>(val));\n",
722 Vals&: underlyingType);
723 os << formatv(Fmt: " return ::llvm::cast<{0}>(baseAttr);\n", Vals&: attrClassName);
724
725 os << "}\n";
726
727 // Emit getValue method
728
729 os << formatv(Fmt: "{0} {1}::getValue() const {{\n", Vals&: enumName, Vals&: attrClassName);
730
731 os << formatv(
732 Fmt: " return "
733 "static_cast<{0}>(::mlir::IntegerAttr::getValue().getZExtValue());\n",
734 Vals&: enumName);
735
736 os << "}\n";
737}
738
739static void emitUnderlyingToSymFnForBitEnum(const Record &enumDef,
740 raw_ostream &os) {
741 EnumInfo enumInfo(enumDef);
742 StringRef enumName = enumInfo.getEnumClassName();
743 std::string underlyingType = std::string(enumInfo.getUnderlyingType());
744 StringRef underlyingToSymFnName = enumInfo.getUnderlyingToSymbolFnName();
745 auto enumerants = enumInfo.getAllCases();
746 auto allBitsUnsetCase = getAllBitsUnsetCase(cases: enumerants);
747
748 os << formatv(Fmt: "::std::optional<{0}> {1}({2} value) {{\n", Vals&: enumName,
749 Vals&: underlyingToSymFnName, Vals&: underlyingType);
750 if (allBitsUnsetCase) {
751 os << " // Special case for all bits unset.\n";
752 os << formatv(Fmt: " if (value == 0) return {0}::{1};\n\n", Vals&: enumName,
753 Vals: makeIdentifier(str: allBitsUnsetCase->getSymbol()));
754 }
755 int64_t validBits = enumDef.getValueAsInt(FieldName: "validBits");
756 os << formatv(Fmt: " if (value & ~static_cast<{0}>({1}u)) return std::nullopt;\n",
757 Vals&: underlyingType, Vals&: validBits);
758 os << formatv(Fmt: " return static_cast<{0}>(value);\n", Vals&: enumName);
759 os << "}\n";
760}
761
762static void emitEnumDecl(const Record &enumDef, raw_ostream &os,
763 SmallVectorImpl<StringRef> &includes) {
764 EnumInfo enumInfo(enumDef);
765 StringRef enumName = enumInfo.getEnumClassName();
766 StringRef cppNamespace = enumInfo.getCppNamespace();
767 std::string underlyingType = std::string(enumInfo.getUnderlyingType());
768 StringRef description = enumInfo.getSummary();
769 StringRef strToSymFnName = enumInfo.getStringToSymbolFnName();
770 StringRef symToStrFnName = enumInfo.getSymbolToStringFnName();
771 StringRef symToStrFnRetType = enumInfo.getSymbolToStringFnRetType();
772 StringRef underlyingToSymFnName = enumInfo.getUnderlyingToSymbolFnName();
773 auto enumerants = enumInfo.getAllCases();
774
775 {
776 llvm::NamespaceEmitter ns(os, cppNamespace);
777
778 // Emit the enum class definition
779 emitEnumClass(enumDef, enumName, underlyingType, description, enumerants,
780 os);
781
782 // Emit conversion function declarations
783 if (llvm::all_of(Range&: enumerants, P: [](EnumCase enumerant) {
784 return enumerant.getValue() >= 0;
785 })) {
786 os << formatv(
787 Fmt: "::std::optional<{0}> {1}({2});\n", Vals&: enumName, Vals&: underlyingToSymFnName,
788 Vals: underlyingType.empty() ? std::string("unsigned") : underlyingType);
789 }
790 os << formatv(Fmt: "{2} {1}({0});\n", Vals&: enumName, Vals&: symToStrFnName,
791 Vals&: symToStrFnRetType);
792 os << formatv(Fmt: "::std::optional<{0}> {1}(::llvm::StringRef);\n", Vals&: enumName,
793 Vals&: strToSymFnName);
794
795 if (enumInfo.isBitEnum()) {
796 emitOperators(enumDef, os);
797 } else {
798 emitMaxValueFn(enumDef, os);
799 }
800
801 // Generate a generic `stringifyEnum` function that forwards to the method
802 // specified by the user.
803 const char *const stringifyEnumStr = R"(
804inline {0} stringifyEnum({1} enumValue) {{
805 return {2}(enumValue);
806}
807)";
808 os << formatv(Fmt: stringifyEnumStr, Vals&: symToStrFnRetType, Vals&: enumName,
809 Vals&: symToStrFnName);
810
811 // Generate a generic `symbolizeEnum` function that forwards to the method
812 // specified by the user.
813 const char *const symbolizeEnumStr = R"(
814template <typename EnumType>
815::std::optional<EnumType> symbolizeEnum(::llvm::StringRef);
816
817template <>
818inline ::std::optional<{0}> symbolizeEnum<{0}>(::llvm::StringRef str) {
819 return {1}(str);
820}
821)";
822 os << formatv(Fmt: symbolizeEnumStr, Vals&: enumName, Vals&: strToSymFnName);
823
824 const char *const attrClassDecl = R"(
825class {1} : public ::mlir::{2} {
826public:
827 using ValueType = {0};
828 using ::mlir::{2}::{2};
829 static bool classof(::mlir::Attribute attr);
830 static {1} get(::mlir::MLIRContext *context, {0} val);
831 {0} getValue() const;
832};
833)";
834 if (enumInfo.genSpecializedAttr()) {
835 StringRef attrClassName = enumInfo.getSpecializedAttrClassName();
836 StringRef baseAttrClassName = "IntegerAttr";
837 os << formatv(Fmt: attrClassDecl, Vals&: enumName, Vals&: attrClassName, Vals&: baseAttrClassName);
838 // `::mlir::IntegerAttr`, the base class of the specialized attribute.
839 includes.push_back(Elt: "mlir/IR/BuiltinAttributes.h");
840 }
841 } // close `ns`.
842
843 // Generate a generic parser and printer for the enum.
844 std::string qualName = enumInfo.getQualifiedName();
845 emitParserPrinter(enumInfo, qualName, os, includes);
846
847 // Emit DenseMapInfo for this enum class
848 emitDenseMapInfo(qualName, underlyingType, cppNamespace, os);
849}
850
851static bool emitEnumDecls(const RecordKeeper &records, raw_ostream &os) {
852 llvm::emitSourceFileHeader(Desc: "Enum Utility Declarations", OS&: os, Record: records);
853
854 ArrayRef<const Record *> defs =
855 records.getAllDerivedDefinitionsIfDefined(ClassName: "EnumInfo");
856 if (defs.empty())
857 return false;
858
859 // The required includes are only known once all declarations were
860 // generated, so buffer the declarations until the includes are emitted.
861 SmallVector<StringRef> includes = {
862 // `::llvm::DenseMapInfo`.
863 "llvm/ADT/DenseMapInfo.h",
864 // `::llvm::StringRef`.
865 "llvm/ADT/StringRef.h",
866 };
867 std::string declarations;
868 llvm::raw_string_ostream declOs(declarations);
869 if (llvm::any_of(Range&: defs, P: [](const Record *def) {
870 return EnumInfo(def).hasParserPrinter();
871 }))
872 declOs << R"(
873namespace mlir {
874class AsmParser;
875
876template <typename T, typename>
877struct FieldParser;
878} // namespace mlir
879)";
880
881 for (const Record *def : defs)
882 emitEnumDecl(enumDef: *def, os&: declOs, includes);
883
884 tblgen::emitIncludes(os, headers: includes);
885 os << declarations;
886 return false;
887}
888
889static void emitEnumDef(const Record &enumDef, raw_ostream &os) {
890 EnumInfo enumInfo(enumDef);
891 StringRef cppNamespace = enumInfo.getCppNamespace();
892
893 {
894 llvm::NamespaceEmitter ns(os, cppNamespace);
895
896 if (enumInfo.isBitEnum()) {
897 emitSymToStrFnForBitEnum(enumDef, os);
898 emitStrToSymFnForBitEnum(enumDef, os);
899 emitUnderlyingToSymFnForBitEnum(enumDef, os);
900 } else {
901 emitSymToStrFnForIntEnum(enumDef, os);
902 emitStrToSymFnForIntEnum(enumDef, os);
903 emitUnderlyingToSymFnForIntEnum(enumDef, os);
904 }
905
906 if (enumInfo.genSpecializedAttr())
907 emitSpecializedAttrDef(enumDef, os);
908 }
909
910 // Generate the definitions of the parsers declared in the header.
911 if (enumInfo.hasParserPrinter())
912 emitFieldParserDefs(enumInfo, os);
913}
914
915/// Appends the headers declaring the C++ constructs used by the definitions of
916/// `enumInfo`, beyond those already included by the declarations, to
917/// `includes`.
918static void addEnumDefIncludes(const EnumInfo &enumInfo,
919 SmallVectorImpl<StringRef> &includes) {
920 // `::llvm::StringSwitch`, used to symbolize strings.
921 includes.push_back(Elt: "llvm/ADT/StringSwitch.h");
922 if (enumInfo.isBitEnum()) {
923 // `::llvm::SmallVector` and `::llvm::join`, used to split and join the
924 // strings of the individual bits.
925 includes.push_back(Elt: "llvm/ADT/SmallVector.h");
926 includes.push_back(Elt: "llvm/ADT/StringExtras.h");
927 }
928 // `::mlir::IntegerType`, used by the specialized attribute.
929 if (enumInfo.genSpecializedAttr())
930 includes.push_back(Elt: "mlir/IR/BuiltinTypes.h");
931
932 // `::mlir::AsmParser`, used by the `FieldParser` specializations.
933 if (enumInfo.hasParserPrinter())
934 includes.push_back(Elt: "mlir/IR/OpImplementation.h");
935}
936
937static bool emitEnumDefs(const RecordKeeper &records, raw_ostream &os) {
938 llvm::emitSourceFileHeader(Desc: "Enum Utility Definitions", OS&: os, Record: records);
939
940 ArrayRef<const Record *> defs =
941 records.getAllDerivedDefinitionsIfDefined(ClassName: "EnumInfo");
942 SmallVector<StringRef> includes;
943 for (const Record *def : defs)
944 addEnumDefIncludes(enumInfo: EnumInfo(def), includes);
945 tblgen::emitIncludes(os, headers: includes);
946
947 for (const Record *def : defs)
948 emitEnumDef(enumDef: *def, os);
949
950 return false;
951}
952
953// Registers the enum utility generator to mlir-tblgen.
954static mlir::GenRegistration
955 genEnumDecls("gen-enum-decls", "Generate enum utility declarations",
956 [](const RecordKeeper &records, raw_ostream &os) {
957 return emitEnumDecls(records, os);
958 });
959
960// Registers the enum utility generator to mlir-tblgen.
961static mlir::GenRegistration
962 genEnumDefs("gen-enum-defs", "Generate enum utility definitions",
963 [](const RecordKeeper &records, raw_ostream &os) {
964 return emitEnumDefs(records, os);
965 });
966