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/DenseSet.h"
16 #include "llvm/ADT/iterator_range.h"
17 #include "llvm/ADT/SmallString.h"
18 #include "llvm/ADT/STLExtras.h"
19 #include "llvm/ADT/StringExtras.h"
20 #include "llvm/ADT/StringRef.h"
21 #include "llvm/ADT/StringSwitch.h"
22 #include "llvm/Support/ErrorHandling.h"
23 #include "llvm/Support/raw_ostream.h"
24 #include "llvm/TableGen/Error.h"
25 #include "llvm/TableGen/Record.h"
26 #include "llvm/TableGen/StringMatcher.h"
27 #include "llvm/TableGen/TableGenBackend.h"
45 class FlattenedSpelling {
50 FlattenedSpelling(const std::string &Variety, const std::string &Name,
51 const std::string &Namespace, bool KnownToGCC) :
52 V(Variety), N(Name), NS(Namespace), K(KnownToGCC) {}
53 explicit FlattenedSpelling(const Record &Spelling) :
54 V(Spelling.getValueAsString("Variety")),
55 N(Spelling.getValueAsString("Name")) {
57 assert(V != "GCC" && "Given a GCC spelling, which means this hasn't been"
59 if (V == "CXX11" || V == "Pragma")
60 NS = Spelling.getValueAsString("Namespace");
62 K = Spelling.getValueAsBitOrUnset("KnownToGCC", Unset);
65 const std::string &variety() const { return V; }
66 const std::string &name() const { return N; }
67 const std::string &nameSpace() const { return NS; }
68 bool knownToGCC() const { return K; }
71 } // end anonymous namespace
73 static std::vector<FlattenedSpelling>
74 GetFlattenedSpellings(const Record &Attr) {
75 std::vector<Record *> Spellings = Attr.getValueAsListOfDefs("Spellings");
76 std::vector<FlattenedSpelling> Ret;
78 for (const auto &Spelling : Spellings) {
79 if (Spelling->getValueAsString("Variety") == "GCC") {
80 // Gin up two new spelling objects to add into the list.
81 Ret.emplace_back("GNU", Spelling->getValueAsString("Name"), "", true);
82 Ret.emplace_back("CXX11", Spelling->getValueAsString("Name"), "gnu",
85 Ret.push_back(FlattenedSpelling(*Spelling));
91 static std::string ReadPCHRecord(StringRef type) {
92 return StringSwitch<std::string>(type)
93 .EndsWith("Decl *", "GetLocalDeclAs<"
94 + std::string(type, 0, type.size()-1) + ">(F, Record[Idx++])")
95 .Case("TypeSourceInfo *", "GetTypeSourceInfo(F, Record, Idx)")
96 .Case("Expr *", "ReadExpr(F)")
97 .Case("IdentifierInfo *", "GetIdentifierInfo(F, Record, Idx)")
98 .Case("StringRef", "ReadString(Record, Idx)")
99 .Default("Record[Idx++]");
102 // Get a type that is suitable for storing an object of the specified type.
103 static StringRef getStorageType(StringRef type) {
104 return StringSwitch<StringRef>(type)
105 .Case("StringRef", "std::string")
109 // Assumes that the way to get the value is SA->getname()
110 static std::string WritePCHRecord(StringRef type, StringRef name) {
111 return "Record." + StringSwitch<std::string>(type)
112 .EndsWith("Decl *", "AddDeclRef(" + std::string(name) + ");\n")
113 .Case("TypeSourceInfo *", "AddTypeSourceInfo(" + std::string(name) + ");\n")
114 .Case("Expr *", "AddStmt(" + std::string(name) + ");\n")
115 .Case("IdentifierInfo *", "AddIdentifierRef(" + std::string(name) + ");\n")
116 .Case("StringRef", "AddString(" + std::string(name) + ");\n")
117 .Default("push_back(" + std::string(name) + ");\n");
120 // Normalize attribute name by removing leading and trailing
121 // underscores. For example, __foo, foo__, __foo__ would
123 static StringRef NormalizeAttrName(StringRef AttrName) {
124 AttrName.consume_front("__");
125 AttrName.consume_back("__");
129 // Normalize the name by removing any and all leading and trailing underscores.
130 // This is different from NormalizeAttrName in that it also handles names like
131 // _pascal and __pascal.
132 static StringRef NormalizeNameForSpellingComparison(StringRef Name) {
133 return Name.trim("_");
136 // Normalize attribute spelling only if the spelling has both leading
137 // and trailing underscores. For example, __ms_struct__ will be
138 // normalized to "ms_struct"; __cdecl will remain intact.
139 static StringRef NormalizeAttrSpelling(StringRef AttrSpelling) {
140 if (AttrSpelling.startswith("__") && AttrSpelling.endswith("__")) {
141 AttrSpelling = AttrSpelling.substr(2, AttrSpelling.size() - 4);
147 typedef std::vector<std::pair<std::string, const Record *>> ParsedAttrMap;
149 static ParsedAttrMap getParsedAttrList(const RecordKeeper &Records,
150 ParsedAttrMap *Dupes = nullptr) {
151 std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
152 std::set<std::string> Seen;
154 for (const auto *Attr : Attrs) {
155 if (Attr->getValueAsBit("SemaHandler")) {
157 if (Attr->isSubClassOf("TargetSpecificAttr") &&
158 !Attr->isValueUnset("ParseKind")) {
159 AN = Attr->getValueAsString("ParseKind");
161 // If this attribute has already been handled, it does not need to be
163 if (Seen.find(AN) != Seen.end()) {
165 Dupes->push_back(std::make_pair(AN, Attr));
170 AN = NormalizeAttrName(Attr->getName()).str();
172 R.push_back(std::make_pair(AN, Attr));
181 std::string lowerName, upperName;
187 Argument(const Record &Arg, StringRef Attr)
188 : lowerName(Arg.getValueAsString("Name")), upperName(lowerName),
189 attrName(Attr), isOpt(false), Fake(false) {
190 if (!lowerName.empty()) {
191 lowerName[0] = std::tolower(lowerName[0]);
192 upperName[0] = std::toupper(upperName[0]);
194 // Work around MinGW's macro definition of 'interface' to 'struct'. We
195 // have an attribute argument called 'Interface', so only the lower case
196 // name conflicts with the macro definition.
197 if (lowerName == "interface")
198 lowerName = "interface_";
200 virtual ~Argument() = default;
202 StringRef getLowerName() const { return lowerName; }
203 StringRef getUpperName() const { return upperName; }
204 StringRef getAttrName() const { return attrName; }
206 bool isOptional() const { return isOpt; }
207 void setOptional(bool set) { isOpt = set; }
209 bool isFake() const { return Fake; }
210 void setFake(bool fake) { Fake = fake; }
212 // These functions print the argument contents formatted in different ways.
213 virtual void writeAccessors(raw_ostream &OS) const = 0;
214 virtual void writeAccessorDefinitions(raw_ostream &OS) const {}
215 virtual void writeASTVisitorTraversal(raw_ostream &OS) const {}
216 virtual void writeCloneArgs(raw_ostream &OS) const = 0;
217 virtual void writeTemplateInstantiationArgs(raw_ostream &OS) const = 0;
218 virtual void writeTemplateInstantiation(raw_ostream &OS) const {}
219 virtual void writeCtorBody(raw_ostream &OS) const {}
220 virtual void writeCtorInitializers(raw_ostream &OS) const = 0;
221 virtual void writeCtorDefaultInitializers(raw_ostream &OS) const = 0;
222 virtual void writeCtorParameters(raw_ostream &OS) const = 0;
223 virtual void writeDeclarations(raw_ostream &OS) const = 0;
224 virtual void writePCHReadArgs(raw_ostream &OS) const = 0;
225 virtual void writePCHReadDecls(raw_ostream &OS) const = 0;
226 virtual void writePCHWrite(raw_ostream &OS) const = 0;
227 virtual void writeValue(raw_ostream &OS) const = 0;
228 virtual void writeDump(raw_ostream &OS) const = 0;
229 virtual void writeDumpChildren(raw_ostream &OS) const {}
230 virtual void writeHasChildren(raw_ostream &OS) const { OS << "false"; }
232 virtual bool isEnumArg() const { return false; }
233 virtual bool isVariadicEnumArg() const { return false; }
234 virtual bool isVariadic() const { return false; }
236 virtual void writeImplicitCtorArgs(raw_ostream &OS) const {
237 OS << getUpperName();
241 class SimpleArgument : public Argument {
245 SimpleArgument(const Record &Arg, StringRef Attr, std::string T)
246 : Argument(Arg, Attr), type(std::move(T)) {}
248 std::string getType() const { return type; }
250 void writeAccessors(raw_ostream &OS) const override {
251 OS << " " << type << " get" << getUpperName() << "() const {\n";
252 OS << " return " << getLowerName() << ";\n";
256 void writeCloneArgs(raw_ostream &OS) const override {
257 OS << getLowerName();
260 void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
261 OS << "A->get" << getUpperName() << "()";
264 void writeCtorInitializers(raw_ostream &OS) const override {
265 OS << getLowerName() << "(" << getUpperName() << ")";
268 void writeCtorDefaultInitializers(raw_ostream &OS) const override {
269 OS << getLowerName() << "()";
272 void writeCtorParameters(raw_ostream &OS) const override {
273 OS << type << " " << getUpperName();
276 void writeDeclarations(raw_ostream &OS) const override {
277 OS << type << " " << getLowerName() << ";";
280 void writePCHReadDecls(raw_ostream &OS) const override {
281 std::string read = ReadPCHRecord(type);
282 OS << " " << type << " " << getLowerName() << " = " << read << ";\n";
285 void writePCHReadArgs(raw_ostream &OS) const override {
286 OS << getLowerName();
289 void writePCHWrite(raw_ostream &OS) const override {
290 OS << " " << WritePCHRecord(type, "SA->get" +
291 std::string(getUpperName()) + "()");
294 void writeValue(raw_ostream &OS) const override {
295 if (type == "FunctionDecl *") {
296 OS << "\" << get" << getUpperName()
297 << "()->getNameInfo().getAsString() << \"";
298 } else if (type == "IdentifierInfo *") {
301 OS << " if (get" << getUpperName() << "()) ";
304 OS << "OS << get" << getUpperName() << "()->getName();\n";
306 } else if (type == "TypeSourceInfo *") {
307 OS << "\" << get" << getUpperName() << "().getAsString() << \"";
309 OS << "\" << get" << getUpperName() << "() << \"";
313 void writeDump(raw_ostream &OS) const override {
314 if (type == "FunctionDecl *") {
315 OS << " OS << \" \";\n";
316 OS << " dumpBareDeclRef(SA->get" << getUpperName() << "());\n";
317 } else if (type == "IdentifierInfo *") {
319 OS << " if (SA->get" << getUpperName() << "())\n ";
320 OS << " OS << \" \" << SA->get" << getUpperName()
321 << "()->getName();\n";
322 } else if (type == "TypeSourceInfo *") {
323 OS << " OS << \" \" << SA->get" << getUpperName()
324 << "().getAsString();\n";
325 } else if (type == "bool") {
326 OS << " if (SA->get" << getUpperName() << "()) OS << \" "
327 << getUpperName() << "\";\n";
328 } else if (type == "int" || type == "unsigned") {
329 OS << " OS << \" \" << SA->get" << getUpperName() << "();\n";
331 llvm_unreachable("Unknown SimpleArgument type!");
336 class DefaultSimpleArgument : public SimpleArgument {
340 DefaultSimpleArgument(const Record &Arg, StringRef Attr,
341 std::string T, int64_t Default)
342 : SimpleArgument(Arg, Attr, T), Default(Default) {}
344 void writeAccessors(raw_ostream &OS) const override {
345 SimpleArgument::writeAccessors(OS);
347 OS << "\n\n static const " << getType() << " Default" << getUpperName()
349 if (getType() == "bool")
350 OS << (Default != 0 ? "true" : "false");
357 class StringArgument : public Argument {
359 StringArgument(const Record &Arg, StringRef Attr)
360 : Argument(Arg, Attr)
363 void writeAccessors(raw_ostream &OS) const override {
364 OS << " llvm::StringRef get" << getUpperName() << "() const {\n";
365 OS << " return llvm::StringRef(" << getLowerName() << ", "
366 << getLowerName() << "Length);\n";
368 OS << " unsigned get" << getUpperName() << "Length() const {\n";
369 OS << " return " << getLowerName() << "Length;\n";
371 OS << " void set" << getUpperName()
372 << "(ASTContext &C, llvm::StringRef S) {\n";
373 OS << " " << getLowerName() << "Length = S.size();\n";
374 OS << " this->" << getLowerName() << " = new (C, 1) char ["
375 << getLowerName() << "Length];\n";
376 OS << " if (!S.empty())\n";
377 OS << " std::memcpy(this->" << getLowerName() << ", S.data(), "
378 << getLowerName() << "Length);\n";
382 void writeCloneArgs(raw_ostream &OS) const override {
383 OS << "get" << getUpperName() << "()";
386 void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
387 OS << "A->get" << getUpperName() << "()";
390 void writeCtorBody(raw_ostream &OS) const override {
391 OS << " if (!" << getUpperName() << ".empty())\n";
392 OS << " std::memcpy(" << getLowerName() << ", " << getUpperName()
393 << ".data(), " << getLowerName() << "Length);\n";
396 void writeCtorInitializers(raw_ostream &OS) const override {
397 OS << getLowerName() << "Length(" << getUpperName() << ".size()),"
398 << getLowerName() << "(new (Ctx, 1) char[" << getLowerName()
402 void writeCtorDefaultInitializers(raw_ostream &OS) const override {
403 OS << getLowerName() << "Length(0)," << getLowerName() << "(nullptr)";
406 void writeCtorParameters(raw_ostream &OS) const override {
407 OS << "llvm::StringRef " << getUpperName();
410 void writeDeclarations(raw_ostream &OS) const override {
411 OS << "unsigned " << getLowerName() << "Length;\n";
412 OS << "char *" << getLowerName() << ";";
415 void writePCHReadDecls(raw_ostream &OS) const override {
416 OS << " std::string " << getLowerName()
417 << "= ReadString(Record, Idx);\n";
420 void writePCHReadArgs(raw_ostream &OS) const override {
421 OS << getLowerName();
424 void writePCHWrite(raw_ostream &OS) const override {
425 OS << " Record.AddString(SA->get" << getUpperName() << "());\n";
428 void writeValue(raw_ostream &OS) const override {
429 OS << "\\\"\" << get" << getUpperName() << "() << \"\\\"";
432 void writeDump(raw_ostream &OS) const override {
433 OS << " OS << \" \\\"\" << SA->get" << getUpperName()
434 << "() << \"\\\"\";\n";
438 class AlignedArgument : public Argument {
440 AlignedArgument(const Record &Arg, StringRef Attr)
441 : Argument(Arg, Attr)
444 void writeAccessors(raw_ostream &OS) const override {
445 OS << " bool is" << getUpperName() << "Dependent() const;\n";
447 OS << " unsigned get" << getUpperName() << "(ASTContext &Ctx) const;\n";
449 OS << " bool is" << getUpperName() << "Expr() const {\n";
450 OS << " return is" << getLowerName() << "Expr;\n";
453 OS << " Expr *get" << getUpperName() << "Expr() const {\n";
454 OS << " assert(is" << getLowerName() << "Expr);\n";
455 OS << " return " << getLowerName() << "Expr;\n";
458 OS << " TypeSourceInfo *get" << getUpperName() << "Type() const {\n";
459 OS << " assert(!is" << getLowerName() << "Expr);\n";
460 OS << " return " << getLowerName() << "Type;\n";
464 void writeAccessorDefinitions(raw_ostream &OS) const override {
465 OS << "bool " << getAttrName() << "Attr::is" << getUpperName()
466 << "Dependent() const {\n";
467 OS << " if (is" << getLowerName() << "Expr)\n";
468 OS << " return " << getLowerName() << "Expr && (" << getLowerName()
469 << "Expr->isValueDependent() || " << getLowerName()
470 << "Expr->isTypeDependent());\n";
472 OS << " return " << getLowerName()
473 << "Type->getType()->isDependentType();\n";
476 // FIXME: Do not do the calculation here
477 // FIXME: Handle types correctly
478 // A null pointer means maximum alignment
479 OS << "unsigned " << getAttrName() << "Attr::get" << getUpperName()
480 << "(ASTContext &Ctx) const {\n";
481 OS << " assert(!is" << getUpperName() << "Dependent());\n";
482 OS << " if (is" << getLowerName() << "Expr)\n";
483 OS << " return " << getLowerName() << "Expr ? " << getLowerName()
484 << "Expr->EvaluateKnownConstInt(Ctx).getZExtValue()"
485 << " * Ctx.getCharWidth() : "
486 << "Ctx.getTargetDefaultAlignForAttributeAligned();\n";
488 OS << " return 0; // FIXME\n";
492 void writeCloneArgs(raw_ostream &OS) const override {
493 OS << "is" << getLowerName() << "Expr, is" << getLowerName()
494 << "Expr ? static_cast<void*>(" << getLowerName()
495 << "Expr) : " << getLowerName()
499 void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
500 // FIXME: move the definition in Sema::InstantiateAttrs to here.
501 // In the meantime, aligned attributes are cloned.
504 void writeCtorBody(raw_ostream &OS) const override {
505 OS << " if (is" << getLowerName() << "Expr)\n";
506 OS << " " << getLowerName() << "Expr = reinterpret_cast<Expr *>("
507 << getUpperName() << ");\n";
509 OS << " " << getLowerName()
510 << "Type = reinterpret_cast<TypeSourceInfo *>(" << getUpperName()
514 void writeCtorInitializers(raw_ostream &OS) const override {
515 OS << "is" << getLowerName() << "Expr(Is" << getUpperName() << "Expr)";
518 void writeCtorDefaultInitializers(raw_ostream &OS) const override {
519 OS << "is" << getLowerName() << "Expr(false)";
522 void writeCtorParameters(raw_ostream &OS) const override {
523 OS << "bool Is" << getUpperName() << "Expr, void *" << getUpperName();
526 void writeImplicitCtorArgs(raw_ostream &OS) const override {
527 OS << "Is" << getUpperName() << "Expr, " << getUpperName();
530 void writeDeclarations(raw_ostream &OS) const override {
531 OS << "bool is" << getLowerName() << "Expr;\n";
533 OS << "Expr *" << getLowerName() << "Expr;\n";
534 OS << "TypeSourceInfo *" << getLowerName() << "Type;\n";
538 void writePCHReadArgs(raw_ostream &OS) const override {
539 OS << "is" << getLowerName() << "Expr, " << getLowerName() << "Ptr";
542 void writePCHReadDecls(raw_ostream &OS) const override {
543 OS << " bool is" << getLowerName() << "Expr = Record[Idx++];\n";
544 OS << " void *" << getLowerName() << "Ptr;\n";
545 OS << " if (is" << getLowerName() << "Expr)\n";
546 OS << " " << getLowerName() << "Ptr = ReadExpr(F);\n";
548 OS << " " << getLowerName()
549 << "Ptr = GetTypeSourceInfo(F, Record, Idx);\n";
552 void writePCHWrite(raw_ostream &OS) const override {
553 OS << " Record.push_back(SA->is" << getUpperName() << "Expr());\n";
554 OS << " if (SA->is" << getUpperName() << "Expr())\n";
555 OS << " Record.AddStmt(SA->get" << getUpperName() << "Expr());\n";
557 OS << " Record.AddTypeSourceInfo(SA->get" << getUpperName()
561 void writeValue(raw_ostream &OS) const override {
563 // The aligned attribute argument expression is optional.
564 OS << " if (is" << getLowerName() << "Expr && "
565 << getLowerName() << "Expr)\n";
566 OS << " " << getLowerName() << "Expr->printPretty(OS, nullptr, Policy);\n";
570 void writeDump(raw_ostream &OS) const override {}
572 void writeDumpChildren(raw_ostream &OS) const override {
573 OS << " if (SA->is" << getUpperName() << "Expr())\n";
574 OS << " dumpStmt(SA->get" << getUpperName() << "Expr());\n";
576 OS << " dumpType(SA->get" << getUpperName()
577 << "Type()->getType());\n";
580 void writeHasChildren(raw_ostream &OS) const override {
581 OS << "SA->is" << getUpperName() << "Expr()";
585 class VariadicArgument : public Argument {
586 std::string Type, ArgName, ArgSizeName, RangeName;
589 // Assumed to receive a parameter: raw_ostream OS.
590 virtual void writeValueImpl(raw_ostream &OS) const {
591 OS << " OS << Val;\n";
595 VariadicArgument(const Record &Arg, StringRef Attr, std::string T)
596 : Argument(Arg, Attr), Type(std::move(T)),
597 ArgName(getLowerName().str() + "_"), ArgSizeName(ArgName + "Size"),
598 RangeName(getLowerName()) {}
600 const std::string &getType() const { return Type; }
601 const std::string &getArgName() const { return ArgName; }
602 const std::string &getArgSizeName() const { return ArgSizeName; }
603 bool isVariadic() const override { return true; }
605 void writeAccessors(raw_ostream &OS) const override {
606 std::string IteratorType = getLowerName().str() + "_iterator";
607 std::string BeginFn = getLowerName().str() + "_begin()";
608 std::string EndFn = getLowerName().str() + "_end()";
610 OS << " typedef " << Type << "* " << IteratorType << ";\n";
611 OS << " " << IteratorType << " " << BeginFn << " const {"
612 << " return " << ArgName << "; }\n";
613 OS << " " << IteratorType << " " << EndFn << " const {"
614 << " return " << ArgName << " + " << ArgSizeName << "; }\n";
615 OS << " unsigned " << getLowerName() << "_size() const {"
616 << " return " << ArgSizeName << "; }\n";
617 OS << " llvm::iterator_range<" << IteratorType << "> " << RangeName
618 << "() const { return llvm::make_range(" << BeginFn << ", " << EndFn
622 void writeCloneArgs(raw_ostream &OS) const override {
623 OS << ArgName << ", " << ArgSizeName;
626 void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
627 // This isn't elegant, but we have to go through public methods...
628 OS << "A->" << getLowerName() << "_begin(), "
629 << "A->" << getLowerName() << "_size()";
632 void writeCtorBody(raw_ostream &OS) const override {
633 OS << " std::copy(" << getUpperName() << ", " << getUpperName()
634 << " + " << ArgSizeName << ", " << ArgName << ");\n";
637 void writeCtorInitializers(raw_ostream &OS) const override {
638 OS << ArgSizeName << "(" << getUpperName() << "Size), "
639 << ArgName << "(new (Ctx, 16) " << getType() << "["
640 << ArgSizeName << "])";
643 void writeCtorDefaultInitializers(raw_ostream &OS) const override {
644 OS << ArgSizeName << "(0), " << ArgName << "(nullptr)";
647 void writeCtorParameters(raw_ostream &OS) const override {
648 OS << getType() << " *" << getUpperName() << ", unsigned "
649 << getUpperName() << "Size";
652 void writeImplicitCtorArgs(raw_ostream &OS) const override {
653 OS << getUpperName() << ", " << getUpperName() << "Size";
656 void writeDeclarations(raw_ostream &OS) const override {
657 OS << " unsigned " << ArgSizeName << ";\n";
658 OS << " " << getType() << " *" << ArgName << ";";
661 void writePCHReadDecls(raw_ostream &OS) const override {
662 OS << " unsigned " << getLowerName() << "Size = Record[Idx++];\n";
663 OS << " SmallVector<" << getType() << ", 4> "
664 << getLowerName() << ";\n";
665 OS << " " << getLowerName() << ".reserve(" << getLowerName()
668 // If we can't store the values in the current type (if it's something
669 // like StringRef), store them in a different type and convert the
670 // container afterwards.
671 std::string StorageType = getStorageType(getType());
672 std::string StorageName = getLowerName();
673 if (StorageType != getType()) {
674 StorageName += "Storage";
675 OS << " SmallVector<" << StorageType << ", 4> "
676 << StorageName << ";\n";
677 OS << " " << StorageName << ".reserve(" << getLowerName()
681 OS << " for (unsigned i = 0; i != " << getLowerName() << "Size; ++i)\n";
682 std::string read = ReadPCHRecord(Type);
683 OS << " " << StorageName << ".push_back(" << read << ");\n";
685 if (StorageType != getType()) {
686 OS << " for (unsigned i = 0; i != " << getLowerName() << "Size; ++i)\n";
687 OS << " " << getLowerName() << ".push_back("
688 << StorageName << "[i]);\n";
692 void writePCHReadArgs(raw_ostream &OS) const override {
693 OS << getLowerName() << ".data(), " << getLowerName() << "Size";
696 void writePCHWrite(raw_ostream &OS) const override {
697 OS << " Record.push_back(SA->" << getLowerName() << "_size());\n";
698 OS << " for (auto &Val : SA->" << RangeName << "())\n";
699 OS << " " << WritePCHRecord(Type, "Val");
702 void writeValue(raw_ostream &OS) const override {
704 OS << " bool isFirst = true;\n"
705 << " for (const auto &Val : " << RangeName << "()) {\n"
706 << " if (isFirst) isFirst = false;\n"
707 << " else OS << \", \";\n";
713 void writeDump(raw_ostream &OS) const override {
714 OS << " for (const auto &Val : SA->" << RangeName << "())\n";
715 OS << " OS << \" \" << Val;\n";
719 // Unique the enums, but maintain the original declaration ordering.
720 std::vector<std::string>
721 uniqueEnumsInOrder(const std::vector<std::string> &enums) {
722 std::vector<std::string> uniques;
723 SmallDenseSet<StringRef, 8> unique_set;
724 for (const auto &i : enums) {
725 if (unique_set.insert(i).second)
726 uniques.push_back(i);
731 class EnumArgument : public Argument {
733 std::vector<std::string> values, enums, uniques;
735 EnumArgument(const Record &Arg, StringRef Attr)
736 : Argument(Arg, Attr), type(Arg.getValueAsString("Type")),
737 values(Arg.getValueAsListOfStrings("Values")),
738 enums(Arg.getValueAsListOfStrings("Enums")),
739 uniques(uniqueEnumsInOrder(enums))
741 // FIXME: Emit a proper error
742 assert(!uniques.empty());
745 bool isEnumArg() const override { return true; }
747 void writeAccessors(raw_ostream &OS) const override {
748 OS << " " << type << " get" << getUpperName() << "() const {\n";
749 OS << " return " << getLowerName() << ";\n";
753 void writeCloneArgs(raw_ostream &OS) const override {
754 OS << getLowerName();
757 void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
758 OS << "A->get" << getUpperName() << "()";
760 void writeCtorInitializers(raw_ostream &OS) const override {
761 OS << getLowerName() << "(" << getUpperName() << ")";
763 void writeCtorDefaultInitializers(raw_ostream &OS) const override {
764 OS << getLowerName() << "(" << type << "(0))";
766 void writeCtorParameters(raw_ostream &OS) const override {
767 OS << type << " " << getUpperName();
769 void writeDeclarations(raw_ostream &OS) const override {
770 auto i = uniques.cbegin(), e = uniques.cend();
771 // The last one needs to not have a comma.
775 OS << " enum " << type << " {\n";
777 OS << " " << *i << ",\n";
778 OS << " " << *e << "\n";
781 OS << " " << type << " " << getLowerName() << ";";
784 void writePCHReadDecls(raw_ostream &OS) const override {
785 OS << " " << getAttrName() << "Attr::" << type << " " << getLowerName()
786 << "(static_cast<" << getAttrName() << "Attr::" << type
787 << ">(Record[Idx++]));\n";
790 void writePCHReadArgs(raw_ostream &OS) const override {
791 OS << getLowerName();
794 void writePCHWrite(raw_ostream &OS) const override {
795 OS << "Record.push_back(SA->get" << getUpperName() << "());\n";
798 void writeValue(raw_ostream &OS) const override {
799 // FIXME: this isn't 100% correct -- some enum arguments require printing
800 // as a string literal, while others require printing as an identifier.
801 // Tablegen currently does not distinguish between the two forms.
802 OS << "\\\"\" << " << getAttrName() << "Attr::Convert" << type << "ToStr(get"
803 << getUpperName() << "()) << \"\\\"";
806 void writeDump(raw_ostream &OS) const override {
807 OS << " switch(SA->get" << getUpperName() << "()) {\n";
808 for (const auto &I : uniques) {
809 OS << " case " << getAttrName() << "Attr::" << I << ":\n";
810 OS << " OS << \" " << I << "\";\n";
816 void writeConversion(raw_ostream &OS) const {
817 OS << " static bool ConvertStrTo" << type << "(StringRef Val, ";
818 OS << type << " &Out) {\n";
819 OS << " Optional<" << type << "> R = llvm::StringSwitch<Optional<";
820 OS << type << ">>(Val)\n";
821 for (size_t I = 0; I < enums.size(); ++I) {
822 OS << " .Case(\"" << values[I] << "\", ";
823 OS << getAttrName() << "Attr::" << enums[I] << ")\n";
825 OS << " .Default(Optional<" << type << ">());\n";
827 OS << " Out = *R;\n return true;\n }\n";
828 OS << " return false;\n";
831 // Mapping from enumeration values back to enumeration strings isn't
832 // trivial because some enumeration values have multiple named
833 // enumerators, such as type_visibility(internal) and
834 // type_visibility(hidden) both mapping to TypeVisibilityAttr::Hidden.
835 OS << " static const char *Convert" << type << "ToStr("
836 << type << " Val) {\n"
837 << " switch(Val) {\n";
838 SmallDenseSet<StringRef, 8> Uniques;
839 for (size_t I = 0; I < enums.size(); ++I) {
840 if (Uniques.insert(enums[I]).second)
841 OS << " case " << getAttrName() << "Attr::" << enums[I]
842 << ": return \"" << values[I] << "\";\n";
845 << " llvm_unreachable(\"No enumerator with that value\");\n"
850 class VariadicEnumArgument: public VariadicArgument {
851 std::string type, QualifiedTypeName;
852 std::vector<std::string> values, enums, uniques;
855 void writeValueImpl(raw_ostream &OS) const override {
856 // FIXME: this isn't 100% correct -- some enum arguments require printing
857 // as a string literal, while others require printing as an identifier.
858 // Tablegen currently does not distinguish between the two forms.
859 OS << " OS << \"\\\"\" << " << getAttrName() << "Attr::Convert" << type
860 << "ToStr(Val)" << "<< \"\\\"\";\n";
864 VariadicEnumArgument(const Record &Arg, StringRef Attr)
865 : VariadicArgument(Arg, Attr, Arg.getValueAsString("Type")),
866 type(Arg.getValueAsString("Type")),
867 values(Arg.getValueAsListOfStrings("Values")),
868 enums(Arg.getValueAsListOfStrings("Enums")),
869 uniques(uniqueEnumsInOrder(enums))
871 QualifiedTypeName = getAttrName().str() + "Attr::" + type;
873 // FIXME: Emit a proper error
874 assert(!uniques.empty());
877 bool isVariadicEnumArg() const override { return true; }
879 void writeDeclarations(raw_ostream &OS) const override {
880 auto i = uniques.cbegin(), e = uniques.cend();
881 // The last one needs to not have a comma.
885 OS << " enum " << type << " {\n";
887 OS << " " << *i << ",\n";
888 OS << " " << *e << "\n";
892 VariadicArgument::writeDeclarations(OS);
895 void writeDump(raw_ostream &OS) const override {
896 OS << " for (" << getAttrName() << "Attr::" << getLowerName()
897 << "_iterator I = SA->" << getLowerName() << "_begin(), E = SA->"
898 << getLowerName() << "_end(); I != E; ++I) {\n";
899 OS << " switch(*I) {\n";
900 for (const auto &UI : uniques) {
901 OS << " case " << getAttrName() << "Attr::" << UI << ":\n";
902 OS << " OS << \" " << UI << "\";\n";
909 void writePCHReadDecls(raw_ostream &OS) const override {
910 OS << " unsigned " << getLowerName() << "Size = Record[Idx++];\n";
911 OS << " SmallVector<" << QualifiedTypeName << ", 4> " << getLowerName()
913 OS << " " << getLowerName() << ".reserve(" << getLowerName()
915 OS << " for (unsigned i = " << getLowerName() << "Size; i; --i)\n";
916 OS << " " << getLowerName() << ".push_back(" << "static_cast<"
917 << QualifiedTypeName << ">(Record[Idx++]));\n";
920 void writePCHWrite(raw_ostream &OS) const override {
921 OS << " Record.push_back(SA->" << getLowerName() << "_size());\n";
922 OS << " for (" << getAttrName() << "Attr::" << getLowerName()
923 << "_iterator i = SA->" << getLowerName() << "_begin(), e = SA->"
924 << getLowerName() << "_end(); i != e; ++i)\n";
925 OS << " " << WritePCHRecord(QualifiedTypeName, "(*i)");
928 void writeConversion(raw_ostream &OS) const {
929 OS << " static bool ConvertStrTo" << type << "(StringRef Val, ";
930 OS << type << " &Out) {\n";
931 OS << " Optional<" << type << "> R = llvm::StringSwitch<Optional<";
932 OS << type << ">>(Val)\n";
933 for (size_t I = 0; I < enums.size(); ++I) {
934 OS << " .Case(\"" << values[I] << "\", ";
935 OS << getAttrName() << "Attr::" << enums[I] << ")\n";
937 OS << " .Default(Optional<" << type << ">());\n";
939 OS << " Out = *R;\n return true;\n }\n";
940 OS << " return false;\n";
943 OS << " static const char *Convert" << type << "ToStr("
944 << type << " Val) {\n"
945 << " switch(Val) {\n";
946 SmallDenseSet<StringRef, 8> Uniques;
947 for (size_t I = 0; I < enums.size(); ++I) {
948 if (Uniques.insert(enums[I]).second)
949 OS << " case " << getAttrName() << "Attr::" << enums[I]
950 << ": return \"" << values[I] << "\";\n";
953 << " llvm_unreachable(\"No enumerator with that value\");\n"
958 class VersionArgument : public Argument {
960 VersionArgument(const Record &Arg, StringRef Attr)
961 : Argument(Arg, Attr)
964 void writeAccessors(raw_ostream &OS) const override {
965 OS << " VersionTuple get" << getUpperName() << "() const {\n";
966 OS << " return " << getLowerName() << ";\n";
968 OS << " void set" << getUpperName()
969 << "(ASTContext &C, VersionTuple V) {\n";
970 OS << " " << getLowerName() << " = V;\n";
974 void writeCloneArgs(raw_ostream &OS) const override {
975 OS << "get" << getUpperName() << "()";
978 void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
979 OS << "A->get" << getUpperName() << "()";
982 void writeCtorInitializers(raw_ostream &OS) const override {
983 OS << getLowerName() << "(" << getUpperName() << ")";
986 void writeCtorDefaultInitializers(raw_ostream &OS) const override {
987 OS << getLowerName() << "()";
990 void writeCtorParameters(raw_ostream &OS) const override {
991 OS << "VersionTuple " << getUpperName();
994 void writeDeclarations(raw_ostream &OS) const override {
995 OS << "VersionTuple " << getLowerName() << ";\n";
998 void writePCHReadDecls(raw_ostream &OS) const override {
999 OS << " VersionTuple " << getLowerName()
1000 << "= ReadVersionTuple(Record, Idx);\n";
1003 void writePCHReadArgs(raw_ostream &OS) const override {
1004 OS << getLowerName();
1007 void writePCHWrite(raw_ostream &OS) const override {
1008 OS << " Record.AddVersionTuple(SA->get" << getUpperName() << "());\n";
1011 void writeValue(raw_ostream &OS) const override {
1012 OS << getLowerName() << "=\" << get" << getUpperName() << "() << \"";
1015 void writeDump(raw_ostream &OS) const override {
1016 OS << " OS << \" \" << SA->get" << getUpperName() << "();\n";
1020 class ExprArgument : public SimpleArgument {
1022 ExprArgument(const Record &Arg, StringRef Attr)
1023 : SimpleArgument(Arg, Attr, "Expr *")
1026 void writeASTVisitorTraversal(raw_ostream &OS) const override {
1028 << "getDerived().TraverseStmt(A->get" << getUpperName() << "()))\n";
1029 OS << " return false;\n";
1032 void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
1033 OS << "tempInst" << getUpperName();
1036 void writeTemplateInstantiation(raw_ostream &OS) const override {
1037 OS << " " << getType() << " tempInst" << getUpperName() << ";\n";
1039 OS << " EnterExpressionEvaluationContext "
1040 << "Unevaluated(S, Sema::Unevaluated);\n";
1041 OS << " ExprResult " << "Result = S.SubstExpr("
1042 << "A->get" << getUpperName() << "(), TemplateArgs);\n";
1043 OS << " tempInst" << getUpperName() << " = "
1044 << "Result.getAs<Expr>();\n";
1048 void writeDump(raw_ostream &OS) const override {}
1050 void writeDumpChildren(raw_ostream &OS) const override {
1051 OS << " dumpStmt(SA->get" << getUpperName() << "());\n";
1054 void writeHasChildren(raw_ostream &OS) const override { OS << "true"; }
1057 class VariadicExprArgument : public VariadicArgument {
1059 VariadicExprArgument(const Record &Arg, StringRef Attr)
1060 : VariadicArgument(Arg, Attr, "Expr *")
1063 void writeASTVisitorTraversal(raw_ostream &OS) const override {
1065 OS << " " << getType() << " *I = A->" << getLowerName()
1067 OS << " " << getType() << " *E = A->" << getLowerName()
1069 OS << " for (; I != E; ++I) {\n";
1070 OS << " if (!getDerived().TraverseStmt(*I))\n";
1071 OS << " return false;\n";
1076 void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
1077 OS << "tempInst" << getUpperName() << ", "
1078 << "A->" << getLowerName() << "_size()";
1081 void writeTemplateInstantiation(raw_ostream &OS) const override {
1082 OS << " auto *tempInst" << getUpperName()
1083 << " = new (C, 16) " << getType()
1084 << "[A->" << getLowerName() << "_size()];\n";
1086 OS << " EnterExpressionEvaluationContext "
1087 << "Unevaluated(S, Sema::Unevaluated);\n";
1088 OS << " " << getType() << " *TI = tempInst" << getUpperName()
1090 OS << " " << getType() << " *I = A->" << getLowerName()
1092 OS << " " << getType() << " *E = A->" << getLowerName()
1094 OS << " for (; I != E; ++I, ++TI) {\n";
1095 OS << " ExprResult Result = S.SubstExpr(*I, TemplateArgs);\n";
1096 OS << " *TI = Result.getAs<Expr>();\n";
1101 void writeDump(raw_ostream &OS) const override {}
1103 void writeDumpChildren(raw_ostream &OS) const override {
1104 OS << " for (" << getAttrName() << "Attr::" << getLowerName()
1105 << "_iterator I = SA->" << getLowerName() << "_begin(), E = SA->"
1106 << getLowerName() << "_end(); I != E; ++I)\n";
1107 OS << " dumpStmt(*I);\n";
1110 void writeHasChildren(raw_ostream &OS) const override {
1111 OS << "SA->" << getLowerName() << "_begin() != "
1112 << "SA->" << getLowerName() << "_end()";
1116 class VariadicStringArgument : public VariadicArgument {
1118 VariadicStringArgument(const Record &Arg, StringRef Attr)
1119 : VariadicArgument(Arg, Attr, "StringRef")
1122 void writeCtorBody(raw_ostream &OS) const override {
1123 OS << " for (size_t I = 0, E = " << getArgSizeName() << "; I != E;\n"
1125 " StringRef Ref = " << getUpperName() << "[I];\n"
1126 " if (!Ref.empty()) {\n"
1127 " char *Mem = new (Ctx, 1) char[Ref.size()];\n"
1128 " std::memcpy(Mem, Ref.data(), Ref.size());\n"
1129 " " << getArgName() << "[I] = StringRef(Mem, Ref.size());\n"
1134 void writeValueImpl(raw_ostream &OS) const override {
1135 OS << " OS << \"\\\"\" << Val << \"\\\"\";\n";
1139 class TypeArgument : public SimpleArgument {
1141 TypeArgument(const Record &Arg, StringRef Attr)
1142 : SimpleArgument(Arg, Attr, "TypeSourceInfo *")
1145 void writeAccessors(raw_ostream &OS) const override {
1146 OS << " QualType get" << getUpperName() << "() const {\n";
1147 OS << " return " << getLowerName() << "->getType();\n";
1149 OS << " " << getType() << " get" << getUpperName() << "Loc() const {\n";
1150 OS << " return " << getLowerName() << ";\n";
1154 void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
1155 OS << "A->get" << getUpperName() << "Loc()";
1158 void writePCHWrite(raw_ostream &OS) const override {
1159 OS << " " << WritePCHRecord(
1160 getType(), "SA->get" + std::string(getUpperName()) + "Loc()");
1164 } // end anonymous namespace
1166 static std::unique_ptr<Argument>
1167 createArgument(const Record &Arg, StringRef Attr,
1168 const Record *Search = nullptr) {
1172 std::unique_ptr<Argument> Ptr;
1173 llvm::StringRef ArgName = Search->getName();
1175 if (ArgName == "AlignedArgument")
1176 Ptr = llvm::make_unique<AlignedArgument>(Arg, Attr);
1177 else if (ArgName == "EnumArgument")
1178 Ptr = llvm::make_unique<EnumArgument>(Arg, Attr);
1179 else if (ArgName == "ExprArgument")
1180 Ptr = llvm::make_unique<ExprArgument>(Arg, Attr);
1181 else if (ArgName == "FunctionArgument")
1182 Ptr = llvm::make_unique<SimpleArgument>(Arg, Attr, "FunctionDecl *");
1183 else if (ArgName == "IdentifierArgument")
1184 Ptr = llvm::make_unique<SimpleArgument>(Arg, Attr, "IdentifierInfo *");
1185 else if (ArgName == "DefaultBoolArgument")
1186 Ptr = llvm::make_unique<DefaultSimpleArgument>(
1187 Arg, Attr, "bool", Arg.getValueAsBit("Default"));
1188 else if (ArgName == "BoolArgument")
1189 Ptr = llvm::make_unique<SimpleArgument>(Arg, Attr, "bool");
1190 else if (ArgName == "DefaultIntArgument")
1191 Ptr = llvm::make_unique<DefaultSimpleArgument>(
1192 Arg, Attr, "int", Arg.getValueAsInt("Default"));
1193 else if (ArgName == "IntArgument")
1194 Ptr = llvm::make_unique<SimpleArgument>(Arg, Attr, "int");
1195 else if (ArgName == "StringArgument")
1196 Ptr = llvm::make_unique<StringArgument>(Arg, Attr);
1197 else if (ArgName == "TypeArgument")
1198 Ptr = llvm::make_unique<TypeArgument>(Arg, Attr);
1199 else if (ArgName == "UnsignedArgument")
1200 Ptr = llvm::make_unique<SimpleArgument>(Arg, Attr, "unsigned");
1201 else if (ArgName == "VariadicUnsignedArgument")
1202 Ptr = llvm::make_unique<VariadicArgument>(Arg, Attr, "unsigned");
1203 else if (ArgName == "VariadicStringArgument")
1204 Ptr = llvm::make_unique<VariadicStringArgument>(Arg, Attr);
1205 else if (ArgName == "VariadicEnumArgument")
1206 Ptr = llvm::make_unique<VariadicEnumArgument>(Arg, Attr);
1207 else if (ArgName == "VariadicExprArgument")
1208 Ptr = llvm::make_unique<VariadicExprArgument>(Arg, Attr);
1209 else if (ArgName == "VersionArgument")
1210 Ptr = llvm::make_unique<VersionArgument>(Arg, Attr);
1213 // Search in reverse order so that the most-derived type is handled first.
1214 ArrayRef<std::pair<Record*, SMRange>> Bases = Search->getSuperClasses();
1215 for (const auto &Base : llvm::reverse(Bases)) {
1216 if ((Ptr = createArgument(Arg, Attr, Base.first)))
1221 if (Ptr && Arg.getValueAsBit("Optional"))
1222 Ptr->setOptional(true);
1224 if (Ptr && Arg.getValueAsBit("Fake"))
1230 static void writeAvailabilityValue(raw_ostream &OS) {
1231 OS << "\" << getPlatform()->getName();\n"
1232 << " if (getStrict()) OS << \", strict\";\n"
1233 << " if (!getIntroduced().empty()) OS << \", introduced=\" << getIntroduced();\n"
1234 << " if (!getDeprecated().empty()) OS << \", deprecated=\" << getDeprecated();\n"
1235 << " if (!getObsoleted().empty()) OS << \", obsoleted=\" << getObsoleted();\n"
1236 << " if (getUnavailable()) OS << \", unavailable\";\n"
1240 static void writeDeprecatedAttrValue(raw_ostream &OS, std::string &Variety) {
1241 OS << "\\\"\" << getMessage() << \"\\\"\";\n";
1242 // Only GNU deprecated has an optional fixit argument at the second position.
1243 if (Variety == "GNU")
1244 OS << " if (!getReplacement().empty()) OS << \", \\\"\""
1245 " << getReplacement() << \"\\\"\";\n";
1249 static void writeGetSpellingFunction(Record &R, raw_ostream &OS) {
1250 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(R);
1252 OS << "const char *" << R.getName() << "Attr::getSpelling() const {\n";
1253 if (Spellings.empty()) {
1254 OS << " return \"(No spelling)\";\n}\n\n";
1258 OS << " switch (SpellingListIndex) {\n"
1260 " llvm_unreachable(\"Unknown attribute spelling!\");\n"
1261 " return \"(No spelling)\";\n";
1263 for (unsigned I = 0; I < Spellings.size(); ++I)
1264 OS << " case " << I << ":\n"
1265 " return \"" << Spellings[I].name() << "\";\n";
1266 // End of the switch statement.
1268 // End of the getSpelling function.
1273 writePrettyPrintFunction(Record &R,
1274 const std::vector<std::unique_ptr<Argument>> &Args,
1276 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(R);
1278 OS << "void " << R.getName() << "Attr::printPretty("
1279 << "raw_ostream &OS, const PrintingPolicy &Policy) const {\n";
1281 if (Spellings.empty()) {
1287 " switch (SpellingListIndex) {\n"
1289 " llvm_unreachable(\"Unknown attribute spelling!\");\n"
1292 for (unsigned I = 0; I < Spellings.size(); ++ I) {
1293 llvm::SmallString<16> Prefix;
1294 llvm::SmallString<8> Suffix;
1295 // The actual spelling of the name and namespace (if applicable)
1296 // of an attribute without considering prefix and suffix.
1297 llvm::SmallString<64> Spelling;
1298 std::string Name = Spellings[I].name();
1299 std::string Variety = Spellings[I].variety();
1301 if (Variety == "GNU") {
1302 Prefix = " __attribute__((";
1304 } else if (Variety == "CXX11") {
1307 std::string Namespace = Spellings[I].nameSpace();
1308 if (!Namespace.empty()) {
1309 Spelling += Namespace;
1312 } else if (Variety == "Declspec") {
1313 Prefix = " __declspec(";
1315 } else if (Variety == "Microsoft") {
1318 } else if (Variety == "Keyword") {
1321 } else if (Variety == "Pragma") {
1322 Prefix = "#pragma ";
1324 std::string Namespace = Spellings[I].nameSpace();
1325 if (!Namespace.empty()) {
1326 Spelling += Namespace;
1330 llvm_unreachable("Unknown attribute syntax variety!");
1336 " case " << I << " : {\n"
1337 " OS << \"" << Prefix << Spelling;
1339 if (Variety == "Pragma") {
1341 OS << " printPrettyPragma(OS, Policy);\n";
1342 OS << " OS << \"\\n\";";
1348 // Fake arguments aren't part of the parsed form and should not be
1350 bool hasNonFakeArgs = llvm::any_of(
1351 Args, [](const std::unique_ptr<Argument> &A) { return !A->isFake(); });
1353 // FIXME: always printing the parenthesis isn't the correct behavior for
1354 // attributes which have optional arguments that were not provided. For
1355 // instance: __attribute__((aligned)) will be pretty printed as
1356 // __attribute__((aligned())). The logic should check whether there is only
1357 // a single argument, and if it is optional, whether it has been provided.
1360 if (Spelling == "availability") {
1361 writeAvailabilityValue(OS);
1362 } else if (Spelling == "deprecated" || Spelling == "gnu::deprecated") {
1363 writeDeprecatedAttrValue(OS, Variety);
1366 for (const auto &arg : Args) {
1367 if (arg->isFake()) continue;
1368 if (index++) OS << ", ";
1369 arg->writeValue(OS);
1375 OS << Suffix + "\";\n";
1382 // End of the switch statement.
1384 // End of the print function.
1388 /// \brief Return the index of a spelling in a spelling list.
1390 getSpellingListIndex(const std::vector<FlattenedSpelling> &SpellingList,
1391 const FlattenedSpelling &Spelling) {
1392 assert(!SpellingList.empty() && "Spelling list is empty!");
1394 for (unsigned Index = 0; Index < SpellingList.size(); ++Index) {
1395 const FlattenedSpelling &S = SpellingList[Index];
1396 if (S.variety() != Spelling.variety())
1398 if (S.nameSpace() != Spelling.nameSpace())
1400 if (S.name() != Spelling.name())
1406 llvm_unreachable("Unknown spelling!");
1409 static void writeAttrAccessorDefinition(const Record &R, raw_ostream &OS) {
1410 std::vector<Record*> Accessors = R.getValueAsListOfDefs("Accessors");
1411 if (Accessors.empty())
1414 const std::vector<FlattenedSpelling> SpellingList = GetFlattenedSpellings(R);
1415 assert(!SpellingList.empty() &&
1416 "Attribute with empty spelling list can't have accessors!");
1417 for (const auto *Accessor : Accessors) {
1418 std::string Name = Accessor->getValueAsString("Name");
1419 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(*Accessor);
1421 OS << " bool " << Name << "() const { return SpellingListIndex == ";
1422 for (unsigned Index = 0; Index < Spellings.size(); ++Index) {
1423 OS << getSpellingListIndex(SpellingList, Spellings[Index]);
1424 if (Index != Spellings.size() - 1)
1425 OS << " ||\n SpellingListIndex == ";
1433 SpellingNamesAreCommon(const std::vector<FlattenedSpelling>& Spellings) {
1434 assert(!Spellings.empty() && "An empty list of spellings was provided");
1435 std::string FirstName = NormalizeNameForSpellingComparison(
1436 Spellings.front().name());
1437 for (const auto &Spelling :
1438 llvm::make_range(std::next(Spellings.begin()), Spellings.end())) {
1439 std::string Name = NormalizeNameForSpellingComparison(Spelling.name());
1440 if (Name != FirstName)
1446 typedef std::map<unsigned, std::string> SemanticSpellingMap;
1448 CreateSemanticSpellings(const std::vector<FlattenedSpelling> &Spellings,
1449 SemanticSpellingMap &Map) {
1450 // The enumerants are automatically generated based on the variety,
1451 // namespace (if present) and name for each attribute spelling. However,
1452 // care is taken to avoid trampling on the reserved namespace due to
1454 std::string Ret(" enum Spelling {\n");
1455 std::set<std::string> Uniques;
1457 for (auto I = Spellings.begin(), E = Spellings.end(); I != E; ++I, ++Idx) {
1458 const FlattenedSpelling &S = *I;
1459 const std::string &Variety = S.variety();
1460 const std::string &Spelling = S.name();
1461 const std::string &Namespace = S.nameSpace();
1462 std::string EnumName;
1464 EnumName += (Variety + "_");
1465 if (!Namespace.empty())
1466 EnumName += (NormalizeNameForSpellingComparison(Namespace).str() +
1468 EnumName += NormalizeNameForSpellingComparison(Spelling);
1470 // Even if the name is not unique, this spelling index corresponds to a
1471 // particular enumerant name that we've calculated.
1472 Map[Idx] = EnumName;
1474 // Since we have been stripping underscores to avoid trampling on the
1475 // reserved namespace, we may have inadvertently created duplicate
1476 // enumerant names. These duplicates are not considered part of the
1477 // semantic spelling, and can be elided.
1478 if (Uniques.find(EnumName) != Uniques.end())
1481 Uniques.insert(EnumName);
1482 if (I != Spellings.begin())
1484 // Duplicate spellings are not considered part of the semantic spelling
1485 // enumeration, but the spelling index and semantic spelling values are
1486 // meant to be equivalent, so we must specify a concrete value for each
1488 Ret += " " + EnumName + " = " + llvm::utostr(Idx);
1494 void WriteSemanticSpellingSwitch(const std::string &VarName,
1495 const SemanticSpellingMap &Map,
1497 OS << " switch (" << VarName << ") {\n default: "
1498 << "llvm_unreachable(\"Unknown spelling list index\");\n";
1499 for (const auto &I : Map)
1500 OS << " case " << I.first << ": return " << I.second << ";\n";
1504 // Emits the LateParsed property for attributes.
1505 static void emitClangAttrLateParsedList(RecordKeeper &Records, raw_ostream &OS) {
1506 OS << "#if defined(CLANG_ATTR_LATE_PARSED_LIST)\n";
1507 std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr");
1509 for (const auto *Attr : Attrs) {
1510 bool LateParsed = Attr->getValueAsBit("LateParsed");
1513 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(*Attr);
1515 // FIXME: Handle non-GNU attributes
1516 for (const auto &I : Spellings) {
1517 if (I.variety() != "GNU")
1519 OS << ".Case(\"" << I.name() << "\", " << LateParsed << ")\n";
1523 OS << "#endif // CLANG_ATTR_LATE_PARSED_LIST\n\n";
1526 template <typename Fn>
1527 static void forEachUniqueSpelling(const Record &Attr, Fn &&F) {
1528 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(Attr);
1529 SmallDenseSet<StringRef, 8> Seen;
1530 for (const FlattenedSpelling &S : Spellings) {
1531 if (Seen.insert(S.name()).second)
1536 /// \brief Emits the first-argument-is-type property for attributes.
1537 static void emitClangAttrTypeArgList(RecordKeeper &Records, raw_ostream &OS) {
1538 OS << "#if defined(CLANG_ATTR_TYPE_ARG_LIST)\n";
1539 std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
1541 for (const auto *Attr : Attrs) {
1542 // Determine whether the first argument is a type.
1543 std::vector<Record *> Args = Attr->getValueAsListOfDefs("Args");
1547 if (Args[0]->getSuperClasses().back().first->getName() != "TypeArgument")
1550 // All these spellings take a single type argument.
1551 forEachUniqueSpelling(*Attr, [&](const FlattenedSpelling &S) {
1552 OS << ".Case(\"" << S.name() << "\", " << "true" << ")\n";
1555 OS << "#endif // CLANG_ATTR_TYPE_ARG_LIST\n\n";
1558 /// \brief Emits the parse-arguments-in-unevaluated-context property for
1560 static void emitClangAttrArgContextList(RecordKeeper &Records, raw_ostream &OS) {
1561 OS << "#if defined(CLANG_ATTR_ARG_CONTEXT_LIST)\n";
1562 ParsedAttrMap Attrs = getParsedAttrList(Records);
1563 for (const auto &I : Attrs) {
1564 const Record &Attr = *I.second;
1566 if (!Attr.getValueAsBit("ParseArgumentsAsUnevaluated"))
1569 // All these spellings take are parsed unevaluated.
1570 forEachUniqueSpelling(Attr, [&](const FlattenedSpelling &S) {
1571 OS << ".Case(\"" << S.name() << "\", " << "true" << ")\n";
1574 OS << "#endif // CLANG_ATTR_ARG_CONTEXT_LIST\n\n";
1577 static bool isIdentifierArgument(Record *Arg) {
1578 return !Arg->getSuperClasses().empty() &&
1579 llvm::StringSwitch<bool>(Arg->getSuperClasses().back().first->getName())
1580 .Case("IdentifierArgument", true)
1581 .Case("EnumArgument", true)
1582 .Case("VariadicEnumArgument", true)
1586 // Emits the first-argument-is-identifier property for attributes.
1587 static void emitClangAttrIdentifierArgList(RecordKeeper &Records, raw_ostream &OS) {
1588 OS << "#if defined(CLANG_ATTR_IDENTIFIER_ARG_LIST)\n";
1589 std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr");
1591 for (const auto *Attr : Attrs) {
1592 // Determine whether the first argument is an identifier.
1593 std::vector<Record *> Args = Attr->getValueAsListOfDefs("Args");
1594 if (Args.empty() || !isIdentifierArgument(Args[0]))
1597 // All these spellings take an identifier argument.
1598 forEachUniqueSpelling(*Attr, [&](const FlattenedSpelling &S) {
1599 OS << ".Case(\"" << S.name() << "\", " << "true" << ")\n";
1602 OS << "#endif // CLANG_ATTR_IDENTIFIER_ARG_LIST\n\n";
1607 // Emits the class definitions for attributes.
1608 void EmitClangAttrClass(RecordKeeper &Records, raw_ostream &OS) {
1609 emitSourceFileHeader("Attribute classes' definitions", OS);
1611 OS << "#ifndef LLVM_CLANG_ATTR_CLASSES_INC\n";
1612 OS << "#define LLVM_CLANG_ATTR_CLASSES_INC\n\n";
1614 std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr");
1616 for (const auto *Attr : Attrs) {
1617 const Record &R = *Attr;
1619 // FIXME: Currently, documentation is generated as-needed due to the fact
1620 // that there is no way to allow a generated project "reach into" the docs
1621 // directory (for instance, it may be an out-of-tree build). However, we want
1622 // to ensure that every attribute has a Documentation field, and produce an
1623 // error if it has been neglected. Otherwise, the on-demand generation which
1624 // happens server-side will fail. This code is ensuring that functionality,
1625 // even though this Emitter doesn't technically need the documentation.
1626 // When attribute documentation can be generated as part of the build
1627 // itself, this code can be removed.
1628 (void)R.getValueAsListOfDefs("Documentation");
1630 if (!R.getValueAsBit("ASTNode"))
1633 ArrayRef<std::pair<Record *, SMRange>> Supers = R.getSuperClasses();
1634 assert(!Supers.empty() && "Forgot to specify a superclass for the attr");
1635 std::string SuperName;
1636 for (const auto &Super : llvm::reverse(Supers)) {
1637 const Record *R = Super.first;
1638 if (R->getName() != "TargetSpecificAttr" && SuperName.empty())
1639 SuperName = R->getName();
1642 OS << "class " << R.getName() << "Attr : public " << SuperName << " {\n";
1644 std::vector<Record*> ArgRecords = R.getValueAsListOfDefs("Args");
1645 std::vector<std::unique_ptr<Argument>> Args;
1646 Args.reserve(ArgRecords.size());
1648 bool HasOptArg = false;
1649 bool HasFakeArg = false;
1650 for (const auto *ArgRecord : ArgRecords) {
1651 Args.emplace_back(createArgument(*ArgRecord, R.getName()));
1652 Args.back()->writeDeclarations(OS);
1655 // For these purposes, fake takes priority over optional.
1656 if (Args.back()->isFake()) {
1658 } else if (Args.back()->isOptional()) {
1665 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(R);
1667 // If there are zero or one spellings, all spelling-related functionality
1668 // can be elided. If all of the spellings share the same name, the spelling
1669 // functionality can also be elided.
1670 bool ElideSpelling = (Spellings.size() <= 1) ||
1671 SpellingNamesAreCommon(Spellings);
1673 // This maps spelling index values to semantic Spelling enumerants.
1674 SemanticSpellingMap SemanticToSyntacticMap;
1677 OS << CreateSemanticSpellings(Spellings, SemanticToSyntacticMap);
1679 // Emit CreateImplicit factory methods.
1680 auto emitCreateImplicit = [&](bool emitFake) {
1681 OS << " static " << R.getName() << "Attr *CreateImplicit(";
1682 OS << "ASTContext &Ctx";
1684 OS << ", Spelling S";
1685 for (auto const &ai : Args) {
1686 if (ai->isFake() && !emitFake) continue;
1688 ai->writeCtorParameters(OS);
1690 OS << ", SourceRange Loc = SourceRange()";
1692 OS << " auto *A = new (Ctx) " << R.getName();
1693 OS << "Attr(Loc, Ctx, ";
1694 for (auto const &ai : Args) {
1695 if (ai->isFake() && !emitFake) continue;
1696 ai->writeImplicitCtorArgs(OS);
1699 OS << (ElideSpelling ? "0" : "S") << ");\n";
1700 OS << " A->setImplicit(true);\n";
1701 OS << " return A;\n }\n\n";
1704 // Emit a CreateImplicit that takes all the arguments.
1705 emitCreateImplicit(true);
1707 // Emit a CreateImplicit that takes all the non-fake arguments.
1709 emitCreateImplicit(false);
1712 // Emit constructors.
1713 auto emitCtor = [&](bool emitOpt, bool emitFake) {
1714 auto shouldEmitArg = [=](const std::unique_ptr<Argument> &arg) {
1715 if (arg->isFake()) return emitFake;
1716 if (arg->isOptional()) return emitOpt;
1720 OS << " " << R.getName() << "Attr(SourceRange R, ASTContext &Ctx\n";
1721 for (auto const &ai : Args) {
1722 if (!shouldEmitArg(ai)) continue;
1724 ai->writeCtorParameters(OS);
1729 OS << "unsigned SI\n";
1732 OS << " : " << SuperName << "(attr::" << R.getName() << ", R, SI, "
1733 << ( R.getValueAsBit("LateParsed") ? "true" : "false" ) << ", "
1734 << ( R.getValueAsBit("DuplicatesAllowedWhileMerging") ? "true" : "false" ) << ")\n";
1736 for (auto const &ai : Args) {
1738 if (!shouldEmitArg(ai)) {
1739 ai->writeCtorDefaultInitializers(OS);
1741 ai->writeCtorInitializers(OS);
1748 for (auto const &ai : Args) {
1749 if (!shouldEmitArg(ai)) continue;
1750 ai->writeCtorBody(OS);
1755 // Emit a constructor that includes all the arguments.
1756 // This is necessary for cloning.
1757 emitCtor(true, true);
1759 // Emit a constructor that takes all the non-fake arguments.
1761 emitCtor(true, false);
1764 // Emit a constructor that takes all the non-fake, non-optional arguments.
1766 emitCtor(false, false);
1769 OS << " " << R.getName() << "Attr *clone(ASTContext &C) const;\n";
1770 OS << " void printPretty(raw_ostream &OS,\n"
1771 << " const PrintingPolicy &Policy) const;\n";
1772 OS << " const char *getSpelling() const;\n";
1774 if (!ElideSpelling) {
1775 assert(!SemanticToSyntacticMap.empty() && "Empty semantic mapping list");
1776 OS << " Spelling getSemanticSpelling() const {\n";
1777 WriteSemanticSpellingSwitch("SpellingListIndex", SemanticToSyntacticMap,
1782 writeAttrAccessorDefinition(R, OS);
1784 for (auto const &ai : Args) {
1785 ai->writeAccessors(OS);
1788 // Don't write conversion routines for fake arguments.
1789 if (ai->isFake()) continue;
1791 if (ai->isEnumArg())
1792 static_cast<const EnumArgument *>(ai.get())->writeConversion(OS);
1793 else if (ai->isVariadicEnumArg())
1794 static_cast<const VariadicEnumArgument *>(ai.get())
1795 ->writeConversion(OS);
1798 OS << R.getValueAsString("AdditionalMembers");
1801 OS << " static bool classof(const Attr *A) { return A->getKind() == "
1802 << "attr::" << R.getName() << "; }\n";
1807 OS << "#endif // LLVM_CLANG_ATTR_CLASSES_INC\n";
1810 // Emits the class method definitions for attributes.
1811 void EmitClangAttrImpl(RecordKeeper &Records, raw_ostream &OS) {
1812 emitSourceFileHeader("Attribute classes' member function definitions", OS);
1814 std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr");
1816 for (auto *Attr : Attrs) {
1819 if (!R.getValueAsBit("ASTNode"))
1822 std::vector<Record*> ArgRecords = R.getValueAsListOfDefs("Args");
1823 std::vector<std::unique_ptr<Argument>> Args;
1824 for (const auto *Arg : ArgRecords)
1825 Args.emplace_back(createArgument(*Arg, R.getName()));
1827 for (auto const &ai : Args)
1828 ai->writeAccessorDefinitions(OS);
1830 OS << R.getName() << "Attr *" << R.getName()
1831 << "Attr::clone(ASTContext &C) const {\n";
1832 OS << " auto *A = new (C) " << R.getName() << "Attr(getLocation(), C";
1833 for (auto const &ai : Args) {
1835 ai->writeCloneArgs(OS);
1837 OS << ", getSpellingListIndex());\n";
1838 OS << " A->Inherited = Inherited;\n";
1839 OS << " A->IsPackExpansion = IsPackExpansion;\n";
1840 OS << " A->Implicit = Implicit;\n";
1841 OS << " return A;\n}\n\n";
1843 writePrettyPrintFunction(R, Args, OS);
1844 writeGetSpellingFunction(R, OS);
1847 // Instead of relying on virtual dispatch we just create a huge dispatch
1848 // switch. This is both smaller and faster than virtual functions.
1849 auto EmitFunc = [&](const char *Method) {
1850 OS << " switch (getKind()) {\n";
1851 for (const auto *Attr : Attrs) {
1852 const Record &R = *Attr;
1853 if (!R.getValueAsBit("ASTNode"))
1856 OS << " case attr::" << R.getName() << ":\n";
1857 OS << " return cast<" << R.getName() << "Attr>(this)->" << Method
1861 OS << " llvm_unreachable(\"Unexpected attribute kind!\");\n";
1865 OS << "const char *Attr::getSpelling() const {\n";
1866 EmitFunc("getSpelling()");
1868 OS << "Attr *Attr::clone(ASTContext &C) const {\n";
1869 EmitFunc("clone(C)");
1871 OS << "void Attr::printPretty(raw_ostream &OS, "
1872 "const PrintingPolicy &Policy) const {\n";
1873 EmitFunc("printPretty(OS, Policy)");
1876 } // end namespace clang
1878 static void emitAttrList(raw_ostream &OS, StringRef Class,
1879 const std::vector<Record*> &AttrList) {
1880 for (auto Cur : AttrList) {
1881 OS << Class << "(" << Cur->getName() << ")\n";
1885 // Determines if an attribute has a Pragma spelling.
1886 static bool AttrHasPragmaSpelling(const Record *R) {
1887 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(*R);
1888 return llvm::find_if(Spellings, [](const FlattenedSpelling &S) {
1889 return S.variety() == "Pragma";
1890 }) != Spellings.end();
1895 struct AttrClassDescriptor {
1896 const char * const MacroName;
1897 const char * const TableGenName;
1900 } // end anonymous namespace
1902 static const AttrClassDescriptor AttrClassDescriptors[] = {
1904 { "STMT_ATTR", "StmtAttr" },
1905 { "INHERITABLE_ATTR", "InheritableAttr" },
1906 { "INHERITABLE_PARAM_ATTR", "InheritableParamAttr" },
1907 { "PARAMETER_ABI_ATTR", "ParameterABIAttr" }
1910 static void emitDefaultDefine(raw_ostream &OS, StringRef name,
1911 const char *superName) {
1912 OS << "#ifndef " << name << "\n";
1913 OS << "#define " << name << "(NAME) ";
1914 if (superName) OS << superName << "(NAME)";
1915 OS << "\n#endif\n\n";
1920 /// A class of attributes.
1922 const AttrClassDescriptor &Descriptor;
1924 AttrClass *SuperClass = nullptr;
1925 std::vector<AttrClass*> SubClasses;
1926 std::vector<Record*> Attrs;
1928 AttrClass(const AttrClassDescriptor &Descriptor, Record *R)
1929 : Descriptor(Descriptor), TheRecord(R) {}
1931 void emitDefaultDefines(raw_ostream &OS) const {
1932 // Default the macro unless this is a root class (i.e. Attr).
1934 emitDefaultDefine(OS, Descriptor.MacroName,
1935 SuperClass->Descriptor.MacroName);
1939 void emitUndefs(raw_ostream &OS) const {
1940 OS << "#undef " << Descriptor.MacroName << "\n";
1943 void emitAttrList(raw_ostream &OS) const {
1944 for (auto SubClass : SubClasses) {
1945 SubClass->emitAttrList(OS);
1948 ::emitAttrList(OS, Descriptor.MacroName, Attrs);
1951 void classifyAttrOnRoot(Record *Attr) {
1952 bool result = classifyAttr(Attr);
1953 assert(result && "failed to classify on root"); (void) result;
1956 void emitAttrRange(raw_ostream &OS) const {
1957 OS << "ATTR_RANGE(" << Descriptor.TableGenName
1958 << ", " << getFirstAttr()->getName()
1959 << ", " << getLastAttr()->getName() << ")\n";
1963 bool classifyAttr(Record *Attr) {
1964 // Check all the subclasses.
1965 for (auto SubClass : SubClasses) {
1966 if (SubClass->classifyAttr(Attr))
1970 // It's not more specific than this class, but it might still belong here.
1971 if (Attr->isSubClassOf(TheRecord)) {
1972 Attrs.push_back(Attr);
1979 Record *getFirstAttr() const {
1980 if (!SubClasses.empty())
1981 return SubClasses.front()->getFirstAttr();
1982 return Attrs.front();
1985 Record *getLastAttr() const {
1987 return Attrs.back();
1988 return SubClasses.back()->getLastAttr();
1992 /// The entire hierarchy of attribute classes.
1993 class AttrClassHierarchy {
1994 std::vector<std::unique_ptr<AttrClass>> Classes;
1997 AttrClassHierarchy(RecordKeeper &Records) {
1998 // Find records for all the classes.
1999 for (auto &Descriptor : AttrClassDescriptors) {
2000 Record *ClassRecord = Records.getClass(Descriptor.TableGenName);
2001 AttrClass *Class = new AttrClass(Descriptor, ClassRecord);
2002 Classes.emplace_back(Class);
2005 // Link up the hierarchy.
2006 for (auto &Class : Classes) {
2007 if (AttrClass *SuperClass = findSuperClass(Class->TheRecord)) {
2008 Class->SuperClass = SuperClass;
2009 SuperClass->SubClasses.push_back(Class.get());
2014 for (auto i = Classes.begin(), e = Classes.end(); i != e; ++i) {
2015 assert((i == Classes.begin()) == ((*i)->SuperClass == nullptr) &&
2016 "only the first class should be a root class!");
2021 void emitDefaultDefines(raw_ostream &OS) const {
2022 for (auto &Class : Classes) {
2023 Class->emitDefaultDefines(OS);
2027 void emitUndefs(raw_ostream &OS) const {
2028 for (auto &Class : Classes) {
2029 Class->emitUndefs(OS);
2033 void emitAttrLists(raw_ostream &OS) const {
2034 // Just start from the root class.
2035 Classes[0]->emitAttrList(OS);
2038 void emitAttrRanges(raw_ostream &OS) const {
2039 for (auto &Class : Classes)
2040 Class->emitAttrRange(OS);
2043 void classifyAttr(Record *Attr) {
2044 // Add the attribute to the root class.
2045 Classes[0]->classifyAttrOnRoot(Attr);
2049 AttrClass *findClassByRecord(Record *R) const {
2050 for (auto &Class : Classes) {
2051 if (Class->TheRecord == R)
2057 AttrClass *findSuperClass(Record *R) const {
2058 // TableGen flattens the superclass list, so we just need to walk it
2060 auto SuperClasses = R->getSuperClasses();
2061 for (signed i = 0, e = SuperClasses.size(); i != e; ++i) {
2062 auto SuperClass = findClassByRecord(SuperClasses[e - i - 1].first);
2063 if (SuperClass) return SuperClass;
2069 } // end anonymous namespace
2073 // Emits the enumeration list for attributes.
2074 void EmitClangAttrList(RecordKeeper &Records, raw_ostream &OS) {
2075 emitSourceFileHeader("List of all attributes that Clang recognizes", OS);
2077 AttrClassHierarchy Hierarchy(Records);
2079 // Add defaulting macro definitions.
2080 Hierarchy.emitDefaultDefines(OS);
2081 emitDefaultDefine(OS, "PRAGMA_SPELLING_ATTR", nullptr);
2083 std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
2084 std::vector<Record *> PragmaAttrs;
2085 for (auto *Attr : Attrs) {
2086 if (!Attr->getValueAsBit("ASTNode"))
2089 // Add the attribute to the ad-hoc groups.
2090 if (AttrHasPragmaSpelling(Attr))
2091 PragmaAttrs.push_back(Attr);
2093 // Place it in the hierarchy.
2094 Hierarchy.classifyAttr(Attr);
2097 // Emit the main attribute list.
2098 Hierarchy.emitAttrLists(OS);
2100 // Emit the ad hoc groups.
2101 emitAttrList(OS, "PRAGMA_SPELLING_ATTR", PragmaAttrs);
2103 // Emit the attribute ranges.
2104 OS << "#ifdef ATTR_RANGE\n";
2105 Hierarchy.emitAttrRanges(OS);
2106 OS << "#undef ATTR_RANGE\n";
2109 Hierarchy.emitUndefs(OS);
2110 OS << "#undef PRAGMA_SPELLING_ATTR\n";
2113 // Emits the code to read an attribute from a precompiled header.
2114 void EmitClangAttrPCHRead(RecordKeeper &Records, raw_ostream &OS) {
2115 emitSourceFileHeader("Attribute deserialization code", OS);
2117 Record *InhClass = Records.getClass("InheritableAttr");
2118 std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr"),
2120 std::vector<std::unique_ptr<Argument>> Args;
2122 OS << " switch (Kind) {\n";
2123 for (const auto *Attr : Attrs) {
2124 const Record &R = *Attr;
2125 if (!R.getValueAsBit("ASTNode"))
2128 OS << " case attr::" << R.getName() << ": {\n";
2129 if (R.isSubClassOf(InhClass))
2130 OS << " bool isInherited = Record[Idx++];\n";
2131 OS << " bool isImplicit = Record[Idx++];\n";
2132 OS << " unsigned Spelling = Record[Idx++];\n";
2133 ArgRecords = R.getValueAsListOfDefs("Args");
2135 for (const auto *Arg : ArgRecords) {
2136 Args.emplace_back(createArgument(*Arg, R.getName()));
2137 Args.back()->writePCHReadDecls(OS);
2139 OS << " New = new (Context) " << R.getName() << "Attr(Range, Context";
2140 for (auto const &ri : Args) {
2142 ri->writePCHReadArgs(OS);
2144 OS << ", Spelling);\n";
2145 if (R.isSubClassOf(InhClass))
2146 OS << " cast<InheritableAttr>(New)->setInherited(isInherited);\n";
2147 OS << " New->setImplicit(isImplicit);\n";
2154 // Emits the code to write an attribute to a precompiled header.
2155 void EmitClangAttrPCHWrite(RecordKeeper &Records, raw_ostream &OS) {
2156 emitSourceFileHeader("Attribute serialization code", OS);
2158 Record *InhClass = Records.getClass("InheritableAttr");
2159 std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr"), Args;
2161 OS << " switch (A->getKind()) {\n";
2162 for (const auto *Attr : Attrs) {
2163 const Record &R = *Attr;
2164 if (!R.getValueAsBit("ASTNode"))
2166 OS << " case attr::" << R.getName() << ": {\n";
2167 Args = R.getValueAsListOfDefs("Args");
2168 if (R.isSubClassOf(InhClass) || !Args.empty())
2169 OS << " const auto *SA = cast<" << R.getName()
2171 if (R.isSubClassOf(InhClass))
2172 OS << " Record.push_back(SA->isInherited());\n";
2173 OS << " Record.push_back(A->isImplicit());\n";
2174 OS << " Record.push_back(A->getSpellingListIndex());\n";
2176 for (const auto *Arg : Args)
2177 createArgument(*Arg, R.getName())->writePCHWrite(OS);
2184 // Generate a conditional expression to check if the current target satisfies
2185 // the conditions for a TargetSpecificAttr record, and append the code for
2186 // those checks to the Test string. If the FnName string pointer is non-null,
2187 // append a unique suffix to distinguish this set of target checks from other
2188 // TargetSpecificAttr records.
2189 static void GenerateTargetSpecificAttrChecks(const Record *R,
2190 std::vector<std::string> &Arches,
2192 std::string *FnName) {
2193 // It is assumed that there will be an llvm::Triple object
2194 // named "T" and a TargetInfo object named "Target" within
2195 // scope that can be used to determine whether the attribute exists in
2199 for (auto I = Arches.begin(), E = Arches.end(); I != E; ++I) {
2200 std::string Part = *I;
2201 Test += "T.getArch() == llvm::Triple::" + Part;
2209 // If the attribute is specific to particular OSes, check those.
2210 if (!R->isValueUnset("OSes")) {
2211 // We know that there was at least one arch test, so we need to and in the
2214 std::vector<std::string> OSes = R->getValueAsListOfStrings("OSes");
2215 for (auto I = OSes.begin(), E = OSes.end(); I != E; ++I) {
2216 std::string Part = *I;
2218 Test += "T.getOS() == llvm::Triple::" + Part;
2227 // If one or more CXX ABIs are specified, check those as well.
2228 if (!R->isValueUnset("CXXABIs")) {
2230 std::vector<std::string> CXXABIs = R->getValueAsListOfStrings("CXXABIs");
2231 for (auto I = CXXABIs.begin(), E = CXXABIs.end(); I != E; ++I) {
2232 std::string Part = *I;
2233 Test += "Target.getCXXABI().getKind() == TargetCXXABI::" + Part;
2243 static void GenerateHasAttrSpellingStringSwitch(
2244 const std::vector<Record *> &Attrs, raw_ostream &OS,
2245 const std::string &Variety = "", const std::string &Scope = "") {
2246 for (const auto *Attr : Attrs) {
2247 // C++11-style attributes have specific version information associated with
2248 // them. If the attribute has no scope, the version information must not
2249 // have the default value (1), as that's incorrect. Instead, the unscoped
2250 // attribute version information should be taken from the SD-6 standing
2251 // document, which can be found at:
2252 // https://isocpp.org/std/standing-documents/sd-6-sg10-feature-test-recommendations
2255 if (Variety == "CXX11") {
2256 std::vector<Record *> Spellings = Attr->getValueAsListOfDefs("Spellings");
2257 for (const auto &Spelling : Spellings) {
2258 if (Spelling->getValueAsString("Variety") == "CXX11") {
2259 Version = static_cast<int>(Spelling->getValueAsInt("Version"));
2260 if (Scope.empty() && Version == 1)
2261 PrintError(Spelling->getLoc(), "C++ standard attributes must "
2262 "have valid version information.");
2269 if (Attr->isSubClassOf("TargetSpecificAttr")) {
2270 const Record *R = Attr->getValueAsDef("Target");
2271 std::vector<std::string> Arches = R->getValueAsListOfStrings("Arches");
2272 GenerateTargetSpecificAttrChecks(R, Arches, Test, nullptr);
2274 // If this is the C++11 variety, also add in the LangOpts test.
2275 if (Variety == "CXX11")
2276 Test += " && LangOpts.CPlusPlus11";
2277 } else if (Variety == "CXX11")
2278 // C++11 mode should be checked against LangOpts, which is presumed to be
2279 // present in the caller.
2280 Test = "LangOpts.CPlusPlus11";
2282 std::string TestStr =
2283 !Test.empty() ? Test + " ? " + llvm::itostr(Version) + " : 0" : "1";
2284 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(*Attr);
2285 for (const auto &S : Spellings)
2286 if (Variety.empty() || (Variety == S.variety() &&
2287 (Scope.empty() || Scope == S.nameSpace())))
2288 OS << " .Case(\"" << S.name() << "\", " << TestStr << ")\n";
2290 OS << " .Default(0);\n";
2293 // Emits the list of spellings for attributes.
2294 void EmitClangAttrHasAttrImpl(RecordKeeper &Records, raw_ostream &OS) {
2295 emitSourceFileHeader("Code to implement the __has_attribute logic", OS);
2297 // Separate all of the attributes out into four group: generic, C++11, GNU,
2298 // and declspecs. Then generate a big switch statement for each of them.
2299 std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
2300 std::vector<Record *> Declspec, Microsoft, GNU, Pragma;
2301 std::map<std::string, std::vector<Record *>> CXX;
2303 // Walk over the list of all attributes, and split them out based on the
2304 // spelling variety.
2305 for (auto *R : Attrs) {
2306 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(*R);
2307 for (const auto &SI : Spellings) {
2308 const std::string &Variety = SI.variety();
2309 if (Variety == "GNU")
2311 else if (Variety == "Declspec")
2312 Declspec.push_back(R);
2313 else if (Variety == "Microsoft")
2314 Microsoft.push_back(R);
2315 else if (Variety == "CXX11")
2316 CXX[SI.nameSpace()].push_back(R);
2317 else if (Variety == "Pragma")
2318 Pragma.push_back(R);
2322 OS << "const llvm::Triple &T = Target.getTriple();\n";
2323 OS << "switch (Syntax) {\n";
2324 OS << "case AttrSyntax::GNU:\n";
2325 OS << " return llvm::StringSwitch<int>(Name)\n";
2326 GenerateHasAttrSpellingStringSwitch(GNU, OS, "GNU");
2327 OS << "case AttrSyntax::Declspec:\n";
2328 OS << " return llvm::StringSwitch<int>(Name)\n";
2329 GenerateHasAttrSpellingStringSwitch(Declspec, OS, "Declspec");
2330 OS << "case AttrSyntax::Microsoft:\n";
2331 OS << " return llvm::StringSwitch<int>(Name)\n";
2332 GenerateHasAttrSpellingStringSwitch(Microsoft, OS, "Microsoft");
2333 OS << "case AttrSyntax::Pragma:\n";
2334 OS << " return llvm::StringSwitch<int>(Name)\n";
2335 GenerateHasAttrSpellingStringSwitch(Pragma, OS, "Pragma");
2336 OS << "case AttrSyntax::CXX: {\n";
2337 // C++11-style attributes are further split out based on the Scope.
2338 for (auto I = CXX.cbegin(), E = CXX.cend(); I != E; ++I) {
2339 if (I != CXX.begin())
2341 if (I->first.empty())
2342 OS << "if (!Scope || Scope->getName() == \"\") {\n";
2344 OS << "if (Scope->getName() == \"" << I->first << "\") {\n";
2345 OS << " return llvm::StringSwitch<int>(Name)\n";
2346 GenerateHasAttrSpellingStringSwitch(I->second, OS, "CXX11", I->first);
2353 void EmitClangAttrSpellingListIndex(RecordKeeper &Records, raw_ostream &OS) {
2354 emitSourceFileHeader("Code to translate different attribute spellings "
2355 "into internal identifiers", OS);
2357 OS << " switch (AttrKind) {\n";
2359 ParsedAttrMap Attrs = getParsedAttrList(Records);
2360 for (const auto &I : Attrs) {
2361 const Record &R = *I.second;
2362 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(R);
2363 OS << " case AT_" << I.first << ": {\n";
2364 for (unsigned I = 0; I < Spellings.size(); ++ I) {
2365 OS << " if (Name == \"" << Spellings[I].name() << "\" && "
2367 << StringSwitch<unsigned>(Spellings[I].variety())
2370 .Case("Declspec", 2)
2371 .Case("Microsoft", 3)
2375 << " && Scope == \"" << Spellings[I].nameSpace() << "\")\n"
2376 << " return " << I << ";\n";
2384 OS << " return 0;\n";
2387 // Emits code used by RecursiveASTVisitor to visit attributes
2388 void EmitClangAttrASTVisitor(RecordKeeper &Records, raw_ostream &OS) {
2389 emitSourceFileHeader("Used by RecursiveASTVisitor to visit attributes.", OS);
2391 std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr");
2393 // Write method declarations for Traverse* methods.
2394 // We emit this here because we only generate methods for attributes that
2395 // are declared as ASTNodes.
2396 OS << "#ifdef ATTR_VISITOR_DECLS_ONLY\n\n";
2397 for (const auto *Attr : Attrs) {
2398 const Record &R = *Attr;
2399 if (!R.getValueAsBit("ASTNode"))
2401 OS << " bool Traverse"
2402 << R.getName() << "Attr(" << R.getName() << "Attr *A);\n";
2404 << R.getName() << "Attr(" << R.getName() << "Attr *A) {\n"
2405 << " return true; \n"
2408 OS << "\n#else // ATTR_VISITOR_DECLS_ONLY\n\n";
2410 // Write individual Traverse* methods for each attribute class.
2411 for (const auto *Attr : Attrs) {
2412 const Record &R = *Attr;
2413 if (!R.getValueAsBit("ASTNode"))
2416 OS << "template <typename Derived>\n"
2417 << "bool VISITORCLASS<Derived>::Traverse"
2418 << R.getName() << "Attr(" << R.getName() << "Attr *A) {\n"
2419 << " if (!getDerived().VisitAttr(A))\n"
2420 << " return false;\n"
2421 << " if (!getDerived().Visit" << R.getName() << "Attr(A))\n"
2422 << " return false;\n";
2424 std::vector<Record*> ArgRecords = R.getValueAsListOfDefs("Args");
2425 for (const auto *Arg : ArgRecords)
2426 createArgument(*Arg, R.getName())->writeASTVisitorTraversal(OS);
2428 OS << " return true;\n";
2432 // Write generic Traverse routine
2433 OS << "template <typename Derived>\n"
2434 << "bool VISITORCLASS<Derived>::TraverseAttr(Attr *A) {\n"
2436 << " return true;\n"
2438 << " switch (A->getKind()) {\n";
2440 for (const auto *Attr : Attrs) {
2441 const Record &R = *Attr;
2442 if (!R.getValueAsBit("ASTNode"))
2445 OS << " case attr::" << R.getName() << ":\n"
2446 << " return getDerived().Traverse" << R.getName() << "Attr("
2447 << "cast<" << R.getName() << "Attr>(A));\n";
2449 OS << " }\n"; // end switch
2450 OS << " llvm_unreachable(\"bad attribute kind\");\n";
2451 OS << "}\n"; // end function
2452 OS << "#endif // ATTR_VISITOR_DECLS_ONLY\n";
2455 // Emits code to instantiate dependent attributes on templates.
2456 void EmitClangAttrTemplateInstantiate(RecordKeeper &Records, raw_ostream &OS) {
2457 emitSourceFileHeader("Template instantiation code for attributes", OS);
2459 std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr");
2461 OS << "namespace clang {\n"
2462 << "namespace sema {\n\n"
2463 << "Attr *instantiateTemplateAttribute(const Attr *At, ASTContext &C, "
2465 << " const MultiLevelTemplateArgumentList &TemplateArgs) {\n"
2466 << " switch (At->getKind()) {\n";
2468 for (const auto *Attr : Attrs) {
2469 const Record &R = *Attr;
2470 if (!R.getValueAsBit("ASTNode"))
2473 OS << " case attr::" << R.getName() << ": {\n";
2474 bool ShouldClone = R.getValueAsBit("Clone");
2477 OS << " return nullptr;\n";
2482 OS << " const auto *A = cast<"
2483 << R.getName() << "Attr>(At);\n";
2484 bool TDependent = R.getValueAsBit("TemplateDependent");
2487 OS << " return A->clone(C);\n";
2492 std::vector<Record*> ArgRecords = R.getValueAsListOfDefs("Args");
2493 std::vector<std::unique_ptr<Argument>> Args;
2494 Args.reserve(ArgRecords.size());
2496 for (const auto *ArgRecord : ArgRecords)
2497 Args.emplace_back(createArgument(*ArgRecord, R.getName()));
2499 for (auto const &ai : Args)
2500 ai->writeTemplateInstantiation(OS);
2502 OS << " return new (C) " << R.getName() << "Attr(A->getLocation(), C";
2503 for (auto const &ai : Args) {
2505 ai->writeTemplateInstantiationArgs(OS);
2507 OS << ", A->getSpellingListIndex());\n }\n";
2509 OS << " } // end switch\n"
2510 << " llvm_unreachable(\"Unknown attribute!\");\n"
2511 << " return nullptr;\n"
2513 << "} // end namespace sema\n"
2514 << "} // end namespace clang\n";
2517 // Emits the list of parsed attributes.
2518 void EmitClangAttrParsedAttrList(RecordKeeper &Records, raw_ostream &OS) {
2519 emitSourceFileHeader("List of all attributes that Clang recognizes", OS);
2521 OS << "#ifndef PARSED_ATTR\n";
2522 OS << "#define PARSED_ATTR(NAME) NAME\n";
2525 ParsedAttrMap Names = getParsedAttrList(Records);
2526 for (const auto &I : Names) {
2527 OS << "PARSED_ATTR(" << I.first << ")\n";
2531 static bool isArgVariadic(const Record &R, StringRef AttrName) {
2532 return createArgument(R, AttrName)->isVariadic();
2535 static void emitArgInfo(const Record &R, std::stringstream &OS) {
2536 // This function will count the number of arguments specified for the
2537 // attribute and emit the number of required arguments followed by the
2538 // number of optional arguments.
2539 std::vector<Record *> Args = R.getValueAsListOfDefs("Args");
2540 unsigned ArgCount = 0, OptCount = 0;
2541 bool HasVariadic = false;
2542 for (const auto *Arg : Args) {
2543 // If the arg is fake, it's the user's job to supply it: general parsing
2544 // logic shouldn't need to know anything about it.
2545 if (Arg->getValueAsBit("Fake"))
2547 Arg->getValueAsBit("Optional") ? ++OptCount : ++ArgCount;
2548 if (!HasVariadic && isArgVariadic(*Arg, R.getName()))
2552 // If there is a variadic argument, we will set the optional argument count
2553 // to its largest value. Since it's currently a 4-bit number, we set it to 15.
2554 OS << ArgCount << ", " << (HasVariadic ? 15 : OptCount);
2557 static void GenerateDefaultAppertainsTo(raw_ostream &OS) {
2558 OS << "static bool defaultAppertainsTo(Sema &, const AttributeList &,";
2559 OS << "const Decl *) {\n";
2560 OS << " return true;\n";
2564 static std::string CalculateDiagnostic(const Record &S) {
2565 // If the SubjectList object has a custom diagnostic associated with it,
2566 // return that directly.
2567 std::string CustomDiag = S.getValueAsString("CustomDiag");
2568 if (!CustomDiag.empty())
2571 // Given the list of subjects, determine what diagnostic best fits.
2575 ObjCMethod = 1U << 2,
2578 GenericRecord = 1U << 5,
2582 ObjCInterface = 1U << 9,
2584 Namespace = 1U << 11,
2586 CXXMethod = 1U << 13,
2587 ObjCProtocol = 1U << 14,
2590 uint32_t SubMask = 0;
2592 std::vector<Record *> Subjects = S.getValueAsListOfDefs("Subjects");
2593 for (const auto *Subject : Subjects) {
2594 const Record &R = *Subject;
2597 if (R.isSubClassOf("SubsetSubject")) {
2598 PrintError(R.getLoc(), "SubsetSubjects should use a custom diagnostic");
2599 // As a fallback, look through the SubsetSubject to see what its base
2600 // type is, and use that. This needs to be updated if SubsetSubjects
2601 // are allowed within other SubsetSubjects.
2602 Name = R.getValueAsDef("Base")->getName();
2606 uint32_t V = StringSwitch<uint32_t>(Name)
2607 .Case("Function", Func)
2609 .Case("ObjCMethod", ObjCMethod)
2610 .Case("ParmVar", Param)
2611 .Case("TypedefName", Type)
2612 .Case("ObjCIvar", ObjCIVar)
2613 .Case("ObjCProperty", ObjCProp)
2614 .Case("Record", GenericRecord)
2615 .Case("ObjCInterface", ObjCInterface)
2616 .Case("ObjCProtocol", ObjCProtocol)
2617 .Case("Block", Block)
2618 .Case("CXXRecord", Class)
2619 .Case("Namespace", Namespace)
2620 .Case("Field", Field)
2621 .Case("CXXMethod", CXXMethod)
2625 // Something wasn't in our mapping, so be helpful and let the developer
2627 PrintFatalError(R.getLoc(), "Unknown subject type: " + R.getName());
2635 // For the simple cases where there's only a single entry in the mask, we
2636 // don't have to resort to bit fiddling.
2637 case Func: return "ExpectedFunction";
2638 case Var: return "ExpectedVariable";
2639 case Param: return "ExpectedParameter";
2640 case Class: return "ExpectedClass";
2641 case Enum: return "ExpectedEnum";
2643 // FIXME: Currently, this maps to ExpectedMethod based on existing code,
2644 // but should map to something a bit more accurate at some point.
2645 case ObjCMethod: return "ExpectedMethod";
2646 case Type: return "ExpectedType";
2647 case ObjCInterface: return "ExpectedObjectiveCInterface";
2648 case ObjCProtocol: return "ExpectedObjectiveCProtocol";
2650 // "GenericRecord" means struct, union or class; check the language options
2651 // and if not compiling for C++, strip off the class part. Note that this
2652 // relies on the fact that the context for this declares "Sema &S".
2654 return "(S.getLangOpts().CPlusPlus ? ExpectedStructOrUnionOrClass : "
2655 "ExpectedStructOrUnion)";
2656 case Func | ObjCMethod | Block: return "ExpectedFunctionMethodOrBlock";
2657 case Func | ObjCMethod | Class: return "ExpectedFunctionMethodOrClass";
2659 case Func | ObjCMethod | Param: return "ExpectedFunctionMethodOrParameter";
2660 case Func | ObjCMethod: return "ExpectedFunctionOrMethod";
2661 case Func | Var: return "ExpectedVariableOrFunction";
2663 // If not compiling for C++, the class portion does not apply.
2664 case Func | Var | Class:
2665 return "(S.getLangOpts().CPlusPlus ? ExpectedFunctionVariableOrClass : "
2666 "ExpectedVariableOrFunction)";
2668 case Func | Var | Class | ObjCInterface:
2669 return "(S.getLangOpts().CPlusPlus"
2670 " ? ((S.getLangOpts().ObjC1 || S.getLangOpts().ObjC2)"
2671 " ? ExpectedFunctionVariableClassOrObjCInterface"
2672 " : ExpectedFunctionVariableOrClass)"
2673 " : ((S.getLangOpts().ObjC1 || S.getLangOpts().ObjC2)"
2674 " ? ExpectedFunctionVariableOrObjCInterface"
2675 " : ExpectedVariableOrFunction))";
2677 case ObjCMethod | ObjCProp: return "ExpectedMethodOrProperty";
2678 case ObjCProtocol | ObjCInterface:
2679 return "ExpectedObjectiveCInterfaceOrProtocol";
2680 case Field | Var: return "ExpectedFieldOrGlobalVar";
2683 PrintFatalError(S.getLoc(),
2684 "Could not deduce diagnostic argument for Attr subjects");
2689 static std::string GetSubjectWithSuffix(const Record *R) {
2690 const std::string &B = R->getName();
2691 if (B == "DeclBase")
2696 static std::string GenerateCustomAppertainsTo(const Record &Subject,
2698 std::string FnName = "is" + Subject.getName().str();
2700 // If this code has already been generated, simply return the previous
2702 static std::set<std::string> CustomSubjectSet;
2703 auto I = CustomSubjectSet.find(FnName);
2704 if (I != CustomSubjectSet.end())
2707 Record *Base = Subject.getValueAsDef("Base");
2709 // Not currently support custom subjects within custom subjects.
2710 if (Base->isSubClassOf("SubsetSubject")) {
2711 PrintFatalError(Subject.getLoc(),
2712 "SubsetSubjects within SubsetSubjects is not supported");
2716 OS << "static bool " << FnName << "(const Decl *D) {\n";
2717 OS << " if (const auto *S = dyn_cast<";
2718 OS << GetSubjectWithSuffix(Base);
2720 OS << " return " << Subject.getValueAsString("CheckCode") << ";\n";
2721 OS << " return false;\n";
2724 CustomSubjectSet.insert(FnName);
2728 static std::string GenerateAppertainsTo(const Record &Attr, raw_ostream &OS) {
2729 // If the attribute does not contain a Subjects definition, then use the
2730 // default appertainsTo logic.
2731 if (Attr.isValueUnset("Subjects"))
2732 return "defaultAppertainsTo";
2734 const Record *SubjectObj = Attr.getValueAsDef("Subjects");
2735 std::vector<Record*> Subjects = SubjectObj->getValueAsListOfDefs("Subjects");
2737 // If the list of subjects is empty, it is assumed that the attribute
2738 // appertains to everything.
2739 if (Subjects.empty())
2740 return "defaultAppertainsTo";
2742 bool Warn = SubjectObj->getValueAsDef("Diag")->getValueAsBit("Warn");
2744 // Otherwise, generate an appertainsTo check specific to this attribute which
2745 // checks all of the given subjects against the Decl passed in. Return the
2746 // name of that check to the caller.
2747 std::string FnName = "check" + Attr.getName().str() + "AppertainsTo";
2748 std::stringstream SS;
2749 SS << "static bool " << FnName << "(Sema &S, const AttributeList &Attr, ";
2750 SS << "const Decl *D) {\n";
2752 for (auto I = Subjects.begin(), E = Subjects.end(); I != E; ++I) {
2753 // If the subject has custom code associated with it, generate a function
2754 // for it. The function cannot be inlined into this check (yet) because it
2755 // requires the subject to be of a specific type, and were that information
2756 // inlined here, it would not support an attribute with multiple custom
2758 if ((*I)->isSubClassOf("SubsetSubject")) {
2759 SS << "!" << GenerateCustomAppertainsTo(**I, OS) << "(D)";
2761 SS << "!isa<" << GetSubjectWithSuffix(*I) << ">(D)";
2768 SS << " S.Diag(Attr.getLoc(), diag::";
2769 SS << (Warn ? "warn_attribute_wrong_decl_type" :
2770 "err_attribute_wrong_decl_type");
2772 SS << " << Attr.getName() << ";
2773 SS << CalculateDiagnostic(*SubjectObj) << ";\n";
2774 SS << " return false;\n";
2776 SS << " return true;\n";
2783 static void GenerateDefaultLangOptRequirements(raw_ostream &OS) {
2784 OS << "static bool defaultDiagnoseLangOpts(Sema &, ";
2785 OS << "const AttributeList &) {\n";
2786 OS << " return true;\n";
2790 static std::string GenerateLangOptRequirements(const Record &R,
2792 // If the attribute has an empty or unset list of language requirements,
2793 // return the default handler.
2794 std::vector<Record *> LangOpts = R.getValueAsListOfDefs("LangOpts");
2795 if (LangOpts.empty())
2796 return "defaultDiagnoseLangOpts";
2798 // Generate the test condition, as well as a unique function name for the
2799 // diagnostic test. The list of options should usually be short (one or two
2800 // options), and the uniqueness isn't strictly necessary (it is just for
2801 // codegen efficiency).
2802 std::string FnName = "check", Test;
2803 for (auto I = LangOpts.begin(), E = LangOpts.end(); I != E; ++I) {
2804 std::string Part = (*I)->getValueAsString("Name");
2805 if ((*I)->getValueAsBit("Negated")) {
2809 Test += "S.LangOpts." + Part;
2814 FnName += "LangOpts";
2816 // If this code has already been generated, simply return the previous
2818 static std::set<std::string> CustomLangOptsSet;
2819 auto I = CustomLangOptsSet.find(FnName);
2820 if (I != CustomLangOptsSet.end())
2823 OS << "static bool " << FnName << "(Sema &S, const AttributeList &Attr) {\n";
2824 OS << " if (" << Test << ")\n";
2825 OS << " return true;\n\n";
2826 OS << " S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) ";
2827 OS << "<< Attr.getName();\n";
2828 OS << " return false;\n";
2831 CustomLangOptsSet.insert(FnName);
2835 static void GenerateDefaultTargetRequirements(raw_ostream &OS) {
2836 OS << "static bool defaultTargetRequirements(const TargetInfo &) {\n";
2837 OS << " return true;\n";
2841 static std::string GenerateTargetRequirements(const Record &Attr,
2842 const ParsedAttrMap &Dupes,
2844 // If the attribute is not a target specific attribute, return the default
2846 if (!Attr.isSubClassOf("TargetSpecificAttr"))
2847 return "defaultTargetRequirements";
2849 // Get the list of architectures to be tested for.
2850 const Record *R = Attr.getValueAsDef("Target");
2851 std::vector<std::string> Arches = R->getValueAsListOfStrings("Arches");
2852 if (Arches.empty()) {
2853 PrintError(Attr.getLoc(), "Empty list of target architectures for a "
2854 "target-specific attr");
2855 return "defaultTargetRequirements";
2858 // If there are other attributes which share the same parsed attribute kind,
2859 // such as target-specific attributes with a shared spelling, collapse the
2860 // duplicate architectures. This is required because a shared target-specific
2861 // attribute has only one AttributeList::Kind enumeration value, but it
2862 // applies to multiple target architectures. In order for the attribute to be
2863 // considered valid, all of its architectures need to be included.
2864 if (!Attr.isValueUnset("ParseKind")) {
2865 std::string APK = Attr.getValueAsString("ParseKind");
2866 for (const auto &I : Dupes) {
2867 if (I.first == APK) {
2868 std::vector<std::string> DA = I.second->getValueAsDef("Target")
2869 ->getValueAsListOfStrings("Arches");
2870 std::move(DA.begin(), DA.end(), std::back_inserter(Arches));
2875 std::string FnName = "isTarget";
2877 GenerateTargetSpecificAttrChecks(R, Arches, Test, &FnName);
2879 // If this code has already been generated, simply return the previous
2881 static std::set<std::string> CustomTargetSet;
2882 auto I = CustomTargetSet.find(FnName);
2883 if (I != CustomTargetSet.end())
2886 OS << "static bool " << FnName << "(const TargetInfo &Target) {\n";
2887 OS << " const llvm::Triple &T = Target.getTriple();\n";
2888 OS << " return " << Test << ";\n";
2891 CustomTargetSet.insert(FnName);
2895 static void GenerateDefaultSpellingIndexToSemanticSpelling(raw_ostream &OS) {
2896 OS << "static unsigned defaultSpellingIndexToSemanticSpelling("
2897 << "const AttributeList &Attr) {\n";
2898 OS << " return UINT_MAX;\n";
2902 static std::string GenerateSpellingIndexToSemanticSpelling(const Record &Attr,
2904 // If the attribute does not have a semantic form, we can bail out early.
2905 if (!Attr.getValueAsBit("ASTNode"))
2906 return "defaultSpellingIndexToSemanticSpelling";
2908 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(Attr);
2910 // If there are zero or one spellings, or all of the spellings share the same
2911 // name, we can also bail out early.
2912 if (Spellings.size() <= 1 || SpellingNamesAreCommon(Spellings))
2913 return "defaultSpellingIndexToSemanticSpelling";
2915 // Generate the enumeration we will use for the mapping.
2916 SemanticSpellingMap SemanticToSyntacticMap;
2917 std::string Enum = CreateSemanticSpellings(Spellings, SemanticToSyntacticMap);
2918 std::string Name = Attr.getName().str() + "AttrSpellingMap";
2920 OS << "static unsigned " << Name << "(const AttributeList &Attr) {\n";
2922 OS << " unsigned Idx = Attr.getAttributeSpellingListIndex();\n";
2923 WriteSemanticSpellingSwitch("Idx", SemanticToSyntacticMap, OS);
2929 static bool IsKnownToGCC(const Record &Attr) {
2930 // Look at the spellings for this subject; if there are any spellings which
2931 // claim to be known to GCC, the attribute is known to GCC.
2932 return llvm::any_of(
2933 GetFlattenedSpellings(Attr),
2934 [](const FlattenedSpelling &S) { return S.knownToGCC(); });
2937 /// Emits the parsed attribute helpers
2938 void EmitClangAttrParsedAttrImpl(RecordKeeper &Records, raw_ostream &OS) {
2939 emitSourceFileHeader("Parsed attribute helpers", OS);
2941 // Get the list of parsed attributes, and accept the optional list of
2942 // duplicates due to the ParseKind.
2943 ParsedAttrMap Dupes;
2944 ParsedAttrMap Attrs = getParsedAttrList(Records, &Dupes);
2946 // Generate the default appertainsTo, target and language option diagnostic,
2947 // and spelling list index mapping methods.
2948 GenerateDefaultAppertainsTo(OS);
2949 GenerateDefaultLangOptRequirements(OS);
2950 GenerateDefaultTargetRequirements(OS);
2951 GenerateDefaultSpellingIndexToSemanticSpelling(OS);
2953 // Generate the appertainsTo diagnostic methods and write their names into
2954 // another mapping. At the same time, generate the AttrInfoMap object
2955 // contents. Due to the reliance on generated code, use separate streams so
2956 // that code will not be interleaved.
2957 std::stringstream SS;
2958 for (auto I = Attrs.begin(), E = Attrs.end(); I != E; ++I) {
2959 // TODO: If the attribute's kind appears in the list of duplicates, that is
2960 // because it is a target-specific attribute that appears multiple times.
2961 // It would be beneficial to test whether the duplicates are "similar
2962 // enough" to each other to not cause problems. For instance, check that
2963 // the spellings are identical, and custom parsing rules match, etc.
2965 // We need to generate struct instances based off ParsedAttrInfo from
2966 // AttributeList.cpp.
2968 emitArgInfo(*I->second, SS);
2969 SS << ", " << I->second->getValueAsBit("HasCustomParsing");
2970 SS << ", " << I->second->isSubClassOf("TargetSpecificAttr");
2971 SS << ", " << I->second->isSubClassOf("TypeAttr");
2972 SS << ", " << I->second->isSubClassOf("StmtAttr");
2973 SS << ", " << IsKnownToGCC(*I->second);
2974 SS << ", " << GenerateAppertainsTo(*I->second, OS);
2975 SS << ", " << GenerateLangOptRequirements(*I->second, OS);
2976 SS << ", " << GenerateTargetRequirements(*I->second, Dupes, OS);
2977 SS << ", " << GenerateSpellingIndexToSemanticSpelling(*I->second, OS);
2983 SS << " // AT_" << I->first << "\n";
2986 OS << "static const ParsedAttrInfo AttrInfoMap[AttributeList::UnknownAttribute + 1] = {\n";
2991 // Emits the kind list of parsed attributes
2992 void EmitClangAttrParsedAttrKinds(RecordKeeper &Records, raw_ostream &OS) {
2993 emitSourceFileHeader("Attribute name matcher", OS);
2995 std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
2996 std::vector<StringMatcher::StringPair> GNU, Declspec, Microsoft, CXX11,
2998 std::set<std::string> Seen;
2999 for (const auto *A : Attrs) {
3000 const Record &Attr = *A;
3002 bool SemaHandler = Attr.getValueAsBit("SemaHandler");
3003 bool Ignored = Attr.getValueAsBit("Ignored");
3004 if (SemaHandler || Ignored) {
3005 // Attribute spellings can be shared between target-specific attributes,
3006 // and can be shared between syntaxes for the same attribute. For
3007 // instance, an attribute can be spelled GNU<"interrupt"> for an ARM-
3008 // specific attribute, or MSP430-specific attribute. Additionally, an
3009 // attribute can be spelled GNU<"dllexport"> and Declspec<"dllexport">
3010 // for the same semantic attribute. Ultimately, we need to map each of
3011 // these to a single AttributeList::Kind value, but the StringMatcher
3012 // class cannot handle duplicate match strings. So we generate a list of
3013 // string to match based on the syntax, and emit multiple string matchers
3014 // depending on the syntax used.
3015 std::string AttrName;
3016 if (Attr.isSubClassOf("TargetSpecificAttr") &&
3017 !Attr.isValueUnset("ParseKind")) {
3018 AttrName = Attr.getValueAsString("ParseKind");
3019 if (Seen.find(AttrName) != Seen.end())
3021 Seen.insert(AttrName);
3023 AttrName = NormalizeAttrName(StringRef(Attr.getName())).str();
3025 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(Attr);
3026 for (const auto &S : Spellings) {
3027 const std::string &RawSpelling = S.name();
3028 std::vector<StringMatcher::StringPair> *Matches = nullptr;
3029 std::string Spelling;
3030 const std::string &Variety = S.variety();
3031 if (Variety == "CXX11") {
3033 Spelling += S.nameSpace();
3035 } else if (Variety == "GNU")
3037 else if (Variety == "Declspec")
3038 Matches = &Declspec;
3039 else if (Variety == "Microsoft")
3040 Matches = &Microsoft;
3041 else if (Variety == "Keyword")
3042 Matches = &Keywords;
3043 else if (Variety == "Pragma")
3046 assert(Matches && "Unsupported spelling variety found");
3048 Spelling += NormalizeAttrSpelling(RawSpelling);
3050 Matches->push_back(StringMatcher::StringPair(Spelling,
3051 "return AttributeList::AT_" + AttrName + ";"));
3053 Matches->push_back(StringMatcher::StringPair(Spelling,
3054 "return AttributeList::IgnoredAttribute;"));
3059 OS << "static AttributeList::Kind getAttrKind(StringRef Name, ";
3060 OS << "AttributeList::Syntax Syntax) {\n";
3061 OS << " if (AttributeList::AS_GNU == Syntax) {\n";
3062 StringMatcher("Name", GNU, OS).Emit();
3063 OS << " } else if (AttributeList::AS_Declspec == Syntax) {\n";
3064 StringMatcher("Name", Declspec, OS).Emit();
3065 OS << " } else if (AttributeList::AS_Microsoft == Syntax) {\n";
3066 StringMatcher("Name", Microsoft, OS).Emit();
3067 OS << " } else if (AttributeList::AS_CXX11 == Syntax) {\n";
3068 StringMatcher("Name", CXX11, OS).Emit();
3069 OS << " } else if (AttributeList::AS_Keyword == Syntax || ";
3070 OS << "AttributeList::AS_ContextSensitiveKeyword == Syntax) {\n";
3071 StringMatcher("Name", Keywords, OS).Emit();
3072 OS << " } else if (AttributeList::AS_Pragma == Syntax) {\n";
3073 StringMatcher("Name", Pragma, OS).Emit();
3075 OS << " return AttributeList::UnknownAttribute;\n"
3079 // Emits the code to dump an attribute.
3080 void EmitClangAttrDump(RecordKeeper &Records, raw_ostream &OS) {
3081 emitSourceFileHeader("Attribute dumper", OS);
3083 OS << " switch (A->getKind()) {\n";
3084 std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr"), Args;
3085 for (const auto *Attr : Attrs) {
3086 const Record &R = *Attr;
3087 if (!R.getValueAsBit("ASTNode"))
3089 OS << " case attr::" << R.getName() << ": {\n";
3091 // If the attribute has a semantically-meaningful name (which is determined
3092 // by whether there is a Spelling enumeration for it), then write out the
3093 // spelling used for the attribute.
3094 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(R);
3095 if (Spellings.size() > 1 && !SpellingNamesAreCommon(Spellings))
3096 OS << " OS << \" \" << A->getSpelling();\n";
3098 Args = R.getValueAsListOfDefs("Args");
3099 if (!Args.empty()) {
3100 OS << " const auto *SA = cast<" << R.getName()
3102 for (const auto *Arg : Args)
3103 createArgument(*Arg, R.getName())->writeDump(OS);
3105 for (const auto *AI : Args)
3106 createArgument(*AI, R.getName())->writeDumpChildren(OS);
3115 void EmitClangAttrParserStringSwitches(RecordKeeper &Records,
3117 emitSourceFileHeader("Parser-related llvm::StringSwitch cases", OS);
3118 emitClangAttrArgContextList(Records, OS);
3119 emitClangAttrIdentifierArgList(Records, OS);
3120 emitClangAttrTypeArgList(Records, OS);
3121 emitClangAttrLateParsedList(Records, OS);
3124 class DocumentationData {
3126 const Record *Documentation;
3127 const Record *Attribute;
3129 DocumentationData(const Record &Documentation, const Record &Attribute)
3130 : Documentation(&Documentation), Attribute(&Attribute) {}
3133 static void WriteCategoryHeader(const Record *DocCategory,
3135 const std::string &Name = DocCategory->getValueAsString("Name");
3136 OS << Name << "\n" << std::string(Name.length(), '=') << "\n";
3138 // If there is content, print that as well.
3139 std::string ContentStr = DocCategory->getValueAsString("Content");
3140 // Trim leading and trailing newlines and spaces.
3141 OS << StringRef(ContentStr).trim();
3155 static void WriteDocumentation(const DocumentationData &Doc,
3157 // FIXME: there is no way to have a per-spelling category for the attribute
3158 // documentation. This may not be a limiting factor since the spellings
3159 // should generally be consistently applied across the category.
3161 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(*Doc.Attribute);
3163 // Determine the heading to be used for this attribute.
3164 std::string Heading = Doc.Documentation->getValueAsString("Heading");
3165 bool CustomHeading = !Heading.empty();
3166 if (Heading.empty()) {
3167 // If there's only one spelling, we can simply use that.
3168 if (Spellings.size() == 1)
3169 Heading = Spellings.begin()->name();
3171 std::set<std::string> Uniques;
3172 for (auto I = Spellings.begin(), E = Spellings.end();
3173 I != E && Uniques.size() <= 1; ++I) {
3174 std::string Spelling = NormalizeNameForSpellingComparison(I->name());
3175 Uniques.insert(Spelling);
3177 // If the semantic map has only one spelling, that is sufficient for our
3179 if (Uniques.size() == 1)
3180 Heading = *Uniques.begin();
3184 // If the heading is still empty, it is an error.
3185 if (Heading.empty())
3186 PrintFatalError(Doc.Attribute->getLoc(),
3187 "This attribute requires a heading to be specified");
3189 // Gather a list of unique spellings; this is not the same as the semantic
3190 // spelling for the attribute. Variations in underscores and other non-
3191 // semantic characters are still acceptable.
3192 std::vector<std::string> Names;
3194 unsigned SupportedSpellings = 0;
3195 for (const auto &I : Spellings) {
3196 SpellingKind Kind = StringSwitch<SpellingKind>(I.variety())
3198 .Case("CXX11", CXX11)
3199 .Case("Declspec", Declspec)
3200 .Case("Microsoft", Microsoft)
3201 .Case("Keyword", Keyword)
3202 .Case("Pragma", Pragma);
3204 // Mask in the supported spelling.
3205 SupportedSpellings |= Kind;
3208 if (Kind == CXX11 && !I.nameSpace().empty())
3209 Name = I.nameSpace() + "::";
3212 // If this name is the same as the heading, do not add it.
3213 if (Name != Heading)
3214 Names.push_back(Name);
3217 // Print out the heading for the attribute. If there are alternate spellings,
3218 // then display those after the heading.
3219 if (!CustomHeading && !Names.empty()) {
3221 for (auto I = Names.begin(), E = Names.end(); I != E; ++I) {
3222 if (I != Names.begin())
3228 OS << Heading << "\n" << std::string(Heading.length(), '-') << "\n";
3230 if (!SupportedSpellings)
3231 PrintFatalError(Doc.Attribute->getLoc(),
3232 "Attribute has no supported spellings; cannot be "
3235 // List what spelling syntaxes the attribute supports.
3236 OS << ".. csv-table:: Supported Syntaxes\n";
3237 OS << " :header: \"GNU\", \"C++11\", \"__declspec\", \"Keyword\",";
3238 OS << " \"Pragma\"\n\n";
3240 if (SupportedSpellings & GNU) OS << "X";
3242 if (SupportedSpellings & CXX11) OS << "X";
3244 if (SupportedSpellings & Declspec) OS << "X";
3246 if (SupportedSpellings & Keyword) OS << "X";
3248 if (SupportedSpellings & Pragma) OS << "X";
3251 // If the attribute is deprecated, print a message about it, and possibly
3252 // provide a replacement attribute.
3253 if (!Doc.Documentation->isValueUnset("Deprecated")) {
3254 OS << "This attribute has been deprecated, and may be removed in a future "
3255 << "version of Clang.";
3256 const Record &Deprecated = *Doc.Documentation->getValueAsDef("Deprecated");
3257 std::string Replacement = Deprecated.getValueAsString("Replacement");
3258 if (!Replacement.empty())
3259 OS << " This attribute has been superseded by ``"
3260 << Replacement << "``.";
3264 std::string ContentStr = Doc.Documentation->getValueAsString("Content");
3265 // Trim leading and trailing newlines and spaces.
3266 OS << StringRef(ContentStr).trim();
3271 void EmitClangAttrDocs(RecordKeeper &Records, raw_ostream &OS) {
3272 // Get the documentation introduction paragraph.
3273 const Record *Documentation = Records.getDef("GlobalDocumentation");
3274 if (!Documentation) {
3275 PrintFatalError("The Documentation top-level definition is missing, "
3276 "no documentation will be generated.");
3280 OS << Documentation->getValueAsString("Intro") << "\n";
3282 // Gather the Documentation lists from each of the attributes, based on the
3283 // category provided.
3284 std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
3285 std::map<const Record *, std::vector<DocumentationData>> SplitDocs;
3286 for (const auto *A : Attrs) {
3287 const Record &Attr = *A;
3288 std::vector<Record *> Docs = Attr.getValueAsListOfDefs("Documentation");
3289 for (const auto *D : Docs) {
3290 const Record &Doc = *D;
3291 const Record *Category = Doc.getValueAsDef("Category");
3292 // If the category is "undocumented", then there cannot be any other
3293 // documentation categories (otherwise, the attribute would become
3295 std::string Cat = Category->getValueAsString("Name");
3296 bool Undocumented = Cat == "Undocumented";
3297 if (Undocumented && Docs.size() > 1)
3298 PrintFatalError(Doc.getLoc(),
3299 "Attribute is \"Undocumented\", but has multiple "
3300 "documentation categories");
3303 SplitDocs[Category].push_back(DocumentationData(Doc, Attr));
3307 // Having split the attributes out based on what documentation goes where,
3308 // we can begin to generate sections of documentation.
3309 for (const auto &I : SplitDocs) {
3310 WriteCategoryHeader(I.first, OS);
3312 // Walk over each of the attributes in the category and write out their
3314 for (const auto &Doc : I.second)
3315 WriteDocumentation(Doc, OS);
3319 } // end namespace clang