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/SmallString.h"
15 #include "llvm/ADT/STLExtras.h"
16 #include "llvm/ADT/SmallSet.h"
17 #include "llvm/ADT/StringSwitch.h"
18 #include "llvm/TableGen/Error.h"
19 #include "llvm/TableGen/Record.h"
20 #include "llvm/TableGen/StringMatcher.h"
21 #include "llvm/TableGen/TableGenBackend.h"
22 #include <algorithm>
23 #include <cctype>
24 #include <memory>
25 #include <set>
26 #include <sstream>
27 
28 using namespace llvm;
29 
30 class FlattenedSpelling {
31   std::string V, N, NS;
32   bool K;
33 
34 public:
35   FlattenedSpelling(const std::string &Variety, const std::string &Name,
36                     const std::string &Namespace, bool KnownToGCC) :
37     V(Variety), N(Name), NS(Namespace), K(KnownToGCC) {}
38   explicit FlattenedSpelling(const Record &Spelling) :
39     V(Spelling.getValueAsString("Variety")),
40     N(Spelling.getValueAsString("Name")) {
41 
42     assert(V != "GCC" && "Given a GCC spelling, which means this hasn't been"
43            "flattened!");
44     if (V == "CXX11")
45       NS = Spelling.getValueAsString("Namespace");
46     bool Unset;
47     K = Spelling.getValueAsBitOrUnset("KnownToGCC", Unset);
48   }
49 
50   const std::string &variety() const { return V; }
51   const std::string &name() const { return N; }
52   const std::string &nameSpace() const { return NS; }
53   bool knownToGCC() const { return K; }
54 };
55 
56 std::vector<FlattenedSpelling> GetFlattenedSpellings(const Record &Attr) {
57   std::vector<Record *> Spellings = Attr.getValueAsListOfDefs("Spellings");
58   std::vector<FlattenedSpelling> Ret;
59 
60   for (const auto &Spelling : Spellings) {
61     if (Spelling->getValueAsString("Variety") == "GCC") {
62       // Gin up two new spelling objects to add into the list.
63       Ret.push_back(FlattenedSpelling("GNU", Spelling->getValueAsString("Name"),
64                                       "", true));
65       Ret.push_back(FlattenedSpelling(
66           "CXX11", Spelling->getValueAsString("Name"), "gnu", true));
67     } else
68       Ret.push_back(FlattenedSpelling(*Spelling));
69   }
70 
71   return Ret;
72 }
73 
74 static std::string ReadPCHRecord(StringRef type) {
75   return StringSwitch<std::string>(type)
76     .EndsWith("Decl *", "GetLocalDeclAs<"
77               + std::string(type, 0, type.size()-1) + ">(F, Record[Idx++])")
78     .Case("TypeSourceInfo *", "GetTypeSourceInfo(F, Record, Idx)")
79     .Case("Expr *", "ReadExpr(F)")
80     .Case("IdentifierInfo *", "GetIdentifierInfo(F, Record, Idx)")
81     .Default("Record[Idx++]");
82 }
83 
84 // Assumes that the way to get the value is SA->getname()
85 static std::string WritePCHRecord(StringRef type, StringRef name) {
86   return StringSwitch<std::string>(type)
87     .EndsWith("Decl *", "AddDeclRef(" + std::string(name) +
88                         ", Record);\n")
89     .Case("TypeSourceInfo *",
90           "AddTypeSourceInfo(" + std::string(name) + ", Record);\n")
91     .Case("Expr *", "AddStmt(" + std::string(name) + ");\n")
92     .Case("IdentifierInfo *",
93           "AddIdentifierRef(" + std::string(name) + ", Record);\n")
94     .Default("Record.push_back(" + std::string(name) + ");\n");
95 }
96 
97 // Normalize attribute name by removing leading and trailing
98 // underscores. For example, __foo, foo__, __foo__ would
99 // become foo.
100 static StringRef NormalizeAttrName(StringRef AttrName) {
101   if (AttrName.startswith("__"))
102     AttrName = AttrName.substr(2, AttrName.size());
103 
104   if (AttrName.endswith("__"))
105     AttrName = AttrName.substr(0, AttrName.size() - 2);
106 
107   return AttrName;
108 }
109 
110 // Normalize the name by removing any and all leading and trailing underscores.
111 // This is different from NormalizeAttrName in that it also handles names like
112 // _pascal and __pascal.
113 static StringRef NormalizeNameForSpellingComparison(StringRef Name) {
114   while (Name.startswith("_"))
115     Name = Name.substr(1, Name.size());
116   while (Name.endswith("_"))
117     Name = Name.substr(0, Name.size() - 1);
118   return Name;
119 }
120 
121 // Normalize attribute spelling only if the spelling has both leading
122 // and trailing underscores. For example, __ms_struct__ will be
123 // normalized to "ms_struct"; __cdecl will remain intact.
124 static StringRef NormalizeAttrSpelling(StringRef AttrSpelling) {
125   if (AttrSpelling.startswith("__") && AttrSpelling.endswith("__")) {
126     AttrSpelling = AttrSpelling.substr(2, AttrSpelling.size() - 4);
127   }
128 
129   return AttrSpelling;
130 }
131 
132 typedef std::vector<std::pair<std::string, Record *>> ParsedAttrMap;
133 
134 static ParsedAttrMap getParsedAttrList(const RecordKeeper &Records,
135                                        ParsedAttrMap *Dupes = 0) {
136   std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
137   std::set<std::string> Seen;
138   ParsedAttrMap R;
139   for (auto Attr : Attrs) {
140     if (Attr->getValueAsBit("SemaHandler")) {
141       std::string AN;
142       if (Attr->isSubClassOf("TargetSpecificAttr") &&
143           !Attr->isValueUnset("ParseKind")) {
144         AN = Attr->getValueAsString("ParseKind");
145 
146         // If this attribute has already been handled, it does not need to be
147         // handled again.
148         if (Seen.find(AN) != Seen.end()) {
149           if (Dupes)
150             Dupes->push_back(std::make_pair(AN, Attr));
151           continue;
152         }
153         Seen.insert(AN);
154       } else
155         AN = NormalizeAttrName(Attr->getName()).str();
156 
157       R.push_back(std::make_pair(AN, Attr));
158     }
159   }
160   return R;
161 }
162 
163 namespace {
164   class Argument {
165     std::string lowerName, upperName;
166     StringRef attrName;
167     bool isOpt;
168 
169   public:
170     Argument(Record &Arg, StringRef Attr)
171       : lowerName(Arg.getValueAsString("Name")), upperName(lowerName),
172         attrName(Attr), isOpt(false) {
173       if (!lowerName.empty()) {
174         lowerName[0] = std::tolower(lowerName[0]);
175         upperName[0] = std::toupper(upperName[0]);
176       }
177     }
178     virtual ~Argument() {}
179 
180     StringRef getLowerName() const { return lowerName; }
181     StringRef getUpperName() const { return upperName; }
182     StringRef getAttrName() const { return attrName; }
183 
184     bool isOptional() const { return isOpt; }
185     void setOptional(bool set) { isOpt = set; }
186 
187     // These functions print the argument contents formatted in different ways.
188     virtual void writeAccessors(raw_ostream &OS) const = 0;
189     virtual void writeAccessorDefinitions(raw_ostream &OS) const {}
190     virtual void writeASTVisitorTraversal(raw_ostream &OS) const {}
191     virtual void writeCloneArgs(raw_ostream &OS) const = 0;
192     virtual void writeTemplateInstantiationArgs(raw_ostream &OS) const = 0;
193     virtual void writeTemplateInstantiation(raw_ostream &OS) const {}
194     virtual void writeCtorBody(raw_ostream &OS) const {}
195     virtual void writeCtorInitializers(raw_ostream &OS) const = 0;
196     virtual void writeCtorDefaultInitializers(raw_ostream &OS) const = 0;
197     virtual void writeCtorParameters(raw_ostream &OS) const = 0;
198     virtual void writeDeclarations(raw_ostream &OS) const = 0;
199     virtual void writePCHReadArgs(raw_ostream &OS) const = 0;
200     virtual void writePCHReadDecls(raw_ostream &OS) const = 0;
201     virtual void writePCHWrite(raw_ostream &OS) const = 0;
202     virtual void writeValue(raw_ostream &OS) const = 0;
203     virtual void writeDump(raw_ostream &OS) const = 0;
204     virtual void writeDumpChildren(raw_ostream &OS) const {}
205     virtual void writeHasChildren(raw_ostream &OS) const { OS << "false"; }
206 
207     virtual bool isEnumArg() const { return false; }
208     virtual bool isVariadicEnumArg() const { return false; }
209 
210     virtual void writeImplicitCtorArgs(raw_ostream &OS) const {
211       OS << getUpperName();
212     }
213   };
214 
215   class SimpleArgument : public Argument {
216     std::string type;
217 
218   public:
219     SimpleArgument(Record &Arg, StringRef Attr, std::string T)
220       : Argument(Arg, Attr), type(T)
221     {}
222 
223     std::string getType() const { return type; }
224 
225     void writeAccessors(raw_ostream &OS) const override {
226       OS << "  " << type << " get" << getUpperName() << "() const {\n";
227       OS << "    return " << getLowerName() << ";\n";
228       OS << "  }";
229     }
230     void writeCloneArgs(raw_ostream &OS) const override {
231       OS << getLowerName();
232     }
233     void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
234       OS << "A->get" << getUpperName() << "()";
235     }
236     void writeCtorInitializers(raw_ostream &OS) const override {
237       OS << getLowerName() << "(" << getUpperName() << ")";
238     }
239     void writeCtorDefaultInitializers(raw_ostream &OS) const override {
240       OS << getLowerName() << "()";
241     }
242     void writeCtorParameters(raw_ostream &OS) const override {
243       OS << type << " " << getUpperName();
244     }
245     void writeDeclarations(raw_ostream &OS) const override {
246       OS << type << " " << getLowerName() << ";";
247     }
248     void writePCHReadDecls(raw_ostream &OS) const override {
249       std::string read = ReadPCHRecord(type);
250       OS << "    " << type << " " << getLowerName() << " = " << read << ";\n";
251     }
252     void writePCHReadArgs(raw_ostream &OS) const override {
253       OS << getLowerName();
254     }
255     void writePCHWrite(raw_ostream &OS) const override {
256       OS << "    " << WritePCHRecord(type, "SA->get" +
257                                            std::string(getUpperName()) + "()");
258     }
259     void writeValue(raw_ostream &OS) const override {
260       if (type == "FunctionDecl *") {
261         OS << "\" << get" << getUpperName()
262            << "()->getNameInfo().getAsString() << \"";
263       } else if (type == "IdentifierInfo *") {
264         OS << "\" << get" << getUpperName() << "()->getName() << \"";
265       } else if (type == "TypeSourceInfo *") {
266         OS << "\" << get" << getUpperName() << "().getAsString() << \"";
267       } else {
268         OS << "\" << get" << getUpperName() << "() << \"";
269       }
270     }
271     void writeDump(raw_ostream &OS) const override {
272       if (type == "FunctionDecl *") {
273         OS << "    OS << \" \";\n";
274         OS << "    dumpBareDeclRef(SA->get" << getUpperName() << "());\n";
275       } else if (type == "IdentifierInfo *") {
276         OS << "    OS << \" \" << SA->get" << getUpperName()
277            << "()->getName();\n";
278       } else if (type == "TypeSourceInfo *") {
279         OS << "    OS << \" \" << SA->get" << getUpperName()
280            << "().getAsString();\n";
281       } else if (type == "bool") {
282         OS << "    if (SA->get" << getUpperName() << "()) OS << \" "
283            << getUpperName() << "\";\n";
284       } else if (type == "int" || type == "unsigned") {
285         OS << "    OS << \" \" << SA->get" << getUpperName() << "();\n";
286       } else {
287         llvm_unreachable("Unknown SimpleArgument type!");
288       }
289     }
290   };
291 
292   class DefaultSimpleArgument : public SimpleArgument {
293     int64_t Default;
294 
295   public:
296     DefaultSimpleArgument(Record &Arg, StringRef Attr,
297                           std::string T, int64_t Default)
298       : SimpleArgument(Arg, Attr, T), Default(Default) {}
299 
300     void writeAccessors(raw_ostream &OS) const override {
301       SimpleArgument::writeAccessors(OS);
302 
303       OS << "\n\n  static const " << getType() << " Default" << getUpperName()
304          << " = " << Default << ";";
305     }
306   };
307 
308   class StringArgument : public Argument {
309   public:
310     StringArgument(Record &Arg, StringRef Attr)
311       : Argument(Arg, Attr)
312     {}
313 
314     void writeAccessors(raw_ostream &OS) const override {
315       OS << "  llvm::StringRef get" << getUpperName() << "() const {\n";
316       OS << "    return llvm::StringRef(" << getLowerName() << ", "
317          << getLowerName() << "Length);\n";
318       OS << "  }\n";
319       OS << "  unsigned get" << getUpperName() << "Length() const {\n";
320       OS << "    return " << getLowerName() << "Length;\n";
321       OS << "  }\n";
322       OS << "  void set" << getUpperName()
323          << "(ASTContext &C, llvm::StringRef S) {\n";
324       OS << "    " << getLowerName() << "Length = S.size();\n";
325       OS << "    this->" << getLowerName() << " = new (C, 1) char ["
326          << getLowerName() << "Length];\n";
327       OS << "    std::memcpy(this->" << getLowerName() << ", S.data(), "
328          << getLowerName() << "Length);\n";
329       OS << "  }";
330     }
331     void writeCloneArgs(raw_ostream &OS) const override {
332       OS << "get" << getUpperName() << "()";
333     }
334     void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
335       OS << "A->get" << getUpperName() << "()";
336     }
337     void writeCtorBody(raw_ostream &OS) const override {
338       OS << "      std::memcpy(" << getLowerName() << ", " << getUpperName()
339          << ".data(), " << getLowerName() << "Length);";
340     }
341     void writeCtorInitializers(raw_ostream &OS) const override {
342       OS << getLowerName() << "Length(" << getUpperName() << ".size()),"
343          << getLowerName() << "(new (Ctx, 1) char[" << getLowerName()
344          << "Length])";
345     }
346     void writeCtorDefaultInitializers(raw_ostream &OS) const override {
347       OS << getLowerName() << "Length(0)," << getLowerName() << "(0)";
348     }
349     void writeCtorParameters(raw_ostream &OS) const override {
350       OS << "llvm::StringRef " << getUpperName();
351     }
352     void writeDeclarations(raw_ostream &OS) const override {
353       OS << "unsigned " << getLowerName() << "Length;\n";
354       OS << "char *" << getLowerName() << ";";
355     }
356     void writePCHReadDecls(raw_ostream &OS) const override {
357       OS << "    std::string " << getLowerName()
358          << "= ReadString(Record, Idx);\n";
359     }
360     void writePCHReadArgs(raw_ostream &OS) const override {
361       OS << getLowerName();
362     }
363     void writePCHWrite(raw_ostream &OS) const override {
364       OS << "    AddString(SA->get" << getUpperName() << "(), Record);\n";
365     }
366     void writeValue(raw_ostream &OS) const override {
367       OS << "\\\"\" << get" << getUpperName() << "() << \"\\\"";
368     }
369     void writeDump(raw_ostream &OS) const override {
370       OS << "    OS << \" \\\"\" << SA->get" << getUpperName()
371          << "() << \"\\\"\";\n";
372     }
373   };
374 
375   class AlignedArgument : public Argument {
376   public:
377     AlignedArgument(Record &Arg, StringRef Attr)
378       : Argument(Arg, Attr)
379     {}
380 
381     void writeAccessors(raw_ostream &OS) const override {
382       OS << "  bool is" << getUpperName() << "Dependent() const;\n";
383 
384       OS << "  unsigned get" << getUpperName() << "(ASTContext &Ctx) const;\n";
385 
386       OS << "  bool is" << getUpperName() << "Expr() const {\n";
387       OS << "    return is" << getLowerName() << "Expr;\n";
388       OS << "  }\n";
389 
390       OS << "  Expr *get" << getUpperName() << "Expr() const {\n";
391       OS << "    assert(is" << getLowerName() << "Expr);\n";
392       OS << "    return " << getLowerName() << "Expr;\n";
393       OS << "  }\n";
394 
395       OS << "  TypeSourceInfo *get" << getUpperName() << "Type() const {\n";
396       OS << "    assert(!is" << getLowerName() << "Expr);\n";
397       OS << "    return " << getLowerName() << "Type;\n";
398       OS << "  }";
399     }
400     void writeAccessorDefinitions(raw_ostream &OS) const override {
401       OS << "bool " << getAttrName() << "Attr::is" << getUpperName()
402          << "Dependent() const {\n";
403       OS << "  if (is" << getLowerName() << "Expr)\n";
404       OS << "    return " << getLowerName() << "Expr && (" << getLowerName()
405          << "Expr->isValueDependent() || " << getLowerName()
406          << "Expr->isTypeDependent());\n";
407       OS << "  else\n";
408       OS << "    return " << getLowerName()
409          << "Type->getType()->isDependentType();\n";
410       OS << "}\n";
411 
412       // FIXME: Do not do the calculation here
413       // FIXME: Handle types correctly
414       // A null pointer means maximum alignment
415       // FIXME: Load the platform-specific maximum alignment, rather than
416       //        16, the x86 max.
417       OS << "unsigned " << getAttrName() << "Attr::get" << getUpperName()
418          << "(ASTContext &Ctx) const {\n";
419       OS << "  assert(!is" << getUpperName() << "Dependent());\n";
420       OS << "  if (is" << getLowerName() << "Expr)\n";
421       OS << "    return (" << getLowerName() << "Expr ? " << getLowerName()
422          << "Expr->EvaluateKnownConstInt(Ctx).getZExtValue() : 16)"
423          << "* Ctx.getCharWidth();\n";
424       OS << "  else\n";
425       OS << "    return 0; // FIXME\n";
426       OS << "}\n";
427     }
428     void writeCloneArgs(raw_ostream &OS) const override {
429       OS << "is" << getLowerName() << "Expr, is" << getLowerName()
430          << "Expr ? static_cast<void*>(" << getLowerName()
431          << "Expr) : " << getLowerName()
432          << "Type";
433     }
434     void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
435       // FIXME: move the definition in Sema::InstantiateAttrs to here.
436       // In the meantime, aligned attributes are cloned.
437     }
438     void writeCtorBody(raw_ostream &OS) const override {
439       OS << "    if (is" << getLowerName() << "Expr)\n";
440       OS << "       " << getLowerName() << "Expr = reinterpret_cast<Expr *>("
441          << getUpperName() << ");\n";
442       OS << "    else\n";
443       OS << "       " << getLowerName()
444          << "Type = reinterpret_cast<TypeSourceInfo *>(" << getUpperName()
445          << ");";
446     }
447     void writeCtorInitializers(raw_ostream &OS) const override {
448       OS << "is" << getLowerName() << "Expr(Is" << getUpperName() << "Expr)";
449     }
450     void writeCtorDefaultInitializers(raw_ostream &OS) const override {
451       OS << "is" << getLowerName() << "Expr(false)";
452     }
453     void writeCtorParameters(raw_ostream &OS) const override {
454       OS << "bool Is" << getUpperName() << "Expr, void *" << getUpperName();
455     }
456     void writeImplicitCtorArgs(raw_ostream &OS) const override {
457       OS << "Is" << getUpperName() << "Expr, " << getUpperName();
458     }
459     void writeDeclarations(raw_ostream &OS) const override {
460       OS << "bool is" << getLowerName() << "Expr;\n";
461       OS << "union {\n";
462       OS << "Expr *" << getLowerName() << "Expr;\n";
463       OS << "TypeSourceInfo *" << getLowerName() << "Type;\n";
464       OS << "};";
465     }
466     void writePCHReadArgs(raw_ostream &OS) const override {
467       OS << "is" << getLowerName() << "Expr, " << getLowerName() << "Ptr";
468     }
469     void writePCHReadDecls(raw_ostream &OS) const override {
470       OS << "    bool is" << getLowerName() << "Expr = Record[Idx++];\n";
471       OS << "    void *" << getLowerName() << "Ptr;\n";
472       OS << "    if (is" << getLowerName() << "Expr)\n";
473       OS << "      " << getLowerName() << "Ptr = ReadExpr(F);\n";
474       OS << "    else\n";
475       OS << "      " << getLowerName()
476          << "Ptr = GetTypeSourceInfo(F, Record, Idx);\n";
477     }
478     void writePCHWrite(raw_ostream &OS) const override {
479       OS << "    Record.push_back(SA->is" << getUpperName() << "Expr());\n";
480       OS << "    if (SA->is" << getUpperName() << "Expr())\n";
481       OS << "      AddStmt(SA->get" << getUpperName() << "Expr());\n";
482       OS << "    else\n";
483       OS << "      AddTypeSourceInfo(SA->get" << getUpperName()
484          << "Type(), Record);\n";
485     }
486     void writeValue(raw_ostream &OS) const override {
487       OS << "\";\n"
488          << "  " << getLowerName() << "Expr->printPretty(OS, 0, Policy);\n"
489          << "  OS << \"";
490     }
491     void writeDump(raw_ostream &OS) const override {
492     }
493     void writeDumpChildren(raw_ostream &OS) const override {
494       OS << "    if (SA->is" << getUpperName() << "Expr()) {\n";
495       OS << "      lastChild();\n";
496       OS << "      dumpStmt(SA->get" << getUpperName() << "Expr());\n";
497       OS << "    } else\n";
498       OS << "      dumpType(SA->get" << getUpperName()
499          << "Type()->getType());\n";
500     }
501     void writeHasChildren(raw_ostream &OS) const override {
502       OS << "SA->is" << getUpperName() << "Expr()";
503     }
504   };
505 
506   class VariadicArgument : public Argument {
507     std::string type;
508 
509   public:
510     VariadicArgument(Record &Arg, StringRef Attr, std::string T)
511       : Argument(Arg, Attr), type(T)
512     {}
513 
514     std::string getType() const { return type; }
515 
516     void writeAccessors(raw_ostream &OS) const override {
517       OS << "  typedef " << type << "* " << getLowerName() << "_iterator;\n";
518       OS << "  " << getLowerName() << "_iterator " << getLowerName()
519          << "_begin() const {\n";
520       OS << "    return " << getLowerName() << ";\n";
521       OS << "  }\n";
522       OS << "  " << getLowerName() << "_iterator " << getLowerName()
523          << "_end() const {\n";
524       OS << "    return " << getLowerName() << " + " << getLowerName()
525          << "Size;\n";
526       OS << "  }\n";
527       OS << "  unsigned " << getLowerName() << "_size() const {\n"
528          << "    return " << getLowerName() << "Size;\n";
529       OS << "  }";
530     }
531     void writeCloneArgs(raw_ostream &OS) const override {
532       OS << getLowerName() << ", " << getLowerName() << "Size";
533     }
534     void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
535       // This isn't elegant, but we have to go through public methods...
536       OS << "A->" << getLowerName() << "_begin(), "
537          << "A->" << getLowerName() << "_size()";
538     }
539     void writeCtorBody(raw_ostream &OS) const override {
540       // FIXME: memcpy is not safe on non-trivial types.
541       OS << "    std::memcpy(" << getLowerName() << ", " << getUpperName()
542          << ", " << getLowerName() << "Size * sizeof(" << getType() << "));\n";
543     }
544     void writeCtorInitializers(raw_ostream &OS) const override {
545       OS << getLowerName() << "Size(" << getUpperName() << "Size), "
546          << getLowerName() << "(new (Ctx, 16) " << getType() << "["
547          << getLowerName() << "Size])";
548     }
549     void writeCtorDefaultInitializers(raw_ostream &OS) const override {
550       OS << getLowerName() << "Size(0), " << getLowerName() << "(0)";
551     }
552     void writeCtorParameters(raw_ostream &OS) const override {
553       OS << getType() << " *" << getUpperName() << ", unsigned "
554          << getUpperName() << "Size";
555     }
556     void writeImplicitCtorArgs(raw_ostream &OS) const override {
557       OS << getUpperName() << ", " << getUpperName() << "Size";
558     }
559     void writeDeclarations(raw_ostream &OS) const override {
560       OS << "  unsigned " << getLowerName() << "Size;\n";
561       OS << "  " << getType() << " *" << getLowerName() << ";";
562     }
563     void writePCHReadDecls(raw_ostream &OS) const override {
564       OS << "  unsigned " << getLowerName() << "Size = Record[Idx++];\n";
565       OS << "  SmallVector<" << type << ", 4> " << getLowerName()
566          << ";\n";
567       OS << "  " << getLowerName() << ".reserve(" << getLowerName()
568          << "Size);\n";
569       OS << "    for (unsigned i = " << getLowerName() << "Size; i; --i)\n";
570 
571       std::string read = ReadPCHRecord(type);
572       OS << "    " << getLowerName() << ".push_back(" << read << ");\n";
573     }
574     void writePCHReadArgs(raw_ostream &OS) const override {
575       OS << getLowerName() << ".data(), " << getLowerName() << "Size";
576     }
577     void writePCHWrite(raw_ostream &OS) const override {
578       OS << "    Record.push_back(SA->" << getLowerName() << "_size());\n";
579       OS << "    for (" << getAttrName() << "Attr::" << getLowerName()
580          << "_iterator i = SA->" << getLowerName() << "_begin(), e = SA->"
581          << getLowerName() << "_end(); i != e; ++i)\n";
582       OS << "      " << WritePCHRecord(type, "(*i)");
583     }
584     void writeValue(raw_ostream &OS) const override {
585       OS << "\";\n";
586       OS << "  bool isFirst = true;\n"
587          << "  for (" << getAttrName() << "Attr::" << getLowerName()
588          << "_iterator i = " << getLowerName() << "_begin(), e = "
589          << getLowerName() << "_end(); i != e; ++i) {\n"
590          << "    if (isFirst) isFirst = false;\n"
591          << "    else OS << \", \";\n"
592          << "    OS << *i;\n"
593          << "  }\n";
594       OS << "  OS << \"";
595     }
596     void writeDump(raw_ostream &OS) const override {
597       OS << "    for (" << getAttrName() << "Attr::" << getLowerName()
598          << "_iterator I = SA->" << getLowerName() << "_begin(), E = SA->"
599          << getLowerName() << "_end(); I != E; ++I)\n";
600       OS << "      OS << \" \" << *I;\n";
601     }
602   };
603 
604   // Unique the enums, but maintain the original declaration ordering.
605   std::vector<std::string>
606   uniqueEnumsInOrder(const std::vector<std::string> &enums) {
607     std::vector<std::string> uniques;
608     std::set<std::string> unique_set(enums.begin(), enums.end());
609     for (const auto &i : enums) {
610       std::set<std::string>::iterator set_i = unique_set.find(i);
611       if (set_i != unique_set.end()) {
612         uniques.push_back(i);
613         unique_set.erase(set_i);
614       }
615     }
616     return uniques;
617   }
618 
619   class EnumArgument : public Argument {
620     std::string type;
621     std::vector<std::string> values, enums, uniques;
622   public:
623     EnumArgument(Record &Arg, StringRef Attr)
624       : Argument(Arg, Attr), type(Arg.getValueAsString("Type")),
625         values(Arg.getValueAsListOfStrings("Values")),
626         enums(Arg.getValueAsListOfStrings("Enums")),
627         uniques(uniqueEnumsInOrder(enums))
628     {
629       // FIXME: Emit a proper error
630       assert(!uniques.empty());
631     }
632 
633     bool isEnumArg() const override { return true; }
634 
635     void writeAccessors(raw_ostream &OS) const override {
636       OS << "  " << type << " get" << getUpperName() << "() const {\n";
637       OS << "    return " << getLowerName() << ";\n";
638       OS << "  }";
639     }
640     void writeCloneArgs(raw_ostream &OS) const override {
641       OS << getLowerName();
642     }
643     void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
644       OS << "A->get" << getUpperName() << "()";
645     }
646     void writeCtorInitializers(raw_ostream &OS) const override {
647       OS << getLowerName() << "(" << getUpperName() << ")";
648     }
649     void writeCtorDefaultInitializers(raw_ostream &OS) const override {
650       OS << getLowerName() << "(" << type << "(0))";
651     }
652     void writeCtorParameters(raw_ostream &OS) const override {
653       OS << type << " " << getUpperName();
654     }
655     void writeDeclarations(raw_ostream &OS) const override {
656       std::vector<std::string>::const_iterator i = uniques.begin(),
657                                                e = uniques.end();
658       // The last one needs to not have a comma.
659       --e;
660 
661       OS << "public:\n";
662       OS << "  enum " << type << " {\n";
663       for (; i != e; ++i)
664         OS << "    " << *i << ",\n";
665       OS << "    " << *e << "\n";
666       OS << "  };\n";
667       OS << "private:\n";
668       OS << "  " << type << " " << getLowerName() << ";";
669     }
670     void writePCHReadDecls(raw_ostream &OS) const override {
671       OS << "    " << getAttrName() << "Attr::" << type << " " << getLowerName()
672          << "(static_cast<" << getAttrName() << "Attr::" << type
673          << ">(Record[Idx++]));\n";
674     }
675     void writePCHReadArgs(raw_ostream &OS) const override {
676       OS << getLowerName();
677     }
678     void writePCHWrite(raw_ostream &OS) const override {
679       OS << "Record.push_back(SA->get" << getUpperName() << "());\n";
680     }
681     void writeValue(raw_ostream &OS) const override {
682       OS << "\" << get" << getUpperName() << "() << \"";
683     }
684     void writeDump(raw_ostream &OS) const override {
685       OS << "    switch(SA->get" << getUpperName() << "()) {\n";
686       for (const auto &I : uniques) {
687         OS << "    case " << getAttrName() << "Attr::" << I << ":\n";
688         OS << "      OS << \" " << I << "\";\n";
689         OS << "      break;\n";
690       }
691       OS << "    }\n";
692     }
693 
694     void writeConversion(raw_ostream &OS) const {
695       OS << "  static bool ConvertStrTo" << type << "(StringRef Val, ";
696       OS << type << " &Out) {\n";
697       OS << "    Optional<" << type << "> R = llvm::StringSwitch<Optional<";
698       OS << type << ">>(Val)\n";
699       for (size_t I = 0; I < enums.size(); ++I) {
700         OS << "      .Case(\"" << values[I] << "\", ";
701         OS << getAttrName() << "Attr::" << enums[I] << ")\n";
702       }
703       OS << "      .Default(Optional<" << type << ">());\n";
704       OS << "    if (R) {\n";
705       OS << "      Out = *R;\n      return true;\n    }\n";
706       OS << "    return false;\n";
707       OS << "  }\n";
708     }
709   };
710 
711   class VariadicEnumArgument: public VariadicArgument {
712     std::string type, QualifiedTypeName;
713     std::vector<std::string> values, enums, uniques;
714   public:
715     VariadicEnumArgument(Record &Arg, StringRef Attr)
716       : VariadicArgument(Arg, Attr, Arg.getValueAsString("Type")),
717         type(Arg.getValueAsString("Type")),
718         values(Arg.getValueAsListOfStrings("Values")),
719         enums(Arg.getValueAsListOfStrings("Enums")),
720         uniques(uniqueEnumsInOrder(enums))
721     {
722       QualifiedTypeName = getAttrName().str() + "Attr::" + type;
723 
724       // FIXME: Emit a proper error
725       assert(!uniques.empty());
726     }
727 
728     bool isVariadicEnumArg() const override { return true; }
729 
730     void writeDeclarations(raw_ostream &OS) const override {
731       std::vector<std::string>::const_iterator i = uniques.begin(),
732                                                e = uniques.end();
733       // The last one needs to not have a comma.
734       --e;
735 
736       OS << "public:\n";
737       OS << "  enum " << type << " {\n";
738       for (; i != e; ++i)
739         OS << "    " << *i << ",\n";
740       OS << "    " << *e << "\n";
741       OS << "  };\n";
742       OS << "private:\n";
743 
744       VariadicArgument::writeDeclarations(OS);
745     }
746     void writeDump(raw_ostream &OS) const override {
747       OS << "    for (" << getAttrName() << "Attr::" << getLowerName()
748          << "_iterator I = SA->" << getLowerName() << "_begin(), E = SA->"
749          << getLowerName() << "_end(); I != E; ++I) {\n";
750       OS << "      switch(*I) {\n";
751       for (const auto &UI : uniques) {
752         OS << "    case " << getAttrName() << "Attr::" << UI << ":\n";
753         OS << "      OS << \" " << UI << "\";\n";
754         OS << "      break;\n";
755       }
756       OS << "      }\n";
757       OS << "    }\n";
758     }
759     void writePCHReadDecls(raw_ostream &OS) const override {
760       OS << "    unsigned " << getLowerName() << "Size = Record[Idx++];\n";
761       OS << "    SmallVector<" << QualifiedTypeName << ", 4> " << getLowerName()
762          << ";\n";
763       OS << "    " << getLowerName() << ".reserve(" << getLowerName()
764          << "Size);\n";
765       OS << "    for (unsigned i = " << getLowerName() << "Size; i; --i)\n";
766       OS << "      " << getLowerName() << ".push_back(" << "static_cast<"
767          << QualifiedTypeName << ">(Record[Idx++]));\n";
768     }
769     void writePCHWrite(raw_ostream &OS) const override {
770       OS << "    Record.push_back(SA->" << getLowerName() << "_size());\n";
771       OS << "    for (" << getAttrName() << "Attr::" << getLowerName()
772          << "_iterator i = SA->" << getLowerName() << "_begin(), e = SA->"
773          << getLowerName() << "_end(); i != e; ++i)\n";
774       OS << "      " << WritePCHRecord(QualifiedTypeName, "(*i)");
775     }
776     void writeConversion(raw_ostream &OS) const {
777       OS << "  static bool ConvertStrTo" << type << "(StringRef Val, ";
778       OS << type << " &Out) {\n";
779       OS << "    Optional<" << type << "> R = llvm::StringSwitch<Optional<";
780       OS << type << ">>(Val)\n";
781       for (size_t I = 0; I < enums.size(); ++I) {
782         OS << "      .Case(\"" << values[I] << "\", ";
783         OS << getAttrName() << "Attr::" << enums[I] << ")\n";
784       }
785       OS << "      .Default(Optional<" << type << ">());\n";
786       OS << "    if (R) {\n";
787       OS << "      Out = *R;\n      return true;\n    }\n";
788       OS << "    return false;\n";
789       OS << "  }\n";
790     }
791   };
792 
793   class VersionArgument : public Argument {
794   public:
795     VersionArgument(Record &Arg, StringRef Attr)
796       : Argument(Arg, Attr)
797     {}
798 
799     void writeAccessors(raw_ostream &OS) const override {
800       OS << "  VersionTuple get" << getUpperName() << "() const {\n";
801       OS << "    return " << getLowerName() << ";\n";
802       OS << "  }\n";
803       OS << "  void set" << getUpperName()
804          << "(ASTContext &C, VersionTuple V) {\n";
805       OS << "    " << getLowerName() << " = V;\n";
806       OS << "  }";
807     }
808     void writeCloneArgs(raw_ostream &OS) const override {
809       OS << "get" << getUpperName() << "()";
810     }
811     void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
812       OS << "A->get" << getUpperName() << "()";
813     }
814     void writeCtorInitializers(raw_ostream &OS) const override {
815       OS << getLowerName() << "(" << getUpperName() << ")";
816     }
817     void writeCtorDefaultInitializers(raw_ostream &OS) const override {
818       OS << getLowerName() << "()";
819     }
820     void writeCtorParameters(raw_ostream &OS) const override {
821       OS << "VersionTuple " << getUpperName();
822     }
823     void writeDeclarations(raw_ostream &OS) const override {
824       OS << "VersionTuple " << getLowerName() << ";\n";
825     }
826     void writePCHReadDecls(raw_ostream &OS) const override {
827       OS << "    VersionTuple " << getLowerName()
828          << "= ReadVersionTuple(Record, Idx);\n";
829     }
830     void writePCHReadArgs(raw_ostream &OS) const override {
831       OS << getLowerName();
832     }
833     void writePCHWrite(raw_ostream &OS) const override {
834       OS << "    AddVersionTuple(SA->get" << getUpperName() << "(), Record);\n";
835     }
836     void writeValue(raw_ostream &OS) const override {
837       OS << getLowerName() << "=\" << get" << getUpperName() << "() << \"";
838     }
839     void writeDump(raw_ostream &OS) const override {
840       OS << "    OS << \" \" << SA->get" << getUpperName() << "();\n";
841     }
842   };
843 
844   class ExprArgument : public SimpleArgument {
845   public:
846     ExprArgument(Record &Arg, StringRef Attr)
847       : SimpleArgument(Arg, Attr, "Expr *")
848     {}
849 
850     void writeASTVisitorTraversal(raw_ostream &OS) const override {
851       OS << "  if (!"
852          << "getDerived().TraverseStmt(A->get" << getUpperName() << "()))\n";
853       OS << "    return false;\n";
854     }
855 
856     void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
857       OS << "tempInst" << getUpperName();
858     }
859 
860     void writeTemplateInstantiation(raw_ostream &OS) const override {
861       OS << "      " << getType() << " tempInst" << getUpperName() << ";\n";
862       OS << "      {\n";
863       OS << "        EnterExpressionEvaluationContext "
864          << "Unevaluated(S, Sema::Unevaluated);\n";
865       OS << "        ExprResult " << "Result = S.SubstExpr("
866          << "A->get" << getUpperName() << "(), TemplateArgs);\n";
867       OS << "        tempInst" << getUpperName() << " = "
868          << "Result.takeAs<Expr>();\n";
869       OS << "      }\n";
870     }
871 
872     void writeDump(raw_ostream &OS) const override {}
873 
874     void writeDumpChildren(raw_ostream &OS) const override {
875       OS << "    lastChild();\n";
876       OS << "    dumpStmt(SA->get" << getUpperName() << "());\n";
877     }
878     void writeHasChildren(raw_ostream &OS) const override { OS << "true"; }
879   };
880 
881   class VariadicExprArgument : public VariadicArgument {
882   public:
883     VariadicExprArgument(Record &Arg, StringRef Attr)
884       : VariadicArgument(Arg, Attr, "Expr *")
885     {}
886 
887     void writeASTVisitorTraversal(raw_ostream &OS) const override {
888       OS << "  {\n";
889       OS << "    " << getType() << " *I = A->" << getLowerName()
890          << "_begin();\n";
891       OS << "    " << getType() << " *E = A->" << getLowerName()
892          << "_end();\n";
893       OS << "    for (; I != E; ++I) {\n";
894       OS << "      if (!getDerived().TraverseStmt(*I))\n";
895       OS << "        return false;\n";
896       OS << "    }\n";
897       OS << "  }\n";
898     }
899 
900     void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
901       OS << "tempInst" << getUpperName() << ", "
902          << "A->" << getLowerName() << "_size()";
903     }
904 
905     void writeTemplateInstantiation(raw_ostream &OS) const override {
906       OS << "      " << getType() << " *tempInst" << getUpperName()
907          << " = new (C, 16) " << getType()
908          << "[A->" << getLowerName() << "_size()];\n";
909       OS << "      {\n";
910       OS << "        EnterExpressionEvaluationContext "
911          << "Unevaluated(S, Sema::Unevaluated);\n";
912       OS << "        " << getType() << " *TI = tempInst" << getUpperName()
913          << ";\n";
914       OS << "        " << getType() << " *I = A->" << getLowerName()
915          << "_begin();\n";
916       OS << "        " << getType() << " *E = A->" << getLowerName()
917          << "_end();\n";
918       OS << "        for (; I != E; ++I, ++TI) {\n";
919       OS << "          ExprResult Result = S.SubstExpr(*I, TemplateArgs);\n";
920       OS << "          *TI = Result.takeAs<Expr>();\n";
921       OS << "        }\n";
922       OS << "      }\n";
923     }
924 
925     void writeDump(raw_ostream &OS) const override {}
926 
927     void writeDumpChildren(raw_ostream &OS) const override {
928       OS << "    for (" << getAttrName() << "Attr::" << getLowerName()
929          << "_iterator I = SA->" << getLowerName() << "_begin(), E = SA->"
930          << getLowerName() << "_end(); I != E; ++I) {\n";
931       OS << "      if (I + 1 == E)\n";
932       OS << "        lastChild();\n";
933       OS << "      dumpStmt(*I);\n";
934       OS << "    }\n";
935     }
936 
937     void writeHasChildren(raw_ostream &OS) const override {
938       OS << "SA->" << getLowerName() << "_begin() != "
939          << "SA->" << getLowerName() << "_end()";
940     }
941   };
942 
943   class TypeArgument : public SimpleArgument {
944   public:
945     TypeArgument(Record &Arg, StringRef Attr)
946       : SimpleArgument(Arg, Attr, "TypeSourceInfo *")
947     {}
948 
949     void writeAccessors(raw_ostream &OS) const override {
950       OS << "  QualType get" << getUpperName() << "() const {\n";
951       OS << "    return " << getLowerName() << "->getType();\n";
952       OS << "  }";
953       OS << "  " << getType() << " get" << getUpperName() << "Loc() const {\n";
954       OS << "    return " << getLowerName() << ";\n";
955       OS << "  }";
956     }
957     void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
958       OS << "A->get" << getUpperName() << "Loc()";
959     }
960     void writePCHWrite(raw_ostream &OS) const override {
961       OS << "    " << WritePCHRecord(
962           getType(), "SA->get" + std::string(getUpperName()) + "Loc()");
963     }
964   };
965 }
966 
967 static std::unique_ptr<Argument> createArgument(Record &Arg, StringRef Attr,
968                                                 Record *Search = 0) {
969   if (!Search)
970     Search = &Arg;
971 
972   Argument *Ptr = 0;
973   llvm::StringRef ArgName = Search->getName();
974 
975   if (ArgName == "AlignedArgument") Ptr = new AlignedArgument(Arg, Attr);
976   else if (ArgName == "EnumArgument") Ptr = new EnumArgument(Arg, Attr);
977   else if (ArgName == "ExprArgument") Ptr = new ExprArgument(Arg, Attr);
978   else if (ArgName == "FunctionArgument")
979     Ptr = new SimpleArgument(Arg, Attr, "FunctionDecl *");
980   else if (ArgName == "IdentifierArgument")
981     Ptr = new SimpleArgument(Arg, Attr, "IdentifierInfo *");
982   else if (ArgName == "DefaultBoolArgument")
983     Ptr = new DefaultSimpleArgument(Arg, Attr, "bool",
984                                     Arg.getValueAsBit("Default"));
985   else if (ArgName == "BoolArgument") Ptr = new SimpleArgument(Arg, Attr,
986                                                                "bool");
987   else if (ArgName == "DefaultIntArgument")
988     Ptr = new DefaultSimpleArgument(Arg, Attr, "int",
989                                     Arg.getValueAsInt("Default"));
990   else if (ArgName == "IntArgument") Ptr = new SimpleArgument(Arg, Attr, "int");
991   else if (ArgName == "StringArgument") Ptr = new StringArgument(Arg, Attr);
992   else if (ArgName == "TypeArgument") Ptr = new TypeArgument(Arg, Attr);
993   else if (ArgName == "UnsignedArgument")
994     Ptr = new SimpleArgument(Arg, Attr, "unsigned");
995   else if (ArgName == "VariadicUnsignedArgument")
996     Ptr = new VariadicArgument(Arg, Attr, "unsigned");
997   else if (ArgName == "VariadicEnumArgument")
998     Ptr = new VariadicEnumArgument(Arg, Attr);
999   else if (ArgName == "VariadicExprArgument")
1000     Ptr = new VariadicExprArgument(Arg, Attr);
1001   else if (ArgName == "VersionArgument")
1002     Ptr = new VersionArgument(Arg, Attr);
1003 
1004   if (!Ptr) {
1005     // Search in reverse order so that the most-derived type is handled first.
1006     std::vector<Record*> Bases = Search->getSuperClasses();
1007     for (auto i = Bases.rbegin(), e = Bases.rend(); i != e; ++i) {
1008       Ptr = createArgument(Arg, Attr, *i).release();
1009       if (Ptr)
1010         break;
1011     }
1012   }
1013 
1014   if (Ptr && Arg.getValueAsBit("Optional"))
1015     Ptr->setOptional(true);
1016 
1017   return std::unique_ptr<Argument>(Ptr);
1018 }
1019 
1020 static void writeAvailabilityValue(raw_ostream &OS) {
1021   OS << "\" << getPlatform()->getName();\n"
1022      << "  if (!getIntroduced().empty()) OS << \", introduced=\" << getIntroduced();\n"
1023      << "  if (!getDeprecated().empty()) OS << \", deprecated=\" << getDeprecated();\n"
1024      << "  if (!getObsoleted().empty()) OS << \", obsoleted=\" << getObsoleted();\n"
1025      << "  if (getUnavailable()) OS << \", unavailable\";\n"
1026      << "  OS << \"";
1027 }
1028 
1029 static void writeGetSpellingFunction(Record &R, raw_ostream &OS) {
1030   std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(R);
1031 
1032   OS << "const char *" << R.getName() << "Attr::getSpelling() const {\n";
1033   if (Spellings.empty()) {
1034     OS << "  return \"(No spelling)\";\n}\n\n";
1035     return;
1036   }
1037 
1038   OS << "  switch (SpellingListIndex) {\n"
1039         "  default:\n"
1040         "    llvm_unreachable(\"Unknown attribute spelling!\");\n"
1041         "    return \"(No spelling)\";\n";
1042 
1043   for (unsigned I = 0; I < Spellings.size(); ++I)
1044     OS << "  case " << I << ":\n"
1045           "    return \"" << Spellings[I].name() << "\";\n";
1046   // End of the switch statement.
1047   OS << "  }\n";
1048   // End of the getSpelling function.
1049   OS << "}\n\n";
1050 }
1051 
1052 static void
1053 writePrettyPrintFunction(Record &R,
1054                          const std::vector<std::unique_ptr<Argument>> &Args,
1055                          raw_ostream &OS) {
1056   std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(R);
1057 
1058   OS << "void " << R.getName() << "Attr::printPretty("
1059     << "raw_ostream &OS, const PrintingPolicy &Policy) const {\n";
1060 
1061   if (Spellings.size() == 0) {
1062     OS << "}\n\n";
1063     return;
1064   }
1065 
1066   OS <<
1067     "  switch (SpellingListIndex) {\n"
1068     "  default:\n"
1069     "    llvm_unreachable(\"Unknown attribute spelling!\");\n"
1070     "    break;\n";
1071 
1072   for (unsigned I = 0; I < Spellings.size(); ++ I) {
1073     llvm::SmallString<16> Prefix;
1074     llvm::SmallString<8> Suffix;
1075     // The actual spelling of the name and namespace (if applicable)
1076     // of an attribute without considering prefix and suffix.
1077     llvm::SmallString<64> Spelling;
1078     std::string Name = Spellings[I].name();
1079     std::string Variety = Spellings[I].variety();
1080 
1081     if (Variety == "GNU") {
1082       Prefix = " __attribute__((";
1083       Suffix = "))";
1084     } else if (Variety == "CXX11") {
1085       Prefix = " [[";
1086       Suffix = "]]";
1087       std::string Namespace = Spellings[I].nameSpace();
1088       if (Namespace != "") {
1089         Spelling += Namespace;
1090         Spelling += "::";
1091       }
1092     } else if (Variety == "Declspec") {
1093       Prefix = " __declspec(";
1094       Suffix = ")";
1095     } else if (Variety == "Keyword") {
1096       Prefix = " ";
1097       Suffix = "";
1098     } else {
1099       llvm_unreachable("Unknown attribute syntax variety!");
1100     }
1101 
1102     Spelling += Name;
1103 
1104     OS <<
1105       "  case " << I << " : {\n"
1106       "    OS << \"" + Prefix.str() + Spelling.str();
1107 
1108     if (!Args.empty())
1109       OS << "(";
1110     if (Spelling == "availability") {
1111       writeAvailabilityValue(OS);
1112     } else {
1113       for (auto I = Args.begin(), E = Args.end(); I != E; ++ I) {
1114         if (I != Args.begin()) OS << ", ";
1115         (*I)->writeValue(OS);
1116       }
1117     }
1118 
1119     if (!Args.empty())
1120       OS << ")";
1121     OS << Suffix.str() + "\";\n";
1122 
1123     OS <<
1124       "    break;\n"
1125       "  }\n";
1126   }
1127 
1128   // End of the switch statement.
1129   OS << "}\n";
1130   // End of the print function.
1131   OS << "}\n\n";
1132 }
1133 
1134 /// \brief Return the index of a spelling in a spelling list.
1135 static unsigned
1136 getSpellingListIndex(const std::vector<FlattenedSpelling> &SpellingList,
1137                      const FlattenedSpelling &Spelling) {
1138   assert(SpellingList.size() && "Spelling list is empty!");
1139 
1140   for (unsigned Index = 0; Index < SpellingList.size(); ++Index) {
1141     const FlattenedSpelling &S = SpellingList[Index];
1142     if (S.variety() != Spelling.variety())
1143       continue;
1144     if (S.nameSpace() != Spelling.nameSpace())
1145       continue;
1146     if (S.name() != Spelling.name())
1147       continue;
1148 
1149     return Index;
1150   }
1151 
1152   llvm_unreachable("Unknown spelling!");
1153 }
1154 
1155 static void writeAttrAccessorDefinition(const Record &R, raw_ostream &OS) {
1156   std::vector<Record*> Accessors = R.getValueAsListOfDefs("Accessors");
1157   for (auto Accessor : Accessors) {
1158     std::string Name = Accessor->getValueAsString("Name");
1159     std::vector<FlattenedSpelling> Spellings =
1160       GetFlattenedSpellings(*Accessor);
1161     std::vector<FlattenedSpelling> SpellingList = GetFlattenedSpellings(R);
1162     assert(SpellingList.size() &&
1163            "Attribute with empty spelling list can't have accessors!");
1164 
1165     OS << "  bool " << Name << "() const { return SpellingListIndex == ";
1166     for (unsigned Index = 0; Index < Spellings.size(); ++Index) {
1167       OS << getSpellingListIndex(SpellingList, Spellings[Index]);
1168       if (Index != Spellings.size() -1)
1169         OS << " ||\n    SpellingListIndex == ";
1170       else
1171         OS << "; }\n";
1172     }
1173   }
1174 }
1175 
1176 static bool
1177 SpellingNamesAreCommon(const std::vector<FlattenedSpelling>& Spellings) {
1178   assert(!Spellings.empty() && "An empty list of spellings was provided");
1179   std::string FirstName = NormalizeNameForSpellingComparison(
1180     Spellings.front().name());
1181   for (auto I = std::next(Spellings.begin()), E = Spellings.end();
1182        I != E; ++I) {
1183     std::string Name = NormalizeNameForSpellingComparison(I->name());
1184     if (Name != FirstName)
1185       return false;
1186   }
1187   return true;
1188 }
1189 
1190 typedef std::map<unsigned, std::string> SemanticSpellingMap;
1191 static std::string
1192 CreateSemanticSpellings(const std::vector<FlattenedSpelling> &Spellings,
1193                         SemanticSpellingMap &Map) {
1194   // The enumerants are automatically generated based on the variety,
1195   // namespace (if present) and name for each attribute spelling. However,
1196   // care is taken to avoid trampling on the reserved namespace due to
1197   // underscores.
1198   std::string Ret("  enum Spelling {\n");
1199   std::set<std::string> Uniques;
1200   unsigned Idx = 0;
1201   for (auto I = Spellings.begin(), E = Spellings.end(); I != E; ++I, ++Idx) {
1202     const FlattenedSpelling &S = *I;
1203     std::string Variety = S.variety();
1204     std::string Spelling = S.name();
1205     std::string Namespace = S.nameSpace();
1206     std::string EnumName = "";
1207 
1208     EnumName += (Variety + "_");
1209     if (!Namespace.empty())
1210       EnumName += (NormalizeNameForSpellingComparison(Namespace).str() +
1211       "_");
1212     EnumName += NormalizeNameForSpellingComparison(Spelling);
1213 
1214     // Even if the name is not unique, this spelling index corresponds to a
1215     // particular enumerant name that we've calculated.
1216     Map[Idx] = EnumName;
1217 
1218     // Since we have been stripping underscores to avoid trampling on the
1219     // reserved namespace, we may have inadvertently created duplicate
1220     // enumerant names. These duplicates are not considered part of the
1221     // semantic spelling, and can be elided.
1222     if (Uniques.find(EnumName) != Uniques.end())
1223       continue;
1224 
1225     Uniques.insert(EnumName);
1226     if (I != Spellings.begin())
1227       Ret += ",\n";
1228     Ret += "    " + EnumName;
1229   }
1230   Ret += "\n  };\n\n";
1231   return Ret;
1232 }
1233 
1234 void WriteSemanticSpellingSwitch(const std::string &VarName,
1235                                  const SemanticSpellingMap &Map,
1236                                  raw_ostream &OS) {
1237   OS << "  switch (" << VarName << ") {\n    default: "
1238     << "llvm_unreachable(\"Unknown spelling list index\");\n";
1239   for (const auto &I : Map)
1240     OS << "    case " << I.first << ": return " << I.second << ";\n";
1241   OS << "  }\n";
1242 }
1243 
1244 // Emits the LateParsed property for attributes.
1245 static void emitClangAttrLateParsedList(RecordKeeper &Records, raw_ostream &OS) {
1246   OS << "#if defined(CLANG_ATTR_LATE_PARSED_LIST)\n";
1247   std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr");
1248 
1249   for (auto Attr : Attrs) {
1250     bool LateParsed = Attr->getValueAsBit("LateParsed");
1251 
1252     if (LateParsed) {
1253       std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(*Attr);
1254 
1255       // FIXME: Handle non-GNU attributes
1256       for (const auto &I : Spellings) {
1257         if (I.variety() != "GNU")
1258           continue;
1259         OS << ".Case(\"" << I.name() << "\", " << LateParsed << ")\n";
1260       }
1261     }
1262   }
1263   OS << "#endif // CLANG_ATTR_LATE_PARSED_LIST\n\n";
1264 }
1265 
1266 /// \brief Emits the first-argument-is-type property for attributes.
1267 static void emitClangAttrTypeArgList(RecordKeeper &Records, raw_ostream &OS) {
1268   OS << "#if defined(CLANG_ATTR_TYPE_ARG_LIST)\n";
1269   std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
1270 
1271   for (auto Attr : Attrs) {
1272     // Determine whether the first argument is a type.
1273     std::vector<Record *> Args = Attr->getValueAsListOfDefs("Args");
1274     if (Args.empty())
1275       continue;
1276 
1277     if (Args[0]->getSuperClasses().back()->getName() != "TypeArgument")
1278       continue;
1279 
1280     // All these spellings take a single type argument.
1281     std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(*Attr);
1282     std::set<std::string> Emitted;
1283     for (const auto &S : Spellings) {
1284       if (Emitted.insert(S.name()).second)
1285         OS << ".Case(\"" << S.name() << "\", " << "true" << ")\n";
1286     }
1287   }
1288   OS << "#endif // CLANG_ATTR_TYPE_ARG_LIST\n\n";
1289 }
1290 
1291 /// \brief Emits the parse-arguments-in-unevaluated-context property for
1292 /// attributes.
1293 static void emitClangAttrArgContextList(RecordKeeper &Records, raw_ostream &OS) {
1294   OS << "#if defined(CLANG_ATTR_ARG_CONTEXT_LIST)\n";
1295   ParsedAttrMap Attrs = getParsedAttrList(Records);
1296   for (const auto &I : Attrs) {
1297     const Record &Attr = *I.second;
1298 
1299     if (!Attr.getValueAsBit("ParseArgumentsAsUnevaluated"))
1300       continue;
1301 
1302     // All these spellings take are parsed unevaluated.
1303     std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(Attr);
1304     std::set<std::string> Emitted;
1305     for (const auto &S : Spellings) {
1306       if (Emitted.insert(S.name()).second)
1307         OS << ".Case(\"" << S.name() << "\", " << "true" << ")\n";
1308     }
1309   }
1310   OS << "#endif // CLANG_ATTR_ARG_CONTEXT_LIST\n\n";
1311 }
1312 
1313 static bool isIdentifierArgument(Record *Arg) {
1314   return !Arg->getSuperClasses().empty() &&
1315     llvm::StringSwitch<bool>(Arg->getSuperClasses().back()->getName())
1316     .Case("IdentifierArgument", true)
1317     .Case("EnumArgument", true)
1318     .Default(false);
1319 }
1320 
1321 // Emits the first-argument-is-identifier property for attributes.
1322 static void emitClangAttrIdentifierArgList(RecordKeeper &Records, raw_ostream &OS) {
1323   OS << "#if defined(CLANG_ATTR_IDENTIFIER_ARG_LIST)\n";
1324   std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr");
1325 
1326   for (auto Attr : Attrs) {
1327     // Determine whether the first argument is an identifier.
1328     std::vector<Record *> Args = Attr->getValueAsListOfDefs("Args");
1329     if (Args.empty() || !isIdentifierArgument(Args[0]))
1330       continue;
1331 
1332     // All these spellings take an identifier argument.
1333     std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(*Attr);
1334     std::set<std::string> Emitted;
1335     for (const auto &S : Spellings) {
1336       if (Emitted.insert(S.name()).second)
1337         OS << ".Case(\"" << S.name() << "\", " << "true" << ")\n";
1338     }
1339   }
1340   OS << "#endif // CLANG_ATTR_IDENTIFIER_ARG_LIST\n\n";
1341 }
1342 
1343 namespace clang {
1344 
1345 // Emits the class definitions for attributes.
1346 void EmitClangAttrClass(RecordKeeper &Records, raw_ostream &OS) {
1347   emitSourceFileHeader("Attribute classes' definitions", OS);
1348 
1349   OS << "#ifndef LLVM_CLANG_ATTR_CLASSES_INC\n";
1350   OS << "#define LLVM_CLANG_ATTR_CLASSES_INC\n\n";
1351 
1352   std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr");
1353 
1354   for (auto i : Attrs) {
1355     const Record &R = *i;
1356 
1357     // FIXME: Currently, documentation is generated as-needed due to the fact
1358     // that there is no way to allow a generated project "reach into" the docs
1359     // directory (for instance, it may be an out-of-tree build). However, we want
1360     // to ensure that every attribute has a Documentation field, and produce an
1361     // error if it has been neglected. Otherwise, the on-demand generation which
1362     // happens server-side will fail. This code is ensuring that functionality,
1363     // even though this Emitter doesn't technically need the documentation.
1364     // When attribute documentation can be generated as part of the build
1365     // itself, this code can be removed.
1366     (void)R.getValueAsListOfDefs("Documentation");
1367 
1368     if (!R.getValueAsBit("ASTNode"))
1369       continue;
1370 
1371     const std::vector<Record *> Supers = R.getSuperClasses();
1372     assert(!Supers.empty() && "Forgot to specify a superclass for the attr");
1373     std::string SuperName;
1374     for (auto I = Supers.rbegin(), E = Supers.rend(); I != E; ++I) {
1375       const Record &R = **I;
1376       if (R.getName() != "TargetSpecificAttr" && SuperName.empty())
1377         SuperName = R.getName();
1378     }
1379 
1380     OS << "class " << R.getName() << "Attr : public " << SuperName << " {\n";
1381 
1382     std::vector<Record*> ArgRecords = R.getValueAsListOfDefs("Args");
1383     std::vector<std::unique_ptr<Argument>> Args;
1384     Args.reserve(ArgRecords.size());
1385 
1386     for (auto ArgRecord : ArgRecords) {
1387       Args.emplace_back(createArgument(*ArgRecord, R.getName()));
1388       Args.back()->writeDeclarations(OS);
1389       OS << "\n\n";
1390     }
1391 
1392     OS << "\npublic:\n";
1393 
1394     std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(R);
1395 
1396     // If there are zero or one spellings, all spelling-related functionality
1397     // can be elided. If all of the spellings share the same name, the spelling
1398     // functionality can also be elided.
1399     bool ElideSpelling = (Spellings.size() <= 1) ||
1400                          SpellingNamesAreCommon(Spellings);
1401 
1402     // This maps spelling index values to semantic Spelling enumerants.
1403     SemanticSpellingMap SemanticToSyntacticMap;
1404 
1405     if (!ElideSpelling)
1406       OS << CreateSemanticSpellings(Spellings, SemanticToSyntacticMap);
1407 
1408     OS << "  static " << R.getName() << "Attr *CreateImplicit(";
1409     OS << "ASTContext &Ctx";
1410     if (!ElideSpelling)
1411       OS << ", Spelling S";
1412     for (auto const &ai : Args) {
1413       OS << ", ";
1414       ai->writeCtorParameters(OS);
1415     }
1416     OS << ", SourceRange Loc = SourceRange()";
1417     OS << ") {\n";
1418     OS << "    " << R.getName() << "Attr *A = new (Ctx) " << R.getName();
1419     OS << "Attr(Loc, Ctx, ";
1420     for (auto const &ai : Args) {
1421       ai->writeImplicitCtorArgs(OS);
1422       OS << ", ";
1423     }
1424     OS << (ElideSpelling ? "0" : "S") << ");\n";
1425     OS << "    A->setImplicit(true);\n";
1426     OS << "    return A;\n  }\n\n";
1427 
1428     OS << "  " << R.getName() << "Attr(SourceRange R, ASTContext &Ctx\n";
1429 
1430     bool HasOpt = false;
1431     for (auto const &ai : Args) {
1432       OS << "              , ";
1433       ai->writeCtorParameters(OS);
1434       OS << "\n";
1435       if (ai->isOptional())
1436         HasOpt = true;
1437     }
1438 
1439     OS << "              , ";
1440     OS << "unsigned SI\n";
1441 
1442     OS << "             )\n";
1443     OS << "    : " << SuperName << "(attr::" << R.getName() << ", R, SI)\n";
1444 
1445     for (auto const &ai : Args) {
1446       OS << "              , ";
1447       ai->writeCtorInitializers(OS);
1448       OS << "\n";
1449     }
1450 
1451     OS << "  {\n";
1452 
1453     for (auto const &ai : Args) {
1454       ai->writeCtorBody(OS);
1455       OS << "\n";
1456     }
1457     OS << "  }\n\n";
1458 
1459     // If there are optional arguments, write out a constructor that elides the
1460     // optional arguments as well.
1461     if (HasOpt) {
1462       OS << "  " << R.getName() << "Attr(SourceRange R, ASTContext &Ctx\n";
1463       for (auto const &ai : Args) {
1464         if (!ai->isOptional()) {
1465           OS << "              , ";
1466           ai->writeCtorParameters(OS);
1467           OS << "\n";
1468         }
1469       }
1470 
1471       OS << "              , ";
1472       OS << "unsigned SI\n";
1473 
1474       OS << "             )\n";
1475       OS << "    : " << SuperName << "(attr::" << R.getName() << ", R, SI)\n";
1476 
1477       for (auto const &ai : Args) {
1478         OS << "              , ";
1479         ai->writeCtorDefaultInitializers(OS);
1480         OS << "\n";
1481       }
1482 
1483       OS << "  {\n";
1484 
1485       for (auto const &ai : Args) {
1486         if (!ai->isOptional()) {
1487           ai->writeCtorBody(OS);
1488           OS << "\n";
1489         }
1490       }
1491       OS << "  }\n\n";
1492     }
1493 
1494     OS << "  " << R.getName() << "Attr *clone(ASTContext &C) const override;\n";
1495     OS << "  void printPretty(raw_ostream &OS,\n"
1496        << "                   const PrintingPolicy &Policy) const override;\n";
1497     OS << "  const char *getSpelling() const override;\n";
1498 
1499     if (!ElideSpelling) {
1500       assert(!SemanticToSyntacticMap.empty() && "Empty semantic mapping list");
1501       OS << "  Spelling getSemanticSpelling() const {\n";
1502       WriteSemanticSpellingSwitch("SpellingListIndex", SemanticToSyntacticMap,
1503                                   OS);
1504       OS << "  }\n";
1505     }
1506 
1507     writeAttrAccessorDefinition(R, OS);
1508 
1509     for (auto const &ai : Args) {
1510       ai->writeAccessors(OS);
1511       OS << "\n\n";
1512 
1513       if (ai->isEnumArg())
1514         static_cast<const EnumArgument *>(ai.get())->writeConversion(OS);
1515       else if (ai->isVariadicEnumArg())
1516         static_cast<const VariadicEnumArgument *>(ai.get())
1517             ->writeConversion(OS);
1518     }
1519 
1520     OS << R.getValueAsString("AdditionalMembers");
1521     OS << "\n\n";
1522 
1523     OS << "  static bool classof(const Attr *A) { return A->getKind() == "
1524        << "attr::" << R.getName() << "; }\n";
1525 
1526     bool LateParsed = R.getValueAsBit("LateParsed");
1527     OS << "  bool isLateParsed() const override { return "
1528        << LateParsed << "; }\n";
1529 
1530     if (R.getValueAsBit("DuplicatesAllowedWhileMerging"))
1531       OS << "  bool duplicatesAllowed() const override { return true; }\n\n";
1532 
1533     OS << "};\n\n";
1534   }
1535 
1536   OS << "#endif\n";
1537 }
1538 
1539 // Emits the class method definitions for attributes.
1540 void EmitClangAttrImpl(RecordKeeper &Records, raw_ostream &OS) {
1541   emitSourceFileHeader("Attribute classes' member function definitions", OS);
1542 
1543   std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr");
1544 
1545   for (auto i : Attrs) {
1546     Record &R = *i;
1547 
1548     if (!R.getValueAsBit("ASTNode"))
1549       continue;
1550 
1551     std::vector<Record*> ArgRecords = R.getValueAsListOfDefs("Args");
1552     std::vector<std::unique_ptr<Argument>> Args;
1553     for (auto ri : ArgRecords)
1554       Args.emplace_back(createArgument(*ri, R.getName()));
1555 
1556     for (auto const &ai : Args)
1557       ai->writeAccessorDefinitions(OS);
1558 
1559     OS << R.getName() << "Attr *" << R.getName()
1560        << "Attr::clone(ASTContext &C) const {\n";
1561     OS << "  return new (C) " << R.getName() << "Attr(getLocation(), C";
1562     for (auto const &ai : Args) {
1563       OS << ", ";
1564       ai->writeCloneArgs(OS);
1565     }
1566     OS << ", getSpellingListIndex());\n}\n\n";
1567 
1568     writePrettyPrintFunction(R, Args, OS);
1569     writeGetSpellingFunction(R, OS);
1570   }
1571 }
1572 
1573 } // end namespace clang
1574 
1575 static void EmitAttrList(raw_ostream &OS, StringRef Class,
1576                          const std::vector<Record*> &AttrList) {
1577   std::vector<Record*>::const_iterator i = AttrList.begin(), e = AttrList.end();
1578 
1579   if (i != e) {
1580     // Move the end iterator back to emit the last attribute.
1581     for(--e; i != e; ++i) {
1582       if (!(*i)->getValueAsBit("ASTNode"))
1583         continue;
1584 
1585       OS << Class << "(" << (*i)->getName() << ")\n";
1586     }
1587 
1588     OS << "LAST_" << Class << "(" << (*i)->getName() << ")\n\n";
1589   }
1590 }
1591 
1592 namespace clang {
1593 
1594 // Emits the enumeration list for attributes.
1595 void EmitClangAttrList(RecordKeeper &Records, raw_ostream &OS) {
1596   emitSourceFileHeader("List of all attributes that Clang recognizes", OS);
1597 
1598   OS << "#ifndef LAST_ATTR\n";
1599   OS << "#define LAST_ATTR(NAME) ATTR(NAME)\n";
1600   OS << "#endif\n\n";
1601 
1602   OS << "#ifndef INHERITABLE_ATTR\n";
1603   OS << "#define INHERITABLE_ATTR(NAME) ATTR(NAME)\n";
1604   OS << "#endif\n\n";
1605 
1606   OS << "#ifndef LAST_INHERITABLE_ATTR\n";
1607   OS << "#define LAST_INHERITABLE_ATTR(NAME) INHERITABLE_ATTR(NAME)\n";
1608   OS << "#endif\n\n";
1609 
1610   OS << "#ifndef INHERITABLE_PARAM_ATTR\n";
1611   OS << "#define INHERITABLE_PARAM_ATTR(NAME) ATTR(NAME)\n";
1612   OS << "#endif\n\n";
1613 
1614   OS << "#ifndef LAST_INHERITABLE_PARAM_ATTR\n";
1615   OS << "#define LAST_INHERITABLE_PARAM_ATTR(NAME)"
1616         " INHERITABLE_PARAM_ATTR(NAME)\n";
1617   OS << "#endif\n\n";
1618 
1619   Record *InhClass = Records.getClass("InheritableAttr");
1620   Record *InhParamClass = Records.getClass("InheritableParamAttr");
1621   std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr"),
1622                        NonInhAttrs, InhAttrs, InhParamAttrs;
1623   for (auto i : Attrs) {
1624     if (!i->getValueAsBit("ASTNode"))
1625       continue;
1626 
1627     if (i->isSubClassOf(InhParamClass))
1628       InhParamAttrs.push_back(i);
1629     else if (i->isSubClassOf(InhClass))
1630       InhAttrs.push_back(i);
1631     else
1632       NonInhAttrs.push_back(i);
1633   }
1634 
1635   EmitAttrList(OS, "INHERITABLE_PARAM_ATTR", InhParamAttrs);
1636   EmitAttrList(OS, "INHERITABLE_ATTR", InhAttrs);
1637   EmitAttrList(OS, "ATTR", NonInhAttrs);
1638 
1639   OS << "#undef LAST_ATTR\n";
1640   OS << "#undef INHERITABLE_ATTR\n";
1641   OS << "#undef LAST_INHERITABLE_ATTR\n";
1642   OS << "#undef LAST_INHERITABLE_PARAM_ATTR\n";
1643   OS << "#undef ATTR\n";
1644 }
1645 
1646 // Emits the code to read an attribute from a precompiled header.
1647 void EmitClangAttrPCHRead(RecordKeeper &Records, raw_ostream &OS) {
1648   emitSourceFileHeader("Attribute deserialization code", OS);
1649 
1650   Record *InhClass = Records.getClass("InheritableAttr");
1651   std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr"),
1652                        ArgRecords;
1653   std::vector<std::unique_ptr<Argument>> Args;
1654 
1655   OS << "  switch (Kind) {\n";
1656   OS << "  default:\n";
1657   OS << "    assert(0 && \"Unknown attribute!\");\n";
1658   OS << "    break;\n";
1659   for (auto i : Attrs) {
1660     const Record &R = *i;
1661     if (!R.getValueAsBit("ASTNode"))
1662       continue;
1663 
1664     OS << "  case attr::" << R.getName() << ": {\n";
1665     if (R.isSubClassOf(InhClass))
1666       OS << "    bool isInherited = Record[Idx++];\n";
1667     OS << "    bool isImplicit = Record[Idx++];\n";
1668     OS << "    unsigned Spelling = Record[Idx++];\n";
1669     ArgRecords = R.getValueAsListOfDefs("Args");
1670     Args.clear();
1671     for (auto ai : ArgRecords) {
1672       Args.emplace_back(createArgument(*ai, R.getName()));
1673       Args.back()->writePCHReadDecls(OS);
1674     }
1675     OS << "    New = new (Context) " << R.getName() << "Attr(Range, Context";
1676     for (auto const &ri : Args) {
1677       OS << ", ";
1678       ri->writePCHReadArgs(OS);
1679     }
1680     OS << ", Spelling);\n";
1681     if (R.isSubClassOf(InhClass))
1682       OS << "    cast<InheritableAttr>(New)->setInherited(isInherited);\n";
1683     OS << "    New->setImplicit(isImplicit);\n";
1684     OS << "    break;\n";
1685     OS << "  }\n";
1686   }
1687   OS << "  }\n";
1688 }
1689 
1690 // Emits the code to write an attribute to a precompiled header.
1691 void EmitClangAttrPCHWrite(RecordKeeper &Records, raw_ostream &OS) {
1692   emitSourceFileHeader("Attribute serialization code", OS);
1693 
1694   Record *InhClass = Records.getClass("InheritableAttr");
1695   std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr"), Args;
1696 
1697   OS << "  switch (A->getKind()) {\n";
1698   OS << "  default:\n";
1699   OS << "    llvm_unreachable(\"Unknown attribute kind!\");\n";
1700   OS << "    break;\n";
1701   for (auto i : Attrs) {
1702     const Record &R = *i;
1703     if (!R.getValueAsBit("ASTNode"))
1704       continue;
1705     OS << "  case attr::" << R.getName() << ": {\n";
1706     Args = R.getValueAsListOfDefs("Args");
1707     if (R.isSubClassOf(InhClass) || !Args.empty())
1708       OS << "    const " << R.getName() << "Attr *SA = cast<" << R.getName()
1709          << "Attr>(A);\n";
1710     if (R.isSubClassOf(InhClass))
1711       OS << "    Record.push_back(SA->isInherited());\n";
1712     OS << "    Record.push_back(A->isImplicit());\n";
1713     OS << "    Record.push_back(A->getSpellingListIndex());\n";
1714 
1715     for (auto ai : Args)
1716       createArgument(*ai, R.getName())->writePCHWrite(OS);
1717     OS << "    break;\n";
1718     OS << "  }\n";
1719   }
1720   OS << "  }\n";
1721 }
1722 
1723 // Emits the list of spellings for attributes.
1724 void EmitClangAttrSpellingList(RecordKeeper &Records, raw_ostream &OS) {
1725   emitSourceFileHeader("llvm::StringSwitch code to match attributes based on "
1726                        "the target triple, T", OS);
1727 
1728   std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr");
1729 
1730   for (auto I : Attrs) {
1731     Record &Attr = *I;
1732 
1733     // It is assumed that there will be an llvm::Triple object named T within
1734     // scope that can be used to determine whether the attribute exists in
1735     // a given target.
1736     std::string Test;
1737     if (Attr.isSubClassOf("TargetSpecificAttr")) {
1738       const Record *R = Attr.getValueAsDef("Target");
1739       std::vector<std::string> Arches = R->getValueAsListOfStrings("Arches");
1740 
1741       Test += "(";
1742       for (auto AI = Arches.begin(), AE = Arches.end(); AI != AE; ++AI) {
1743         std::string Part = *AI;
1744         Test += "T.getArch() == llvm::Triple::" + Part;
1745         if (AI + 1 != AE)
1746           Test += " || ";
1747       }
1748       Test += ")";
1749 
1750       std::vector<std::string> OSes;
1751       if (!R->isValueUnset("OSes")) {
1752         Test += " && (";
1753         std::vector<std::string> OSes = R->getValueAsListOfStrings("OSes");
1754         for (auto AI = OSes.begin(), AE = OSes.end(); AI != AE; ++AI) {
1755           std::string Part = *AI;
1756 
1757           Test += "T.getOS() == llvm::Triple::" + Part;
1758           if (AI + 1 != AE)
1759             Test += " || ";
1760         }
1761         Test += ")";
1762       }
1763     } else
1764       Test = "true";
1765 
1766     std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(Attr);
1767     for (const auto &S : Spellings)
1768       OS << ".Case(\"" << S.name() << "\", " << Test << ")\n";
1769   }
1770 }
1771 
1772 void EmitClangAttrSpellingListIndex(RecordKeeper &Records, raw_ostream &OS) {
1773   emitSourceFileHeader("Code to translate different attribute spellings "
1774                        "into internal identifiers", OS);
1775 
1776   OS <<
1777     "  switch (AttrKind) {\n"
1778     "  default:\n"
1779     "    llvm_unreachable(\"Unknown attribute kind!\");\n"
1780     "    break;\n";
1781 
1782   ParsedAttrMap Attrs = getParsedAttrList(Records);
1783   for (const auto &I : Attrs) {
1784     Record &R = *I.second;
1785     std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(R);
1786     OS << "  case AT_" << I.first << ": {\n";
1787     for (unsigned I = 0; I < Spellings.size(); ++ I) {
1788       OS << "    if (Name == \""
1789         << Spellings[I].name() << "\" && "
1790         << "SyntaxUsed == "
1791         << StringSwitch<unsigned>(Spellings[I].variety())
1792           .Case("GNU", 0)
1793           .Case("CXX11", 1)
1794           .Case("Declspec", 2)
1795           .Case("Keyword", 3)
1796           .Default(0)
1797         << " && Scope == \"" << Spellings[I].nameSpace() << "\")\n"
1798         << "        return " << I << ";\n";
1799     }
1800 
1801     OS << "    break;\n";
1802     OS << "  }\n";
1803   }
1804 
1805   OS << "  }\n";
1806   OS << "  return 0;\n";
1807 }
1808 
1809 // Emits code used by RecursiveASTVisitor to visit attributes
1810 void EmitClangAttrASTVisitor(RecordKeeper &Records, raw_ostream &OS) {
1811   emitSourceFileHeader("Used by RecursiveASTVisitor to visit attributes.", OS);
1812 
1813   std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr");
1814 
1815   // Write method declarations for Traverse* methods.
1816   // We emit this here because we only generate methods for attributes that
1817   // are declared as ASTNodes.
1818   OS << "#ifdef ATTR_VISITOR_DECLS_ONLY\n\n";
1819   for (auto I : Attrs) {
1820     const Record &R = *I;
1821     if (!R.getValueAsBit("ASTNode"))
1822       continue;
1823     OS << "  bool Traverse"
1824        << R.getName() << "Attr(" << R.getName() << "Attr *A);\n";
1825     OS << "  bool Visit"
1826        << R.getName() << "Attr(" << R.getName() << "Attr *A) {\n"
1827        << "    return true; \n"
1828        << "  };\n";
1829   }
1830   OS << "\n#else // ATTR_VISITOR_DECLS_ONLY\n\n";
1831 
1832   // Write individual Traverse* methods for each attribute class.
1833   for (auto I : Attrs) {
1834     const Record &R = *I;
1835     if (!R.getValueAsBit("ASTNode"))
1836       continue;
1837 
1838     OS << "template <typename Derived>\n"
1839        << "bool VISITORCLASS<Derived>::Traverse"
1840        << R.getName() << "Attr(" << R.getName() << "Attr *A) {\n"
1841        << "  if (!getDerived().VisitAttr(A))\n"
1842        << "    return false;\n"
1843        << "  if (!getDerived().Visit" << R.getName() << "Attr(A))\n"
1844        << "    return false;\n";
1845 
1846     std::vector<Record*> ArgRecords = R.getValueAsListOfDefs("Args");
1847     for (auto ri : ArgRecords)
1848       createArgument(*ri, R.getName())->writeASTVisitorTraversal(OS);
1849 
1850     OS << "  return true;\n";
1851     OS << "}\n\n";
1852   }
1853 
1854   // Write generic Traverse routine
1855   OS << "template <typename Derived>\n"
1856      << "bool VISITORCLASS<Derived>::TraverseAttr(Attr *A) {\n"
1857      << "  if (!A)\n"
1858      << "    return true;\n"
1859      << "\n"
1860      << "  switch (A->getKind()) {\n"
1861      << "    default:\n"
1862      << "      return true;\n";
1863 
1864   for (auto I : Attrs) {
1865     const Record &R = *I;
1866     if (!R.getValueAsBit("ASTNode"))
1867       continue;
1868 
1869     OS << "    case attr::" << R.getName() << ":\n"
1870        << "      return getDerived().Traverse" << R.getName() << "Attr("
1871        << "cast<" << R.getName() << "Attr>(A));\n";
1872   }
1873   OS << "  }\n";  // end case
1874   OS << "}\n";  // end function
1875   OS << "#endif  // ATTR_VISITOR_DECLS_ONLY\n";
1876 }
1877 
1878 // Emits code to instantiate dependent attributes on templates.
1879 void EmitClangAttrTemplateInstantiate(RecordKeeper &Records, raw_ostream &OS) {
1880   emitSourceFileHeader("Template instantiation code for attributes", OS);
1881 
1882   std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr");
1883 
1884   OS << "namespace clang {\n"
1885      << "namespace sema {\n\n"
1886      << "Attr *instantiateTemplateAttribute(const Attr *At, ASTContext &C, "
1887      << "Sema &S,\n"
1888      << "        const MultiLevelTemplateArgumentList &TemplateArgs) {\n"
1889      << "  switch (At->getKind()) {\n"
1890      << "    default:\n"
1891      << "      break;\n";
1892 
1893   for (auto I : Attrs) {
1894     const Record &R = *I;
1895     if (!R.getValueAsBit("ASTNode"))
1896       continue;
1897 
1898     OS << "    case attr::" << R.getName() << ": {\n";
1899     bool ShouldClone = R.getValueAsBit("Clone");
1900 
1901     if (!ShouldClone) {
1902       OS << "      return NULL;\n";
1903       OS << "    }\n";
1904       continue;
1905     }
1906 
1907     OS << "      const " << R.getName() << "Attr *A = cast<"
1908        << R.getName() << "Attr>(At);\n";
1909     bool TDependent = R.getValueAsBit("TemplateDependent");
1910 
1911     if (!TDependent) {
1912       OS << "      return A->clone(C);\n";
1913       OS << "    }\n";
1914       continue;
1915     }
1916 
1917     std::vector<Record*> ArgRecords = R.getValueAsListOfDefs("Args");
1918     std::vector<std::unique_ptr<Argument>> Args;
1919     Args.reserve(ArgRecords.size());
1920 
1921     for (auto ArgRecord : ArgRecords)
1922       Args.emplace_back(createArgument(*ArgRecord, R.getName()));
1923 
1924     for (auto const &ai : Args)
1925       ai->writeTemplateInstantiation(OS);
1926 
1927     OS << "      return new (C) " << R.getName() << "Attr(A->getLocation(), C";
1928     for (auto const &ai : Args) {
1929       OS << ", ";
1930       ai->writeTemplateInstantiationArgs(OS);
1931     }
1932     OS << ", A->getSpellingListIndex());\n    }\n";
1933   }
1934   OS << "  } // end switch\n"
1935      << "  llvm_unreachable(\"Unknown attribute!\");\n"
1936      << "  return 0;\n"
1937      << "}\n\n"
1938      << "} // end namespace sema\n"
1939      << "} // end namespace clang\n";
1940 }
1941 
1942 // Emits the list of parsed attributes.
1943 void EmitClangAttrParsedAttrList(RecordKeeper &Records, raw_ostream &OS) {
1944   emitSourceFileHeader("List of all attributes that Clang recognizes", OS);
1945 
1946   OS << "#ifndef PARSED_ATTR\n";
1947   OS << "#define PARSED_ATTR(NAME) NAME\n";
1948   OS << "#endif\n\n";
1949 
1950   ParsedAttrMap Names = getParsedAttrList(Records);
1951   for (const auto &I : Names) {
1952     OS << "PARSED_ATTR(" << I.first << ")\n";
1953   }
1954 }
1955 
1956 static void emitArgInfo(const Record &R, std::stringstream &OS) {
1957   // This function will count the number of arguments specified for the
1958   // attribute and emit the number of required arguments followed by the
1959   // number of optional arguments.
1960   std::vector<Record *> Args = R.getValueAsListOfDefs("Args");
1961   unsigned ArgCount = 0, OptCount = 0;
1962   for (auto Arg : Args) {
1963     Arg->getValueAsBit("Optional") ? ++OptCount : ++ArgCount;
1964   }
1965   OS << ArgCount << ", " << OptCount;
1966 }
1967 
1968 static void GenerateDefaultAppertainsTo(raw_ostream &OS) {
1969   OS << "static bool defaultAppertainsTo(Sema &, const AttributeList &,";
1970   OS << "const Decl *) {\n";
1971   OS << "  return true;\n";
1972   OS << "}\n\n";
1973 }
1974 
1975 static std::string CalculateDiagnostic(const Record &S) {
1976   // If the SubjectList object has a custom diagnostic associated with it,
1977   // return that directly.
1978   std::string CustomDiag = S.getValueAsString("CustomDiag");
1979   if (!CustomDiag.empty())
1980     return CustomDiag;
1981 
1982   // Given the list of subjects, determine what diagnostic best fits.
1983   enum {
1984     Func = 1U << 0,
1985     Var = 1U << 1,
1986     ObjCMethod = 1U << 2,
1987     Param = 1U << 3,
1988     Class = 1U << 4,
1989     GenericRecord = 1U << 5,
1990     Type = 1U << 6,
1991     ObjCIVar = 1U << 7,
1992     ObjCProp = 1U << 8,
1993     ObjCInterface = 1U << 9,
1994     Block = 1U << 10,
1995     Namespace = 1U << 11,
1996     FuncTemplate = 1U << 12,
1997     Field = 1U << 13,
1998     CXXMethod = 1U << 14,
1999     ObjCProtocol = 1U << 15
2000   };
2001   uint32_t SubMask = 0;
2002 
2003   std::vector<Record *> Subjects = S.getValueAsListOfDefs("Subjects");
2004   for (auto I : Subjects) {
2005     const Record &R = *I;
2006     std::string Name;
2007 
2008     if (R.isSubClassOf("SubsetSubject")) {
2009       PrintError(R.getLoc(), "SubsetSubjects should use a custom diagnostic");
2010       // As a fallback, look through the SubsetSubject to see what its base
2011       // type is, and use that. This needs to be updated if SubsetSubjects
2012       // are allowed within other SubsetSubjects.
2013       Name = R.getValueAsDef("Base")->getName();
2014     } else
2015       Name = R.getName();
2016 
2017     uint32_t V = StringSwitch<uint32_t>(Name)
2018                    .Case("Function", Func)
2019                    .Case("Var", Var)
2020                    .Case("ObjCMethod", ObjCMethod)
2021                    .Case("ParmVar", Param)
2022                    .Case("TypedefName", Type)
2023                    .Case("ObjCIvar", ObjCIVar)
2024                    .Case("ObjCProperty", ObjCProp)
2025                    .Case("Record", GenericRecord)
2026                    .Case("ObjCInterface", ObjCInterface)
2027                    .Case("ObjCProtocol", ObjCProtocol)
2028                    .Case("Block", Block)
2029                    .Case("CXXRecord", Class)
2030                    .Case("Namespace", Namespace)
2031                    .Case("FunctionTemplate", FuncTemplate)
2032                    .Case("Field", Field)
2033                    .Case("CXXMethod", CXXMethod)
2034                    .Default(0);
2035     if (!V) {
2036       // Something wasn't in our mapping, so be helpful and let the developer
2037       // know about it.
2038       PrintFatalError(R.getLoc(), "Unknown subject type: " + R.getName());
2039       return "";
2040     }
2041 
2042     SubMask |= V;
2043   }
2044 
2045   switch (SubMask) {
2046     // For the simple cases where there's only a single entry in the mask, we
2047     // don't have to resort to bit fiddling.
2048     case Func:  return "ExpectedFunction";
2049     case Var:   return "ExpectedVariable";
2050     case Param: return "ExpectedParameter";
2051     case Class: return "ExpectedClass";
2052     case CXXMethod:
2053       // FIXME: Currently, this maps to ExpectedMethod based on existing code,
2054       // but should map to something a bit more accurate at some point.
2055     case ObjCMethod:  return "ExpectedMethod";
2056     case Type:  return "ExpectedType";
2057     case ObjCInterface: return "ExpectedObjectiveCInterface";
2058     case ObjCProtocol: return "ExpectedObjectiveCProtocol";
2059 
2060     // "GenericRecord" means struct, union or class; check the language options
2061     // and if not compiling for C++, strip off the class part. Note that this
2062     // relies on the fact that the context for this declares "Sema &S".
2063     case GenericRecord:
2064       return "(S.getLangOpts().CPlusPlus ? ExpectedStructOrUnionOrClass : "
2065                                            "ExpectedStructOrUnion)";
2066     case Func | ObjCMethod | Block: return "ExpectedFunctionMethodOrBlock";
2067     case Func | ObjCMethod | Class: return "ExpectedFunctionMethodOrClass";
2068     case Func | Param:
2069     case Func | ObjCMethod | Param: return "ExpectedFunctionMethodOrParameter";
2070     case Func | FuncTemplate:
2071     case Func | ObjCMethod: return "ExpectedFunctionOrMethod";
2072     case Func | Var: return "ExpectedVariableOrFunction";
2073 
2074     // If not compiling for C++, the class portion does not apply.
2075     case Func | Var | Class:
2076       return "(S.getLangOpts().CPlusPlus ? ExpectedFunctionVariableOrClass : "
2077                                            "ExpectedVariableOrFunction)";
2078 
2079     case ObjCMethod | ObjCProp: return "ExpectedMethodOrProperty";
2080     case Field | Var: return "ExpectedFieldOrGlobalVar";
2081   }
2082 
2083   PrintFatalError(S.getLoc(),
2084                   "Could not deduce diagnostic argument for Attr subjects");
2085 
2086   return "";
2087 }
2088 
2089 static std::string GetSubjectWithSuffix(const Record *R) {
2090   std::string B = R->getName();
2091   if (B == "DeclBase")
2092     return "Decl";
2093   return B + "Decl";
2094 }
2095 static std::string GenerateCustomAppertainsTo(const Record &Subject,
2096                                               raw_ostream &OS) {
2097   std::string FnName = "is" + Subject.getName();
2098 
2099   // If this code has already been generated, simply return the previous
2100   // instance of it.
2101   static std::set<std::string> CustomSubjectSet;
2102   std::set<std::string>::iterator I = CustomSubjectSet.find(FnName);
2103   if (I != CustomSubjectSet.end())
2104     return *I;
2105 
2106   Record *Base = Subject.getValueAsDef("Base");
2107 
2108   // Not currently support custom subjects within custom subjects.
2109   if (Base->isSubClassOf("SubsetSubject")) {
2110     PrintFatalError(Subject.getLoc(),
2111                     "SubsetSubjects within SubsetSubjects is not supported");
2112     return "";
2113   }
2114 
2115   OS << "static bool " << FnName << "(const Decl *D) {\n";
2116   OS << "  if (const " << GetSubjectWithSuffix(Base) << " *S = dyn_cast<";
2117   OS << GetSubjectWithSuffix(Base);
2118   OS << ">(D))\n";
2119   OS << "    return " << Subject.getValueAsString("CheckCode") << ";\n";
2120   OS << "  return false;\n";
2121   OS << "}\n\n";
2122 
2123   CustomSubjectSet.insert(FnName);
2124   return FnName;
2125 }
2126 
2127 static std::string GenerateAppertainsTo(const Record &Attr, raw_ostream &OS) {
2128   // If the attribute does not contain a Subjects definition, then use the
2129   // default appertainsTo logic.
2130   if (Attr.isValueUnset("Subjects"))
2131     return "defaultAppertainsTo";
2132 
2133   const Record *SubjectObj = Attr.getValueAsDef("Subjects");
2134   std::vector<Record*> Subjects = SubjectObj->getValueAsListOfDefs("Subjects");
2135 
2136   // If the list of subjects is empty, it is assumed that the attribute
2137   // appertains to everything.
2138   if (Subjects.empty())
2139     return "defaultAppertainsTo";
2140 
2141   bool Warn = SubjectObj->getValueAsDef("Diag")->getValueAsBit("Warn");
2142 
2143   // Otherwise, generate an appertainsTo check specific to this attribute which
2144   // checks all of the given subjects against the Decl passed in. Return the
2145   // name of that check to the caller.
2146   std::string FnName = "check" + Attr.getName() + "AppertainsTo";
2147   std::stringstream SS;
2148   SS << "static bool " << FnName << "(Sema &S, const AttributeList &Attr, ";
2149   SS << "const Decl *D) {\n";
2150   SS << "  if (";
2151   for (auto I = Subjects.begin(), E = Subjects.end(); I != E; ++I) {
2152     // If the subject has custom code associated with it, generate a function
2153     // for it. The function cannot be inlined into this check (yet) because it
2154     // requires the subject to be of a specific type, and were that information
2155     // inlined here, it would not support an attribute with multiple custom
2156     // subjects.
2157     if ((*I)->isSubClassOf("SubsetSubject")) {
2158       SS << "!" << GenerateCustomAppertainsTo(**I, OS) << "(D)";
2159     } else {
2160       SS << "!isa<" << GetSubjectWithSuffix(*I) << ">(D)";
2161     }
2162 
2163     if (I + 1 != E)
2164       SS << " && ";
2165   }
2166   SS << ") {\n";
2167   SS << "    S.Diag(Attr.getLoc(), diag::";
2168   SS << (Warn ? "warn_attribute_wrong_decl_type" :
2169                "err_attribute_wrong_decl_type");
2170   SS << ")\n";
2171   SS << "      << Attr.getName() << ";
2172   SS << CalculateDiagnostic(*SubjectObj) << ";\n";
2173   SS << "    return false;\n";
2174   SS << "  }\n";
2175   SS << "  return true;\n";
2176   SS << "}\n\n";
2177 
2178   OS << SS.str();
2179   return FnName;
2180 }
2181 
2182 static void GenerateDefaultLangOptRequirements(raw_ostream &OS) {
2183   OS << "static bool defaultDiagnoseLangOpts(Sema &, ";
2184   OS << "const AttributeList &) {\n";
2185   OS << "  return true;\n";
2186   OS << "}\n\n";
2187 }
2188 
2189 static std::string GenerateLangOptRequirements(const Record &R,
2190                                                raw_ostream &OS) {
2191   // If the attribute has an empty or unset list of language requirements,
2192   // return the default handler.
2193   std::vector<Record *> LangOpts = R.getValueAsListOfDefs("LangOpts");
2194   if (LangOpts.empty())
2195     return "defaultDiagnoseLangOpts";
2196 
2197   // Generate the test condition, as well as a unique function name for the
2198   // diagnostic test. The list of options should usually be short (one or two
2199   // options), and the uniqueness isn't strictly necessary (it is just for
2200   // codegen efficiency).
2201   std::string FnName = "check", Test;
2202   for (auto I = LangOpts.begin(), E = LangOpts.end(); I != E; ++I) {
2203     std::string Part = (*I)->getValueAsString("Name");
2204     Test += "S.LangOpts." + Part;
2205     if (I + 1 != E)
2206       Test += " || ";
2207     FnName += Part;
2208   }
2209   FnName += "LangOpts";
2210 
2211   // If this code has already been generated, simply return the previous
2212   // instance of it.
2213   static std::set<std::string> CustomLangOptsSet;
2214   std::set<std::string>::iterator I = CustomLangOptsSet.find(FnName);
2215   if (I != CustomLangOptsSet.end())
2216     return *I;
2217 
2218   OS << "static bool " << FnName << "(Sema &S, const AttributeList &Attr) {\n";
2219   OS << "  if (" << Test << ")\n";
2220   OS << "    return true;\n\n";
2221   OS << "  S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) ";
2222   OS << "<< Attr.getName();\n";
2223   OS << "  return false;\n";
2224   OS << "}\n\n";
2225 
2226   CustomLangOptsSet.insert(FnName);
2227   return FnName;
2228 }
2229 
2230 static void GenerateDefaultTargetRequirements(raw_ostream &OS) {
2231   OS << "static bool defaultTargetRequirements(const llvm::Triple &) {\n";
2232   OS << "  return true;\n";
2233   OS << "}\n\n";
2234 }
2235 
2236 static std::string GenerateTargetRequirements(const Record &Attr,
2237                                               const ParsedAttrMap &Dupes,
2238                                               raw_ostream &OS) {
2239   // If the attribute is not a target specific attribute, return the default
2240   // target handler.
2241   if (!Attr.isSubClassOf("TargetSpecificAttr"))
2242     return "defaultTargetRequirements";
2243 
2244   // Get the list of architectures to be tested for.
2245   const Record *R = Attr.getValueAsDef("Target");
2246   std::vector<std::string> Arches = R->getValueAsListOfStrings("Arches");
2247   if (Arches.empty()) {
2248     PrintError(Attr.getLoc(), "Empty list of target architectures for a "
2249                               "target-specific attr");
2250     return "defaultTargetRequirements";
2251   }
2252 
2253   // If there are other attributes which share the same parsed attribute kind,
2254   // such as target-specific attributes with a shared spelling, collapse the
2255   // duplicate architectures. This is required because a shared target-specific
2256   // attribute has only one AttributeList::Kind enumeration value, but it
2257   // applies to multiple target architectures. In order for the attribute to be
2258   // considered valid, all of its architectures need to be included.
2259   if (!Attr.isValueUnset("ParseKind")) {
2260     std::string APK = Attr.getValueAsString("ParseKind");
2261     for (const auto &I : Dupes) {
2262       if (I.first == APK) {
2263         std::vector<std::string> DA = I.second->getValueAsDef("Target")
2264                                           ->getValueAsListOfStrings("Arches");
2265         std::copy(DA.begin(), DA.end(), std::back_inserter(Arches));
2266       }
2267     }
2268   }
2269 
2270   std::string FnName = "isTarget", Test = "(";
2271   for (auto I = Arches.begin(), E = Arches.end(); I != E; ++I) {
2272     std::string Part = *I;
2273     Test += "Arch == llvm::Triple::" + Part;
2274     if (I + 1 != E)
2275       Test += " || ";
2276     FnName += Part;
2277   }
2278   Test += ")";
2279 
2280   // If the target also requires OS testing, generate those tests as well.
2281   bool UsesOS = false;
2282   if (!R->isValueUnset("OSes")) {
2283     UsesOS = true;
2284 
2285     // We know that there was at least one arch test, so we need to and in the
2286     // OS tests.
2287     Test += " && (";
2288     std::vector<std::string> OSes = R->getValueAsListOfStrings("OSes");
2289     for (auto I = OSes.begin(), E = OSes.end(); I != E; ++I) {
2290       std::string Part = *I;
2291 
2292       Test += "OS == llvm::Triple::" + Part;
2293       if (I + 1 != E)
2294         Test += " || ";
2295       FnName += Part;
2296     }
2297     Test += ")";
2298   }
2299 
2300   // If this code has already been generated, simply return the previous
2301   // instance of it.
2302   static std::set<std::string> CustomTargetSet;
2303   std::set<std::string>::iterator I = CustomTargetSet.find(FnName);
2304   if (I != CustomTargetSet.end())
2305     return *I;
2306 
2307   OS << "static bool " << FnName << "(const llvm::Triple &T) {\n";
2308   OS << "  llvm::Triple::ArchType Arch = T.getArch();\n";
2309   if (UsesOS)
2310     OS << "  llvm::Triple::OSType OS = T.getOS();\n";
2311   OS << "  return " << Test << ";\n";
2312   OS << "}\n\n";
2313 
2314   CustomTargetSet.insert(FnName);
2315   return FnName;
2316 }
2317 
2318 static void GenerateDefaultSpellingIndexToSemanticSpelling(raw_ostream &OS) {
2319   OS << "static unsigned defaultSpellingIndexToSemanticSpelling("
2320      << "const AttributeList &Attr) {\n";
2321   OS << "  return UINT_MAX;\n";
2322   OS << "}\n\n";
2323 }
2324 
2325 static std::string GenerateSpellingIndexToSemanticSpelling(const Record &Attr,
2326                                                            raw_ostream &OS) {
2327   // If the attribute does not have a semantic form, we can bail out early.
2328   if (!Attr.getValueAsBit("ASTNode"))
2329     return "defaultSpellingIndexToSemanticSpelling";
2330 
2331   std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(Attr);
2332 
2333   // If there are zero or one spellings, or all of the spellings share the same
2334   // name, we can also bail out early.
2335   if (Spellings.size() <= 1 || SpellingNamesAreCommon(Spellings))
2336     return "defaultSpellingIndexToSemanticSpelling";
2337 
2338   // Generate the enumeration we will use for the mapping.
2339   SemanticSpellingMap SemanticToSyntacticMap;
2340   std::string Enum = CreateSemanticSpellings(Spellings, SemanticToSyntacticMap);
2341   std::string Name = Attr.getName() + "AttrSpellingMap";
2342 
2343   OS << "static unsigned " << Name << "(const AttributeList &Attr) {\n";
2344   OS << Enum;
2345   OS << "  unsigned Idx = Attr.getAttributeSpellingListIndex();\n";
2346   WriteSemanticSpellingSwitch("Idx", SemanticToSyntacticMap, OS);
2347   OS << "}\n\n";
2348 
2349   return Name;
2350 }
2351 
2352 static bool IsKnownToGCC(const Record &Attr) {
2353   // Look at the spellings for this subject; if there are any spellings which
2354   // claim to be known to GCC, the attribute is known to GCC.
2355   std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(Attr);
2356   for (const auto &I : Spellings) {
2357     if (I.knownToGCC())
2358       return true;
2359   }
2360   return false;
2361 }
2362 
2363 /// Emits the parsed attribute helpers
2364 void EmitClangAttrParsedAttrImpl(RecordKeeper &Records, raw_ostream &OS) {
2365   emitSourceFileHeader("Parsed attribute helpers", OS);
2366 
2367   // Get the list of parsed attributes, and accept the optional list of
2368   // duplicates due to the ParseKind.
2369   ParsedAttrMap Dupes;
2370   ParsedAttrMap Attrs = getParsedAttrList(Records, &Dupes);
2371 
2372   // Generate the default appertainsTo, target and language option diagnostic,
2373   // and spelling list index mapping methods.
2374   GenerateDefaultAppertainsTo(OS);
2375   GenerateDefaultLangOptRequirements(OS);
2376   GenerateDefaultTargetRequirements(OS);
2377   GenerateDefaultSpellingIndexToSemanticSpelling(OS);
2378 
2379   // Generate the appertainsTo diagnostic methods and write their names into
2380   // another mapping. At the same time, generate the AttrInfoMap object
2381   // contents. Due to the reliance on generated code, use separate streams so
2382   // that code will not be interleaved.
2383   std::stringstream SS;
2384   for (auto I = Attrs.begin(), E = Attrs.end(); I != E; ++I) {
2385     // TODO: If the attribute's kind appears in the list of duplicates, that is
2386     // because it is a target-specific attribute that appears multiple times.
2387     // It would be beneficial to test whether the duplicates are "similar
2388     // enough" to each other to not cause problems. For instance, check that
2389     // the spellings are identical, and custom parsing rules match, etc.
2390 
2391     // We need to generate struct instances based off ParsedAttrInfo from
2392     // AttributeList.cpp.
2393     SS << "  { ";
2394     emitArgInfo(*I->second, SS);
2395     SS << ", " << I->second->getValueAsBit("HasCustomParsing");
2396     SS << ", " << I->second->isSubClassOf("TargetSpecificAttr");
2397     SS << ", " << I->second->isSubClassOf("TypeAttr");
2398     SS << ", " << IsKnownToGCC(*I->second);
2399     SS << ", " << GenerateAppertainsTo(*I->second, OS);
2400     SS << ", " << GenerateLangOptRequirements(*I->second, OS);
2401     SS << ", " << GenerateTargetRequirements(*I->second, Dupes, OS);
2402     SS << ", " << GenerateSpellingIndexToSemanticSpelling(*I->second, OS);
2403     SS << " }";
2404 
2405     if (I + 1 != E)
2406       SS << ",";
2407 
2408     SS << "  // AT_" << I->first << "\n";
2409   }
2410 
2411   OS << "static const ParsedAttrInfo AttrInfoMap[AttributeList::UnknownAttribute + 1] = {\n";
2412   OS << SS.str();
2413   OS << "};\n\n";
2414 }
2415 
2416 // Emits the kind list of parsed attributes
2417 void EmitClangAttrParsedAttrKinds(RecordKeeper &Records, raw_ostream &OS) {
2418   emitSourceFileHeader("Attribute name matcher", OS);
2419 
2420   std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
2421   std::vector<StringMatcher::StringPair> GNU, Declspec, CXX11, Keywords;
2422   std::set<std::string> Seen;
2423   for (auto I : Attrs) {
2424     const Record &Attr = *I;
2425 
2426     bool SemaHandler = Attr.getValueAsBit("SemaHandler");
2427     bool Ignored = Attr.getValueAsBit("Ignored");
2428     if (SemaHandler || Ignored) {
2429       // Attribute spellings can be shared between target-specific attributes,
2430       // and can be shared between syntaxes for the same attribute. For
2431       // instance, an attribute can be spelled GNU<"interrupt"> for an ARM-
2432       // specific attribute, or MSP430-specific attribute. Additionally, an
2433       // attribute can be spelled GNU<"dllexport"> and Declspec<"dllexport">
2434       // for the same semantic attribute. Ultimately, we need to map each of
2435       // these to a single AttributeList::Kind value, but the StringMatcher
2436       // class cannot handle duplicate match strings. So we generate a list of
2437       // string to match based on the syntax, and emit multiple string matchers
2438       // depending on the syntax used.
2439       std::string AttrName;
2440       if (Attr.isSubClassOf("TargetSpecificAttr") &&
2441           !Attr.isValueUnset("ParseKind")) {
2442         AttrName = Attr.getValueAsString("ParseKind");
2443         if (Seen.find(AttrName) != Seen.end())
2444           continue;
2445         Seen.insert(AttrName);
2446       } else
2447         AttrName = NormalizeAttrName(StringRef(Attr.getName())).str();
2448 
2449       std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(Attr);
2450       for (const auto &S : Spellings) {
2451         std::string RawSpelling = S.name();
2452         std::vector<StringMatcher::StringPair> *Matches = 0;
2453         std::string Spelling, Variety = S.variety();
2454         if (Variety == "CXX11") {
2455           Matches = &CXX11;
2456           Spelling += S.nameSpace();
2457           Spelling += "::";
2458         } else if (Variety == "GNU")
2459           Matches = &GNU;
2460         else if (Variety == "Declspec")
2461           Matches = &Declspec;
2462         else if (Variety == "Keyword")
2463           Matches = &Keywords;
2464 
2465         assert(Matches && "Unsupported spelling variety found");
2466 
2467         Spelling += NormalizeAttrSpelling(RawSpelling);
2468         if (SemaHandler)
2469           Matches->push_back(StringMatcher::StringPair(Spelling,
2470                               "return AttributeList::AT_" + AttrName + ";"));
2471         else
2472           Matches->push_back(StringMatcher::StringPair(Spelling,
2473                               "return AttributeList::IgnoredAttribute;"));
2474       }
2475     }
2476   }
2477 
2478   OS << "static AttributeList::Kind getAttrKind(StringRef Name, ";
2479   OS << "AttributeList::Syntax Syntax) {\n";
2480   OS << "  if (AttributeList::AS_GNU == Syntax) {\n";
2481   StringMatcher("Name", GNU, OS).Emit();
2482   OS << "  } else if (AttributeList::AS_Declspec == Syntax) {\n";
2483   StringMatcher("Name", Declspec, OS).Emit();
2484   OS << "  } else if (AttributeList::AS_CXX11 == Syntax) {\n";
2485   StringMatcher("Name", CXX11, OS).Emit();
2486   OS << "  } else if (AttributeList::AS_Keyword == Syntax) {\n";
2487   StringMatcher("Name", Keywords, OS).Emit();
2488   OS << "  }\n";
2489   OS << "  return AttributeList::UnknownAttribute;\n"
2490      << "}\n";
2491 }
2492 
2493 // Emits the code to dump an attribute.
2494 void EmitClangAttrDump(RecordKeeper &Records, raw_ostream &OS) {
2495   emitSourceFileHeader("Attribute dumper", OS);
2496 
2497   OS <<
2498     "  switch (A->getKind()) {\n"
2499     "  default:\n"
2500     "    llvm_unreachable(\"Unknown attribute kind!\");\n"
2501     "    break;\n";
2502   std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr"), Args;
2503   for (auto I : Attrs) {
2504     const Record &R = *I;
2505     if (!R.getValueAsBit("ASTNode"))
2506       continue;
2507     OS << "  case attr::" << R.getName() << ": {\n";
2508 
2509     // If the attribute has a semantically-meaningful name (which is determined
2510     // by whether there is a Spelling enumeration for it), then write out the
2511     // spelling used for the attribute.
2512     std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(R);
2513     if (Spellings.size() > 1 && !SpellingNamesAreCommon(Spellings))
2514       OS << "    OS << \" \" << A->getSpelling();\n";
2515 
2516     Args = R.getValueAsListOfDefs("Args");
2517     if (!Args.empty()) {
2518       OS << "    const " << R.getName() << "Attr *SA = cast<" << R.getName()
2519          << "Attr>(A);\n";
2520       for (auto AI : Args)
2521         createArgument(*AI, R.getName())->writeDump(OS);
2522 
2523       // Code for detecting the last child.
2524       OS << "    bool OldMoreChildren = hasMoreChildren();\n";
2525       OS << "    bool MoreChildren;\n";
2526 
2527       for (auto AI = Args.begin(), AE = Args.end(); AI != AE; ++AI) {
2528         // More code for detecting the last child.
2529         OS << "    MoreChildren = OldMoreChildren";
2530         for (auto Next = AI + 1; Next != AE; ++Next) {
2531           OS << " || ";
2532           createArgument(**Next, R.getName())->writeHasChildren(OS);
2533         }
2534         OS << ";\n";
2535         OS << "    setMoreChildren(MoreChildren);\n";
2536 
2537         createArgument(**AI, R.getName())->writeDumpChildren(OS);
2538       }
2539 
2540       // Reset the last child.
2541       OS << "    setMoreChildren(OldMoreChildren);\n";
2542     }
2543     OS <<
2544       "    break;\n"
2545       "  }\n";
2546   }
2547   OS << "  }\n";
2548 }
2549 
2550 void EmitClangAttrParserStringSwitches(RecordKeeper &Records,
2551                                        raw_ostream &OS) {
2552   emitSourceFileHeader("Parser-related llvm::StringSwitch cases", OS);
2553   emitClangAttrArgContextList(Records, OS);
2554   emitClangAttrIdentifierArgList(Records, OS);
2555   emitClangAttrTypeArgList(Records, OS);
2556   emitClangAttrLateParsedList(Records, OS);
2557 }
2558 
2559 class DocumentationData {
2560 public:
2561   const Record *Documentation;
2562   const Record *Attribute;
2563 
2564   DocumentationData(const Record &Documentation, const Record &Attribute)
2565       : Documentation(&Documentation), Attribute(&Attribute) {}
2566 };
2567 
2568 static void WriteCategoryHeader(const Record *DocCategory,
2569                                 raw_ostream &OS) {
2570   const std::string &Name = DocCategory->getValueAsString("Name");
2571   OS << Name << "\n" << std::string(Name.length(), '=') << "\n";
2572 
2573   // If there is content, print that as well.
2574   std::string ContentStr = DocCategory->getValueAsString("Content");
2575   if (!ContentStr.empty()) {
2576     // Trim leading and trailing newlines and spaces.
2577     StringRef Content(ContentStr);
2578     while (Content.startswith("\r") || Content.startswith("\n") ||
2579            Content.startswith(" ") || Content.startswith("\t"))
2580            Content = Content.substr(1);
2581     while (Content.endswith("\r") || Content.endswith("\n") ||
2582            Content.endswith(" ") || Content.endswith("\t"))
2583            Content = Content.substr(0, Content.size() - 1);
2584     OS << Content;
2585   }
2586   OS << "\n\n";
2587 }
2588 
2589 enum SpellingKind {
2590   GNU = 1 << 0,
2591   CXX11 = 1 << 1,
2592   Declspec = 1 << 2,
2593   Keyword = 1 << 3
2594 };
2595 
2596 static void WriteDocumentation(const DocumentationData &Doc,
2597                                raw_ostream &OS) {
2598   // FIXME: there is no way to have a per-spelling category for the attribute
2599   // documentation. This may not be a limiting factor since the spellings
2600   // should generally be consistently applied across the category.
2601 
2602   std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(*Doc.Attribute);
2603 
2604   // Determine the heading to be used for this attribute.
2605   std::string Heading = Doc.Documentation->getValueAsString("Heading");
2606   bool CustomHeading = !Heading.empty();
2607   if (Heading.empty()) {
2608     // If there's only one spelling, we can simply use that.
2609     if (Spellings.size() == 1)
2610       Heading = Spellings.begin()->name();
2611     else {
2612       std::set<std::string> Uniques;
2613       for (auto I = Spellings.begin(), E = Spellings.end();
2614            I != E && Uniques.size() <= 1; ++I) {
2615         std::string Spelling = NormalizeNameForSpellingComparison(I->name());
2616         Uniques.insert(Spelling);
2617       }
2618       // If the semantic map has only one spelling, that is sufficient for our
2619       // needs.
2620       if (Uniques.size() == 1)
2621         Heading = *Uniques.begin();
2622     }
2623   }
2624 
2625   // If the heading is still empty, it is an error.
2626   if (Heading.empty())
2627     PrintFatalError(Doc.Attribute->getLoc(),
2628                     "This attribute requires a heading to be specified");
2629 
2630   // Gather a list of unique spellings; this is not the same as the semantic
2631   // spelling for the attribute. Variations in underscores and other non-
2632   // semantic characters are still acceptable.
2633   std::vector<std::string> Names;
2634 
2635   unsigned SupportedSpellings = 0;
2636   for (const auto &I : Spellings) {
2637     SpellingKind Kind = StringSwitch<SpellingKind>(I.variety())
2638       .Case("GNU", GNU)
2639       .Case("CXX11", CXX11)
2640       .Case("Declspec", Declspec)
2641       .Case("Keyword", Keyword);
2642 
2643     // Mask in the supported spelling.
2644     SupportedSpellings |= Kind;
2645 
2646     std::string Name;
2647     if (Kind == CXX11 && !I.nameSpace().empty())
2648       Name = I.nameSpace() + "::";
2649     Name += I.name();
2650 
2651     // If this name is the same as the heading, do not add it.
2652     if (Name != Heading)
2653       Names.push_back(Name);
2654   }
2655 
2656   // Print out the heading for the attribute. If there are alternate spellings,
2657   // then display those after the heading.
2658   if (!CustomHeading && !Names.empty()) {
2659     Heading += " (";
2660     for (auto I = Names.begin(), E = Names.end(); I != E; ++I) {
2661       if (I != Names.begin())
2662         Heading += ", ";
2663       Heading += *I;
2664     }
2665     Heading += ")";
2666   }
2667   OS << Heading << "\n" << std::string(Heading.length(), '-') << "\n";
2668 
2669   if (!SupportedSpellings)
2670     PrintFatalError(Doc.Attribute->getLoc(),
2671                     "Attribute has no supported spellings; cannot be "
2672                     "documented");
2673 
2674   // List what spelling syntaxes the attribute supports.
2675   OS << ".. csv-table:: Supported Syntaxes\n";
2676   OS << "   :header: \"GNU\", \"C++11\", \"__declspec\", \"Keyword\"\n\n";
2677   OS << "   \"";
2678   if (SupportedSpellings & GNU) OS << "X";
2679   OS << "\",\"";
2680   if (SupportedSpellings & CXX11) OS << "X";
2681   OS << "\",\"";
2682   if (SupportedSpellings & Declspec) OS << "X";
2683   OS << "\",\"";
2684   if (SupportedSpellings & Keyword) OS << "X";
2685   OS << "\"\n\n";
2686 
2687   // If the attribute is deprecated, print a message about it, and possibly
2688   // provide a replacement attribute.
2689   if (!Doc.Documentation->isValueUnset("Deprecated")) {
2690     OS << "This attribute has been deprecated, and may be removed in a future "
2691        << "version of Clang.";
2692     const Record &Deprecated = *Doc.Documentation->getValueAsDef("Deprecated");
2693     std::string Replacement = Deprecated.getValueAsString("Replacement");
2694     if (!Replacement.empty())
2695       OS << "  This attribute has been superseded by ``"
2696          << Replacement << "``.";
2697     OS << "\n\n";
2698   }
2699 
2700   std::string ContentStr = Doc.Documentation->getValueAsString("Content");
2701   // Trim leading and trailing newlines and spaces.
2702   StringRef Content(ContentStr);
2703   while (Content.startswith("\r") || Content.startswith("\n") ||
2704          Content.startswith(" ") || Content.startswith("\t"))
2705     Content = Content.substr(1);
2706   while (Content.endswith("\r") || Content.endswith("\n") ||
2707          Content.endswith(" ") || Content.endswith("\t"))
2708     Content = Content.substr(0, Content.size() - 1);
2709   OS << Content;
2710 
2711   OS << "\n\n\n";
2712 }
2713 
2714 void EmitClangAttrDocs(RecordKeeper &Records, raw_ostream &OS) {
2715   // Get the documentation introduction paragraph.
2716   const Record *Documentation = Records.getDef("GlobalDocumentation");
2717   if (!Documentation) {
2718     PrintFatalError("The Documentation top-level definition is missing, "
2719                     "no documentation will be generated.");
2720     return;
2721   }
2722 
2723   OS << Documentation->getValueAsString("Intro") << "\n";
2724 
2725   // Gather the Documentation lists from each of the attributes, based on the
2726   // category provided.
2727   std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
2728   std::map<const Record *, std::vector<DocumentationData>> SplitDocs;
2729   for (auto I : Attrs) {
2730     const Record &Attr = *I;
2731     std::vector<Record *> Docs = Attr.getValueAsListOfDefs("Documentation");
2732     for (auto DI : Docs) {
2733       const Record &Doc = *DI;
2734       const Record *Category = Doc.getValueAsDef("Category");
2735       // If the category is "undocumented", then there cannot be any other
2736       // documentation categories (otherwise, the attribute would become
2737       // documented).
2738       std::string Cat = Category->getValueAsString("Name");
2739       bool Undocumented = Cat == "Undocumented";
2740       if (Undocumented && Docs.size() > 1)
2741         PrintFatalError(Doc.getLoc(),
2742                         "Attribute is \"Undocumented\", but has multiple "
2743                         "documentation categories");
2744 
2745       if (!Undocumented)
2746         SplitDocs[Category].push_back(DocumentationData(Doc, Attr));
2747     }
2748   }
2749 
2750   // Having split the attributes out based on what documentation goes where,
2751   // we can begin to generate sections of documentation.
2752   for (const auto &I : SplitDocs) {
2753     WriteCategoryHeader(I.first, OS);
2754 
2755     // Walk over each of the attributes in the category and write out their
2756     // documentation.
2757     for (const auto &Doc : I.second)
2758       WriteDocumentation(Doc, OS);
2759   }
2760 }
2761 
2762 } // end namespace clang
2763