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