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