1 //===- ClangAttrEmitter.cpp - Generate Clang attribute handling =-*- C++ -*--=//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // These tablegen backends emit Clang attribute processing code
12 //===----------------------------------------------------------------------===//
14 #include "llvm/ADT/ArrayRef.h"
15 #include "llvm/ADT/DenseMap.h"
16 #include "llvm/ADT/DenseSet.h"
17 #include "llvm/ADT/STLExtras.h"
18 #include "llvm/ADT/SmallString.h"
19 #include "llvm/ADT/StringExtras.h"
20 #include "llvm/ADT/StringRef.h"
21 #include "llvm/ADT/StringSet.h"
22 #include "llvm/ADT/StringSwitch.h"
23 #include "llvm/ADT/iterator_range.h"
24 #include "llvm/Support/ErrorHandling.h"
25 #include "llvm/Support/raw_ostream.h"
26 #include "llvm/TableGen/Error.h"
27 #include "llvm/TableGen/Record.h"
28 #include "llvm/TableGen/StringMatcher.h"
29 #include "llvm/TableGen/TableGenBackend.h"
47 class FlattenedSpelling {
52 FlattenedSpelling(const std::string &Variety, const std::string &Name,
53 const std::string &Namespace, bool KnownToGCC) :
54 V(Variety), N(Name), NS(Namespace), K(KnownToGCC) {}
55 explicit FlattenedSpelling(const Record &Spelling) :
56 V(Spelling.getValueAsString("Variety")),
57 N(Spelling.getValueAsString("Name")) {
59 assert(V != "GCC" && V != "Clang" &&
60 "Given a GCC spelling, which means this hasn't been flattened!");
61 if (V == "CXX11" || V == "C2x" || V == "Pragma")
62 NS = Spelling.getValueAsString("Namespace");
64 K = Spelling.getValueAsBitOrUnset("KnownToGCC", Unset);
67 const std::string &variety() const { return V; }
68 const std::string &name() const { return N; }
69 const std::string &nameSpace() const { return NS; }
70 bool knownToGCC() const { return K; }
73 } // end anonymous namespace
75 static std::vector<FlattenedSpelling>
76 GetFlattenedSpellings(const Record &Attr) {
77 std::vector<Record *> Spellings = Attr.getValueAsListOfDefs("Spellings");
78 std::vector<FlattenedSpelling> Ret;
80 for (const auto &Spelling : Spellings) {
81 StringRef Variety = Spelling->getValueAsString("Variety");
82 StringRef Name = Spelling->getValueAsString("Name");
83 if (Variety == "GCC") {
84 // Gin up two new spelling objects to add into the list.
85 Ret.emplace_back("GNU", Name, "", true);
86 Ret.emplace_back("CXX11", Name, "gnu", true);
87 } else if (Variety == "Clang") {
88 Ret.emplace_back("GNU", Name, "", false);
89 Ret.emplace_back("CXX11", Name, "clang", false);
91 Ret.push_back(FlattenedSpelling(*Spelling));
97 static std::string ReadPCHRecord(StringRef type) {
98 return StringSwitch<std::string>(type)
99 .EndsWith("Decl *", "Record.GetLocalDeclAs<"
100 + std::string(type, 0, type.size()-1) + ">(Record.readInt())")
101 .Case("TypeSourceInfo *", "Record.getTypeSourceInfo()")
102 .Case("Expr *", "Record.readExpr()")
103 .Case("IdentifierInfo *", "Record.getIdentifierInfo()")
104 .Case("StringRef", "Record.readString()")
105 .Default("Record.readInt()");
108 // Get a type that is suitable for storing an object of the specified type.
109 static StringRef getStorageType(StringRef type) {
110 return StringSwitch<StringRef>(type)
111 .Case("StringRef", "std::string")
115 // Assumes that the way to get the value is SA->getname()
116 static std::string WritePCHRecord(StringRef type, StringRef name) {
117 return "Record." + StringSwitch<std::string>(type)
118 .EndsWith("Decl *", "AddDeclRef(" + std::string(name) + ");\n")
119 .Case("TypeSourceInfo *", "AddTypeSourceInfo(" + std::string(name) + ");\n")
120 .Case("Expr *", "AddStmt(" + std::string(name) + ");\n")
121 .Case("IdentifierInfo *", "AddIdentifierRef(" + std::string(name) + ");\n")
122 .Case("StringRef", "AddString(" + std::string(name) + ");\n")
123 .Default("push_back(" + std::string(name) + ");\n");
126 // Normalize attribute name by removing leading and trailing
127 // underscores. For example, __foo, foo__, __foo__ would
129 static StringRef NormalizeAttrName(StringRef AttrName) {
130 AttrName.consume_front("__");
131 AttrName.consume_back("__");
135 // Normalize the name by removing any and all leading and trailing underscores.
136 // This is different from NormalizeAttrName in that it also handles names like
137 // _pascal and __pascal.
138 static StringRef NormalizeNameForSpellingComparison(StringRef Name) {
139 return Name.trim("_");
142 // Normalize the spelling of a GNU attribute (i.e. "x" in "__attribute__((x))"),
143 // removing "__" if it appears at the beginning and end of the attribute's name.
144 static StringRef NormalizeGNUAttrSpelling(StringRef AttrSpelling) {
145 if (AttrSpelling.startswith("__") && AttrSpelling.endswith("__")) {
146 AttrSpelling = AttrSpelling.substr(2, AttrSpelling.size() - 4);
152 typedef std::vector<std::pair<std::string, const Record *>> ParsedAttrMap;
154 static ParsedAttrMap getParsedAttrList(const RecordKeeper &Records,
155 ParsedAttrMap *Dupes = nullptr) {
156 std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
157 std::set<std::string> Seen;
159 for (const auto *Attr : Attrs) {
160 if (Attr->getValueAsBit("SemaHandler")) {
162 if (Attr->isSubClassOf("TargetSpecificAttr") &&
163 !Attr->isValueUnset("ParseKind")) {
164 AN = Attr->getValueAsString("ParseKind");
166 // If this attribute has already been handled, it does not need to be
168 if (Seen.find(AN) != Seen.end()) {
170 Dupes->push_back(std::make_pair(AN, Attr));
175 AN = NormalizeAttrName(Attr->getName()).str();
177 R.push_back(std::make_pair(AN, Attr));
186 std::string lowerName, upperName;
192 Argument(const Record &Arg, StringRef Attr)
193 : lowerName(Arg.getValueAsString("Name")), upperName(lowerName),
194 attrName(Attr), isOpt(false), Fake(false) {
195 if (!lowerName.empty()) {
196 lowerName[0] = std::tolower(lowerName[0]);
197 upperName[0] = std::toupper(upperName[0]);
199 // Work around MinGW's macro definition of 'interface' to 'struct'. We
200 // have an attribute argument called 'Interface', so only the lower case
201 // name conflicts with the macro definition.
202 if (lowerName == "interface")
203 lowerName = "interface_";
205 virtual ~Argument() = default;
207 StringRef getLowerName() const { return lowerName; }
208 StringRef getUpperName() const { return upperName; }
209 StringRef getAttrName() const { return attrName; }
211 bool isOptional() const { return isOpt; }
212 void setOptional(bool set) { isOpt = set; }
214 bool isFake() const { return Fake; }
215 void setFake(bool fake) { Fake = fake; }
217 // These functions print the argument contents formatted in different ways.
218 virtual void writeAccessors(raw_ostream &OS) const = 0;
219 virtual void writeAccessorDefinitions(raw_ostream &OS) const {}
220 virtual void writeASTVisitorTraversal(raw_ostream &OS) const {}
221 virtual void writeCloneArgs(raw_ostream &OS) const = 0;
222 virtual void writeTemplateInstantiationArgs(raw_ostream &OS) const = 0;
223 virtual void writeTemplateInstantiation(raw_ostream &OS) const {}
224 virtual void writeCtorBody(raw_ostream &OS) const {}
225 virtual void writeCtorInitializers(raw_ostream &OS) const = 0;
226 virtual void writeCtorDefaultInitializers(raw_ostream &OS) const = 0;
227 virtual void writeCtorParameters(raw_ostream &OS) const = 0;
228 virtual void writeDeclarations(raw_ostream &OS) const = 0;
229 virtual void writePCHReadArgs(raw_ostream &OS) const = 0;
230 virtual void writePCHReadDecls(raw_ostream &OS) const = 0;
231 virtual void writePCHWrite(raw_ostream &OS) const = 0;
232 virtual void writeValue(raw_ostream &OS) const = 0;
233 virtual void writeDump(raw_ostream &OS) const = 0;
234 virtual void writeDumpChildren(raw_ostream &OS) const {}
235 virtual void writeHasChildren(raw_ostream &OS) const { OS << "false"; }
237 virtual bool isEnumArg() const { return false; }
238 virtual bool isVariadicEnumArg() const { return false; }
239 virtual bool isVariadic() const { return false; }
241 virtual void writeImplicitCtorArgs(raw_ostream &OS) const {
242 OS << getUpperName();
246 class SimpleArgument : public Argument {
250 SimpleArgument(const Record &Arg, StringRef Attr, std::string T)
251 : Argument(Arg, Attr), type(std::move(T)) {}
253 std::string getType() const { return type; }
255 void writeAccessors(raw_ostream &OS) const override {
256 OS << " " << type << " get" << getUpperName() << "() const {\n";
257 OS << " return " << getLowerName() << ";\n";
261 void writeCloneArgs(raw_ostream &OS) const override {
262 OS << getLowerName();
265 void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
266 OS << "A->get" << getUpperName() << "()";
269 void writeCtorInitializers(raw_ostream &OS) const override {
270 OS << getLowerName() << "(" << getUpperName() << ")";
273 void writeCtorDefaultInitializers(raw_ostream &OS) const override {
274 OS << getLowerName() << "()";
277 void writeCtorParameters(raw_ostream &OS) const override {
278 OS << type << " " << getUpperName();
281 void writeDeclarations(raw_ostream &OS) const override {
282 OS << type << " " << getLowerName() << ";";
285 void writePCHReadDecls(raw_ostream &OS) const override {
286 std::string read = ReadPCHRecord(type);
287 OS << " " << type << " " << getLowerName() << " = " << read << ";\n";
290 void writePCHReadArgs(raw_ostream &OS) const override {
291 OS << getLowerName();
294 void writePCHWrite(raw_ostream &OS) const override {
295 OS << " " << WritePCHRecord(type, "SA->get" +
296 std::string(getUpperName()) + "()");
299 void writeValue(raw_ostream &OS) const override {
300 if (type == "FunctionDecl *") {
301 OS << "\" << get" << getUpperName()
302 << "()->getNameInfo().getAsString() << \"";
303 } else if (type == "IdentifierInfo *") {
306 OS << " if (get" << getUpperName() << "()) ";
309 OS << "OS << get" << getUpperName() << "()->getName();\n";
311 } else if (type == "TypeSourceInfo *") {
312 OS << "\" << get" << getUpperName() << "().getAsString() << \"";
314 OS << "\" << get" << getUpperName() << "() << \"";
318 void writeDump(raw_ostream &OS) const override {
319 if (type == "FunctionDecl *" || type == "NamedDecl *") {
320 OS << " OS << \" \";\n";
321 OS << " dumpBareDeclRef(SA->get" << getUpperName() << "());\n";
322 } else if (type == "IdentifierInfo *") {
324 OS << " if (SA->get" << getUpperName() << "())\n ";
325 OS << " OS << \" \" << SA->get" << getUpperName()
326 << "()->getName();\n";
327 } else if (type == "TypeSourceInfo *") {
328 OS << " OS << \" \" << SA->get" << getUpperName()
329 << "().getAsString();\n";
330 } else if (type == "bool") {
331 OS << " if (SA->get" << getUpperName() << "()) OS << \" "
332 << getUpperName() << "\";\n";
333 } else if (type == "int" || type == "unsigned") {
334 OS << " OS << \" \" << SA->get" << getUpperName() << "();\n";
336 llvm_unreachable("Unknown SimpleArgument type!");
341 class DefaultSimpleArgument : public SimpleArgument {
345 DefaultSimpleArgument(const Record &Arg, StringRef Attr,
346 std::string T, int64_t Default)
347 : SimpleArgument(Arg, Attr, T), Default(Default) {}
349 void writeAccessors(raw_ostream &OS) const override {
350 SimpleArgument::writeAccessors(OS);
352 OS << "\n\n static const " << getType() << " Default" << getUpperName()
354 if (getType() == "bool")
355 OS << (Default != 0 ? "true" : "false");
362 class StringArgument : public Argument {
364 StringArgument(const Record &Arg, StringRef Attr)
365 : Argument(Arg, Attr)
368 void writeAccessors(raw_ostream &OS) const override {
369 OS << " llvm::StringRef get" << getUpperName() << "() const {\n";
370 OS << " return llvm::StringRef(" << getLowerName() << ", "
371 << getLowerName() << "Length);\n";
373 OS << " unsigned get" << getUpperName() << "Length() const {\n";
374 OS << " return " << getLowerName() << "Length;\n";
376 OS << " void set" << getUpperName()
377 << "(ASTContext &C, llvm::StringRef S) {\n";
378 OS << " " << getLowerName() << "Length = S.size();\n";
379 OS << " this->" << getLowerName() << " = new (C, 1) char ["
380 << getLowerName() << "Length];\n";
381 OS << " if (!S.empty())\n";
382 OS << " std::memcpy(this->" << getLowerName() << ", S.data(), "
383 << getLowerName() << "Length);\n";
387 void writeCloneArgs(raw_ostream &OS) const override {
388 OS << "get" << getUpperName() << "()";
391 void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
392 OS << "A->get" << getUpperName() << "()";
395 void writeCtorBody(raw_ostream &OS) const override {
396 OS << " if (!" << getUpperName() << ".empty())\n";
397 OS << " std::memcpy(" << getLowerName() << ", " << getUpperName()
398 << ".data(), " << getLowerName() << "Length);\n";
401 void writeCtorInitializers(raw_ostream &OS) const override {
402 OS << getLowerName() << "Length(" << getUpperName() << ".size()),"
403 << getLowerName() << "(new (Ctx, 1) char[" << getLowerName()
407 void writeCtorDefaultInitializers(raw_ostream &OS) const override {
408 OS << getLowerName() << "Length(0)," << getLowerName() << "(nullptr)";
411 void writeCtorParameters(raw_ostream &OS) const override {
412 OS << "llvm::StringRef " << getUpperName();
415 void writeDeclarations(raw_ostream &OS) const override {
416 OS << "unsigned " << getLowerName() << "Length;\n";
417 OS << "char *" << getLowerName() << ";";
420 void writePCHReadDecls(raw_ostream &OS) const override {
421 OS << " std::string " << getLowerName()
422 << "= Record.readString();\n";
425 void writePCHReadArgs(raw_ostream &OS) const override {
426 OS << getLowerName();
429 void writePCHWrite(raw_ostream &OS) const override {
430 OS << " Record.AddString(SA->get" << getUpperName() << "());\n";
433 void writeValue(raw_ostream &OS) const override {
434 OS << "\\\"\" << get" << getUpperName() << "() << \"\\\"";
437 void writeDump(raw_ostream &OS) const override {
438 OS << " OS << \" \\\"\" << SA->get" << getUpperName()
439 << "() << \"\\\"\";\n";
443 class AlignedArgument : public Argument {
445 AlignedArgument(const Record &Arg, StringRef Attr)
446 : Argument(Arg, Attr)
449 void writeAccessors(raw_ostream &OS) const override {
450 OS << " bool is" << getUpperName() << "Dependent() const;\n";
452 OS << " unsigned get" << getUpperName() << "(ASTContext &Ctx) const;\n";
454 OS << " bool is" << getUpperName() << "Expr() const {\n";
455 OS << " return is" << getLowerName() << "Expr;\n";
458 OS << " Expr *get" << getUpperName() << "Expr() const {\n";
459 OS << " assert(is" << getLowerName() << "Expr);\n";
460 OS << " return " << getLowerName() << "Expr;\n";
463 OS << " TypeSourceInfo *get" << getUpperName() << "Type() const {\n";
464 OS << " assert(!is" << getLowerName() << "Expr);\n";
465 OS << " return " << getLowerName() << "Type;\n";
469 void writeAccessorDefinitions(raw_ostream &OS) const override {
470 OS << "bool " << getAttrName() << "Attr::is" << getUpperName()
471 << "Dependent() const {\n";
472 OS << " if (is" << getLowerName() << "Expr)\n";
473 OS << " return " << getLowerName() << "Expr && (" << getLowerName()
474 << "Expr->isValueDependent() || " << getLowerName()
475 << "Expr->isTypeDependent());\n";
477 OS << " return " << getLowerName()
478 << "Type->getType()->isDependentType();\n";
481 // FIXME: Do not do the calculation here
482 // FIXME: Handle types correctly
483 // A null pointer means maximum alignment
484 OS << "unsigned " << getAttrName() << "Attr::get" << getUpperName()
485 << "(ASTContext &Ctx) const {\n";
486 OS << " assert(!is" << getUpperName() << "Dependent());\n";
487 OS << " if (is" << getLowerName() << "Expr)\n";
488 OS << " return " << getLowerName() << "Expr ? " << getLowerName()
489 << "Expr->EvaluateKnownConstInt(Ctx).getZExtValue()"
490 << " * Ctx.getCharWidth() : "
491 << "Ctx.getTargetDefaultAlignForAttributeAligned();\n";
493 OS << " return 0; // FIXME\n";
497 void writeASTVisitorTraversal(raw_ostream &OS) const override {
498 StringRef Name = getUpperName();
499 OS << " if (A->is" << Name << "Expr()) {\n"
500 << " if (!getDerived().TraverseStmt(A->get" << Name << "Expr()))\n"
501 << " return false;\n"
502 << " } else if (auto *TSI = A->get" << Name << "Type()) {\n"
503 << " if (!getDerived().TraverseTypeLoc(TSI->getTypeLoc()))\n"
504 << " return false;\n"
508 void writeCloneArgs(raw_ostream &OS) const override {
509 OS << "is" << getLowerName() << "Expr, is" << getLowerName()
510 << "Expr ? static_cast<void*>(" << getLowerName()
511 << "Expr) : " << getLowerName()
515 void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
516 // FIXME: move the definition in Sema::InstantiateAttrs to here.
517 // In the meantime, aligned attributes are cloned.
520 void writeCtorBody(raw_ostream &OS) const override {
521 OS << " if (is" << getLowerName() << "Expr)\n";
522 OS << " " << getLowerName() << "Expr = reinterpret_cast<Expr *>("
523 << getUpperName() << ");\n";
525 OS << " " << getLowerName()
526 << "Type = reinterpret_cast<TypeSourceInfo *>(" << getUpperName()
530 void writeCtorInitializers(raw_ostream &OS) const override {
531 OS << "is" << getLowerName() << "Expr(Is" << getUpperName() << "Expr)";
534 void writeCtorDefaultInitializers(raw_ostream &OS) const override {
535 OS << "is" << getLowerName() << "Expr(false)";
538 void writeCtorParameters(raw_ostream &OS) const override {
539 OS << "bool Is" << getUpperName() << "Expr, void *" << getUpperName();
542 void writeImplicitCtorArgs(raw_ostream &OS) const override {
543 OS << "Is" << getUpperName() << "Expr, " << getUpperName();
546 void writeDeclarations(raw_ostream &OS) const override {
547 OS << "bool is" << getLowerName() << "Expr;\n";
549 OS << "Expr *" << getLowerName() << "Expr;\n";
550 OS << "TypeSourceInfo *" << getLowerName() << "Type;\n";
554 void writePCHReadArgs(raw_ostream &OS) const override {
555 OS << "is" << getLowerName() << "Expr, " << getLowerName() << "Ptr";
558 void writePCHReadDecls(raw_ostream &OS) const override {
559 OS << " bool is" << getLowerName() << "Expr = Record.readInt();\n";
560 OS << " void *" << getLowerName() << "Ptr;\n";
561 OS << " if (is" << getLowerName() << "Expr)\n";
562 OS << " " << getLowerName() << "Ptr = Record.readExpr();\n";
564 OS << " " << getLowerName()
565 << "Ptr = Record.getTypeSourceInfo();\n";
568 void writePCHWrite(raw_ostream &OS) const override {
569 OS << " Record.push_back(SA->is" << getUpperName() << "Expr());\n";
570 OS << " if (SA->is" << getUpperName() << "Expr())\n";
571 OS << " Record.AddStmt(SA->get" << getUpperName() << "Expr());\n";
573 OS << " Record.AddTypeSourceInfo(SA->get" << getUpperName()
577 void writeValue(raw_ostream &OS) const override {
579 // The aligned attribute argument expression is optional.
580 OS << " if (is" << getLowerName() << "Expr && "
581 << getLowerName() << "Expr)\n";
582 OS << " " << getLowerName() << "Expr->printPretty(OS, nullptr, Policy);\n";
586 void writeDump(raw_ostream &OS) const override {}
588 void writeDumpChildren(raw_ostream &OS) const override {
589 OS << " if (SA->is" << getUpperName() << "Expr())\n";
590 OS << " dumpStmt(SA->get" << getUpperName() << "Expr());\n";
592 OS << " dumpType(SA->get" << getUpperName()
593 << "Type()->getType());\n";
596 void writeHasChildren(raw_ostream &OS) const override {
597 OS << "SA->is" << getUpperName() << "Expr()";
601 class VariadicArgument : public Argument {
602 std::string Type, ArgName, ArgSizeName, RangeName;
605 // Assumed to receive a parameter: raw_ostream OS.
606 virtual void writeValueImpl(raw_ostream &OS) const {
607 OS << " OS << Val;\n";
611 VariadicArgument(const Record &Arg, StringRef Attr, std::string T)
612 : Argument(Arg, Attr), Type(std::move(T)),
613 ArgName(getLowerName().str() + "_"), ArgSizeName(ArgName + "Size"),
614 RangeName(getLowerName()) {}
616 const std::string &getType() const { return Type; }
617 const std::string &getArgName() const { return ArgName; }
618 const std::string &getArgSizeName() const { return ArgSizeName; }
619 bool isVariadic() const override { return true; }
621 void writeAccessors(raw_ostream &OS) const override {
622 std::string IteratorType = getLowerName().str() + "_iterator";
623 std::string BeginFn = getLowerName().str() + "_begin()";
624 std::string EndFn = getLowerName().str() + "_end()";
626 OS << " typedef " << Type << "* " << IteratorType << ";\n";
627 OS << " " << IteratorType << " " << BeginFn << " const {"
628 << " return " << ArgName << "; }\n";
629 OS << " " << IteratorType << " " << EndFn << " const {"
630 << " return " << ArgName << " + " << ArgSizeName << "; }\n";
631 OS << " unsigned " << getLowerName() << "_size() const {"
632 << " return " << ArgSizeName << "; }\n";
633 OS << " llvm::iterator_range<" << IteratorType << "> " << RangeName
634 << "() const { return llvm::make_range(" << BeginFn << ", " << EndFn
638 void writeCloneArgs(raw_ostream &OS) const override {
639 OS << ArgName << ", " << ArgSizeName;
642 void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
643 // This isn't elegant, but we have to go through public methods...
644 OS << "A->" << getLowerName() << "_begin(), "
645 << "A->" << getLowerName() << "_size()";
648 void writeASTVisitorTraversal(raw_ostream &OS) const override {
649 // FIXME: Traverse the elements.
652 void writeCtorBody(raw_ostream &OS) const override {
653 OS << " std::copy(" << getUpperName() << ", " << getUpperName()
654 << " + " << ArgSizeName << ", " << ArgName << ");\n";
657 void writeCtorInitializers(raw_ostream &OS) const override {
658 OS << ArgSizeName << "(" << getUpperName() << "Size), "
659 << ArgName << "(new (Ctx, 16) " << getType() << "["
660 << ArgSizeName << "])";
663 void writeCtorDefaultInitializers(raw_ostream &OS) const override {
664 OS << ArgSizeName << "(0), " << ArgName << "(nullptr)";
667 void writeCtorParameters(raw_ostream &OS) const override {
668 OS << getType() << " *" << getUpperName() << ", unsigned "
669 << getUpperName() << "Size";
672 void writeImplicitCtorArgs(raw_ostream &OS) const override {
673 OS << getUpperName() << ", " << getUpperName() << "Size";
676 void writeDeclarations(raw_ostream &OS) const override {
677 OS << " unsigned " << ArgSizeName << ";\n";
678 OS << " " << getType() << " *" << ArgName << ";";
681 void writePCHReadDecls(raw_ostream &OS) const override {
682 OS << " unsigned " << getLowerName() << "Size = Record.readInt();\n";
683 OS << " SmallVector<" << getType() << ", 4> "
684 << getLowerName() << ";\n";
685 OS << " " << getLowerName() << ".reserve(" << getLowerName()
688 // If we can't store the values in the current type (if it's something
689 // like StringRef), store them in a different type and convert the
690 // container afterwards.
691 std::string StorageType = getStorageType(getType());
692 std::string StorageName = getLowerName();
693 if (StorageType != getType()) {
694 StorageName += "Storage";
695 OS << " SmallVector<" << StorageType << ", 4> "
696 << StorageName << ";\n";
697 OS << " " << StorageName << ".reserve(" << getLowerName()
701 OS << " for (unsigned i = 0; i != " << getLowerName() << "Size; ++i)\n";
702 std::string read = ReadPCHRecord(Type);
703 OS << " " << StorageName << ".push_back(" << read << ");\n";
705 if (StorageType != getType()) {
706 OS << " for (unsigned i = 0; i != " << getLowerName() << "Size; ++i)\n";
707 OS << " " << getLowerName() << ".push_back("
708 << StorageName << "[i]);\n";
712 void writePCHReadArgs(raw_ostream &OS) const override {
713 OS << getLowerName() << ".data(), " << getLowerName() << "Size";
716 void writePCHWrite(raw_ostream &OS) const override {
717 OS << " Record.push_back(SA->" << getLowerName() << "_size());\n";
718 OS << " for (auto &Val : SA->" << RangeName << "())\n";
719 OS << " " << WritePCHRecord(Type, "Val");
722 void writeValue(raw_ostream &OS) const override {
724 OS << " bool isFirst = true;\n"
725 << " for (const auto &Val : " << RangeName << "()) {\n"
726 << " if (isFirst) isFirst = false;\n"
727 << " else OS << \", \";\n";
733 void writeDump(raw_ostream &OS) const override {
734 OS << " for (const auto &Val : SA->" << RangeName << "())\n";
735 OS << " OS << \" \" << Val;\n";
739 // Unique the enums, but maintain the original declaration ordering.
740 std::vector<StringRef>
741 uniqueEnumsInOrder(const std::vector<StringRef> &enums) {
742 std::vector<StringRef> uniques;
743 SmallDenseSet<StringRef, 8> unique_set;
744 for (const auto &i : enums) {
745 if (unique_set.insert(i).second)
746 uniques.push_back(i);
751 class EnumArgument : public Argument {
753 std::vector<StringRef> values, enums, uniques;
756 EnumArgument(const Record &Arg, StringRef Attr)
757 : Argument(Arg, Attr), type(Arg.getValueAsString("Type")),
758 values(Arg.getValueAsListOfStrings("Values")),
759 enums(Arg.getValueAsListOfStrings("Enums")),
760 uniques(uniqueEnumsInOrder(enums))
762 // FIXME: Emit a proper error
763 assert(!uniques.empty());
766 bool isEnumArg() const override { return true; }
768 void writeAccessors(raw_ostream &OS) const override {
769 OS << " " << type << " get" << getUpperName() << "() const {\n";
770 OS << " return " << getLowerName() << ";\n";
774 void writeCloneArgs(raw_ostream &OS) const override {
775 OS << getLowerName();
778 void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
779 OS << "A->get" << getUpperName() << "()";
781 void writeCtorInitializers(raw_ostream &OS) const override {
782 OS << getLowerName() << "(" << getUpperName() << ")";
784 void writeCtorDefaultInitializers(raw_ostream &OS) const override {
785 OS << getLowerName() << "(" << type << "(0))";
787 void writeCtorParameters(raw_ostream &OS) const override {
788 OS << type << " " << getUpperName();
790 void writeDeclarations(raw_ostream &OS) const override {
791 auto i = uniques.cbegin(), e = uniques.cend();
792 // The last one needs to not have a comma.
796 OS << " enum " << type << " {\n";
798 OS << " " << *i << ",\n";
799 OS << " " << *e << "\n";
802 OS << " " << type << " " << getLowerName() << ";";
805 void writePCHReadDecls(raw_ostream &OS) const override {
806 OS << " " << getAttrName() << "Attr::" << type << " " << getLowerName()
807 << "(static_cast<" << getAttrName() << "Attr::" << type
808 << ">(Record.readInt()));\n";
811 void writePCHReadArgs(raw_ostream &OS) const override {
812 OS << getLowerName();
815 void writePCHWrite(raw_ostream &OS) const override {
816 OS << "Record.push_back(SA->get" << getUpperName() << "());\n";
819 void writeValue(raw_ostream &OS) const override {
820 // FIXME: this isn't 100% correct -- some enum arguments require printing
821 // as a string literal, while others require printing as an identifier.
822 // Tablegen currently does not distinguish between the two forms.
823 OS << "\\\"\" << " << getAttrName() << "Attr::Convert" << type << "ToStr(get"
824 << getUpperName() << "()) << \"\\\"";
827 void writeDump(raw_ostream &OS) const override {
828 OS << " switch(SA->get" << getUpperName() << "()) {\n";
829 for (const auto &I : uniques) {
830 OS << " case " << getAttrName() << "Attr::" << I << ":\n";
831 OS << " OS << \" " << I << "\";\n";
837 void writeConversion(raw_ostream &OS) const {
838 OS << " static bool ConvertStrTo" << type << "(StringRef Val, ";
839 OS << type << " &Out) {\n";
840 OS << " Optional<" << type << "> R = llvm::StringSwitch<Optional<";
841 OS << type << ">>(Val)\n";
842 for (size_t I = 0; I < enums.size(); ++I) {
843 OS << " .Case(\"" << values[I] << "\", ";
844 OS << getAttrName() << "Attr::" << enums[I] << ")\n";
846 OS << " .Default(Optional<" << type << ">());\n";
848 OS << " Out = *R;\n return true;\n }\n";
849 OS << " return false;\n";
852 // Mapping from enumeration values back to enumeration strings isn't
853 // trivial because some enumeration values have multiple named
854 // enumerators, such as type_visibility(internal) and
855 // type_visibility(hidden) both mapping to TypeVisibilityAttr::Hidden.
856 OS << " static const char *Convert" << type << "ToStr("
857 << type << " Val) {\n"
858 << " switch(Val) {\n";
859 SmallDenseSet<StringRef, 8> Uniques;
860 for (size_t I = 0; I < enums.size(); ++I) {
861 if (Uniques.insert(enums[I]).second)
862 OS << " case " << getAttrName() << "Attr::" << enums[I]
863 << ": return \"" << values[I] << "\";\n";
866 << " llvm_unreachable(\"No enumerator with that value\");\n"
871 class VariadicEnumArgument: public VariadicArgument {
872 std::string type, QualifiedTypeName;
873 std::vector<StringRef> values, enums, uniques;
876 void writeValueImpl(raw_ostream &OS) const override {
877 // FIXME: this isn't 100% correct -- some enum arguments require printing
878 // as a string literal, while others require printing as an identifier.
879 // Tablegen currently does not distinguish between the two forms.
880 OS << " OS << \"\\\"\" << " << getAttrName() << "Attr::Convert" << type
881 << "ToStr(Val)" << "<< \"\\\"\";\n";
885 VariadicEnumArgument(const Record &Arg, StringRef Attr)
886 : VariadicArgument(Arg, Attr, Arg.getValueAsString("Type")),
887 type(Arg.getValueAsString("Type")),
888 values(Arg.getValueAsListOfStrings("Values")),
889 enums(Arg.getValueAsListOfStrings("Enums")),
890 uniques(uniqueEnumsInOrder(enums))
892 QualifiedTypeName = getAttrName().str() + "Attr::" + type;
894 // FIXME: Emit a proper error
895 assert(!uniques.empty());
898 bool isVariadicEnumArg() const override { return true; }
900 void writeDeclarations(raw_ostream &OS) const override {
901 auto i = uniques.cbegin(), e = uniques.cend();
902 // The last one needs to not have a comma.
906 OS << " enum " << type << " {\n";
908 OS << " " << *i << ",\n";
909 OS << " " << *e << "\n";
913 VariadicArgument::writeDeclarations(OS);
916 void writeDump(raw_ostream &OS) const override {
917 OS << " for (" << getAttrName() << "Attr::" << getLowerName()
918 << "_iterator I = SA->" << getLowerName() << "_begin(), E = SA->"
919 << getLowerName() << "_end(); I != E; ++I) {\n";
920 OS << " switch(*I) {\n";
921 for (const auto &UI : uniques) {
922 OS << " case " << getAttrName() << "Attr::" << UI << ":\n";
923 OS << " OS << \" " << UI << "\";\n";
930 void writePCHReadDecls(raw_ostream &OS) const override {
931 OS << " unsigned " << getLowerName() << "Size = Record.readInt();\n";
932 OS << " SmallVector<" << QualifiedTypeName << ", 4> " << getLowerName()
934 OS << " " << getLowerName() << ".reserve(" << getLowerName()
936 OS << " for (unsigned i = " << getLowerName() << "Size; i; --i)\n";
937 OS << " " << getLowerName() << ".push_back(" << "static_cast<"
938 << QualifiedTypeName << ">(Record.readInt()));\n";
941 void writePCHWrite(raw_ostream &OS) const override {
942 OS << " Record.push_back(SA->" << getLowerName() << "_size());\n";
943 OS << " for (" << getAttrName() << "Attr::" << getLowerName()
944 << "_iterator i = SA->" << getLowerName() << "_begin(), e = SA->"
945 << getLowerName() << "_end(); i != e; ++i)\n";
946 OS << " " << WritePCHRecord(QualifiedTypeName, "(*i)");
949 void writeConversion(raw_ostream &OS) const {
950 OS << " static bool ConvertStrTo" << type << "(StringRef Val, ";
951 OS << type << " &Out) {\n";
952 OS << " Optional<" << type << "> R = llvm::StringSwitch<Optional<";
953 OS << type << ">>(Val)\n";
954 for (size_t I = 0; I < enums.size(); ++I) {
955 OS << " .Case(\"" << values[I] << "\", ";
956 OS << getAttrName() << "Attr::" << enums[I] << ")\n";
958 OS << " .Default(Optional<" << type << ">());\n";
960 OS << " Out = *R;\n return true;\n }\n";
961 OS << " return false;\n";
964 OS << " static const char *Convert" << type << "ToStr("
965 << type << " Val) {\n"
966 << " switch(Val) {\n";
967 SmallDenseSet<StringRef, 8> Uniques;
968 for (size_t I = 0; I < enums.size(); ++I) {
969 if (Uniques.insert(enums[I]).second)
970 OS << " case " << getAttrName() << "Attr::" << enums[I]
971 << ": return \"" << values[I] << "\";\n";
974 << " llvm_unreachable(\"No enumerator with that value\");\n"
979 class VersionArgument : public Argument {
981 VersionArgument(const Record &Arg, StringRef Attr)
982 : Argument(Arg, Attr)
985 void writeAccessors(raw_ostream &OS) const override {
986 OS << " VersionTuple get" << getUpperName() << "() const {\n";
987 OS << " return " << getLowerName() << ";\n";
989 OS << " void set" << getUpperName()
990 << "(ASTContext &C, VersionTuple V) {\n";
991 OS << " " << getLowerName() << " = V;\n";
995 void writeCloneArgs(raw_ostream &OS) const override {
996 OS << "get" << getUpperName() << "()";
999 void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
1000 OS << "A->get" << getUpperName() << "()";
1003 void writeCtorInitializers(raw_ostream &OS) const override {
1004 OS << getLowerName() << "(" << getUpperName() << ")";
1007 void writeCtorDefaultInitializers(raw_ostream &OS) const override {
1008 OS << getLowerName() << "()";
1011 void writeCtorParameters(raw_ostream &OS) const override {
1012 OS << "VersionTuple " << getUpperName();
1015 void writeDeclarations(raw_ostream &OS) const override {
1016 OS << "VersionTuple " << getLowerName() << ";\n";
1019 void writePCHReadDecls(raw_ostream &OS) const override {
1020 OS << " VersionTuple " << getLowerName()
1021 << "= Record.readVersionTuple();\n";
1024 void writePCHReadArgs(raw_ostream &OS) const override {
1025 OS << getLowerName();
1028 void writePCHWrite(raw_ostream &OS) const override {
1029 OS << " Record.AddVersionTuple(SA->get" << getUpperName() << "());\n";
1032 void writeValue(raw_ostream &OS) const override {
1033 OS << getLowerName() << "=\" << get" << getUpperName() << "() << \"";
1036 void writeDump(raw_ostream &OS) const override {
1037 OS << " OS << \" \" << SA->get" << getUpperName() << "();\n";
1041 class ExprArgument : public SimpleArgument {
1043 ExprArgument(const Record &Arg, StringRef Attr)
1044 : SimpleArgument(Arg, Attr, "Expr *")
1047 void writeASTVisitorTraversal(raw_ostream &OS) const override {
1049 << "getDerived().TraverseStmt(A->get" << getUpperName() << "()))\n";
1050 OS << " return false;\n";
1053 void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
1054 OS << "tempInst" << getUpperName();
1057 void writeTemplateInstantiation(raw_ostream &OS) const override {
1058 OS << " " << getType() << " tempInst" << getUpperName() << ";\n";
1060 OS << " EnterExpressionEvaluationContext "
1061 << "Unevaluated(S, Sema::ExpressionEvaluationContext::Unevaluated);\n";
1062 OS << " ExprResult " << "Result = S.SubstExpr("
1063 << "A->get" << getUpperName() << "(), TemplateArgs);\n";
1064 OS << " tempInst" << getUpperName() << " = "
1065 << "Result.getAs<Expr>();\n";
1069 void writeDump(raw_ostream &OS) const override {}
1071 void writeDumpChildren(raw_ostream &OS) const override {
1072 OS << " dumpStmt(SA->get" << getUpperName() << "());\n";
1075 void writeHasChildren(raw_ostream &OS) const override { OS << "true"; }
1078 class VariadicExprArgument : public VariadicArgument {
1080 VariadicExprArgument(const Record &Arg, StringRef Attr)
1081 : VariadicArgument(Arg, Attr, "Expr *")
1084 void writeASTVisitorTraversal(raw_ostream &OS) const override {
1086 OS << " " << getType() << " *I = A->" << getLowerName()
1088 OS << " " << getType() << " *E = A->" << getLowerName()
1090 OS << " for (; I != E; ++I) {\n";
1091 OS << " if (!getDerived().TraverseStmt(*I))\n";
1092 OS << " return false;\n";
1097 void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
1098 OS << "tempInst" << getUpperName() << ", "
1099 << "A->" << getLowerName() << "_size()";
1102 void writeTemplateInstantiation(raw_ostream &OS) const override {
1103 OS << " auto *tempInst" << getUpperName()
1104 << " = new (C, 16) " << getType()
1105 << "[A->" << getLowerName() << "_size()];\n";
1107 OS << " EnterExpressionEvaluationContext "
1108 << "Unevaluated(S, Sema::ExpressionEvaluationContext::Unevaluated);\n";
1109 OS << " " << getType() << " *TI = tempInst" << getUpperName()
1111 OS << " " << getType() << " *I = A->" << getLowerName()
1113 OS << " " << getType() << " *E = A->" << getLowerName()
1115 OS << " for (; I != E; ++I, ++TI) {\n";
1116 OS << " ExprResult Result = S.SubstExpr(*I, TemplateArgs);\n";
1117 OS << " *TI = Result.getAs<Expr>();\n";
1122 void writeDump(raw_ostream &OS) const override {}
1124 void writeDumpChildren(raw_ostream &OS) const override {
1125 OS << " for (" << getAttrName() << "Attr::" << getLowerName()
1126 << "_iterator I = SA->" << getLowerName() << "_begin(), E = SA->"
1127 << getLowerName() << "_end(); I != E; ++I)\n";
1128 OS << " dumpStmt(*I);\n";
1131 void writeHasChildren(raw_ostream &OS) const override {
1132 OS << "SA->" << getLowerName() << "_begin() != "
1133 << "SA->" << getLowerName() << "_end()";
1137 class VariadicStringArgument : public VariadicArgument {
1139 VariadicStringArgument(const Record &Arg, StringRef Attr)
1140 : VariadicArgument(Arg, Attr, "StringRef")
1143 void writeCtorBody(raw_ostream &OS) const override {
1144 OS << " for (size_t I = 0, E = " << getArgSizeName() << "; I != E;\n"
1146 " StringRef Ref = " << getUpperName() << "[I];\n"
1147 " if (!Ref.empty()) {\n"
1148 " char *Mem = new (Ctx, 1) char[Ref.size()];\n"
1149 " std::memcpy(Mem, Ref.data(), Ref.size());\n"
1150 " " << getArgName() << "[I] = StringRef(Mem, Ref.size());\n"
1155 void writeValueImpl(raw_ostream &OS) const override {
1156 OS << " OS << \"\\\"\" << Val << \"\\\"\";\n";
1160 class TypeArgument : public SimpleArgument {
1162 TypeArgument(const Record &Arg, StringRef Attr)
1163 : SimpleArgument(Arg, Attr, "TypeSourceInfo *")
1166 void writeAccessors(raw_ostream &OS) const override {
1167 OS << " QualType get" << getUpperName() << "() const {\n";
1168 OS << " return " << getLowerName() << "->getType();\n";
1170 OS << " " << getType() << " get" << getUpperName() << "Loc() const {\n";
1171 OS << " return " << getLowerName() << ";\n";
1175 void writeASTVisitorTraversal(raw_ostream &OS) const override {
1176 OS << " if (auto *TSI = A->get" << getUpperName() << "Loc())\n";
1177 OS << " if (!getDerived().TraverseTypeLoc(TSI->getTypeLoc()))\n";
1178 OS << " return false;\n";
1181 void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
1182 OS << "A->get" << getUpperName() << "Loc()";
1185 void writePCHWrite(raw_ostream &OS) const override {
1186 OS << " " << WritePCHRecord(
1187 getType(), "SA->get" + std::string(getUpperName()) + "Loc()");
1191 } // end anonymous namespace
1193 static std::unique_ptr<Argument>
1194 createArgument(const Record &Arg, StringRef Attr,
1195 const Record *Search = nullptr) {
1199 std::unique_ptr<Argument> Ptr;
1200 llvm::StringRef ArgName = Search->getName();
1202 if (ArgName == "AlignedArgument")
1203 Ptr = llvm::make_unique<AlignedArgument>(Arg, Attr);
1204 else if (ArgName == "EnumArgument")
1205 Ptr = llvm::make_unique<EnumArgument>(Arg, Attr);
1206 else if (ArgName == "ExprArgument")
1207 Ptr = llvm::make_unique<ExprArgument>(Arg, Attr);
1208 else if (ArgName == "FunctionArgument")
1209 Ptr = llvm::make_unique<SimpleArgument>(Arg, Attr, "FunctionDecl *");
1210 else if (ArgName == "NamedArgument")
1211 Ptr = llvm::make_unique<SimpleArgument>(Arg, Attr, "NamedDecl *");
1212 else if (ArgName == "IdentifierArgument")
1213 Ptr = llvm::make_unique<SimpleArgument>(Arg, Attr, "IdentifierInfo *");
1214 else if (ArgName == "DefaultBoolArgument")
1215 Ptr = llvm::make_unique<DefaultSimpleArgument>(
1216 Arg, Attr, "bool", Arg.getValueAsBit("Default"));
1217 else if (ArgName == "BoolArgument")
1218 Ptr = llvm::make_unique<SimpleArgument>(Arg, Attr, "bool");
1219 else if (ArgName == "DefaultIntArgument")
1220 Ptr = llvm::make_unique<DefaultSimpleArgument>(
1221 Arg, Attr, "int", Arg.getValueAsInt("Default"));
1222 else if (ArgName == "IntArgument")
1223 Ptr = llvm::make_unique<SimpleArgument>(Arg, Attr, "int");
1224 else if (ArgName == "StringArgument")
1225 Ptr = llvm::make_unique<StringArgument>(Arg, Attr);
1226 else if (ArgName == "TypeArgument")
1227 Ptr = llvm::make_unique<TypeArgument>(Arg, Attr);
1228 else if (ArgName == "UnsignedArgument")
1229 Ptr = llvm::make_unique<SimpleArgument>(Arg, Attr, "unsigned");
1230 else if (ArgName == "VariadicUnsignedArgument")
1231 Ptr = llvm::make_unique<VariadicArgument>(Arg, Attr, "unsigned");
1232 else if (ArgName == "VariadicStringArgument")
1233 Ptr = llvm::make_unique<VariadicStringArgument>(Arg, Attr);
1234 else if (ArgName == "VariadicEnumArgument")
1235 Ptr = llvm::make_unique<VariadicEnumArgument>(Arg, Attr);
1236 else if (ArgName == "VariadicExprArgument")
1237 Ptr = llvm::make_unique<VariadicExprArgument>(Arg, Attr);
1238 else if (ArgName == "VersionArgument")
1239 Ptr = llvm::make_unique<VersionArgument>(Arg, Attr);
1242 // Search in reverse order so that the most-derived type is handled first.
1243 ArrayRef<std::pair<Record*, SMRange>> Bases = Search->getSuperClasses();
1244 for (const auto &Base : llvm::reverse(Bases)) {
1245 if ((Ptr = createArgument(Arg, Attr, Base.first)))
1250 if (Ptr && Arg.getValueAsBit("Optional"))
1251 Ptr->setOptional(true);
1253 if (Ptr && Arg.getValueAsBit("Fake"))
1259 static void writeAvailabilityValue(raw_ostream &OS) {
1260 OS << "\" << getPlatform()->getName();\n"
1261 << " if (getStrict()) OS << \", strict\";\n"
1262 << " if (!getIntroduced().empty()) OS << \", introduced=\" << getIntroduced();\n"
1263 << " if (!getDeprecated().empty()) OS << \", deprecated=\" << getDeprecated();\n"
1264 << " if (!getObsoleted().empty()) OS << \", obsoleted=\" << getObsoleted();\n"
1265 << " if (getUnavailable()) OS << \", unavailable\";\n"
1269 static void writeDeprecatedAttrValue(raw_ostream &OS, std::string &Variety) {
1270 OS << "\\\"\" << getMessage() << \"\\\"\";\n";
1271 // Only GNU deprecated has an optional fixit argument at the second position.
1272 if (Variety == "GNU")
1273 OS << " if (!getReplacement().empty()) OS << \", \\\"\""
1274 " << getReplacement() << \"\\\"\";\n";
1278 static void writeGetSpellingFunction(Record &R, raw_ostream &OS) {
1279 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(R);
1281 OS << "const char *" << R.getName() << "Attr::getSpelling() const {\n";
1282 if (Spellings.empty()) {
1283 OS << " return \"(No spelling)\";\n}\n\n";
1287 OS << " switch (SpellingListIndex) {\n"
1289 " llvm_unreachable(\"Unknown attribute spelling!\");\n"
1290 " return \"(No spelling)\";\n";
1292 for (unsigned I = 0; I < Spellings.size(); ++I)
1293 OS << " case " << I << ":\n"
1294 " return \"" << Spellings[I].name() << "\";\n";
1295 // End of the switch statement.
1297 // End of the getSpelling function.
1302 writePrettyPrintFunction(Record &R,
1303 const std::vector<std::unique_ptr<Argument>> &Args,
1305 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(R);
1307 OS << "void " << R.getName() << "Attr::printPretty("
1308 << "raw_ostream &OS, const PrintingPolicy &Policy) const {\n";
1310 if (Spellings.empty()) {
1316 " switch (SpellingListIndex) {\n"
1318 " llvm_unreachable(\"Unknown attribute spelling!\");\n"
1321 for (unsigned I = 0; I < Spellings.size(); ++ I) {
1322 llvm::SmallString<16> Prefix;
1323 llvm::SmallString<8> Suffix;
1324 // The actual spelling of the name and namespace (if applicable)
1325 // of an attribute without considering prefix and suffix.
1326 llvm::SmallString<64> Spelling;
1327 std::string Name = Spellings[I].name();
1328 std::string Variety = Spellings[I].variety();
1330 if (Variety == "GNU") {
1331 Prefix = " __attribute__((";
1333 } else if (Variety == "CXX11" || Variety == "C2x") {
1336 std::string Namespace = Spellings[I].nameSpace();
1337 if (!Namespace.empty()) {
1338 Spelling += Namespace;
1341 } else if (Variety == "Declspec") {
1342 Prefix = " __declspec(";
1344 } else if (Variety == "Microsoft") {
1347 } else if (Variety == "Keyword") {
1350 } else if (Variety == "Pragma") {
1351 Prefix = "#pragma ";
1353 std::string Namespace = Spellings[I].nameSpace();
1354 if (!Namespace.empty()) {
1355 Spelling += Namespace;
1359 llvm_unreachable("Unknown attribute syntax variety!");
1365 " case " << I << " : {\n"
1366 " OS << \"" << Prefix << Spelling;
1368 if (Variety == "Pragma") {
1370 OS << " printPrettyPragma(OS, Policy);\n";
1371 OS << " OS << \"\\n\";";
1377 // Fake arguments aren't part of the parsed form and should not be
1379 bool hasNonFakeArgs = llvm::any_of(
1380 Args, [](const std::unique_ptr<Argument> &A) { return !A->isFake(); });
1382 // FIXME: always printing the parenthesis isn't the correct behavior for
1383 // attributes which have optional arguments that were not provided. For
1384 // instance: __attribute__((aligned)) will be pretty printed as
1385 // __attribute__((aligned())). The logic should check whether there is only
1386 // a single argument, and if it is optional, whether it has been provided.
1389 if (Spelling == "availability") {
1390 writeAvailabilityValue(OS);
1391 } else if (Spelling == "deprecated" || Spelling == "gnu::deprecated") {
1392 writeDeprecatedAttrValue(OS, Variety);
1395 for (const auto &arg : Args) {
1396 if (arg->isFake()) continue;
1397 if (index++) OS << ", ";
1398 arg->writeValue(OS);
1404 OS << Suffix + "\";\n";
1411 // End of the switch statement.
1413 // End of the print function.
1417 /// \brief Return the index of a spelling in a spelling list.
1419 getSpellingListIndex(const std::vector<FlattenedSpelling> &SpellingList,
1420 const FlattenedSpelling &Spelling) {
1421 assert(!SpellingList.empty() && "Spelling list is empty!");
1423 for (unsigned Index = 0; Index < SpellingList.size(); ++Index) {
1424 const FlattenedSpelling &S = SpellingList[Index];
1425 if (S.variety() != Spelling.variety())
1427 if (S.nameSpace() != Spelling.nameSpace())
1429 if (S.name() != Spelling.name())
1435 llvm_unreachable("Unknown spelling!");
1438 static void writeAttrAccessorDefinition(const Record &R, raw_ostream &OS) {
1439 std::vector<Record*> Accessors = R.getValueAsListOfDefs("Accessors");
1440 if (Accessors.empty())
1443 const std::vector<FlattenedSpelling> SpellingList = GetFlattenedSpellings(R);
1444 assert(!SpellingList.empty() &&
1445 "Attribute with empty spelling list can't have accessors!");
1446 for (const auto *Accessor : Accessors) {
1447 const StringRef Name = Accessor->getValueAsString("Name");
1448 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(*Accessor);
1450 OS << " bool " << Name << "() const { return SpellingListIndex == ";
1451 for (unsigned Index = 0; Index < Spellings.size(); ++Index) {
1452 OS << getSpellingListIndex(SpellingList, Spellings[Index]);
1453 if (Index != Spellings.size() - 1)
1454 OS << " ||\n SpellingListIndex == ";
1462 SpellingNamesAreCommon(const std::vector<FlattenedSpelling>& Spellings) {
1463 assert(!Spellings.empty() && "An empty list of spellings was provided");
1464 std::string FirstName = NormalizeNameForSpellingComparison(
1465 Spellings.front().name());
1466 for (const auto &Spelling :
1467 llvm::make_range(std::next(Spellings.begin()), Spellings.end())) {
1468 std::string Name = NormalizeNameForSpellingComparison(Spelling.name());
1469 if (Name != FirstName)
1475 typedef std::map<unsigned, std::string> SemanticSpellingMap;
1477 CreateSemanticSpellings(const std::vector<FlattenedSpelling> &Spellings,
1478 SemanticSpellingMap &Map) {
1479 // The enumerants are automatically generated based on the variety,
1480 // namespace (if present) and name for each attribute spelling. However,
1481 // care is taken to avoid trampling on the reserved namespace due to
1483 std::string Ret(" enum Spelling {\n");
1484 std::set<std::string> Uniques;
1486 for (auto I = Spellings.begin(), E = Spellings.end(); I != E; ++I, ++Idx) {
1487 const FlattenedSpelling &S = *I;
1488 const std::string &Variety = S.variety();
1489 const std::string &Spelling = S.name();
1490 const std::string &Namespace = S.nameSpace();
1491 std::string EnumName;
1493 EnumName += (Variety + "_");
1494 if (!Namespace.empty())
1495 EnumName += (NormalizeNameForSpellingComparison(Namespace).str() +
1497 EnumName += NormalizeNameForSpellingComparison(Spelling);
1499 // Even if the name is not unique, this spelling index corresponds to a
1500 // particular enumerant name that we've calculated.
1501 Map[Idx] = EnumName;
1503 // Since we have been stripping underscores to avoid trampling on the
1504 // reserved namespace, we may have inadvertently created duplicate
1505 // enumerant names. These duplicates are not considered part of the
1506 // semantic spelling, and can be elided.
1507 if (Uniques.find(EnumName) != Uniques.end())
1510 Uniques.insert(EnumName);
1511 if (I != Spellings.begin())
1513 // Duplicate spellings are not considered part of the semantic spelling
1514 // enumeration, but the spelling index and semantic spelling values are
1515 // meant to be equivalent, so we must specify a concrete value for each
1517 Ret += " " + EnumName + " = " + llvm::utostr(Idx);
1523 void WriteSemanticSpellingSwitch(const std::string &VarName,
1524 const SemanticSpellingMap &Map,
1526 OS << " switch (" << VarName << ") {\n default: "
1527 << "llvm_unreachable(\"Unknown spelling list index\");\n";
1528 for (const auto &I : Map)
1529 OS << " case " << I.first << ": return " << I.second << ";\n";
1533 // Emits the LateParsed property for attributes.
1534 static void emitClangAttrLateParsedList(RecordKeeper &Records, raw_ostream &OS) {
1535 OS << "#if defined(CLANG_ATTR_LATE_PARSED_LIST)\n";
1536 std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr");
1538 for (const auto *Attr : Attrs) {
1539 bool LateParsed = Attr->getValueAsBit("LateParsed");
1542 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(*Attr);
1544 // FIXME: Handle non-GNU attributes
1545 for (const auto &I : Spellings) {
1546 if (I.variety() != "GNU")
1548 OS << ".Case(\"" << I.name() << "\", " << LateParsed << ")\n";
1552 OS << "#endif // CLANG_ATTR_LATE_PARSED_LIST\n\n";
1555 static bool hasGNUorCXX11Spelling(const Record &Attribute) {
1556 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(Attribute);
1557 for (const auto &I : Spellings) {
1558 if (I.variety() == "GNU" || I.variety() == "CXX11")
1566 struct AttributeSubjectMatchRule {
1567 const Record *MetaSubject;
1568 const Record *Constraint;
1570 AttributeSubjectMatchRule(const Record *MetaSubject, const Record *Constraint)
1571 : MetaSubject(MetaSubject), Constraint(Constraint) {
1572 assert(MetaSubject && "Missing subject");
1575 bool isSubRule() const { return Constraint != nullptr; }
1577 std::vector<Record *> getSubjects() const {
1578 return (Constraint ? Constraint : MetaSubject)
1579 ->getValueAsListOfDefs("Subjects");
1582 std::vector<Record *> getLangOpts() const {
1584 // Lookup the options in the sub-rule first, in case the sub-rule
1585 // overrides the rules options.
1586 std::vector<Record *> Opts = Constraint->getValueAsListOfDefs("LangOpts");
1590 return MetaSubject->getValueAsListOfDefs("LangOpts");
1593 // Abstract rules are used only for sub-rules
1594 bool isAbstractRule() const { return getSubjects().empty(); }
1596 StringRef getName() const {
1597 return (Constraint ? Constraint : MetaSubject)->getValueAsString("Name");
1600 bool isNegatedSubRule() const {
1601 assert(isSubRule() && "Not a sub-rule");
1602 return Constraint->getValueAsBit("Negated");
1605 std::string getSpelling() const {
1606 std::string Result = MetaSubject->getValueAsString("Name");
1609 if (isNegatedSubRule())
1610 Result += "unless(";
1611 Result += getName();
1612 if (isNegatedSubRule())
1619 std::string getEnumValueName() const {
1620 SmallString<128> Result;
1621 Result += "SubjectMatchRule_";
1622 Result += MetaSubject->getValueAsString("Name");
1625 if (isNegatedSubRule())
1627 Result += Constraint->getValueAsString("Name");
1629 if (isAbstractRule())
1630 Result += "_abstract";
1631 return Result.str();
1634 std::string getEnumValue() const { return "attr::" + getEnumValueName(); }
1636 static const char *EnumName;
1639 const char *AttributeSubjectMatchRule::EnumName = "attr::SubjectMatchRule";
1641 struct PragmaClangAttributeSupport {
1642 std::vector<AttributeSubjectMatchRule> Rules;
1644 class RuleOrAggregateRuleSet {
1645 std::vector<AttributeSubjectMatchRule> Rules;
1647 RuleOrAggregateRuleSet(ArrayRef<AttributeSubjectMatchRule> Rules,
1649 : Rules(Rules), IsRule(IsRule) {}
1652 bool isRule() const { return IsRule; }
1654 const AttributeSubjectMatchRule &getRule() const {
1655 assert(IsRule && "not a rule!");
1659 ArrayRef<AttributeSubjectMatchRule> getAggregateRuleSet() const {
1663 static RuleOrAggregateRuleSet
1664 getRule(const AttributeSubjectMatchRule &Rule) {
1665 return RuleOrAggregateRuleSet(Rule, /*IsRule=*/true);
1667 static RuleOrAggregateRuleSet
1668 getAggregateRuleSet(ArrayRef<AttributeSubjectMatchRule> Rules) {
1669 return RuleOrAggregateRuleSet(Rules, /*IsRule=*/false);
1672 llvm::DenseMap<const Record *, RuleOrAggregateRuleSet> SubjectsToRules;
1674 PragmaClangAttributeSupport(RecordKeeper &Records);
1676 bool isAttributedSupported(const Record &Attribute);
1678 void emitMatchRuleList(raw_ostream &OS);
1680 std::string generateStrictConformsTo(const Record &Attr, raw_ostream &OS);
1682 void generateParsingHelpers(raw_ostream &OS);
1685 } // end anonymous namespace
1687 static bool doesDeclDeriveFrom(const Record *D, const Record *Base) {
1688 const Record *CurrentBase = D->getValueAsDef("Base");
1691 if (CurrentBase == Base)
1693 return doesDeclDeriveFrom(CurrentBase, Base);
1696 PragmaClangAttributeSupport::PragmaClangAttributeSupport(
1697 RecordKeeper &Records) {
1698 std::vector<Record *> MetaSubjects =
1699 Records.getAllDerivedDefinitions("AttrSubjectMatcherRule");
1700 auto MapFromSubjectsToRules = [this](const Record *SubjectContainer,
1701 const Record *MetaSubject,
1702 const Record *Constraint) {
1703 Rules.emplace_back(MetaSubject, Constraint);
1704 std::vector<Record *> ApplicableSubjects =
1705 SubjectContainer->getValueAsListOfDefs("Subjects");
1706 for (const auto *Subject : ApplicableSubjects) {
1709 .try_emplace(Subject, RuleOrAggregateRuleSet::getRule(
1710 AttributeSubjectMatchRule(MetaSubject,
1714 PrintFatalError("Attribute subject match rules should not represent"
1715 "same attribute subjects.");
1719 for (const auto *MetaSubject : MetaSubjects) {
1720 MapFromSubjectsToRules(MetaSubject, MetaSubject, /*Constraints=*/nullptr);
1721 std::vector<Record *> Constraints =
1722 MetaSubject->getValueAsListOfDefs("Constraints");
1723 for (const auto *Constraint : Constraints)
1724 MapFromSubjectsToRules(Constraint, MetaSubject, Constraint);
1727 std::vector<Record *> Aggregates =
1728 Records.getAllDerivedDefinitions("AttrSubjectMatcherAggregateRule");
1729 std::vector<Record *> DeclNodes = Records.getAllDerivedDefinitions("DDecl");
1730 for (const auto *Aggregate : Aggregates) {
1731 Record *SubjectDecl = Aggregate->getValueAsDef("Subject");
1733 // Gather sub-classes of the aggregate subject that act as attribute
1735 std::vector<AttributeSubjectMatchRule> Rules;
1736 for (const auto *D : DeclNodes) {
1737 if (doesDeclDeriveFrom(D, SubjectDecl)) {
1738 auto It = SubjectsToRules.find(D);
1739 if (It == SubjectsToRules.end())
1741 if (!It->second.isRule() || It->second.getRule().isSubRule())
1742 continue; // Assume that the rule will be included as well.
1743 Rules.push_back(It->second.getRule());
1749 .try_emplace(SubjectDecl,
1750 RuleOrAggregateRuleSet::getAggregateRuleSet(Rules))
1753 PrintFatalError("Attribute subject match rules should not represent"
1754 "same attribute subjects.");
1759 static PragmaClangAttributeSupport &
1760 getPragmaAttributeSupport(RecordKeeper &Records) {
1761 static PragmaClangAttributeSupport Instance(Records);
1765 void PragmaClangAttributeSupport::emitMatchRuleList(raw_ostream &OS) {
1766 OS << "#ifndef ATTR_MATCH_SUB_RULE\n";
1767 OS << "#define ATTR_MATCH_SUB_RULE(Value, Spelling, IsAbstract, Parent, "
1769 << "ATTR_MATCH_RULE(Value, Spelling, IsAbstract)\n";
1771 for (const auto &Rule : Rules) {
1772 OS << (Rule.isSubRule() ? "ATTR_MATCH_SUB_RULE" : "ATTR_MATCH_RULE") << '(';
1773 OS << Rule.getEnumValueName() << ", \"" << Rule.getSpelling() << "\", "
1774 << Rule.isAbstractRule();
1775 if (Rule.isSubRule())
1777 << AttributeSubjectMatchRule(Rule.MetaSubject, nullptr).getEnumValue()
1778 << ", " << Rule.isNegatedSubRule();
1781 OS << "#undef ATTR_MATCH_SUB_RULE\n";
1784 bool PragmaClangAttributeSupport::isAttributedSupported(
1785 const Record &Attribute) {
1786 if (Attribute.getValueAsBit("ForcePragmaAttributeSupport"))
1789 // FIXME: The documentation check should be moved before
1790 // the ForcePragmaAttributeSupport check after annotate is documented.
1791 // No documentation present.
1792 if (Attribute.isValueUnset("Documentation"))
1794 std::vector<Record *> Docs = Attribute.getValueAsListOfDefs("Documentation");
1797 if (Docs.size() == 1 && Docs[0]->getName() == "Undocumented")
1799 // An attribute requires delayed parsing (LateParsed is on)
1800 if (Attribute.getValueAsBit("LateParsed"))
1802 // An attribute has no GNU/CXX11 spelling
1803 if (!hasGNUorCXX11Spelling(Attribute))
1805 // An attribute subject list has a subject that isn't covered by one of the
1806 // subject match rules or has no subjects at all.
1807 if (Attribute.isValueUnset("Subjects"))
1809 const Record *SubjectObj = Attribute.getValueAsDef("Subjects");
1810 std::vector<Record *> Subjects = SubjectObj->getValueAsListOfDefs("Subjects");
1811 if (Subjects.empty())
1813 for (const auto *Subject : Subjects) {
1814 if (SubjectsToRules.find(Subject) == SubjectsToRules.end())
1821 PragmaClangAttributeSupport::generateStrictConformsTo(const Record &Attr,
1823 if (!isAttributedSupported(Attr))
1825 // Generate a function that constructs a set of matching rules that describe
1826 // to which declarations the attribute should apply to.
1827 std::string FnName = "matchRulesFor" + Attr.getName().str();
1828 OS << "static void " << FnName << "(llvm::SmallVectorImpl<std::pair<"
1829 << AttributeSubjectMatchRule::EnumName
1830 << ", bool>> &MatchRules, const LangOptions &LangOpts) {\n";
1831 if (Attr.isValueUnset("Subjects")) {
1835 const Record *SubjectObj = Attr.getValueAsDef("Subjects");
1836 std::vector<Record *> Subjects = SubjectObj->getValueAsListOfDefs("Subjects");
1837 for (const auto *Subject : Subjects) {
1838 auto It = SubjectsToRules.find(Subject);
1839 assert(It != SubjectsToRules.end() &&
1840 "This attribute is unsupported by #pragma clang attribute");
1841 for (const auto &Rule : It->getSecond().getAggregateRuleSet()) {
1842 // The rule might be language specific, so only subtract it from the given
1843 // rules if the specific language options are specified.
1844 std::vector<Record *> LangOpts = Rule.getLangOpts();
1845 OS << " MatchRules.push_back(std::make_pair(" << Rule.getEnumValue()
1846 << ", /*IsSupported=*/";
1847 if (!LangOpts.empty()) {
1848 for (auto I = LangOpts.begin(), E = LangOpts.end(); I != E; ++I) {
1849 const StringRef Part = (*I)->getValueAsString("Name");
1850 if ((*I)->getValueAsBit("Negated"))
1852 OS << "LangOpts." << Part;
1865 void PragmaClangAttributeSupport::generateParsingHelpers(raw_ostream &OS) {
1866 // Generate routines that check the names of sub-rules.
1867 OS << "Optional<attr::SubjectMatchRule> "
1868 "defaultIsAttributeSubjectMatchSubRuleFor(StringRef, bool) {\n";
1869 OS << " return None;\n";
1872 std::map<const Record *, std::vector<AttributeSubjectMatchRule>>
1874 for (const auto &Rule : Rules) {
1875 if (!Rule.isSubRule())
1877 SubMatchRules[Rule.MetaSubject].push_back(Rule);
1880 for (const auto &SubMatchRule : SubMatchRules) {
1881 OS << "Optional<attr::SubjectMatchRule> isAttributeSubjectMatchSubRuleFor_"
1882 << SubMatchRule.first->getValueAsString("Name")
1883 << "(StringRef Name, bool IsUnless) {\n";
1884 OS << " if (IsUnless)\n";
1886 "llvm::StringSwitch<Optional<attr::SubjectMatchRule>>(Name).\n";
1887 for (const auto &Rule : SubMatchRule.second) {
1888 if (Rule.isNegatedSubRule())
1889 OS << " Case(\"" << Rule.getName() << "\", " << Rule.getEnumValue()
1892 OS << " Default(None);\n";
1894 "llvm::StringSwitch<Optional<attr::SubjectMatchRule>>(Name).\n";
1895 for (const auto &Rule : SubMatchRule.second) {
1896 if (!Rule.isNegatedSubRule())
1897 OS << " Case(\"" << Rule.getName() << "\", " << Rule.getEnumValue()
1900 OS << " Default(None);\n";
1904 // Generate the function that checks for the top-level rules.
1905 OS << "std::pair<Optional<attr::SubjectMatchRule>, "
1906 "Optional<attr::SubjectMatchRule> (*)(StringRef, "
1907 "bool)> isAttributeSubjectMatchRule(StringRef Name) {\n";
1909 "llvm::StringSwitch<std::pair<Optional<attr::SubjectMatchRule>, "
1910 "Optional<attr::SubjectMatchRule> (*) (StringRef, "
1912 for (const auto &Rule : Rules) {
1913 if (Rule.isSubRule())
1915 std::string SubRuleFunction;
1916 if (SubMatchRules.count(Rule.MetaSubject))
1918 ("isAttributeSubjectMatchSubRuleFor_" + Rule.getName()).str();
1920 SubRuleFunction = "defaultIsAttributeSubjectMatchSubRuleFor";
1921 OS << " Case(\"" << Rule.getName() << "\", std::make_pair("
1922 << Rule.getEnumValue() << ", " << SubRuleFunction << ")).\n";
1924 OS << " Default(std::make_pair(None, "
1925 "defaultIsAttributeSubjectMatchSubRuleFor));\n";
1928 // Generate the function that checks for the submatch rules.
1929 OS << "const char *validAttributeSubjectMatchSubRules("
1930 << AttributeSubjectMatchRule::EnumName << " Rule) {\n";
1931 OS << " switch (Rule) {\n";
1932 for (const auto &SubMatchRule : SubMatchRules) {
1934 << AttributeSubjectMatchRule(SubMatchRule.first, nullptr).getEnumValue()
1936 OS << " return \"'";
1937 bool IsFirst = true;
1938 for (const auto &Rule : SubMatchRule.second) {
1942 if (Rule.isNegatedSubRule())
1944 OS << Rule.getName();
1945 if (Rule.isNegatedSubRule())
1951 OS << " default: return nullptr;\n";
1956 template <typename Fn>
1957 static void forEachUniqueSpelling(const Record &Attr, Fn &&F) {
1958 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(Attr);
1959 SmallDenseSet<StringRef, 8> Seen;
1960 for (const FlattenedSpelling &S : Spellings) {
1961 if (Seen.insert(S.name()).second)
1966 /// \brief Emits the first-argument-is-type property for attributes.
1967 static void emitClangAttrTypeArgList(RecordKeeper &Records, raw_ostream &OS) {
1968 OS << "#if defined(CLANG_ATTR_TYPE_ARG_LIST)\n";
1969 std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
1971 for (const auto *Attr : Attrs) {
1972 // Determine whether the first argument is a type.
1973 std::vector<Record *> Args = Attr->getValueAsListOfDefs("Args");
1977 if (Args[0]->getSuperClasses().back().first->getName() != "TypeArgument")
1980 // All these spellings take a single type argument.
1981 forEachUniqueSpelling(*Attr, [&](const FlattenedSpelling &S) {
1982 OS << ".Case(\"" << S.name() << "\", " << "true" << ")\n";
1985 OS << "#endif // CLANG_ATTR_TYPE_ARG_LIST\n\n";
1988 /// \brief Emits the parse-arguments-in-unevaluated-context property for
1990 static void emitClangAttrArgContextList(RecordKeeper &Records, raw_ostream &OS) {
1991 OS << "#if defined(CLANG_ATTR_ARG_CONTEXT_LIST)\n";
1992 ParsedAttrMap Attrs = getParsedAttrList(Records);
1993 for (const auto &I : Attrs) {
1994 const Record &Attr = *I.second;
1996 if (!Attr.getValueAsBit("ParseArgumentsAsUnevaluated"))
1999 // All these spellings take are parsed unevaluated.
2000 forEachUniqueSpelling(Attr, [&](const FlattenedSpelling &S) {
2001 OS << ".Case(\"" << S.name() << "\", " << "true" << ")\n";
2004 OS << "#endif // CLANG_ATTR_ARG_CONTEXT_LIST\n\n";
2007 static bool isIdentifierArgument(Record *Arg) {
2008 return !Arg->getSuperClasses().empty() &&
2009 llvm::StringSwitch<bool>(Arg->getSuperClasses().back().first->getName())
2010 .Case("IdentifierArgument", true)
2011 .Case("EnumArgument", true)
2012 .Case("VariadicEnumArgument", true)
2016 // Emits the first-argument-is-identifier property for attributes.
2017 static void emitClangAttrIdentifierArgList(RecordKeeper &Records, raw_ostream &OS) {
2018 OS << "#if defined(CLANG_ATTR_IDENTIFIER_ARG_LIST)\n";
2019 std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr");
2021 for (const auto *Attr : Attrs) {
2022 // Determine whether the first argument is an identifier.
2023 std::vector<Record *> Args = Attr->getValueAsListOfDefs("Args");
2024 if (Args.empty() || !isIdentifierArgument(Args[0]))
2027 // All these spellings take an identifier argument.
2028 forEachUniqueSpelling(*Attr, [&](const FlattenedSpelling &S) {
2029 OS << ".Case(\"" << S.name() << "\", " << "true" << ")\n";
2032 OS << "#endif // CLANG_ATTR_IDENTIFIER_ARG_LIST\n\n";
2037 // Emits the class definitions for attributes.
2038 void EmitClangAttrClass(RecordKeeper &Records, raw_ostream &OS) {
2039 emitSourceFileHeader("Attribute classes' definitions", OS);
2041 OS << "#ifndef LLVM_CLANG_ATTR_CLASSES_INC\n";
2042 OS << "#define LLVM_CLANG_ATTR_CLASSES_INC\n\n";
2044 std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr");
2046 for (const auto *Attr : Attrs) {
2047 const Record &R = *Attr;
2049 // FIXME: Currently, documentation is generated as-needed due to the fact
2050 // that there is no way to allow a generated project "reach into" the docs
2051 // directory (for instance, it may be an out-of-tree build). However, we want
2052 // to ensure that every attribute has a Documentation field, and produce an
2053 // error if it has been neglected. Otherwise, the on-demand generation which
2054 // happens server-side will fail. This code is ensuring that functionality,
2055 // even though this Emitter doesn't technically need the documentation.
2056 // When attribute documentation can be generated as part of the build
2057 // itself, this code can be removed.
2058 (void)R.getValueAsListOfDefs("Documentation");
2060 if (!R.getValueAsBit("ASTNode"))
2063 ArrayRef<std::pair<Record *, SMRange>> Supers = R.getSuperClasses();
2064 assert(!Supers.empty() && "Forgot to specify a superclass for the attr");
2065 std::string SuperName;
2066 for (const auto &Super : llvm::reverse(Supers)) {
2067 const Record *R = Super.first;
2068 if (R->getName() != "TargetSpecificAttr" && SuperName.empty())
2069 SuperName = R->getName();
2072 OS << "class " << R.getName() << "Attr : public " << SuperName << " {\n";
2074 std::vector<Record*> ArgRecords = R.getValueAsListOfDefs("Args");
2075 std::vector<std::unique_ptr<Argument>> Args;
2076 Args.reserve(ArgRecords.size());
2078 bool HasOptArg = false;
2079 bool HasFakeArg = false;
2080 for (const auto *ArgRecord : ArgRecords) {
2081 Args.emplace_back(createArgument(*ArgRecord, R.getName()));
2082 Args.back()->writeDeclarations(OS);
2085 // For these purposes, fake takes priority over optional.
2086 if (Args.back()->isFake()) {
2088 } else if (Args.back()->isOptional()) {
2095 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(R);
2097 // If there are zero or one spellings, all spelling-related functionality
2098 // can be elided. If all of the spellings share the same name, the spelling
2099 // functionality can also be elided.
2100 bool ElideSpelling = (Spellings.size() <= 1) ||
2101 SpellingNamesAreCommon(Spellings);
2103 // This maps spelling index values to semantic Spelling enumerants.
2104 SemanticSpellingMap SemanticToSyntacticMap;
2107 OS << CreateSemanticSpellings(Spellings, SemanticToSyntacticMap);
2109 // Emit CreateImplicit factory methods.
2110 auto emitCreateImplicit = [&](bool emitFake) {
2111 OS << " static " << R.getName() << "Attr *CreateImplicit(";
2112 OS << "ASTContext &Ctx";
2114 OS << ", Spelling S";
2115 for (auto const &ai : Args) {
2116 if (ai->isFake() && !emitFake) continue;
2118 ai->writeCtorParameters(OS);
2120 OS << ", SourceRange Loc = SourceRange()";
2122 OS << " auto *A = new (Ctx) " << R.getName();
2123 OS << "Attr(Loc, Ctx, ";
2124 for (auto const &ai : Args) {
2125 if (ai->isFake() && !emitFake) continue;
2126 ai->writeImplicitCtorArgs(OS);
2129 OS << (ElideSpelling ? "0" : "S") << ");\n";
2130 OS << " A->setImplicit(true);\n";
2131 OS << " return A;\n }\n\n";
2134 // Emit a CreateImplicit that takes all the arguments.
2135 emitCreateImplicit(true);
2137 // Emit a CreateImplicit that takes all the non-fake arguments.
2139 emitCreateImplicit(false);
2142 // Emit constructors.
2143 auto emitCtor = [&](bool emitOpt, bool emitFake) {
2144 auto shouldEmitArg = [=](const std::unique_ptr<Argument> &arg) {
2145 if (arg->isFake()) return emitFake;
2146 if (arg->isOptional()) return emitOpt;
2150 OS << " " << R.getName() << "Attr(SourceRange R, ASTContext &Ctx\n";
2151 for (auto const &ai : Args) {
2152 if (!shouldEmitArg(ai)) continue;
2154 ai->writeCtorParameters(OS);
2159 OS << "unsigned SI\n";
2162 OS << " : " << SuperName << "(attr::" << R.getName() << ", R, SI, "
2163 << ( R.getValueAsBit("LateParsed") ? "true" : "false" ) << ", "
2164 << ( R.getValueAsBit("DuplicatesAllowedWhileMerging") ? "true" : "false" ) << ")\n";
2166 for (auto const &ai : Args) {
2168 if (!shouldEmitArg(ai)) {
2169 ai->writeCtorDefaultInitializers(OS);
2171 ai->writeCtorInitializers(OS);
2178 for (auto const &ai : Args) {
2179 if (!shouldEmitArg(ai)) continue;
2180 ai->writeCtorBody(OS);
2185 // Emit a constructor that includes all the arguments.
2186 // This is necessary for cloning.
2187 emitCtor(true, true);
2189 // Emit a constructor that takes all the non-fake arguments.
2191 emitCtor(true, false);
2194 // Emit a constructor that takes all the non-fake, non-optional arguments.
2196 emitCtor(false, false);
2199 OS << " " << R.getName() << "Attr *clone(ASTContext &C) const;\n";
2200 OS << " void printPretty(raw_ostream &OS,\n"
2201 << " const PrintingPolicy &Policy) const;\n";
2202 OS << " const char *getSpelling() const;\n";
2204 if (!ElideSpelling) {
2205 assert(!SemanticToSyntacticMap.empty() && "Empty semantic mapping list");
2206 OS << " Spelling getSemanticSpelling() const {\n";
2207 WriteSemanticSpellingSwitch("SpellingListIndex", SemanticToSyntacticMap,
2212 writeAttrAccessorDefinition(R, OS);
2214 for (auto const &ai : Args) {
2215 ai->writeAccessors(OS);
2218 // Don't write conversion routines for fake arguments.
2219 if (ai->isFake()) continue;
2221 if (ai->isEnumArg())
2222 static_cast<const EnumArgument *>(ai.get())->writeConversion(OS);
2223 else if (ai->isVariadicEnumArg())
2224 static_cast<const VariadicEnumArgument *>(ai.get())
2225 ->writeConversion(OS);
2228 OS << R.getValueAsString("AdditionalMembers");
2231 OS << " static bool classof(const Attr *A) { return A->getKind() == "
2232 << "attr::" << R.getName() << "; }\n";
2237 OS << "#endif // LLVM_CLANG_ATTR_CLASSES_INC\n";
2240 // Emits the class method definitions for attributes.
2241 void EmitClangAttrImpl(RecordKeeper &Records, raw_ostream &OS) {
2242 emitSourceFileHeader("Attribute classes' member function definitions", OS);
2244 std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr");
2246 for (auto *Attr : Attrs) {
2249 if (!R.getValueAsBit("ASTNode"))
2252 std::vector<Record*> ArgRecords = R.getValueAsListOfDefs("Args");
2253 std::vector<std::unique_ptr<Argument>> Args;
2254 for (const auto *Arg : ArgRecords)
2255 Args.emplace_back(createArgument(*Arg, R.getName()));
2257 for (auto const &ai : Args)
2258 ai->writeAccessorDefinitions(OS);
2260 OS << R.getName() << "Attr *" << R.getName()
2261 << "Attr::clone(ASTContext &C) const {\n";
2262 OS << " auto *A = new (C) " << R.getName() << "Attr(getLocation(), C";
2263 for (auto const &ai : Args) {
2265 ai->writeCloneArgs(OS);
2267 OS << ", getSpellingListIndex());\n";
2268 OS << " A->Inherited = Inherited;\n";
2269 OS << " A->IsPackExpansion = IsPackExpansion;\n";
2270 OS << " A->Implicit = Implicit;\n";
2271 OS << " return A;\n}\n\n";
2273 writePrettyPrintFunction(R, Args, OS);
2274 writeGetSpellingFunction(R, OS);
2277 // Instead of relying on virtual dispatch we just create a huge dispatch
2278 // switch. This is both smaller and faster than virtual functions.
2279 auto EmitFunc = [&](const char *Method) {
2280 OS << " switch (getKind()) {\n";
2281 for (const auto *Attr : Attrs) {
2282 const Record &R = *Attr;
2283 if (!R.getValueAsBit("ASTNode"))
2286 OS << " case attr::" << R.getName() << ":\n";
2287 OS << " return cast<" << R.getName() << "Attr>(this)->" << Method
2291 OS << " llvm_unreachable(\"Unexpected attribute kind!\");\n";
2295 OS << "const char *Attr::getSpelling() const {\n";
2296 EmitFunc("getSpelling()");
2298 OS << "Attr *Attr::clone(ASTContext &C) const {\n";
2299 EmitFunc("clone(C)");
2301 OS << "void Attr::printPretty(raw_ostream &OS, "
2302 "const PrintingPolicy &Policy) const {\n";
2303 EmitFunc("printPretty(OS, Policy)");
2306 } // end namespace clang
2308 static void emitAttrList(raw_ostream &OS, StringRef Class,
2309 const std::vector<Record*> &AttrList) {
2310 for (auto Cur : AttrList) {
2311 OS << Class << "(" << Cur->getName() << ")\n";
2315 // Determines if an attribute has a Pragma spelling.
2316 static bool AttrHasPragmaSpelling(const Record *R) {
2317 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(*R);
2318 return llvm::find_if(Spellings, [](const FlattenedSpelling &S) {
2319 return S.variety() == "Pragma";
2320 }) != Spellings.end();
2325 struct AttrClassDescriptor {
2326 const char * const MacroName;
2327 const char * const TableGenName;
2330 } // end anonymous namespace
2332 static const AttrClassDescriptor AttrClassDescriptors[] = {
2334 { "STMT_ATTR", "StmtAttr" },
2335 { "INHERITABLE_ATTR", "InheritableAttr" },
2336 { "INHERITABLE_PARAM_ATTR", "InheritableParamAttr" },
2337 { "PARAMETER_ABI_ATTR", "ParameterABIAttr" }
2340 static void emitDefaultDefine(raw_ostream &OS, StringRef name,
2341 const char *superName) {
2342 OS << "#ifndef " << name << "\n";
2343 OS << "#define " << name << "(NAME) ";
2344 if (superName) OS << superName << "(NAME)";
2345 OS << "\n#endif\n\n";
2350 /// A class of attributes.
2352 const AttrClassDescriptor &Descriptor;
2354 AttrClass *SuperClass = nullptr;
2355 std::vector<AttrClass*> SubClasses;
2356 std::vector<Record*> Attrs;
2358 AttrClass(const AttrClassDescriptor &Descriptor, Record *R)
2359 : Descriptor(Descriptor), TheRecord(R) {}
2361 void emitDefaultDefines(raw_ostream &OS) const {
2362 // Default the macro unless this is a root class (i.e. Attr).
2364 emitDefaultDefine(OS, Descriptor.MacroName,
2365 SuperClass->Descriptor.MacroName);
2369 void emitUndefs(raw_ostream &OS) const {
2370 OS << "#undef " << Descriptor.MacroName << "\n";
2373 void emitAttrList(raw_ostream &OS) const {
2374 for (auto SubClass : SubClasses) {
2375 SubClass->emitAttrList(OS);
2378 ::emitAttrList(OS, Descriptor.MacroName, Attrs);
2381 void classifyAttrOnRoot(Record *Attr) {
2382 bool result = classifyAttr(Attr);
2383 assert(result && "failed to classify on root"); (void) result;
2386 void emitAttrRange(raw_ostream &OS) const {
2387 OS << "ATTR_RANGE(" << Descriptor.TableGenName
2388 << ", " << getFirstAttr()->getName()
2389 << ", " << getLastAttr()->getName() << ")\n";
2393 bool classifyAttr(Record *Attr) {
2394 // Check all the subclasses.
2395 for (auto SubClass : SubClasses) {
2396 if (SubClass->classifyAttr(Attr))
2400 // It's not more specific than this class, but it might still belong here.
2401 if (Attr->isSubClassOf(TheRecord)) {
2402 Attrs.push_back(Attr);
2409 Record *getFirstAttr() const {
2410 if (!SubClasses.empty())
2411 return SubClasses.front()->getFirstAttr();
2412 return Attrs.front();
2415 Record *getLastAttr() const {
2417 return Attrs.back();
2418 return SubClasses.back()->getLastAttr();
2422 /// The entire hierarchy of attribute classes.
2423 class AttrClassHierarchy {
2424 std::vector<std::unique_ptr<AttrClass>> Classes;
2427 AttrClassHierarchy(RecordKeeper &Records) {
2428 // Find records for all the classes.
2429 for (auto &Descriptor : AttrClassDescriptors) {
2430 Record *ClassRecord = Records.getClass(Descriptor.TableGenName);
2431 AttrClass *Class = new AttrClass(Descriptor, ClassRecord);
2432 Classes.emplace_back(Class);
2435 // Link up the hierarchy.
2436 for (auto &Class : Classes) {
2437 if (AttrClass *SuperClass = findSuperClass(Class->TheRecord)) {
2438 Class->SuperClass = SuperClass;
2439 SuperClass->SubClasses.push_back(Class.get());
2444 for (auto i = Classes.begin(), e = Classes.end(); i != e; ++i) {
2445 assert((i == Classes.begin()) == ((*i)->SuperClass == nullptr) &&
2446 "only the first class should be a root class!");
2451 void emitDefaultDefines(raw_ostream &OS) const {
2452 for (auto &Class : Classes) {
2453 Class->emitDefaultDefines(OS);
2457 void emitUndefs(raw_ostream &OS) const {
2458 for (auto &Class : Classes) {
2459 Class->emitUndefs(OS);
2463 void emitAttrLists(raw_ostream &OS) const {
2464 // Just start from the root class.
2465 Classes[0]->emitAttrList(OS);
2468 void emitAttrRanges(raw_ostream &OS) const {
2469 for (auto &Class : Classes)
2470 Class->emitAttrRange(OS);
2473 void classifyAttr(Record *Attr) {
2474 // Add the attribute to the root class.
2475 Classes[0]->classifyAttrOnRoot(Attr);
2479 AttrClass *findClassByRecord(Record *R) const {
2480 for (auto &Class : Classes) {
2481 if (Class->TheRecord == R)
2487 AttrClass *findSuperClass(Record *R) const {
2488 // TableGen flattens the superclass list, so we just need to walk it
2490 auto SuperClasses = R->getSuperClasses();
2491 for (signed i = 0, e = SuperClasses.size(); i != e; ++i) {
2492 auto SuperClass = findClassByRecord(SuperClasses[e - i - 1].first);
2493 if (SuperClass) return SuperClass;
2499 } // end anonymous namespace
2503 // Emits the enumeration list for attributes.
2504 void EmitClangAttrList(RecordKeeper &Records, raw_ostream &OS) {
2505 emitSourceFileHeader("List of all attributes that Clang recognizes", OS);
2507 AttrClassHierarchy Hierarchy(Records);
2509 // Add defaulting macro definitions.
2510 Hierarchy.emitDefaultDefines(OS);
2511 emitDefaultDefine(OS, "PRAGMA_SPELLING_ATTR", nullptr);
2513 std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
2514 std::vector<Record *> PragmaAttrs;
2515 for (auto *Attr : Attrs) {
2516 if (!Attr->getValueAsBit("ASTNode"))
2519 // Add the attribute to the ad-hoc groups.
2520 if (AttrHasPragmaSpelling(Attr))
2521 PragmaAttrs.push_back(Attr);
2523 // Place it in the hierarchy.
2524 Hierarchy.classifyAttr(Attr);
2527 // Emit the main attribute list.
2528 Hierarchy.emitAttrLists(OS);
2530 // Emit the ad hoc groups.
2531 emitAttrList(OS, "PRAGMA_SPELLING_ATTR", PragmaAttrs);
2533 // Emit the attribute ranges.
2534 OS << "#ifdef ATTR_RANGE\n";
2535 Hierarchy.emitAttrRanges(OS);
2536 OS << "#undef ATTR_RANGE\n";
2539 Hierarchy.emitUndefs(OS);
2540 OS << "#undef PRAGMA_SPELLING_ATTR\n";
2543 // Emits the enumeration list for attributes.
2544 void EmitClangAttrSubjectMatchRuleList(RecordKeeper &Records, raw_ostream &OS) {
2545 emitSourceFileHeader(
2546 "List of all attribute subject matching rules that Clang recognizes", OS);
2547 PragmaClangAttributeSupport &PragmaAttributeSupport =
2548 getPragmaAttributeSupport(Records);
2549 emitDefaultDefine(OS, "ATTR_MATCH_RULE", nullptr);
2550 PragmaAttributeSupport.emitMatchRuleList(OS);
2551 OS << "#undef ATTR_MATCH_RULE\n";
2554 // Emits the code to read an attribute from a precompiled header.
2555 void EmitClangAttrPCHRead(RecordKeeper &Records, raw_ostream &OS) {
2556 emitSourceFileHeader("Attribute deserialization code", OS);
2558 Record *InhClass = Records.getClass("InheritableAttr");
2559 std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr"),
2561 std::vector<std::unique_ptr<Argument>> Args;
2563 OS << " switch (Kind) {\n";
2564 for (const auto *Attr : Attrs) {
2565 const Record &R = *Attr;
2566 if (!R.getValueAsBit("ASTNode"))
2569 OS << " case attr::" << R.getName() << ": {\n";
2570 if (R.isSubClassOf(InhClass))
2571 OS << " bool isInherited = Record.readInt();\n";
2572 OS << " bool isImplicit = Record.readInt();\n";
2573 OS << " unsigned Spelling = Record.readInt();\n";
2574 ArgRecords = R.getValueAsListOfDefs("Args");
2576 for (const auto *Arg : ArgRecords) {
2577 Args.emplace_back(createArgument(*Arg, R.getName()));
2578 Args.back()->writePCHReadDecls(OS);
2580 OS << " New = new (Context) " << R.getName() << "Attr(Range, Context";
2581 for (auto const &ri : Args) {
2583 ri->writePCHReadArgs(OS);
2585 OS << ", Spelling);\n";
2586 if (R.isSubClassOf(InhClass))
2587 OS << " cast<InheritableAttr>(New)->setInherited(isInherited);\n";
2588 OS << " New->setImplicit(isImplicit);\n";
2595 // Emits the code to write an attribute to a precompiled header.
2596 void EmitClangAttrPCHWrite(RecordKeeper &Records, raw_ostream &OS) {
2597 emitSourceFileHeader("Attribute serialization code", OS);
2599 Record *InhClass = Records.getClass("InheritableAttr");
2600 std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr"), Args;
2602 OS << " switch (A->getKind()) {\n";
2603 for (const auto *Attr : Attrs) {
2604 const Record &R = *Attr;
2605 if (!R.getValueAsBit("ASTNode"))
2607 OS << " case attr::" << R.getName() << ": {\n";
2608 Args = R.getValueAsListOfDefs("Args");
2609 if (R.isSubClassOf(InhClass) || !Args.empty())
2610 OS << " const auto *SA = cast<" << R.getName()
2612 if (R.isSubClassOf(InhClass))
2613 OS << " Record.push_back(SA->isInherited());\n";
2614 OS << " Record.push_back(A->isImplicit());\n";
2615 OS << " Record.push_back(A->getSpellingListIndex());\n";
2617 for (const auto *Arg : Args)
2618 createArgument(*Arg, R.getName())->writePCHWrite(OS);
2625 // Generate a conditional expression to check if the current target satisfies
2626 // the conditions for a TargetSpecificAttr record, and append the code for
2627 // those checks to the Test string. If the FnName string pointer is non-null,
2628 // append a unique suffix to distinguish this set of target checks from other
2629 // TargetSpecificAttr records.
2630 static void GenerateTargetSpecificAttrChecks(const Record *R,
2631 std::vector<StringRef> &Arches,
2633 std::string *FnName) {
2634 // It is assumed that there will be an llvm::Triple object
2635 // named "T" and a TargetInfo object named "Target" within
2636 // scope that can be used to determine whether the attribute exists in
2640 for (auto I = Arches.begin(), E = Arches.end(); I != E; ++I) {
2641 StringRef Part = *I;
2642 Test += "T.getArch() == llvm::Triple::";
2651 // If the attribute is specific to particular OSes, check those.
2652 if (!R->isValueUnset("OSes")) {
2653 // We know that there was at least one arch test, so we need to and in the
2656 std::vector<StringRef> OSes = R->getValueAsListOfStrings("OSes");
2657 for (auto I = OSes.begin(), E = OSes.end(); I != E; ++I) {
2658 StringRef Part = *I;
2660 Test += "T.getOS() == llvm::Triple::";
2670 // If one or more CXX ABIs are specified, check those as well.
2671 if (!R->isValueUnset("CXXABIs")) {
2673 std::vector<StringRef> CXXABIs = R->getValueAsListOfStrings("CXXABIs");
2674 for (auto I = CXXABIs.begin(), E = CXXABIs.end(); I != E; ++I) {
2675 StringRef Part = *I;
2676 Test += "Target.getCXXABI().getKind() == TargetCXXABI::";
2687 static void GenerateHasAttrSpellingStringSwitch(
2688 const std::vector<Record *> &Attrs, raw_ostream &OS,
2689 const std::string &Variety = "", const std::string &Scope = "") {
2690 for (const auto *Attr : Attrs) {
2691 // C++11-style attributes have specific version information associated with
2692 // them. If the attribute has no scope, the version information must not
2693 // have the default value (1), as that's incorrect. Instead, the unscoped
2694 // attribute version information should be taken from the SD-6 standing
2695 // document, which can be found at:
2696 // https://isocpp.org/std/standing-documents/sd-6-sg10-feature-test-recommendations
2699 if (Variety == "CXX11") {
2700 std::vector<Record *> Spellings = Attr->getValueAsListOfDefs("Spellings");
2701 for (const auto &Spelling : Spellings) {
2702 if (Spelling->getValueAsString("Variety") == "CXX11") {
2703 Version = static_cast<int>(Spelling->getValueAsInt("Version"));
2704 if (Scope.empty() && Version == 1)
2705 PrintError(Spelling->getLoc(), "C++ standard attributes must "
2706 "have valid version information.");
2713 if (Attr->isSubClassOf("TargetSpecificAttr")) {
2714 const Record *R = Attr->getValueAsDef("Target");
2715 std::vector<StringRef> Arches = R->getValueAsListOfStrings("Arches");
2716 GenerateTargetSpecificAttrChecks(R, Arches, Test, nullptr);
2718 // If this is the C++11 variety, also add in the LangOpts test.
2719 if (Variety == "CXX11")
2720 Test += " && LangOpts.CPlusPlus11";
2721 else if (Variety == "C2x")
2722 Test += " && LangOpts.DoubleSquareBracketAttributes";
2723 } else if (Variety == "CXX11")
2724 // C++11 mode should be checked against LangOpts, which is presumed to be
2725 // present in the caller.
2726 Test = "LangOpts.CPlusPlus11";
2727 else if (Variety == "C2x")
2728 Test = "LangOpts.DoubleSquareBracketAttributes";
2730 std::string TestStr =
2731 !Test.empty() ? Test + " ? " + llvm::itostr(Version) + " : 0" : "1";
2732 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(*Attr);
2733 for (const auto &S : Spellings)
2734 if (Variety.empty() || (Variety == S.variety() &&
2735 (Scope.empty() || Scope == S.nameSpace())))
2736 OS << " .Case(\"" << S.name() << "\", " << TestStr << ")\n";
2738 OS << " .Default(0);\n";
2741 // Emits the list of spellings for attributes.
2742 void EmitClangAttrHasAttrImpl(RecordKeeper &Records, raw_ostream &OS) {
2743 emitSourceFileHeader("Code to implement the __has_attribute logic", OS);
2745 // Separate all of the attributes out into four group: generic, C++11, GNU,
2746 // and declspecs. Then generate a big switch statement for each of them.
2747 std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
2748 std::vector<Record *> Declspec, Microsoft, GNU, Pragma;
2749 std::map<std::string, std::vector<Record *>> CXX, C2x;
2751 // Walk over the list of all attributes, and split them out based on the
2752 // spelling variety.
2753 for (auto *R : Attrs) {
2754 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(*R);
2755 for (const auto &SI : Spellings) {
2756 const std::string &Variety = SI.variety();
2757 if (Variety == "GNU")
2759 else if (Variety == "Declspec")
2760 Declspec.push_back(R);
2761 else if (Variety == "Microsoft")
2762 Microsoft.push_back(R);
2763 else if (Variety == "CXX11")
2764 CXX[SI.nameSpace()].push_back(R);
2765 else if (Variety == "C2x")
2766 C2x[SI.nameSpace()].push_back(R);
2767 else if (Variety == "Pragma")
2768 Pragma.push_back(R);
2772 OS << "const llvm::Triple &T = Target.getTriple();\n";
2773 OS << "switch (Syntax) {\n";
2774 OS << "case AttrSyntax::GNU:\n";
2775 OS << " return llvm::StringSwitch<int>(Name)\n";
2776 GenerateHasAttrSpellingStringSwitch(GNU, OS, "GNU");
2777 OS << "case AttrSyntax::Declspec:\n";
2778 OS << " return llvm::StringSwitch<int>(Name)\n";
2779 GenerateHasAttrSpellingStringSwitch(Declspec, OS, "Declspec");
2780 OS << "case AttrSyntax::Microsoft:\n";
2781 OS << " return llvm::StringSwitch<int>(Name)\n";
2782 GenerateHasAttrSpellingStringSwitch(Microsoft, OS, "Microsoft");
2783 OS << "case AttrSyntax::Pragma:\n";
2784 OS << " return llvm::StringSwitch<int>(Name)\n";
2785 GenerateHasAttrSpellingStringSwitch(Pragma, OS, "Pragma");
2786 auto fn = [&OS](const char *Spelling, const char *Variety,
2787 const std::map<std::string, std::vector<Record *>> &List) {
2788 OS << "case AttrSyntax::" << Variety << ": {\n";
2789 // C++11-style attributes are further split out based on the Scope.
2790 for (auto I = List.cbegin(), E = List.cend(); I != E; ++I) {
2791 if (I != List.cbegin())
2793 if (I->first.empty())
2794 OS << "if (!Scope || Scope->getName() == \"\") {\n";
2796 OS << "if (Scope->getName() == \"" << I->first << "\") {\n";
2797 OS << " return llvm::StringSwitch<int>(Name)\n";
2798 GenerateHasAttrSpellingStringSwitch(I->second, OS, Spelling, I->first);
2801 OS << "\n} break;\n";
2803 fn("CXX11", "CXX", CXX);
2804 fn("C2x", "C", C2x);
2808 void EmitClangAttrSpellingListIndex(RecordKeeper &Records, raw_ostream &OS) {
2809 emitSourceFileHeader("Code to translate different attribute spellings "
2810 "into internal identifiers", OS);
2812 OS << " switch (AttrKind) {\n";
2814 ParsedAttrMap Attrs = getParsedAttrList(Records);
2815 for (const auto &I : Attrs) {
2816 const Record &R = *I.second;
2817 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(R);
2818 OS << " case AT_" << I.first << ": {\n";
2819 for (unsigned I = 0; I < Spellings.size(); ++ I) {
2820 OS << " if (Name == \"" << Spellings[I].name() << "\" && "
2822 << StringSwitch<unsigned>(Spellings[I].variety())
2826 .Case("Declspec", 3)
2827 .Case("Microsoft", 4)
2831 << " && Scope == \"" << Spellings[I].nameSpace() << "\")\n"
2832 << " return " << I << ";\n";
2840 OS << " return 0;\n";
2843 // Emits code used by RecursiveASTVisitor to visit attributes
2844 void EmitClangAttrASTVisitor(RecordKeeper &Records, raw_ostream &OS) {
2845 emitSourceFileHeader("Used by RecursiveASTVisitor to visit attributes.", OS);
2847 std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr");
2849 // Write method declarations for Traverse* methods.
2850 // We emit this here because we only generate methods for attributes that
2851 // are declared as ASTNodes.
2852 OS << "#ifdef ATTR_VISITOR_DECLS_ONLY\n\n";
2853 for (const auto *Attr : Attrs) {
2854 const Record &R = *Attr;
2855 if (!R.getValueAsBit("ASTNode"))
2857 OS << " bool Traverse"
2858 << R.getName() << "Attr(" << R.getName() << "Attr *A);\n";
2860 << R.getName() << "Attr(" << R.getName() << "Attr *A) {\n"
2861 << " return true; \n"
2864 OS << "\n#else // ATTR_VISITOR_DECLS_ONLY\n\n";
2866 // Write individual Traverse* methods for each attribute class.
2867 for (const auto *Attr : Attrs) {
2868 const Record &R = *Attr;
2869 if (!R.getValueAsBit("ASTNode"))
2872 OS << "template <typename Derived>\n"
2873 << "bool VISITORCLASS<Derived>::Traverse"
2874 << R.getName() << "Attr(" << R.getName() << "Attr *A) {\n"
2875 << " if (!getDerived().VisitAttr(A))\n"
2876 << " return false;\n"
2877 << " if (!getDerived().Visit" << R.getName() << "Attr(A))\n"
2878 << " return false;\n";
2880 std::vector<Record*> ArgRecords = R.getValueAsListOfDefs("Args");
2881 for (const auto *Arg : ArgRecords)
2882 createArgument(*Arg, R.getName())->writeASTVisitorTraversal(OS);
2884 OS << " return true;\n";
2888 // Write generic Traverse routine
2889 OS << "template <typename Derived>\n"
2890 << "bool VISITORCLASS<Derived>::TraverseAttr(Attr *A) {\n"
2892 << " return true;\n"
2894 << " switch (A->getKind()) {\n";
2896 for (const auto *Attr : Attrs) {
2897 const Record &R = *Attr;
2898 if (!R.getValueAsBit("ASTNode"))
2901 OS << " case attr::" << R.getName() << ":\n"
2902 << " return getDerived().Traverse" << R.getName() << "Attr("
2903 << "cast<" << R.getName() << "Attr>(A));\n";
2905 OS << " }\n"; // end switch
2906 OS << " llvm_unreachable(\"bad attribute kind\");\n";
2907 OS << "}\n"; // end function
2908 OS << "#endif // ATTR_VISITOR_DECLS_ONLY\n";
2911 void EmitClangAttrTemplateInstantiateHelper(const std::vector<Record *> &Attrs,
2913 bool AppliesToDecl) {
2915 OS << " switch (At->getKind()) {\n";
2916 for (const auto *Attr : Attrs) {
2917 const Record &R = *Attr;
2918 if (!R.getValueAsBit("ASTNode"))
2920 OS << " case attr::" << R.getName() << ": {\n";
2921 bool ShouldClone = R.getValueAsBit("Clone") &&
2923 R.getValueAsBit("MeaningfulToClassTemplateDefinition"));
2926 OS << " return nullptr;\n";
2931 OS << " const auto *A = cast<"
2932 << R.getName() << "Attr>(At);\n";
2933 bool TDependent = R.getValueAsBit("TemplateDependent");
2936 OS << " return A->clone(C);\n";
2941 std::vector<Record*> ArgRecords = R.getValueAsListOfDefs("Args");
2942 std::vector<std::unique_ptr<Argument>> Args;
2943 Args.reserve(ArgRecords.size());
2945 for (const auto *ArgRecord : ArgRecords)
2946 Args.emplace_back(createArgument(*ArgRecord, R.getName()));
2948 for (auto const &ai : Args)
2949 ai->writeTemplateInstantiation(OS);
2951 OS << " return new (C) " << R.getName() << "Attr(A->getLocation(), C";
2952 for (auto const &ai : Args) {
2954 ai->writeTemplateInstantiationArgs(OS);
2956 OS << ", A->getSpellingListIndex());\n }\n";
2958 OS << " } // end switch\n"
2959 << " llvm_unreachable(\"Unknown attribute!\");\n"
2960 << " return nullptr;\n";
2963 // Emits code to instantiate dependent attributes on templates.
2964 void EmitClangAttrTemplateInstantiate(RecordKeeper &Records, raw_ostream &OS) {
2965 emitSourceFileHeader("Template instantiation code for attributes", OS);
2967 std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr");
2969 OS << "namespace clang {\n"
2970 << "namespace sema {\n\n"
2971 << "Attr *instantiateTemplateAttribute(const Attr *At, ASTContext &C, "
2973 << " const MultiLevelTemplateArgumentList &TemplateArgs) {\n";
2974 EmitClangAttrTemplateInstantiateHelper(Attrs, OS, /*AppliesToDecl*/false);
2976 << "Attr *instantiateTemplateAttributeForDecl(const Attr *At,\n"
2977 << " ASTContext &C, Sema &S,\n"
2978 << " const MultiLevelTemplateArgumentList &TemplateArgs) {\n";
2979 EmitClangAttrTemplateInstantiateHelper(Attrs, OS, /*AppliesToDecl*/true);
2981 << "} // end namespace sema\n"
2982 << "} // end namespace clang\n";
2985 // Emits the list of parsed attributes.
2986 void EmitClangAttrParsedAttrList(RecordKeeper &Records, raw_ostream &OS) {
2987 emitSourceFileHeader("List of all attributes that Clang recognizes", OS);
2989 OS << "#ifndef PARSED_ATTR\n";
2990 OS << "#define PARSED_ATTR(NAME) NAME\n";
2993 ParsedAttrMap Names = getParsedAttrList(Records);
2994 for (const auto &I : Names) {
2995 OS << "PARSED_ATTR(" << I.first << ")\n";
2999 static bool isArgVariadic(const Record &R, StringRef AttrName) {
3000 return createArgument(R, AttrName)->isVariadic();
3003 static void emitArgInfo(const Record &R, raw_ostream &OS) {
3004 // This function will count the number of arguments specified for the
3005 // attribute and emit the number of required arguments followed by the
3006 // number of optional arguments.
3007 std::vector<Record *> Args = R.getValueAsListOfDefs("Args");
3008 unsigned ArgCount = 0, OptCount = 0;
3009 bool HasVariadic = false;
3010 for (const auto *Arg : Args) {
3011 // If the arg is fake, it's the user's job to supply it: general parsing
3012 // logic shouldn't need to know anything about it.
3013 if (Arg->getValueAsBit("Fake"))
3015 Arg->getValueAsBit("Optional") ? ++OptCount : ++ArgCount;
3016 if (!HasVariadic && isArgVariadic(*Arg, R.getName()))
3020 // If there is a variadic argument, we will set the optional argument count
3021 // to its largest value. Since it's currently a 4-bit number, we set it to 15.
3022 OS << ArgCount << ", " << (HasVariadic ? 15 : OptCount);
3025 static void GenerateDefaultAppertainsTo(raw_ostream &OS) {
3026 OS << "static bool defaultAppertainsTo(Sema &, const AttributeList &,";
3027 OS << "const Decl *) {\n";
3028 OS << " return true;\n";
3032 static std::string GetDiagnosticSpelling(const Record &R) {
3033 std::string Ret = R.getValueAsString("DiagSpelling");
3037 // If we couldn't find the DiagSpelling in this object, we can check to see
3038 // if the object is one that has a base, and if it is, loop up to the Base
3039 // member recursively.
3040 std::string Super = R.getSuperClasses().back().first->getName();
3041 if (Super == "DDecl" || Super == "DStmt")
3042 return GetDiagnosticSpelling(*R.getValueAsDef("Base"));
3047 static std::string CalculateDiagnostic(const Record &S) {
3048 // If the SubjectList object has a custom diagnostic associated with it,
3049 // return that directly.
3050 const StringRef CustomDiag = S.getValueAsString("CustomDiag");
3051 if (!CustomDiag.empty())
3052 return ("\"" + Twine(CustomDiag) + "\"").str();
3054 std::vector<std::string> DiagList;
3055 std::vector<Record *> Subjects = S.getValueAsListOfDefs("Subjects");
3056 for (const auto *Subject : Subjects) {
3057 const Record &R = *Subject;
3058 // Get the diagnostic text from the Decl or Stmt node given.
3059 std::string V = GetDiagnosticSpelling(R);
3061 PrintError(R.getLoc(),
3062 "Could not determine diagnostic spelling for the node: " +
3063 R.getName() + "; please add one to DeclNodes.td");
3065 // The node may contain a list of elements itself, so split the elements
3066 // by a comma, and trim any whitespace.
3067 SmallVector<StringRef, 2> Frags;
3068 llvm::SplitString(V, Frags, ",");
3069 for (auto Str : Frags) {
3070 DiagList.push_back(Str.trim());
3075 if (DiagList.empty()) {
3076 PrintFatalError(S.getLoc(),
3077 "Could not deduce diagnostic argument for Attr subjects");
3081 // FIXME: this is not particularly good for localization purposes and ideally
3082 // should be part of the diagnostics engine itself with some sort of list
3085 // A single member of the list can be returned directly.
3086 if (DiagList.size() == 1)
3087 return '"' + DiagList.front() + '"';
3089 if (DiagList.size() == 2)
3090 return '"' + DiagList[0] + " and " + DiagList[1] + '"';
3092 // If there are more than two in the list, we serialize the first N - 1
3093 // elements with a comma. This leaves the string in the state: foo, bar,
3094 // baz (but misses quux). We can then add ", and " for the last element
3096 std::string Diag = llvm::join(DiagList.begin(), DiagList.end() - 1, ", ");
3097 return '"' + Diag + ", and " + *(DiagList.end() - 1) + '"';
3100 static std::string GetSubjectWithSuffix(const Record *R) {
3101 const std::string &B = R->getName();
3102 if (B == "DeclBase")
3107 static std::string functionNameForCustomAppertainsTo(const Record &Subject) {
3108 return "is" + Subject.getName().str();
3111 static std::string GenerateCustomAppertainsTo(const Record &Subject,
3113 std::string FnName = functionNameForCustomAppertainsTo(Subject);
3115 // If this code has already been generated, simply return the previous
3117 static std::set<std::string> CustomSubjectSet;
3118 auto I = CustomSubjectSet.find(FnName);
3119 if (I != CustomSubjectSet.end())
3122 Record *Base = Subject.getValueAsDef("Base");
3124 // Not currently support custom subjects within custom subjects.
3125 if (Base->isSubClassOf("SubsetSubject")) {
3126 PrintFatalError(Subject.getLoc(),
3127 "SubsetSubjects within SubsetSubjects is not supported");
3131 OS << "static bool " << FnName << "(const Decl *D) {\n";
3132 OS << " if (const auto *S = dyn_cast<";
3133 OS << GetSubjectWithSuffix(Base);
3135 OS << " return " << Subject.getValueAsString("CheckCode") << ";\n";
3136 OS << " return false;\n";
3139 CustomSubjectSet.insert(FnName);
3143 static std::string GenerateAppertainsTo(const Record &Attr, raw_ostream &OS) {
3144 // If the attribute does not contain a Subjects definition, then use the
3145 // default appertainsTo logic.
3146 if (Attr.isValueUnset("Subjects"))
3147 return "defaultAppertainsTo";
3149 const Record *SubjectObj = Attr.getValueAsDef("Subjects");
3150 std::vector<Record*> Subjects = SubjectObj->getValueAsListOfDefs("Subjects");
3152 // If the list of subjects is empty, it is assumed that the attribute
3153 // appertains to everything.
3154 if (Subjects.empty())
3155 return "defaultAppertainsTo";
3157 bool Warn = SubjectObj->getValueAsDef("Diag")->getValueAsBit("Warn");
3159 // Otherwise, generate an appertainsTo check specific to this attribute which
3160 // checks all of the given subjects against the Decl passed in. Return the
3161 // name of that check to the caller.
3162 std::string FnName = "check" + Attr.getName().str() + "AppertainsTo";
3163 std::stringstream SS;
3164 SS << "static bool " << FnName << "(Sema &S, const AttributeList &Attr, ";
3165 SS << "const Decl *D) {\n";
3167 for (auto I = Subjects.begin(), E = Subjects.end(); I != E; ++I) {
3168 // If the subject has custom code associated with it, generate a function
3169 // for it. The function cannot be inlined into this check (yet) because it
3170 // requires the subject to be of a specific type, and were that information
3171 // inlined here, it would not support an attribute with multiple custom
3173 if ((*I)->isSubClassOf("SubsetSubject")) {
3174 SS << "!" << GenerateCustomAppertainsTo(**I, OS) << "(D)";
3176 SS << "!isa<" << GetSubjectWithSuffix(*I) << ">(D)";
3183 SS << " S.Diag(Attr.getLoc(), diag::";
3184 SS << (Warn ? "warn_attribute_wrong_decl_type_str" :
3185 "err_attribute_wrong_decl_type_str");
3187 SS << " << Attr.getName() << ";
3188 SS << CalculateDiagnostic(*SubjectObj) << ";\n";
3189 SS << " return false;\n";
3191 SS << " return true;\n";
3199 emitAttributeMatchRules(PragmaClangAttributeSupport &PragmaAttributeSupport,
3201 OS << "static bool checkAttributeMatchRuleAppliesTo(const Decl *D, "
3202 << AttributeSubjectMatchRule::EnumName << " rule) {\n";
3203 OS << " switch (rule) {\n";
3204 for (const auto &Rule : PragmaAttributeSupport.Rules) {
3205 if (Rule.isAbstractRule()) {
3206 OS << " case " << Rule.getEnumValue() << ":\n";
3207 OS << " assert(false && \"Abstract matcher rule isn't allowed\");\n";
3208 OS << " return false;\n";
3211 std::vector<Record *> Subjects = Rule.getSubjects();
3212 assert(!Subjects.empty() && "Missing subjects");
3213 OS << " case " << Rule.getEnumValue() << ":\n";
3215 for (auto I = Subjects.begin(), E = Subjects.end(); I != E; ++I) {
3216 // If the subject has custom code associated with it, use the function
3217 // that was generated for GenerateAppertainsTo to check if the declaration
3219 if ((*I)->isSubClassOf("SubsetSubject"))
3220 OS << functionNameForCustomAppertainsTo(**I) << "(D)";
3222 OS << "isa<" << GetSubjectWithSuffix(*I) << ">(D)";
3230 OS << " llvm_unreachable(\"Invalid match rule\");\nreturn false;\n";
3234 static void GenerateDefaultLangOptRequirements(raw_ostream &OS) {
3235 OS << "static bool defaultDiagnoseLangOpts(Sema &, ";
3236 OS << "const AttributeList &) {\n";
3237 OS << " return true;\n";
3241 static std::string GenerateLangOptRequirements(const Record &R,
3243 // If the attribute has an empty or unset list of language requirements,
3244 // return the default handler.
3245 std::vector<Record *> LangOpts = R.getValueAsListOfDefs("LangOpts");
3246 if (LangOpts.empty())
3247 return "defaultDiagnoseLangOpts";
3249 // Generate the test condition, as well as a unique function name for the
3250 // diagnostic test. The list of options should usually be short (one or two
3251 // options), and the uniqueness isn't strictly necessary (it is just for
3252 // codegen efficiency).
3253 std::string FnName = "check", Test;
3254 for (auto I = LangOpts.begin(), E = LangOpts.end(); I != E; ++I) {
3255 const StringRef Part = (*I)->getValueAsString("Name");
3256 if ((*I)->getValueAsBit("Negated")) {
3260 Test += "S.LangOpts.";
3266 FnName += "LangOpts";
3268 // If this code has already been generated, simply return the previous
3270 static std::set<std::string> CustomLangOptsSet;
3271 auto I = CustomLangOptsSet.find(FnName);
3272 if (I != CustomLangOptsSet.end())
3275 OS << "static bool " << FnName << "(Sema &S, const AttributeList &Attr) {\n";
3276 OS << " if (" << Test << ")\n";
3277 OS << " return true;\n\n";
3278 OS << " S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) ";
3279 OS << "<< Attr.getName();\n";
3280 OS << " return false;\n";
3283 CustomLangOptsSet.insert(FnName);
3287 static void GenerateDefaultTargetRequirements(raw_ostream &OS) {
3288 OS << "static bool defaultTargetRequirements(const TargetInfo &) {\n";
3289 OS << " return true;\n";
3293 static std::string GenerateTargetRequirements(const Record &Attr,
3294 const ParsedAttrMap &Dupes,
3296 // If the attribute is not a target specific attribute, return the default
3298 if (!Attr.isSubClassOf("TargetSpecificAttr"))
3299 return "defaultTargetRequirements";
3301 // Get the list of architectures to be tested for.
3302 const Record *R = Attr.getValueAsDef("Target");
3303 std::vector<StringRef> Arches = R->getValueAsListOfStrings("Arches");
3304 if (Arches.empty()) {
3305 PrintError(Attr.getLoc(), "Empty list of target architectures for a "
3306 "target-specific attr");
3307 return "defaultTargetRequirements";
3310 // If there are other attributes which share the same parsed attribute kind,
3311 // such as target-specific attributes with a shared spelling, collapse the
3312 // duplicate architectures. This is required because a shared target-specific
3313 // attribute has only one AttributeList::Kind enumeration value, but it
3314 // applies to multiple target architectures. In order for the attribute to be
3315 // considered valid, all of its architectures need to be included.
3316 if (!Attr.isValueUnset("ParseKind")) {
3317 const StringRef APK = Attr.getValueAsString("ParseKind");
3318 for (const auto &I : Dupes) {
3319 if (I.first == APK) {
3320 std::vector<StringRef> DA =
3321 I.second->getValueAsDef("Target")->getValueAsListOfStrings(
3323 Arches.insert(Arches.end(), DA.begin(), DA.end());
3328 std::string FnName = "isTarget";
3330 GenerateTargetSpecificAttrChecks(R, Arches, Test, &FnName);
3332 // If this code has already been generated, simply return the previous
3334 static std::set<std::string> CustomTargetSet;
3335 auto I = CustomTargetSet.find(FnName);
3336 if (I != CustomTargetSet.end())
3339 OS << "static bool " << FnName << "(const TargetInfo &Target) {\n";
3340 OS << " const llvm::Triple &T = Target.getTriple();\n";
3341 OS << " return " << Test << ";\n";
3344 CustomTargetSet.insert(FnName);
3348 static void GenerateDefaultSpellingIndexToSemanticSpelling(raw_ostream &OS) {
3349 OS << "static unsigned defaultSpellingIndexToSemanticSpelling("
3350 << "const AttributeList &Attr) {\n";
3351 OS << " return UINT_MAX;\n";
3355 static std::string GenerateSpellingIndexToSemanticSpelling(const Record &Attr,
3357 // If the attribute does not have a semantic form, we can bail out early.
3358 if (!Attr.getValueAsBit("ASTNode"))
3359 return "defaultSpellingIndexToSemanticSpelling";
3361 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(Attr);
3363 // If there are zero or one spellings, or all of the spellings share the same
3364 // name, we can also bail out early.
3365 if (Spellings.size() <= 1 || SpellingNamesAreCommon(Spellings))
3366 return "defaultSpellingIndexToSemanticSpelling";
3368 // Generate the enumeration we will use for the mapping.
3369 SemanticSpellingMap SemanticToSyntacticMap;
3370 std::string Enum = CreateSemanticSpellings(Spellings, SemanticToSyntacticMap);
3371 std::string Name = Attr.getName().str() + "AttrSpellingMap";
3373 OS << "static unsigned " << Name << "(const AttributeList &Attr) {\n";
3375 OS << " unsigned Idx = Attr.getAttributeSpellingListIndex();\n";
3376 WriteSemanticSpellingSwitch("Idx", SemanticToSyntacticMap, OS);
3382 static bool IsKnownToGCC(const Record &Attr) {
3383 // Look at the spellings for this subject; if there are any spellings which
3384 // claim to be known to GCC, the attribute is known to GCC.
3385 return llvm::any_of(
3386 GetFlattenedSpellings(Attr),
3387 [](const FlattenedSpelling &S) { return S.knownToGCC(); });
3390 /// Emits the parsed attribute helpers
3391 void EmitClangAttrParsedAttrImpl(RecordKeeper &Records, raw_ostream &OS) {
3392 emitSourceFileHeader("Parsed attribute helpers", OS);
3394 PragmaClangAttributeSupport &PragmaAttributeSupport =
3395 getPragmaAttributeSupport(Records);
3397 // Get the list of parsed attributes, and accept the optional list of
3398 // duplicates due to the ParseKind.
3399 ParsedAttrMap Dupes;
3400 ParsedAttrMap Attrs = getParsedAttrList(Records, &Dupes);
3402 // Generate the default appertainsTo, target and language option diagnostic,
3403 // and spelling list index mapping methods.
3404 GenerateDefaultAppertainsTo(OS);
3405 GenerateDefaultLangOptRequirements(OS);
3406 GenerateDefaultTargetRequirements(OS);
3407 GenerateDefaultSpellingIndexToSemanticSpelling(OS);
3409 // Generate the appertainsTo diagnostic methods and write their names into
3410 // another mapping. At the same time, generate the AttrInfoMap object
3411 // contents. Due to the reliance on generated code, use separate streams so
3412 // that code will not be interleaved.
3414 raw_string_ostream SS {Buffer};
3415 for (auto I = Attrs.begin(), E = Attrs.end(); I != E; ++I) {
3416 // TODO: If the attribute's kind appears in the list of duplicates, that is
3417 // because it is a target-specific attribute that appears multiple times.
3418 // It would be beneficial to test whether the duplicates are "similar
3419 // enough" to each other to not cause problems. For instance, check that
3420 // the spellings are identical, and custom parsing rules match, etc.
3422 // We need to generate struct instances based off ParsedAttrInfo from
3423 // AttributeList.cpp.
3425 emitArgInfo(*I->second, SS);
3426 SS << ", " << I->second->getValueAsBit("HasCustomParsing");
3427 SS << ", " << I->second->isSubClassOf("TargetSpecificAttr");
3428 SS << ", " << I->second->isSubClassOf("TypeAttr");
3429 SS << ", " << I->second->isSubClassOf("StmtAttr");
3430 SS << ", " << IsKnownToGCC(*I->second);
3431 SS << ", " << PragmaAttributeSupport.isAttributedSupported(*I->second);
3432 SS << ", " << GenerateAppertainsTo(*I->second, OS);
3433 SS << ", " << GenerateLangOptRequirements(*I->second, OS);
3434 SS << ", " << GenerateTargetRequirements(*I->second, Dupes, OS);
3435 SS << ", " << GenerateSpellingIndexToSemanticSpelling(*I->second, OS);
3437 << PragmaAttributeSupport.generateStrictConformsTo(*I->second, OS);
3443 SS << " // AT_" << I->first << "\n";
3446 OS << "static const ParsedAttrInfo AttrInfoMap[AttributeList::UnknownAttribute + 1] = {\n";
3450 // Generate the attribute match rules.
3451 emitAttributeMatchRules(PragmaAttributeSupport, OS);
3454 // Emits the kind list of parsed attributes
3455 void EmitClangAttrParsedAttrKinds(RecordKeeper &Records, raw_ostream &OS) {
3456 emitSourceFileHeader("Attribute name matcher", OS);
3458 std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
3459 std::vector<StringMatcher::StringPair> GNU, Declspec, Microsoft, CXX11,
3460 Keywords, Pragma, C2x;
3461 std::set<std::string> Seen;
3462 for (const auto *A : Attrs) {
3463 const Record &Attr = *A;
3465 bool SemaHandler = Attr.getValueAsBit("SemaHandler");
3466 bool Ignored = Attr.getValueAsBit("Ignored");
3467 if (SemaHandler || Ignored) {
3468 // Attribute spellings can be shared between target-specific attributes,
3469 // and can be shared between syntaxes for the same attribute. For
3470 // instance, an attribute can be spelled GNU<"interrupt"> for an ARM-
3471 // specific attribute, or MSP430-specific attribute. Additionally, an
3472 // attribute can be spelled GNU<"dllexport"> and Declspec<"dllexport">
3473 // for the same semantic attribute. Ultimately, we need to map each of
3474 // these to a single AttributeList::Kind value, but the StringMatcher
3475 // class cannot handle duplicate match strings. So we generate a list of
3476 // string to match based on the syntax, and emit multiple string matchers
3477 // depending on the syntax used.
3478 std::string AttrName;
3479 if (Attr.isSubClassOf("TargetSpecificAttr") &&
3480 !Attr.isValueUnset("ParseKind")) {
3481 AttrName = Attr.getValueAsString("ParseKind");
3482 if (Seen.find(AttrName) != Seen.end())
3484 Seen.insert(AttrName);
3486 AttrName = NormalizeAttrName(StringRef(Attr.getName())).str();
3488 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(Attr);
3489 for (const auto &S : Spellings) {
3490 const std::string &RawSpelling = S.name();
3491 std::vector<StringMatcher::StringPair> *Matches = nullptr;
3492 std::string Spelling;
3493 const std::string &Variety = S.variety();
3494 if (Variety == "CXX11") {
3496 Spelling += S.nameSpace();
3498 } else if (Variety == "C2x") {
3500 Spelling += S.nameSpace();
3502 } else if (Variety == "GNU")
3504 else if (Variety == "Declspec")
3505 Matches = &Declspec;
3506 else if (Variety == "Microsoft")
3507 Matches = &Microsoft;
3508 else if (Variety == "Keyword")
3509 Matches = &Keywords;
3510 else if (Variety == "Pragma")
3513 assert(Matches && "Unsupported spelling variety found");
3515 if (Variety == "GNU")
3516 Spelling += NormalizeGNUAttrSpelling(RawSpelling);
3518 Spelling += RawSpelling;
3521 Matches->push_back(StringMatcher::StringPair(Spelling,
3522 "return AttributeList::AT_" + AttrName + ";"));
3524 Matches->push_back(StringMatcher::StringPair(Spelling,
3525 "return AttributeList::IgnoredAttribute;"));
3530 OS << "static AttributeList::Kind getAttrKind(StringRef Name, ";
3531 OS << "AttributeList::Syntax Syntax) {\n";
3532 OS << " if (AttributeList::AS_GNU == Syntax) {\n";
3533 StringMatcher("Name", GNU, OS).Emit();
3534 OS << " } else if (AttributeList::AS_Declspec == Syntax) {\n";
3535 StringMatcher("Name", Declspec, OS).Emit();
3536 OS << " } else if (AttributeList::AS_Microsoft == Syntax) {\n";
3537 StringMatcher("Name", Microsoft, OS).Emit();
3538 OS << " } else if (AttributeList::AS_CXX11 == Syntax) {\n";
3539 StringMatcher("Name", CXX11, OS).Emit();
3540 OS << " } else if (AttributeList::AS_C2x == Syntax) {\n";
3541 StringMatcher("Name", C2x, OS).Emit();
3542 OS << " } else if (AttributeList::AS_Keyword == Syntax || ";
3543 OS << "AttributeList::AS_ContextSensitiveKeyword == Syntax) {\n";
3544 StringMatcher("Name", Keywords, OS).Emit();
3545 OS << " } else if (AttributeList::AS_Pragma == Syntax) {\n";
3546 StringMatcher("Name", Pragma, OS).Emit();
3548 OS << " return AttributeList::UnknownAttribute;\n"
3552 // Emits the code to dump an attribute.
3553 void EmitClangAttrDump(RecordKeeper &Records, raw_ostream &OS) {
3554 emitSourceFileHeader("Attribute dumper", OS);
3556 OS << " switch (A->getKind()) {\n";
3557 std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr"), Args;
3558 for (const auto *Attr : Attrs) {
3559 const Record &R = *Attr;
3560 if (!R.getValueAsBit("ASTNode"))
3562 OS << " case attr::" << R.getName() << ": {\n";
3564 // If the attribute has a semantically-meaningful name (which is determined
3565 // by whether there is a Spelling enumeration for it), then write out the
3566 // spelling used for the attribute.
3567 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(R);
3568 if (Spellings.size() > 1 && !SpellingNamesAreCommon(Spellings))
3569 OS << " OS << \" \" << A->getSpelling();\n";
3571 Args = R.getValueAsListOfDefs("Args");
3572 if (!Args.empty()) {
3573 OS << " const auto *SA = cast<" << R.getName()
3575 for (const auto *Arg : Args)
3576 createArgument(*Arg, R.getName())->writeDump(OS);
3578 for (const auto *AI : Args)
3579 createArgument(*AI, R.getName())->writeDumpChildren(OS);
3588 void EmitClangAttrParserStringSwitches(RecordKeeper &Records,
3590 emitSourceFileHeader("Parser-related llvm::StringSwitch cases", OS);
3591 emitClangAttrArgContextList(Records, OS);
3592 emitClangAttrIdentifierArgList(Records, OS);
3593 emitClangAttrTypeArgList(Records, OS);
3594 emitClangAttrLateParsedList(Records, OS);
3597 void EmitClangAttrSubjectMatchRulesParserStringSwitches(RecordKeeper &Records,
3599 getPragmaAttributeSupport(Records).generateParsingHelpers(OS);
3602 class DocumentationData {
3604 const Record *Documentation;
3605 const Record *Attribute;
3606 std::string Heading;
3607 unsigned SupportedSpellings;
3609 DocumentationData(const Record &Documentation, const Record &Attribute,
3610 const std::pair<std::string, unsigned> HeadingAndKinds)
3611 : Documentation(&Documentation), Attribute(&Attribute),
3612 Heading(std::move(HeadingAndKinds.first)),
3613 SupportedSpellings(HeadingAndKinds.second) {}
3616 static void WriteCategoryHeader(const Record *DocCategory,
3618 const StringRef Name = DocCategory->getValueAsString("Name");
3619 OS << Name << "\n" << std::string(Name.size(), '=') << "\n";
3621 // If there is content, print that as well.
3622 const StringRef ContentStr = DocCategory->getValueAsString("Content");
3623 // Trim leading and trailing newlines and spaces.
3624 OS << ContentStr.trim();
3639 static std::pair<std::string, unsigned>
3640 GetAttributeHeadingAndSpellingKinds(const Record &Documentation,
3641 const Record &Attribute) {
3642 // FIXME: there is no way to have a per-spelling category for the attribute
3643 // documentation. This may not be a limiting factor since the spellings
3644 // should generally be consistently applied across the category.
3646 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(Attribute);
3648 // Determine the heading to be used for this attribute.
3649 std::string Heading = Documentation.getValueAsString("Heading");
3650 bool CustomHeading = !Heading.empty();
3651 if (Heading.empty()) {
3652 // If there's only one spelling, we can simply use that.
3653 if (Spellings.size() == 1)
3654 Heading = Spellings.begin()->name();
3656 std::set<std::string> Uniques;
3657 for (auto I = Spellings.begin(), E = Spellings.end();
3658 I != E && Uniques.size() <= 1; ++I) {
3659 std::string Spelling = NormalizeNameForSpellingComparison(I->name());
3660 Uniques.insert(Spelling);
3662 // If the semantic map has only one spelling, that is sufficient for our
3664 if (Uniques.size() == 1)
3665 Heading = *Uniques.begin();
3669 // If the heading is still empty, it is an error.
3670 if (Heading.empty())
3671 PrintFatalError(Attribute.getLoc(),
3672 "This attribute requires a heading to be specified");
3674 // Gather a list of unique spellings; this is not the same as the semantic
3675 // spelling for the attribute. Variations in underscores and other non-
3676 // semantic characters are still acceptable.
3677 std::vector<std::string> Names;
3679 unsigned SupportedSpellings = 0;
3680 for (const auto &I : Spellings) {
3681 SpellingKind Kind = StringSwitch<SpellingKind>(I.variety())
3683 .Case("CXX11", CXX11)
3685 .Case("Declspec", Declspec)
3686 .Case("Microsoft", Microsoft)
3687 .Case("Keyword", Keyword)
3688 .Case("Pragma", Pragma);
3690 // Mask in the supported spelling.
3691 SupportedSpellings |= Kind;
3694 if ((Kind == CXX11 || Kind == C2x) && !I.nameSpace().empty())
3695 Name = I.nameSpace() + "::";
3698 // If this name is the same as the heading, do not add it.
3699 if (Name != Heading)
3700 Names.push_back(Name);
3703 // Print out the heading for the attribute. If there are alternate spellings,
3704 // then display those after the heading.
3705 if (!CustomHeading && !Names.empty()) {
3707 for (auto I = Names.begin(), E = Names.end(); I != E; ++I) {
3708 if (I != Names.begin())
3714 if (!SupportedSpellings)
3715 PrintFatalError(Attribute.getLoc(),
3716 "Attribute has no supported spellings; cannot be "
3718 return std::make_pair(std::move(Heading), SupportedSpellings);
3721 static void WriteDocumentation(RecordKeeper &Records,
3722 const DocumentationData &Doc, raw_ostream &OS) {
3723 OS << Doc.Heading << "\n" << std::string(Doc.Heading.length(), '-') << "\n";
3725 // List what spelling syntaxes the attribute supports.
3726 OS << ".. csv-table:: Supported Syntaxes\n";
3727 OS << " :header: \"GNU\", \"C++11\", \"C2x\", \"__declspec\", \"Keyword\",";
3728 OS << " \"Pragma\", \"Pragma clang attribute\"\n\n";
3730 if (Doc.SupportedSpellings & GNU) OS << "X";
3732 if (Doc.SupportedSpellings & CXX11) OS << "X";
3734 if (Doc.SupportedSpellings & C2x) OS << "X";
3736 if (Doc.SupportedSpellings & Declspec) OS << "X";
3738 if (Doc.SupportedSpellings & Keyword) OS << "X";
3740 if (Doc.SupportedSpellings & Pragma) OS << "X";
3742 if (getPragmaAttributeSupport(Records).isAttributedSupported(*Doc.Attribute))
3746 // If the attribute is deprecated, print a message about it, and possibly
3747 // provide a replacement attribute.
3748 if (!Doc.Documentation->isValueUnset("Deprecated")) {
3749 OS << "This attribute has been deprecated, and may be removed in a future "
3750 << "version of Clang.";
3751 const Record &Deprecated = *Doc.Documentation->getValueAsDef("Deprecated");
3752 const StringRef Replacement = Deprecated.getValueAsString("Replacement");
3753 if (!Replacement.empty())
3754 OS << " This attribute has been superseded by ``"
3755 << Replacement << "``.";
3759 const StringRef ContentStr = Doc.Documentation->getValueAsString("Content");
3760 // Trim leading and trailing newlines and spaces.
3761 OS << ContentStr.trim();
3766 void EmitClangAttrDocs(RecordKeeper &Records, raw_ostream &OS) {
3767 // Get the documentation introduction paragraph.
3768 const Record *Documentation = Records.getDef("GlobalDocumentation");
3769 if (!Documentation) {
3770 PrintFatalError("The Documentation top-level definition is missing, "
3771 "no documentation will be generated.");
3775 OS << Documentation->getValueAsString("Intro") << "\n";
3777 // Gather the Documentation lists from each of the attributes, based on the
3778 // category provided.
3779 std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
3780 std::map<const Record *, std::vector<DocumentationData>> SplitDocs;
3781 for (const auto *A : Attrs) {
3782 const Record &Attr = *A;
3783 std::vector<Record *> Docs = Attr.getValueAsListOfDefs("Documentation");
3784 for (const auto *D : Docs) {
3785 const Record &Doc = *D;
3786 const Record *Category = Doc.getValueAsDef("Category");
3787 // If the category is "undocumented", then there cannot be any other
3788 // documentation categories (otherwise, the attribute would become
3790 const StringRef Cat = Category->getValueAsString("Name");
3791 bool Undocumented = Cat == "Undocumented";
3792 if (Undocumented && Docs.size() > 1)
3793 PrintFatalError(Doc.getLoc(),
3794 "Attribute is \"Undocumented\", but has multiple "
3795 "documentation categories");
3798 SplitDocs[Category].push_back(DocumentationData(
3799 Doc, Attr, GetAttributeHeadingAndSpellingKinds(Doc, Attr)));
3803 // Having split the attributes out based on what documentation goes where,
3804 // we can begin to generate sections of documentation.
3805 for (auto &I : SplitDocs) {
3806 WriteCategoryHeader(I.first, OS);
3808 std::sort(I.second.begin(), I.second.end(),
3809 [](const DocumentationData &D1, const DocumentationData &D2) {
3810 return D1.Heading < D2.Heading;
3813 // Walk over each of the attributes in the category and write out their
3815 for (const auto &Doc : I.second)
3816 WriteDocumentation(Records, Doc, OS);
3820 void EmitTestPragmaAttributeSupportedAttributes(RecordKeeper &Records,
3822 PragmaClangAttributeSupport Support = getPragmaAttributeSupport(Records);
3823 ParsedAttrMap Attrs = getParsedAttrList(Records);
3824 unsigned NumAttrs = 0;
3825 for (const auto &I : Attrs) {
3826 if (Support.isAttributedSupported(*I.second))
3829 OS << "#pragma clang attribute supports " << NumAttrs << " attributes:\n";
3830 for (const auto &I : Attrs) {
3831 if (!Support.isAttributedSupported(*I.second))
3834 if (I.second->isValueUnset("Subjects")) {
3838 const Record *SubjectObj = I.second->getValueAsDef("Subjects");
3839 std::vector<Record *> Subjects =
3840 SubjectObj->getValueAsListOfDefs("Subjects");
3842 for (const auto &Subject : llvm::enumerate(Subjects)) {
3843 if (Subject.index())
3845 PragmaClangAttributeSupport::RuleOrAggregateRuleSet &RuleSet =
3846 Support.SubjectsToRules.find(Subject.value())->getSecond();
3847 if (RuleSet.isRule()) {
3848 OS << RuleSet.getRule().getEnumValueName();
3852 for (const auto &Rule : llvm::enumerate(RuleSet.getAggregateRuleSet())) {
3855 OS << Rule.value().getEnumValueName();
3863 } // end namespace clang