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