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