xref: /llvm-project/clang/utils/TableGen/ClangAttrEmitter.cpp (revision 4018317407006b2c632fbb75729de624a2426439)
1 //===-- ClangAttrEmitter.cpp - Generate Clang attribute handling ----------===//
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 // These tablegen backends emit Clang attribute processing code
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "TableGenBackends.h"
14 #include "ASTTableGen.h"
15 
16 #include "llvm/ADT/ArrayRef.h"
17 #include "llvm/ADT/DenseMap.h"
18 #include "llvm/ADT/DenseSet.h"
19 #include "llvm/ADT/MapVector.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/ADT/SmallString.h"
22 #include "llvm/ADT/StringExtras.h"
23 #include "llvm/ADT/StringRef.h"
24 #include "llvm/ADT/StringSwitch.h"
25 #include "llvm/Support/ErrorHandling.h"
26 #include "llvm/Support/raw_ostream.h"
27 #include "llvm/TableGen/Error.h"
28 #include "llvm/TableGen/Record.h"
29 #include "llvm/TableGen/StringMatcher.h"
30 #include "llvm/TableGen/TableGenBackend.h"
31 #include <cassert>
32 #include <cctype>
33 #include <cstddef>
34 #include <cstdint>
35 #include <map>
36 #include <memory>
37 #include <optional>
38 #include <set>
39 #include <string>
40 #include <utility>
41 #include <vector>
42 
43 using namespace llvm;
44 
45 namespace {
46 
47 class FlattenedSpelling {
48   StringRef V, N, NS;
49   bool K = false;
50   const Record &OriginalSpelling;
51 
52 public:
53   FlattenedSpelling(StringRef Variety, StringRef Name, StringRef Namespace,
54                     bool KnownToGCC, const Record &OriginalSpelling)
55       : V(Variety), N(Name), NS(Namespace), K(KnownToGCC),
56         OriginalSpelling(OriginalSpelling) {}
57   explicit FlattenedSpelling(const Record &Spelling)
58       : V(Spelling.getValueAsString("Variety")),
59         N(Spelling.getValueAsString("Name")), OriginalSpelling(Spelling) {
60     assert(V != "GCC" && V != "Clang" &&
61            "Given a GCC spelling, which means this hasn't been flattened!");
62     if (V == "CXX11" || V == "C23" || V == "Pragma")
63       NS = Spelling.getValueAsString("Namespace");
64   }
65 
66   StringRef variety() const { return V; }
67   StringRef name() const { return N; }
68   StringRef nameSpace() const { return NS; }
69   bool knownToGCC() const { return K; }
70   const Record &getSpellingRecord() const { return OriginalSpelling; }
71 };
72 
73 struct FlattenedSpellingInfo {
74   FlattenedSpellingInfo(StringRef Syntax, StringRef Scope,
75                         const std::string &TargetTest, uint32_t ArgMask)
76       : Syntax(Syntax), Scope(Scope), TargetTest(TargetTest), ArgMask(ArgMask) {
77   }
78   StringRef Syntax;
79   StringRef Scope;
80   std::string TargetTest;
81   uint32_t ArgMask;
82 };
83 using FSIVecTy = std::vector<FlattenedSpellingInfo>;
84 
85 } // end anonymous namespace
86 
87 static bool GenerateTargetSpecificAttrChecks(const Record *R,
88                                              std::vector<StringRef> &Arches,
89                                              std::string &Test,
90                                              std::string *FnName);
91 static bool isStringLiteralArgument(const Record *Arg);
92 static bool isVariadicStringLiteralArgument(const Record *Arg);
93 
94 static std::vector<FlattenedSpelling>
95 GetFlattenedSpellings(const Record &Attr) {
96   std::vector<FlattenedSpelling> Ret;
97 
98   for (const auto &Spelling : Attr.getValueAsListOfDefs("Spellings")) {
99     StringRef Variety = Spelling->getValueAsString("Variety");
100     StringRef Name = Spelling->getValueAsString("Name");
101     if (Variety == "GCC") {
102       Ret.emplace_back("GNU", Name, "", true, *Spelling);
103       Ret.emplace_back("CXX11", Name, "gnu", true, *Spelling);
104       if (Spelling->getValueAsBit("AllowInC"))
105         Ret.emplace_back("C23", Name, "gnu", true, *Spelling);
106     } else if (Variety == "Clang") {
107       Ret.emplace_back("GNU", Name, "", false, *Spelling);
108       Ret.emplace_back("CXX11", Name, "clang", false, *Spelling);
109       if (Spelling->getValueAsBit("AllowInC"))
110         Ret.emplace_back("C23", Name, "clang", false, *Spelling);
111     } else {
112       Ret.push_back(FlattenedSpelling(*Spelling));
113     }
114   }
115 
116   return Ret;
117 }
118 
119 static std::string ReadPCHRecord(StringRef type) {
120   return StringSwitch<std::string>(type)
121       .EndsWith("Decl *", "Record.readDeclAs<" + type.drop_back().str() + ">()")
122       .Case("TypeSourceInfo *", "Record.readTypeSourceInfo()")
123       .Case("Expr *", "Record.readExpr()")
124       .Case("IdentifierInfo *", "Record.readIdentifier()")
125       .Case("StringRef", "Record.readString()")
126       .Case("ParamIdx", "ParamIdx::deserialize(Record.readInt())")
127       .Case("OMPTraitInfo *", "Record.readOMPTraitInfo()")
128       .Default("Record.readInt()");
129 }
130 
131 // Get a type that is suitable for storing an object of the specified type.
132 static StringRef getStorageType(StringRef type) {
133   return StringSwitch<StringRef>(type)
134     .Case("StringRef", "std::string")
135     .Default(type);
136 }
137 
138 // Assumes that the way to get the value is SA->getname()
139 static std::string WritePCHRecord(StringRef type, StringRef name) {
140   return "Record." +
141          StringSwitch<std::string>(type)
142              .EndsWith("Decl *", "AddDeclRef(" + name.str() + ");\n")
143              .Case("TypeSourceInfo *",
144                    "AddTypeSourceInfo(" + name.str() + ");\n")
145              .Case("Expr *", "AddStmt(" + name.str() + ");\n")
146              .Case("IdentifierInfo *",
147                    "AddIdentifierRef(" + name.str() + ");\n")
148              .Case("StringRef", "AddString(" + name.str() + ");\n")
149              .Case("ParamIdx", "push_back(" + name.str() + ".serialize());\n")
150              .Case("OMPTraitInfo *", "writeOMPTraitInfo(" + name.str() + ");\n")
151              .Default("push_back(" + name.str() + ");\n");
152 }
153 
154 // Normalize attribute name by removing leading and trailing
155 // underscores. For example, __foo, foo__, __foo__ would
156 // become foo.
157 static StringRef NormalizeAttrName(StringRef AttrName) {
158   AttrName.consume_front("__");
159   AttrName.consume_back("__");
160   return AttrName;
161 }
162 
163 // Normalize the name by removing any and all leading and trailing underscores.
164 // This is different from NormalizeAttrName in that it also handles names like
165 // _pascal and __pascal.
166 static StringRef NormalizeNameForSpellingComparison(StringRef Name) {
167   return Name.trim("_");
168 }
169 
170 // Normalize the spelling of a GNU attribute (i.e. "x" in "__attribute__((x))"),
171 // removing "__" if it appears at the beginning and end of the attribute's name.
172 static StringRef NormalizeGNUAttrSpelling(StringRef AttrSpelling) {
173   if (AttrSpelling.starts_with("__") && AttrSpelling.ends_with("__")) {
174     AttrSpelling = AttrSpelling.substr(2, AttrSpelling.size() - 4);
175   }
176 
177   return AttrSpelling;
178 }
179 
180 typedef std::vector<std::pair<std::string, const Record *>> ParsedAttrMap;
181 
182 static ParsedAttrMap getParsedAttrList(const RecordKeeper &Records,
183                                        ParsedAttrMap *Dupes = nullptr,
184                                        bool SemaOnly = true) {
185   std::set<std::string> Seen;
186   ParsedAttrMap R;
187   for (const Record *Attr : Records.getAllDerivedDefinitions("Attr")) {
188     if (!SemaOnly || Attr->getValueAsBit("SemaHandler")) {
189       std::string AN;
190       if (Attr->isSubClassOf("TargetSpecificAttr") &&
191           !Attr->isValueUnset("ParseKind")) {
192         AN = Attr->getValueAsString("ParseKind").str();
193 
194         // If this attribute has already been handled, it does not need to be
195         // handled again.
196         if (!Seen.insert(AN).second) {
197           if (Dupes)
198             Dupes->push_back(std::make_pair(AN, Attr));
199           continue;
200         }
201       } else
202         AN = NormalizeAttrName(Attr->getName()).str();
203 
204       R.push_back(std::make_pair(AN, Attr));
205     }
206   }
207   return R;
208 }
209 
210 namespace {
211 
212   class Argument {
213     std::string lowerName, upperName;
214     StringRef attrName;
215     bool isOpt;
216     bool Fake;
217 
218   public:
219     Argument(StringRef Arg, StringRef Attr)
220         : lowerName(Arg.str()), upperName(lowerName), attrName(Attr),
221           isOpt(false), Fake(false) {
222       if (!lowerName.empty()) {
223         lowerName[0] = std::tolower(lowerName[0]);
224         upperName[0] = std::toupper(upperName[0]);
225       }
226       // Work around MinGW's macro definition of 'interface' to 'struct'. We
227       // have an attribute argument called 'Interface', so only the lower case
228       // name conflicts with the macro definition.
229       if (lowerName == "interface")
230         lowerName = "interface_";
231     }
232     Argument(const Record &Arg, StringRef Attr)
233         : Argument(Arg.getValueAsString("Name"), Attr) {}
234     virtual ~Argument() = default;
235 
236     StringRef getLowerName() const { return lowerName; }
237     StringRef getUpperName() const { return upperName; }
238     StringRef getAttrName() const { return attrName; }
239 
240     bool isOptional() const { return isOpt; }
241     void setOptional(bool set) { isOpt = set; }
242 
243     bool isFake() const { return Fake; }
244     void setFake(bool fake) { Fake = fake; }
245 
246     // These functions print the argument contents formatted in different ways.
247     virtual void writeAccessors(raw_ostream &OS) const = 0;
248     virtual void writeAccessorDefinitions(raw_ostream &OS) const {}
249     virtual void writeASTVisitorTraversal(raw_ostream &OS) const {}
250     virtual void writeCloneArgs(raw_ostream &OS) const = 0;
251     virtual void writeTemplateInstantiationArgs(raw_ostream &OS) const = 0;
252     virtual void writeTemplateInstantiation(raw_ostream &OS) const {}
253     virtual void writeCtorBody(raw_ostream &OS) const {}
254     virtual void writeCtorInitializers(raw_ostream &OS) const = 0;
255     virtual void writeCtorDefaultInitializers(raw_ostream &OS) const = 0;
256     virtual void writeCtorParameters(raw_ostream &OS) const = 0;
257     virtual void writeDeclarations(raw_ostream &OS) const = 0;
258     virtual void writePCHReadArgs(raw_ostream &OS) const = 0;
259     virtual void writePCHReadDecls(raw_ostream &OS) const = 0;
260     virtual void writePCHWrite(raw_ostream &OS) const = 0;
261     virtual std::string getIsOmitted() const { return "false"; }
262     virtual void writeValue(raw_ostream &OS) const = 0;
263     virtual void writeDump(raw_ostream &OS) const = 0;
264     virtual void writeDumpChildren(raw_ostream &OS) const {}
265     virtual void writeHasChildren(raw_ostream &OS) const { OS << "false"; }
266 
267     virtual bool isEnumArg() const { return false; }
268     virtual bool isVariadicEnumArg() const { return false; }
269     virtual bool isVariadic() const { return false; }
270 
271     virtual void writeImplicitCtorArgs(raw_ostream &OS) const {
272       OS << getUpperName();
273     }
274   };
275 
276   class SimpleArgument : public Argument {
277     std::string type;
278 
279   public:
280     SimpleArgument(const Record &Arg, StringRef Attr, std::string T)
281         : Argument(Arg, Attr), type(std::move(T)) {}
282 
283     std::string getType() const { return type; }
284 
285     void writeAccessors(raw_ostream &OS) const override {
286       OS << "  " << type << " get" << getUpperName() << "() const {\n";
287       OS << "    return " << getLowerName() << ";\n";
288       OS << "  }";
289     }
290 
291     void writeCloneArgs(raw_ostream &OS) const override {
292       OS << getLowerName();
293     }
294 
295     void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
296       OS << "A->get" << getUpperName() << "()";
297     }
298 
299     void writeCtorInitializers(raw_ostream &OS) const override {
300       OS << getLowerName() << "(" << getUpperName() << ")";
301     }
302 
303     void writeCtorDefaultInitializers(raw_ostream &OS) const override {
304       OS << getLowerName() << "()";
305     }
306 
307     void writeCtorParameters(raw_ostream &OS) const override {
308       OS << type << " " << getUpperName();
309     }
310 
311     void writeDeclarations(raw_ostream &OS) const override {
312       OS << type << " " << getLowerName() << ";";
313     }
314 
315     void writePCHReadDecls(raw_ostream &OS) const override {
316       std::string read = ReadPCHRecord(type);
317       OS << "    " << type << " " << getLowerName() << " = " << read << ";\n";
318     }
319 
320     void writePCHReadArgs(raw_ostream &OS) const override {
321       OS << getLowerName();
322     }
323 
324     void writePCHWrite(raw_ostream &OS) const override {
325       OS << "    "
326          << WritePCHRecord(type, "SA->get" + getUpperName().str() + "()");
327     }
328 
329     std::string getIsOmitted() const override {
330       auto IsOneOf = [](StringRef subject, auto... list) {
331         return ((subject == list) || ...);
332       };
333 
334       if (IsOneOf(type, "IdentifierInfo *", "Expr *"))
335         return "!get" + getUpperName().str() + "()";
336       if (IsOneOf(type, "TypeSourceInfo *"))
337         return "!get" + getUpperName().str() + "Loc()";
338       if (IsOneOf(type, "ParamIdx"))
339         return "!get" + getUpperName().str() + "().isValid()";
340 
341       assert(IsOneOf(type, "unsigned", "int", "bool", "FunctionDecl *",
342                      "VarDecl *"));
343       return "false";
344     }
345 
346     void writeValue(raw_ostream &OS) const override {
347       if (type == "FunctionDecl *")
348         OS << "\" << get" << getUpperName()
349            << "()->getNameInfo().getAsString() << \"";
350       else if (type == "IdentifierInfo *")
351         // Some non-optional (comma required) identifier arguments can be the
352         // empty string but are then recorded as a nullptr.
353         OS << "\" << (get" << getUpperName() << "() ? get" << getUpperName()
354            << "()->getName() : \"\") << \"";
355       else if (type == "VarDecl *")
356         OS << "\" << get" << getUpperName() << "()->getName() << \"";
357       else if (type == "TypeSourceInfo *")
358         OS << "\" << get" << getUpperName() << "().getAsString() << \"";
359       else if (type == "ParamIdx")
360         OS << "\" << get" << getUpperName() << "().getSourceIndex() << \"";
361       else
362         OS << "\" << get" << getUpperName() << "() << \"";
363     }
364 
365     void writeDump(raw_ostream &OS) const override {
366       if (StringRef(type).ends_with("Decl *")) {
367         OS << "    OS << \" \";\n";
368         OS << "    dumpBareDeclRef(SA->get" << getUpperName() << "());\n";
369       } else if (type == "IdentifierInfo *") {
370         // Some non-optional (comma required) identifier arguments can be the
371         // empty string but are then recorded as a nullptr.
372         OS << "    if (SA->get" << getUpperName() << "())\n"
373            << "      OS << \" \" << SA->get" << getUpperName()
374            << "()->getName();\n";
375       } else if (type == "TypeSourceInfo *") {
376         if (isOptional())
377           OS << "    if (SA->get" << getUpperName() << "Loc())";
378         OS << "    OS << \" \" << SA->get" << getUpperName()
379            << "().getAsString();\n";
380       } else if (type == "bool") {
381         OS << "    if (SA->get" << getUpperName() << "()) OS << \" "
382            << getUpperName() << "\";\n";
383       } else if (type == "int" || type == "unsigned") {
384         OS << "    OS << \" \" << SA->get" << getUpperName() << "();\n";
385       } else if (type == "ParamIdx") {
386         if (isOptional())
387           OS << "    if (SA->get" << getUpperName() << "().isValid())\n  ";
388         OS << "    OS << \" \" << SA->get" << getUpperName()
389            << "().getSourceIndex();\n";
390       } else if (type == "OMPTraitInfo *") {
391         OS << "    OS << \" \" << SA->get" << getUpperName() << "();\n";
392       } else {
393         llvm_unreachable("Unknown SimpleArgument type!");
394       }
395     }
396   };
397 
398   class DefaultSimpleArgument : public SimpleArgument {
399     int64_t Default;
400 
401   public:
402     DefaultSimpleArgument(const Record &Arg, StringRef Attr,
403                           std::string T, int64_t Default)
404       : SimpleArgument(Arg, Attr, T), Default(Default) {}
405 
406     void writeAccessors(raw_ostream &OS) const override {
407       SimpleArgument::writeAccessors(OS);
408 
409       OS << "\n\n  static const " << getType() << " Default" << getUpperName()
410          << " = ";
411       if (getType() == "bool")
412         OS << (Default != 0 ? "true" : "false");
413       else
414         OS << Default;
415       OS << ";";
416     }
417   };
418 
419   class StringArgument : public Argument {
420   public:
421     StringArgument(const Record &Arg, StringRef Attr)
422       : Argument(Arg, Attr)
423     {}
424 
425     void writeAccessors(raw_ostream &OS) const override {
426       OS << "  llvm::StringRef get" << getUpperName() << "() const {\n";
427       OS << "    return llvm::StringRef(" << getLowerName() << ", "
428          << getLowerName() << "Length);\n";
429       OS << "  }\n";
430       OS << "  unsigned get" << getUpperName() << "Length() const {\n";
431       OS << "    return " << getLowerName() << "Length;\n";
432       OS << "  }\n";
433       OS << "  void set" << getUpperName()
434          << "(ASTContext &C, llvm::StringRef S) {\n";
435       OS << "    " << getLowerName() << "Length = S.size();\n";
436       OS << "    this->" << getLowerName() << " = new (C, 1) char ["
437          << getLowerName() << "Length];\n";
438       OS << "    if (!S.empty())\n";
439       OS << "      std::memcpy(this->" << getLowerName() << ", S.data(), "
440          << getLowerName() << "Length);\n";
441       OS << "  }";
442     }
443 
444     void writeCloneArgs(raw_ostream &OS) const override {
445       OS << "get" << getUpperName() << "()";
446     }
447 
448     void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
449       OS << "A->get" << getUpperName() << "()";
450     }
451 
452     void writeCtorBody(raw_ostream &OS) const override {
453       OS << "    if (!" << getUpperName() << ".empty())\n";
454       OS << "      std::memcpy(" << getLowerName() << ", " << getUpperName()
455          << ".data(), " << getLowerName() << "Length);\n";
456     }
457 
458     void writeCtorInitializers(raw_ostream &OS) const override {
459       OS << getLowerName() << "Length(" << getUpperName() << ".size()),"
460          << getLowerName() << "(new (Ctx, 1) char[" << getLowerName()
461          << "Length])";
462     }
463 
464     void writeCtorDefaultInitializers(raw_ostream &OS) const override {
465       OS << getLowerName() << "Length(0)," << getLowerName() << "(nullptr)";
466     }
467 
468     void writeCtorParameters(raw_ostream &OS) const override {
469       OS << "llvm::StringRef " << getUpperName();
470     }
471 
472     void writeDeclarations(raw_ostream &OS) const override {
473       OS << "unsigned " << getLowerName() << "Length;\n";
474       OS << "char *" << getLowerName() << ";";
475     }
476 
477     void writePCHReadDecls(raw_ostream &OS) const override {
478       OS << "    std::string " << getLowerName()
479          << "= Record.readString();\n";
480     }
481 
482     void writePCHReadArgs(raw_ostream &OS) const override {
483       OS << getLowerName();
484     }
485 
486     void writePCHWrite(raw_ostream &OS) const override {
487       OS << "    Record.AddString(SA->get" << getUpperName() << "());\n";
488     }
489 
490     void writeValue(raw_ostream &OS) const override {
491       OS << "\\\"\" << get" << getUpperName() << "() << \"\\\"";
492     }
493 
494     void writeDump(raw_ostream &OS) const override {
495       OS << "    OS << \" \\\"\" << SA->get" << getUpperName()
496          << "() << \"\\\"\";\n";
497     }
498   };
499 
500   class AlignedArgument : public Argument {
501   public:
502     AlignedArgument(const Record &Arg, StringRef Attr)
503       : Argument(Arg, Attr)
504     {}
505 
506     void writeAccessors(raw_ostream &OS) const override {
507       OS << "  bool is" << getUpperName() << "Dependent() const;\n";
508       OS << "  bool is" << getUpperName() << "ErrorDependent() const;\n";
509 
510       OS << "  unsigned get" << getUpperName() << "(ASTContext &Ctx) const;\n";
511 
512       OS << "  bool is" << getUpperName() << "Expr() const {\n";
513       OS << "    return is" << getLowerName() << "Expr;\n";
514       OS << "  }\n";
515 
516       OS << "  Expr *get" << getUpperName() << "Expr() const {\n";
517       OS << "    assert(is" << getLowerName() << "Expr);\n";
518       OS << "    return " << getLowerName() << "Expr;\n";
519       OS << "  }\n";
520 
521       OS << "  TypeSourceInfo *get" << getUpperName() << "Type() const {\n";
522       OS << "    assert(!is" << getLowerName() << "Expr);\n";
523       OS << "    return " << getLowerName() << "Type;\n";
524       OS << "  }";
525 
526       OS << "  std::optional<unsigned> getCached" << getUpperName()
527          << "Value() const {\n";
528       OS << "    return " << getLowerName() << "Cache;\n";
529       OS << "  }";
530 
531       OS << "  void setCached" << getUpperName()
532          << "Value(unsigned AlignVal) {\n";
533       OS << "    " << getLowerName() << "Cache = AlignVal;\n";
534       OS << "  }";
535     }
536 
537     void writeAccessorDefinitions(raw_ostream &OS) const override {
538       OS << "bool " << getAttrName() << "Attr::is" << getUpperName()
539          << "Dependent() const {\n";
540       OS << "  if (is" << getLowerName() << "Expr)\n";
541       OS << "    return " << getLowerName() << "Expr && (" << getLowerName()
542          << "Expr->isValueDependent() || " << getLowerName()
543          << "Expr->isTypeDependent());\n";
544       OS << "  else\n";
545       OS << "    return " << getLowerName()
546          << "Type->getType()->isDependentType();\n";
547       OS << "}\n";
548 
549       OS << "bool " << getAttrName() << "Attr::is" << getUpperName()
550          << "ErrorDependent() const {\n";
551       OS << "  if (is" << getLowerName() << "Expr)\n";
552       OS << "    return " << getLowerName() << "Expr && " << getLowerName()
553          << "Expr->containsErrors();\n";
554       OS << "  return " << getLowerName()
555          << "Type->getType()->containsErrors();\n";
556       OS << "}\n";
557     }
558 
559     void writeASTVisitorTraversal(raw_ostream &OS) const override {
560       StringRef Name = getUpperName();
561       OS << "  if (A->is" << Name << "Expr()) {\n"
562          << "    if (!getDerived().TraverseStmt(A->get" << Name << "Expr()))\n"
563          << "      return false;\n"
564          << "  } else if (auto *TSI = A->get" << Name << "Type()) {\n"
565          << "    if (!getDerived().TraverseTypeLoc(TSI->getTypeLoc()))\n"
566          << "      return false;\n"
567          << "  }\n";
568     }
569 
570     void writeCloneArgs(raw_ostream &OS) const override {
571       OS << "is" << getLowerName() << "Expr, is" << getLowerName()
572          << "Expr ? static_cast<void*>(" << getLowerName()
573          << "Expr) : " << getLowerName()
574          << "Type";
575     }
576 
577     void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
578       // FIXME: move the definition in Sema::InstantiateAttrs to here.
579       // In the meantime, aligned attributes are cloned.
580     }
581 
582     void writeCtorBody(raw_ostream &OS) const override {
583       OS << "    if (is" << getLowerName() << "Expr)\n";
584       OS << "       " << getLowerName() << "Expr = reinterpret_cast<Expr *>("
585          << getUpperName() << ");\n";
586       OS << "    else\n";
587       OS << "       " << getLowerName()
588          << "Type = reinterpret_cast<TypeSourceInfo *>(" << getUpperName()
589          << ");\n";
590     }
591 
592     void writeCtorInitializers(raw_ostream &OS) const override {
593       OS << "is" << getLowerName() << "Expr(Is" << getUpperName() << "Expr)";
594     }
595 
596     void writeCtorDefaultInitializers(raw_ostream &OS) const override {
597       OS << "is" << getLowerName() << "Expr(false)";
598     }
599 
600     void writeCtorParameters(raw_ostream &OS) const override {
601       OS << "bool Is" << getUpperName() << "Expr, void *" << getUpperName();
602     }
603 
604     void writeImplicitCtorArgs(raw_ostream &OS) const override {
605       OS << "Is" << getUpperName() << "Expr, " << getUpperName();
606     }
607 
608     void writeDeclarations(raw_ostream &OS) const override {
609       OS << "bool is" << getLowerName() << "Expr;\n";
610       OS << "union {\n";
611       OS << "Expr *" << getLowerName() << "Expr;\n";
612       OS << "TypeSourceInfo *" << getLowerName() << "Type;\n";
613       OS << "};\n";
614       OS << "std::optional<unsigned> " << getLowerName() << "Cache;\n";
615     }
616 
617     void writePCHReadArgs(raw_ostream &OS) const override {
618       OS << "is" << getLowerName() << "Expr, " << getLowerName() << "Ptr";
619     }
620 
621     void writePCHReadDecls(raw_ostream &OS) const override {
622       OS << "    bool is" << getLowerName() << "Expr = Record.readInt();\n";
623       OS << "    void *" << getLowerName() << "Ptr;\n";
624       OS << "    if (is" << getLowerName() << "Expr)\n";
625       OS << "      " << getLowerName() << "Ptr = Record.readExpr();\n";
626       OS << "    else\n";
627       OS << "      " << getLowerName()
628          << "Ptr = Record.readTypeSourceInfo();\n";
629     }
630 
631     void writePCHWrite(raw_ostream &OS) const override {
632       OS << "    Record.push_back(SA->is" << getUpperName() << "Expr());\n";
633       OS << "    if (SA->is" << getUpperName() << "Expr())\n";
634       OS << "      Record.AddStmt(SA->get" << getUpperName() << "Expr());\n";
635       OS << "    else\n";
636       OS << "      Record.AddTypeSourceInfo(SA->get" << getUpperName()
637          << "Type());\n";
638     }
639 
640     std::string getIsOmitted() const override {
641       return "!((is" + getLowerName().str() + "Expr && " +
642              getLowerName().str() + "Expr) || (!is" + getLowerName().str() +
643              "Expr && " + getLowerName().str() + "Type))";
644     }
645 
646     void writeValue(raw_ostream &OS) const override {
647       OS << "\";\n";
648       OS << "    if (is" << getLowerName() << "Expr && " << getLowerName()
649          << "Expr)";
650       OS << "      " << getLowerName()
651          << "Expr->printPretty(OS, nullptr, Policy);\n";
652       OS << "    if (!is" << getLowerName() << "Expr && " << getLowerName()
653          << "Type)";
654       OS << "      " << getLowerName()
655          << "Type->getType().print(OS, Policy);\n";
656       OS << "    OS << \"";
657     }
658 
659     void writeDump(raw_ostream &OS) const override {
660       OS << "    if (!SA->is" << getUpperName() << "Expr())\n";
661       OS << "      dumpType(SA->get" << getUpperName()
662          << "Type()->getType());\n";
663     }
664 
665     void writeDumpChildren(raw_ostream &OS) const override {
666       OS << "    if (SA->is" << getUpperName() << "Expr())\n";
667       OS << "      Visit(SA->get" << getUpperName() << "Expr());\n";
668     }
669 
670     void writeHasChildren(raw_ostream &OS) const override {
671       OS << "SA->is" << getUpperName() << "Expr()";
672     }
673   };
674 
675   class VariadicArgument : public Argument {
676     std::string Type, ArgName, ArgSizeName, RangeName;
677 
678   protected:
679     // Assumed to receive a parameter: raw_ostream OS.
680     virtual void writeValueImpl(raw_ostream &OS) const {
681       OS << "    OS << Val;\n";
682     }
683     // Assumed to receive a parameter: raw_ostream OS.
684     virtual void writeDumpImpl(raw_ostream &OS) const {
685       OS << "      OS << \" \" << Val;\n";
686     }
687 
688   public:
689     VariadicArgument(const Record &Arg, StringRef Attr, std::string T)
690         : Argument(Arg, Attr), Type(std::move(T)),
691           ArgName(getLowerName().str() + "_"), ArgSizeName(ArgName + "Size"),
692           RangeName(getLowerName().str()) {}
693 
694     VariadicArgument(StringRef Arg, StringRef Attr, std::string T)
695         : Argument(Arg, Attr), Type(std::move(T)),
696           ArgName(getLowerName().str() + "_"), ArgSizeName(ArgName + "Size"),
697           RangeName(getLowerName().str()) {}
698 
699     const std::string &getType() const { return Type; }
700     const std::string &getArgName() const { return ArgName; }
701     const std::string &getArgSizeName() const { return ArgSizeName; }
702     bool isVariadic() const override { return true; }
703 
704     void writeAccessors(raw_ostream &OS) const override {
705       std::string IteratorType = getLowerName().str() + "_iterator";
706       std::string BeginFn = getLowerName().str() + "_begin()";
707       std::string EndFn = getLowerName().str() + "_end()";
708 
709       OS << "  typedef " << Type << "* " << IteratorType << ";\n";
710       OS << "  " << IteratorType << " " << BeginFn << " const {"
711          << " return " << ArgName << "; }\n";
712       OS << "  " << IteratorType << " " << EndFn << " const {"
713          << " return " << ArgName << " + " << ArgSizeName << "; }\n";
714       OS << "  unsigned " << getLowerName() << "_size() const {"
715          << " return " << ArgSizeName << "; }\n";
716       OS << "  llvm::iterator_range<" << IteratorType << "> " << RangeName
717          << "() const { return llvm::make_range(" << BeginFn << ", " << EndFn
718          << "); }\n";
719     }
720 
721     void writeSetter(raw_ostream &OS) const {
722       OS << "  void set" << getUpperName() << "(ASTContext &Ctx, ";
723       writeCtorParameters(OS);
724       OS << ") {\n";
725       OS << "    " << ArgSizeName << " = " << getUpperName() << "Size;\n";
726       OS << "    " << ArgName << " = new (Ctx, 16) " << getType() << "["
727          << ArgSizeName << "];\n";
728       OS << "  ";
729       writeCtorBody(OS);
730       OS << "  }\n";
731     }
732 
733     void writeCloneArgs(raw_ostream &OS) const override {
734       OS << ArgName << ", " << ArgSizeName;
735     }
736 
737     void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
738       // This isn't elegant, but we have to go through public methods...
739       OS << "A->" << getLowerName() << "_begin(), "
740          << "A->" << getLowerName() << "_size()";
741     }
742 
743     void writeASTVisitorTraversal(raw_ostream &OS) const override {
744       // FIXME: Traverse the elements.
745     }
746 
747     void writeCtorBody(raw_ostream &OS) const override {
748       OS << "  std::copy(" << getUpperName() << ", " << getUpperName() << " + "
749          << ArgSizeName << ", " << ArgName << ");\n";
750     }
751 
752     void writeCtorInitializers(raw_ostream &OS) const override {
753       OS << ArgSizeName << "(" << getUpperName() << "Size), "
754          << ArgName << "(new (Ctx, 16) " << getType() << "["
755          << ArgSizeName << "])";
756     }
757 
758     void writeCtorDefaultInitializers(raw_ostream &OS) const override {
759       OS << ArgSizeName << "(0), " << ArgName << "(nullptr)";
760     }
761 
762     void writeCtorParameters(raw_ostream &OS) const override {
763       OS << getType() << " *" << getUpperName() << ", unsigned "
764          << getUpperName() << "Size";
765     }
766 
767     void writeImplicitCtorArgs(raw_ostream &OS) const override {
768       OS << getUpperName() << ", " << getUpperName() << "Size";
769     }
770 
771     void writeDeclarations(raw_ostream &OS) const override {
772       OS << "  unsigned " << ArgSizeName << ";\n";
773       OS << "  " << getType() << " *" << ArgName << ";";
774     }
775 
776     void writePCHReadDecls(raw_ostream &OS) const override {
777       OS << "    unsigned " << getLowerName() << "Size = Record.readInt();\n";
778       OS << "    SmallVector<" << getType() << ", 4> "
779          << getLowerName() << ";\n";
780       OS << "    " << getLowerName() << ".reserve(" << getLowerName()
781          << "Size);\n";
782 
783       // If we can't store the values in the current type (if it's something
784       // like StringRef), store them in a different type and convert the
785       // container afterwards.
786       std::string StorageType = getStorageType(getType()).str();
787       std::string StorageName = getLowerName().str();
788       if (StorageType != getType()) {
789         StorageName += "Storage";
790         OS << "    SmallVector<" << StorageType << ", 4> "
791            << StorageName << ";\n";
792         OS << "    " << StorageName << ".reserve(" << getLowerName()
793            << "Size);\n";
794       }
795 
796       OS << "    for (unsigned i = 0; i != " << getLowerName() << "Size; ++i)\n";
797       std::string read = ReadPCHRecord(Type);
798       OS << "      " << StorageName << ".push_back(" << read << ");\n";
799 
800       if (StorageType != getType()) {
801         OS << "    for (unsigned i = 0; i != " << getLowerName() << "Size; ++i)\n";
802         OS << "      " << getLowerName() << ".push_back("
803            << StorageName << "[i]);\n";
804       }
805     }
806 
807     void writePCHReadArgs(raw_ostream &OS) const override {
808       OS << getLowerName() << ".data(), " << getLowerName() << "Size";
809     }
810 
811     void writePCHWrite(raw_ostream &OS) const override {
812       OS << "    Record.push_back(SA->" << getLowerName() << "_size());\n";
813       OS << "    for (auto &Val : SA->" << RangeName << "())\n";
814       OS << "      " << WritePCHRecord(Type, "Val");
815     }
816 
817     void writeValue(raw_ostream &OS) const override {
818       OS << "\";\n";
819       OS << "  for (const auto &Val : " << RangeName << "()) {\n"
820          << "    DelimitAttributeArgument(OS, IsFirstArgument);\n";
821       writeValueImpl(OS);
822       OS << "  }\n";
823       OS << "  OS << \"";
824     }
825 
826     void writeDump(raw_ostream &OS) const override {
827       OS << "    for (const auto &Val : SA->" << RangeName << "())\n";
828       writeDumpImpl(OS);
829     }
830   };
831 
832   class VariadicOMPInteropInfoArgument : public VariadicArgument {
833   public:
834     VariadicOMPInteropInfoArgument(const Record &Arg, StringRef Attr)
835         : VariadicArgument(Arg, Attr, "OMPInteropInfo") {}
836 
837     void writeDump(raw_ostream &OS) const override {
838       OS << "    for (" << getAttrName() << "Attr::" << getLowerName()
839          << "_iterator I = SA->" << getLowerName() << "_begin(), E = SA->"
840          << getLowerName() << "_end(); I != E; ++I) {\n";
841       OS << "      if (I->IsTarget && I->IsTargetSync)\n";
842       OS << "        OS << \" Target_TargetSync\";\n";
843       OS << "      else if (I->IsTarget)\n";
844       OS << "        OS << \" Target\";\n";
845       OS << "      else\n";
846       OS << "        OS << \" TargetSync\";\n";
847       OS << "    }\n";
848     }
849 
850     void writePCHReadDecls(raw_ostream &OS) const override {
851       OS << "    unsigned " << getLowerName() << "Size = Record.readInt();\n";
852       OS << "    SmallVector<OMPInteropInfo, 4> " << getLowerName() << ";\n";
853       OS << "    " << getLowerName() << ".reserve(" << getLowerName()
854          << "Size);\n";
855       OS << "    for (unsigned I = 0, E = " << getLowerName() << "Size; ";
856       OS << "I != E; ++I) {\n";
857       OS << "      bool IsTarget = Record.readBool();\n";
858       OS << "      bool IsTargetSync = Record.readBool();\n";
859       OS << "      " << getLowerName()
860          << ".emplace_back(IsTarget, IsTargetSync);\n";
861       OS << "    }\n";
862     }
863 
864     void writePCHWrite(raw_ostream &OS) const override {
865       OS << "    Record.push_back(SA->" << getLowerName() << "_size());\n";
866       OS << "    for (" << getAttrName() << "Attr::" << getLowerName()
867          << "_iterator I = SA->" << getLowerName() << "_begin(), E = SA->"
868          << getLowerName() << "_end(); I != E; ++I) {\n";
869       OS << "      Record.writeBool(I->IsTarget);\n";
870       OS << "      Record.writeBool(I->IsTargetSync);\n";
871       OS << "    }\n";
872     }
873   };
874 
875   class VariadicParamIdxArgument : public VariadicArgument {
876   public:
877     VariadicParamIdxArgument(const Record &Arg, StringRef Attr)
878         : VariadicArgument(Arg, Attr, "ParamIdx") {}
879 
880   public:
881     void writeValueImpl(raw_ostream &OS) const override {
882       OS << "    OS << Val.getSourceIndex();\n";
883     }
884 
885     void writeDumpImpl(raw_ostream &OS) const override {
886       OS << "      OS << \" \" << Val.getSourceIndex();\n";
887     }
888   };
889 
890   struct VariadicParamOrParamIdxArgument : public VariadicArgument {
891     VariadicParamOrParamIdxArgument(const Record &Arg, StringRef Attr)
892         : VariadicArgument(Arg, Attr, "int") {}
893   };
894 
895   // Unique the enums, but maintain the original declaration ordering.
896   std::vector<StringRef>
897   uniqueEnumsInOrder(const std::vector<StringRef> &enums) {
898     std::vector<StringRef> uniques;
899     SmallDenseSet<StringRef, 8> unique_set;
900     for (const auto &i : enums) {
901       if (unique_set.insert(i).second)
902         uniques.push_back(i);
903     }
904     return uniques;
905   }
906 
907   class EnumArgument : public Argument {
908     std::string fullType;
909     StringRef shortType;
910     std::vector<StringRef> values, enums, uniques;
911     bool isExternal;
912     bool isCovered;
913 
914   public:
915     EnumArgument(const Record &Arg, StringRef Attr)
916         : Argument(Arg, Attr), values(Arg.getValueAsListOfStrings("Values")),
917           enums(Arg.getValueAsListOfStrings("Enums")),
918           uniques(uniqueEnumsInOrder(enums)),
919           isExternal(Arg.getValueAsBit("IsExternalType")),
920           isCovered(Arg.getValueAsBit("IsCovered")) {
921       StringRef Type = Arg.getValueAsString("Type");
922       shortType = isExternal ? Type.rsplit("::").second : Type;
923       // If shortType didn't contain :: at all rsplit will give us an empty
924       // string.
925       if (shortType.empty())
926         shortType = Type;
927       fullType = isExternal ? Type : (getAttrName() + "Attr::" + Type).str();
928 
929       // FIXME: Emit a proper error
930       assert(!uniques.empty());
931     }
932 
933     bool isEnumArg() const override { return true; }
934 
935     void writeAccessors(raw_ostream &OS) const override {
936       OS << "  " << fullType << " get" << getUpperName() << "() const {\n";
937       OS << "    return " << getLowerName() << ";\n";
938       OS << "  }";
939     }
940 
941     void writeCloneArgs(raw_ostream &OS) const override {
942       OS << getLowerName();
943     }
944 
945     void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
946       OS << "A->get" << getUpperName() << "()";
947     }
948     void writeCtorInitializers(raw_ostream &OS) const override {
949       OS << getLowerName() << "(" << getUpperName() << ")";
950     }
951     void writeCtorDefaultInitializers(raw_ostream &OS) const override {
952       OS << getLowerName() << "(" << fullType << "(0))";
953     }
954     void writeCtorParameters(raw_ostream &OS) const override {
955       OS << fullType << " " << getUpperName();
956     }
957     void writeDeclarations(raw_ostream &OS) const override {
958       if (!isExternal) {
959         auto i = uniques.cbegin(), e = uniques.cend();
960         // The last one needs to not have a comma.
961         --e;
962 
963         OS << "public:\n";
964         OS << "  enum " << shortType << " {\n";
965         for (; i != e; ++i)
966           OS << "    " << *i << ",\n";
967         OS << "    " << *e << "\n";
968         OS << "  };\n";
969       }
970 
971       OS << "private:\n";
972       OS << "  " << fullType << " " << getLowerName() << ";";
973     }
974 
975     void writePCHReadDecls(raw_ostream &OS) const override {
976       OS << "    " << fullType << " " << getLowerName() << "(static_cast<"
977          << fullType << ">(Record.readInt()));\n";
978     }
979 
980     void writePCHReadArgs(raw_ostream &OS) const override {
981       OS << getLowerName();
982     }
983 
984     void writePCHWrite(raw_ostream &OS) const override {
985       OS << "Record.push_back(static_cast<uint64_t>(SA->get" << getUpperName()
986          << "()));\n";
987     }
988 
989     void writeValue(raw_ostream &OS) const override {
990       // FIXME: this isn't 100% correct -- some enum arguments require printing
991       // as a string literal, while others require printing as an identifier.
992       // Tablegen currently does not distinguish between the two forms.
993       OS << "\\\"\" << " << getAttrName() << "Attr::Convert" << shortType
994          << "ToStr(get" << getUpperName() << "()) << \"\\\"";
995     }
996 
997     void writeDump(raw_ostream &OS) const override {
998       OS << "    switch(SA->get" << getUpperName() << "()) {\n";
999       for (const auto &I : uniques) {
1000         OS << "    case " << fullType << "::" << I << ":\n";
1001         OS << "      OS << \" " << I << "\";\n";
1002         OS << "      break;\n";
1003       }
1004       if (!isCovered) {
1005         OS << "    default:\n";
1006         OS << "      llvm_unreachable(\"Invalid attribute value\");\n";
1007       }
1008       OS << "    }\n";
1009     }
1010 
1011     void writeConversion(raw_ostream &OS, bool Header) const {
1012       if (Header) {
1013         OS << "  static bool ConvertStrTo" << shortType << "(StringRef Val, "
1014            << fullType << " &Out);\n";
1015         OS << "  static const char *Convert" << shortType << "ToStr("
1016            << fullType << " Val);\n";
1017         return;
1018       }
1019 
1020       OS << "bool " << getAttrName() << "Attr::ConvertStrTo" << shortType
1021          << "(StringRef Val, " << fullType << " &Out) {\n";
1022       OS << "  std::optional<" << fullType << "> "
1023          << "R = llvm::StringSwitch<std::optional<" << fullType << ">>(Val)\n";
1024       for (size_t I = 0; I < enums.size(); ++I) {
1025         OS << "    .Case(\"" << values[I] << "\", ";
1026         OS << fullType << "::" << enums[I] << ")\n";
1027       }
1028       OS << "    .Default(std::optional<" << fullType << ">());\n";
1029       OS << "  if (R) {\n";
1030       OS << "    Out = *R;\n      return true;\n    }\n";
1031       OS << "  return false;\n";
1032       OS << "}\n\n";
1033 
1034       // Mapping from enumeration values back to enumeration strings isn't
1035       // trivial because some enumeration values have multiple named
1036       // enumerators, such as type_visibility(internal) and
1037       // type_visibility(hidden) both mapping to TypeVisibilityAttr::Hidden.
1038       OS << "const char *" << getAttrName() << "Attr::Convert" << shortType
1039          << "ToStr(" << fullType << " Val) {\n"
1040          << "  switch(Val) {\n";
1041       SmallDenseSet<StringRef, 8> Uniques;
1042       for (size_t I = 0; I < enums.size(); ++I) {
1043         if (Uniques.insert(enums[I]).second)
1044           OS << "  case " << fullType << "::" << enums[I] << ": return \""
1045              << values[I] << "\";\n";
1046       }
1047       if (!isCovered) {
1048         OS << "  default: llvm_unreachable(\"Invalid attribute value\");\n";
1049       }
1050       OS << "  }\n"
1051          << "  llvm_unreachable(\"No enumerator with that value\");\n"
1052          << "}\n";
1053     }
1054   };
1055 
1056   class VariadicEnumArgument: public VariadicArgument {
1057     std::string fullType;
1058     StringRef shortType;
1059     std::vector<StringRef> values, enums, uniques;
1060     bool isExternal;
1061     bool isCovered;
1062 
1063   protected:
1064     void writeValueImpl(raw_ostream &OS) const override {
1065       // FIXME: this isn't 100% correct -- some enum arguments require printing
1066       // as a string literal, while others require printing as an identifier.
1067       // Tablegen currently does not distinguish between the two forms.
1068       OS << "    OS << \"\\\"\" << " << getAttrName() << "Attr::Convert"
1069          << shortType << "ToStr(Val)"
1070          << "<< \"\\\"\";\n";
1071     }
1072 
1073   public:
1074     VariadicEnumArgument(const Record &Arg, StringRef Attr)
1075         : VariadicArgument(Arg, Attr, Arg.getValueAsString("Type").str()),
1076           values(Arg.getValueAsListOfStrings("Values")),
1077           enums(Arg.getValueAsListOfStrings("Enums")),
1078           uniques(uniqueEnumsInOrder(enums)),
1079           isExternal(Arg.getValueAsBit("IsExternalType")),
1080           isCovered(Arg.getValueAsBit("IsCovered")) {
1081       StringRef Type = Arg.getValueAsString("Type");
1082       shortType = isExternal ? Type.rsplit("::").second : Type;
1083       // If shortType didn't contain :: at all rsplit will give us an empty
1084       // string.
1085       if (shortType.empty())
1086         shortType = Type;
1087       fullType = isExternal ? Type : (getAttrName() + "Attr::" + Type).str();
1088 
1089       // FIXME: Emit a proper error
1090       assert(!uniques.empty());
1091     }
1092 
1093     bool isVariadicEnumArg() const override { return true; }
1094 
1095     void writeDeclarations(raw_ostream &OS) const override {
1096       if (!isExternal) {
1097         auto i = uniques.cbegin(), e = uniques.cend();
1098         // The last one needs to not have a comma.
1099         --e;
1100 
1101         OS << "public:\n";
1102         OS << "  enum " << shortType << " {\n";
1103         for (; i != e; ++i)
1104           OS << "    " << *i << ",\n";
1105         OS << "    " << *e << "\n";
1106         OS << "  };\n";
1107       }
1108       OS << "private:\n";
1109 
1110       VariadicArgument::writeDeclarations(OS);
1111     }
1112 
1113     void writeDump(raw_ostream &OS) const override {
1114       OS << "    for (" << getAttrName() << "Attr::" << getLowerName()
1115          << "_iterator I = SA->" << getLowerName() << "_begin(), E = SA->"
1116          << getLowerName() << "_end(); I != E; ++I) {\n";
1117       OS << "      switch(*I) {\n";
1118       for (const auto &UI : uniques) {
1119         OS << "    case " << fullType << "::" << UI << ":\n";
1120         OS << "      OS << \" " << UI << "\";\n";
1121         OS << "      break;\n";
1122       }
1123       if (!isCovered) {
1124         OS << "    default:\n";
1125         OS << "      llvm_unreachable(\"Invalid attribute value\");\n";
1126       }
1127       OS << "      }\n";
1128       OS << "    }\n";
1129     }
1130 
1131     void writePCHReadDecls(raw_ostream &OS) const override {
1132       OS << "    unsigned " << getLowerName() << "Size = Record.readInt();\n";
1133       OS << "    SmallVector<" << fullType << ", 4> " << getLowerName()
1134          << ";\n";
1135       OS << "    " << getLowerName() << ".reserve(" << getLowerName()
1136          << "Size);\n";
1137       OS << "    for (unsigned i = " << getLowerName() << "Size; i; --i)\n";
1138       OS << "      " << getLowerName() << ".push_back("
1139          << "static_cast<" << fullType << ">(Record.readInt()));\n";
1140     }
1141 
1142     void writePCHWrite(raw_ostream &OS) const override {
1143       OS << "    Record.push_back(SA->" << getLowerName() << "_size());\n";
1144       OS << "    for (" << getAttrName() << "Attr::" << getLowerName()
1145          << "_iterator i = SA->" << getLowerName() << "_begin(), e = SA->"
1146          << getLowerName() << "_end(); i != e; ++i)\n";
1147       OS << "      " << WritePCHRecord(fullType, "(*i)");
1148     }
1149 
1150     void writeConversion(raw_ostream &OS, bool Header) const {
1151       if (Header) {
1152         OS << "  static bool ConvertStrTo" << shortType << "(StringRef Val, "
1153            << fullType << " &Out);\n";
1154         OS << "  static const char *Convert" << shortType << "ToStr("
1155            << fullType << " Val);\n";
1156         return;
1157       }
1158 
1159       OS << "bool " << getAttrName() << "Attr::ConvertStrTo" << shortType
1160          << "(StringRef Val, ";
1161       OS << fullType << " &Out) {\n";
1162       OS << "  std::optional<" << fullType
1163          << "> R = llvm::StringSwitch<std::optional<";
1164       OS << fullType << ">>(Val)\n";
1165       for (size_t I = 0; I < enums.size(); ++I) {
1166         OS << "    .Case(\"" << values[I] << "\", ";
1167         OS << fullType << "::" << enums[I] << ")\n";
1168       }
1169       OS << "    .Default(std::optional<" << fullType << ">());\n";
1170       OS << "  if (R) {\n";
1171       OS << "    Out = *R;\n      return true;\n    }\n";
1172       OS << "  return false;\n";
1173       OS << "}\n\n";
1174 
1175       OS << "const char *" << getAttrName() << "Attr::Convert" << shortType
1176          << "ToStr(" << fullType << " Val) {\n"
1177          << "  switch(Val) {\n";
1178       SmallDenseSet<StringRef, 8> Uniques;
1179       for (size_t I = 0; I < enums.size(); ++I) {
1180         if (Uniques.insert(enums[I]).second)
1181           OS << "  case " << fullType << "::" << enums[I] << ": return \""
1182              << values[I] << "\";\n";
1183       }
1184       if (!isCovered) {
1185         OS << "  default: llvm_unreachable(\"Invalid attribute value\");\n";
1186       }
1187       OS << "  }\n"
1188          << "  llvm_unreachable(\"No enumerator with that value\");\n"
1189          << "}\n";
1190     }
1191   };
1192 
1193   class VersionArgument : public Argument {
1194   public:
1195     VersionArgument(const Record &Arg, StringRef Attr)
1196       : Argument(Arg, Attr)
1197     {}
1198 
1199     void writeAccessors(raw_ostream &OS) const override {
1200       OS << "  VersionTuple get" << getUpperName() << "() const {\n";
1201       OS << "    return " << getLowerName() << ";\n";
1202       OS << "  }\n";
1203       OS << "  void set" << getUpperName()
1204          << "(ASTContext &C, VersionTuple V) {\n";
1205       OS << "    " << getLowerName() << " = V;\n";
1206       OS << "  }";
1207     }
1208 
1209     void writeCloneArgs(raw_ostream &OS) const override {
1210       OS << "get" << getUpperName() << "()";
1211     }
1212 
1213     void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
1214       OS << "A->get" << getUpperName() << "()";
1215     }
1216 
1217     void writeCtorInitializers(raw_ostream &OS) const override {
1218       OS << getLowerName() << "(" << getUpperName() << ")";
1219     }
1220 
1221     void writeCtorDefaultInitializers(raw_ostream &OS) const override {
1222       OS << getLowerName() << "()";
1223     }
1224 
1225     void writeCtorParameters(raw_ostream &OS) const override {
1226       OS << "VersionTuple " << getUpperName();
1227     }
1228 
1229     void writeDeclarations(raw_ostream &OS) const override {
1230       OS << "VersionTuple " << getLowerName() << ";\n";
1231     }
1232 
1233     void writePCHReadDecls(raw_ostream &OS) const override {
1234       OS << "    VersionTuple " << getLowerName()
1235          << "= Record.readVersionTuple();\n";
1236     }
1237 
1238     void writePCHReadArgs(raw_ostream &OS) const override {
1239       OS << getLowerName();
1240     }
1241 
1242     void writePCHWrite(raw_ostream &OS) const override {
1243       OS << "    Record.AddVersionTuple(SA->get" << getUpperName() << "());\n";
1244     }
1245 
1246     void writeValue(raw_ostream &OS) const override {
1247       OS << getLowerName() << "=\" << get" << getUpperName() << "() << \"";
1248     }
1249 
1250     void writeDump(raw_ostream &OS) const override {
1251       OS << "    OS << \" \" << SA->get" << getUpperName() << "();\n";
1252     }
1253   };
1254 
1255   class ExprArgument : public SimpleArgument {
1256   public:
1257     ExprArgument(const Record &Arg, StringRef Attr)
1258       : SimpleArgument(Arg, Attr, "Expr *")
1259     {}
1260 
1261     void writeASTVisitorTraversal(raw_ostream &OS) const override {
1262       OS << "  if (!"
1263          << "getDerived().TraverseStmt(A->get" << getUpperName() << "()))\n";
1264       OS << "    return false;\n";
1265     }
1266 
1267     void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
1268       OS << "tempInst" << getUpperName();
1269     }
1270 
1271     void writeTemplateInstantiation(raw_ostream &OS) const override {
1272       OS << "      " << getType() << " tempInst" << getUpperName() << ";\n";
1273       OS << "      {\n";
1274       OS << "        EnterExpressionEvaluationContext "
1275          << "Unevaluated(S, Sema::ExpressionEvaluationContext::Unevaluated);\n";
1276       OS << "        ExprResult " << "Result = S.SubstExpr("
1277          << "A->get" << getUpperName() << "(), TemplateArgs);\n";
1278       OS << "        if (Result.isInvalid())\n";
1279       OS << "          return nullptr;\n";
1280       OS << "        tempInst" << getUpperName() << " = Result.get();\n";
1281       OS << "      }\n";
1282     }
1283 
1284     void writeValue(raw_ostream &OS) const override {
1285       OS << "\";\n";
1286       OS << "    get" << getUpperName()
1287          << "()->printPretty(OS, nullptr, Policy);\n";
1288       OS << "    OS << \"";
1289     }
1290 
1291     void writeDump(raw_ostream &OS) const override {}
1292 
1293     void writeDumpChildren(raw_ostream &OS) const override {
1294       OS << "    Visit(SA->get" << getUpperName() << "());\n";
1295     }
1296 
1297     void writeHasChildren(raw_ostream &OS) const override { OS << "true"; }
1298   };
1299 
1300   class VariadicExprArgument : public VariadicArgument {
1301   public:
1302     VariadicExprArgument(const Record &Arg, StringRef Attr)
1303       : VariadicArgument(Arg, Attr, "Expr *")
1304     {}
1305 
1306     VariadicExprArgument(StringRef ArgName, StringRef Attr)
1307         : VariadicArgument(ArgName, Attr, "Expr *") {}
1308 
1309     void writeASTVisitorTraversal(raw_ostream &OS) const override {
1310       OS << "  {\n";
1311       OS << "    " << getType() << " *I = A->" << getLowerName()
1312          << "_begin();\n";
1313       OS << "    " << getType() << " *E = A->" << getLowerName()
1314          << "_end();\n";
1315       OS << "    for (; I != E; ++I) {\n";
1316       OS << "      if (!getDerived().TraverseStmt(*I))\n";
1317       OS << "        return false;\n";
1318       OS << "    }\n";
1319       OS << "  }\n";
1320     }
1321 
1322     void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
1323       OS << "tempInst" << getUpperName() << ", "
1324          << "A->" << getLowerName() << "_size()";
1325     }
1326 
1327     void writeTemplateInstantiation(raw_ostream &OS) const override {
1328       OS << "      auto *tempInst" << getUpperName()
1329          << " = new (C, 16) " << getType()
1330          << "[A->" << getLowerName() << "_size()];\n";
1331       OS << "      {\n";
1332       OS << "        EnterExpressionEvaluationContext "
1333          << "Unevaluated(S, Sema::ExpressionEvaluationContext::Unevaluated);\n";
1334       OS << "        " << getType() << " *TI = tempInst" << getUpperName()
1335          << ";\n";
1336       OS << "        " << getType() << " *I = A->" << getLowerName()
1337          << "_begin();\n";
1338       OS << "        " << getType() << " *E = A->" << getLowerName()
1339          << "_end();\n";
1340       OS << "        for (; I != E; ++I, ++TI) {\n";
1341       OS << "          ExprResult Result = S.SubstExpr(*I, TemplateArgs);\n";
1342       OS << "          if (Result.isInvalid())\n";
1343       OS << "            return nullptr;\n";
1344       OS << "          *TI = Result.get();\n";
1345       OS << "        }\n";
1346       OS << "      }\n";
1347     }
1348 
1349     void writeDump(raw_ostream &OS) const override {}
1350 
1351     void writeDumpChildren(raw_ostream &OS) const override {
1352       OS << "    for (" << getAttrName() << "Attr::" << getLowerName()
1353          << "_iterator I = SA->" << getLowerName() << "_begin(), E = SA->"
1354          << getLowerName() << "_end(); I != E; ++I)\n";
1355       OS << "      Visit(*I);\n";
1356     }
1357 
1358     void writeHasChildren(raw_ostream &OS) const override {
1359       OS << "SA->" << getLowerName() << "_begin() != "
1360          << "SA->" << getLowerName() << "_end()";
1361     }
1362   };
1363 
1364   class VariadicIdentifierArgument : public VariadicArgument {
1365   public:
1366     VariadicIdentifierArgument(const Record &Arg, StringRef Attr)
1367       : VariadicArgument(Arg, Attr, "IdentifierInfo *")
1368     {}
1369   };
1370 
1371   class VariadicStringArgument : public VariadicArgument {
1372   public:
1373     VariadicStringArgument(const Record &Arg, StringRef Attr)
1374       : VariadicArgument(Arg, Attr, "StringRef")
1375     {}
1376 
1377     void writeCtorBody(raw_ostream &OS) const override {
1378       OS << "  for (size_t I = 0, E = " << getArgSizeName() << "; I != E;\n"
1379             "       ++I) {\n"
1380             "    StringRef Ref = " << getUpperName() << "[I];\n"
1381             "    if (!Ref.empty()) {\n"
1382             "      char *Mem = new (Ctx, 1) char[Ref.size()];\n"
1383             "      std::memcpy(Mem, Ref.data(), Ref.size());\n"
1384             "      " << getArgName() << "[I] = StringRef(Mem, Ref.size());\n"
1385             "    }\n"
1386             "  }\n";
1387     }
1388 
1389     void writeValueImpl(raw_ostream &OS) const override {
1390       OS << "    OS << \"\\\"\" << Val << \"\\\"\";\n";
1391     }
1392   };
1393 
1394   class TypeArgument : public SimpleArgument {
1395   public:
1396     TypeArgument(const Record &Arg, StringRef Attr)
1397       : SimpleArgument(Arg, Attr, "TypeSourceInfo *")
1398     {}
1399 
1400     void writeAccessors(raw_ostream &OS) const override {
1401       OS << "  QualType get" << getUpperName() << "() const {\n";
1402       OS << "    return " << getLowerName() << "->getType();\n";
1403       OS << "  }";
1404       OS << "  " << getType() << " get" << getUpperName() << "Loc() const {\n";
1405       OS << "    return " << getLowerName() << ";\n";
1406       OS << "  }";
1407     }
1408 
1409     void writeASTVisitorTraversal(raw_ostream &OS) const override {
1410       OS << "  if (auto *TSI = A->get" << getUpperName() << "Loc())\n";
1411       OS << "    if (!getDerived().TraverseTypeLoc(TSI->getTypeLoc()))\n";
1412       OS << "      return false;\n";
1413     }
1414 
1415     void writeTemplateInstantiation(raw_ostream &OS) const override {
1416       OS << "      " << getType() << " tempInst" << getUpperName() << " =\n";
1417       OS << "        S.SubstType(A->get" << getUpperName() << "Loc(), "
1418          << "TemplateArgs, A->getLoc(), A->getAttrName());\n";
1419       OS << "      if (!tempInst" << getUpperName() << ")\n";
1420       OS << "        return nullptr;\n";
1421     }
1422 
1423     void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
1424       OS << "tempInst" << getUpperName();
1425     }
1426 
1427     void writePCHWrite(raw_ostream &OS) const override {
1428       OS << "    "
1429          << WritePCHRecord(getType(),
1430                            "SA->get" + getUpperName().str() + "Loc()");
1431     }
1432   };
1433 
1434   class WrappedAttr : public SimpleArgument {
1435   public:
1436     WrappedAttr(const Record &Arg, StringRef Attr)
1437         : SimpleArgument(Arg, Attr, "Attr *") {}
1438 
1439     void writePCHReadDecls(raw_ostream &OS) const override {
1440       OS << "    Attr *" << getLowerName() << " = Record.readAttr();";
1441     }
1442 
1443     void writePCHWrite(raw_ostream &OS) const override {
1444       OS << "    AddAttr(SA->get" << getUpperName() << "());";
1445     }
1446 
1447     void writeDump(raw_ostream &OS) const override {}
1448 
1449     void writeDumpChildren(raw_ostream &OS) const override {
1450       OS << "    Visit(SA->get" << getUpperName() << "());\n";
1451     }
1452 
1453     void writeHasChildren(raw_ostream &OS) const override { OS << "true"; }
1454   };
1455 
1456   } // end anonymous namespace
1457 
1458 static std::unique_ptr<Argument>
1459 createArgument(const Record &Arg, StringRef Attr,
1460                const Record *Search = nullptr) {
1461   if (!Search)
1462     Search = &Arg;
1463 
1464   std::unique_ptr<Argument> Ptr;
1465   StringRef ArgName = Search->getName();
1466 
1467   if (ArgName == "AlignedArgument")
1468     Ptr = std::make_unique<AlignedArgument>(Arg, Attr);
1469   else if (ArgName == "EnumArgument")
1470     Ptr = std::make_unique<EnumArgument>(Arg, Attr);
1471   else if (ArgName == "ExprArgument")
1472     Ptr = std::make_unique<ExprArgument>(Arg, Attr);
1473   else if (ArgName == "DeclArgument")
1474     Ptr = std::make_unique<SimpleArgument>(
1475         Arg, Attr, (Arg.getValueAsDef("Kind")->getName() + "Decl *").str());
1476   else if (ArgName == "IdentifierArgument")
1477     Ptr = std::make_unique<SimpleArgument>(Arg, Attr, "IdentifierInfo *");
1478   else if (ArgName == "DefaultBoolArgument")
1479     Ptr = std::make_unique<DefaultSimpleArgument>(
1480         Arg, Attr, "bool", Arg.getValueAsBit("Default"));
1481   else if (ArgName == "BoolArgument")
1482     Ptr = std::make_unique<SimpleArgument>(Arg, Attr, "bool");
1483   else if (ArgName == "DefaultIntArgument")
1484     Ptr = std::make_unique<DefaultSimpleArgument>(
1485         Arg, Attr, "int", Arg.getValueAsInt("Default"));
1486   else if (ArgName == "IntArgument")
1487     Ptr = std::make_unique<SimpleArgument>(Arg, Attr, "int");
1488   else if (ArgName == "StringArgument")
1489     Ptr = std::make_unique<StringArgument>(Arg, Attr);
1490   else if (ArgName == "TypeArgument")
1491     Ptr = std::make_unique<TypeArgument>(Arg, Attr);
1492   else if (ArgName == "UnsignedArgument")
1493     Ptr = std::make_unique<SimpleArgument>(Arg, Attr, "unsigned");
1494   else if (ArgName == "VariadicUnsignedArgument")
1495     Ptr = std::make_unique<VariadicArgument>(Arg, Attr, "unsigned");
1496   else if (ArgName == "VariadicStringArgument")
1497     Ptr = std::make_unique<VariadicStringArgument>(Arg, Attr);
1498   else if (ArgName == "VariadicEnumArgument")
1499     Ptr = std::make_unique<VariadicEnumArgument>(Arg, Attr);
1500   else if (ArgName == "VariadicExprArgument")
1501     Ptr = std::make_unique<VariadicExprArgument>(Arg, Attr);
1502   else if (ArgName == "VariadicParamIdxArgument")
1503     Ptr = std::make_unique<VariadicParamIdxArgument>(Arg, Attr);
1504   else if (ArgName == "VariadicParamOrParamIdxArgument")
1505     Ptr = std::make_unique<VariadicParamOrParamIdxArgument>(Arg, Attr);
1506   else if (ArgName == "ParamIdxArgument")
1507     Ptr = std::make_unique<SimpleArgument>(Arg, Attr, "ParamIdx");
1508   else if (ArgName == "VariadicIdentifierArgument")
1509     Ptr = std::make_unique<VariadicIdentifierArgument>(Arg, Attr);
1510   else if (ArgName == "VersionArgument")
1511     Ptr = std::make_unique<VersionArgument>(Arg, Attr);
1512   else if (ArgName == "WrappedAttr")
1513     Ptr = std::make_unique<WrappedAttr>(Arg, Attr);
1514   else if (ArgName == "OMPTraitInfoArgument")
1515     Ptr = std::make_unique<SimpleArgument>(Arg, Attr, "OMPTraitInfo *");
1516   else if (ArgName == "VariadicOMPInteropInfoArgument")
1517     Ptr = std::make_unique<VariadicOMPInteropInfoArgument>(Arg, Attr);
1518 
1519   if (!Ptr) {
1520     // Search in reverse order so that the most-derived type is handled first.
1521     for (const auto &[Base, _] : reverse(Search->getSuperClasses())) {
1522       if ((Ptr = createArgument(Arg, Attr, Base)))
1523         break;
1524     }
1525   }
1526 
1527   if (Ptr && Arg.getValueAsBit("Optional"))
1528     Ptr->setOptional(true);
1529 
1530   if (Ptr && Arg.getValueAsBit("Fake"))
1531     Ptr->setFake(true);
1532 
1533   return Ptr;
1534 }
1535 
1536 static void writeAvailabilityValue(raw_ostream &OS) {
1537   OS << "\" << getPlatform()->getName();\n"
1538      << "  if (getStrict()) OS << \", strict\";\n"
1539      << "  if (!getIntroduced().empty()) OS << \", introduced=\" << getIntroduced();\n"
1540      << "  if (!getDeprecated().empty()) OS << \", deprecated=\" << getDeprecated();\n"
1541      << "  if (!getObsoleted().empty()) OS << \", obsoleted=\" << getObsoleted();\n"
1542      << "  if (getUnavailable()) OS << \", unavailable\";\n"
1543      << "  OS << \"";
1544 }
1545 
1546 static void writeDeprecatedAttrValue(raw_ostream &OS, StringRef Variety) {
1547   OS << "\\\"\" << getMessage() << \"\\\"\";\n";
1548   // Only GNU deprecated has an optional fixit argument at the second position.
1549   if (Variety == "GNU")
1550      OS << "    if (!getReplacement().empty()) OS << \", \\\"\""
1551            " << getReplacement() << \"\\\"\";\n";
1552   OS << "    OS << \"";
1553 }
1554 
1555 static void writeGetSpellingFunction(const Record &R, raw_ostream &OS) {
1556   std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(R);
1557 
1558   OS << "const char *" << R.getName() << "Attr::getSpelling() const {\n";
1559   if (Spellings.empty()) {
1560     OS << "  return \"(No spelling)\";\n}\n\n";
1561     return;
1562   }
1563 
1564   OS << "  switch (getAttributeSpellingListIndex()) {\n"
1565         "  default:\n"
1566         "    llvm_unreachable(\"Unknown attribute spelling!\");\n"
1567         "    return \"(No spelling)\";\n";
1568 
1569   for (const auto &[Idx, S] : enumerate(Spellings)) {
1570     // clang-format off
1571     OS << "  case " << Idx << ":\n"
1572           "    return \"" << S.name() << "\";\n";
1573     // clang-format on
1574   }
1575   // End of the switch statement.
1576   OS << "  }\n";
1577   // End of the getSpelling function.
1578   OS << "}\n\n";
1579 }
1580 
1581 static void
1582 writePrettyPrintFunction(const Record &R,
1583                          const std::vector<std::unique_ptr<Argument>> &Args,
1584                          raw_ostream &OS) {
1585   std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(R);
1586 
1587   OS << "void " << R.getName() << "Attr::printPretty("
1588     << "raw_ostream &OS, const PrintingPolicy &Policy) const {\n";
1589 
1590   if (Spellings.empty()) {
1591     OS << "}\n\n";
1592     return;
1593   }
1594 
1595   OS << "  bool IsFirstArgument = true; (void)IsFirstArgument;\n"
1596      << "  unsigned TrailingOmittedArgs = 0; (void)TrailingOmittedArgs;\n"
1597      << "  switch (getAttributeSpellingListIndex()) {\n"
1598      << "  default:\n"
1599      << "    llvm_unreachable(\"Unknown attribute spelling!\");\n"
1600      << "    break;\n";
1601 
1602   for (const auto &[Idx, S] : enumerate(Spellings)) {
1603     SmallString<16> Prefix;
1604     SmallString<8> Suffix;
1605     // The actual spelling of the name and namespace (if applicable)
1606     // of an attribute without considering prefix and suffix.
1607     SmallString<64> Spelling;
1608     StringRef Name = S.name();
1609     StringRef Variety = S.variety();
1610 
1611     if (Variety == "GNU") {
1612       Prefix = "__attribute__((";
1613       Suffix = "))";
1614     } else if (Variety == "CXX11" || Variety == "C23") {
1615       Prefix = "[[";
1616       Suffix = "]]";
1617       StringRef Namespace = S.nameSpace();
1618       if (!Namespace.empty()) {
1619         Spelling += Namespace;
1620         Spelling += "::";
1621       }
1622     } else if (Variety == "Declspec") {
1623       Prefix = "__declspec(";
1624       Suffix = ")";
1625     } else if (Variety == "Microsoft") {
1626       Prefix = "[";
1627       Suffix = "]";
1628     } else if (Variety == "Keyword") {
1629       Prefix = "";
1630       Suffix = "";
1631     } else if (Variety == "Pragma") {
1632       Prefix = "#pragma ";
1633       Suffix = "\n";
1634       StringRef Namespace = S.nameSpace();
1635       if (!Namespace.empty()) {
1636         Spelling += Namespace;
1637         Spelling += " ";
1638       }
1639     } else if (Variety == "HLSLAnnotation") {
1640       Prefix = ":";
1641       Suffix = "";
1642     } else {
1643       llvm_unreachable("Unknown attribute syntax variety!");
1644     }
1645 
1646     Spelling += Name;
1647 
1648     OS << "  case " << Idx << " : {\n"
1649        << "    OS << \"" << Prefix << Spelling << "\";\n";
1650 
1651     if (Variety == "Pragma") {
1652       OS << "    printPrettyPragma(OS, Policy);\n";
1653       OS << "    OS << \"\\n\";";
1654       OS << "    break;\n";
1655       OS << "  }\n";
1656       continue;
1657     }
1658 
1659     if (Spelling == "availability") {
1660       OS << "    OS << \"(";
1661       writeAvailabilityValue(OS);
1662       OS << ")\";\n";
1663     } else if (Spelling == "deprecated" || Spelling == "gnu::deprecated") {
1664       OS << "    OS << \"(";
1665       writeDeprecatedAttrValue(OS, Variety);
1666       OS << ")\";\n";
1667     } else {
1668       // To avoid printing parentheses around an empty argument list or
1669       // printing spurious commas at the end of an argument list, we need to
1670       // determine where the last provided non-fake argument is.
1671       bool FoundNonOptArg = false;
1672       for (const auto &arg : reverse(Args)) {
1673         if (arg->isFake())
1674           continue;
1675         if (FoundNonOptArg)
1676           continue;
1677         // FIXME: arg->getIsOmitted() == "false" means we haven't implemented
1678         // any way to detect whether the argument was omitted.
1679         if (!arg->isOptional() || arg->getIsOmitted() == "false") {
1680           FoundNonOptArg = true;
1681           continue;
1682         }
1683         OS << "    if (" << arg->getIsOmitted() << ")\n"
1684            << "      ++TrailingOmittedArgs;\n";
1685       }
1686       unsigned ArgIndex = 0;
1687       for (const auto &arg : Args) {
1688         if (arg->isFake())
1689           continue;
1690         std::string IsOmitted = arg->getIsOmitted();
1691         if (arg->isOptional() && IsOmitted != "false")
1692           OS << "    if (!(" << IsOmitted << ")) {\n";
1693         // Variadic arguments print their own leading comma.
1694         if (!arg->isVariadic())
1695           OS << "    DelimitAttributeArgument(OS, IsFirstArgument);\n";
1696         OS << "    OS << \"";
1697         arg->writeValue(OS);
1698         OS << "\";\n";
1699         if (arg->isOptional() && IsOmitted != "false")
1700           OS << "    }\n";
1701         ++ArgIndex;
1702       }
1703       if (ArgIndex != 0)
1704         OS << "    if (!IsFirstArgument)\n"
1705            << "      OS << \")\";\n";
1706     }
1707     OS << "    OS << \"" << Suffix << "\";\n"
1708        << "    break;\n"
1709        << "  }\n";
1710   }
1711 
1712   // End of the switch statement.
1713   OS << "}\n";
1714   // End of the print function.
1715   OS << "}\n\n";
1716 }
1717 
1718 /// Return the index of a spelling in a spelling list.
1719 static unsigned getSpellingListIndex(ArrayRef<FlattenedSpelling> SpellingList,
1720                                      const FlattenedSpelling &Spelling) {
1721   assert(!SpellingList.empty() && "Spelling list is empty!");
1722 
1723   for (const auto &[Index, S] : enumerate(SpellingList)) {
1724     if (S.variety() == Spelling.variety() &&
1725         S.nameSpace() == Spelling.nameSpace() && S.name() == Spelling.name())
1726       return Index;
1727   }
1728 
1729   PrintFatalError("Unknown spelling: " + Spelling.name());
1730 }
1731 
1732 static void writeAttrAccessorDefinition(const Record &R, raw_ostream &OS) {
1733   std::vector<const Record *> Accessors = R.getValueAsListOfDefs("Accessors");
1734   if (Accessors.empty())
1735     return;
1736 
1737   const std::vector<FlattenedSpelling> SpellingList = GetFlattenedSpellings(R);
1738   assert(!SpellingList.empty() &&
1739          "Attribute with empty spelling list can't have accessors!");
1740   for (const auto *Accessor : Accessors) {
1741     const StringRef Name = Accessor->getValueAsString("Name");
1742     std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(*Accessor);
1743 
1744     OS << "  bool " << Name
1745        << "() const { return getAttributeSpellingListIndex() == ";
1746     for (unsigned Index = 0; Index < Spellings.size(); ++Index) {
1747       OS << getSpellingListIndex(SpellingList, Spellings[Index]);
1748       if (Index != Spellings.size() - 1)
1749         OS << " ||\n    getAttributeSpellingListIndex() == ";
1750       else
1751         OS << "; }\n";
1752     }
1753   }
1754 }
1755 
1756 static bool
1757 SpellingNamesAreCommon(const std::vector<FlattenedSpelling>& Spellings) {
1758   assert(!Spellings.empty() && "An empty list of spellings was provided");
1759   StringRef FirstName =
1760       NormalizeNameForSpellingComparison(Spellings.front().name());
1761   for (const auto &Spelling : drop_begin(Spellings)) {
1762     StringRef Name = NormalizeNameForSpellingComparison(Spelling.name());
1763     if (Name != FirstName)
1764       return false;
1765   }
1766   return true;
1767 }
1768 
1769 typedef std::map<unsigned, std::string> SemanticSpellingMap;
1770 static std::string
1771 CreateSemanticSpellings(const std::vector<FlattenedSpelling> &Spellings,
1772                         SemanticSpellingMap &Map) {
1773   // The enumerants are automatically generated based on the variety,
1774   // namespace (if present) and name for each attribute spelling. However,
1775   // care is taken to avoid trampling on the reserved namespace due to
1776   // underscores.
1777   std::string Ret("  enum Spelling {\n");
1778   std::set<std::string> Uniques;
1779   unsigned Idx = 0;
1780 
1781   // If we have a need to have this many spellings we likely need to add an
1782   // extra bit to the SpellingIndex in AttributeCommonInfo, then increase the
1783   // value of SpellingNotCalculated there and here.
1784   assert(Spellings.size() < 15 &&
1785          "Too many spellings, would step on SpellingNotCalculated in "
1786          "AttributeCommonInfo");
1787   for (auto I = Spellings.begin(), E = Spellings.end(); I != E; ++I, ++Idx) {
1788     const FlattenedSpelling &S = *I;
1789     StringRef Variety = S.variety();
1790     StringRef Spelling = S.name();
1791     StringRef Namespace = S.nameSpace();
1792     std::string EnumName;
1793 
1794     EnumName += Variety;
1795     EnumName += "_";
1796     if (!Namespace.empty())
1797       EnumName += NormalizeNameForSpellingComparison(Namespace).str() + "_";
1798     EnumName += NormalizeNameForSpellingComparison(Spelling);
1799 
1800     // Even if the name is not unique, this spelling index corresponds to a
1801     // particular enumerant name that we've calculated.
1802     Map[Idx] = EnumName;
1803 
1804     // Since we have been stripping underscores to avoid trampling on the
1805     // reserved namespace, we may have inadvertently created duplicate
1806     // enumerant names. These duplicates are not considered part of the
1807     // semantic spelling, and can be elided.
1808     if (!Uniques.insert(EnumName).second)
1809       continue;
1810 
1811     if (I != Spellings.begin())
1812       Ret += ",\n";
1813     // Duplicate spellings are not considered part of the semantic spelling
1814     // enumeration, but the spelling index and semantic spelling values are
1815     // meant to be equivalent, so we must specify a concrete value for each
1816     // enumerator.
1817     Ret += "    " + EnumName + " = " + utostr(Idx);
1818   }
1819   Ret += ",\n  SpellingNotCalculated = 15\n";
1820   Ret += "\n  };\n\n";
1821   return Ret;
1822 }
1823 
1824 static void WriteSemanticSpellingSwitch(StringRef VarName,
1825                                         const SemanticSpellingMap &Map,
1826                                         raw_ostream &OS) {
1827   OS << "  switch (" << VarName << ") {\n    default: "
1828     << "llvm_unreachable(\"Unknown spelling list index\");\n";
1829   for (const auto &I : Map)
1830     OS << "    case " << I.first << ": return " << I.second << ";\n";
1831   OS << "  }\n";
1832 }
1833 
1834 // Note: these values need to match the values used by LateAttrParseKind in
1835 // `Attr.td`
1836 enum class LateAttrParseKind { Never = 0, Standard = 1, ExperimentalExt = 2 };
1837 
1838 static LateAttrParseKind getLateAttrParseKind(const Record *Attr) {
1839   // This function basically does
1840   // `Attr->getValueAsDef("LateParsed")->getValueAsInt("Kind")` but does a bunch
1841   // of sanity checking to ensure that `LateAttrParseMode` in `Attr.td` is in
1842   // sync with the `LateAttrParseKind` enum in this source file.
1843 
1844   static constexpr StringRef LateParsedStr = "LateParsed";
1845   static constexpr StringRef LateAttrParseKindStr = "LateAttrParseKind";
1846   static constexpr StringRef KindFieldStr = "Kind";
1847 
1848   auto *LAPK = Attr->getValueAsDef(LateParsedStr);
1849 
1850   // Typecheck the `LateParsed` field.
1851   SmallVector<const Record *, 1> SuperClasses;
1852   LAPK->getDirectSuperClasses(SuperClasses);
1853   if (SuperClasses.size() != 1)
1854     PrintFatalError(Attr, "Field `" + Twine(LateParsedStr) +
1855                               "`should only have one super class");
1856 
1857   if (SuperClasses[0]->getName() != LateAttrParseKindStr)
1858     PrintFatalError(
1859         Attr, "Field `" + Twine(LateParsedStr) + "`should only have type `" +
1860                   Twine(LateAttrParseKindStr) + "` but found type `" +
1861                   SuperClasses[0]->getName() + "`");
1862 
1863   // Get Kind and verify the enum name matches the name in `Attr.td`.
1864   unsigned Kind = LAPK->getValueAsInt(KindFieldStr);
1865   switch (LateAttrParseKind(Kind)) {
1866 #define CASE(X)                                                                \
1867   case LateAttrParseKind::X:                                                   \
1868     if (LAPK->getName().compare("LateAttrParse" #X) != 0) {                    \
1869       PrintFatalError(                                                         \
1870           Attr,                                                                \
1871           "Field `" + Twine(LateParsedStr) + "` set to `" + LAPK->getName() +  \
1872               "` but this converts to `LateAttrParseKind::" + Twine(#X) +      \
1873               "`");                                                            \
1874     }                                                                          \
1875     return LateAttrParseKind::X;
1876 
1877     CASE(Never)
1878     CASE(Standard)
1879     CASE(ExperimentalExt)
1880 #undef CASE
1881   }
1882 
1883   // The Kind value is completely invalid
1884   auto KindValueStr = utostr(Kind);
1885   PrintFatalError(Attr, "Field `" + Twine(LateParsedStr) + "` set to `" +
1886                             LAPK->getName() + "` has unexpected `" +
1887                             Twine(KindFieldStr) + "` value of " + KindValueStr);
1888 }
1889 
1890 // Emits the LateParsed property for attributes.
1891 static void emitClangAttrLateParsedListImpl(const RecordKeeper &Records,
1892                                             raw_ostream &OS,
1893                                             LateAttrParseKind LateParseMode) {
1894   for (const auto *Attr : Records.getAllDerivedDefinitions("Attr")) {
1895     if (LateAttrParseKind LateParsed = getLateAttrParseKind(Attr);
1896         LateParsed != LateParseMode)
1897       continue;
1898 
1899     std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(*Attr);
1900 
1901     // FIXME: Handle non-GNU attributes
1902     for (const auto &I : Spellings) {
1903       if (I.variety() != "GNU")
1904         continue;
1905       OS << ".Case(\"" << I.name() << "\", 1)\n";
1906     }
1907   }
1908 }
1909 
1910 static void emitClangAttrLateParsedList(const RecordKeeper &Records,
1911                                         raw_ostream &OS) {
1912   OS << "#if defined(CLANG_ATTR_LATE_PARSED_LIST)\n";
1913   emitClangAttrLateParsedListImpl(Records, OS, LateAttrParseKind::Standard);
1914   OS << "#endif // CLANG_ATTR_LATE_PARSED_LIST\n\n";
1915 }
1916 
1917 static void emitClangAttrLateParsedExperimentalList(const RecordKeeper &Records,
1918                                                     raw_ostream &OS) {
1919   OS << "#if defined(CLANG_ATTR_LATE_PARSED_EXPERIMENTAL_EXT_LIST)\n";
1920   emitClangAttrLateParsedListImpl(Records, OS,
1921                                   LateAttrParseKind::ExperimentalExt);
1922   OS << "#endif // CLANG_ATTR_LATE_PARSED_EXPERIMENTAL_EXT_LIST\n\n";
1923 }
1924 
1925 static bool hasGNUorCXX11Spelling(const Record &Attribute) {
1926   std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(Attribute);
1927   for (const auto &I : Spellings) {
1928     if (I.variety() == "GNU" || I.variety() == "CXX11")
1929       return true;
1930   }
1931   return false;
1932 }
1933 
1934 namespace {
1935 
1936 struct AttributeSubjectMatchRule {
1937   const Record *MetaSubject;
1938   const Record *Constraint;
1939 
1940   AttributeSubjectMatchRule(const Record *MetaSubject, const Record *Constraint)
1941       : MetaSubject(MetaSubject), Constraint(Constraint) {
1942     assert(MetaSubject && "Missing subject");
1943   }
1944 
1945   bool isSubRule() const { return Constraint != nullptr; }
1946 
1947   std::vector<const Record *> getSubjects() const {
1948     return (Constraint ? Constraint : MetaSubject)
1949         ->getValueAsListOfDefs("Subjects");
1950   }
1951 
1952   std::vector<const Record *> getLangOpts() const {
1953     if (Constraint) {
1954       // Lookup the options in the sub-rule first, in case the sub-rule
1955       // overrides the rules options.
1956       std::vector<const Record *> Opts =
1957           Constraint->getValueAsListOfDefs("LangOpts");
1958       if (!Opts.empty())
1959         return Opts;
1960     }
1961     return MetaSubject->getValueAsListOfDefs("LangOpts");
1962   }
1963 
1964   // Abstract rules are used only for sub-rules
1965   bool isAbstractRule() const { return getSubjects().empty(); }
1966 
1967   StringRef getName() const {
1968     return (Constraint ? Constraint : MetaSubject)->getValueAsString("Name");
1969   }
1970 
1971   bool isNegatedSubRule() const {
1972     assert(isSubRule() && "Not a sub-rule");
1973     return Constraint->getValueAsBit("Negated");
1974   }
1975 
1976   std::string getSpelling() const {
1977     std::string Result = MetaSubject->getValueAsString("Name").str();
1978     if (isSubRule()) {
1979       Result += '(';
1980       if (isNegatedSubRule())
1981         Result += "unless(";
1982       Result += getName();
1983       if (isNegatedSubRule())
1984         Result += ')';
1985       Result += ')';
1986     }
1987     return Result;
1988   }
1989 
1990   std::string getEnumValueName() const {
1991     SmallString<128> Result;
1992     Result += "SubjectMatchRule_";
1993     Result += MetaSubject->getValueAsString("Name");
1994     if (isSubRule()) {
1995       Result += "_";
1996       if (isNegatedSubRule())
1997         Result += "not_";
1998       Result += Constraint->getValueAsString("Name");
1999     }
2000     if (isAbstractRule())
2001       Result += "_abstract";
2002     return std::string(Result);
2003   }
2004 
2005   std::string getEnumValue() const { return "attr::" + getEnumValueName(); }
2006 
2007   static const char *EnumName;
2008 };
2009 
2010 const char *AttributeSubjectMatchRule::EnumName = "attr::SubjectMatchRule";
2011 
2012 struct PragmaClangAttributeSupport {
2013   std::vector<AttributeSubjectMatchRule> Rules;
2014 
2015   class RuleOrAggregateRuleSet {
2016     std::vector<AttributeSubjectMatchRule> Rules;
2017     bool IsRule;
2018     RuleOrAggregateRuleSet(ArrayRef<AttributeSubjectMatchRule> Rules,
2019                            bool IsRule)
2020         : Rules(Rules), IsRule(IsRule) {}
2021 
2022   public:
2023     bool isRule() const { return IsRule; }
2024 
2025     const AttributeSubjectMatchRule &getRule() const {
2026       assert(IsRule && "not a rule!");
2027       return Rules[0];
2028     }
2029 
2030     ArrayRef<AttributeSubjectMatchRule> getAggregateRuleSet() const {
2031       return Rules;
2032     }
2033 
2034     static RuleOrAggregateRuleSet
2035     getRule(const AttributeSubjectMatchRule &Rule) {
2036       return RuleOrAggregateRuleSet(Rule, /*IsRule=*/true);
2037     }
2038     static RuleOrAggregateRuleSet
2039     getAggregateRuleSet(ArrayRef<AttributeSubjectMatchRule> Rules) {
2040       return RuleOrAggregateRuleSet(Rules, /*IsRule=*/false);
2041     }
2042   };
2043   DenseMap<const Record *, RuleOrAggregateRuleSet> SubjectsToRules;
2044 
2045   PragmaClangAttributeSupport(const RecordKeeper &Records);
2046 
2047   bool isAttributedSupported(const Record &Attribute);
2048 
2049   void emitMatchRuleList(raw_ostream &OS);
2050 
2051   void generateStrictConformsTo(const Record &Attr, raw_ostream &OS);
2052 
2053   void generateParsingHelpers(raw_ostream &OS);
2054 };
2055 
2056 } // end anonymous namespace
2057 
2058 static bool isSupportedPragmaClangAttributeSubject(const Record &Subject) {
2059   // FIXME: #pragma clang attribute does not currently support statement
2060   // attributes, so test whether the subject is one that appertains to a
2061   // declaration node. However, it may be reasonable for support for statement
2062   // attributes to be added.
2063   if (Subject.isSubClassOf("DeclNode") || Subject.isSubClassOf("DeclBase") ||
2064       Subject.getName() == "DeclBase")
2065     return true;
2066 
2067   if (Subject.isSubClassOf("SubsetSubject"))
2068     return isSupportedPragmaClangAttributeSubject(
2069         *Subject.getValueAsDef("Base"));
2070 
2071   return false;
2072 }
2073 
2074 static bool doesDeclDeriveFrom(const Record *D, const Record *Base) {
2075   const Record *CurrentBase = D->getValueAsOptionalDef(BaseFieldName);
2076   if (!CurrentBase)
2077     return false;
2078   if (CurrentBase == Base)
2079     return true;
2080   return doesDeclDeriveFrom(CurrentBase, Base);
2081 }
2082 
2083 PragmaClangAttributeSupport::PragmaClangAttributeSupport(
2084     const RecordKeeper &Records) {
2085   auto MapFromSubjectsToRules = [this](const Record *SubjectContainer,
2086                                        const Record *MetaSubject,
2087                                        const Record *Constraint) {
2088     Rules.emplace_back(MetaSubject, Constraint);
2089     for (const Record *Subject :
2090          SubjectContainer->getValueAsListOfDefs("Subjects")) {
2091       bool Inserted =
2092           SubjectsToRules
2093               .try_emplace(Subject, RuleOrAggregateRuleSet::getRule(
2094                                         AttributeSubjectMatchRule(MetaSubject,
2095                                                                   Constraint)))
2096               .second;
2097       if (!Inserted) {
2098         PrintFatalError("Attribute subject match rules should not represent"
2099                         "same attribute subjects.");
2100       }
2101     }
2102   };
2103   for (const auto *MetaSubject :
2104        Records.getAllDerivedDefinitions("AttrSubjectMatcherRule")) {
2105     MapFromSubjectsToRules(MetaSubject, MetaSubject, /*Constraints=*/nullptr);
2106     for (const Record *Constraint :
2107          MetaSubject->getValueAsListOfDefs("Constraints"))
2108       MapFromSubjectsToRules(Constraint, MetaSubject, Constraint);
2109   }
2110 
2111   ArrayRef<const Record *> DeclNodes =
2112       Records.getAllDerivedDefinitions(DeclNodeClassName);
2113   for (const auto *Aggregate :
2114        Records.getAllDerivedDefinitions("AttrSubjectMatcherAggregateRule")) {
2115     const Record *SubjectDecl = Aggregate->getValueAsDef("Subject");
2116 
2117     // Gather sub-classes of the aggregate subject that act as attribute
2118     // subject rules.
2119     std::vector<AttributeSubjectMatchRule> Rules;
2120     for (const auto *D : DeclNodes) {
2121       if (doesDeclDeriveFrom(D, SubjectDecl)) {
2122         auto It = SubjectsToRules.find(D);
2123         if (It == SubjectsToRules.end())
2124           continue;
2125         if (!It->second.isRule() || It->second.getRule().isSubRule())
2126           continue; // Assume that the rule will be included as well.
2127         Rules.push_back(It->second.getRule());
2128       }
2129     }
2130 
2131     bool Inserted =
2132         SubjectsToRules
2133             .try_emplace(SubjectDecl,
2134                          RuleOrAggregateRuleSet::getAggregateRuleSet(Rules))
2135             .second;
2136     if (!Inserted) {
2137       PrintFatalError("Attribute subject match rules should not represent"
2138                       "same attribute subjects.");
2139     }
2140   }
2141 }
2142 
2143 static PragmaClangAttributeSupport &
2144 getPragmaAttributeSupport(const RecordKeeper &Records) {
2145   static PragmaClangAttributeSupport Instance(Records);
2146   return Instance;
2147 }
2148 
2149 void PragmaClangAttributeSupport::emitMatchRuleList(raw_ostream &OS) {
2150   OS << "#ifndef ATTR_MATCH_SUB_RULE\n";
2151   OS << "#define ATTR_MATCH_SUB_RULE(Value, Spelling, IsAbstract, Parent, "
2152         "IsNegated) "
2153      << "ATTR_MATCH_RULE(Value, Spelling, IsAbstract)\n";
2154   OS << "#endif\n";
2155   for (const auto &Rule : Rules) {
2156     OS << (Rule.isSubRule() ? "ATTR_MATCH_SUB_RULE" : "ATTR_MATCH_RULE") << '(';
2157     OS << Rule.getEnumValueName() << ", \"" << Rule.getSpelling() << "\", "
2158        << Rule.isAbstractRule();
2159     if (Rule.isSubRule())
2160       OS << ", "
2161          << AttributeSubjectMatchRule(Rule.MetaSubject, nullptr).getEnumValue()
2162          << ", " << Rule.isNegatedSubRule();
2163     OS << ")\n";
2164   }
2165   OS << "#undef ATTR_MATCH_SUB_RULE\n";
2166 }
2167 
2168 bool PragmaClangAttributeSupport::isAttributedSupported(
2169     const Record &Attribute) {
2170   // If the attribute explicitly specified whether to support #pragma clang
2171   // attribute, use that setting.
2172   bool Unset;
2173   bool SpecifiedResult =
2174     Attribute.getValueAsBitOrUnset("PragmaAttributeSupport", Unset);
2175   if (!Unset)
2176     return SpecifiedResult;
2177 
2178   // Opt-out rules:
2179 
2180   // An attribute requires delayed parsing (LateParsed is on).
2181   switch (getLateAttrParseKind(&Attribute)) {
2182   case LateAttrParseKind::Never:
2183     break;
2184   case LateAttrParseKind::Standard:
2185     return false;
2186   case LateAttrParseKind::ExperimentalExt:
2187     // This is only late parsed in certain parsing contexts when
2188     // `LangOpts.ExperimentalLateParseAttributes` is true. Information about the
2189     // parsing context and `LangOpts` is not available in this method so just
2190     // opt this attribute out.
2191     return false;
2192   }
2193 
2194   // An attribute has no GNU/CXX11 spelling
2195   if (!hasGNUorCXX11Spelling(Attribute))
2196     return false;
2197   // An attribute subject list has a subject that isn't covered by one of the
2198   // subject match rules or has no subjects at all.
2199   if (Attribute.isValueUnset("Subjects"))
2200     return false;
2201   const Record *SubjectObj = Attribute.getValueAsDef("Subjects");
2202   bool HasAtLeastOneValidSubject = false;
2203   for (const auto *Subject : SubjectObj->getValueAsListOfDefs("Subjects")) {
2204     if (!isSupportedPragmaClangAttributeSubject(*Subject))
2205       continue;
2206     if (!SubjectsToRules.contains(Subject))
2207       return false;
2208     HasAtLeastOneValidSubject = true;
2209   }
2210   return HasAtLeastOneValidSubject;
2211 }
2212 
2213 static std::string GenerateTestExpression(ArrayRef<const Record *> LangOpts) {
2214   std::string Test;
2215 
2216   for (auto *E : LangOpts) {
2217     if (!Test.empty())
2218       Test += " || ";
2219 
2220     const StringRef Code = E->getValueAsString("CustomCode");
2221     if (!Code.empty()) {
2222       Test += "(";
2223       Test += Code;
2224       Test += ")";
2225       if (!E->getValueAsString("Name").empty()) {
2226         PrintWarning(
2227             E->getLoc(),
2228             "non-empty 'Name' field ignored because 'CustomCode' was supplied");
2229       }
2230     } else {
2231       Test += "LangOpts.";
2232       Test += E->getValueAsString("Name");
2233     }
2234   }
2235 
2236   if (Test.empty())
2237     return "true";
2238 
2239   return Test;
2240 }
2241 
2242 void
2243 PragmaClangAttributeSupport::generateStrictConformsTo(const Record &Attr,
2244                                                       raw_ostream &OS) {
2245   if (!isAttributedSupported(Attr) || Attr.isValueUnset("Subjects"))
2246     return;
2247   // Generate a function that constructs a set of matching rules that describe
2248   // to which declarations the attribute should apply to.
2249   OS << "void getPragmaAttributeMatchRules("
2250      << "llvm::SmallVectorImpl<std::pair<"
2251      << AttributeSubjectMatchRule::EnumName
2252      << ", bool>> &MatchRules, const LangOptions &LangOpts) const override {\n";
2253   const Record *SubjectObj = Attr.getValueAsDef("Subjects");
2254   for (const auto *Subject : SubjectObj->getValueAsListOfDefs("Subjects")) {
2255     if (!isSupportedPragmaClangAttributeSubject(*Subject))
2256       continue;
2257     auto It = SubjectsToRules.find(Subject);
2258     assert(It != SubjectsToRules.end() &&
2259            "This attribute is unsupported by #pragma clang attribute");
2260     for (const auto &Rule : It->getSecond().getAggregateRuleSet()) {
2261       // The rule might be language specific, so only subtract it from the given
2262       // rules if the specific language options are specified.
2263       std::vector<const Record *> LangOpts = Rule.getLangOpts();
2264       OS << "  MatchRules.push_back(std::make_pair(" << Rule.getEnumValue()
2265          << ", /*IsSupported=*/" << GenerateTestExpression(LangOpts)
2266          << "));\n";
2267     }
2268   }
2269   OS << "}\n\n";
2270 }
2271 
2272 void PragmaClangAttributeSupport::generateParsingHelpers(raw_ostream &OS) {
2273   // Generate routines that check the names of sub-rules.
2274   OS << "std::optional<attr::SubjectMatchRule> "
2275         "defaultIsAttributeSubjectMatchSubRuleFor(StringRef, bool) {\n";
2276   OS << "  return std::nullopt;\n";
2277   OS << "}\n\n";
2278 
2279   MapVector<const Record *, std::vector<AttributeSubjectMatchRule>>
2280       SubMatchRules;
2281   for (const auto &Rule : Rules) {
2282     if (!Rule.isSubRule())
2283       continue;
2284     SubMatchRules[Rule.MetaSubject].push_back(Rule);
2285   }
2286 
2287   for (const auto &SubMatchRule : SubMatchRules) {
2288     OS << "std::optional<attr::SubjectMatchRule> "
2289           "isAttributeSubjectMatchSubRuleFor_"
2290        << SubMatchRule.first->getValueAsString("Name")
2291        << "(StringRef Name, bool IsUnless) {\n";
2292     OS << "  if (IsUnless)\n";
2293     OS << "    return "
2294           "llvm::StringSwitch<std::optional<attr::SubjectMatchRule>>(Name).\n";
2295     for (const auto &Rule : SubMatchRule.second) {
2296       if (Rule.isNegatedSubRule())
2297         OS << "    Case(\"" << Rule.getName() << "\", " << Rule.getEnumValue()
2298            << ").\n";
2299     }
2300     OS << "    Default(std::nullopt);\n";
2301     OS << "  return "
2302           "llvm::StringSwitch<std::optional<attr::SubjectMatchRule>>(Name).\n";
2303     for (const auto &Rule : SubMatchRule.second) {
2304       if (!Rule.isNegatedSubRule())
2305         OS << "  Case(\"" << Rule.getName() << "\", " << Rule.getEnumValue()
2306            << ").\n";
2307     }
2308     OS << "  Default(std::nullopt);\n";
2309     OS << "}\n\n";
2310   }
2311 
2312   // Generate the function that checks for the top-level rules.
2313   OS << "std::pair<std::optional<attr::SubjectMatchRule>, "
2314         "std::optional<attr::SubjectMatchRule> (*)(StringRef, "
2315         "bool)> isAttributeSubjectMatchRule(StringRef Name) {\n";
2316   OS << "  return "
2317         "llvm::StringSwitch<std::pair<std::optional<attr::SubjectMatchRule>, "
2318         "std::optional<attr::SubjectMatchRule> (*) (StringRef, "
2319         "bool)>>(Name).\n";
2320   for (const auto &Rule : Rules) {
2321     if (Rule.isSubRule())
2322       continue;
2323     std::string SubRuleFunction;
2324     if (SubMatchRules.count(Rule.MetaSubject))
2325       SubRuleFunction =
2326           ("isAttributeSubjectMatchSubRuleFor_" + Rule.getName()).str();
2327     else
2328       SubRuleFunction = "defaultIsAttributeSubjectMatchSubRuleFor";
2329     OS << "  Case(\"" << Rule.getName() << "\", std::make_pair("
2330        << Rule.getEnumValue() << ", " << SubRuleFunction << ")).\n";
2331   }
2332   OS << "  Default(std::make_pair(std::nullopt, "
2333         "defaultIsAttributeSubjectMatchSubRuleFor));\n";
2334   OS << "}\n\n";
2335 
2336   // Generate the function that checks for the submatch rules.
2337   OS << "const char *validAttributeSubjectMatchSubRules("
2338      << AttributeSubjectMatchRule::EnumName << " Rule) {\n";
2339   OS << "  switch (Rule) {\n";
2340   for (const auto &SubMatchRule : SubMatchRules) {
2341     OS << "  case "
2342        << AttributeSubjectMatchRule(SubMatchRule.first, nullptr).getEnumValue()
2343        << ":\n";
2344     OS << "  return \"'";
2345     bool IsFirst = true;
2346     for (const auto &Rule : SubMatchRule.second) {
2347       if (!IsFirst)
2348         OS << ", '";
2349       IsFirst = false;
2350       if (Rule.isNegatedSubRule())
2351         OS << "unless(";
2352       OS << Rule.getName();
2353       if (Rule.isNegatedSubRule())
2354         OS << ')';
2355       OS << "'";
2356     }
2357     OS << "\";\n";
2358   }
2359   OS << "  default: return nullptr;\n";
2360   OS << "  }\n";
2361   OS << "}\n\n";
2362 }
2363 
2364 template <typename Fn> static void forEachSpelling(const Record &Attr, Fn &&F) {
2365   for (const FlattenedSpelling &S : GetFlattenedSpellings(Attr)) {
2366     F(S);
2367   }
2368 }
2369 
2370 static std::map<StringRef, std::vector<const Record *>> NameToAttrsMap;
2371 
2372 /// Build a map from the attribute name to the Attrs that use that name. If more
2373 /// than one Attr use a name, the arguments could be different so a more complex
2374 /// check is needed in the generated switch.
2375 static void generateNameToAttrsMap(const RecordKeeper &Records) {
2376   for (const auto *A : Records.getAllDerivedDefinitions("Attr")) {
2377     for (const FlattenedSpelling &S : GetFlattenedSpellings(*A)) {
2378       auto [It, Inserted] = NameToAttrsMap.try_emplace(S.name());
2379       if (Inserted || !is_contained(It->second, A))
2380         It->second.emplace_back(A);
2381     }
2382   }
2383 }
2384 
2385 /// Generate the info needed to produce the case values in case more than one
2386 /// attribute has the same name. Store the info in a map that can be processed
2387 /// after all attributes are seen.
2388 static void generateFlattenedSpellingInfo(const Record &Attr,
2389                                           std::map<StringRef, FSIVecTy> &Map,
2390                                           uint32_t ArgMask = 0) {
2391   std::string TargetTest;
2392   if (Attr.isSubClassOf("TargetSpecificAttr") &&
2393       !Attr.isValueUnset("ParseKind")) {
2394     const Record *T = Attr.getValueAsDef("Target");
2395     std::vector<StringRef> Arches = T->getValueAsListOfStrings("Arches");
2396     (void)GenerateTargetSpecificAttrChecks(T, Arches, TargetTest, nullptr);
2397   }
2398 
2399   forEachSpelling(Attr, [&](const FlattenedSpelling &S) {
2400     Map[S.name()].emplace_back(S.variety(), S.nameSpace(), TargetTest, ArgMask);
2401   });
2402 }
2403 
2404 static bool nameAppliesToOneAttribute(StringRef Name) {
2405   auto It = NameToAttrsMap.find(Name);
2406   assert(It != NameToAttrsMap.end());
2407   return It->second.size() == 1;
2408 }
2409 
2410 static bool emitIfSimpleValue(StringRef Name, uint32_t ArgMask,
2411                               raw_ostream &OS) {
2412   if (nameAppliesToOneAttribute(Name)) {
2413     OS << ".Case(\"" << Name << "\", ";
2414     if (ArgMask != 0)
2415       OS << ArgMask << ")\n";
2416     else
2417       OS << "true)\n";
2418     return true;
2419   }
2420   return false;
2421 }
2422 
2423 static void emitSingleCondition(const FlattenedSpellingInfo &FSI,
2424                                 raw_ostream &OS) {
2425   OS << "(Syntax==AttributeCommonInfo::AS_" << FSI.Syntax << " && ";
2426   if (!FSI.Scope.empty())
2427     OS << "ScopeName && ScopeName->getName()==\"" << FSI.Scope << "\"";
2428   else
2429     OS << "!ScopeName";
2430   if (!FSI.TargetTest.empty())
2431     OS << " && " << FSI.TargetTest;
2432   OS << ")";
2433 }
2434 
2435 static void emitStringSwitchCases(std::map<StringRef, FSIVecTy> &Map,
2436                                   raw_ostream &OS) {
2437   for (const auto &[Name, Vec] : Map) {
2438     if (emitIfSimpleValue(Name, Vec[0].ArgMask, OS))
2439       continue;
2440 
2441     // Not simple, build expressions for each case.
2442     OS << ".Case(\"" << Name << "\", ";
2443     for (unsigned I = 0, E = Vec.size(); I < E; ++I) {
2444       emitSingleCondition(Vec[I], OS);
2445       uint32_t ArgMask = Vec[I].ArgMask;
2446       if (E == 1 && ArgMask == 0)
2447         continue;
2448 
2449       // More than one or it's the Mask form. Create a conditional expression.
2450       uint32_t SuccessValue = ArgMask != 0 ? ArgMask : 1;
2451       OS << " ? " << SuccessValue << " : ";
2452       if (I == E - 1)
2453         OS << 0;
2454     }
2455     OS << ")\n";
2456   }
2457 }
2458 
2459 static bool isTypeArgument(const Record *Arg) {
2460   return !Arg->getSuperClasses().empty() &&
2461          Arg->getSuperClasses().back().first->getName() == "TypeArgument";
2462 }
2463 
2464 /// Emits the first-argument-is-type property for attributes.
2465 static void emitClangAttrTypeArgList(const RecordKeeper &Records,
2466                                      raw_ostream &OS) {
2467   OS << "#if defined(CLANG_ATTR_TYPE_ARG_LIST)\n";
2468   std::map<StringRef, FSIVecTy> FSIMap;
2469   for (const auto *Attr : Records.getAllDerivedDefinitions("Attr")) {
2470     // Determine whether the first argument is a type.
2471     std::vector<const Record *> Args = Attr->getValueAsListOfDefs("Args");
2472     if (Args.empty())
2473       continue;
2474 
2475     if (!isTypeArgument(Args[0]))
2476       continue;
2477     generateFlattenedSpellingInfo(*Attr, FSIMap);
2478   }
2479   emitStringSwitchCases(FSIMap, OS);
2480   OS << "#endif // CLANG_ATTR_TYPE_ARG_LIST\n\n";
2481 }
2482 
2483 /// Emits the parse-arguments-in-unevaluated-context property for
2484 /// attributes.
2485 static void emitClangAttrArgContextList(const RecordKeeper &Records,
2486                                         raw_ostream &OS) {
2487   OS << "#if defined(CLANG_ATTR_ARG_CONTEXT_LIST)\n";
2488   std::map<StringRef, FSIVecTy> FSIMap;
2489   ParsedAttrMap Attrs = getParsedAttrList(Records);
2490   for (const auto &I : Attrs) {
2491     const Record &Attr = *I.second;
2492 
2493     if (!Attr.getValueAsBit("ParseArgumentsAsUnevaluated"))
2494       continue;
2495     generateFlattenedSpellingInfo(Attr, FSIMap);
2496   }
2497   emitStringSwitchCases(FSIMap, OS);
2498   OS << "#endif // CLANG_ATTR_ARG_CONTEXT_LIST\n\n";
2499 }
2500 
2501 static bool isIdentifierArgument(const Record *Arg) {
2502   return !Arg->getSuperClasses().empty() &&
2503          StringSwitch<bool>(Arg->getSuperClasses().back().first->getName())
2504              .Case("IdentifierArgument", true)
2505              .Case("EnumArgument", true)
2506              .Case("VariadicEnumArgument", true)
2507              .Default(false);
2508 }
2509 
2510 static bool isVariadicIdentifierArgument(const Record *Arg) {
2511   return !Arg->getSuperClasses().empty() &&
2512          StringSwitch<bool>(Arg->getSuperClasses().back().first->getName())
2513              .Case("VariadicIdentifierArgument", true)
2514              .Case("VariadicParamOrParamIdxArgument", true)
2515              .Default(false);
2516 }
2517 
2518 static bool isVariadicExprArgument(const Record *Arg) {
2519   return !Arg->getSuperClasses().empty() &&
2520          StringSwitch<bool>(Arg->getSuperClasses().back().first->getName())
2521              .Case("VariadicExprArgument", true)
2522              .Default(false);
2523 }
2524 
2525 static bool isStringLiteralArgument(const Record *Arg) {
2526   if (Arg->getSuperClasses().empty())
2527     return false;
2528   StringRef ArgKind = Arg->getSuperClasses().back().first->getName();
2529   if (ArgKind == "EnumArgument")
2530     return Arg->getValueAsBit("IsString");
2531   return ArgKind == "StringArgument";
2532 }
2533 
2534 static bool isVariadicStringLiteralArgument(const Record *Arg) {
2535   if (Arg->getSuperClasses().empty())
2536     return false;
2537   StringRef ArgKind = Arg->getSuperClasses().back().first->getName();
2538   if (ArgKind == "VariadicEnumArgument")
2539     return Arg->getValueAsBit("IsString");
2540   return ArgKind == "VariadicStringArgument";
2541 }
2542 
2543 static void emitClangAttrVariadicIdentifierArgList(const RecordKeeper &Records,
2544                                                    raw_ostream &OS) {
2545   OS << "#if defined(CLANG_ATTR_VARIADIC_IDENTIFIER_ARG_LIST)\n";
2546   std::map<StringRef, FSIVecTy> FSIMap;
2547   for (const auto *A : Records.getAllDerivedDefinitions("Attr")) {
2548     // Determine whether the first argument is a variadic identifier.
2549     std::vector<const Record *> Args = A->getValueAsListOfDefs("Args");
2550     if (Args.empty() || !isVariadicIdentifierArgument(Args[0]))
2551       continue;
2552     generateFlattenedSpellingInfo(*A, FSIMap);
2553   }
2554   emitStringSwitchCases(FSIMap, OS);
2555   OS << "#endif // CLANG_ATTR_VARIADIC_IDENTIFIER_ARG_LIST\n\n";
2556 }
2557 
2558 // Emits the list of arguments that should be parsed as unevaluated string
2559 // literals for each attribute.
2560 static void
2561 emitClangAttrUnevaluatedStringLiteralList(const RecordKeeper &Records,
2562                                           raw_ostream &OS) {
2563   OS << "#if defined(CLANG_ATTR_STRING_LITERAL_ARG_LIST)\n";
2564 
2565   auto MakeMask = [](ArrayRef<const Record *> Args) {
2566     uint32_t Bits = 0;
2567     assert(Args.size() <= 32 && "unsupported number of arguments in attribute");
2568     for (uint32_t N = 0; N < Args.size(); ++N) {
2569       Bits |= (isStringLiteralArgument(Args[N]) << N);
2570       // If we have a variadic string argument, set all the remaining bits to 1
2571       if (isVariadicStringLiteralArgument(Args[N])) {
2572         Bits |= maskTrailingZeros<decltype(Bits)>(N);
2573         break;
2574       }
2575     }
2576     return Bits;
2577   };
2578 
2579   std::map<StringRef, FSIVecTy> FSIMap;
2580   for (const auto *Attr : Records.getAllDerivedDefinitions("Attr")) {
2581     // Determine whether there are any string arguments.
2582     uint32_t ArgMask = MakeMask(Attr->getValueAsListOfDefs("Args"));
2583     if (!ArgMask)
2584       continue;
2585     generateFlattenedSpellingInfo(*Attr, FSIMap, ArgMask);
2586   }
2587   emitStringSwitchCases(FSIMap, OS);
2588   OS << "#endif // CLANG_ATTR_STRING_LITERAL_ARG_LIST\n\n";
2589 }
2590 
2591 // Emits the first-argument-is-identifier property for attributes.
2592 static void emitClangAttrIdentifierArgList(const RecordKeeper &Records,
2593                                            raw_ostream &OS) {
2594   OS << "#if defined(CLANG_ATTR_IDENTIFIER_ARG_LIST)\n";
2595   std::map<StringRef, FSIVecTy> FSIMap;
2596   for (const auto *Attr : Records.getAllDerivedDefinitions("Attr")) {
2597     // Determine whether the first argument is an identifier.
2598     std::vector<const Record *> Args = Attr->getValueAsListOfDefs("Args");
2599     if (Args.empty() || !isIdentifierArgument(Args[0]))
2600       continue;
2601     generateFlattenedSpellingInfo(*Attr, FSIMap);
2602   }
2603   emitStringSwitchCases(FSIMap, OS);
2604   OS << "#endif // CLANG_ATTR_IDENTIFIER_ARG_LIST\n\n";
2605 }
2606 
2607 // Emits the list for attributes having StrictEnumParameters.
2608 static void emitClangAttrStrictIdentifierArgList(const RecordKeeper &Records,
2609                                                  raw_ostream &OS) {
2610   OS << "#if defined(CLANG_ATTR_STRICT_IDENTIFIER_ARG_LIST)\n";
2611   std::map<StringRef, FSIVecTy> FSIMap;
2612   for (const auto *Attr : Records.getAllDerivedDefinitions("Attr")) {
2613     if (!Attr->getValueAsBit("StrictEnumParameters"))
2614       continue;
2615     // Check that there is really an identifier argument.
2616     std::vector<const Record *> Args = Attr->getValueAsListOfDefs("Args");
2617     if (none_of(Args, [&](const Record *R) { return isIdentifierArgument(R); }))
2618       continue;
2619     generateFlattenedSpellingInfo(*Attr, FSIMap);
2620   }
2621   emitStringSwitchCases(FSIMap, OS);
2622   OS << "#endif // CLANG_ATTR_STRICT_IDENTIFIER_ARG_LIST\n\n";
2623 }
2624 
2625 static bool keywordThisIsaIdentifierInArgument(const Record *Arg) {
2626   return !Arg->getSuperClasses().empty() &&
2627          StringSwitch<bool>(Arg->getSuperClasses().back().first->getName())
2628              .Case("VariadicParamOrParamIdxArgument", true)
2629              .Default(false);
2630 }
2631 
2632 static void emitClangAttrThisIsaIdentifierArgList(const RecordKeeper &Records,
2633                                                   raw_ostream &OS) {
2634   OS << "#if defined(CLANG_ATTR_THIS_ISA_IDENTIFIER_ARG_LIST)\n";
2635   std::map<StringRef, FSIVecTy> FSIMap;
2636   for (const auto *A : Records.getAllDerivedDefinitions("Attr")) {
2637     // Determine whether the first argument is a variadic identifier.
2638     std::vector<const Record *> Args = A->getValueAsListOfDefs("Args");
2639     if (Args.empty() || !keywordThisIsaIdentifierInArgument(Args[0]))
2640       continue;
2641     generateFlattenedSpellingInfo(*A, FSIMap);
2642   }
2643   emitStringSwitchCases(FSIMap, OS);
2644   OS << "#endif // CLANG_ATTR_THIS_ISA_IDENTIFIER_ARG_LIST\n\n";
2645 }
2646 
2647 static void emitClangAttrAcceptsExprPack(const RecordKeeper &Records,
2648                                          raw_ostream &OS) {
2649   OS << "#if defined(CLANG_ATTR_ACCEPTS_EXPR_PACK)\n";
2650   ParsedAttrMap Attrs = getParsedAttrList(Records);
2651   std::map<StringRef, FSIVecTy> FSIMap;
2652   for (const auto &I : Attrs) {
2653     const Record &Attr = *I.second;
2654 
2655     if (!Attr.getValueAsBit("AcceptsExprPack"))
2656       continue;
2657     generateFlattenedSpellingInfo(Attr, FSIMap);
2658   }
2659   emitStringSwitchCases(FSIMap, OS);
2660   OS << "#endif // CLANG_ATTR_ACCEPTS_EXPR_PACK\n\n";
2661 }
2662 
2663 static bool isRegularKeywordAttribute(const FlattenedSpelling &S) {
2664   return (S.variety() == "Keyword" &&
2665           !S.getSpellingRecord().getValueAsBit("HasOwnParseRules"));
2666 }
2667 
2668 static void emitFormInitializer(raw_ostream &OS,
2669                                 const FlattenedSpelling &Spelling,
2670                                 StringRef SpellingIndex) {
2671   bool IsAlignas =
2672       (Spelling.variety() == "Keyword" && Spelling.name() == "alignas");
2673   OS << "{AttributeCommonInfo::AS_" << Spelling.variety() << ", "
2674      << SpellingIndex << ", " << (IsAlignas ? "true" : "false")
2675      << " /*IsAlignas*/, "
2676      << (isRegularKeywordAttribute(Spelling) ? "true" : "false")
2677      << " /*IsRegularKeywordAttribute*/}";
2678 }
2679 
2680 static void emitAttributes(const RecordKeeper &Records, raw_ostream &OS,
2681                            bool Header) {
2682   ParsedAttrMap AttrMap = getParsedAttrList(Records);
2683 
2684   // Helper to print the starting character of an attribute argument. If there
2685   // hasn't been an argument yet, it prints an opening parenthese; otherwise it
2686   // prints a comma.
2687   OS << "static inline void DelimitAttributeArgument("
2688      << "raw_ostream& OS, bool& IsFirst) {\n"
2689      << "  if (IsFirst) {\n"
2690      << "    IsFirst = false;\n"
2691      << "    OS << \"(\";\n"
2692      << "  } else\n"
2693      << "    OS << \", \";\n"
2694      << "}\n";
2695 
2696   for (const auto *Attr : Records.getAllDerivedDefinitions("Attr")) {
2697     const Record &R = *Attr;
2698 
2699     // FIXME: Currently, documentation is generated as-needed due to the fact
2700     // that there is no way to allow a generated project "reach into" the docs
2701     // directory (for instance, it may be an out-of-tree build). However, we want
2702     // to ensure that every attribute has a Documentation field, and produce an
2703     // error if it has been neglected. Otherwise, the on-demand generation which
2704     // happens server-side will fail. This code is ensuring that functionality,
2705     // even though this Emitter doesn't technically need the documentation.
2706     // When attribute documentation can be generated as part of the build
2707     // itself, this code can be removed.
2708     (void)R.getValueAsListOfDefs("Documentation");
2709 
2710     if (!R.getValueAsBit("ASTNode"))
2711       continue;
2712 
2713     ArrayRef<std::pair<const Record *, SMRange>> Supers = R.getSuperClasses();
2714     assert(!Supers.empty() && "Forgot to specify a superclass for the attr");
2715     std::string SuperName;
2716     bool Inheritable = false;
2717     for (const auto &[R, _] : reverse(Supers)) {
2718       if (R->getName() != "TargetSpecificAttr" &&
2719           R->getName() != "DeclOrTypeAttr" && SuperName.empty())
2720         SuperName = R->getName().str();
2721       if (R->getName() == "InheritableAttr")
2722         Inheritable = true;
2723     }
2724 
2725     if (Header)
2726       OS << "class CLANG_ABI " << R.getName() << "Attr : public " << SuperName
2727          << " {\n";
2728     else
2729       OS << "\n// " << R.getName() << "Attr implementation\n\n";
2730 
2731     std::vector<const Record *> ArgRecords = R.getValueAsListOfDefs("Args");
2732     std::vector<std::unique_ptr<Argument>> Args;
2733     Args.reserve(ArgRecords.size());
2734 
2735     bool AttrAcceptsExprPack = Attr->getValueAsBit("AcceptsExprPack");
2736     if (AttrAcceptsExprPack) {
2737       for (size_t I = 0; I < ArgRecords.size(); ++I) {
2738         const Record *ArgR = ArgRecords[I];
2739         if (isIdentifierArgument(ArgR) || isVariadicIdentifierArgument(ArgR) ||
2740             isTypeArgument(ArgR))
2741           PrintFatalError(Attr->getLoc(),
2742                           "Attributes accepting packs cannot also "
2743                           "have identifier or type arguments.");
2744         // When trying to determine if value-dependent expressions can populate
2745         // the attribute without prior instantiation, the decision is made based
2746         // on the assumption that only the last argument is ever variadic.
2747         if (I < (ArgRecords.size() - 1) && isVariadicExprArgument(ArgR))
2748           PrintFatalError(Attr->getLoc(),
2749                           "Attributes accepting packs can only have the last "
2750                           "argument be variadic.");
2751       }
2752     }
2753 
2754     bool HasOptArg = false;
2755     bool HasFakeArg = false;
2756     for (const auto *ArgRecord : ArgRecords) {
2757       Args.emplace_back(createArgument(*ArgRecord, R.getName()));
2758       if (Header) {
2759         Args.back()->writeDeclarations(OS);
2760         OS << "\n\n";
2761       }
2762 
2763       // For these purposes, fake takes priority over optional.
2764       if (Args.back()->isFake()) {
2765         HasFakeArg = true;
2766       } else if (Args.back()->isOptional()) {
2767         HasOptArg = true;
2768       }
2769     }
2770 
2771     std::unique_ptr<VariadicExprArgument> DelayedArgs = nullptr;
2772     if (AttrAcceptsExprPack) {
2773       DelayedArgs =
2774           std::make_unique<VariadicExprArgument>("DelayedArgs", R.getName());
2775       if (Header) {
2776         DelayedArgs->writeDeclarations(OS);
2777         OS << "\n\n";
2778       }
2779     }
2780 
2781     if (Header)
2782       OS << "public:\n";
2783 
2784     std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(R);
2785 
2786     // If there are zero or one spellings, all spelling-related functionality
2787     // can be elided. If all of the spellings share the same name, the spelling
2788     // functionality can also be elided.
2789     bool ElideSpelling = (Spellings.size() <= 1) ||
2790                          SpellingNamesAreCommon(Spellings);
2791 
2792     // This maps spelling index values to semantic Spelling enumerants.
2793     SemanticSpellingMap SemanticToSyntacticMap;
2794 
2795     std::string SpellingEnum;
2796     if (Spellings.size() > 1)
2797       SpellingEnum = CreateSemanticSpellings(Spellings, SemanticToSyntacticMap);
2798     if (Header)
2799       OS << SpellingEnum;
2800 
2801     const auto &ParsedAttrSpellingItr =
2802         find_if(AttrMap, [R](const std::pair<std::string, const Record *> &P) {
2803           return &R == P.second;
2804         });
2805 
2806     // Emit CreateImplicit factory methods.
2807     auto emitCreate = [&](bool Implicit, bool DelayedArgsOnly, bool emitFake) {
2808       if (Header)
2809         OS << "  static ";
2810       OS << R.getName() << "Attr *";
2811       if (!Header)
2812         OS << R.getName() << "Attr::";
2813       OS << "Create";
2814       if (Implicit)
2815         OS << "Implicit";
2816       if (DelayedArgsOnly)
2817         OS << "WithDelayedArgs";
2818       OS << "(";
2819       OS << "ASTContext &Ctx";
2820       if (!DelayedArgsOnly) {
2821         for (auto const &ai : Args) {
2822           if (ai->isFake() && !emitFake)
2823             continue;
2824           OS << ", ";
2825           ai->writeCtorParameters(OS);
2826         }
2827       } else {
2828         OS << ", ";
2829         DelayedArgs->writeCtorParameters(OS);
2830       }
2831       OS << ", const AttributeCommonInfo &CommonInfo";
2832       OS << ")";
2833       if (Header) {
2834         OS << ";\n";
2835         return;
2836       }
2837 
2838       OS << " {\n";
2839       OS << "  auto *A = new (Ctx) " << R.getName();
2840       OS << "Attr(Ctx, CommonInfo";
2841 
2842       if (!DelayedArgsOnly) {
2843         for (auto const &ai : Args) {
2844           if (ai->isFake() && !emitFake)
2845             continue;
2846           OS << ", ";
2847           ai->writeImplicitCtorArgs(OS);
2848         }
2849       }
2850       OS << ");\n";
2851       if (Implicit) {
2852         OS << "  A->setImplicit(true);\n";
2853       }
2854       if (Implicit || ElideSpelling) {
2855         OS << "  if (!A->isAttributeSpellingListCalculated() && "
2856               "!A->getAttrName())\n";
2857         OS << "    A->setAttributeSpellingListIndex(0);\n";
2858       }
2859       if (DelayedArgsOnly) {
2860         OS << "  A->setDelayedArgs(Ctx, ";
2861         DelayedArgs->writeImplicitCtorArgs(OS);
2862         OS << ");\n";
2863       }
2864       OS << "  return A;\n}\n\n";
2865     };
2866 
2867     auto emitCreateNoCI = [&](bool Implicit, bool DelayedArgsOnly,
2868                               bool emitFake) {
2869       if (Header)
2870         OS << "  static ";
2871       OS << R.getName() << "Attr *";
2872       if (!Header)
2873         OS << R.getName() << "Attr::";
2874       OS << "Create";
2875       if (Implicit)
2876         OS << "Implicit";
2877       if (DelayedArgsOnly)
2878         OS << "WithDelayedArgs";
2879       OS << "(";
2880       OS << "ASTContext &Ctx";
2881       if (!DelayedArgsOnly) {
2882         for (auto const &ai : Args) {
2883           if (ai->isFake() && !emitFake)
2884             continue;
2885           OS << ", ";
2886           ai->writeCtorParameters(OS);
2887         }
2888       } else {
2889         OS << ", ";
2890         DelayedArgs->writeCtorParameters(OS);
2891       }
2892       OS << ", SourceRange Range";
2893       if (Header)
2894         OS << " = {}";
2895       if (Spellings.size() > 1) {
2896         OS << ", Spelling S";
2897         if (Header)
2898           OS << " = " << SemanticToSyntacticMap[0];
2899       }
2900       OS << ")";
2901       if (Header) {
2902         OS << ";\n";
2903         return;
2904       }
2905 
2906       OS << " {\n";
2907       OS << "  AttributeCommonInfo I(Range, ";
2908 
2909       if (ParsedAttrSpellingItr != std::end(AttrMap))
2910         OS << "AT_" << ParsedAttrSpellingItr->first;
2911       else
2912         OS << "NoSemaHandlerAttribute";
2913 
2914       if (Spellings.size() == 0) {
2915         OS << ", AttributeCommonInfo::Form::Implicit()";
2916       } else if (Spellings.size() == 1) {
2917         OS << ", ";
2918         emitFormInitializer(OS, Spellings[0], "0");
2919       } else {
2920         OS << ", [&]() {\n";
2921         OS << "    switch (S) {\n";
2922         std::set<std::string> Uniques;
2923         unsigned Idx = 0;
2924         for (auto I = Spellings.begin(), E = Spellings.end(); I != E;
2925              ++I, ++Idx) {
2926           const FlattenedSpelling &S = *I;
2927           const auto &Name = SemanticToSyntacticMap[Idx];
2928           if (Uniques.insert(Name).second) {
2929             OS << "    case " << Name << ":\n";
2930             OS << "      return AttributeCommonInfo::Form";
2931             emitFormInitializer(OS, S, Name);
2932             OS << ";\n";
2933           }
2934         }
2935         OS << "    default:\n";
2936         OS << "      llvm_unreachable(\"Unknown attribute spelling!\");\n"
2937            << "      return AttributeCommonInfo::Form";
2938         emitFormInitializer(OS, Spellings[0], "0");
2939         OS << ";\n"
2940            << "    }\n"
2941            << "  }()";
2942       }
2943 
2944       OS << ");\n";
2945       OS << "  return Create";
2946       if (Implicit)
2947         OS << "Implicit";
2948       if (DelayedArgsOnly)
2949         OS << "WithDelayedArgs";
2950       OS << "(Ctx";
2951       if (!DelayedArgsOnly) {
2952         for (auto const &ai : Args) {
2953           if (ai->isFake() && !emitFake)
2954             continue;
2955           OS << ", ";
2956           ai->writeImplicitCtorArgs(OS);
2957         }
2958       } else {
2959         OS << ", ";
2960         DelayedArgs->writeImplicitCtorArgs(OS);
2961       }
2962       OS << ", I);\n";
2963       OS << "}\n\n";
2964     };
2965 
2966     auto emitCreates = [&](bool DelayedArgsOnly, bool emitFake) {
2967       emitCreate(true, DelayedArgsOnly, emitFake);
2968       emitCreate(false, DelayedArgsOnly, emitFake);
2969       emitCreateNoCI(true, DelayedArgsOnly, emitFake);
2970       emitCreateNoCI(false, DelayedArgsOnly, emitFake);
2971     };
2972 
2973     if (Header)
2974       OS << "  // Factory methods\n";
2975 
2976     // Emit a CreateImplicit that takes all the arguments.
2977     emitCreates(false, true);
2978 
2979     // Emit a CreateImplicit that takes all the non-fake arguments.
2980     if (HasFakeArg)
2981       emitCreates(false, false);
2982 
2983     // Emit a CreateWithDelayedArgs that takes only the dependent argument
2984     // expressions.
2985     if (DelayedArgs)
2986       emitCreates(true, false);
2987 
2988     // Emit constructors.
2989     auto emitCtor = [&](bool emitOpt, bool emitFake, bool emitNoArgs) {
2990       auto shouldEmitArg = [=](const std::unique_ptr<Argument> &arg) {
2991         if (emitNoArgs)
2992           return false;
2993         if (arg->isFake())
2994           return emitFake;
2995         if (arg->isOptional())
2996           return emitOpt;
2997         return true;
2998       };
2999       if (Header)
3000         OS << "  ";
3001       else
3002         OS << R.getName() << "Attr::";
3003       OS << R.getName()
3004          << "Attr(ASTContext &Ctx, const AttributeCommonInfo &CommonInfo";
3005       OS << '\n';
3006       for (auto const &ai : Args) {
3007         if (!shouldEmitArg(ai))
3008           continue;
3009         OS << "              , ";
3010         ai->writeCtorParameters(OS);
3011         OS << "\n";
3012       }
3013 
3014       OS << "             )";
3015       if (Header) {
3016         OS << ";\n";
3017         return;
3018       }
3019       OS << "\n  : " << SuperName << "(Ctx, CommonInfo, ";
3020       OS << "attr::" << R.getName() << ", ";
3021 
3022       // Handle different late parsing modes.
3023       OS << "/*IsLateParsed=*/";
3024       switch (getLateAttrParseKind(&R)) {
3025       case LateAttrParseKind::Never:
3026         OS << "false";
3027         break;
3028       case LateAttrParseKind::ExperimentalExt:
3029         // Currently no clients need to know the distinction between `Standard`
3030         // and `ExperimentalExt` so treat `ExperimentalExt` just like
3031         // `Standard` for now.
3032       case LateAttrParseKind::Standard:
3033         // Note: This is misleading. `IsLateParsed` doesn't mean the
3034         // attribute was actually late parsed. Instead it means the attribute in
3035         // `Attr.td` is marked as being late parsed. Maybe it should be called
3036         // `IsLateParseable`?
3037         OS << "true";
3038         break;
3039       }
3040 
3041       if (Inheritable) {
3042         OS << ", "
3043            << (R.getValueAsBit("InheritEvenIfAlreadyPresent") ? "true"
3044                                                               : "false");
3045       }
3046       OS << ")\n";
3047 
3048       for (auto const &ai : Args) {
3049         OS << "              , ";
3050         if (!shouldEmitArg(ai)) {
3051           ai->writeCtorDefaultInitializers(OS);
3052         } else {
3053           ai->writeCtorInitializers(OS);
3054         }
3055         OS << "\n";
3056       }
3057       if (DelayedArgs) {
3058         OS << "              , ";
3059         DelayedArgs->writeCtorDefaultInitializers(OS);
3060         OS << "\n";
3061       }
3062 
3063       OS << "  {\n";
3064 
3065       for (auto const &ai : Args) {
3066         if (!shouldEmitArg(ai))
3067           continue;
3068         ai->writeCtorBody(OS);
3069       }
3070       OS << "}\n\n";
3071     };
3072 
3073     if (Header)
3074       OS << "\n  // Constructors\n";
3075 
3076     // Emit a constructor that includes all the arguments.
3077     // This is necessary for cloning.
3078     emitCtor(true, true, false);
3079 
3080     // Emit a constructor that takes all the non-fake arguments.
3081     if (HasFakeArg)
3082       emitCtor(true, false, false);
3083 
3084     // Emit a constructor that takes all the non-fake, non-optional arguments.
3085     if (HasOptArg)
3086       emitCtor(false, false, false);
3087 
3088     // Emit constructors that takes no arguments if none already exists.
3089     // This is used for delaying arguments.
3090     bool HasRequiredArgs =
3091         count_if(Args, [=](const std::unique_ptr<Argument> &arg) {
3092           return !arg->isFake() && !arg->isOptional();
3093         });
3094     if (DelayedArgs && HasRequiredArgs)
3095       emitCtor(false, false, true);
3096 
3097     if (Header) {
3098       OS << '\n';
3099       OS << "  " << R.getName() << "Attr *clone(ASTContext &C) const;\n";
3100       OS << "  void printPretty(raw_ostream &OS,\n"
3101          << "                   const PrintingPolicy &Policy) const;\n";
3102       OS << "  const char *getSpelling() const;\n";
3103     }
3104 
3105     if (!ElideSpelling) {
3106       assert(!SemanticToSyntacticMap.empty() && "Empty semantic mapping list");
3107       if (Header)
3108         OS << "  Spelling getSemanticSpelling() const;\n";
3109       else {
3110         OS << R.getName() << "Attr::Spelling " << R.getName()
3111            << "Attr::getSemanticSpelling() const {\n";
3112         WriteSemanticSpellingSwitch("getAttributeSpellingListIndex()",
3113                                     SemanticToSyntacticMap, OS);
3114         OS << "}\n";
3115       }
3116     }
3117 
3118     if (Header)
3119       writeAttrAccessorDefinition(R, OS);
3120 
3121     for (auto const &ai : Args) {
3122       if (Header) {
3123         ai->writeAccessors(OS);
3124       } else {
3125         ai->writeAccessorDefinitions(OS);
3126       }
3127       OS << "\n\n";
3128 
3129       // Don't write conversion routines for fake arguments.
3130       if (ai->isFake()) continue;
3131 
3132       if (ai->isEnumArg())
3133         static_cast<const EnumArgument *>(ai.get())->writeConversion(OS,
3134                                                                      Header);
3135       else if (ai->isVariadicEnumArg())
3136         static_cast<const VariadicEnumArgument *>(ai.get())->writeConversion(
3137             OS, Header);
3138     }
3139 
3140     if (Header) {
3141       if (DelayedArgs) {
3142         DelayedArgs->writeAccessors(OS);
3143         DelayedArgs->writeSetter(OS);
3144       }
3145 
3146       OS << R.getValueAsString("AdditionalMembers");
3147       OS << "\n\n";
3148 
3149       OS << "  static bool classof(const Attr *A) { return A->getKind() == "
3150          << "attr::" << R.getName() << "; }\n";
3151 
3152       OS << "};\n\n";
3153     } else {
3154       if (DelayedArgs)
3155         DelayedArgs->writeAccessorDefinitions(OS);
3156 
3157       OS << R.getName() << "Attr *" << R.getName()
3158          << "Attr::clone(ASTContext &C) const {\n";
3159       OS << "  auto *A = new (C) " << R.getName() << "Attr(C, *this";
3160       for (auto const &ai : Args) {
3161         OS << ", ";
3162         ai->writeCloneArgs(OS);
3163       }
3164       OS << ");\n";
3165       OS << "  A->Inherited = Inherited;\n";
3166       OS << "  A->IsPackExpansion = IsPackExpansion;\n";
3167       OS << "  A->setImplicit(Implicit);\n";
3168       if (DelayedArgs) {
3169         OS << "  A->setDelayedArgs(C, ";
3170         DelayedArgs->writeCloneArgs(OS);
3171         OS << ");\n";
3172       }
3173       OS << "  return A;\n}\n\n";
3174 
3175       writePrettyPrintFunction(R, Args, OS);
3176       writeGetSpellingFunction(R, OS);
3177     }
3178   }
3179 }
3180 // Emits the class definitions for attributes.
3181 void clang::EmitClangAttrClass(const RecordKeeper &Records, raw_ostream &OS) {
3182   emitSourceFileHeader("Attribute classes' definitions", OS, Records);
3183 
3184   OS << "#ifndef LLVM_CLANG_ATTR_CLASSES_INC\n";
3185   OS << "#define LLVM_CLANG_ATTR_CLASSES_INC\n";
3186 
3187   emitAttributes(Records, OS, true);
3188 
3189   OS << "#endif // LLVM_CLANG_ATTR_CLASSES_INC\n";
3190 }
3191 
3192 // Emits the class method definitions for attributes.
3193 void clang::EmitClangAttrImpl(const RecordKeeper &Records, raw_ostream &OS) {
3194   emitSourceFileHeader("Attribute classes' member function definitions", OS,
3195                        Records);
3196 
3197   emitAttributes(Records, OS, false);
3198 
3199   // Instead of relying on virtual dispatch we just create a huge dispatch
3200   // switch. This is both smaller and faster than virtual functions.
3201   auto EmitFunc = [&](const char *Method) {
3202     OS << "  switch (getKind()) {\n";
3203     for (const auto *Attr : Records.getAllDerivedDefinitions("Attr")) {
3204       const Record &R = *Attr;
3205       if (!R.getValueAsBit("ASTNode"))
3206         continue;
3207 
3208       OS << "  case attr::" << R.getName() << ":\n";
3209       OS << "    return cast<" << R.getName() << "Attr>(this)->" << Method
3210          << ";\n";
3211     }
3212     OS << "  }\n";
3213     OS << "  llvm_unreachable(\"Unexpected attribute kind!\");\n";
3214     OS << "}\n\n";
3215   };
3216 
3217   OS << "const char *Attr::getSpelling() const {\n";
3218   EmitFunc("getSpelling()");
3219 
3220   OS << "Attr *Attr::clone(ASTContext &C) const {\n";
3221   EmitFunc("clone(C)");
3222 
3223   OS << "void Attr::printPretty(raw_ostream &OS, "
3224         "const PrintingPolicy &Policy) const {\n";
3225   EmitFunc("printPretty(OS, Policy)");
3226 }
3227 
3228 static void emitAttrList(raw_ostream &OS, StringRef Class,
3229                          ArrayRef<const Record *> AttrList) {
3230   for (auto Cur : AttrList) {
3231     OS << Class << "(" << Cur->getName() << ")\n";
3232   }
3233 }
3234 
3235 // Determines if an attribute has a Pragma spelling.
3236 static bool AttrHasPragmaSpelling(const Record *R) {
3237   std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(*R);
3238   return any_of(Spellings, [](const FlattenedSpelling &S) {
3239     return S.variety() == "Pragma";
3240   });
3241 }
3242 
3243 namespace {
3244 
3245   struct AttrClassDescriptor {
3246     const char * const MacroName;
3247     const char * const TableGenName;
3248   };
3249 
3250 } // end anonymous namespace
3251 
3252 static const AttrClassDescriptor AttrClassDescriptors[] = {
3253     {"ATTR", "Attr"},
3254     {"TYPE_ATTR", "TypeAttr"},
3255     {"STMT_ATTR", "StmtAttr"},
3256     {"DECL_OR_STMT_ATTR", "DeclOrStmtAttr"},
3257     {"INHERITABLE_ATTR", "InheritableAttr"},
3258     {"DECL_OR_TYPE_ATTR", "DeclOrTypeAttr"},
3259     {"INHERITABLE_PARAM_ATTR", "InheritableParamAttr"},
3260     {"INHERITABLE_PARAM_OR_STMT_ATTR", "InheritableParamOrStmtAttr"},
3261     {"PARAMETER_ABI_ATTR", "ParameterABIAttr"},
3262     {"HLSL_ANNOTATION_ATTR", "HLSLAnnotationAttr"}};
3263 
3264 static void emitDefaultDefine(raw_ostream &OS, StringRef name,
3265                               const char *superName) {
3266   OS << "#ifndef " << name << "\n";
3267   OS << "#define " << name << "(NAME) ";
3268   if (superName) OS << superName << "(NAME)";
3269   OS << "\n#endif\n\n";
3270 }
3271 
3272 namespace {
3273 
3274   /// A class of attributes.
3275   struct AttrClass {
3276     const AttrClassDescriptor &Descriptor;
3277     const Record *TheRecord;
3278     AttrClass *SuperClass = nullptr;
3279     std::vector<AttrClass*> SubClasses;
3280     std::vector<const Record *> Attrs;
3281 
3282     AttrClass(const AttrClassDescriptor &Descriptor, const Record *R)
3283         : Descriptor(Descriptor), TheRecord(R) {}
3284 
3285     void emitDefaultDefines(raw_ostream &OS) const {
3286       // Default the macro unless this is a root class (i.e. Attr).
3287       if (SuperClass) {
3288         emitDefaultDefine(OS, Descriptor.MacroName,
3289                           SuperClass->Descriptor.MacroName);
3290       }
3291     }
3292 
3293     void emitUndefs(raw_ostream &OS) const {
3294       OS << "#undef " << Descriptor.MacroName << "\n";
3295     }
3296 
3297     void emitAttrList(raw_ostream &OS) const {
3298       for (auto SubClass : SubClasses) {
3299         SubClass->emitAttrList(OS);
3300       }
3301 
3302       ::emitAttrList(OS, Descriptor.MacroName, Attrs);
3303     }
3304 
3305     void classifyAttrOnRoot(const Record *Attr) {
3306       bool result = classifyAttr(Attr);
3307       assert(result && "failed to classify on root"); (void) result;
3308     }
3309 
3310     void emitAttrRange(raw_ostream &OS) const {
3311       OS << "ATTR_RANGE(" << Descriptor.TableGenName
3312          << ", " << getFirstAttr()->getName()
3313          << ", " << getLastAttr()->getName() << ")\n";
3314     }
3315 
3316   private:
3317     bool classifyAttr(const Record *Attr) {
3318       // Check all the subclasses.
3319       for (auto SubClass : SubClasses) {
3320         if (SubClass->classifyAttr(Attr))
3321           return true;
3322       }
3323 
3324       // It's not more specific than this class, but it might still belong here.
3325       if (Attr->isSubClassOf(TheRecord)) {
3326         Attrs.push_back(Attr);
3327         return true;
3328       }
3329 
3330       return false;
3331     }
3332 
3333     const Record *getFirstAttr() const {
3334       if (!SubClasses.empty())
3335         return SubClasses.front()->getFirstAttr();
3336       return Attrs.front();
3337     }
3338 
3339     const Record *getLastAttr() const {
3340       if (!Attrs.empty())
3341         return Attrs.back();
3342       return SubClasses.back()->getLastAttr();
3343     }
3344   };
3345 
3346   /// The entire hierarchy of attribute classes.
3347   class AttrClassHierarchy {
3348     std::vector<std::unique_ptr<AttrClass>> Classes;
3349 
3350   public:
3351     AttrClassHierarchy(const RecordKeeper &Records) {
3352       // Find records for all the classes.
3353       for (auto &Descriptor : AttrClassDescriptors) {
3354         const Record *ClassRecord = Records.getClass(Descriptor.TableGenName);
3355         AttrClass *Class = new AttrClass(Descriptor, ClassRecord);
3356         Classes.emplace_back(Class);
3357       }
3358 
3359       // Link up the hierarchy.
3360       for (auto &Class : Classes) {
3361         if (AttrClass *SuperClass = findSuperClass(Class->TheRecord)) {
3362           Class->SuperClass = SuperClass;
3363           SuperClass->SubClasses.push_back(Class.get());
3364         }
3365       }
3366 
3367 #ifndef NDEBUG
3368       for (auto i = Classes.begin(), e = Classes.end(); i != e; ++i) {
3369         assert((i == Classes.begin()) == ((*i)->SuperClass == nullptr) &&
3370                "only the first class should be a root class!");
3371       }
3372 #endif
3373     }
3374 
3375     void emitDefaultDefines(raw_ostream &OS) const {
3376       for (auto &Class : Classes) {
3377         Class->emitDefaultDefines(OS);
3378       }
3379     }
3380 
3381     void emitUndefs(raw_ostream &OS) const {
3382       for (auto &Class : Classes) {
3383         Class->emitUndefs(OS);
3384       }
3385     }
3386 
3387     void emitAttrLists(raw_ostream &OS) const {
3388       // Just start from the root class.
3389       Classes[0]->emitAttrList(OS);
3390     }
3391 
3392     void emitAttrRanges(raw_ostream &OS) const {
3393       for (auto &Class : Classes)
3394         Class->emitAttrRange(OS);
3395     }
3396 
3397     void classifyAttr(const Record *Attr) {
3398       // Add the attribute to the root class.
3399       Classes[0]->classifyAttrOnRoot(Attr);
3400     }
3401 
3402   private:
3403     AttrClass *findClassByRecord(const Record *R) const {
3404       for (auto &Class : Classes) {
3405         if (Class->TheRecord == R)
3406           return Class.get();
3407       }
3408       return nullptr;
3409     }
3410 
3411     AttrClass *findSuperClass(const Record *R) const {
3412       // TableGen flattens the superclass list, so we just need to walk it
3413       // in reverse.
3414       auto SuperClasses = R->getSuperClasses();
3415       for (signed i = 0, e = SuperClasses.size(); i != e; ++i) {
3416         auto SuperClass = findClassByRecord(SuperClasses[e - i - 1].first);
3417         if (SuperClass) return SuperClass;
3418       }
3419       return nullptr;
3420     }
3421   };
3422 
3423 } // end anonymous namespace
3424 
3425 namespace clang {
3426 
3427 // Emits the enumeration list for attributes.
3428 void EmitClangAttrList(const RecordKeeper &Records, raw_ostream &OS) {
3429   emitSourceFileHeader("List of all attributes that Clang recognizes", OS,
3430                        Records);
3431 
3432   AttrClassHierarchy Hierarchy(Records);
3433 
3434   // Add defaulting macro definitions.
3435   Hierarchy.emitDefaultDefines(OS);
3436   emitDefaultDefine(OS, "PRAGMA_SPELLING_ATTR", nullptr);
3437 
3438   std::vector<const Record *> PragmaAttrs;
3439   for (auto *Attr : Records.getAllDerivedDefinitions("Attr")) {
3440     if (!Attr->getValueAsBit("ASTNode"))
3441       continue;
3442 
3443     // Add the attribute to the ad-hoc groups.
3444     if (AttrHasPragmaSpelling(Attr))
3445       PragmaAttrs.push_back(Attr);
3446 
3447     // Place it in the hierarchy.
3448     Hierarchy.classifyAttr(Attr);
3449   }
3450 
3451   // Emit the main attribute list.
3452   Hierarchy.emitAttrLists(OS);
3453 
3454   // Emit the ad hoc groups.
3455   emitAttrList(OS, "PRAGMA_SPELLING_ATTR", PragmaAttrs);
3456 
3457   // Emit the attribute ranges.
3458   OS << "#ifdef ATTR_RANGE\n";
3459   Hierarchy.emitAttrRanges(OS);
3460   OS << "#undef ATTR_RANGE\n";
3461   OS << "#endif\n";
3462 
3463   Hierarchy.emitUndefs(OS);
3464   OS << "#undef PRAGMA_SPELLING_ATTR\n";
3465 }
3466 
3467 // Emits the enumeration list for attributes.
3468 void EmitClangAttrSubjectMatchRuleList(const RecordKeeper &Records,
3469                                        raw_ostream &OS) {
3470   emitSourceFileHeader(
3471       "List of all attribute subject matching rules that Clang recognizes", OS,
3472       Records);
3473   PragmaClangAttributeSupport &PragmaAttributeSupport =
3474       getPragmaAttributeSupport(Records);
3475   emitDefaultDefine(OS, "ATTR_MATCH_RULE", nullptr);
3476   PragmaAttributeSupport.emitMatchRuleList(OS);
3477   OS << "#undef ATTR_MATCH_RULE\n";
3478 }
3479 
3480 // Emits the code to read an attribute from a precompiled header.
3481 void EmitClangAttrPCHRead(const RecordKeeper &Records, raw_ostream &OS) {
3482   emitSourceFileHeader("Attribute deserialization code", OS, Records);
3483 
3484   const Record *InhClass = Records.getClass("InheritableAttr");
3485   std::vector<const Record *> ArgRecords;
3486   std::vector<std::unique_ptr<Argument>> Args;
3487   std::unique_ptr<VariadicExprArgument> DelayedArgs;
3488 
3489   OS << "  switch (Kind) {\n";
3490   for (const auto *Attr : Records.getAllDerivedDefinitions("Attr")) {
3491     const Record &R = *Attr;
3492     if (!R.getValueAsBit("ASTNode"))
3493       continue;
3494 
3495     OS << "  case attr::" << R.getName() << ": {\n";
3496     if (R.isSubClassOf(InhClass))
3497       OS << "    bool isInherited = Record.readInt();\n";
3498     OS << "    bool isImplicit = Record.readInt();\n";
3499     OS << "    bool isPackExpansion = Record.readInt();\n";
3500     DelayedArgs = nullptr;
3501     if (Attr->getValueAsBit("AcceptsExprPack")) {
3502       DelayedArgs =
3503           std::make_unique<VariadicExprArgument>("DelayedArgs", R.getName());
3504       DelayedArgs->writePCHReadDecls(OS);
3505     }
3506     ArgRecords = R.getValueAsListOfDefs("Args");
3507     Args.clear();
3508     for (const auto *Arg : ArgRecords) {
3509       Args.emplace_back(createArgument(*Arg, R.getName()));
3510       Args.back()->writePCHReadDecls(OS);
3511     }
3512     OS << "    New = new (Context) " << R.getName() << "Attr(Context, Info";
3513     for (auto const &ri : Args) {
3514       OS << ", ";
3515       ri->writePCHReadArgs(OS);
3516     }
3517     OS << ");\n";
3518     if (R.isSubClassOf(InhClass))
3519       OS << "    cast<InheritableAttr>(New)->setInherited(isInherited);\n";
3520     OS << "    New->setImplicit(isImplicit);\n";
3521     OS << "    New->setPackExpansion(isPackExpansion);\n";
3522     if (DelayedArgs) {
3523       OS << "    cast<" << R.getName()
3524          << "Attr>(New)->setDelayedArgs(Context, ";
3525       DelayedArgs->writePCHReadArgs(OS);
3526       OS << ");\n";
3527     }
3528     OS << "    break;\n";
3529     OS << "  }\n";
3530   }
3531   OS << "  }\n";
3532 }
3533 
3534 // Emits the code to write an attribute to a precompiled header.
3535 void EmitClangAttrPCHWrite(const RecordKeeper &Records, raw_ostream &OS) {
3536   emitSourceFileHeader("Attribute serialization code", OS, Records);
3537 
3538   const Record *InhClass = Records.getClass("InheritableAttr");
3539   OS << "  switch (A->getKind()) {\n";
3540   for (const auto *Attr : Records.getAllDerivedDefinitions("Attr")) {
3541     const Record &R = *Attr;
3542     if (!R.getValueAsBit("ASTNode"))
3543       continue;
3544     OS << "  case attr::" << R.getName() << ": {\n";
3545     std::vector<const Record *> Args = R.getValueAsListOfDefs("Args");
3546     if (R.isSubClassOf(InhClass) || !Args.empty())
3547       OS << "    const auto *SA = cast<" << R.getName()
3548          << "Attr>(A);\n";
3549     if (R.isSubClassOf(InhClass))
3550       OS << "    Record.push_back(SA->isInherited());\n";
3551     OS << "    Record.push_back(A->isImplicit());\n";
3552     OS << "    Record.push_back(A->isPackExpansion());\n";
3553     if (Attr->getValueAsBit("AcceptsExprPack"))
3554       VariadicExprArgument("DelayedArgs", R.getName()).writePCHWrite(OS);
3555 
3556     for (const auto *Arg : Args)
3557       createArgument(*Arg, R.getName())->writePCHWrite(OS);
3558     OS << "    break;\n";
3559     OS << "  }\n";
3560   }
3561   OS << "  }\n";
3562 }
3563 
3564 } // namespace clang
3565 
3566 // Helper function for GenerateTargetSpecificAttrChecks that alters the 'Test'
3567 // parameter with only a single check type, if applicable.
3568 static bool GenerateTargetSpecificAttrCheck(const Record *R, std::string &Test,
3569                                             std::string *FnName,
3570                                             StringRef ListName,
3571                                             StringRef CheckAgainst,
3572                                             StringRef Scope) {
3573   if (!R->isValueUnset(ListName)) {
3574     Test += " && (";
3575     std::vector<StringRef> Items = R->getValueAsListOfStrings(ListName);
3576     for (auto I = Items.begin(), E = Items.end(); I != E; ++I) {
3577       StringRef Part = *I;
3578       Test += CheckAgainst;
3579       Test += " == ";
3580       Test += Scope;
3581       Test += Part;
3582       if (I + 1 != E)
3583         Test += " || ";
3584       if (FnName)
3585         *FnName += Part;
3586     }
3587     Test += ")";
3588     return true;
3589   }
3590   return false;
3591 }
3592 
3593 // Generate a conditional expression to check if the current target satisfies
3594 // the conditions for a TargetSpecificAttr record, and append the code for
3595 // those checks to the Test string. If the FnName string pointer is non-null,
3596 // append a unique suffix to distinguish this set of target checks from other
3597 // TargetSpecificAttr records.
3598 static bool GenerateTargetSpecificAttrChecks(const Record *R,
3599                                              std::vector<StringRef> &Arches,
3600                                              std::string &Test,
3601                                              std::string *FnName) {
3602   bool AnyTargetChecks = false;
3603 
3604   // It is assumed that there will be an Triple object
3605   // named "T" and a TargetInfo object named "Target" within
3606   // scope that can be used to determine whether the attribute exists in
3607   // a given target.
3608   Test += "true";
3609   // If one or more architectures is specified, check those.  Arches are handled
3610   // differently because GenerateTargetRequirements needs to combine the list
3611   // with ParseKind.
3612   if (!Arches.empty()) {
3613     AnyTargetChecks = true;
3614     Test += " && (";
3615     for (auto I = Arches.begin(), E = Arches.end(); I != E; ++I) {
3616       StringRef Part = *I;
3617       Test += "T.getArch() == llvm::Triple::";
3618       Test += Part;
3619       if (I + 1 != E)
3620         Test += " || ";
3621       if (FnName)
3622         *FnName += Part;
3623     }
3624     Test += ")";
3625   }
3626 
3627   // If the attribute is specific to particular OSes, check those.
3628   AnyTargetChecks |= GenerateTargetSpecificAttrCheck(
3629       R, Test, FnName, "OSes", "T.getOS()", "llvm::Triple::");
3630 
3631   // If one or more object formats is specified, check those.
3632   AnyTargetChecks |=
3633       GenerateTargetSpecificAttrCheck(R, Test, FnName, "ObjectFormats",
3634                                       "T.getObjectFormat()", "llvm::Triple::");
3635 
3636   // If custom code is specified, emit it.
3637   StringRef Code = R->getValueAsString("CustomCode");
3638   if (!Code.empty()) {
3639     AnyTargetChecks = true;
3640     Test += " && (";
3641     Test += Code;
3642     Test += ")";
3643   }
3644 
3645   return AnyTargetChecks;
3646 }
3647 
3648 static void GenerateHasAttrSpellingStringSwitch(
3649     ArrayRef<std::pair<const Record *, FlattenedSpelling>> Attrs,
3650     raw_ostream &OS, StringRef Variety, StringRef Scope = "") {
3651   for (const auto &[Attr, Spelling] : Attrs) {
3652     // C++11-style attributes have specific version information associated with
3653     // them. If the attribute has no scope, the version information must not
3654     // have the default value (1), as that's incorrect. Instead, the unscoped
3655     // attribute version information should be taken from the SD-6 standing
3656     // document, which can be found at:
3657     // https://isocpp.org/std/standing-documents/sd-6-sg10-feature-test-recommendations
3658     //
3659     // C23-style attributes have the same kind of version information
3660     // associated with them. The unscoped attribute version information should
3661     // be taken from the specification of the attribute in the C Standard.
3662     //
3663     // Clang-specific attributes have the same kind of version information
3664     // associated with them. This version is typically the default value (1).
3665     // These version values are clang-specific and should typically be
3666     // incremented once the attribute changes its syntax and/or semantics in a
3667     // a way that is impactful to the end user.
3668     int Version = 1;
3669 
3670     assert(Spelling.variety() == Variety);
3671     std::string Name = "";
3672     if (Spelling.nameSpace().empty() || Scope == Spelling.nameSpace()) {
3673       Name = Spelling.name();
3674       Version = static_cast<int>(
3675           Spelling.getSpellingRecord().getValueAsInt("Version"));
3676       // Verify that explicitly specified CXX11 and C23 spellings (i.e.
3677       // not inferred from Clang/GCC spellings) have a version that's
3678       // different from the default (1).
3679       bool RequiresValidVersion =
3680           (Variety == "CXX11" || Variety == "C23") &&
3681           Spelling.getSpellingRecord().getValueAsString("Variety") == Variety;
3682       if (RequiresValidVersion && Scope.empty() && Version == 1)
3683         PrintError(Spelling.getSpellingRecord().getLoc(),
3684                    "Standard attributes must have "
3685                    "valid version information.");
3686     }
3687 
3688     std::string Test;
3689     if (Attr->isSubClassOf("TargetSpecificAttr")) {
3690       const Record *R = Attr->getValueAsDef("Target");
3691       std::vector<StringRef> Arches = R->getValueAsListOfStrings("Arches");
3692       GenerateTargetSpecificAttrChecks(R, Arches, Test, nullptr);
3693     } else if (!Attr->getValueAsListOfDefs("TargetSpecificSpellings").empty()) {
3694       // Add target checks if this spelling is target-specific.
3695       for (const auto &TargetSpelling :
3696            Attr->getValueAsListOfDefs("TargetSpecificSpellings")) {
3697         // Find spelling that matches current scope and name.
3698         for (const auto &Spelling : GetFlattenedSpellings(*TargetSpelling)) {
3699           if (Scope == Spelling.nameSpace() && Name == Spelling.name()) {
3700             const Record *Target = TargetSpelling->getValueAsDef("Target");
3701             std::vector<StringRef> Arches =
3702                 Target->getValueAsListOfStrings("Arches");
3703             GenerateTargetSpecificAttrChecks(Target, Arches, Test,
3704                                              /*FnName=*/nullptr);
3705             break;
3706           }
3707         }
3708       }
3709     }
3710 
3711     std::string TestStr = !Test.empty()
3712                               ? Test + " ? " + itostr(Version) + " : 0"
3713                               : itostr(Version);
3714     if (Scope.empty() || Scope == Spelling.nameSpace())
3715       OS << "    .Case(\"" << Spelling.name() << "\", " << TestStr << ")\n";
3716   }
3717   OS << "    .Default(0);\n";
3718 }
3719 
3720 namespace clang {
3721 
3722 // Emits list of regular keyword attributes with info about their arguments.
3723 void EmitClangRegularKeywordAttributeInfo(const RecordKeeper &Records,
3724                                           raw_ostream &OS) {
3725   emitSourceFileHeader(
3726       "A list of regular keyword attributes generated from the attribute"
3727       " definitions",
3728       OS);
3729   // Assume for now that the same token is not used in multiple regular
3730   // keyword attributes.
3731   for (auto *R : Records.getAllDerivedDefinitions("Attr"))
3732     for (const auto &S : GetFlattenedSpellings(*R)) {
3733       if (!isRegularKeywordAttribute(S))
3734         continue;
3735       std::vector<const Record *> Args = R->getValueAsListOfDefs("Args");
3736       bool HasArgs = any_of(
3737           Args, [](const Record *Arg) { return !Arg->getValueAsBit("Fake"); });
3738 
3739       OS << "KEYWORD_ATTRIBUTE("
3740          << S.getSpellingRecord().getValueAsString("Name") << ", "
3741          << (HasArgs ? "true" : "false") << ", )\n";
3742     }
3743   OS << "#undef KEYWORD_ATTRIBUTE\n";
3744 }
3745 
3746 void EmitCXX11AttributeInfo(const RecordKeeper &Records, raw_ostream &OS) {
3747   OS << "#if defined(CXX11_ATTR_ARGS_INFO)\n";
3748   for (auto *R : Records.getAllDerivedDefinitions("Attr")) {
3749     for (const FlattenedSpelling &SI : GetFlattenedSpellings(*R)) {
3750       if (SI.variety() == "CXX11" && SI.nameSpace().empty()) {
3751         unsigned RequiredArgs = 0;
3752         unsigned OptionalArgs = 0;
3753         for (const auto *Arg : R->getValueAsListOfDefs("Args")) {
3754           if (Arg->getValueAsBit("Fake"))
3755             continue;
3756 
3757           if (Arg->getValueAsBit("Optional"))
3758             OptionalArgs++;
3759           else
3760             RequiredArgs++;
3761         }
3762         OS << ".Case(\"" << SI.getSpellingRecord().getValueAsString("Name")
3763            << "\","
3764            << "AttributeCommonInfo::AttrArgsInfo::"
3765            << (RequiredArgs   ? "Required"
3766                : OptionalArgs ? "Optional"
3767                               : "None")
3768            << ")"
3769            << "\n";
3770       }
3771     }
3772   }
3773   OS << "#endif // CXX11_ATTR_ARGS_INFO\n";
3774 }
3775 
3776 // Emits the list of spellings for attributes.
3777 void EmitClangAttrHasAttrImpl(const RecordKeeper &Records, raw_ostream &OS) {
3778   emitSourceFileHeader("Code to implement the __has_attribute logic", OS,
3779                        Records);
3780 
3781   // Separate all of the attributes out into four group: generic, C++11, GNU,
3782   // and declspecs. Then generate a big switch statement for each of them.
3783   using PairTy = std::pair<const Record *, FlattenedSpelling>;
3784   std::vector<PairTy> Declspec, Microsoft, GNU, Pragma, HLSLAnnotation;
3785   std::map<StringRef, std::vector<PairTy>> CXX, C23;
3786 
3787   // Walk over the list of all attributes, and split them out based on the
3788   // spelling variety.
3789   for (auto *R : Records.getAllDerivedDefinitions("Attr")) {
3790     for (const FlattenedSpelling &SI : GetFlattenedSpellings(*R)) {
3791       StringRef Variety = SI.variety();
3792       if (Variety == "GNU")
3793         GNU.emplace_back(R, SI);
3794       else if (Variety == "Declspec")
3795         Declspec.emplace_back(R, SI);
3796       else if (Variety == "Microsoft")
3797         Microsoft.emplace_back(R, SI);
3798       else if (Variety == "CXX11")
3799         CXX[SI.nameSpace()].emplace_back(R, SI);
3800       else if (Variety == "C23")
3801         C23[SI.nameSpace()].emplace_back(R, SI);
3802       else if (Variety == "Pragma")
3803         Pragma.emplace_back(R, SI);
3804       else if (Variety == "HLSLAnnotation")
3805         HLSLAnnotation.emplace_back(R, SI);
3806     }
3807   }
3808 
3809   OS << "const llvm::Triple &T = Target.getTriple();\n";
3810   OS << "switch (Syntax) {\n";
3811   OS << "case AttributeCommonInfo::Syntax::AS_GNU:\n";
3812   OS << "  return llvm::StringSwitch<int>(Name)\n";
3813   GenerateHasAttrSpellingStringSwitch(GNU, OS, "GNU");
3814   OS << "case AttributeCommonInfo::Syntax::AS_Declspec:\n";
3815   OS << "  return llvm::StringSwitch<int>(Name)\n";
3816   GenerateHasAttrSpellingStringSwitch(Declspec, OS, "Declspec");
3817   OS << "case AttributeCommonInfo::Syntax::AS_Microsoft:\n";
3818   OS << "  return llvm::StringSwitch<int>(Name)\n";
3819   GenerateHasAttrSpellingStringSwitch(Microsoft, OS, "Microsoft");
3820   OS << "case AttributeCommonInfo::Syntax::AS_Pragma:\n";
3821   OS << "  return llvm::StringSwitch<int>(Name)\n";
3822   GenerateHasAttrSpellingStringSwitch(Pragma, OS, "Pragma");
3823   OS << "case AttributeCommonInfo::Syntax::AS_HLSLAnnotation:\n";
3824   OS << "  return llvm::StringSwitch<int>(Name)\n";
3825   GenerateHasAttrSpellingStringSwitch(HLSLAnnotation, OS, "HLSLAnnotation");
3826   auto fn = [&OS](StringRef Spelling,
3827                   const std::map<StringRef, std::vector<PairTy>> &Map) {
3828     OS << "case AttributeCommonInfo::Syntax::AS_" << Spelling << ": {\n";
3829     // C++11-style attributes are further split out based on the Scope.
3830     ListSeparator LS(" else ");
3831     for (const auto &[Scope, List] : Map) {
3832       OS << LS;
3833       OS << "if (ScopeName == \"" << Scope << "\") {\n";
3834       OS << "  return llvm::StringSwitch<int>(Name)\n";
3835       GenerateHasAttrSpellingStringSwitch(List, OS, Spelling, Scope);
3836       OS << "}";
3837     }
3838     OS << "\n} break;\n";
3839   };
3840   fn("CXX11", CXX);
3841   fn("C23", C23);
3842   OS << "case AttributeCommonInfo::Syntax::AS_Keyword:\n";
3843   OS << "case AttributeCommonInfo::Syntax::AS_ContextSensitiveKeyword:\n";
3844   OS << "  llvm_unreachable(\"hasAttribute not supported for keyword\");\n";
3845   OS << "  return 0;\n";
3846   OS << "case AttributeCommonInfo::Syntax::AS_Implicit:\n";
3847   OS << "  llvm_unreachable (\"hasAttribute not supported for "
3848         "AS_Implicit\");\n";
3849   OS << "  return 0;\n";
3850 
3851   OS << "}\n";
3852 }
3853 
3854 void EmitClangAttrSpellingListIndex(const RecordKeeper &Records,
3855                                     raw_ostream &OS) {
3856   emitSourceFileHeader("Code to translate different attribute spellings into "
3857                        "internal identifiers",
3858                        OS, Records);
3859 
3860   OS << "  switch (getParsedKind()) {\n";
3861   OS << "    case IgnoredAttribute:\n";
3862   OS << "    case UnknownAttribute:\n";
3863   OS << "    case NoSemaHandlerAttribute:\n";
3864   OS << "      llvm_unreachable(\"Ignored/unknown shouldn't get here\");\n";
3865 
3866   ParsedAttrMap Attrs = getParsedAttrList(Records);
3867   for (const auto &I : Attrs) {
3868     const Record &R = *I.second;
3869     std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(R);
3870     OS << "  case AT_" << I.first << ": {\n";
3871 
3872     // If there are none or one spelling to check, resort to the default
3873     // behavior of returning index as 0.
3874     if (Spellings.size() <= 1) {
3875       OS << "    return 0;\n"
3876          << "    break;\n"
3877          << "  }\n";
3878       continue;
3879     }
3880 
3881     std::vector<StringRef> Names;
3882     llvm::transform(Spellings, std::back_inserter(Names),
3883                     [](const FlattenedSpelling &FS) { return FS.name(); });
3884     llvm::sort(Names);
3885     Names.erase(llvm::unique(Names), Names.end());
3886 
3887     for (const auto &[Idx, FS] : enumerate(Spellings)) {
3888       OS << "    if (";
3889       if (Names.size() > 1) {
3890         SmallVector<StringRef, 6> SameLenNames;
3891         StringRef FSName = FS.name();
3892         llvm::copy_if(
3893             Names, std::back_inserter(SameLenNames),
3894             [&](StringRef N) { return N.size() == FSName.size(); });
3895 
3896         if (SameLenNames.size() == 1) {
3897           OS << "Name.size() == " << FS.name().size() << " && ";
3898         } else {
3899           // FIXME: We currently fall back to comparing entire strings if there
3900           // are 2 or more spelling names with the same length. This can be
3901           // optimized to check only for the the first differing character
3902           // between them instead.
3903           OS << "Name == \"" << FS.name() << "\""
3904              << " && ";
3905         }
3906       }
3907 
3908       OS << "getSyntax() == AttributeCommonInfo::AS_" << FS.variety()
3909          << " && ComputedScope == ";
3910       if (FS.nameSpace() == "")
3911         OS << "AttributeCommonInfo::Scope::NONE";
3912       else
3913         OS << "AttributeCommonInfo::Scope::" + FS.nameSpace().upper();
3914 
3915       OS << ")\n"
3916          << "      return " << Idx << ";\n";
3917     }
3918 
3919     OS << "    break;\n"
3920        << "  }\n";
3921   }
3922 
3923   OS << "  }\n"
3924      << "  return 0;\n";
3925 }
3926 
3927 // Emits code used by RecursiveASTVisitor to visit attributes
3928 void EmitClangAttrASTVisitor(const RecordKeeper &Records, raw_ostream &OS) {
3929   emitSourceFileHeader("Used by RecursiveASTVisitor to visit attributes.", OS,
3930                        Records);
3931   // Write method declarations for Traverse* methods.
3932   // We emit this here because we only generate methods for attributes that
3933   // are declared as ASTNodes.
3934   OS << "#ifdef ATTR_VISITOR_DECLS_ONLY\n\n";
3935   ArrayRef<const Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
3936   for (const auto *Attr : Attrs) {
3937     const Record &R = *Attr;
3938     if (!R.getValueAsBit("ASTNode"))
3939       continue;
3940     OS << "  bool Traverse"
3941        << R.getName() << "Attr(" << R.getName() << "Attr *A);\n";
3942     OS << "  bool Visit"
3943        << R.getName() << "Attr(" << R.getName() << "Attr *A) {\n"
3944        << "    return true; \n"
3945        << "  }\n";
3946   }
3947   OS << "\n#else // ATTR_VISITOR_DECLS_ONLY\n\n";
3948 
3949   // Write individual Traverse* methods for each attribute class.
3950   for (const auto *Attr : Attrs) {
3951     const Record &R = *Attr;
3952     if (!R.getValueAsBit("ASTNode"))
3953       continue;
3954 
3955     OS << "template <typename Derived>\n"
3956        << "bool VISITORCLASS<Derived>::Traverse"
3957        << R.getName() << "Attr(" << R.getName() << "Attr *A) {\n"
3958        << "  if (!getDerived().VisitAttr(A))\n"
3959        << "    return false;\n"
3960        << "  if (!getDerived().Visit" << R.getName() << "Attr(A))\n"
3961        << "    return false;\n";
3962 
3963     for (const auto *Arg : R.getValueAsListOfDefs("Args"))
3964       createArgument(*Arg, R.getName())->writeASTVisitorTraversal(OS);
3965 
3966     if (Attr->getValueAsBit("AcceptsExprPack"))
3967       VariadicExprArgument("DelayedArgs", R.getName())
3968           .writeASTVisitorTraversal(OS);
3969 
3970     OS << "  return true;\n";
3971     OS << "}\n\n";
3972   }
3973 
3974   // Write generic Traverse routine
3975   OS << "template <typename Derived>\n"
3976      << "bool VISITORCLASS<Derived>::TraverseAttr(Attr *A) {\n"
3977      << "  if (!A)\n"
3978      << "    return true;\n"
3979      << "\n"
3980      << "  switch (A->getKind()) {\n";
3981 
3982   for (const auto *Attr : Attrs) {
3983     const Record &R = *Attr;
3984     if (!R.getValueAsBit("ASTNode"))
3985       continue;
3986 
3987     OS << "    case attr::" << R.getName() << ":\n"
3988        << "      return getDerived().Traverse" << R.getName() << "Attr("
3989        << "cast<" << R.getName() << "Attr>(A));\n";
3990   }
3991   OS << "  }\n";  // end switch
3992   OS << "  llvm_unreachable(\"bad attribute kind\");\n";
3993   OS << "}\n";  // end function
3994   OS << "#endif  // ATTR_VISITOR_DECLS_ONLY\n";
3995 }
3996 
3997 static void
3998 EmitClangAttrTemplateInstantiateHelper(ArrayRef<const Record *> Attrs,
3999                                        raw_ostream &OS, bool AppliesToDecl) {
4000 
4001   OS << "  switch (At->getKind()) {\n";
4002   for (const auto *Attr : Attrs) {
4003     const Record &R = *Attr;
4004     if (!R.getValueAsBit("ASTNode"))
4005       continue;
4006     OS << "    case attr::" << R.getName() << ": {\n";
4007     bool ShouldClone = R.getValueAsBit("Clone") &&
4008                        (!AppliesToDecl ||
4009                         R.getValueAsBit("MeaningfulToClassTemplateDefinition"));
4010 
4011     if (!ShouldClone) {
4012       OS << "      return nullptr;\n";
4013       OS << "    }\n";
4014       continue;
4015     }
4016 
4017     OS << "      const auto *A = cast<"
4018        << R.getName() << "Attr>(At);\n";
4019     bool TDependent = R.getValueAsBit("TemplateDependent");
4020 
4021     if (!TDependent) {
4022       OS << "      return A->clone(C);\n";
4023       OS << "    }\n";
4024       continue;
4025     }
4026 
4027     std::vector<const Record *> ArgRecords = R.getValueAsListOfDefs("Args");
4028     std::vector<std::unique_ptr<Argument>> Args;
4029     Args.reserve(ArgRecords.size());
4030 
4031     for (const auto *ArgRecord : ArgRecords)
4032       Args.emplace_back(createArgument(*ArgRecord, R.getName()));
4033 
4034     for (auto const &ai : Args)
4035       ai->writeTemplateInstantiation(OS);
4036 
4037     OS << "      return new (C) " << R.getName() << "Attr(C, *A";
4038     for (auto const &ai : Args) {
4039       OS << ", ";
4040       ai->writeTemplateInstantiationArgs(OS);
4041     }
4042     OS << ");\n"
4043        << "    }\n";
4044   }
4045   OS << "  } // end switch\n"
4046      << "  llvm_unreachable(\"Unknown attribute!\");\n"
4047      << "  return nullptr;\n";
4048 }
4049 
4050 // Emits code to instantiate dependent attributes on templates.
4051 void EmitClangAttrTemplateInstantiate(const RecordKeeper &Records,
4052                                       raw_ostream &OS) {
4053   emitSourceFileHeader("Template instantiation code for attributes", OS,
4054                        Records);
4055 
4056   ArrayRef<const Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
4057 
4058   OS << "namespace clang {\n"
4059      << "namespace sema {\n\n"
4060      << "Attr *instantiateTemplateAttribute(const Attr *At, ASTContext &C, "
4061      << "Sema &S,\n"
4062      << "        const MultiLevelTemplateArgumentList &TemplateArgs) {\n";
4063   EmitClangAttrTemplateInstantiateHelper(Attrs, OS, /*AppliesToDecl*/false);
4064   OS << "}\n\n"
4065      << "Attr *instantiateTemplateAttributeForDecl(const Attr *At,\n"
4066      << " ASTContext &C, Sema &S,\n"
4067      << "        const MultiLevelTemplateArgumentList &TemplateArgs) {\n";
4068   EmitClangAttrTemplateInstantiateHelper(Attrs, OS, /*AppliesToDecl*/true);
4069   OS << "}\n\n"
4070      << "} // end namespace sema\n"
4071      << "} // end namespace clang\n";
4072 }
4073 
4074 // Emits the list of parsed attributes.
4075 void EmitClangAttrParsedAttrList(const RecordKeeper &Records, raw_ostream &OS) {
4076   emitSourceFileHeader("List of all attributes that Clang recognizes", OS,
4077                        Records);
4078 
4079   OS << "#ifndef PARSED_ATTR\n";
4080   OS << "#define PARSED_ATTR(NAME) NAME\n";
4081   OS << "#endif\n\n";
4082 
4083   ParsedAttrMap Names = getParsedAttrList(Records);
4084   for (const auto &I : Names) {
4085     OS << "PARSED_ATTR(" << I.first << ")\n";
4086   }
4087 }
4088 
4089 static bool isArgVariadic(const Record &R, StringRef AttrName) {
4090   return createArgument(R, AttrName)->isVariadic();
4091 }
4092 
4093 static void emitArgInfo(const Record &R, raw_ostream &OS) {
4094   // This function will count the number of arguments specified for the
4095   // attribute and emit the number of required arguments followed by the
4096   // number of optional arguments.
4097   unsigned ArgCount = 0, OptCount = 0, ArgMemberCount = 0;
4098   bool HasVariadic = false;
4099   for (const auto *Arg : R.getValueAsListOfDefs("Args")) {
4100     // If the arg is fake, it's the user's job to supply it: general parsing
4101     // logic shouldn't need to know anything about it.
4102     if (Arg->getValueAsBit("Fake"))
4103       continue;
4104     Arg->getValueAsBit("Optional") ? ++OptCount : ++ArgCount;
4105     ++ArgMemberCount;
4106     if (!HasVariadic && isArgVariadic(*Arg, R.getName()))
4107       HasVariadic = true;
4108   }
4109 
4110   // If there is a variadic argument, we will set the optional argument count
4111   // to its largest value. Since it's currently a 4-bit number, we set it to 15.
4112   OS << "    /*NumArgs=*/" << ArgCount << ",\n";
4113   OS << "    /*OptArgs=*/" << (HasVariadic ? 15 : OptCount) << ",\n";
4114   OS << "    /*NumArgMembers=*/" << ArgMemberCount << ",\n";
4115 }
4116 
4117 static std::string GetDiagnosticSpelling(const Record &R) {
4118   StringRef Ret = R.getValueAsString("DiagSpelling");
4119   if (!Ret.empty())
4120     return Ret.str();
4121 
4122   // If we couldn't find the DiagSpelling in this object, we can check to see
4123   // if the object is one that has a base, and if it is, loop up to the Base
4124   // member recursively.
4125   if (auto Base = R.getValueAsOptionalDef(BaseFieldName))
4126     return GetDiagnosticSpelling(*Base);
4127 
4128   return "";
4129 }
4130 
4131 static std::string CalculateDiagnostic(const Record &S) {
4132   // If the SubjectList object has a custom diagnostic associated with it,
4133   // return that directly.
4134   const StringRef CustomDiag = S.getValueAsString("CustomDiag");
4135   if (!CustomDiag.empty())
4136     return ("\"" + Twine(CustomDiag) + "\"").str();
4137 
4138   std::vector<std::string> DiagList;
4139   for (const auto *Subject : S.getValueAsListOfDefs("Subjects")) {
4140     const Record &R = *Subject;
4141     // Get the diagnostic text from the Decl or Stmt node given.
4142     std::string V = GetDiagnosticSpelling(R);
4143     if (V.empty()) {
4144       PrintError(R.getLoc(),
4145                  "Could not determine diagnostic spelling for the node: " +
4146                      R.getName() + "; please add one to DeclNodes.td");
4147     } else {
4148       // The node may contain a list of elements itself, so split the elements
4149       // by a comma, and trim any whitespace.
4150       SmallVector<StringRef, 2> Frags;
4151       SplitString(V, Frags, ",");
4152       for (auto Str : Frags) {
4153         DiagList.push_back(Str.trim().str());
4154       }
4155     }
4156   }
4157 
4158   if (DiagList.empty()) {
4159     PrintFatalError(S.getLoc(),
4160                     "Could not deduce diagnostic argument for Attr subjects");
4161     return "";
4162   }
4163 
4164   // FIXME: this is not particularly good for localization purposes and ideally
4165   // should be part of the diagnostics engine itself with some sort of list
4166   // specifier.
4167 
4168   // A single member of the list can be returned directly.
4169   if (DiagList.size() == 1)
4170     return '"' + DiagList.front() + '"';
4171 
4172   if (DiagList.size() == 2)
4173     return '"' + DiagList[0] + " and " + DiagList[1] + '"';
4174 
4175   // If there are more than two in the list, we serialize the first N - 1
4176   // elements with a comma. This leaves the string in the state: foo, bar,
4177   // baz (but misses quux). We can then add ", and " for the last element
4178   // manually.
4179   std::string Diag = join(DiagList.begin(), DiagList.end() - 1, ", ");
4180   return '"' + Diag + ", and " + *(DiagList.end() - 1) + '"';
4181 }
4182 
4183 static std::string GetSubjectWithSuffix(const Record *R) {
4184   const std::string B = R->getName().str();
4185   if (B == "DeclBase")
4186     return "Decl";
4187   return B + "Decl";
4188 }
4189 
4190 static std::string functionNameForCustomAppertainsTo(const Record &Subject) {
4191   return "is" + Subject.getName().str();
4192 }
4193 
4194 static void GenerateCustomAppertainsTo(const Record &Subject, raw_ostream &OS) {
4195   std::string FnName = functionNameForCustomAppertainsTo(Subject);
4196 
4197   // If this code has already been generated, we don't need to do anything.
4198   static std::set<std::string> CustomSubjectSet;
4199   auto I = CustomSubjectSet.find(FnName);
4200   if (I != CustomSubjectSet.end())
4201     return;
4202 
4203   // This only works with non-root Decls.
4204   const Record *Base = Subject.getValueAsDef(BaseFieldName);
4205 
4206   // Not currently support custom subjects within custom subjects.
4207   if (Base->isSubClassOf("SubsetSubject")) {
4208     PrintFatalError(Subject.getLoc(),
4209                     "SubsetSubjects within SubsetSubjects is not supported");
4210     return;
4211   }
4212 
4213   OS << "static bool " << FnName << "(const Decl *D) {\n";
4214   OS << "  if (const auto *S = dyn_cast<";
4215   OS << GetSubjectWithSuffix(Base);
4216   OS << ">(D))\n";
4217   OS << "    return " << Subject.getValueAsString("CheckCode") << ";\n";
4218   OS << "  return false;\n";
4219   OS << "}\n\n";
4220 
4221   CustomSubjectSet.insert(FnName);
4222 }
4223 
4224 static void GenerateAppertainsTo(const Record &Attr, raw_ostream &OS) {
4225   // If the attribute does not contain a Subjects definition, then use the
4226   // default appertainsTo logic.
4227   if (Attr.isValueUnset("Subjects"))
4228     return;
4229 
4230   const Record *SubjectObj = Attr.getValueAsDef("Subjects");
4231   std::vector<const Record *> Subjects =
4232       SubjectObj->getValueAsListOfDefs("Subjects");
4233 
4234   // If the list of subjects is empty, it is assumed that the attribute
4235   // appertains to everything.
4236   if (Subjects.empty())
4237     return;
4238 
4239   bool Warn = SubjectObj->getValueAsDef("Diag")->getValueAsBit("Warn");
4240 
4241   // Split the subjects into declaration subjects and statement subjects.
4242   // FIXME: subset subjects are added to the declaration list until there are
4243   // enough statement attributes with custom subject needs to warrant
4244   // the implementation effort.
4245   std::vector<const Record *> DeclSubjects, StmtSubjects;
4246   copy_if(Subjects, std::back_inserter(DeclSubjects), [](const Record *R) {
4247     return R->isSubClassOf("SubsetSubject") || !R->isSubClassOf("StmtNode");
4248   });
4249   copy_if(Subjects, std::back_inserter(StmtSubjects),
4250           [](const Record *R) { return R->isSubClassOf("StmtNode"); });
4251 
4252   // We should have sorted all of the subjects into two lists.
4253   // FIXME: this assertion will be wrong if we ever add type attribute subjects.
4254   assert(DeclSubjects.size() + StmtSubjects.size() == Subjects.size());
4255 
4256   if (DeclSubjects.empty()) {
4257     // If there are no decl subjects but there are stmt subjects, diagnose
4258     // trying to apply a statement attribute to a declaration.
4259     if (!StmtSubjects.empty()) {
4260       OS << "bool diagAppertainsToDecl(Sema &S, const ParsedAttr &AL, ";
4261       OS << "const Decl *D) const override {\n";
4262       OS << "  S.Diag(AL.getLoc(), diag::err_attribute_invalid_on_decl)\n";
4263       OS << "    << AL << AL.isRegularKeywordAttribute() << "
4264             "D->getLocation();\n";
4265       OS << "  return false;\n";
4266       OS << "}\n\n";
4267     }
4268   } else {
4269     // Otherwise, generate an appertainsTo check specific to this attribute
4270     // which checks all of the given subjects against the Decl passed in.
4271     OS << "bool diagAppertainsToDecl(Sema &S, ";
4272     OS << "const ParsedAttr &Attr, const Decl *D) const override {\n";
4273     OS << "  if (";
4274     for (auto I = DeclSubjects.begin(), E = DeclSubjects.end(); I != E; ++I) {
4275       // If the subject has custom code associated with it, use the generated
4276       // function for it. The function cannot be inlined into this check (yet)
4277       // because it requires the subject to be of a specific type, and were that
4278       // information inlined here, it would not support an attribute with
4279       // multiple custom subjects.
4280       if ((*I)->isSubClassOf("SubsetSubject"))
4281         OS << "!" << functionNameForCustomAppertainsTo(**I) << "(D)";
4282       else
4283         OS << "!isa<" << GetSubjectWithSuffix(*I) << ">(D)";
4284 
4285       if (I + 1 != E)
4286         OS << " && ";
4287     }
4288     OS << ") {\n";
4289     OS << "    S.Diag(Attr.getLoc(), diag::";
4290     OS << (Warn ? "warn_attribute_wrong_decl_type_str"
4291                 : "err_attribute_wrong_decl_type_str");
4292     OS << ")\n";
4293     OS << "      << Attr << Attr.isRegularKeywordAttribute() << ";
4294     OS << CalculateDiagnostic(*SubjectObj) << ";\n";
4295     OS << "    return false;\n";
4296     OS << "  }\n";
4297     OS << "  return true;\n";
4298     OS << "}\n\n";
4299   }
4300 
4301   if (StmtSubjects.empty()) {
4302     // If there are no stmt subjects but there are decl subjects, diagnose
4303     // trying to apply a declaration attribute to a statement.
4304     if (!DeclSubjects.empty()) {
4305       OS << "bool diagAppertainsToStmt(Sema &S, const ParsedAttr &AL, ";
4306       OS << "const Stmt *St) const override {\n";
4307       OS << "  S.Diag(AL.getLoc(), diag::err_decl_attribute_invalid_on_stmt)\n";
4308       OS << "    << AL << AL.isRegularKeywordAttribute() << "
4309             "St->getBeginLoc();\n";
4310       OS << "  return false;\n";
4311       OS << "}\n\n";
4312     }
4313   } else {
4314     // Now, do the same for statements.
4315     OS << "bool diagAppertainsToStmt(Sema &S, ";
4316     OS << "const ParsedAttr &Attr, const Stmt *St) const override {\n";
4317     OS << "  if (";
4318     for (auto I = StmtSubjects.begin(), E = StmtSubjects.end(); I != E; ++I) {
4319       OS << "!isa<" << (*I)->getName() << ">(St)";
4320       if (I + 1 != E)
4321         OS << " && ";
4322     }
4323     OS << ") {\n";
4324     OS << "    S.Diag(Attr.getLoc(), diag::";
4325     OS << (Warn ? "warn_attribute_wrong_decl_type_str"
4326                 : "err_attribute_wrong_decl_type_str");
4327     OS << ")\n";
4328     OS << "      << Attr << Attr.isRegularKeywordAttribute() << ";
4329     OS << CalculateDiagnostic(*SubjectObj) << ";\n";
4330     OS << "    return false;\n";
4331     OS << "  }\n";
4332     OS << "  return true;\n";
4333     OS << "}\n\n";
4334   }
4335 }
4336 
4337 // Generates the mutual exclusion checks. The checks for parsed attributes are
4338 // written into OS and the checks for merging declaration attributes are
4339 // written into MergeOS.
4340 static void GenerateMutualExclusionsChecks(const Record &Attr,
4341                                            const RecordKeeper &Records,
4342                                            raw_ostream &OS,
4343                                            raw_ostream &MergeDeclOS,
4344                                            raw_ostream &MergeStmtOS) {
4345   // We don't do any of this magic for type attributes yet.
4346   if (Attr.isSubClassOf("TypeAttr"))
4347     return;
4348 
4349   // This means the attribute is either a statement attribute, a decl
4350   // attribute, or both; find out which.
4351   bool CurAttrIsStmtAttr = Attr.isSubClassOf("StmtAttr") ||
4352                            Attr.isSubClassOf("DeclOrStmtAttr") ||
4353                            Attr.isSubClassOf("InheritableParamOrStmtAttr");
4354   bool CurAttrIsDeclAttr = !CurAttrIsStmtAttr ||
4355                            Attr.isSubClassOf("DeclOrStmtAttr") ||
4356                            Attr.isSubClassOf("InheritableParamOrStmtAttr");
4357 
4358   std::vector<std::string> DeclAttrs, StmtAttrs;
4359 
4360   // Find all of the definitions that inherit from MutualExclusions and include
4361   // the given attribute in the list of exclusions to generate the
4362   // diagMutualExclusion() check.
4363   for (const Record *Exclusion :
4364        Records.getAllDerivedDefinitions("MutualExclusions")) {
4365     std::vector<const Record *> MutuallyExclusiveAttrs =
4366         Exclusion->getValueAsListOfDefs("Exclusions");
4367     auto IsCurAttr = [Attr](const Record *R) {
4368       return R->getName() == Attr.getName();
4369     };
4370     if (any_of(MutuallyExclusiveAttrs, IsCurAttr)) {
4371       // This list of exclusions includes the attribute we're looking for, so
4372       // add the exclusive attributes to the proper list for checking.
4373       for (const Record *AttrToExclude : MutuallyExclusiveAttrs) {
4374         if (IsCurAttr(AttrToExclude))
4375           continue;
4376 
4377         if (CurAttrIsStmtAttr)
4378           StmtAttrs.push_back((AttrToExclude->getName() + "Attr").str());
4379         if (CurAttrIsDeclAttr)
4380           DeclAttrs.push_back((AttrToExclude->getName() + "Attr").str());
4381       }
4382     }
4383   }
4384 
4385   // If there are any decl or stmt attributes, silence -Woverloaded-virtual
4386   // warnings for them both.
4387   if (!DeclAttrs.empty() || !StmtAttrs.empty())
4388     OS << "  using ParsedAttrInfo::diagMutualExclusion;\n\n";
4389 
4390   // If we discovered any decl or stmt attributes to test for, generate the
4391   // predicates for them now.
4392   if (!DeclAttrs.empty()) {
4393     // Generate the ParsedAttrInfo subclass logic for declarations.
4394     OS << "  bool diagMutualExclusion(Sema &S, const ParsedAttr &AL, "
4395        << "const Decl *D) const override {\n";
4396     for (const std::string &A : DeclAttrs) {
4397       OS << "    if (const auto *A = D->getAttr<" << A << ">()) {\n";
4398       OS << "      S.Diag(AL.getLoc(), diag::err_attributes_are_not_compatible)"
4399          << " << AL << A << (AL.isRegularKeywordAttribute() ||"
4400          << " A->isRegularKeywordAttribute());\n";
4401       OS << "      S.Diag(A->getLocation(), diag::note_conflicting_attribute);";
4402       OS << "      \nreturn false;\n";
4403       OS << "    }\n";
4404     }
4405     OS << "    return true;\n";
4406     OS << "  }\n\n";
4407 
4408     // Also generate the declaration attribute merging logic if the current
4409     // attribute is one that can be inheritted on a declaration. It is assumed
4410     // this code will be executed in the context of a function with parameters:
4411     // Sema &S, Decl *D, Attr *A and that returns a bool (false on diagnostic,
4412     // true on success).
4413     if (Attr.isSubClassOf("InheritableAttr")) {
4414       MergeDeclOS << "  if (const auto *Second = dyn_cast<"
4415                   << (Attr.getName() + "Attr").str() << ">(A)) {\n";
4416       for (const std::string &A : DeclAttrs) {
4417         MergeDeclOS << "    if (const auto *First = D->getAttr<" << A
4418                     << ">()) {\n";
4419         MergeDeclOS << "      S.Diag(First->getLocation(), "
4420                     << "diag::err_attributes_are_not_compatible) << First << "
4421                     << "Second << (First->isRegularKeywordAttribute() || "
4422                     << "Second->isRegularKeywordAttribute());\n";
4423         MergeDeclOS << "      S.Diag(Second->getLocation(), "
4424                     << "diag::note_conflicting_attribute);\n";
4425         MergeDeclOS << "      return false;\n";
4426         MergeDeclOS << "    }\n";
4427       }
4428       MergeDeclOS << "    return true;\n";
4429       MergeDeclOS << "  }\n";
4430     }
4431   }
4432 
4433   // Statement attributes are a bit different from declarations. With
4434   // declarations, each attribute is added to the declaration as it is
4435   // processed, and so you can look on the Decl * itself to see if there is a
4436   // conflicting attribute. Statement attributes are processed as a group
4437   // because AttributedStmt needs to tail-allocate all of the attribute nodes
4438   // at once. This means we cannot check whether the statement already contains
4439   // an attribute to check for the conflict. Instead, we need to check whether
4440   // the given list of semantic attributes contain any conflicts. It is assumed
4441   // this code will be executed in the context of a function with parameters:
4442   // Sema &S, const SmallVectorImpl<const Attr *> &C. The code will be within a
4443   // loop which loops over the container C with a loop variable named A to
4444   // represent the current attribute to check for conflicts.
4445   //
4446   // FIXME: it would be nice not to walk over the list of potential attributes
4447   // to apply to the statement more than once, but statements typically don't
4448   // have long lists of attributes on them, so re-walking the list should not
4449   // be an expensive operation.
4450   if (!StmtAttrs.empty()) {
4451     MergeStmtOS << "    if (const auto *Second = dyn_cast<"
4452                 << (Attr.getName() + "Attr").str() << ">(A)) {\n";
4453     MergeStmtOS << "      auto Iter = llvm::find_if(C, [](const Attr *Check) "
4454                 << "{ return isa<";
4455     interleave(
4456         StmtAttrs, [&](StringRef Name) { MergeStmtOS << Name; },
4457         [&] { MergeStmtOS << ", "; });
4458     MergeStmtOS << ">(Check); });\n";
4459     MergeStmtOS << "      if (Iter != C.end()) {\n";
4460     MergeStmtOS << "        S.Diag((*Iter)->getLocation(), "
4461                 << "diag::err_attributes_are_not_compatible) << *Iter << "
4462                 << "Second << ((*Iter)->isRegularKeywordAttribute() || "
4463                 << "Second->isRegularKeywordAttribute());\n";
4464     MergeStmtOS << "        S.Diag(Second->getLocation(), "
4465                 << "diag::note_conflicting_attribute);\n";
4466     MergeStmtOS << "        return false;\n";
4467     MergeStmtOS << "      }\n";
4468     MergeStmtOS << "    }\n";
4469   }
4470 }
4471 
4472 static void
4473 emitAttributeMatchRules(PragmaClangAttributeSupport &PragmaAttributeSupport,
4474                         raw_ostream &OS) {
4475   OS << "static bool checkAttributeMatchRuleAppliesTo(const Decl *D, "
4476      << AttributeSubjectMatchRule::EnumName << " rule) {\n";
4477   OS << "  switch (rule) {\n";
4478   for (const auto &Rule : PragmaAttributeSupport.Rules) {
4479     if (Rule.isAbstractRule()) {
4480       OS << "  case " << Rule.getEnumValue() << ":\n";
4481       OS << "    assert(false && \"Abstract matcher rule isn't allowed\");\n";
4482       OS << "    return false;\n";
4483       continue;
4484     }
4485     std::vector<const Record *> Subjects = Rule.getSubjects();
4486     assert(!Subjects.empty() && "Missing subjects");
4487     OS << "  case " << Rule.getEnumValue() << ":\n";
4488     OS << "    return ";
4489     for (auto I = Subjects.begin(), E = Subjects.end(); I != E; ++I) {
4490       // If the subject has custom code associated with it, use the function
4491       // that was generated for GenerateAppertainsTo to check if the declaration
4492       // is valid.
4493       if ((*I)->isSubClassOf("SubsetSubject"))
4494         OS << functionNameForCustomAppertainsTo(**I) << "(D)";
4495       else
4496         OS << "isa<" << GetSubjectWithSuffix(*I) << ">(D)";
4497 
4498       if (I + 1 != E)
4499         OS << " || ";
4500     }
4501     OS << ";\n";
4502   }
4503   OS << "  }\n";
4504   OS << "  llvm_unreachable(\"Invalid match rule\");\nreturn false;\n";
4505   OS << "}\n\n";
4506 }
4507 
4508 static void GenerateLangOptRequirements(const Record &R,
4509                                         raw_ostream &OS) {
4510   // If the attribute has an empty or unset list of language requirements,
4511   // use the default handler.
4512   std::vector<const Record *> LangOpts = R.getValueAsListOfDefs("LangOpts");
4513   if (LangOpts.empty())
4514     return;
4515 
4516   OS << "bool acceptsLangOpts(const LangOptions &LangOpts) const override {\n";
4517   OS << "  return " << GenerateTestExpression(LangOpts) << ";\n";
4518   OS << "}\n\n";
4519 }
4520 
4521 static void GenerateTargetRequirements(const Record &Attr,
4522                                        const ParsedAttrMap &Dupes,
4523                                        raw_ostream &OS) {
4524   // If the attribute is not a target specific attribute, use the default
4525   // target handler.
4526   if (!Attr.isSubClassOf("TargetSpecificAttr"))
4527     return;
4528 
4529   // Get the list of architectures to be tested for.
4530   const Record *R = Attr.getValueAsDef("Target");
4531   std::vector<StringRef> Arches = R->getValueAsListOfStrings("Arches");
4532 
4533   // If there are other attributes which share the same parsed attribute kind,
4534   // such as target-specific attributes with a shared spelling, collapse the
4535   // duplicate architectures. This is required because a shared target-specific
4536   // attribute has only one ParsedAttr::Kind enumeration value, but it
4537   // applies to multiple target architectures. In order for the attribute to be
4538   // considered valid, all of its architectures need to be included.
4539   if (!Attr.isValueUnset("ParseKind")) {
4540     const StringRef APK = Attr.getValueAsString("ParseKind");
4541     for (const auto &I : Dupes) {
4542       if (I.first == APK) {
4543         std::vector<StringRef> DA =
4544             I.second->getValueAsDef("Target")->getValueAsListOfStrings(
4545                 "Arches");
4546         Arches.insert(Arches.end(), DA.begin(), DA.end());
4547       }
4548     }
4549   }
4550 
4551   std::string FnName = "isTarget";
4552   std::string Test;
4553   bool UsesT = GenerateTargetSpecificAttrChecks(R, Arches, Test, &FnName);
4554 
4555   OS << "bool existsInTarget(const TargetInfo &Target) const override {\n";
4556   if (UsesT)
4557     OS << "  const llvm::Triple &T = Target.getTriple(); (void)T;\n";
4558   OS << "  return " << Test << ";\n";
4559   OS << "}\n\n";
4560 }
4561 
4562 static void
4563 GenerateSpellingTargetRequirements(const Record &Attr,
4564                                    ArrayRef<const Record *> TargetSpellings,
4565                                    raw_ostream &OS) {
4566   // If there are no target specific spellings, use the default target handler.
4567   if (TargetSpellings.empty())
4568     return;
4569 
4570   std::string Test;
4571   bool UsesT = false;
4572   const std::vector<FlattenedSpelling> SpellingList =
4573       GetFlattenedSpellings(Attr);
4574   for (unsigned TargetIndex = 0; TargetIndex < TargetSpellings.size();
4575        ++TargetIndex) {
4576     const auto &TargetSpelling = TargetSpellings[TargetIndex];
4577     std::vector<FlattenedSpelling> Spellings =
4578         GetFlattenedSpellings(*TargetSpelling);
4579 
4580     Test += "((SpellingListIndex == ";
4581     for (unsigned Index = 0; Index < Spellings.size(); ++Index) {
4582       Test += itostr(getSpellingListIndex(SpellingList, Spellings[Index]));
4583       if (Index != Spellings.size() - 1)
4584         Test += " ||\n    SpellingListIndex == ";
4585       else
4586         Test += ") && ";
4587     }
4588 
4589     const Record *Target = TargetSpelling->getValueAsDef("Target");
4590     std::vector<StringRef> Arches = Target->getValueAsListOfStrings("Arches");
4591     std::string FnName = "isTargetSpelling";
4592     UsesT |= GenerateTargetSpecificAttrChecks(Target, Arches, Test, &FnName);
4593     Test += ")";
4594     if (TargetIndex != TargetSpellings.size() - 1)
4595       Test += " || ";
4596   }
4597 
4598   OS << "bool spellingExistsInTarget(const TargetInfo &Target,\n";
4599   OS << "                            const unsigned SpellingListIndex) const "
4600         "override {\n";
4601   if (UsesT)
4602     OS << "  const llvm::Triple &T = Target.getTriple(); (void)T;\n";
4603   OS << "  return " << Test << ";\n", OS << "}\n\n";
4604 }
4605 
4606 static void GenerateSpellingIndexToSemanticSpelling(const Record &Attr,
4607                                                     raw_ostream &OS) {
4608   // If the attribute does not have a semantic form, we can bail out early.
4609   if (!Attr.getValueAsBit("ASTNode"))
4610     return;
4611 
4612   std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(Attr);
4613 
4614   // If there are zero or one spellings, or all of the spellings share the same
4615   // name, we can also bail out early.
4616   if (Spellings.size() <= 1 || SpellingNamesAreCommon(Spellings))
4617     return;
4618 
4619   // Generate the enumeration we will use for the mapping.
4620   SemanticSpellingMap SemanticToSyntacticMap;
4621   std::string Enum = CreateSemanticSpellings(Spellings, SemanticToSyntacticMap);
4622   std::string Name = Attr.getName().str() + "AttrSpellingMap";
4623 
4624   OS << "unsigned spellingIndexToSemanticSpelling(";
4625   OS << "const ParsedAttr &Attr) const override {\n";
4626   OS << Enum;
4627   OS << "  unsigned Idx = Attr.getAttributeSpellingListIndex();\n";
4628   WriteSemanticSpellingSwitch("Idx", SemanticToSyntacticMap, OS);
4629   OS << "}\n\n";
4630 }
4631 
4632 static void GenerateHandleDeclAttribute(const Record &Attr, raw_ostream &OS) {
4633   // Only generate if Attr can be handled simply.
4634   if (!Attr.getValueAsBit("SimpleHandler"))
4635     return;
4636 
4637   // Generate a function which just converts from ParsedAttr to the Attr type.
4638   OS << "AttrHandling handleDeclAttribute(Sema &S, Decl *D,";
4639   OS << "const ParsedAttr &Attr) const override {\n";
4640   OS << "  D->addAttr(::new (S.Context) " << Attr.getName();
4641   OS << "Attr(S.Context, Attr));\n";
4642   OS << "  return AttributeApplied;\n";
4643   OS << "}\n\n";
4644 }
4645 
4646 static bool isParamExpr(const Record *Arg) {
4647   return !Arg->getSuperClasses().empty() &&
4648          StringSwitch<bool>(Arg->getSuperClasses().back().first->getName())
4649              .Case("ExprArgument", true)
4650              .Case("VariadicExprArgument", true)
4651              .Default(false);
4652 }
4653 
4654 static void GenerateIsParamExpr(const Record &Attr, raw_ostream &OS) {
4655   OS << "bool isParamExpr(size_t N) const override {\n";
4656   OS << "  return ";
4657   auto Args = Attr.getValueAsListOfDefs("Args");
4658   for (size_t I = 0; I < Args.size(); ++I)
4659     if (isParamExpr(Args[I]))
4660       OS << "(N == " << I << ") || ";
4661   OS << "false;\n";
4662   OS << "}\n\n";
4663 }
4664 
4665 static void GenerateHandleAttrWithDelayedArgs(const RecordKeeper &Records,
4666                                               raw_ostream &OS) {
4667   OS << "static void handleAttrWithDelayedArgs(Sema &S, Decl *D, ";
4668   OS << "const ParsedAttr &Attr) {\n";
4669   OS << "  SmallVector<Expr *, 4> ArgExprs;\n";
4670   OS << "  ArgExprs.reserve(Attr.getNumArgs());\n";
4671   OS << "  for (unsigned I = 0; I < Attr.getNumArgs(); ++I) {\n";
4672   OS << "    assert(!Attr.isArgIdent(I));\n";
4673   OS << "    ArgExprs.push_back(Attr.getArgAsExpr(I));\n";
4674   OS << "  }\n";
4675   OS << "  clang::Attr *CreatedAttr = nullptr;\n";
4676   OS << "  switch (Attr.getKind()) {\n";
4677   OS << "  default:\n";
4678   OS << "    llvm_unreachable(\"Attribute cannot hold delayed arguments.\");\n";
4679   ParsedAttrMap Attrs = getParsedAttrList(Records);
4680   for (const auto &I : Attrs) {
4681     const Record &R = *I.second;
4682     if (!R.getValueAsBit("AcceptsExprPack"))
4683       continue;
4684     OS << "  case ParsedAttr::AT_" << I.first << ": {\n";
4685     OS << "    CreatedAttr = " << R.getName() << "Attr::CreateWithDelayedArgs";
4686     OS << "(S.Context, ArgExprs.data(), ArgExprs.size(), Attr);\n";
4687     OS << "    break;\n";
4688     OS << "  }\n";
4689   }
4690   OS << "  }\n";
4691   OS << "  D->addAttr(CreatedAttr);\n";
4692   OS << "}\n\n";
4693 }
4694 
4695 static bool IsKnownToGCC(const Record &Attr) {
4696   // Look at the spellings for this subject; if there are any spellings which
4697   // claim to be known to GCC, the attribute is known to GCC.
4698   return any_of(GetFlattenedSpellings(Attr),
4699                 [](const FlattenedSpelling &S) { return S.knownToGCC(); });
4700 }
4701 
4702 /// Emits the parsed attribute helpers
4703 void EmitClangAttrParsedAttrImpl(const RecordKeeper &Records, raw_ostream &OS) {
4704   emitSourceFileHeader("Parsed attribute helpers", OS, Records);
4705 
4706   OS << "#if !defined(WANT_DECL_MERGE_LOGIC) && "
4707      << "!defined(WANT_STMT_MERGE_LOGIC)\n";
4708   PragmaClangAttributeSupport &PragmaAttributeSupport =
4709       getPragmaAttributeSupport(Records);
4710 
4711   // Get the list of parsed attributes, and accept the optional list of
4712   // duplicates due to the ParseKind.
4713   ParsedAttrMap Dupes;
4714   ParsedAttrMap Attrs = getParsedAttrList(Records, &Dupes);
4715 
4716   // Generate all of the custom appertainsTo functions that the attributes
4717   // will be using.
4718   for (const auto &I : Attrs) {
4719     const Record &Attr = *I.second;
4720     if (Attr.isValueUnset("Subjects"))
4721       continue;
4722     const Record *SubjectObj = Attr.getValueAsDef("Subjects");
4723     for (const Record *Subject : SubjectObj->getValueAsListOfDefs("Subjects"))
4724       if (Subject->isSubClassOf("SubsetSubject"))
4725         GenerateCustomAppertainsTo(*Subject, OS);
4726   }
4727 
4728   // This stream is used to collect all of the declaration attribute merging
4729   // logic for performing mutual exclusion checks. This gets emitted at the
4730   // end of the file in a helper function of its own.
4731   std::string DeclMergeChecks, StmtMergeChecks;
4732   raw_string_ostream MergeDeclOS(DeclMergeChecks), MergeStmtOS(StmtMergeChecks);
4733 
4734   // Generate a ParsedAttrInfo struct for each of the attributes.
4735   for (auto I = Attrs.begin(), E = Attrs.end(); I != E; ++I) {
4736     // TODO: If the attribute's kind appears in the list of duplicates, that is
4737     // because it is a target-specific attribute that appears multiple times.
4738     // It would be beneficial to test whether the duplicates are "similar
4739     // enough" to each other to not cause problems. For instance, check that
4740     // the spellings are identical, and custom parsing rules match, etc.
4741 
4742     // We need to generate struct instances based off ParsedAttrInfo from
4743     // ParsedAttr.cpp.
4744     const std::string &AttrName = I->first;
4745     const Record &Attr = *I->second;
4746     auto Spellings = GetFlattenedSpellings(Attr);
4747     if (!Spellings.empty()) {
4748       OS << "static constexpr ParsedAttrInfo::Spelling " << I->first
4749          << "Spellings[] = {\n";
4750       for (const auto &S : Spellings) {
4751         StringRef RawSpelling = S.name();
4752         std::string Spelling;
4753         if (!S.nameSpace().empty())
4754           Spelling += S.nameSpace().str() + "::";
4755         if (S.variety() == "GNU")
4756           Spelling += NormalizeGNUAttrSpelling(RawSpelling);
4757         else
4758           Spelling += RawSpelling;
4759         OS << "  {AttributeCommonInfo::AS_" << S.variety();
4760         OS << ", \"" << Spelling << "\"},\n";
4761       }
4762       OS << "};\n";
4763     }
4764 
4765     std::vector<std::string> ArgNames;
4766     for (const auto *Arg : Attr.getValueAsListOfDefs("Args")) {
4767       bool UnusedUnset;
4768       if (Arg->getValueAsBitOrUnset("Fake", UnusedUnset))
4769         continue;
4770       ArgNames.push_back(Arg->getValueAsString("Name").str());
4771       for (const auto &[Class, _] : Arg->getSuperClasses()) {
4772         if (Class->getName().starts_with("Variadic")) {
4773           ArgNames.back().append("...");
4774           break;
4775         }
4776       }
4777     }
4778     if (!ArgNames.empty()) {
4779       OS << "static constexpr const char *" << I->first << "ArgNames[] = {\n";
4780       for (const auto &N : ArgNames)
4781         OS << '"' << N << "\",";
4782       OS << "};\n";
4783     }
4784 
4785     OS << "struct ParsedAttrInfo" << I->first
4786        << " final : public ParsedAttrInfo {\n";
4787     OS << "  constexpr ParsedAttrInfo" << I->first << "() : ParsedAttrInfo(\n";
4788     OS << "    /*AttrKind=*/ParsedAttr::AT_" << AttrName << ",\n";
4789     emitArgInfo(Attr, OS);
4790     OS << "    /*HasCustomParsing=*/";
4791     OS << Attr.getValueAsBit("HasCustomParsing") << ",\n";
4792     OS << "    /*AcceptsExprPack=*/";
4793     OS << Attr.getValueAsBit("AcceptsExprPack") << ",\n";
4794     OS << "    /*IsTargetSpecific=*/";
4795     OS << Attr.isSubClassOf("TargetSpecificAttr") << ",\n";
4796     OS << "    /*IsType=*/";
4797     OS << (Attr.isSubClassOf("TypeAttr") || Attr.isSubClassOf("DeclOrTypeAttr"))
4798        << ",\n";
4799     OS << "    /*IsStmt=*/";
4800     OS << (Attr.isSubClassOf("StmtAttr") || Attr.isSubClassOf("DeclOrStmtAttr"))
4801        << ",\n";
4802     OS << "    /*IsKnownToGCC=*/";
4803     OS << IsKnownToGCC(Attr) << ",\n";
4804     OS << "    /*IsSupportedByPragmaAttribute=*/";
4805     OS << PragmaAttributeSupport.isAttributedSupported(*I->second) << ",\n";
4806     if (!Spellings.empty())
4807       OS << "    /*Spellings=*/" << I->first << "Spellings,\n";
4808     else
4809       OS << "    /*Spellings=*/{},\n";
4810     if (!ArgNames.empty())
4811       OS << "    /*ArgNames=*/" << I->first << "ArgNames";
4812     else
4813       OS << "    /*ArgNames=*/{}";
4814     OS << ") {}\n";
4815     GenerateAppertainsTo(Attr, OS);
4816     GenerateMutualExclusionsChecks(Attr, Records, OS, MergeDeclOS, MergeStmtOS);
4817     GenerateLangOptRequirements(Attr, OS);
4818     GenerateTargetRequirements(Attr, Dupes, OS);
4819     GenerateSpellingTargetRequirements(
4820         Attr, Attr.getValueAsListOfDefs("TargetSpecificSpellings"), OS);
4821     GenerateSpellingIndexToSemanticSpelling(Attr, OS);
4822     PragmaAttributeSupport.generateStrictConformsTo(*I->second, OS);
4823     GenerateHandleDeclAttribute(Attr, OS);
4824     GenerateIsParamExpr(Attr, OS);
4825     OS << "static const ParsedAttrInfo" << I->first << " Instance;\n";
4826     OS << "};\n";
4827     OS << "const ParsedAttrInfo" << I->first << " ParsedAttrInfo" << I->first
4828        << "::Instance;\n";
4829   }
4830 
4831   OS << "static const ParsedAttrInfo *AttrInfoMap[] = {\n";
4832   for (auto I = Attrs.begin(), E = Attrs.end(); I != E; ++I) {
4833     OS << "&ParsedAttrInfo" << I->first << "::Instance,\n";
4834   }
4835   OS << "};\n\n";
4836 
4837   // Generate function for handling attributes with delayed arguments
4838   GenerateHandleAttrWithDelayedArgs(Records, OS);
4839 
4840   // Generate the attribute match rules.
4841   emitAttributeMatchRules(PragmaAttributeSupport, OS);
4842 
4843   OS << "#elif defined(WANT_DECL_MERGE_LOGIC)\n\n";
4844 
4845   // Write out the declaration merging check logic.
4846   OS << "static bool DiagnoseMutualExclusions(Sema &S, const NamedDecl *D, "
4847      << "const Attr *A) {\n";
4848   OS << DeclMergeChecks;
4849   OS << "  return true;\n";
4850   OS << "}\n\n";
4851 
4852   OS << "#elif defined(WANT_STMT_MERGE_LOGIC)\n\n";
4853 
4854   // Write out the statement merging check logic.
4855   OS << "static bool DiagnoseMutualExclusions(Sema &S, "
4856      << "const SmallVectorImpl<const Attr *> &C) {\n";
4857   OS << "  for (const Attr *A : C) {\n";
4858   OS << StmtMergeChecks;
4859   OS << "  }\n";
4860   OS << "  return true;\n";
4861   OS << "}\n\n";
4862 
4863   OS << "#endif\n";
4864 }
4865 
4866 // Emits the kind list of parsed attributes
4867 void EmitClangAttrParsedAttrKinds(const RecordKeeper &Records,
4868                                   raw_ostream &OS) {
4869   emitSourceFileHeader("Attribute name matcher", OS, Records);
4870 
4871   std::vector<StringMatcher::StringPair> GNU, Declspec, Microsoft, CXX11,
4872       Keywords, Pragma, C23, HLSLAnnotation;
4873   std::set<StringRef> Seen;
4874   for (const auto *A : Records.getAllDerivedDefinitions("Attr")) {
4875     const Record &Attr = *A;
4876 
4877     bool SemaHandler = Attr.getValueAsBit("SemaHandler");
4878     bool Ignored = Attr.getValueAsBit("Ignored");
4879     if (SemaHandler || Ignored) {
4880       // Attribute spellings can be shared between target-specific attributes,
4881       // and can be shared between syntaxes for the same attribute. For
4882       // instance, an attribute can be spelled GNU<"interrupt"> for an ARM-
4883       // specific attribute, or MSP430-specific attribute. Additionally, an
4884       // attribute can be spelled GNU<"dllexport"> and Declspec<"dllexport">
4885       // for the same semantic attribute. Ultimately, we need to map each of
4886       // these to a single AttributeCommonInfo::Kind value, but the
4887       // StringMatcher class cannot handle duplicate match strings. So we
4888       // generate a list of string to match based on the syntax, and emit
4889       // multiple string matchers depending on the syntax used.
4890       std::string AttrName;
4891       if (Attr.isSubClassOf("TargetSpecificAttr") &&
4892           !Attr.isValueUnset("ParseKind")) {
4893         StringRef ParseKind = Attr.getValueAsString("ParseKind");
4894         if (!Seen.insert(ParseKind).second)
4895           continue;
4896         AttrName = ParseKind.str();
4897       } else {
4898         AttrName = NormalizeAttrName(Attr.getName()).str();
4899       }
4900 
4901       std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(Attr);
4902       for (const auto &S : Spellings) {
4903         StringRef RawSpelling = S.name();
4904         std::vector<StringMatcher::StringPair> *Matches = nullptr;
4905         std::string Spelling;
4906         StringRef Variety = S.variety();
4907         if (Variety == "CXX11") {
4908           Matches = &CXX11;
4909           if (!S.nameSpace().empty())
4910             Spelling += S.nameSpace().str() + "::";
4911         } else if (Variety == "C23") {
4912           Matches = &C23;
4913           if (!S.nameSpace().empty())
4914             Spelling += S.nameSpace().str() + "::";
4915         } else if (Variety == "GNU") {
4916           Matches = &GNU;
4917         } else if (Variety == "Declspec") {
4918           Matches = &Declspec;
4919         } else if (Variety == "Microsoft") {
4920           Matches = &Microsoft;
4921         } else if (Variety == "Keyword") {
4922           Matches = &Keywords;
4923         } else if (Variety == "Pragma") {
4924           Matches = &Pragma;
4925         } else if (Variety == "HLSLAnnotation") {
4926           Matches = &HLSLAnnotation;
4927         }
4928 
4929         assert(Matches && "Unsupported spelling variety found");
4930 
4931         if (Variety == "GNU")
4932           Spelling += NormalizeGNUAttrSpelling(RawSpelling);
4933         else
4934           Spelling += RawSpelling;
4935 
4936         if (SemaHandler)
4937           Matches->push_back(StringMatcher::StringPair(
4938               Spelling, "return AttributeCommonInfo::AT_" + AttrName + ";"));
4939         else
4940           Matches->push_back(StringMatcher::StringPair(
4941               Spelling, "return AttributeCommonInfo::IgnoredAttribute;"));
4942       }
4943     }
4944   }
4945 
4946   OS << "static AttributeCommonInfo::Kind getAttrKind(StringRef Name, ";
4947   OS << "AttributeCommonInfo::Syntax Syntax) {\n";
4948   OS << "  if (AttributeCommonInfo::AS_GNU == Syntax) {\n";
4949   StringMatcher("Name", GNU, OS).Emit();
4950   OS << "  } else if (AttributeCommonInfo::AS_Declspec == Syntax) {\n";
4951   StringMatcher("Name", Declspec, OS).Emit();
4952   OS << "  } else if (AttributeCommonInfo::AS_Microsoft == Syntax) {\n";
4953   StringMatcher("Name", Microsoft, OS).Emit();
4954   OS << "  } else if (AttributeCommonInfo::AS_CXX11 == Syntax) {\n";
4955   StringMatcher("Name", CXX11, OS).Emit();
4956   OS << "  } else if (AttributeCommonInfo::AS_C23 == Syntax) {\n";
4957   StringMatcher("Name", C23, OS).Emit();
4958   OS << "  } else if (AttributeCommonInfo::AS_Keyword == Syntax || ";
4959   OS << "AttributeCommonInfo::AS_ContextSensitiveKeyword == Syntax) {\n";
4960   StringMatcher("Name", Keywords, OS).Emit();
4961   OS << "  } else if (AttributeCommonInfo::AS_Pragma == Syntax) {\n";
4962   StringMatcher("Name", Pragma, OS).Emit();
4963   OS << "  } else if (AttributeCommonInfo::AS_HLSLAnnotation == Syntax) {\n";
4964   StringMatcher("Name", HLSLAnnotation, OS).Emit();
4965   OS << "  }\n";
4966   OS << "  return AttributeCommonInfo::UnknownAttribute;\n"
4967      << "}\n";
4968 }
4969 
4970 // Emits the code to dump an attribute.
4971 void EmitClangAttrTextNodeDump(const RecordKeeper &Records, raw_ostream &OS) {
4972   emitSourceFileHeader("Attribute text node dumper", OS, Records);
4973 
4974   for (const auto *Attr : Records.getAllDerivedDefinitions("Attr")) {
4975     const Record &R = *Attr;
4976     if (!R.getValueAsBit("ASTNode"))
4977       continue;
4978 
4979     // If the attribute has a semantically-meaningful name (which is determined
4980     // by whether there is a Spelling enumeration for it), then write out the
4981     // spelling used for the attribute.
4982 
4983     std::string FunctionContent;
4984     raw_string_ostream SS(FunctionContent);
4985 
4986     std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(R);
4987     if (Spellings.size() > 1 && !SpellingNamesAreCommon(Spellings))
4988       SS << "    OS << \" \" << A->getSpelling();\n";
4989 
4990     std::vector<const Record *> Args = R.getValueAsListOfDefs("Args");
4991     for (const auto *Arg : Args)
4992       createArgument(*Arg, R.getName())->writeDump(SS);
4993 
4994     if (Attr->getValueAsBit("AcceptsExprPack"))
4995       VariadicExprArgument("DelayedArgs", R.getName()).writeDump(OS);
4996 
4997     if (SS.tell()) {
4998       OS << "  void Visit" << R.getName() << "Attr(const " << R.getName()
4999          << "Attr *A) {\n";
5000       if (!Args.empty())
5001         OS << "    const auto *SA = cast<" << R.getName()
5002            << "Attr>(A); (void)SA;\n";
5003       OS << FunctionContent;
5004       OS << "  }\n";
5005     }
5006   }
5007 }
5008 
5009 void EmitClangAttrNodeTraverse(const RecordKeeper &Records, raw_ostream &OS) {
5010   emitSourceFileHeader("Attribute text node traverser", OS, Records);
5011 
5012   for (const auto *Attr : Records.getAllDerivedDefinitions("Attr")) {
5013     const Record &R = *Attr;
5014     if (!R.getValueAsBit("ASTNode"))
5015       continue;
5016 
5017     std::string FunctionContent;
5018     raw_string_ostream SS(FunctionContent);
5019 
5020     std::vector<const Record *> Args = R.getValueAsListOfDefs("Args");
5021     for (const auto *Arg : Args)
5022       createArgument(*Arg, R.getName())->writeDumpChildren(SS);
5023     if (Attr->getValueAsBit("AcceptsExprPack"))
5024       VariadicExprArgument("DelayedArgs", R.getName()).writeDumpChildren(SS);
5025     if (SS.tell()) {
5026       OS << "  void Visit" << R.getName() << "Attr(const " << R.getName()
5027          << "Attr *A) {\n";
5028       if (!Args.empty())
5029         OS << "    const auto *SA = cast<" << R.getName()
5030            << "Attr>(A); (void)SA;\n";
5031       OS << FunctionContent;
5032       OS << "  }\n";
5033     }
5034   }
5035 }
5036 
5037 void EmitClangAttrParserStringSwitches(const RecordKeeper &Records,
5038                                        raw_ostream &OS) {
5039   generateNameToAttrsMap(Records);
5040   emitSourceFileHeader("Parser-related llvm::StringSwitch cases", OS, Records);
5041   emitClangAttrArgContextList(Records, OS);
5042   emitClangAttrIdentifierArgList(Records, OS);
5043   emitClangAttrUnevaluatedStringLiteralList(Records, OS);
5044   emitClangAttrVariadicIdentifierArgList(Records, OS);
5045   emitClangAttrThisIsaIdentifierArgList(Records, OS);
5046   emitClangAttrAcceptsExprPack(Records, OS);
5047   emitClangAttrTypeArgList(Records, OS);
5048   emitClangAttrLateParsedList(Records, OS);
5049   emitClangAttrLateParsedExperimentalList(Records, OS);
5050   emitClangAttrStrictIdentifierArgList(Records, OS);
5051 }
5052 
5053 void EmitClangAttrSubjectMatchRulesParserStringSwitches(
5054     const RecordKeeper &Records, raw_ostream &OS) {
5055   getPragmaAttributeSupport(Records).generateParsingHelpers(OS);
5056 }
5057 
5058 void EmitClangAttrDocTable(const RecordKeeper &Records, raw_ostream &OS) {
5059   emitSourceFileHeader("Clang attribute documentation", OS, Records);
5060 
5061   for (const auto *A : Records.getAllDerivedDefinitions("Attr")) {
5062     if (!A->getValueAsBit("ASTNode"))
5063       continue;
5064     std::vector<const Record *> Docs = A->getValueAsListOfDefs("Documentation");
5065     assert(!Docs.empty());
5066     // Only look at the first documentation if there are several.
5067     // (Currently there's only one such attr, revisit if this becomes common).
5068     StringRef Text =
5069         Docs.front()->getValueAsOptionalString("Content").value_or("");
5070     OS << "\nstatic const char AttrDoc_" << A->getName() << "[] = "
5071        << "R\"reST(" << Text.trim() << ")reST\";\n";
5072   }
5073 }
5074 
5075 enum class SpellingKind : size_t {
5076   GNU,
5077   CXX11,
5078   C23,
5079   Declspec,
5080   Microsoft,
5081   Keyword,
5082   Pragma,
5083   HLSLAnnotation,
5084   NumSpellingKinds
5085 };
5086 static const size_t NumSpellingKinds = (size_t)SpellingKind::NumSpellingKinds;
5087 
5088 class SpellingList {
5089   std::vector<std::string> Spellings[NumSpellingKinds];
5090 
5091 public:
5092   ArrayRef<std::string> operator[](SpellingKind K) const {
5093     return Spellings[(size_t)K];
5094   }
5095 
5096   void add(const Record &Attr, FlattenedSpelling Spelling) {
5097     SpellingKind Kind =
5098         StringSwitch<SpellingKind>(Spelling.variety())
5099             .Case("GNU", SpellingKind::GNU)
5100             .Case("CXX11", SpellingKind::CXX11)
5101             .Case("C23", SpellingKind::C23)
5102             .Case("Declspec", SpellingKind::Declspec)
5103             .Case("Microsoft", SpellingKind::Microsoft)
5104             .Case("Keyword", SpellingKind::Keyword)
5105             .Case("Pragma", SpellingKind::Pragma)
5106             .Case("HLSLAnnotation", SpellingKind::HLSLAnnotation);
5107     std::string Name;
5108     StringRef NameSpace = Spelling.nameSpace();
5109     if (!NameSpace.empty()) {
5110       Name = NameSpace;
5111       switch (Kind) {
5112       case SpellingKind::CXX11:
5113       case SpellingKind::C23:
5114         Name += "::";
5115         break;
5116       case SpellingKind::Pragma:
5117         Name = " ";
5118         break;
5119       default:
5120         PrintFatalError(Attr.getLoc(), "Unexpected namespace in spelling");
5121       }
5122     }
5123     Name += Spelling.name();
5124 
5125     Spellings[(size_t)Kind].push_back(Name);
5126   }
5127 };
5128 
5129 class DocumentationData {
5130 public:
5131   const Record *Documentation;
5132   const Record *Attribute;
5133   std::string Heading;
5134   SpellingList SupportedSpellings;
5135 
5136   DocumentationData(const Record &Documentation, const Record &Attribute,
5137                     std::pair<std::string, SpellingList> HeadingAndSpellings)
5138       : Documentation(&Documentation), Attribute(&Attribute),
5139         Heading(std::move(HeadingAndSpellings.first)),
5140         SupportedSpellings(std::move(HeadingAndSpellings.second)) {}
5141 };
5142 
5143 static void WriteCategoryHeader(const Record *DocCategory,
5144                                 raw_ostream &OS) {
5145   const StringRef Name = DocCategory->getValueAsString("Name");
5146   OS << Name << "\n" << std::string(Name.size(), '=') << "\n";
5147 
5148   // If there is content, print that as well.
5149   const StringRef ContentStr = DocCategory->getValueAsString("Content");
5150   // Trim leading and trailing newlines and spaces.
5151   OS << ContentStr.trim();
5152 
5153   OS << "\n\n";
5154 }
5155 
5156 static std::pair<std::string, SpellingList>
5157 GetAttributeHeadingAndSpellings(const Record &Documentation,
5158                                 const Record &Attribute,
5159                                 StringRef Cat) {
5160   // FIXME: there is no way to have a per-spelling category for the attribute
5161   // documentation. This may not be a limiting factor since the spellings
5162   // should generally be consistently applied across the category.
5163 
5164   std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(Attribute);
5165   if (Spellings.empty())
5166     PrintFatalError(Attribute.getLoc(),
5167                     "Attribute has no supported spellings; cannot be "
5168                     "documented");
5169 
5170   // Determine the heading to be used for this attribute.
5171   std::string Heading = Documentation.getValueAsString("Heading").str();
5172   if (Heading.empty()) {
5173     // If there's only one spelling, we can simply use that.
5174     if (Spellings.size() == 1)
5175       Heading = Spellings.begin()->name();
5176     else {
5177       std::set<std::string> Uniques;
5178       for (auto I = Spellings.begin(), E = Spellings.end();
5179            I != E; ++I) {
5180         std::string Spelling =
5181             NormalizeNameForSpellingComparison(I->name()).str();
5182         Uniques.insert(Spelling);
5183       }
5184       // If the semantic map has only one spelling, that is sufficient for our
5185       // needs.
5186       if (Uniques.size() == 1)
5187         Heading = *Uniques.begin();
5188       // If it's in the undocumented category, just construct a header by
5189       // concatenating all the spellings. Might not be great, but better than
5190       // nothing.
5191       else if (Cat == "Undocumented")
5192         Heading = join(Uniques.begin(), Uniques.end(), ", ");
5193     }
5194   }
5195 
5196   // If the heading is still empty, it is an error.
5197   if (Heading.empty())
5198     PrintFatalError(Attribute.getLoc(),
5199                     "This attribute requires a heading to be specified");
5200 
5201   SpellingList SupportedSpellings;
5202   for (const auto &I : Spellings)
5203     SupportedSpellings.add(Attribute, I);
5204 
5205   return std::make_pair(std::move(Heading), std::move(SupportedSpellings));
5206 }
5207 
5208 static void WriteDocumentation(const RecordKeeper &Records,
5209                                const DocumentationData &Doc, raw_ostream &OS) {
5210   if (StringRef Label = Doc.Documentation->getValueAsString("Label");
5211       !Label.empty())
5212     OS << ".. _" << Label << ":\n\n";
5213   OS << Doc.Heading << "\n" << std::string(Doc.Heading.length(), '-') << "\n";
5214 
5215   // List what spelling syntaxes the attribute supports.
5216   // Note: "#pragma clang attribute" is handled outside the spelling kinds loop
5217   // so it must be last.
5218   OS << ".. csv-table:: Supported Syntaxes\n";
5219   OS << "   :header: \"GNU\", \"C++11\", \"C23\", \"``__declspec``\",";
5220   OS << " \"Keyword\", \"``#pragma``\", \"HLSL Annotation\", \"``#pragma "
5221         "clang ";
5222   OS << "attribute``\"\n\n   \"";
5223   for (size_t Kind = 0; Kind != NumSpellingKinds; ++Kind) {
5224     SpellingKind K = (SpellingKind)Kind;
5225     // TODO: List Microsoft (IDL-style attribute) spellings once we fully
5226     // support them.
5227     if (K == SpellingKind::Microsoft)
5228       continue;
5229 
5230     bool PrintedAny = false;
5231     for (StringRef Spelling : Doc.SupportedSpellings[K]) {
5232       if (PrintedAny)
5233         OS << " |br| ";
5234       OS << "``" << Spelling << "``";
5235       PrintedAny = true;
5236     }
5237 
5238     OS << "\",\"";
5239   }
5240 
5241   if (getPragmaAttributeSupport(Records).isAttributedSupported(
5242           *Doc.Attribute))
5243     OS << "Yes";
5244   OS << "\"\n\n";
5245 
5246   // If the attribute is deprecated, print a message about it, and possibly
5247   // provide a replacement attribute.
5248   if (!Doc.Documentation->isValueUnset("Deprecated")) {
5249     OS << "This attribute has been deprecated, and may be removed in a future "
5250        << "version of Clang.";
5251     const Record &Deprecated = *Doc.Documentation->getValueAsDef("Deprecated");
5252     const StringRef Replacement = Deprecated.getValueAsString("Replacement");
5253     if (!Replacement.empty())
5254       OS << "  This attribute has been superseded by ``" << Replacement
5255          << "``.";
5256     OS << "\n\n";
5257   }
5258 
5259   const StringRef ContentStr = Doc.Documentation->getValueAsString("Content");
5260   // Trim leading and trailing newlines and spaces.
5261   OS << ContentStr.trim();
5262 
5263   OS << "\n\n\n";
5264 }
5265 
5266 void EmitClangAttrDocs(const RecordKeeper &Records, raw_ostream &OS) {
5267   // Get the documentation introduction paragraph.
5268   const Record *Documentation = Records.getDef("GlobalDocumentation");
5269   if (!Documentation) {
5270     PrintFatalError("The Documentation top-level definition is missing, "
5271                     "no documentation will be generated.");
5272     return;
5273   }
5274 
5275   OS << Documentation->getValueAsString("Intro") << "\n";
5276 
5277   // Gather the Documentation lists from each of the attributes, based on the
5278   // category provided.
5279   struct CategoryLess {
5280     bool operator()(const Record *L, const Record *R) const {
5281       return L->getValueAsString("Name") < R->getValueAsString("Name");
5282     }
5283   };
5284   std::map<const Record *, std::vector<DocumentationData>, CategoryLess>
5285       SplitDocs;
5286   for (const auto *A : Records.getAllDerivedDefinitions("Attr")) {
5287     const Record &Attr = *A;
5288     std::vector<const Record *> Docs =
5289         Attr.getValueAsListOfDefs("Documentation");
5290     for (const auto *D : Docs) {
5291       const Record &Doc = *D;
5292       const Record *Category = Doc.getValueAsDef("Category");
5293       // If the category is "InternalOnly", then there cannot be any other
5294       // documentation categories (otherwise, the attribute would be
5295       // emitted into the docs).
5296       const StringRef Cat = Category->getValueAsString("Name");
5297       bool InternalOnly = Cat == "InternalOnly";
5298       if (InternalOnly && Docs.size() > 1)
5299         PrintFatalError(Doc.getLoc(),
5300                         "Attribute is \"InternalOnly\", but has multiple "
5301                         "documentation categories");
5302 
5303       if (!InternalOnly)
5304         SplitDocs[Category].push_back(DocumentationData(
5305             Doc, Attr, GetAttributeHeadingAndSpellings(Doc, Attr, Cat)));
5306     }
5307   }
5308 
5309   // Having split the attributes out based on what documentation goes where,
5310   // we can begin to generate sections of documentation.
5311   for (auto &I : SplitDocs) {
5312     WriteCategoryHeader(I.first, OS);
5313 
5314     sort(I.second,
5315          [](const DocumentationData &D1, const DocumentationData &D2) {
5316            return D1.Heading < D2.Heading;
5317          });
5318 
5319     // Walk over each of the attributes in the category and write out their
5320     // documentation.
5321     for (const auto &Doc : I.second)
5322       WriteDocumentation(Records, Doc, OS);
5323   }
5324 }
5325 
5326 void EmitTestPragmaAttributeSupportedAttributes(const RecordKeeper &Records,
5327                                                 raw_ostream &OS) {
5328   PragmaClangAttributeSupport Support = getPragmaAttributeSupport(Records);
5329   ParsedAttrMap Attrs = getParsedAttrList(Records);
5330   OS << "#pragma clang attribute supports the following attributes:\n";
5331   for (const auto &I : Attrs) {
5332     if (!Support.isAttributedSupported(*I.second))
5333       continue;
5334     OS << I.first;
5335     if (I.second->isValueUnset("Subjects")) {
5336       OS << " ()\n";
5337       continue;
5338     }
5339     const Record *SubjectObj = I.second->getValueAsDef("Subjects");
5340     OS << " (";
5341     bool PrintComma = false;
5342     for (const auto &Subject :
5343          enumerate(SubjectObj->getValueAsListOfDefs("Subjects"))) {
5344       if (!isSupportedPragmaClangAttributeSubject(*Subject.value()))
5345         continue;
5346       if (PrintComma)
5347         OS << ", ";
5348       PrintComma = true;
5349       PragmaClangAttributeSupport::RuleOrAggregateRuleSet &RuleSet =
5350           Support.SubjectsToRules.find(Subject.value())->getSecond();
5351       if (RuleSet.isRule()) {
5352         OS << RuleSet.getRule().getEnumValueName();
5353         continue;
5354       }
5355       OS << "(";
5356       for (const auto &Rule : enumerate(RuleSet.getAggregateRuleSet())) {
5357         if (Rule.index())
5358           OS << ", ";
5359         OS << Rule.value().getEnumValueName();
5360       }
5361       OS << ")";
5362     }
5363     OS << ")\n";
5364   }
5365   OS << "End of supported attributes.\n";
5366 }
5367 
5368 } // end namespace clang
5369