xref: /freebsd/contrib/llvm-project/llvm/utils/TableGen/DirectiveEmitter.cpp (revision 972a253a57b6f144b0e4a3e2080a2a0076ec55a0)
1 //===- DirectiveEmitter.cpp - Directive Language Emitter ------------------===//
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 // DirectiveEmitter uses the descriptions of directives and clauses to construct
10 // common code declarations to be used in Frontends.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "llvm/TableGen/DirectiveEmitter.h"
15 #include "llvm/ADT/STLExtras.h"
16 #include "llvm/ADT/SmallVector.h"
17 #include "llvm/ADT/StringSet.h"
18 #include "llvm/ADT/StringSwitch.h"
19 #include "llvm/TableGen/Error.h"
20 #include "llvm/TableGen/Record.h"
21 
22 using namespace llvm;
23 
24 namespace {
25 // Simple RAII helper for defining ifdef-undef-endif scopes.
26 class IfDefScope {
27 public:
28   IfDefScope(StringRef Name, raw_ostream &OS) : Name(Name), OS(OS) {
29     OS << "#ifdef " << Name << "\n"
30        << "#undef " << Name << "\n";
31   }
32 
33   ~IfDefScope() { OS << "\n#endif // " << Name << "\n\n"; }
34 
35 private:
36   StringRef Name;
37   raw_ostream &OS;
38 };
39 } // end anonymous namespace
40 
41 namespace llvm {
42 
43 // Generate enum class
44 void GenerateEnumClass(const std::vector<Record *> &Records, raw_ostream &OS,
45                        StringRef Enum, StringRef Prefix,
46                        const DirectiveLanguage &DirLang) {
47   OS << "\n";
48   OS << "enum class " << Enum << " {\n";
49   for (const auto &R : Records) {
50     BaseRecord Rec{R};
51     OS << "  " << Prefix << Rec.getFormattedName() << ",\n";
52   }
53   OS << "};\n";
54   OS << "\n";
55   OS << "static constexpr std::size_t " << Enum
56      << "_enumSize = " << Records.size() << ";\n";
57 
58   // Make the enum values available in the defined namespace. This allows us to
59   // write something like Enum_X if we have a `using namespace <CppNamespace>`.
60   // At the same time we do not loose the strong type guarantees of the enum
61   // class, that is we cannot pass an unsigned as Directive without an explicit
62   // cast.
63   if (DirLang.hasMakeEnumAvailableInNamespace()) {
64     OS << "\n";
65     for (const auto &R : Records) {
66       BaseRecord Rec{R};
67       OS << "constexpr auto " << Prefix << Rec.getFormattedName() << " = "
68          << "llvm::" << DirLang.getCppNamespace() << "::" << Enum
69          << "::" << Prefix << Rec.getFormattedName() << ";\n";
70     }
71   }
72 }
73 
74 // Generate enums for values that clauses can take.
75 // Also generate function declarations for get<Enum>Name(StringRef Str).
76 void GenerateEnumClauseVal(const std::vector<Record *> &Records,
77                            raw_ostream &OS, const DirectiveLanguage &DirLang,
78                            std::string &EnumHelperFuncs) {
79   for (const auto &R : Records) {
80     Clause C{R};
81     const auto &ClauseVals = C.getClauseVals();
82     if (ClauseVals.size() <= 0)
83       continue;
84 
85     const auto &EnumName = C.getEnumName();
86     if (EnumName.size() == 0) {
87       PrintError("enumClauseValue field not set in Clause" +
88                  C.getFormattedName() + ".");
89       return;
90     }
91 
92     OS << "\n";
93     OS << "enum class " << EnumName << " {\n";
94     for (const auto &CV : ClauseVals) {
95       ClauseVal CVal{CV};
96       OS << "  " << CV->getName() << "=" << CVal.getValue() << ",\n";
97     }
98     OS << "};\n";
99 
100     if (DirLang.hasMakeEnumAvailableInNamespace()) {
101       OS << "\n";
102       for (const auto &CV : ClauseVals) {
103         OS << "constexpr auto " << CV->getName() << " = "
104            << "llvm::" << DirLang.getCppNamespace() << "::" << EnumName
105            << "::" << CV->getName() << ";\n";
106       }
107       EnumHelperFuncs += (llvm::Twine(EnumName) + llvm::Twine(" get") +
108                           llvm::Twine(EnumName) + llvm::Twine("(StringRef);\n"))
109                              .str();
110 
111       EnumHelperFuncs +=
112           (llvm::Twine("llvm::StringRef get") + llvm::Twine(DirLang.getName()) +
113            llvm::Twine(EnumName) + llvm::Twine("Name(") +
114            llvm::Twine(EnumName) + llvm::Twine(");\n"))
115               .str();
116     }
117   }
118 }
119 
120 bool HasDuplicateClauses(const std::vector<Record *> &Clauses,
121                          const Directive &Directive,
122                          llvm::StringSet<> &CrtClauses) {
123   bool HasError = false;
124   for (const auto &C : Clauses) {
125     VersionedClause VerClause{C};
126     const auto insRes = CrtClauses.insert(VerClause.getClause().getName());
127     if (!insRes.second) {
128       PrintError("Clause " + VerClause.getClause().getRecordName() +
129                  " already defined on directive " + Directive.getRecordName());
130       HasError = true;
131     }
132   }
133   return HasError;
134 }
135 
136 // Check for duplicate clauses in lists. Clauses cannot appear twice in the
137 // three allowed list. Also, since required implies allowed, clauses cannot
138 // appear in both the allowedClauses and requiredClauses lists.
139 bool HasDuplicateClausesInDirectives(const std::vector<Record *> &Directives) {
140   bool HasDuplicate = false;
141   for (const auto &D : Directives) {
142     Directive Dir{D};
143     llvm::StringSet<> Clauses;
144     // Check for duplicates in the three allowed lists.
145     if (HasDuplicateClauses(Dir.getAllowedClauses(), Dir, Clauses) ||
146         HasDuplicateClauses(Dir.getAllowedOnceClauses(), Dir, Clauses) ||
147         HasDuplicateClauses(Dir.getAllowedExclusiveClauses(), Dir, Clauses)) {
148       HasDuplicate = true;
149     }
150     // Check for duplicate between allowedClauses and required
151     Clauses.clear();
152     if (HasDuplicateClauses(Dir.getAllowedClauses(), Dir, Clauses) ||
153         HasDuplicateClauses(Dir.getRequiredClauses(), Dir, Clauses)) {
154       HasDuplicate = true;
155     }
156     if (HasDuplicate)
157       PrintFatalError("One or more clauses are defined multiple times on"
158                       " directive " +
159                       Dir.getRecordName());
160   }
161 
162   return HasDuplicate;
163 }
164 
165 // Check consitency of records. Return true if an error has been detected.
166 // Return false if the records are valid.
167 bool DirectiveLanguage::HasValidityErrors() const {
168   if (getDirectiveLanguages().size() != 1) {
169     PrintFatalError("A single definition of DirectiveLanguage is needed.");
170     return true;
171   }
172 
173   return HasDuplicateClausesInDirectives(getDirectives());
174 }
175 
176 // Generate the declaration section for the enumeration in the directive
177 // language
178 void EmitDirectivesDecl(RecordKeeper &Records, raw_ostream &OS) {
179   const auto DirLang = DirectiveLanguage{Records};
180   if (DirLang.HasValidityErrors())
181     return;
182 
183   OS << "#ifndef LLVM_" << DirLang.getName() << "_INC\n";
184   OS << "#define LLVM_" << DirLang.getName() << "_INC\n";
185 
186   if (DirLang.hasEnableBitmaskEnumInNamespace())
187     OS << "\n#include \"llvm/ADT/BitmaskEnum.h\"\n";
188 
189   OS << "\n";
190   OS << "namespace llvm {\n";
191   OS << "class StringRef;\n";
192 
193   // Open namespaces defined in the directive language
194   llvm::SmallVector<StringRef, 2> Namespaces;
195   llvm::SplitString(DirLang.getCppNamespace(), Namespaces, "::");
196   for (auto Ns : Namespaces)
197     OS << "namespace " << Ns << " {\n";
198 
199   if (DirLang.hasEnableBitmaskEnumInNamespace())
200     OS << "\nLLVM_ENABLE_BITMASK_ENUMS_IN_NAMESPACE();\n";
201 
202   // Emit Directive enumeration
203   GenerateEnumClass(DirLang.getDirectives(), OS, "Directive",
204                     DirLang.getDirectivePrefix(), DirLang);
205 
206   // Emit Clause enumeration
207   GenerateEnumClass(DirLang.getClauses(), OS, "Clause",
208                     DirLang.getClausePrefix(), DirLang);
209 
210   // Emit ClauseVal enumeration
211   std::string EnumHelperFuncs;
212   GenerateEnumClauseVal(DirLang.getClauses(), OS, DirLang, EnumHelperFuncs);
213 
214   // Generic function signatures
215   OS << "\n";
216   OS << "// Enumeration helper functions\n";
217   OS << "Directive get" << DirLang.getName()
218      << "DirectiveKind(llvm::StringRef Str);\n";
219   OS << "\n";
220   OS << "llvm::StringRef get" << DirLang.getName()
221      << "DirectiveName(Directive D);\n";
222   OS << "\n";
223   OS << "Clause get" << DirLang.getName()
224      << "ClauseKind(llvm::StringRef Str);\n";
225   OS << "\n";
226   OS << "llvm::StringRef get" << DirLang.getName() << "ClauseName(Clause C);\n";
227   OS << "\n";
228   OS << "/// Return true if \\p C is a valid clause for \\p D in version \\p "
229      << "Version.\n";
230   OS << "bool isAllowedClauseForDirective(Directive D, "
231      << "Clause C, unsigned Version);\n";
232   OS << "\n";
233   if (EnumHelperFuncs.length() > 0) {
234     OS << EnumHelperFuncs;
235     OS << "\n";
236   }
237 
238   // Closing namespaces
239   for (auto Ns : llvm::reverse(Namespaces))
240     OS << "} // namespace " << Ns << "\n";
241 
242   OS << "} // namespace llvm\n";
243 
244   OS << "#endif // LLVM_" << DirLang.getName() << "_INC\n";
245 }
246 
247 // Generate function implementation for get<Enum>Name(StringRef Str)
248 void GenerateGetName(const std::vector<Record *> &Records, raw_ostream &OS,
249                      StringRef Enum, const DirectiveLanguage &DirLang,
250                      StringRef Prefix) {
251   OS << "\n";
252   OS << "llvm::StringRef llvm::" << DirLang.getCppNamespace() << "::get"
253      << DirLang.getName() << Enum << "Name(" << Enum << " Kind) {\n";
254   OS << "  switch (Kind) {\n";
255   for (const auto &R : Records) {
256     BaseRecord Rec{R};
257     OS << "    case " << Prefix << Rec.getFormattedName() << ":\n";
258     OS << "      return \"";
259     if (Rec.getAlternativeName().empty())
260       OS << Rec.getName();
261     else
262       OS << Rec.getAlternativeName();
263     OS << "\";\n";
264   }
265   OS << "  }\n"; // switch
266   OS << "  llvm_unreachable(\"Invalid " << DirLang.getName() << " " << Enum
267      << " kind\");\n";
268   OS << "}\n";
269 }
270 
271 // Generate function implementation for get<Enum>Kind(StringRef Str)
272 void GenerateGetKind(const std::vector<Record *> &Records, raw_ostream &OS,
273                      StringRef Enum, const DirectiveLanguage &DirLang,
274                      StringRef Prefix, bool ImplicitAsUnknown) {
275 
276   auto DefaultIt = llvm::find_if(
277       Records, [](Record *R) { return R->getValueAsBit("isDefault") == true; });
278 
279   if (DefaultIt == Records.end()) {
280     PrintError("At least one " + Enum + " must be defined as default.");
281     return;
282   }
283 
284   BaseRecord DefaultRec{(*DefaultIt)};
285 
286   OS << "\n";
287   OS << Enum << " llvm::" << DirLang.getCppNamespace() << "::get"
288      << DirLang.getName() << Enum << "Kind(llvm::StringRef Str) {\n";
289   OS << "  return llvm::StringSwitch<" << Enum << ">(Str)\n";
290 
291   for (const auto &R : Records) {
292     BaseRecord Rec{R};
293     if (ImplicitAsUnknown && R->getValueAsBit("isImplicit")) {
294       OS << "    .Case(\"" << Rec.getName() << "\"," << Prefix
295          << DefaultRec.getFormattedName() << ")\n";
296     } else {
297       OS << "    .Case(\"" << Rec.getName() << "\"," << Prefix
298          << Rec.getFormattedName() << ")\n";
299     }
300   }
301   OS << "    .Default(" << Prefix << DefaultRec.getFormattedName() << ");\n";
302   OS << "}\n";
303 }
304 
305 // Generate function implementation for get<ClauseVal>Kind(StringRef Str)
306 void GenerateGetKindClauseVal(const DirectiveLanguage &DirLang,
307                               raw_ostream &OS) {
308   for (const auto &R : DirLang.getClauses()) {
309     Clause C{R};
310     const auto &ClauseVals = C.getClauseVals();
311     if (ClauseVals.size() <= 0)
312       continue;
313 
314     auto DefaultIt = llvm::find_if(ClauseVals, [](Record *CV) {
315       return CV->getValueAsBit("isDefault") == true;
316     });
317 
318     if (DefaultIt == ClauseVals.end()) {
319       PrintError("At least one val in Clause " + C.getFormattedName() +
320                  " must be defined as default.");
321       return;
322     }
323     const auto DefaultName = (*DefaultIt)->getName();
324 
325     const auto &EnumName = C.getEnumName();
326     if (EnumName.size() == 0) {
327       PrintError("enumClauseValue field not set in Clause" +
328                  C.getFormattedName() + ".");
329       return;
330     }
331 
332     OS << "\n";
333     OS << EnumName << " llvm::" << DirLang.getCppNamespace() << "::get"
334        << EnumName << "(llvm::StringRef Str) {\n";
335     OS << "  return llvm::StringSwitch<" << EnumName << ">(Str)\n";
336     for (const auto &CV : ClauseVals) {
337       ClauseVal CVal{CV};
338       OS << "    .Case(\"" << CVal.getFormattedName() << "\"," << CV->getName()
339          << ")\n";
340     }
341     OS << "    .Default(" << DefaultName << ");\n";
342     OS << "}\n";
343 
344     OS << "\n";
345     OS << "llvm::StringRef llvm::" << DirLang.getCppNamespace() << "::get"
346        << DirLang.getName() << EnumName
347        << "Name(llvm::" << DirLang.getCppNamespace() << "::" << EnumName
348        << " x) {\n";
349     OS << "  switch (x) {\n";
350     for (const auto &CV : ClauseVals) {
351       ClauseVal CVal{CV};
352       OS << "    case " << CV->getName() << ":\n";
353       OS << "      return \"" << CVal.getFormattedName() << "\";\n";
354     }
355     OS << "  }\n"; // switch
356     OS << "  llvm_unreachable(\"Invalid " << DirLang.getName() << " "
357        << EnumName << " kind\");\n";
358     OS << "}\n";
359   }
360 }
361 
362 void GenerateCaseForVersionedClauses(const std::vector<Record *> &Clauses,
363                                      raw_ostream &OS, StringRef DirectiveName,
364                                      const DirectiveLanguage &DirLang,
365                                      llvm::StringSet<> &Cases) {
366   for (const auto &C : Clauses) {
367     VersionedClause VerClause{C};
368 
369     const auto ClauseFormattedName = VerClause.getClause().getFormattedName();
370 
371     if (Cases.insert(ClauseFormattedName).second) {
372       OS << "        case " << DirLang.getClausePrefix() << ClauseFormattedName
373          << ":\n";
374       OS << "          return " << VerClause.getMinVersion()
375          << " <= Version && " << VerClause.getMaxVersion() << " >= Version;\n";
376     }
377   }
378 }
379 
380 // Generate the isAllowedClauseForDirective function implementation.
381 void GenerateIsAllowedClause(const DirectiveLanguage &DirLang,
382                              raw_ostream &OS) {
383   OS << "\n";
384   OS << "bool llvm::" << DirLang.getCppNamespace()
385      << "::isAllowedClauseForDirective("
386      << "Directive D, Clause C, unsigned Version) {\n";
387   OS << "  assert(unsigned(D) <= llvm::" << DirLang.getCppNamespace()
388      << "::Directive_enumSize);\n";
389   OS << "  assert(unsigned(C) <= llvm::" << DirLang.getCppNamespace()
390      << "::Clause_enumSize);\n";
391 
392   OS << "  switch (D) {\n";
393 
394   for (const auto &D : DirLang.getDirectives()) {
395     Directive Dir{D};
396 
397     OS << "    case " << DirLang.getDirectivePrefix() << Dir.getFormattedName()
398        << ":\n";
399     if (Dir.getAllowedClauses().size() == 0 &&
400         Dir.getAllowedOnceClauses().size() == 0 &&
401         Dir.getAllowedExclusiveClauses().size() == 0 &&
402         Dir.getRequiredClauses().size() == 0) {
403       OS << "      return false;\n";
404     } else {
405       OS << "      switch (C) {\n";
406 
407       llvm::StringSet<> Cases;
408 
409       GenerateCaseForVersionedClauses(Dir.getAllowedClauses(), OS,
410                                       Dir.getName(), DirLang, Cases);
411 
412       GenerateCaseForVersionedClauses(Dir.getAllowedOnceClauses(), OS,
413                                       Dir.getName(), DirLang, Cases);
414 
415       GenerateCaseForVersionedClauses(Dir.getAllowedExclusiveClauses(), OS,
416                                       Dir.getName(), DirLang, Cases);
417 
418       GenerateCaseForVersionedClauses(Dir.getRequiredClauses(), OS,
419                                       Dir.getName(), DirLang, Cases);
420 
421       OS << "        default:\n";
422       OS << "          return false;\n";
423       OS << "      }\n"; // End of clauses switch
424     }
425     OS << "      break;\n";
426   }
427 
428   OS << "  }\n"; // End of directives switch
429   OS << "  llvm_unreachable(\"Invalid " << DirLang.getName()
430      << " Directive kind\");\n";
431   OS << "}\n"; // End of function isAllowedClauseForDirective
432 }
433 
434 // Generate a simple enum set with the give clauses.
435 void GenerateClauseSet(const std::vector<Record *> &Clauses, raw_ostream &OS,
436                        StringRef ClauseSetPrefix, Directive &Dir,
437                        const DirectiveLanguage &DirLang) {
438 
439   OS << "\n";
440   OS << "  static " << DirLang.getClauseEnumSetClass() << " " << ClauseSetPrefix
441      << DirLang.getDirectivePrefix() << Dir.getFormattedName() << " {\n";
442 
443   for (const auto &C : Clauses) {
444     VersionedClause VerClause{C};
445     OS << "    llvm::" << DirLang.getCppNamespace()
446        << "::Clause::" << DirLang.getClausePrefix()
447        << VerClause.getClause().getFormattedName() << ",\n";
448   }
449   OS << "  };\n";
450 }
451 
452 // Generate an enum set for the 4 kinds of clauses linked to a directive.
453 void GenerateDirectiveClauseSets(const DirectiveLanguage &DirLang,
454                                  raw_ostream &OS) {
455 
456   IfDefScope Scope("GEN_FLANG_DIRECTIVE_CLAUSE_SETS", OS);
457 
458   OS << "\n";
459   OS << "namespace llvm {\n";
460 
461   // Open namespaces defined in the directive language.
462   llvm::SmallVector<StringRef, 2> Namespaces;
463   llvm::SplitString(DirLang.getCppNamespace(), Namespaces, "::");
464   for (auto Ns : Namespaces)
465     OS << "namespace " << Ns << " {\n";
466 
467   for (const auto &D : DirLang.getDirectives()) {
468     Directive Dir{D};
469 
470     OS << "\n";
471     OS << "  // Sets for " << Dir.getName() << "\n";
472 
473     GenerateClauseSet(Dir.getAllowedClauses(), OS, "allowedClauses_", Dir,
474                       DirLang);
475     GenerateClauseSet(Dir.getAllowedOnceClauses(), OS, "allowedOnceClauses_",
476                       Dir, DirLang);
477     GenerateClauseSet(Dir.getAllowedExclusiveClauses(), OS,
478                       "allowedExclusiveClauses_", Dir, DirLang);
479     GenerateClauseSet(Dir.getRequiredClauses(), OS, "requiredClauses_", Dir,
480                       DirLang);
481   }
482 
483   // Closing namespaces
484   for (auto Ns : llvm::reverse(Namespaces))
485     OS << "} // namespace " << Ns << "\n";
486 
487   OS << "} // namespace llvm\n";
488 }
489 
490 // Generate a map of directive (key) with DirectiveClauses struct as values.
491 // The struct holds the 4 sets of enumeration for the 4 kinds of clauses
492 // allowances (allowed, allowed once, allowed exclusive and required).
493 void GenerateDirectiveClauseMap(const DirectiveLanguage &DirLang,
494                                 raw_ostream &OS) {
495 
496   IfDefScope Scope("GEN_FLANG_DIRECTIVE_CLAUSE_MAP", OS);
497 
498   OS << "\n";
499   OS << "{\n";
500 
501   for (const auto &D : DirLang.getDirectives()) {
502     Directive Dir{D};
503     OS << "  {llvm::" << DirLang.getCppNamespace()
504        << "::Directive::" << DirLang.getDirectivePrefix()
505        << Dir.getFormattedName() << ",\n";
506     OS << "    {\n";
507     OS << "      llvm::" << DirLang.getCppNamespace() << "::allowedClauses_"
508        << DirLang.getDirectivePrefix() << Dir.getFormattedName() << ",\n";
509     OS << "      llvm::" << DirLang.getCppNamespace() << "::allowedOnceClauses_"
510        << DirLang.getDirectivePrefix() << Dir.getFormattedName() << ",\n";
511     OS << "      llvm::" << DirLang.getCppNamespace()
512        << "::allowedExclusiveClauses_" << DirLang.getDirectivePrefix()
513        << Dir.getFormattedName() << ",\n";
514     OS << "      llvm::" << DirLang.getCppNamespace() << "::requiredClauses_"
515        << DirLang.getDirectivePrefix() << Dir.getFormattedName() << ",\n";
516     OS << "    }\n";
517     OS << "  },\n";
518   }
519 
520   OS << "}\n";
521 }
522 
523 // Generate classes entry for Flang clauses in the Flang parse-tree
524 // If the clause as a non-generic class, no entry is generated.
525 // If the clause does not hold a value, an EMPTY_CLASS is used.
526 // If the clause class is generic then a WRAPPER_CLASS is used. When the value
527 // is optional, the value class is wrapped into a std::optional.
528 void GenerateFlangClauseParserClass(const DirectiveLanguage &DirLang,
529                                     raw_ostream &OS) {
530 
531   IfDefScope Scope("GEN_FLANG_CLAUSE_PARSER_CLASSES", OS);
532 
533   OS << "\n";
534 
535   for (const auto &C : DirLang.getClauses()) {
536     Clause Clause{C};
537     if (!Clause.getFlangClass().empty()) {
538       OS << "WRAPPER_CLASS(" << Clause.getFormattedParserClassName() << ", ";
539       if (Clause.isValueOptional() && Clause.isValueList()) {
540         OS << "std::optional<std::list<" << Clause.getFlangClass() << ">>";
541       } else if (Clause.isValueOptional()) {
542         OS << "std::optional<" << Clause.getFlangClass() << ">";
543       } else if (Clause.isValueList()) {
544         OS << "std::list<" << Clause.getFlangClass() << ">";
545       } else {
546         OS << Clause.getFlangClass();
547       }
548     } else {
549       OS << "EMPTY_CLASS(" << Clause.getFormattedParserClassName();
550     }
551     OS << ");\n";
552   }
553 }
554 
555 // Generate a list of the different clause classes for Flang.
556 void GenerateFlangClauseParserClassList(const DirectiveLanguage &DirLang,
557                                         raw_ostream &OS) {
558 
559   IfDefScope Scope("GEN_FLANG_CLAUSE_PARSER_CLASSES_LIST", OS);
560 
561   OS << "\n";
562   llvm::interleaveComma(DirLang.getClauses(), OS, [&](Record *C) {
563     Clause Clause{C};
564     OS << Clause.getFormattedParserClassName() << "\n";
565   });
566 }
567 
568 // Generate dump node list for the clauses holding a generic class name.
569 void GenerateFlangClauseDump(const DirectiveLanguage &DirLang,
570                              raw_ostream &OS) {
571 
572   IfDefScope Scope("GEN_FLANG_DUMP_PARSE_TREE_CLAUSES", OS);
573 
574   OS << "\n";
575   for (const auto &C : DirLang.getClauses()) {
576     Clause Clause{C};
577     OS << "NODE(" << DirLang.getFlangClauseBaseClass() << ", "
578        << Clause.getFormattedParserClassName() << ")\n";
579   }
580 }
581 
582 // Generate Unparse functions for clauses classes in the Flang parse-tree
583 // If the clause is a non-generic class, no entry is generated.
584 void GenerateFlangClauseUnparse(const DirectiveLanguage &DirLang,
585                                 raw_ostream &OS) {
586 
587   IfDefScope Scope("GEN_FLANG_CLAUSE_UNPARSE", OS);
588 
589   OS << "\n";
590 
591   for (const auto &C : DirLang.getClauses()) {
592     Clause Clause{C};
593     if (!Clause.getFlangClass().empty()) {
594       if (Clause.isValueOptional() && Clause.getDefaultValue().empty()) {
595         OS << "void Unparse(const " << DirLang.getFlangClauseBaseClass()
596            << "::" << Clause.getFormattedParserClassName() << " &x) {\n";
597         OS << "  Word(\"" << Clause.getName().upper() << "\");\n";
598 
599         OS << "  Walk(\"(\", x.v, \")\");\n";
600         OS << "}\n";
601       } else if (Clause.isValueOptional()) {
602         OS << "void Unparse(const " << DirLang.getFlangClauseBaseClass()
603            << "::" << Clause.getFormattedParserClassName() << " &x) {\n";
604         OS << "  Word(\"" << Clause.getName().upper() << "\");\n";
605         OS << "  Put(\"(\");\n";
606         OS << "  if (x.v.has_value())\n";
607         if (Clause.isValueList())
608           OS << "    Walk(x.v, \",\");\n";
609         else
610           OS << "    Walk(x.v);\n";
611         OS << "  else\n";
612         OS << "    Put(\"" << Clause.getDefaultValue() << "\");\n";
613         OS << "  Put(\")\");\n";
614         OS << "}\n";
615       } else {
616         OS << "void Unparse(const " << DirLang.getFlangClauseBaseClass()
617            << "::" << Clause.getFormattedParserClassName() << " &x) {\n";
618         OS << "  Word(\"" << Clause.getName().upper() << "\");\n";
619         OS << "  Put(\"(\");\n";
620         if (Clause.isValueList())
621           OS << "  Walk(x.v, \",\");\n";
622         else
623           OS << "  Walk(x.v);\n";
624         OS << "  Put(\")\");\n";
625         OS << "}\n";
626       }
627     } else {
628       OS << "void Before(const " << DirLang.getFlangClauseBaseClass()
629          << "::" << Clause.getFormattedParserClassName() << " &) { Word(\""
630          << Clause.getName().upper() << "\"); }\n";
631     }
632   }
633 }
634 
635 // Generate check in the Enter functions for clauses classes.
636 void GenerateFlangClauseCheckPrototypes(const DirectiveLanguage &DirLang,
637                                         raw_ostream &OS) {
638 
639   IfDefScope Scope("GEN_FLANG_CLAUSE_CHECK_ENTER", OS);
640 
641   OS << "\n";
642   for (const auto &C : DirLang.getClauses()) {
643     Clause Clause{C};
644     OS << "void Enter(const parser::" << DirLang.getFlangClauseBaseClass()
645        << "::" << Clause.getFormattedParserClassName() << " &);\n";
646   }
647 }
648 
649 // Generate the mapping for clauses between the parser class and the
650 // corresponding clause Kind
651 void GenerateFlangClauseParserKindMap(const DirectiveLanguage &DirLang,
652                                       raw_ostream &OS) {
653 
654   IfDefScope Scope("GEN_FLANG_CLAUSE_PARSER_KIND_MAP", OS);
655 
656   OS << "\n";
657   for (const auto &C : DirLang.getClauses()) {
658     Clause Clause{C};
659     OS << "if constexpr (std::is_same_v<A, parser::"
660        << DirLang.getFlangClauseBaseClass()
661        << "::" << Clause.getFormattedParserClassName();
662     OS << ">)\n";
663     OS << "  return llvm::" << DirLang.getCppNamespace()
664        << "::Clause::" << DirLang.getClausePrefix() << Clause.getFormattedName()
665        << ";\n";
666   }
667 
668   OS << "llvm_unreachable(\"Invalid " << DirLang.getName()
669      << " Parser clause\");\n";
670 }
671 
672 bool compareClauseName(Record *R1, Record *R2) {
673   Clause C1{R1};
674   Clause C2{R2};
675   return (C1.getName() > C2.getName());
676 }
677 
678 // Generate the parser for the clauses.
679 void GenerateFlangClausesParser(const DirectiveLanguage &DirLang,
680                                 raw_ostream &OS) {
681   std::vector<Record *> Clauses = DirLang.getClauses();
682   // Sort clauses in reverse alphabetical order so with clauses with same
683   // beginning, the longer option is tried before.
684   llvm::sort(Clauses, compareClauseName);
685   IfDefScope Scope("GEN_FLANG_CLAUSES_PARSER", OS);
686   OS << "\n";
687   unsigned index = 0;
688   unsigned lastClauseIndex = DirLang.getClauses().size() - 1;
689   OS << "TYPE_PARSER(\n";
690   for (const auto &C : Clauses) {
691     Clause Clause{C};
692     if (Clause.getAliases().empty()) {
693       OS << "  \"" << Clause.getName() << "\"";
694     } else {
695       OS << "  ("
696          << "\"" << Clause.getName() << "\"_tok";
697       for (StringRef alias : Clause.getAliases()) {
698         OS << " || \"" << alias << "\"_tok";
699       }
700       OS << ")";
701     }
702 
703     OS << " >> construct<" << DirLang.getFlangClauseBaseClass()
704        << ">(construct<" << DirLang.getFlangClauseBaseClass()
705        << "::" << Clause.getFormattedParserClassName() << ">(";
706     if (Clause.getFlangClass().empty()) {
707       OS << "))";
708       if (index != lastClauseIndex)
709         OS << " ||";
710       OS << "\n";
711       ++index;
712       continue;
713     }
714 
715     if (Clause.isValueOptional())
716       OS << "maybe(";
717     OS << "parenthesized(";
718 
719     if (!Clause.getPrefix().empty())
720       OS << "\"" << Clause.getPrefix() << ":\" >> ";
721 
722     // The common Flang parser are used directly. Their name is identical to
723     // the Flang class with first letter as lowercase. If the Flang class is
724     // not a common class, we assume there is a specific Parser<>{} with the
725     // Flang class name provided.
726     llvm::SmallString<128> Scratch;
727     StringRef Parser =
728         llvm::StringSwitch<StringRef>(Clause.getFlangClass())
729             .Case("Name", "name")
730             .Case("ScalarIntConstantExpr", "scalarIntConstantExpr")
731             .Case("ScalarIntExpr", "scalarIntExpr")
732             .Case("ScalarLogicalExpr", "scalarLogicalExpr")
733             .Default(("Parser<" + Clause.getFlangClass() + ">{}")
734                          .toStringRef(Scratch));
735     OS << Parser;
736     if (!Clause.getPrefix().empty() && Clause.isPrefixOptional())
737       OS << " || " << Parser;
738     OS << ")"; // close parenthesized(.
739 
740     if (Clause.isValueOptional()) // close maybe(.
741       OS << ")";
742     OS << "))";
743     if (index != lastClauseIndex)
744       OS << " ||";
745     OS << "\n";
746     ++index;
747   }
748   OS << ")\n";
749 }
750 
751 // Generate the implementation section for the enumeration in the directive
752 // language
753 void EmitDirectivesFlangImpl(const DirectiveLanguage &DirLang,
754                              raw_ostream &OS) {
755 
756   GenerateDirectiveClauseSets(DirLang, OS);
757 
758   GenerateDirectiveClauseMap(DirLang, OS);
759 
760   GenerateFlangClauseParserClass(DirLang, OS);
761 
762   GenerateFlangClauseParserClassList(DirLang, OS);
763 
764   GenerateFlangClauseDump(DirLang, OS);
765 
766   GenerateFlangClauseUnparse(DirLang, OS);
767 
768   GenerateFlangClauseCheckPrototypes(DirLang, OS);
769 
770   GenerateFlangClauseParserKindMap(DirLang, OS);
771 
772   GenerateFlangClausesParser(DirLang, OS);
773 }
774 
775 void GenerateClauseClassMacro(const DirectiveLanguage &DirLang,
776                               raw_ostream &OS) {
777   // Generate macros style information for legacy code in clang
778   IfDefScope Scope("GEN_CLANG_CLAUSE_CLASS", OS);
779 
780   OS << "\n";
781 
782   OS << "#ifndef CLAUSE\n";
783   OS << "#define CLAUSE(Enum, Str, Implicit)\n";
784   OS << "#endif\n";
785   OS << "#ifndef CLAUSE_CLASS\n";
786   OS << "#define CLAUSE_CLASS(Enum, Str, Class)\n";
787   OS << "#endif\n";
788   OS << "#ifndef CLAUSE_NO_CLASS\n";
789   OS << "#define CLAUSE_NO_CLASS(Enum, Str)\n";
790   OS << "#endif\n";
791   OS << "\n";
792   OS << "#define __CLAUSE(Name, Class)                      \\\n";
793   OS << "  CLAUSE(" << DirLang.getClausePrefix()
794      << "##Name, #Name, /* Implicit */ false) \\\n";
795   OS << "  CLAUSE_CLASS(" << DirLang.getClausePrefix()
796      << "##Name, #Name, Class)\n";
797   OS << "#define __CLAUSE_NO_CLASS(Name)                    \\\n";
798   OS << "  CLAUSE(" << DirLang.getClausePrefix()
799      << "##Name, #Name, /* Implicit */ false) \\\n";
800   OS << "  CLAUSE_NO_CLASS(" << DirLang.getClausePrefix() << "##Name, #Name)\n";
801   OS << "#define __IMPLICIT_CLAUSE_CLASS(Name, Str, Class)  \\\n";
802   OS << "  CLAUSE(" << DirLang.getClausePrefix()
803      << "##Name, Str, /* Implicit */ true)    \\\n";
804   OS << "  CLAUSE_CLASS(" << DirLang.getClausePrefix()
805      << "##Name, Str, Class)\n";
806   OS << "#define __IMPLICIT_CLAUSE_NO_CLASS(Name, Str)      \\\n";
807   OS << "  CLAUSE(" << DirLang.getClausePrefix()
808      << "##Name, Str, /* Implicit */ true)    \\\n";
809   OS << "  CLAUSE_NO_CLASS(" << DirLang.getClausePrefix() << "##Name, Str)\n";
810   OS << "\n";
811 
812   for (const auto &R : DirLang.getClauses()) {
813     Clause C{R};
814     if (C.getClangClass().empty()) { // NO_CLASS
815       if (C.isImplicit()) {
816         OS << "__IMPLICIT_CLAUSE_NO_CLASS(" << C.getFormattedName() << ", \""
817            << C.getFormattedName() << "\")\n";
818       } else {
819         OS << "__CLAUSE_NO_CLASS(" << C.getFormattedName() << ")\n";
820       }
821     } else { // CLASS
822       if (C.isImplicit()) {
823         OS << "__IMPLICIT_CLAUSE_CLASS(" << C.getFormattedName() << ", \""
824            << C.getFormattedName() << "\", " << C.getClangClass() << ")\n";
825       } else {
826         OS << "__CLAUSE(" << C.getFormattedName() << ", " << C.getClangClass()
827            << ")\n";
828       }
829     }
830   }
831 
832   OS << "\n";
833   OS << "#undef __IMPLICIT_CLAUSE_NO_CLASS\n";
834   OS << "#undef __IMPLICIT_CLAUSE_CLASS\n";
835   OS << "#undef __CLAUSE\n";
836   OS << "#undef CLAUSE_NO_CLASS\n";
837   OS << "#undef CLAUSE_CLASS\n";
838   OS << "#undef CLAUSE\n";
839 }
840 
841 // Generate the implemenation for the enumeration in the directive
842 // language. This code can be included in library.
843 void EmitDirectivesBasicImpl(const DirectiveLanguage &DirLang,
844                              raw_ostream &OS) {
845   IfDefScope Scope("GEN_DIRECTIVES_IMPL", OS);
846 
847   // getDirectiveKind(StringRef Str)
848   GenerateGetKind(DirLang.getDirectives(), OS, "Directive", DirLang,
849                   DirLang.getDirectivePrefix(), /*ImplicitAsUnknown=*/false);
850 
851   // getDirectiveName(Directive Kind)
852   GenerateGetName(DirLang.getDirectives(), OS, "Directive", DirLang,
853                   DirLang.getDirectivePrefix());
854 
855   // getClauseKind(StringRef Str)
856   GenerateGetKind(DirLang.getClauses(), OS, "Clause", DirLang,
857                   DirLang.getClausePrefix(),
858                   /*ImplicitAsUnknown=*/true);
859 
860   // getClauseName(Clause Kind)
861   GenerateGetName(DirLang.getClauses(), OS, "Clause", DirLang,
862                   DirLang.getClausePrefix());
863 
864   // get<ClauseVal>Kind(StringRef Str)
865   GenerateGetKindClauseVal(DirLang, OS);
866 
867   // isAllowedClauseForDirective(Directive D, Clause C, unsigned Version)
868   GenerateIsAllowedClause(DirLang, OS);
869 }
870 
871 // Generate the implemenation section for the enumeration in the directive
872 // language.
873 void EmitDirectivesImpl(RecordKeeper &Records, raw_ostream &OS) {
874   const auto DirLang = DirectiveLanguage{Records};
875   if (DirLang.HasValidityErrors())
876     return;
877 
878   EmitDirectivesFlangImpl(DirLang, OS);
879 
880   GenerateClauseClassMacro(DirLang, OS);
881 
882   EmitDirectivesBasicImpl(DirLang, OS);
883 }
884 
885 } // namespace llvm
886