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