1//===- OpDocGen.cpp - MLIR operation documentation 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// OpDocGen uses the description of operations to generate documentation for the
10// operations.
11//
12//===----------------------------------------------------------------------===//
13
14#include "DialectGenUtilities.h"
15#include "DocGenUtilities.h"
16#include "OpGenHelpers.h"
17#include "mlir/Support/IndentedOstream.h"
18#include "mlir/TableGen/AttrOrTypeDef.h"
19#include "mlir/TableGen/Attribute.h"
20#include "mlir/TableGen/EnumInfo.h"
21#include "mlir/TableGen/GenInfo.h"
22#include "mlir/TableGen/Operator.h"
23#include "llvm/ADT/DenseMap.h"
24#include "llvm/ADT/SetVector.h"
25#include "llvm/ADT/StringExtras.h"
26#include "llvm/ADT/StringRef.h"
27#include "llvm/Support/CommandLine.h"
28#include "llvm/Support/FormatVariadic.h"
29#include "llvm/Support/Regex.h"
30#include "llvm/Support/Signals.h"
31#include "llvm/TableGen/Error.h"
32#include "llvm/TableGen/Record.h"
33#include "llvm/TableGen/TableGenBackend.h"
34
35#include <set>
36#include <string>
37
38using namespace llvm;
39using namespace mlir;
40using namespace mlir::tblgen;
41using mlir::tblgen::Operator;
42
43//===----------------------------------------------------------------------===//
44// Commandline Options
45//===----------------------------------------------------------------------===//
46static cl::OptionCategory
47 docCat("Options for -gen-(attrdef|typedef|enum|op|dialect)-doc");
48static cl::opt<std::string>
49 stripPrefix("strip-prefix",
50 cl::desc("Strip prefix of the fully qualified names"),
51 cl::init(Val: "::mlir::"), cl::cat(docCat));
52static cl::opt<bool> allowHugoSpecificFeatures(
53 "allow-hugo-specific-features",
54 cl::desc("Allows using features specific to Hugo"), cl::init(Val: false),
55 cl::cat(docCat));
56static cl::opt<bool>
57 keepOpSourceOrder("keep-op-source-order",
58 cl::desc("Do not sort ops alphabetically"),
59 cl::init(Val: false), cl::cat(docCat));
60
61void mlir::tblgen::emitSummary(StringRef summary, raw_ostream &os) {
62 if (summary.empty())
63 return;
64 StringRef trimmed = summary.trim();
65 char first = std::toupper(c: trimmed.front());
66 StringRef rest = trimmed.drop_front();
67 os << "\n_" << first << rest << "_\n";
68}
69
70// Emit the description by aligning the text to the left per line (e.g.,
71// removing the minimum indentation across the block).
72//
73// This expects that the description in the tablegen file is already formatted
74// in a way the user wanted but has some additional indenting due to being
75// nested in the op definition.
76void mlir::tblgen::emitDescription(StringRef description, raw_ostream &os) {
77 if (description.empty())
78 return;
79 os << "\n";
80 raw_indented_ostream ros(os);
81 StringRef trimmed = description.rtrim(Chars: " \t");
82 ros.printReindented(str: trimmed);
83 if (!trimmed.ends_with(Suffix: "\n"))
84 ros << "\n";
85}
86
87void mlir::tblgen::emitDescriptionComment(StringRef description,
88 raw_ostream &os, StringRef prefix) {
89 if (description.empty())
90 return;
91 os << "\n";
92 raw_indented_ostream ros(os);
93 StringRef trimmed = description.rtrim(Chars: " \t");
94 ros.printReindented(str: trimmed, extraPrefix: (Twine(prefix) + "/// ").str());
95 if (!trimmed.ends_with(Suffix: "\n"))
96 ros << "\n";
97}
98
99/// Emit the given named constraint.
100template <typename T>
101static void emitNamedConstraint(const T &it, raw_ostream &os) {
102 if (!it.name.empty())
103 os << "| `" << it.name << "`";
104 else
105 os << "| &laquo;unnamed&raquo;";
106 os << " | " << it.constraint.getSummary() << " |\n";
107}
108
109//===----------------------------------------------------------------------===//
110// Records
111//===----------------------------------------------------------------------===//
112
113namespace {
114struct OpDocGroup {
115 const Dialect &getDialect() const { return ops.front().getDialect(); }
116
117 /// Summary description of the section.
118 std::string summary = "";
119
120 /// Description of the section.
121 StringRef description = "";
122
123 /// Instances inside the section.
124 std::vector<Operator> ops;
125};
126
127/// Holds all records collected from a dialect relevant for documentation
128/// generation.
129struct DialectRecords {
130 DialectRecords(Dialect dialect, StringRef inputFilename)
131 : dialect(dialect), inputFilename(inputFilename) {}
132
133 Dialect dialect;
134 StringRef inputFilename;
135 std::vector<Attribute> attributes;
136 std::vector<AttrDef> attrDefs;
137 std::vector<OpDocGroup> ops;
138 std::vector<Type> types;
139 std::vector<TypeDef> typeDefs;
140 std::vector<EnumInfo> enums;
141};
142} // namespace
143
144//===----------------------------------------------------------------------===//
145// Operation Documentation
146//===----------------------------------------------------------------------===//
147
148/// Emit the assembly format of an operation.
149static void emitAssemblyFormat(StringRef opName, StringRef format,
150 raw_ostream &os) {
151 if (format.empty())
152 return;
153 os << "\nSyntax:\n\n```\noperation ::= `" << opName << "` ";
154
155 // Print the assembly format aligned.
156 unsigned indent = strlen(s: "operation ::= ");
157 std::pair<StringRef, StringRef> split = format.split(Separator: '\n');
158 os << split.first.trim() << "\n";
159 do {
160 split = split.second.split(Separator: '\n');
161 StringRef formatChunk = split.first.trim();
162 if (!formatChunk.empty())
163 os.indent(NumSpaces: indent) << formatChunk << "\n";
164 } while (!split.second.empty());
165 os << "```\n";
166}
167
168/// Place `text` between backticks so that the Markdown processor renders it as
169/// inline code.
170static std::string backticks(const std::string &text) {
171 return '`' + text + '`';
172}
173
174static void emitOpTraitsDoc(const Operator &op, raw_ostream &os) {
175 // TODO: We should link to the trait/documentation of it. That also means we
176 // should add descriptions to traits that can be queried.
177 // Collect using set to sort effects, interfaces & traits.
178 std::set<std::string> effects, interfaces, traits;
179 for (auto &trait : op.getTraits()) {
180 if (isa<PredTrait>(Val: &trait))
181 continue;
182
183 std::string name = trait.getDef().getName().str();
184 StringRef ref = name;
185 StringRef traitName = trait.getDef().getValueAsString(FieldName: "trait");
186 traitName.consume_back(Suffix: "::Trait");
187 traitName.consume_back(Suffix: "::Impl");
188 if (ref.starts_with(Prefix: "anonymous_"))
189 name = traitName.str();
190 if (isa<InterfaceTrait>(Val: &trait)) {
191 if (trait.getDef().isSubClassOf(Name: "SideEffectsTraitBase")) {
192 auto effectName = trait.getDef().getValueAsString(FieldName: "baseEffectName");
193 effectName.consume_front(Prefix: "::");
194 effectName.consume_front(Prefix: "mlir::");
195 std::string effectStr;
196 raw_string_ostream os(effectStr);
197 os << effectName << "{";
198 auto list = trait.getDef().getValueAsListOfDefs(FieldName: "effects");
199 interleaveComma(c: list, os, each_fn: [&](const Record *rec) {
200 StringRef effect = rec->getValueAsString(FieldName: "effect");
201 effect.consume_front(Prefix: "::");
202 effect.consume_front(Prefix: "mlir::");
203 os << effect << " on " << rec->getValueAsString(FieldName: "resource");
204 });
205 os << "}";
206 effects.insert(x: backticks(text: effectStr));
207 name.append(str: formatv(Fmt: " ({0})", Vals&: traitName).str());
208 }
209 interfaces.insert(x: backticks(text: name));
210 continue;
211 }
212
213 traits.insert(x: backticks(text: name));
214 }
215 if (!traits.empty()) {
216 interleaveComma(c: traits, os&: os << "\nTraits: ");
217 os << "\n";
218 }
219 if (!interfaces.empty()) {
220 interleaveComma(c: interfaces, os&: os << "\nInterfaces: ");
221 os << "\n";
222 }
223 if (!effects.empty()) {
224 interleaveComma(c: effects, os&: os << "\nEffects: ");
225 os << "\n";
226 }
227}
228
229static StringRef resolveAttrDescription(const Attribute &attr) {
230 StringRef description = attr.getDescription();
231 if (description.empty())
232 return attr.getBaseAttr().getDescription();
233 return description;
234}
235
236static void emitOpDoc(const Operator &op, raw_ostream &os) {
237 std::string classNameStr = op.getQualCppClassName();
238 StringRef className = classNameStr;
239 (void)className.consume_front(Prefix: stripPrefix);
240 os << formatv(Fmt: "\n### `{0}` ({1})\n", Vals: op.getOperationName(), Vals&: className);
241
242 // Emit the summary, syntax, and description if present.
243 if (op.hasSummary())
244 emitSummary(summary: op.getSummary(), os);
245 if (op.hasAssemblyFormat())
246 emitAssemblyFormat(opName: op.getOperationName(), format: op.getAssemblyFormat().trim(),
247 os);
248 if (op.hasDescription())
249 mlir::tblgen::emitDescription(description: op.getDescription(), os);
250
251 emitOpTraitsDoc(op, os);
252
253 // Emit attributes.
254 if (op.getNumAttributes() != 0) {
255 os << "\n#### Attributes:\n\n";
256 // Note: This table is HTML rather than markdown so the attribute's
257 // description can appear in an expandable region. The description may be
258 // multiple lines, which is not supported in a markdown table cell.
259 os << "<table>\n";
260 // Header.
261 os << "<tr><th>Attribute</th><th>MLIR Type</th><th>Description</th></tr>\n";
262 for (const auto &it : op.getAttributes()) {
263 StringRef storageType = it.attr.getStorageType();
264 // Name and storage type.
265 os << "<tr>";
266 os << "<td><code>" << it.name << "</code></td><td>" << storageType
267 << "</td><td>";
268 StringRef description = resolveAttrDescription(attr: it.attr);
269 if (allowHugoSpecificFeatures && !description.empty()) {
270 // Expandable description.
271 // This appears as just the summary, but when clicked shows the full
272 // description.
273 os << "<details>" << "<summary>" << it.attr.getSummary() << "</summary>"
274 << "{{% markdown %}}" << description << "{{% /markdown %}}"
275 << "</details>";
276 } else {
277 // Fallback: Single-line summary.
278 os << it.attr.getSummary();
279 }
280 os << "</td></tr>\n";
281 }
282 os << "</table>\n";
283 }
284
285 // Emit each of the operands.
286 if (op.getNumOperands() != 0) {
287 os << "\n#### Operands:\n\n";
288 os << "| Operand | Description |\n"
289 << "| :-----: | ----------- |\n";
290 for (const auto &it : op.getOperands())
291 emitNamedConstraint(it, os);
292 }
293
294 // Emit results.
295 if (op.getNumResults() != 0) {
296 os << "\n#### Results:\n\n";
297 os << "| Result | Description |\n"
298 << "| :----: | ----------- |\n";
299 for (const auto &it : op.getResults())
300 emitNamedConstraint(it, os);
301 }
302
303 // Emit successors.
304 if (op.getNumSuccessors() != 0) {
305 os << "\n#### Successors:\n\n";
306 os << "| Successor | Description |\n"
307 << "| :-------: | ----------- |\n";
308 for (const auto &it : op.getSuccessors())
309 emitNamedConstraint(it, os);
310 }
311
312 os << "\n";
313}
314
315static void emitSourceLink(StringRef inputFilename, raw_ostream &os) {
316 size_t pathBegin = inputFilename.find(Str: "mlir/include/mlir/");
317 if (pathBegin == StringRef::npos)
318 return;
319
320 StringRef inputFromMlirInclude = inputFilename.substr(Start: pathBegin);
321
322 os << "\n[source](https://github.com/llvm/llvm-project/blob/main/"
323 << inputFromMlirInclude << ")\n";
324}
325
326static void maybeNest(bool nest, llvm::function_ref<void(raw_ostream &os)> fn,
327 raw_ostream &os) {
328 std::string str;
329 raw_string_ostream ss(str);
330 fn(ss);
331 for (StringRef x : llvm::split(Str: str, Separator: "\n")) {
332 if (nest && x.starts_with(Prefix: "#"))
333 os << "#";
334 os << x << "\n";
335 }
336}
337
338static void emitOpDocGroup(const OpDocGroup &grouping, raw_ostream &os) {
339 bool nested = !grouping.summary.empty();
340 maybeNest(
341 nest: nested,
342 fn: [&](raw_ostream &os) {
343 if (nested) {
344 os << "\n## " << StringRef(grouping.summary).trim() << "\n";
345 emitDescription(description: grouping.description, os);
346 os << "\n";
347 }
348 for (const Operator &op : grouping.ops) {
349 emitOpDoc(op, os);
350 }
351 },
352 os);
353}
354
355static bool emitOpDoc(const DialectRecords &records, raw_ostream &os) {
356 os << "<!-- Autogenerated by mlir-tblgen; don't manually edit -->\n";
357 emitSourceLink(inputFilename: records.inputFilename, os);
358 for (const OpDocGroup &grouping : records.ops)
359 emitOpDocGroup(grouping, os);
360 return false;
361}
362
363//===----------------------------------------------------------------------===//
364// Attribute Documentation
365//===----------------------------------------------------------------------===//
366
367static void emitAttrDoc(const Attribute &attr, raw_ostream &os) {
368 os << "\n### " << attr.getSummary() << "\n";
369 emitDescription(description: attr.getDescription(), os);
370 os << "\n";
371}
372
373//===----------------------------------------------------------------------===//
374// Type Documentation
375//===----------------------------------------------------------------------===//
376
377static void emitTypeDoc(const Type &type, raw_ostream &os) {
378 os << "\n### " << type.getSummary() << "\n";
379 emitDescription(description: type.getDescription(), os);
380 os << "\n";
381}
382
383//===----------------------------------------------------------------------===//
384// TypeDef Documentation
385//===----------------------------------------------------------------------===//
386
387/// If `param` is an EnumParameter, return a string listing the enum's keyword
388/// alternatives (e.g. "`read` | `read_write`"). Otherwise return std::nullopt.
389static std::optional<std::string>
390getEnumParameterDocSyntax(const AttrOrTypeParameter &param) {
391 const auto *paramDef = dyn_cast<DefInit>(Val: param.getDef());
392 if (!paramDef || !paramDef->getDef()->isSubClassOf(Name: "EnumParameter"))
393 return std::nullopt;
394 const Record *enumRec = paramDef->getDef()->getValueAsDef(FieldName: "enum");
395 EnumInfo enumInfo(enumRec);
396 std::vector<EnumCase> cases = enumInfo.getAllCases();
397 std::string result;
398 llvm::interleave(
399 c: cases, each_fn: [&](const EnumCase &c) { result += "`" + c.getStr().str() + "`"; },
400 between_fn: [&] { result += " | "; });
401 return result;
402}
403
404static void emitAttrOrTypeDefAssemblyFormat(const AttrOrTypeDef &def,
405 raw_ostream &os) {
406 ArrayRef<AttrOrTypeParameter> parameters = def.getParameters();
407 char prefix = isa<AttrDef>(Val: def) ? '#' : '!';
408 if (parameters.empty()) {
409 os << "\nSyntax: `" << prefix << def.getDialect().getName() << "."
410 << def.getMnemonic() << "`\n";
411 return;
412 }
413
414 os << "\nSyntax:\n\n```\n"
415 << prefix << def.getDialect().getName() << "." << def.getMnemonic()
416 << "<\n";
417 for (const auto &it : llvm::enumerate(First&: parameters)) {
418 const AttrOrTypeParameter &param = it.value();
419 if (auto enumSyntax = getEnumParameterDocSyntax(param))
420 os << " " << *enumSyntax;
421 else
422 os << " " << param.getSyntax();
423 if (it.index() < (parameters.size() - 1))
424 os << ",";
425 os << " # " << param.getName() << "\n";
426 }
427 os << ">\n```\n";
428}
429
430static void emitAttrOrTypeDefDoc(const AttrOrTypeDef &def, raw_ostream &os) {
431 os << formatv(Fmt: "\n### {0}\n", Vals: def.getCppClassName());
432
433 // Emit the summary if present.
434 if (def.hasSummary())
435 emitSummary(summary: def.getSummary(), os);
436
437 // Emit the syntax if present.
438 if (def.getMnemonic() && !def.hasCustomAssemblyFormat())
439 emitAttrOrTypeDefAssemblyFormat(def, os);
440
441 // Emit the description if present.
442 if (def.hasDescription()) {
443 mlir::tblgen::emitDescription(description: def.getDescription(), os);
444 }
445
446 // Emit parameter documentation.
447 ArrayRef<AttrOrTypeParameter> parameters = def.getParameters();
448 if (!parameters.empty()) {
449 os << "\n#### Parameters:\n\n";
450 os << "| Parameter | C++ type | Description |\n"
451 << "| :-------: | :-------: | ----------- |";
452 for (const auto &it : parameters) {
453 auto desc = it.getSummary();
454 os << "\n| " << it.getName() << " | `" << it.getCppType() << "` | "
455 << (desc ? *desc : "") << " |";
456 }
457 }
458
459 os << "\n";
460}
461
462static bool emitAttrDefDoc(const DialectRecords &records, raw_ostream &os) {
463 os << "<!-- Autogenerated by mlir-tblgen; don't manually edit -->\n";
464 for (const AttrDef &def : records.attrDefs)
465 emitAttrOrTypeDefDoc(def, os);
466 return false;
467}
468
469static bool emitTypeDefDoc(const DialectRecords &records, raw_ostream &os) {
470 os << "<!-- Autogenerated by mlir-tblgen; don't manually edit -->\n";
471 for (const TypeDef &def : records.typeDefs)
472 emitAttrOrTypeDefDoc(def, os);
473 return false;
474}
475
476//===----------------------------------------------------------------------===//
477// Enum Documentation
478//===----------------------------------------------------------------------===//
479
480static void emitEnumDoc(const EnumInfo &def, raw_ostream &os) {
481 os << formatv(Fmt: "\n### {0}\n", Vals: def.getEnumClassName());
482
483 // Emit the summary if present.
484 emitSummary(summary: def.getSummary(), os);
485
486 // Emit case documentation.
487 std::vector<EnumCase> cases = def.getAllCases();
488 os << "\n#### Cases:\n\n";
489 os << "| Symbol | Value | String |\n"
490 << "| :----: | :---: | ------ |";
491 for (const auto &it : cases) {
492 os << "\n| " << it.getSymbol() << " | `" << it.getValue() << "` | "
493 << it.getStr() << " |";
494 }
495
496 os << "\n";
497}
498
499static bool emitEnumDoc(const DialectRecords &records, raw_ostream &os) {
500 os << "<!-- Autogenerated by mlir-tblgen; don't manually edit -->\n";
501 for (const EnumInfo &def : records.enums)
502 emitEnumDoc(def, os);
503 return false;
504}
505
506//===----------------------------------------------------------------------===//
507// Dialect Documentation
508//===----------------------------------------------------------------------===//
509
510static void emitBlock(const DialectRecords &records, raw_ostream &os) {
511 if (!records.ops.empty()) {
512 os << "\n## Operations\n";
513 emitSourceLink(inputFilename: records.inputFilename, os);
514 for (const OpDocGroup &grouping : records.ops)
515 emitOpDocGroup(grouping, os);
516 }
517
518 if (!records.attributes.empty()) {
519 os << "\n## Attribute constraints\n";
520 for (const Attribute &attr : records.attributes)
521 emitAttrDoc(attr, os);
522 }
523
524 if (!records.attrDefs.empty()) {
525 os << "\n## Attributes\n";
526 for (const AttrDef &def : records.attrDefs)
527 emitAttrOrTypeDefDoc(def, os);
528 }
529
530 // TODO: Add link between use and def for types
531 if (!records.types.empty()) {
532 os << "\n## Type constraints\n";
533 for (const Type &type : records.types)
534 emitTypeDoc(type, os);
535 }
536
537 if (!records.typeDefs.empty()) {
538 os << "\n## Types\n";
539 for (const TypeDef &def : records.typeDefs)
540 emitAttrOrTypeDefDoc(def, os);
541 }
542
543 if (!records.enums.empty()) {
544 os << "\n## Enums\n";
545 for (const EnumInfo &def : records.enums)
546 emitEnumDoc(def, os);
547 }
548}
549
550static bool emitDialectDoc(const DialectRecords &records, raw_ostream &os) {
551 os << "<!-- Autogenerated by mlir-tblgen; don't manually edit -->\n";
552 os << "\n# '" << records.dialect.getName() << "' Dialect\n";
553 emitSummary(summary: records.dialect.getSummary(), os);
554 emitDescription(description: records.dialect.getDescription(), os);
555
556 // Generate a TOC marker except if description already contains one.
557 Regex r("^[[:space:]]*\\[TOC\\]$", Regex::RegexFlags::Newline);
558 if (!r.match(String: records.dialect.getDescription()))
559 os << "\n[TOC]\n";
560
561 emitBlock(records, os);
562 return false;
563}
564
565//===----------------------------------------------------------------------===//
566// Record Collection
567//===----------------------------------------------------------------------===//
568
569/// Collect, filter, and organize all records relevant for dialect documentation
570/// generation. Returns none if no single dialect could be determined. See
571/// `mlir::tblgen::findDialectToGenerate`.
572static std::optional<DialectRecords>
573collectRecords(const RecordKeeper &records) {
574 auto dialectDefs = records.getAllDerivedDefinitionsIfDefined(ClassName: "Dialect");
575 SmallVector<Dialect> dialects(dialectDefs.begin(), dialectDefs.end());
576 std::optional<Dialect> dialect = findDialectToGenerate(dialects);
577 if (!dialect)
578 return std::nullopt;
579
580 std::vector<const Record *> opDefs = getRequestedOpDefinitions(records);
581 auto attrDefs = records.getAllDerivedDefinitionsIfDefined(ClassName: "DialectAttr");
582 auto typeDefs = records.getAllDerivedDefinitionsIfDefined(ClassName: "DialectType");
583 auto typeDefDefs = records.getAllDerivedDefinitionsIfDefined(ClassName: "TypeDef");
584 auto attrDefDefs = records.getAllDerivedDefinitionsIfDefined(ClassName: "AttrDef");
585 auto enumDefs = records.getAllDerivedDefinitionsIfDefined(ClassName: "EnumInfo");
586
587 DialectRecords result(*dialect, records.getInputFilename());
588 SmallDenseSet<const Record *> seen;
589 auto addIfNotSeen = [&](const Record *record, const auto &def, auto &vec) {
590 if (seen.insert(V: record).second) {
591 vec.push_back(def);
592 return true;
593 }
594 return false;
595 };
596 auto addIfInDialect = [&](const Record *record, const auto &def, auto &vec) {
597 return def.getDialect() == *dialect && addIfNotSeen(record, def, vec);
598 };
599
600 SmallDenseMap<const Record *, OpDocGroup> opDocGroup;
601
602 for (const Record *def : attrDefDefs)
603 addIfInDialect(def, AttrDef(def), result.attrDefs);
604 for (const Record *def : attrDefs)
605 addIfInDialect(def, Attribute(def), result.attributes);
606 for (const Record *def : opDefs) {
607 if (const Record *group = def->getValueAsOptionalDef(FieldName: "opDocGroup")) {
608 OpDocGroup &op = opDocGroup[group];
609 addIfInDialect(def, Operator(def), op.ops);
610 } else {
611 OpDocGroup op;
612 op.ops.emplace_back(args&: def);
613 addIfInDialect(def, op, result.ops);
614 }
615 }
616 for (const Record *rec :
617 records.getAllDerivedDefinitionsIfDefined(ClassName: "OpDocGroup")) {
618 if (opDocGroup[rec].ops.empty())
619 continue;
620 opDocGroup[rec].summary = rec->getValueAsString(FieldName: "summary");
621 opDocGroup[rec].description = rec->getValueAsString(FieldName: "description");
622 result.ops.push_back(x: opDocGroup[rec]);
623 }
624 for (const Record *def : typeDefDefs)
625 addIfInDialect(def, TypeDef(def), result.typeDefs);
626 for (const Record *def : typeDefs)
627 addIfInDialect(def, Type(def), result.types);
628 result.enums.reserve(n: enumDefs.size());
629 for (const Record *def : enumDefs)
630 addIfNotSeen(def, EnumInfo(def), result.enums);
631
632 // Sort alphabetically ignorning dialect for ops and section name for
633 // sections.
634 // TODO: The sorting order could be revised, currently attempting to sort of
635 // keep in alphabetical order.
636 if (keepOpSourceOrder)
637 return result;
638 llvm::sort(C&: result.ops, Comp: [](const OpDocGroup &lhs, const OpDocGroup &rhs) {
639 auto getDesc = [](const OpDocGroup &arg) -> StringRef {
640 if (!arg.summary.empty())
641 return arg.summary;
642 return arg.ops.front().getDef().getValueAsString(FieldName: "opName");
643 };
644 return getDesc(lhs).compare_insensitive(RHS: getDesc(rhs)) < 0;
645 });
646
647 return result;
648}
649
650//===----------------------------------------------------------------------===//
651// Gen Registration
652//===----------------------------------------------------------------------===//
653
654static mlir::GenRegistration
655 genAttrRegister("gen-attrdef-doc",
656 "Generate dialect attribute documentation",
657 [](const RecordKeeper &records, raw_ostream &os) {
658 if (auto filtered = collectRecords(records))
659 return emitAttrDefDoc(records: *filtered, os);
660 return true;
661 });
662
663static mlir::GenRegistration
664 genOpRegister("gen-op-doc", "Generate dialect documentation",
665 [](const RecordKeeper &records, raw_ostream &os) {
666 if (auto filtered = collectRecords(records))
667 return emitOpDoc(records: *filtered, os);
668 return true;
669 });
670
671static mlir::GenRegistration
672 genTypeRegister("gen-typedef-doc", "Generate dialect type documentation",
673 [](const RecordKeeper &records, raw_ostream &os) {
674 if (auto filtered = collectRecords(records))
675 return emitTypeDefDoc(records: *filtered, os);
676 return true;
677 });
678
679static mlir::GenRegistration
680 genEnumRegister("gen-enum-doc", "Generate dialect enum documentation",
681 [](const RecordKeeper &records, raw_ostream &os) {
682 if (auto filtered = collectRecords(records))
683 return emitEnumDoc(records: *filtered, os);
684 return true;
685 });
686
687static mlir::GenRegistration
688 genRegister("gen-dialect-doc", "Generate dialect documentation",
689 [](const RecordKeeper &records, raw_ostream &os) {
690 if (auto filtered = collectRecords(records))
691 return emitDialectDoc(records: *filtered, os);
692 return true;
693 });
694