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