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