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 the spelling of a GNU attribute (i.e. "x" in "__attribute__((x))"),
137 // removing "__" if it appears at the beginning and end of the attribute's name.
138 static StringRef NormalizeGNUAttrSpelling(StringRef AttrSpelling) {
139 if (AttrSpelling.startswith("__") && AttrSpelling.endswith("__")) {
140 AttrSpelling = AttrSpelling.substr(2, AttrSpelling.size() - 4);
146 typedef std::vector<std::pair<std::string, const Record *>> ParsedAttrMap;
148 static ParsedAttrMap getParsedAttrList(const RecordKeeper &Records,
149 ParsedAttrMap *Dupes = nullptr) {
150 std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
151 std::set<std::string> Seen;
153 for (const auto *Attr : Attrs) {
154 if (Attr->getValueAsBit("SemaHandler")) {
156 if (Attr->isSubClassOf("TargetSpecificAttr") &&
157 !Attr->isValueUnset("ParseKind")) {
158 AN = Attr->getValueAsString("ParseKind");
160 // If this attribute has already been handled, it does not need to be
162 if (Seen.find(AN) != Seen.end()) {
164 Dupes->push_back(std::make_pair(AN, Attr));
169 AN = NormalizeAttrName(Attr->getName()).str();
171 R.push_back(std::make_pair(AN, Attr));
180 std::string lowerName, upperName;
186 Argument(const Record &Arg, StringRef Attr)
187 : lowerName(Arg.getValueAsString("Name")), upperName(lowerName),
188 attrName(Attr), isOpt(false), Fake(false) {
189 if (!lowerName.empty()) {
190 lowerName[0] = std::tolower(lowerName[0]);
191 upperName[0] = std::toupper(upperName[0]);
193 // Work around MinGW's macro definition of 'interface' to 'struct'. We
194 // have an attribute argument called 'Interface', so only the lower case
195 // name conflicts with the macro definition.
196 if (lowerName == "interface")
197 lowerName = "interface_";
199 virtual ~Argument() = default;
201 StringRef getLowerName() const { return lowerName; }
202 StringRef getUpperName() const { return upperName; }
203 StringRef getAttrName() const { return attrName; }
205 bool isOptional() const { return isOpt; }
206 void setOptional(bool set) { isOpt = set; }
208 bool isFake() const { return Fake; }
209 void setFake(bool fake) { Fake = fake; }
211 // These functions print the argument contents formatted in different ways.
212 virtual void writeAccessors(raw_ostream &OS) const = 0;
213 virtual void writeAccessorDefinitions(raw_ostream &OS) const {}
214 virtual void writeASTVisitorTraversal(raw_ostream &OS) const {}
215 virtual void writeCloneArgs(raw_ostream &OS) const = 0;
216 virtual void writeTemplateInstantiationArgs(raw_ostream &OS) const = 0;
217 virtual void writeTemplateInstantiation(raw_ostream &OS) const {}
218 virtual void writeCtorBody(raw_ostream &OS) const {}
219 virtual void writeCtorInitializers(raw_ostream &OS) const = 0;
220 virtual void writeCtorDefaultInitializers(raw_ostream &OS) const = 0;
221 virtual void writeCtorParameters(raw_ostream &OS) const = 0;
222 virtual void writeDeclarations(raw_ostream &OS) const = 0;
223 virtual void writePCHReadArgs(raw_ostream &OS) const = 0;
224 virtual void writePCHReadDecls(raw_ostream &OS) const = 0;
225 virtual void writePCHWrite(raw_ostream &OS) const = 0;
226 virtual void writeValue(raw_ostream &OS) const = 0;
227 virtual void writeDump(raw_ostream &OS) const = 0;
228 virtual void writeDumpChildren(raw_ostream &OS) const {}
229 virtual void writeHasChildren(raw_ostream &OS) const { OS << "false"; }
231 virtual bool isEnumArg() const { return false; }
232 virtual bool isVariadicEnumArg() const { return false; }
233 virtual bool isVariadic() const { return false; }
235 virtual void writeImplicitCtorArgs(raw_ostream &OS) const {
236 OS << getUpperName();
240 class SimpleArgument : public Argument {
244 SimpleArgument(const Record &Arg, StringRef Attr, std::string T)
245 : Argument(Arg, Attr), type(std::move(T)) {}
247 std::string getType() const { return type; }
249 void writeAccessors(raw_ostream &OS) const override {
250 OS << " " << type << " get" << getUpperName() << "() const {\n";
251 OS << " return " << getLowerName() << ";\n";
255 void writeCloneArgs(raw_ostream &OS) const override {
256 OS << getLowerName();
259 void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
260 OS << "A->get" << getUpperName() << "()";
263 void writeCtorInitializers(raw_ostream &OS) const override {
264 OS << getLowerName() << "(" << getUpperName() << ")";
267 void writeCtorDefaultInitializers(raw_ostream &OS) const override {
268 OS << getLowerName() << "()";
271 void writeCtorParameters(raw_ostream &OS) const override {
272 OS << type << " " << getUpperName();
275 void writeDeclarations(raw_ostream &OS) const override {
276 OS << type << " " << getLowerName() << ";";
279 void writePCHReadDecls(raw_ostream &OS) const override {
280 std::string read = ReadPCHRecord(type);
281 OS << " " << type << " " << getLowerName() << " = " << read << ";\n";
284 void writePCHReadArgs(raw_ostream &OS) const override {
285 OS << getLowerName();
288 void writePCHWrite(raw_ostream &OS) const override {
289 OS << " " << WritePCHRecord(type, "SA->get" +
290 std::string(getUpperName()) + "()");
293 void writeValue(raw_ostream &OS) const override {
294 if (type == "FunctionDecl *") {
295 OS << "\" << get" << getUpperName()
296 << "()->getNameInfo().getAsString() << \"";
297 } else if (type == "IdentifierInfo *") {
300 OS << " if (get" << getUpperName() << "()) ";
303 OS << "OS << get" << getUpperName() << "()->getName();\n";
305 } else if (type == "TypeSourceInfo *") {
306 OS << "\" << get" << getUpperName() << "().getAsString() << \"";
308 OS << "\" << get" << getUpperName() << "() << \"";
312 void writeDump(raw_ostream &OS) const override {
313 if (type == "FunctionDecl *") {
314 OS << " OS << \" \";\n";
315 OS << " dumpBareDeclRef(SA->get" << getUpperName() << "());\n";
316 } else if (type == "IdentifierInfo *") {
318 OS << " if (SA->get" << getUpperName() << "())\n ";
319 OS << " OS << \" \" << SA->get" << getUpperName()
320 << "()->getName();\n";
321 } else if (type == "TypeSourceInfo *") {
322 OS << " OS << \" \" << SA->get" << getUpperName()
323 << "().getAsString();\n";
324 } else if (type == "bool") {
325 OS << " if (SA->get" << getUpperName() << "()) OS << \" "
326 << getUpperName() << "\";\n";
327 } else if (type == "int" || type == "unsigned") {
328 OS << " OS << \" \" << SA->get" << getUpperName() << "();\n";
330 llvm_unreachable("Unknown SimpleArgument type!");
335 class DefaultSimpleArgument : public SimpleArgument {
339 DefaultSimpleArgument(const Record &Arg, StringRef Attr,
340 std::string T, int64_t Default)
341 : SimpleArgument(Arg, Attr, T), Default(Default) {}
343 void writeAccessors(raw_ostream &OS) const override {
344 SimpleArgument::writeAccessors(OS);
346 OS << "\n\n static const " << getType() << " Default" << getUpperName()
348 if (getType() == "bool")
349 OS << (Default != 0 ? "true" : "false");
356 class StringArgument : public Argument {
358 StringArgument(const Record &Arg, StringRef Attr)
359 : Argument(Arg, Attr)
362 void writeAccessors(raw_ostream &OS) const override {
363 OS << " llvm::StringRef get" << getUpperName() << "() const {\n";
364 OS << " return llvm::StringRef(" << getLowerName() << ", "
365 << getLowerName() << "Length);\n";
367 OS << " unsigned get" << getUpperName() << "Length() const {\n";
368 OS << " return " << getLowerName() << "Length;\n";
370 OS << " void set" << getUpperName()
371 << "(ASTContext &C, llvm::StringRef S) {\n";
372 OS << " " << getLowerName() << "Length = S.size();\n";
373 OS << " this->" << getLowerName() << " = new (C, 1) char ["
374 << getLowerName() << "Length];\n";
375 OS << " if (!S.empty())\n";
376 OS << " std::memcpy(this->" << getLowerName() << ", S.data(), "
377 << getLowerName() << "Length);\n";
381 void writeCloneArgs(raw_ostream &OS) const override {
382 OS << "get" << getUpperName() << "()";
385 void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
386 OS << "A->get" << getUpperName() << "()";
389 void writeCtorBody(raw_ostream &OS) const override {
390 OS << " if (!" << getUpperName() << ".empty())\n";
391 OS << " std::memcpy(" << getLowerName() << ", " << getUpperName()
392 << ".data(), " << getLowerName() << "Length);\n";
395 void writeCtorInitializers(raw_ostream &OS) const override {
396 OS << getLowerName() << "Length(" << getUpperName() << ".size()),"
397 << getLowerName() << "(new (Ctx, 1) char[" << getLowerName()
401 void writeCtorDefaultInitializers(raw_ostream &OS) const override {
402 OS << getLowerName() << "Length(0)," << getLowerName() << "(nullptr)";
405 void writeCtorParameters(raw_ostream &OS) const override {
406 OS << "llvm::StringRef " << getUpperName();
409 void writeDeclarations(raw_ostream &OS) const override {
410 OS << "unsigned " << getLowerName() << "Length;\n";
411 OS << "char *" << getLowerName() << ";";
414 void writePCHReadDecls(raw_ostream &OS) const override {
415 OS << " std::string " << getLowerName()
416 << "= ReadString(Record, Idx);\n";
419 void writePCHReadArgs(raw_ostream &OS) const override {
420 OS << getLowerName();
423 void writePCHWrite(raw_ostream &OS) const override {
424 OS << " Record.AddString(SA->get" << getUpperName() << "());\n";
427 void writeValue(raw_ostream &OS) const override {
428 OS << "\\\"\" << get" << getUpperName() << "() << \"\\\"";
431 void writeDump(raw_ostream &OS) const override {
432 OS << " OS << \" \\\"\" << SA->get" << getUpperName()
433 << "() << \"\\\"\";\n";
437 class AlignedArgument : public Argument {
439 AlignedArgument(const Record &Arg, StringRef Attr)
440 : Argument(Arg, Attr)
443 void writeAccessors(raw_ostream &OS) const override {
444 OS << " bool is" << getUpperName() << "Dependent() const;\n";
446 OS << " unsigned get" << getUpperName() << "(ASTContext &Ctx) const;\n";
448 OS << " bool is" << getUpperName() << "Expr() const {\n";
449 OS << " return is" << getLowerName() << "Expr;\n";
452 OS << " Expr *get" << getUpperName() << "Expr() const {\n";
453 OS << " assert(is" << getLowerName() << "Expr);\n";
454 OS << " return " << getLowerName() << "Expr;\n";
457 OS << " TypeSourceInfo *get" << getUpperName() << "Type() const {\n";
458 OS << " assert(!is" << getLowerName() << "Expr);\n";
459 OS << " return " << getLowerName() << "Type;\n";
463 void writeAccessorDefinitions(raw_ostream &OS) const override {
464 OS << "bool " << getAttrName() << "Attr::is" << getUpperName()
465 << "Dependent() const {\n";
466 OS << " if (is" << getLowerName() << "Expr)\n";
467 OS << " return " << getLowerName() << "Expr && (" << getLowerName()
468 << "Expr->isValueDependent() || " << getLowerName()
469 << "Expr->isTypeDependent());\n";
471 OS << " return " << getLowerName()
472 << "Type->getType()->isDependentType();\n";
475 // FIXME: Do not do the calculation here
476 // FIXME: Handle types correctly
477 // A null pointer means maximum alignment
478 OS << "unsigned " << getAttrName() << "Attr::get" << getUpperName()
479 << "(ASTContext &Ctx) const {\n";
480 OS << " assert(!is" << getUpperName() << "Dependent());\n";
481 OS << " if (is" << getLowerName() << "Expr)\n";
482 OS << " return " << getLowerName() << "Expr ? " << getLowerName()
483 << "Expr->EvaluateKnownConstInt(Ctx).getZExtValue()"
484 << " * Ctx.getCharWidth() : "
485 << "Ctx.getTargetDefaultAlignForAttributeAligned();\n";
487 OS << " return 0; // FIXME\n";
491 void writeCloneArgs(raw_ostream &OS) const override {
492 OS << "is" << getLowerName() << "Expr, is" << getLowerName()
493 << "Expr ? static_cast<void*>(" << getLowerName()
494 << "Expr) : " << getLowerName()
498 void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
499 // FIXME: move the definition in Sema::InstantiateAttrs to here.
500 // In the meantime, aligned attributes are cloned.
503 void writeCtorBody(raw_ostream &OS) const override {
504 OS << " if (is" << getLowerName() << "Expr)\n";
505 OS << " " << getLowerName() << "Expr = reinterpret_cast<Expr *>("
506 << getUpperName() << ");\n";
508 OS << " " << getLowerName()
509 << "Type = reinterpret_cast<TypeSourceInfo *>(" << getUpperName()
513 void writeCtorInitializers(raw_ostream &OS) const override {
514 OS << "is" << getLowerName() << "Expr(Is" << getUpperName() << "Expr)";
517 void writeCtorDefaultInitializers(raw_ostream &OS) const override {
518 OS << "is" << getLowerName() << "Expr(false)";
521 void writeCtorParameters(raw_ostream &OS) const override {
522 OS << "bool Is" << getUpperName() << "Expr, void *" << getUpperName();
525 void writeImplicitCtorArgs(raw_ostream &OS) const override {
526 OS << "Is" << getUpperName() << "Expr, " << getUpperName();
529 void writeDeclarations(raw_ostream &OS) const override {
530 OS << "bool is" << getLowerName() << "Expr;\n";
532 OS << "Expr *" << getLowerName() << "Expr;\n";
533 OS << "TypeSourceInfo *" << getLowerName() << "Type;\n";
537 void writePCHReadArgs(raw_ostream &OS) const override {
538 OS << "is" << getLowerName() << "Expr, " << getLowerName() << "Ptr";
541 void writePCHReadDecls(raw_ostream &OS) const override {
542 OS << " bool is" << getLowerName() << "Expr = Record[Idx++];\n";
543 OS << " void *" << getLowerName() << "Ptr;\n";
544 OS << " if (is" << getLowerName() << "Expr)\n";
545 OS << " " << getLowerName() << "Ptr = ReadExpr(F);\n";
547 OS << " " << getLowerName()
548 << "Ptr = GetTypeSourceInfo(F, Record, Idx);\n";
551 void writePCHWrite(raw_ostream &OS) const override {
552 OS << " Record.push_back(SA->is" << getUpperName() << "Expr());\n";
553 OS << " if (SA->is" << getUpperName() << "Expr())\n";
554 OS << " Record.AddStmt(SA->get" << getUpperName() << "Expr());\n";
556 OS << " Record.AddTypeSourceInfo(SA->get" << getUpperName()
560 void writeValue(raw_ostream &OS) const override {
562 // The aligned attribute argument expression is optional.
563 OS << " if (is" << getLowerName() << "Expr && "
564 << getLowerName() << "Expr)\n";
565 OS << " " << getLowerName() << "Expr->printPretty(OS, nullptr, Policy);\n";
569 void writeDump(raw_ostream &OS) const override {}
571 void writeDumpChildren(raw_ostream &OS) const override {
572 OS << " if (SA->is" << getUpperName() << "Expr())\n";
573 OS << " dumpStmt(SA->get" << getUpperName() << "Expr());\n";
575 OS << " dumpType(SA->get" << getUpperName()
576 << "Type()->getType());\n";
579 void writeHasChildren(raw_ostream &OS) const override {
580 OS << "SA->is" << getUpperName() << "Expr()";
584 class VariadicArgument : public Argument {
585 std::string Type, ArgName, ArgSizeName, RangeName;
588 // Assumed to receive a parameter: raw_ostream OS.
589 virtual void writeValueImpl(raw_ostream &OS) const {
590 OS << " OS << Val;\n";
594 VariadicArgument(const Record &Arg, StringRef Attr, std::string T)
595 : Argument(Arg, Attr), Type(std::move(T)),
596 ArgName(getLowerName().str() + "_"), ArgSizeName(ArgName + "Size"),
597 RangeName(getLowerName()) {}
599 const std::string &getType() const { return Type; }
600 const std::string &getArgName() const { return ArgName; }
601 const std::string &getArgSizeName() const { return ArgSizeName; }
602 bool isVariadic() const override { return true; }
604 void writeAccessors(raw_ostream &OS) const override {
605 std::string IteratorType = getLowerName().str() + "_iterator";
606 std::string BeginFn = getLowerName().str() + "_begin()";
607 std::string EndFn = getLowerName().str() + "_end()";
609 OS << " typedef " << Type << "* " << IteratorType << ";\n";
610 OS << " " << IteratorType << " " << BeginFn << " const {"
611 << " return " << ArgName << "; }\n";
612 OS << " " << IteratorType << " " << EndFn << " const {"
613 << " return " << ArgName << " + " << ArgSizeName << "; }\n";
614 OS << " unsigned " << getLowerName() << "_size() const {"
615 << " return " << ArgSizeName << "; }\n";
616 OS << " llvm::iterator_range<" << IteratorType << "> " << RangeName
617 << "() const { return llvm::make_range(" << BeginFn << ", " << EndFn
621 void writeCloneArgs(raw_ostream &OS) const override {
622 OS << ArgName << ", " << ArgSizeName;
625 void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
626 // This isn't elegant, but we have to go through public methods...
627 OS << "A->" << getLowerName() << "_begin(), "
628 << "A->" << getLowerName() << "_size()";
631 void writeCtorBody(raw_ostream &OS) const override {
632 OS << " std::copy(" << getUpperName() << ", " << getUpperName()
633 << " + " << ArgSizeName << ", " << ArgName << ");\n";
636 void writeCtorInitializers(raw_ostream &OS) const override {
637 OS << ArgSizeName << "(" << getUpperName() << "Size), "
638 << ArgName << "(new (Ctx, 16) " << getType() << "["
639 << ArgSizeName << "])";
642 void writeCtorDefaultInitializers(raw_ostream &OS) const override {
643 OS << ArgSizeName << "(0), " << ArgName << "(nullptr)";
646 void writeCtorParameters(raw_ostream &OS) const override {
647 OS << getType() << " *" << getUpperName() << ", unsigned "
648 << getUpperName() << "Size";
651 void writeImplicitCtorArgs(raw_ostream &OS) const override {
652 OS << getUpperName() << ", " << getUpperName() << "Size";
655 void writeDeclarations(raw_ostream &OS) const override {
656 OS << " unsigned " << ArgSizeName << ";\n";
657 OS << " " << getType() << " *" << ArgName << ";";
660 void writePCHReadDecls(raw_ostream &OS) const override {
661 OS << " unsigned " << getLowerName() << "Size = Record[Idx++];\n";
662 OS << " SmallVector<" << getType() << ", 4> "
663 << getLowerName() << ";\n";
664 OS << " " << getLowerName() << ".reserve(" << getLowerName()
667 // If we can't store the values in the current type (if it's something
668 // like StringRef), store them in a different type and convert the
669 // container afterwards.
670 std::string StorageType = getStorageType(getType());
671 std::string StorageName = getLowerName();
672 if (StorageType != getType()) {
673 StorageName += "Storage";
674 OS << " SmallVector<" << StorageType << ", 4> "
675 << StorageName << ";\n";
676 OS << " " << StorageName << ".reserve(" << getLowerName()
680 OS << " for (unsigned i = 0; i != " << getLowerName() << "Size; ++i)\n";
681 std::string read = ReadPCHRecord(Type);
682 OS << " " << StorageName << ".push_back(" << read << ");\n";
684 if (StorageType != getType()) {
685 OS << " for (unsigned i = 0; i != " << getLowerName() << "Size; ++i)\n";
686 OS << " " << getLowerName() << ".push_back("
687 << StorageName << "[i]);\n";
691 void writePCHReadArgs(raw_ostream &OS) const override {
692 OS << getLowerName() << ".data(), " << getLowerName() << "Size";
695 void writePCHWrite(raw_ostream &OS) const override {
696 OS << " Record.push_back(SA->" << getLowerName() << "_size());\n";
697 OS << " for (auto &Val : SA->" << RangeName << "())\n";
698 OS << " " << WritePCHRecord(Type, "Val");
701 void writeValue(raw_ostream &OS) const override {
703 OS << " bool isFirst = true;\n"
704 << " for (const auto &Val : " << RangeName << "()) {\n"
705 << " if (isFirst) isFirst = false;\n"
706 << " else OS << \", \";\n";
712 void writeDump(raw_ostream &OS) const override {
713 OS << " for (const auto &Val : SA->" << RangeName << "())\n";
714 OS << " OS << \" \" << Val;\n";
718 // Unique the enums, but maintain the original declaration ordering.
719 std::vector<std::string>
720 uniqueEnumsInOrder(const std::vector<std::string> &enums) {
721 std::vector<std::string> uniques;
722 SmallDenseSet<StringRef, 8> unique_set;
723 for (const auto &i : enums) {
724 if (unique_set.insert(i).second)
725 uniques.push_back(i);
730 class EnumArgument : public Argument {
732 std::vector<std::string> values, enums, uniques;
734 EnumArgument(const Record &Arg, StringRef Attr)
735 : Argument(Arg, Attr), type(Arg.getValueAsString("Type")),
736 values(Arg.getValueAsListOfStrings("Values")),
737 enums(Arg.getValueAsListOfStrings("Enums")),
738 uniques(uniqueEnumsInOrder(enums))
740 // FIXME: Emit a proper error
741 assert(!uniques.empty());
744 bool isEnumArg() const override { return true; }
746 void writeAccessors(raw_ostream &OS) const override {
747 OS << " " << type << " get" << getUpperName() << "() const {\n";
748 OS << " return " << getLowerName() << ";\n";
752 void writeCloneArgs(raw_ostream &OS) const override {
753 OS << getLowerName();
756 void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
757 OS << "A->get" << getUpperName() << "()";
759 void writeCtorInitializers(raw_ostream &OS) const override {
760 OS << getLowerName() << "(" << getUpperName() << ")";
762 void writeCtorDefaultInitializers(raw_ostream &OS) const override {
763 OS << getLowerName() << "(" << type << "(0))";
765 void writeCtorParameters(raw_ostream &OS) const override {
766 OS << type << " " << getUpperName();
768 void writeDeclarations(raw_ostream &OS) const override {
769 auto i = uniques.cbegin(), e = uniques.cend();
770 // The last one needs to not have a comma.
774 OS << " enum " << type << " {\n";
776 OS << " " << *i << ",\n";
777 OS << " " << *e << "\n";
780 OS << " " << type << " " << getLowerName() << ";";
783 void writePCHReadDecls(raw_ostream &OS) const override {
784 OS << " " << getAttrName() << "Attr::" << type << " " << getLowerName()
785 << "(static_cast<" << getAttrName() << "Attr::" << type
786 << ">(Record[Idx++]));\n";
789 void writePCHReadArgs(raw_ostream &OS) const override {
790 OS << getLowerName();
793 void writePCHWrite(raw_ostream &OS) const override {
794 OS << "Record.push_back(SA->get" << getUpperName() << "());\n";
797 void writeValue(raw_ostream &OS) const override {
798 // FIXME: this isn't 100% correct -- some enum arguments require printing
799 // as a string literal, while others require printing as an identifier.
800 // Tablegen currently does not distinguish between the two forms.
801 OS << "\\\"\" << " << getAttrName() << "Attr::Convert" << type << "ToStr(get"
802 << getUpperName() << "()) << \"\\\"";
805 void writeDump(raw_ostream &OS) const override {
806 OS << " switch(SA->get" << getUpperName() << "()) {\n";
807 for (const auto &I : uniques) {
808 OS << " case " << getAttrName() << "Attr::" << I << ":\n";
809 OS << " OS << \" " << I << "\";\n";
815 void writeConversion(raw_ostream &OS) const {
816 OS << " static bool ConvertStrTo" << type << "(StringRef Val, ";
817 OS << type << " &Out) {\n";
818 OS << " Optional<" << type << "> R = llvm::StringSwitch<Optional<";
819 OS << type << ">>(Val)\n";
820 for (size_t I = 0; I < enums.size(); ++I) {
821 OS << " .Case(\"" << values[I] << "\", ";
822 OS << getAttrName() << "Attr::" << enums[I] << ")\n";
824 OS << " .Default(Optional<" << type << ">());\n";
826 OS << " Out = *R;\n return true;\n }\n";
827 OS << " return false;\n";
830 // Mapping from enumeration values back to enumeration strings isn't
831 // trivial because some enumeration values have multiple named
832 // enumerators, such as type_visibility(internal) and
833 // type_visibility(hidden) both mapping to TypeVisibilityAttr::Hidden.
834 OS << " static const char *Convert" << type << "ToStr("
835 << type << " Val) {\n"
836 << " switch(Val) {\n";
837 SmallDenseSet<StringRef, 8> Uniques;
838 for (size_t I = 0; I < enums.size(); ++I) {
839 if (Uniques.insert(enums[I]).second)
840 OS << " case " << getAttrName() << "Attr::" << enums[I]
841 << ": return \"" << values[I] << "\";\n";
844 << " llvm_unreachable(\"No enumerator with that value\");\n"
849 class VariadicEnumArgument: public VariadicArgument {
850 std::string type, QualifiedTypeName;
851 std::vector<std::string> values, enums, uniques;
854 void writeValueImpl(raw_ostream &OS) const override {
855 // FIXME: this isn't 100% correct -- some enum arguments require printing
856 // as a string literal, while others require printing as an identifier.
857 // Tablegen currently does not distinguish between the two forms.
858 OS << " OS << \"\\\"\" << " << getAttrName() << "Attr::Convert" << type
859 << "ToStr(Val)" << "<< \"\\\"\";\n";
863 VariadicEnumArgument(const Record &Arg, StringRef Attr)
864 : VariadicArgument(Arg, Attr, Arg.getValueAsString("Type")),
865 type(Arg.getValueAsString("Type")),
866 values(Arg.getValueAsListOfStrings("Values")),
867 enums(Arg.getValueAsListOfStrings("Enums")),
868 uniques(uniqueEnumsInOrder(enums))
870 QualifiedTypeName = getAttrName().str() + "Attr::" + type;
872 // FIXME: Emit a proper error
873 assert(!uniques.empty());
876 bool isVariadicEnumArg() const override { return true; }
878 void writeDeclarations(raw_ostream &OS) const override {
879 auto i = uniques.cbegin(), e = uniques.cend();
880 // The last one needs to not have a comma.
884 OS << " enum " << type << " {\n";
886 OS << " " << *i << ",\n";
887 OS << " " << *e << "\n";
891 VariadicArgument::writeDeclarations(OS);
894 void writeDump(raw_ostream &OS) const override {
895 OS << " for (" << getAttrName() << "Attr::" << getLowerName()
896 << "_iterator I = SA->" << getLowerName() << "_begin(), E = SA->"
897 << getLowerName() << "_end(); I != E; ++I) {\n";
898 OS << " switch(*I) {\n";
899 for (const auto &UI : uniques) {
900 OS << " case " << getAttrName() << "Attr::" << UI << ":\n";
901 OS << " OS << \" " << UI << "\";\n";
908 void writePCHReadDecls(raw_ostream &OS) const override {
909 OS << " unsigned " << getLowerName() << "Size = Record[Idx++];\n";
910 OS << " SmallVector<" << QualifiedTypeName << ", 4> " << getLowerName()
912 OS << " " << getLowerName() << ".reserve(" << getLowerName()
914 OS << " for (unsigned i = " << getLowerName() << "Size; i; --i)\n";
915 OS << " " << getLowerName() << ".push_back(" << "static_cast<"
916 << QualifiedTypeName << ">(Record[Idx++]));\n";
919 void writePCHWrite(raw_ostream &OS) const override {
920 OS << " Record.push_back(SA->" << getLowerName() << "_size());\n";
921 OS << " for (" << getAttrName() << "Attr::" << getLowerName()
922 << "_iterator i = SA->" << getLowerName() << "_begin(), e = SA->"
923 << getLowerName() << "_end(); i != e; ++i)\n";
924 OS << " " << WritePCHRecord(QualifiedTypeName, "(*i)");
927 void writeConversion(raw_ostream &OS) const {
928 OS << " static bool ConvertStrTo" << type << "(StringRef Val, ";
929 OS << type << " &Out) {\n";
930 OS << " Optional<" << type << "> R = llvm::StringSwitch<Optional<";
931 OS << type << ">>(Val)\n";
932 for (size_t I = 0; I < enums.size(); ++I) {
933 OS << " .Case(\"" << values[I] << "\", ";
934 OS << getAttrName() << "Attr::" << enums[I] << ")\n";
936 OS << " .Default(Optional<" << type << ">());\n";
938 OS << " Out = *R;\n return true;\n }\n";
939 OS << " return false;\n";
942 OS << " static const char *Convert" << type << "ToStr("
943 << type << " Val) {\n"
944 << " switch(Val) {\n";
945 SmallDenseSet<StringRef, 8> Uniques;
946 for (size_t I = 0; I < enums.size(); ++I) {
947 if (Uniques.insert(enums[I]).second)
948 OS << " case " << getAttrName() << "Attr::" << enums[I]
949 << ": return \"" << values[I] << "\";\n";
952 << " llvm_unreachable(\"No enumerator with that value\");\n"
957 class VersionArgument : public Argument {
959 VersionArgument(const Record &Arg, StringRef Attr)
960 : Argument(Arg, Attr)
963 void writeAccessors(raw_ostream &OS) const override {
964 OS << " VersionTuple get" << getUpperName() << "() const {\n";
965 OS << " return " << getLowerName() << ";\n";
967 OS << " void set" << getUpperName()
968 << "(ASTContext &C, VersionTuple V) {\n";
969 OS << " " << getLowerName() << " = V;\n";
973 void writeCloneArgs(raw_ostream &OS) const override {
974 OS << "get" << getUpperName() << "()";
977 void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
978 OS << "A->get" << getUpperName() << "()";
981 void writeCtorInitializers(raw_ostream &OS) const override {
982 OS << getLowerName() << "(" << getUpperName() << ")";
985 void writeCtorDefaultInitializers(raw_ostream &OS) const override {
986 OS << getLowerName() << "()";
989 void writeCtorParameters(raw_ostream &OS) const override {
990 OS << "VersionTuple " << getUpperName();
993 void writeDeclarations(raw_ostream &OS) const override {
994 OS << "VersionTuple " << getLowerName() << ";\n";
997 void writePCHReadDecls(raw_ostream &OS) const override {
998 OS << " VersionTuple " << getLowerName()
999 << "= ReadVersionTuple(Record, Idx);\n";
1002 void writePCHReadArgs(raw_ostream &OS) const override {
1003 OS << getLowerName();
1006 void writePCHWrite(raw_ostream &OS) const override {
1007 OS << " Record.AddVersionTuple(SA->get" << getUpperName() << "());\n";
1010 void writeValue(raw_ostream &OS) const override {
1011 OS << getLowerName() << "=\" << get" << getUpperName() << "() << \"";
1014 void writeDump(raw_ostream &OS) const override {
1015 OS << " OS << \" \" << SA->get" << getUpperName() << "();\n";
1019 class ExprArgument : public SimpleArgument {
1021 ExprArgument(const Record &Arg, StringRef Attr)
1022 : SimpleArgument(Arg, Attr, "Expr *")
1025 void writeASTVisitorTraversal(raw_ostream &OS) const override {
1027 << "getDerived().TraverseStmt(A->get" << getUpperName() << "()))\n";
1028 OS << " return false;\n";
1031 void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
1032 OS << "tempInst" << getUpperName();
1035 void writeTemplateInstantiation(raw_ostream &OS) const override {
1036 OS << " " << getType() << " tempInst" << getUpperName() << ";\n";
1038 OS << " EnterExpressionEvaluationContext "
1039 << "Unevaluated(S, Sema::Unevaluated);\n";
1040 OS << " ExprResult " << "Result = S.SubstExpr("
1041 << "A->get" << getUpperName() << "(), TemplateArgs);\n";
1042 OS << " tempInst" << getUpperName() << " = "
1043 << "Result.getAs<Expr>();\n";
1047 void writeDump(raw_ostream &OS) const override {}
1049 void writeDumpChildren(raw_ostream &OS) const override {
1050 OS << " dumpStmt(SA->get" << getUpperName() << "());\n";
1053 void writeHasChildren(raw_ostream &OS) const override { OS << "true"; }
1056 class VariadicExprArgument : public VariadicArgument {
1058 VariadicExprArgument(const Record &Arg, StringRef Attr)
1059 : VariadicArgument(Arg, Attr, "Expr *")
1062 void writeASTVisitorTraversal(raw_ostream &OS) const override {
1064 OS << " " << getType() << " *I = A->" << getLowerName()
1066 OS << " " << getType() << " *E = A->" << getLowerName()
1068 OS << " for (; I != E; ++I) {\n";
1069 OS << " if (!getDerived().TraverseStmt(*I))\n";
1070 OS << " return false;\n";
1075 void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
1076 OS << "tempInst" << getUpperName() << ", "
1077 << "A->" << getLowerName() << "_size()";
1080 void writeTemplateInstantiation(raw_ostream &OS) const override {
1081 OS << " auto *tempInst" << getUpperName()
1082 << " = new (C, 16) " << getType()
1083 << "[A->" << getLowerName() << "_size()];\n";
1085 OS << " EnterExpressionEvaluationContext "
1086 << "Unevaluated(S, Sema::Unevaluated);\n";
1087 OS << " " << getType() << " *TI = tempInst" << getUpperName()
1089 OS << " " << getType() << " *I = A->" << getLowerName()
1091 OS << " " << getType() << " *E = A->" << getLowerName()
1093 OS << " for (; I != E; ++I, ++TI) {\n";
1094 OS << " ExprResult Result = S.SubstExpr(*I, TemplateArgs);\n";
1095 OS << " *TI = Result.getAs<Expr>();\n";
1100 void writeDump(raw_ostream &OS) const override {}
1102 void writeDumpChildren(raw_ostream &OS) const override {
1103 OS << " for (" << getAttrName() << "Attr::" << getLowerName()
1104 << "_iterator I = SA->" << getLowerName() << "_begin(), E = SA->"
1105 << getLowerName() << "_end(); I != E; ++I)\n";
1106 OS << " dumpStmt(*I);\n";
1109 void writeHasChildren(raw_ostream &OS) const override {
1110 OS << "SA->" << getLowerName() << "_begin() != "
1111 << "SA->" << getLowerName() << "_end()";
1115 class VariadicStringArgument : public VariadicArgument {
1117 VariadicStringArgument(const Record &Arg, StringRef Attr)
1118 : VariadicArgument(Arg, Attr, "StringRef")
1121 void writeCtorBody(raw_ostream &OS) const override {
1122 OS << " for (size_t I = 0, E = " << getArgSizeName() << "; I != E;\n"
1124 " StringRef Ref = " << getUpperName() << "[I];\n"
1125 " if (!Ref.empty()) {\n"
1126 " char *Mem = new (Ctx, 1) char[Ref.size()];\n"
1127 " std::memcpy(Mem, Ref.data(), Ref.size());\n"
1128 " " << getArgName() << "[I] = StringRef(Mem, Ref.size());\n"
1133 void writeValueImpl(raw_ostream &OS) const override {
1134 OS << " OS << \"\\\"\" << Val << \"\\\"\";\n";
1138 class TypeArgument : public SimpleArgument {
1140 TypeArgument(const Record &Arg, StringRef Attr)
1141 : SimpleArgument(Arg, Attr, "TypeSourceInfo *")
1144 void writeAccessors(raw_ostream &OS) const override {
1145 OS << " QualType get" << getUpperName() << "() const {\n";
1146 OS << " return " << getLowerName() << "->getType();\n";
1148 OS << " " << getType() << " get" << getUpperName() << "Loc() const {\n";
1149 OS << " return " << getLowerName() << ";\n";
1153 void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
1154 OS << "A->get" << getUpperName() << "Loc()";
1157 void writePCHWrite(raw_ostream &OS) const override {
1158 OS << " " << WritePCHRecord(
1159 getType(), "SA->get" + std::string(getUpperName()) + "Loc()");
1163 } // end anonymous namespace
1165 static std::unique_ptr<Argument>
1166 createArgument(const Record &Arg, StringRef Attr,
1167 const Record *Search = nullptr) {
1171 std::unique_ptr<Argument> Ptr;
1172 llvm::StringRef ArgName = Search->getName();
1174 if (ArgName == "AlignedArgument")
1175 Ptr = llvm::make_unique<AlignedArgument>(Arg, Attr);
1176 else if (ArgName == "EnumArgument")
1177 Ptr = llvm::make_unique<EnumArgument>(Arg, Attr);
1178 else if (ArgName == "ExprArgument")
1179 Ptr = llvm::make_unique<ExprArgument>(Arg, Attr);
1180 else if (ArgName == "FunctionArgument")
1181 Ptr = llvm::make_unique<SimpleArgument>(Arg, Attr, "FunctionDecl *");
1182 else if (ArgName == "IdentifierArgument")
1183 Ptr = llvm::make_unique<SimpleArgument>(Arg, Attr, "IdentifierInfo *");
1184 else if (ArgName == "DefaultBoolArgument")
1185 Ptr = llvm::make_unique<DefaultSimpleArgument>(
1186 Arg, Attr, "bool", Arg.getValueAsBit("Default"));
1187 else if (ArgName == "BoolArgument")
1188 Ptr = llvm::make_unique<SimpleArgument>(Arg, Attr, "bool");
1189 else if (ArgName == "DefaultIntArgument")
1190 Ptr = llvm::make_unique<DefaultSimpleArgument>(
1191 Arg, Attr, "int", Arg.getValueAsInt("Default"));
1192 else if (ArgName == "IntArgument")
1193 Ptr = llvm::make_unique<SimpleArgument>(Arg, Attr, "int");
1194 else if (ArgName == "StringArgument")
1195 Ptr = llvm::make_unique<StringArgument>(Arg, Attr);
1196 else if (ArgName == "TypeArgument")
1197 Ptr = llvm::make_unique<TypeArgument>(Arg, Attr);
1198 else if (ArgName == "UnsignedArgument")
1199 Ptr = llvm::make_unique<SimpleArgument>(Arg, Attr, "unsigned");
1200 else if (ArgName == "VariadicUnsignedArgument")
1201 Ptr = llvm::make_unique<VariadicArgument>(Arg, Attr, "unsigned");
1202 else if (ArgName == "VariadicStringArgument")
1203 Ptr = llvm::make_unique<VariadicStringArgument>(Arg, Attr);
1204 else if (ArgName == "VariadicEnumArgument")
1205 Ptr = llvm::make_unique<VariadicEnumArgument>(Arg, Attr);
1206 else if (ArgName == "VariadicExprArgument")
1207 Ptr = llvm::make_unique<VariadicExprArgument>(Arg, Attr);
1208 else if (ArgName == "VersionArgument")
1209 Ptr = llvm::make_unique<VersionArgument>(Arg, Attr);
1212 // Search in reverse order so that the most-derived type is handled first.
1213 ArrayRef<std::pair<Record*, SMRange>> Bases = Search->getSuperClasses();
1214 for (const auto &Base : llvm::reverse(Bases)) {
1215 if ((Ptr = createArgument(Arg, Attr, Base.first)))
1220 if (Ptr && Arg.getValueAsBit("Optional"))
1221 Ptr->setOptional(true);
1223 if (Ptr && Arg.getValueAsBit("Fake"))
1229 static void writeAvailabilityValue(raw_ostream &OS) {
1230 OS << "\" << getPlatform()->getName();\n"
1231 << " if (getStrict()) OS << \", strict\";\n"
1232 << " if (!getIntroduced().empty()) OS << \", introduced=\" << getIntroduced();\n"
1233 << " if (!getDeprecated().empty()) OS << \", deprecated=\" << getDeprecated();\n"
1234 << " if (!getObsoleted().empty()) OS << \", obsoleted=\" << getObsoleted();\n"
1235 << " if (getUnavailable()) OS << \", unavailable\";\n"
1239 static void writeDeprecatedAttrValue(raw_ostream &OS, std::string &Variety) {
1240 OS << "\\\"\" << getMessage() << \"\\\"\";\n";
1241 // Only GNU deprecated has an optional fixit argument at the second position.
1242 if (Variety == "GNU")
1243 OS << " if (!getReplacement().empty()) OS << \", \\\"\""
1244 " << getReplacement() << \"\\\"\";\n";
1248 static void writeGetSpellingFunction(Record &R, raw_ostream &OS) {
1249 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(R);
1251 OS << "const char *" << R.getName() << "Attr::getSpelling() const {\n";
1252 if (Spellings.empty()) {
1253 OS << " return \"(No spelling)\";\n}\n\n";
1257 OS << " switch (SpellingListIndex) {\n"
1259 " llvm_unreachable(\"Unknown attribute spelling!\");\n"
1260 " return \"(No spelling)\";\n";
1262 for (unsigned I = 0; I < Spellings.size(); ++I)
1263 OS << " case " << I << ":\n"
1264 " return \"" << Spellings[I].name() << "\";\n";
1265 // End of the switch statement.
1267 // End of the getSpelling function.
1272 writePrettyPrintFunction(Record &R,
1273 const std::vector<std::unique_ptr<Argument>> &Args,
1275 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(R);
1277 OS << "void " << R.getName() << "Attr::printPretty("
1278 << "raw_ostream &OS, const PrintingPolicy &Policy) const {\n";
1280 if (Spellings.empty()) {
1286 " switch (SpellingListIndex) {\n"
1288 " llvm_unreachable(\"Unknown attribute spelling!\");\n"
1291 for (unsigned I = 0; I < Spellings.size(); ++ I) {
1292 llvm::SmallString<16> Prefix;
1293 llvm::SmallString<8> Suffix;
1294 // The actual spelling of the name and namespace (if applicable)
1295 // of an attribute without considering prefix and suffix.
1296 llvm::SmallString<64> Spelling;
1297 std::string Name = Spellings[I].name();
1298 std::string Variety = Spellings[I].variety();
1300 if (Variety == "GNU") {
1301 Prefix = " __attribute__((";
1303 } else if (Variety == "CXX11") {
1306 std::string Namespace = Spellings[I].nameSpace();
1307 if (!Namespace.empty()) {
1308 Spelling += Namespace;
1311 } else if (Variety == "Declspec") {
1312 Prefix = " __declspec(";
1314 } else if (Variety == "Microsoft") {
1317 } else if (Variety == "Keyword") {
1320 } else if (Variety == "Pragma") {
1321 Prefix = "#pragma ";
1323 std::string Namespace = Spellings[I].nameSpace();
1324 if (!Namespace.empty()) {
1325 Spelling += Namespace;
1329 llvm_unreachable("Unknown attribute syntax variety!");
1335 " case " << I << " : {\n"
1336 " OS << \"" << Prefix << Spelling;
1338 if (Variety == "Pragma") {
1340 OS << " printPrettyPragma(OS, Policy);\n";
1341 OS << " OS << \"\\n\";";
1347 // Fake arguments aren't part of the parsed form and should not be
1349 bool hasNonFakeArgs = llvm::any_of(
1350 Args, [](const std::unique_ptr<Argument> &A) { return !A->isFake(); });
1352 // FIXME: always printing the parenthesis isn't the correct behavior for
1353 // attributes which have optional arguments that were not provided. For
1354 // instance: __attribute__((aligned)) will be pretty printed as
1355 // __attribute__((aligned())). The logic should check whether there is only
1356 // a single argument, and if it is optional, whether it has been provided.
1359 if (Spelling == "availability") {
1360 writeAvailabilityValue(OS);
1361 } else if (Spelling == "deprecated" || Spelling == "gnu::deprecated") {
1362 writeDeprecatedAttrValue(OS, Variety);
1365 for (const auto &arg : Args) {
1366 if (arg->isFake()) continue;
1367 if (index++) OS << ", ";
1368 arg->writeValue(OS);
1374 OS << Suffix + "\";\n";
1381 // End of the switch statement.
1383 // End of the print function.
1387 /// \brief Return the index of a spelling in a spelling list.
1389 getSpellingListIndex(const std::vector<FlattenedSpelling> &SpellingList,
1390 const FlattenedSpelling &Spelling) {
1391 assert(!SpellingList.empty() && "Spelling list is empty!");
1393 for (unsigned Index = 0; Index < SpellingList.size(); ++Index) {
1394 const FlattenedSpelling &S = SpellingList[Index];
1395 if (S.variety() != Spelling.variety())
1397 if (S.nameSpace() != Spelling.nameSpace())
1399 if (S.name() != Spelling.name())
1405 llvm_unreachable("Unknown spelling!");
1408 static void writeAttrAccessorDefinition(const Record &R, raw_ostream &OS) {
1409 std::vector<Record*> Accessors = R.getValueAsListOfDefs("Accessors");
1410 if (Accessors.empty())
1413 const std::vector<FlattenedSpelling> SpellingList = GetFlattenedSpellings(R);
1414 assert(!SpellingList.empty() &&
1415 "Attribute with empty spelling list can't have accessors!");
1416 for (const auto *Accessor : Accessors) {
1417 std::string Name = Accessor->getValueAsString("Name");
1418 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(*Accessor);
1420 OS << " bool " << Name << "() const { return SpellingListIndex == ";
1421 for (unsigned Index = 0; Index < Spellings.size(); ++Index) {
1422 OS << getSpellingListIndex(SpellingList, Spellings[Index]);
1423 if (Index != Spellings.size() - 1)
1424 OS << " ||\n SpellingListIndex == ";
1432 SpellingNamesAreCommon(const std::vector<FlattenedSpelling>& Spellings) {
1433 assert(!Spellings.empty() && "An empty list of spellings was provided");
1434 std::string FirstName = NormalizeNameForSpellingComparison(
1435 Spellings.front().name());
1436 for (const auto &Spelling :
1437 llvm::make_range(std::next(Spellings.begin()), Spellings.end())) {
1438 std::string Name = NormalizeNameForSpellingComparison(Spelling.name());
1439 if (Name != FirstName)
1445 typedef std::map<unsigned, std::string> SemanticSpellingMap;
1447 CreateSemanticSpellings(const std::vector<FlattenedSpelling> &Spellings,
1448 SemanticSpellingMap &Map) {
1449 // The enumerants are automatically generated based on the variety,
1450 // namespace (if present) and name for each attribute spelling. However,
1451 // care is taken to avoid trampling on the reserved namespace due to
1453 std::string Ret(" enum Spelling {\n");
1454 std::set<std::string> Uniques;
1456 for (auto I = Spellings.begin(), E = Spellings.end(); I != E; ++I, ++Idx) {
1457 const FlattenedSpelling &S = *I;
1458 const std::string &Variety = S.variety();
1459 const std::string &Spelling = S.name();
1460 const std::string &Namespace = S.nameSpace();
1461 std::string EnumName;
1463 EnumName += (Variety + "_");
1464 if (!Namespace.empty())
1465 EnumName += (NormalizeNameForSpellingComparison(Namespace).str() +
1467 EnumName += NormalizeNameForSpellingComparison(Spelling);
1469 // Even if the name is not unique, this spelling index corresponds to a
1470 // particular enumerant name that we've calculated.
1471 Map[Idx] = EnumName;
1473 // Since we have been stripping underscores to avoid trampling on the
1474 // reserved namespace, we may have inadvertently created duplicate
1475 // enumerant names. These duplicates are not considered part of the
1476 // semantic spelling, and can be elided.
1477 if (Uniques.find(EnumName) != Uniques.end())
1480 Uniques.insert(EnumName);
1481 if (I != Spellings.begin())
1483 // Duplicate spellings are not considered part of the semantic spelling
1484 // enumeration, but the spelling index and semantic spelling values are
1485 // meant to be equivalent, so we must specify a concrete value for each
1487 Ret += " " + EnumName + " = " + llvm::utostr(Idx);
1493 void WriteSemanticSpellingSwitch(const std::string &VarName,
1494 const SemanticSpellingMap &Map,
1496 OS << " switch (" << VarName << ") {\n default: "
1497 << "llvm_unreachable(\"Unknown spelling list index\");\n";
1498 for (const auto &I : Map)
1499 OS << " case " << I.first << ": return " << I.second << ";\n";
1503 // Emits the LateParsed property for attributes.
1504 static void emitClangAttrLateParsedList(RecordKeeper &Records, raw_ostream &OS) {
1505 OS << "#if defined(CLANG_ATTR_LATE_PARSED_LIST)\n";
1506 std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr");
1508 for (const auto *Attr : Attrs) {
1509 bool LateParsed = Attr->getValueAsBit("LateParsed");
1512 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(*Attr);
1514 // FIXME: Handle non-GNU attributes
1515 for (const auto &I : Spellings) {
1516 if (I.variety() != "GNU")
1518 OS << ".Case(\"" << I.name() << "\", " << LateParsed << ")\n";
1522 OS << "#endif // CLANG_ATTR_LATE_PARSED_LIST\n\n";
1525 template <typename Fn>
1526 static void forEachUniqueSpelling(const Record &Attr, Fn &&F) {
1527 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(Attr);
1528 SmallDenseSet<StringRef, 8> Seen;
1529 for (const FlattenedSpelling &S : Spellings) {
1530 if (Seen.insert(S.name()).second)
1535 /// \brief Emits the first-argument-is-type property for attributes.
1536 static void emitClangAttrTypeArgList(RecordKeeper &Records, raw_ostream &OS) {
1537 OS << "#if defined(CLANG_ATTR_TYPE_ARG_LIST)\n";
1538 std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
1540 for (const auto *Attr : Attrs) {
1541 // Determine whether the first argument is a type.
1542 std::vector<Record *> Args = Attr->getValueAsListOfDefs("Args");
1546 if (Args[0]->getSuperClasses().back().first->getName() != "TypeArgument")
1549 // All these spellings take a single type argument.
1550 forEachUniqueSpelling(*Attr, [&](const FlattenedSpelling &S) {
1551 OS << ".Case(\"" << S.name() << "\", " << "true" << ")\n";
1554 OS << "#endif // CLANG_ATTR_TYPE_ARG_LIST\n\n";
1557 /// \brief Emits the parse-arguments-in-unevaluated-context property for
1559 static void emitClangAttrArgContextList(RecordKeeper &Records, raw_ostream &OS) {
1560 OS << "#if defined(CLANG_ATTR_ARG_CONTEXT_LIST)\n";
1561 ParsedAttrMap Attrs = getParsedAttrList(Records);
1562 for (const auto &I : Attrs) {
1563 const Record &Attr = *I.second;
1565 if (!Attr.getValueAsBit("ParseArgumentsAsUnevaluated"))
1568 // All these spellings take are parsed unevaluated.
1569 forEachUniqueSpelling(Attr, [&](const FlattenedSpelling &S) {
1570 OS << ".Case(\"" << S.name() << "\", " << "true" << ")\n";
1573 OS << "#endif // CLANG_ATTR_ARG_CONTEXT_LIST\n\n";
1576 static bool isIdentifierArgument(Record *Arg) {
1577 return !Arg->getSuperClasses().empty() &&
1578 llvm::StringSwitch<bool>(Arg->getSuperClasses().back().first->getName())
1579 .Case("IdentifierArgument", true)
1580 .Case("EnumArgument", true)
1581 .Case("VariadicEnumArgument", true)
1585 // Emits the first-argument-is-identifier property for attributes.
1586 static void emitClangAttrIdentifierArgList(RecordKeeper &Records, raw_ostream &OS) {
1587 OS << "#if defined(CLANG_ATTR_IDENTIFIER_ARG_LIST)\n";
1588 std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr");
1590 for (const auto *Attr : Attrs) {
1591 // Determine whether the first argument is an identifier.
1592 std::vector<Record *> Args = Attr->getValueAsListOfDefs("Args");
1593 if (Args.empty() || !isIdentifierArgument(Args[0]))
1596 // All these spellings take an identifier argument.
1597 forEachUniqueSpelling(*Attr, [&](const FlattenedSpelling &S) {
1598 OS << ".Case(\"" << S.name() << "\", " << "true" << ")\n";
1601 OS << "#endif // CLANG_ATTR_IDENTIFIER_ARG_LIST\n\n";
1606 // Emits the class definitions for attributes.
1607 void EmitClangAttrClass(RecordKeeper &Records, raw_ostream &OS) {
1608 emitSourceFileHeader("Attribute classes' definitions", OS);
1610 OS << "#ifndef LLVM_CLANG_ATTR_CLASSES_INC\n";
1611 OS << "#define LLVM_CLANG_ATTR_CLASSES_INC\n\n";
1613 std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr");
1615 for (const auto *Attr : Attrs) {
1616 const Record &R = *Attr;
1618 // FIXME: Currently, documentation is generated as-needed due to the fact
1619 // that there is no way to allow a generated project "reach into" the docs
1620 // directory (for instance, it may be an out-of-tree build). However, we want
1621 // to ensure that every attribute has a Documentation field, and produce an
1622 // error if it has been neglected. Otherwise, the on-demand generation which
1623 // happens server-side will fail. This code is ensuring that functionality,
1624 // even though this Emitter doesn't technically need the documentation.
1625 // When attribute documentation can be generated as part of the build
1626 // itself, this code can be removed.
1627 (void)R.getValueAsListOfDefs("Documentation");
1629 if (!R.getValueAsBit("ASTNode"))
1632 ArrayRef<std::pair<Record *, SMRange>> Supers = R.getSuperClasses();
1633 assert(!Supers.empty() && "Forgot to specify a superclass for the attr");
1634 std::string SuperName;
1635 for (const auto &Super : llvm::reverse(Supers)) {
1636 const Record *R = Super.first;
1637 if (R->getName() != "TargetSpecificAttr" && SuperName.empty())
1638 SuperName = R->getName();
1641 OS << "class " << R.getName() << "Attr : public " << SuperName << " {\n";
1643 std::vector<Record*> ArgRecords = R.getValueAsListOfDefs("Args");
1644 std::vector<std::unique_ptr<Argument>> Args;
1645 Args.reserve(ArgRecords.size());
1647 bool HasOptArg = false;
1648 bool HasFakeArg = false;
1649 for (const auto *ArgRecord : ArgRecords) {
1650 Args.emplace_back(createArgument(*ArgRecord, R.getName()));
1651 Args.back()->writeDeclarations(OS);
1654 // For these purposes, fake takes priority over optional.
1655 if (Args.back()->isFake()) {
1657 } else if (Args.back()->isOptional()) {
1664 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(R);
1666 // If there are zero or one spellings, all spelling-related functionality
1667 // can be elided. If all of the spellings share the same name, the spelling
1668 // functionality can also be elided.
1669 bool ElideSpelling = (Spellings.size() <= 1) ||
1670 SpellingNamesAreCommon(Spellings);
1672 // This maps spelling index values to semantic Spelling enumerants.
1673 SemanticSpellingMap SemanticToSyntacticMap;
1676 OS << CreateSemanticSpellings(Spellings, SemanticToSyntacticMap);
1678 // Emit CreateImplicit factory methods.
1679 auto emitCreateImplicit = [&](bool emitFake) {
1680 OS << " static " << R.getName() << "Attr *CreateImplicit(";
1681 OS << "ASTContext &Ctx";
1683 OS << ", Spelling S";
1684 for (auto const &ai : Args) {
1685 if (ai->isFake() && !emitFake) continue;
1687 ai->writeCtorParameters(OS);
1689 OS << ", SourceRange Loc = SourceRange()";
1691 OS << " auto *A = new (Ctx) " << R.getName();
1692 OS << "Attr(Loc, Ctx, ";
1693 for (auto const &ai : Args) {
1694 if (ai->isFake() && !emitFake) continue;
1695 ai->writeImplicitCtorArgs(OS);
1698 OS << (ElideSpelling ? "0" : "S") << ");\n";
1699 OS << " A->setImplicit(true);\n";
1700 OS << " return A;\n }\n\n";
1703 // Emit a CreateImplicit that takes all the arguments.
1704 emitCreateImplicit(true);
1706 // Emit a CreateImplicit that takes all the non-fake arguments.
1708 emitCreateImplicit(false);
1711 // Emit constructors.
1712 auto emitCtor = [&](bool emitOpt, bool emitFake) {
1713 auto shouldEmitArg = [=](const std::unique_ptr<Argument> &arg) {
1714 if (arg->isFake()) return emitFake;
1715 if (arg->isOptional()) return emitOpt;
1719 OS << " " << R.getName() << "Attr(SourceRange R, ASTContext &Ctx\n";
1720 for (auto const &ai : Args) {
1721 if (!shouldEmitArg(ai)) continue;
1723 ai->writeCtorParameters(OS);
1728 OS << "unsigned SI\n";
1731 OS << " : " << SuperName << "(attr::" << R.getName() << ", R, SI, "
1732 << ( R.getValueAsBit("LateParsed") ? "true" : "false" ) << ", "
1733 << ( R.getValueAsBit("DuplicatesAllowedWhileMerging") ? "true" : "false" ) << ")\n";
1735 for (auto const &ai : Args) {
1737 if (!shouldEmitArg(ai)) {
1738 ai->writeCtorDefaultInitializers(OS);
1740 ai->writeCtorInitializers(OS);
1747 for (auto const &ai : Args) {
1748 if (!shouldEmitArg(ai)) continue;
1749 ai->writeCtorBody(OS);
1754 // Emit a constructor that includes all the arguments.
1755 // This is necessary for cloning.
1756 emitCtor(true, true);
1758 // Emit a constructor that takes all the non-fake arguments.
1760 emitCtor(true, false);
1763 // Emit a constructor that takes all the non-fake, non-optional arguments.
1765 emitCtor(false, false);
1768 OS << " " << R.getName() << "Attr *clone(ASTContext &C) const;\n";
1769 OS << " void printPretty(raw_ostream &OS,\n"
1770 << " const PrintingPolicy &Policy) const;\n";
1771 OS << " const char *getSpelling() const;\n";
1773 if (!ElideSpelling) {
1774 assert(!SemanticToSyntacticMap.empty() && "Empty semantic mapping list");
1775 OS << " Spelling getSemanticSpelling() const {\n";
1776 WriteSemanticSpellingSwitch("SpellingListIndex", SemanticToSyntacticMap,
1781 writeAttrAccessorDefinition(R, OS);
1783 for (auto const &ai : Args) {
1784 ai->writeAccessors(OS);
1787 // Don't write conversion routines for fake arguments.
1788 if (ai->isFake()) continue;
1790 if (ai->isEnumArg())
1791 static_cast<const EnumArgument *>(ai.get())->writeConversion(OS);
1792 else if (ai->isVariadicEnumArg())
1793 static_cast<const VariadicEnumArgument *>(ai.get())
1794 ->writeConversion(OS);
1797 OS << R.getValueAsString("AdditionalMembers");
1800 OS << " static bool classof(const Attr *A) { return A->getKind() == "
1801 << "attr::" << R.getName() << "; }\n";
1806 OS << "#endif // LLVM_CLANG_ATTR_CLASSES_INC\n";
1809 // Emits the class method definitions for attributes.
1810 void EmitClangAttrImpl(RecordKeeper &Records, raw_ostream &OS) {
1811 emitSourceFileHeader("Attribute classes' member function definitions", OS);
1813 std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr");
1815 for (auto *Attr : Attrs) {
1818 if (!R.getValueAsBit("ASTNode"))
1821 std::vector<Record*> ArgRecords = R.getValueAsListOfDefs("Args");
1822 std::vector<std::unique_ptr<Argument>> Args;
1823 for (const auto *Arg : ArgRecords)
1824 Args.emplace_back(createArgument(*Arg, R.getName()));
1826 for (auto const &ai : Args)
1827 ai->writeAccessorDefinitions(OS);
1829 OS << R.getName() << "Attr *" << R.getName()
1830 << "Attr::clone(ASTContext &C) const {\n";
1831 OS << " auto *A = new (C) " << R.getName() << "Attr(getLocation(), C";
1832 for (auto const &ai : Args) {
1834 ai->writeCloneArgs(OS);
1836 OS << ", getSpellingListIndex());\n";
1837 OS << " A->Inherited = Inherited;\n";
1838 OS << " A->IsPackExpansion = IsPackExpansion;\n";
1839 OS << " A->Implicit = Implicit;\n";
1840 OS << " return A;\n}\n\n";
1842 writePrettyPrintFunction(R, Args, OS);
1843 writeGetSpellingFunction(R, OS);
1846 // Instead of relying on virtual dispatch we just create a huge dispatch
1847 // switch. This is both smaller and faster than virtual functions.
1848 auto EmitFunc = [&](const char *Method) {
1849 OS << " switch (getKind()) {\n";
1850 for (const auto *Attr : Attrs) {
1851 const Record &R = *Attr;
1852 if (!R.getValueAsBit("ASTNode"))
1855 OS << " case attr::" << R.getName() << ":\n";
1856 OS << " return cast<" << R.getName() << "Attr>(this)->" << Method
1860 OS << " llvm_unreachable(\"Unexpected attribute kind!\");\n";
1864 OS << "const char *Attr::getSpelling() const {\n";
1865 EmitFunc("getSpelling()");
1867 OS << "Attr *Attr::clone(ASTContext &C) const {\n";
1868 EmitFunc("clone(C)");
1870 OS << "void Attr::printPretty(raw_ostream &OS, "
1871 "const PrintingPolicy &Policy) const {\n";
1872 EmitFunc("printPretty(OS, Policy)");
1875 } // end namespace clang
1877 static void emitAttrList(raw_ostream &OS, StringRef Class,
1878 const std::vector<Record*> &AttrList) {
1879 for (auto Cur : AttrList) {
1880 OS << Class << "(" << Cur->getName() << ")\n";
1884 // Determines if an attribute has a Pragma spelling.
1885 static bool AttrHasPragmaSpelling(const Record *R) {
1886 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(*R);
1887 return llvm::find_if(Spellings, [](const FlattenedSpelling &S) {
1888 return S.variety() == "Pragma";
1889 }) != Spellings.end();
1894 struct AttrClassDescriptor {
1895 const char * const MacroName;
1896 const char * const TableGenName;
1899 } // end anonymous namespace
1901 static const AttrClassDescriptor AttrClassDescriptors[] = {
1903 { "STMT_ATTR", "StmtAttr" },
1904 { "INHERITABLE_ATTR", "InheritableAttr" },
1905 { "INHERITABLE_PARAM_ATTR", "InheritableParamAttr" },
1906 { "PARAMETER_ABI_ATTR", "ParameterABIAttr" }
1909 static void emitDefaultDefine(raw_ostream &OS, StringRef name,
1910 const char *superName) {
1911 OS << "#ifndef " << name << "\n";
1912 OS << "#define " << name << "(NAME) ";
1913 if (superName) OS << superName << "(NAME)";
1914 OS << "\n#endif\n\n";
1919 /// A class of attributes.
1921 const AttrClassDescriptor &Descriptor;
1923 AttrClass *SuperClass = nullptr;
1924 std::vector<AttrClass*> SubClasses;
1925 std::vector<Record*> Attrs;
1927 AttrClass(const AttrClassDescriptor &Descriptor, Record *R)
1928 : Descriptor(Descriptor), TheRecord(R) {}
1930 void emitDefaultDefines(raw_ostream &OS) const {
1931 // Default the macro unless this is a root class (i.e. Attr).
1933 emitDefaultDefine(OS, Descriptor.MacroName,
1934 SuperClass->Descriptor.MacroName);
1938 void emitUndefs(raw_ostream &OS) const {
1939 OS << "#undef " << Descriptor.MacroName << "\n";
1942 void emitAttrList(raw_ostream &OS) const {
1943 for (auto SubClass : SubClasses) {
1944 SubClass->emitAttrList(OS);
1947 ::emitAttrList(OS, Descriptor.MacroName, Attrs);
1950 void classifyAttrOnRoot(Record *Attr) {
1951 bool result = classifyAttr(Attr);
1952 assert(result && "failed to classify on root"); (void) result;
1955 void emitAttrRange(raw_ostream &OS) const {
1956 OS << "ATTR_RANGE(" << Descriptor.TableGenName
1957 << ", " << getFirstAttr()->getName()
1958 << ", " << getLastAttr()->getName() << ")\n";
1962 bool classifyAttr(Record *Attr) {
1963 // Check all the subclasses.
1964 for (auto SubClass : SubClasses) {
1965 if (SubClass->classifyAttr(Attr))
1969 // It's not more specific than this class, but it might still belong here.
1970 if (Attr->isSubClassOf(TheRecord)) {
1971 Attrs.push_back(Attr);
1978 Record *getFirstAttr() const {
1979 if (!SubClasses.empty())
1980 return SubClasses.front()->getFirstAttr();
1981 return Attrs.front();
1984 Record *getLastAttr() const {
1986 return Attrs.back();
1987 return SubClasses.back()->getLastAttr();
1991 /// The entire hierarchy of attribute classes.
1992 class AttrClassHierarchy {
1993 std::vector<std::unique_ptr<AttrClass>> Classes;
1996 AttrClassHierarchy(RecordKeeper &Records) {
1997 // Find records for all the classes.
1998 for (auto &Descriptor : AttrClassDescriptors) {
1999 Record *ClassRecord = Records.getClass(Descriptor.TableGenName);
2000 AttrClass *Class = new AttrClass(Descriptor, ClassRecord);
2001 Classes.emplace_back(Class);
2004 // Link up the hierarchy.
2005 for (auto &Class : Classes) {
2006 if (AttrClass *SuperClass = findSuperClass(Class->TheRecord)) {
2007 Class->SuperClass = SuperClass;
2008 SuperClass->SubClasses.push_back(Class.get());
2013 for (auto i = Classes.begin(), e = Classes.end(); i != e; ++i) {
2014 assert((i == Classes.begin()) == ((*i)->SuperClass == nullptr) &&
2015 "only the first class should be a root class!");
2020 void emitDefaultDefines(raw_ostream &OS) const {
2021 for (auto &Class : Classes) {
2022 Class->emitDefaultDefines(OS);
2026 void emitUndefs(raw_ostream &OS) const {
2027 for (auto &Class : Classes) {
2028 Class->emitUndefs(OS);
2032 void emitAttrLists(raw_ostream &OS) const {
2033 // Just start from the root class.
2034 Classes[0]->emitAttrList(OS);
2037 void emitAttrRanges(raw_ostream &OS) const {
2038 for (auto &Class : Classes)
2039 Class->emitAttrRange(OS);
2042 void classifyAttr(Record *Attr) {
2043 // Add the attribute to the root class.
2044 Classes[0]->classifyAttrOnRoot(Attr);
2048 AttrClass *findClassByRecord(Record *R) const {
2049 for (auto &Class : Classes) {
2050 if (Class->TheRecord == R)
2056 AttrClass *findSuperClass(Record *R) const {
2057 // TableGen flattens the superclass list, so we just need to walk it
2059 auto SuperClasses = R->getSuperClasses();
2060 for (signed i = 0, e = SuperClasses.size(); i != e; ++i) {
2061 auto SuperClass = findClassByRecord(SuperClasses[e - i - 1].first);
2062 if (SuperClass) return SuperClass;
2068 } // end anonymous namespace
2072 // Emits the enumeration list for attributes.
2073 void EmitClangAttrList(RecordKeeper &Records, raw_ostream &OS) {
2074 emitSourceFileHeader("List of all attributes that Clang recognizes", OS);
2076 AttrClassHierarchy Hierarchy(Records);
2078 // Add defaulting macro definitions.
2079 Hierarchy.emitDefaultDefines(OS);
2080 emitDefaultDefine(OS, "PRAGMA_SPELLING_ATTR", nullptr);
2082 std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
2083 std::vector<Record *> PragmaAttrs;
2084 for (auto *Attr : Attrs) {
2085 if (!Attr->getValueAsBit("ASTNode"))
2088 // Add the attribute to the ad-hoc groups.
2089 if (AttrHasPragmaSpelling(Attr))
2090 PragmaAttrs.push_back(Attr);
2092 // Place it in the hierarchy.
2093 Hierarchy.classifyAttr(Attr);
2096 // Emit the main attribute list.
2097 Hierarchy.emitAttrLists(OS);
2099 // Emit the ad hoc groups.
2100 emitAttrList(OS, "PRAGMA_SPELLING_ATTR", PragmaAttrs);
2102 // Emit the attribute ranges.
2103 OS << "#ifdef ATTR_RANGE\n";
2104 Hierarchy.emitAttrRanges(OS);
2105 OS << "#undef ATTR_RANGE\n";
2108 Hierarchy.emitUndefs(OS);
2109 OS << "#undef PRAGMA_SPELLING_ATTR\n";
2112 // Emits the code to read an attribute from a precompiled header.
2113 void EmitClangAttrPCHRead(RecordKeeper &Records, raw_ostream &OS) {
2114 emitSourceFileHeader("Attribute deserialization code", OS);
2116 Record *InhClass = Records.getClass("InheritableAttr");
2117 std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr"),
2119 std::vector<std::unique_ptr<Argument>> Args;
2121 OS << " switch (Kind) {\n";
2122 for (const auto *Attr : Attrs) {
2123 const Record &R = *Attr;
2124 if (!R.getValueAsBit("ASTNode"))
2127 OS << " case attr::" << R.getName() << ": {\n";
2128 if (R.isSubClassOf(InhClass))
2129 OS << " bool isInherited = Record[Idx++];\n";
2130 OS << " bool isImplicit = Record[Idx++];\n";
2131 OS << " unsigned Spelling = Record[Idx++];\n";
2132 ArgRecords = R.getValueAsListOfDefs("Args");
2134 for (const auto *Arg : ArgRecords) {
2135 Args.emplace_back(createArgument(*Arg, R.getName()));
2136 Args.back()->writePCHReadDecls(OS);
2138 OS << " New = new (Context) " << R.getName() << "Attr(Range, Context";
2139 for (auto const &ri : Args) {
2141 ri->writePCHReadArgs(OS);
2143 OS << ", Spelling);\n";
2144 if (R.isSubClassOf(InhClass))
2145 OS << " cast<InheritableAttr>(New)->setInherited(isInherited);\n";
2146 OS << " New->setImplicit(isImplicit);\n";
2153 // Emits the code to write an attribute to a precompiled header.
2154 void EmitClangAttrPCHWrite(RecordKeeper &Records, raw_ostream &OS) {
2155 emitSourceFileHeader("Attribute serialization code", OS);
2157 Record *InhClass = Records.getClass("InheritableAttr");
2158 std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr"), Args;
2160 OS << " switch (A->getKind()) {\n";
2161 for (const auto *Attr : Attrs) {
2162 const Record &R = *Attr;
2163 if (!R.getValueAsBit("ASTNode"))
2165 OS << " case attr::" << R.getName() << ": {\n";
2166 Args = R.getValueAsListOfDefs("Args");
2167 if (R.isSubClassOf(InhClass) || !Args.empty())
2168 OS << " const auto *SA = cast<" << R.getName()
2170 if (R.isSubClassOf(InhClass))
2171 OS << " Record.push_back(SA->isInherited());\n";
2172 OS << " Record.push_back(A->isImplicit());\n";
2173 OS << " Record.push_back(A->getSpellingListIndex());\n";
2175 for (const auto *Arg : Args)
2176 createArgument(*Arg, R.getName())->writePCHWrite(OS);
2183 // Generate a conditional expression to check if the current target satisfies
2184 // the conditions for a TargetSpecificAttr record, and append the code for
2185 // those checks to the Test string. If the FnName string pointer is non-null,
2186 // append a unique suffix to distinguish this set of target checks from other
2187 // TargetSpecificAttr records.
2188 static void GenerateTargetSpecificAttrChecks(const Record *R,
2189 std::vector<std::string> &Arches,
2191 std::string *FnName) {
2192 // It is assumed that there will be an llvm::Triple object
2193 // named "T" and a TargetInfo object named "Target" within
2194 // scope that can be used to determine whether the attribute exists in
2198 for (auto I = Arches.begin(), E = Arches.end(); I != E; ++I) {
2199 std::string Part = *I;
2200 Test += "T.getArch() == llvm::Triple::" + Part;
2208 // If the attribute is specific to particular OSes, check those.
2209 if (!R->isValueUnset("OSes")) {
2210 // We know that there was at least one arch test, so we need to and in the
2213 std::vector<std::string> OSes = R->getValueAsListOfStrings("OSes");
2214 for (auto I = OSes.begin(), E = OSes.end(); I != E; ++I) {
2215 std::string Part = *I;
2217 Test += "T.getOS() == llvm::Triple::" + Part;
2226 // If one or more CXX ABIs are specified, check those as well.
2227 if (!R->isValueUnset("CXXABIs")) {
2229 std::vector<std::string> CXXABIs = R->getValueAsListOfStrings("CXXABIs");
2230 for (auto I = CXXABIs.begin(), E = CXXABIs.end(); I != E; ++I) {
2231 std::string Part = *I;
2232 Test += "Target.getCXXABI().getKind() == TargetCXXABI::" + Part;
2242 static void GenerateHasAttrSpellingStringSwitch(
2243 const std::vector<Record *> &Attrs, raw_ostream &OS,
2244 const std::string &Variety = "", const std::string &Scope = "") {
2245 for (const auto *Attr : Attrs) {
2246 // C++11-style attributes have specific version information associated with
2247 // them. If the attribute has no scope, the version information must not
2248 // have the default value (1), as that's incorrect. Instead, the unscoped
2249 // attribute version information should be taken from the SD-6 standing
2250 // document, which can be found at:
2251 // https://isocpp.org/std/standing-documents/sd-6-sg10-feature-test-recommendations
2254 if (Variety == "CXX11") {
2255 std::vector<Record *> Spellings = Attr->getValueAsListOfDefs("Spellings");
2256 for (const auto &Spelling : Spellings) {
2257 if (Spelling->getValueAsString("Variety") == "CXX11") {
2258 Version = static_cast<int>(Spelling->getValueAsInt("Version"));
2259 if (Scope.empty() && Version == 1)
2260 PrintError(Spelling->getLoc(), "C++ standard attributes must "
2261 "have valid version information.");
2268 if (Attr->isSubClassOf("TargetSpecificAttr")) {
2269 const Record *R = Attr->getValueAsDef("Target");
2270 std::vector<std::string> Arches = R->getValueAsListOfStrings("Arches");
2271 GenerateTargetSpecificAttrChecks(R, Arches, Test, nullptr);
2273 // If this is the C++11 variety, also add in the LangOpts test.
2274 if (Variety == "CXX11")
2275 Test += " && LangOpts.CPlusPlus11";
2276 } else if (Variety == "CXX11")
2277 // C++11 mode should be checked against LangOpts, which is presumed to be
2278 // present in the caller.
2279 Test = "LangOpts.CPlusPlus11";
2281 std::string TestStr =
2282 !Test.empty() ? Test + " ? " + llvm::itostr(Version) + " : 0" : "1";
2283 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(*Attr);
2284 for (const auto &S : Spellings)
2285 if (Variety.empty() || (Variety == S.variety() &&
2286 (Scope.empty() || Scope == S.nameSpace())))
2287 OS << " .Case(\"" << S.name() << "\", " << TestStr << ")\n";
2289 OS << " .Default(0);\n";
2292 // Emits the list of spellings for attributes.
2293 void EmitClangAttrHasAttrImpl(RecordKeeper &Records, raw_ostream &OS) {
2294 emitSourceFileHeader("Code to implement the __has_attribute logic", OS);
2296 // Separate all of the attributes out into four group: generic, C++11, GNU,
2297 // and declspecs. Then generate a big switch statement for each of them.
2298 std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
2299 std::vector<Record *> Declspec, Microsoft, GNU, Pragma;
2300 std::map<std::string, std::vector<Record *>> CXX;
2302 // Walk over the list of all attributes, and split them out based on the
2303 // spelling variety.
2304 for (auto *R : Attrs) {
2305 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(*R);
2306 for (const auto &SI : Spellings) {
2307 const std::string &Variety = SI.variety();
2308 if (Variety == "GNU")
2310 else if (Variety == "Declspec")
2311 Declspec.push_back(R);
2312 else if (Variety == "Microsoft")
2313 Microsoft.push_back(R);
2314 else if (Variety == "CXX11")
2315 CXX[SI.nameSpace()].push_back(R);
2316 else if (Variety == "Pragma")
2317 Pragma.push_back(R);
2321 OS << "const llvm::Triple &T = Target.getTriple();\n";
2322 OS << "switch (Syntax) {\n";
2323 OS << "case AttrSyntax::GNU:\n";
2324 OS << " return llvm::StringSwitch<int>(Name)\n";
2325 GenerateHasAttrSpellingStringSwitch(GNU, OS, "GNU");
2326 OS << "case AttrSyntax::Declspec:\n";
2327 OS << " return llvm::StringSwitch<int>(Name)\n";
2328 GenerateHasAttrSpellingStringSwitch(Declspec, OS, "Declspec");
2329 OS << "case AttrSyntax::Microsoft:\n";
2330 OS << " return llvm::StringSwitch<int>(Name)\n";
2331 GenerateHasAttrSpellingStringSwitch(Microsoft, OS, "Microsoft");
2332 OS << "case AttrSyntax::Pragma:\n";
2333 OS << " return llvm::StringSwitch<int>(Name)\n";
2334 GenerateHasAttrSpellingStringSwitch(Pragma, OS, "Pragma");
2335 OS << "case AttrSyntax::CXX: {\n";
2336 // C++11-style attributes are further split out based on the Scope.
2337 for (auto I = CXX.cbegin(), E = CXX.cend(); I != E; ++I) {
2338 if (I != CXX.begin())
2340 if (I->first.empty())
2341 OS << "if (!Scope || Scope->getName() == \"\") {\n";
2343 OS << "if (Scope->getName() == \"" << I->first << "\") {\n";
2344 OS << " return llvm::StringSwitch<int>(Name)\n";
2345 GenerateHasAttrSpellingStringSwitch(I->second, OS, "CXX11", I->first);
2352 void EmitClangAttrSpellingListIndex(RecordKeeper &Records, raw_ostream &OS) {
2353 emitSourceFileHeader("Code to translate different attribute spellings "
2354 "into internal identifiers", OS);
2356 OS << " switch (AttrKind) {\n";
2358 ParsedAttrMap Attrs = getParsedAttrList(Records);
2359 for (const auto &I : Attrs) {
2360 const Record &R = *I.second;
2361 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(R);
2362 OS << " case AT_" << I.first << ": {\n";
2363 for (unsigned I = 0; I < Spellings.size(); ++ I) {
2364 OS << " if (Name == \"" << Spellings[I].name() << "\" && "
2366 << StringSwitch<unsigned>(Spellings[I].variety())
2369 .Case("Declspec", 2)
2370 .Case("Microsoft", 3)
2374 << " && Scope == \"" << Spellings[I].nameSpace() << "\")\n"
2375 << " return " << I << ";\n";
2383 OS << " return 0;\n";
2386 // Emits code used by RecursiveASTVisitor to visit attributes
2387 void EmitClangAttrASTVisitor(RecordKeeper &Records, raw_ostream &OS) {
2388 emitSourceFileHeader("Used by RecursiveASTVisitor to visit attributes.", OS);
2390 std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr");
2392 // Write method declarations for Traverse* methods.
2393 // We emit this here because we only generate methods for attributes that
2394 // are declared as ASTNodes.
2395 OS << "#ifdef ATTR_VISITOR_DECLS_ONLY\n\n";
2396 for (const auto *Attr : Attrs) {
2397 const Record &R = *Attr;
2398 if (!R.getValueAsBit("ASTNode"))
2400 OS << " bool Traverse"
2401 << R.getName() << "Attr(" << R.getName() << "Attr *A);\n";
2403 << R.getName() << "Attr(" << R.getName() << "Attr *A) {\n"
2404 << " return true; \n"
2407 OS << "\n#else // ATTR_VISITOR_DECLS_ONLY\n\n";
2409 // Write individual Traverse* methods for each attribute class.
2410 for (const auto *Attr : Attrs) {
2411 const Record &R = *Attr;
2412 if (!R.getValueAsBit("ASTNode"))
2415 OS << "template <typename Derived>\n"
2416 << "bool VISITORCLASS<Derived>::Traverse"
2417 << R.getName() << "Attr(" << R.getName() << "Attr *A) {\n"
2418 << " if (!getDerived().VisitAttr(A))\n"
2419 << " return false;\n"
2420 << " if (!getDerived().Visit" << R.getName() << "Attr(A))\n"
2421 << " return false;\n";
2423 std::vector<Record*> ArgRecords = R.getValueAsListOfDefs("Args");
2424 for (const auto *Arg : ArgRecords)
2425 createArgument(*Arg, R.getName())->writeASTVisitorTraversal(OS);
2427 OS << " return true;\n";
2431 // Write generic Traverse routine
2432 OS << "template <typename Derived>\n"
2433 << "bool VISITORCLASS<Derived>::TraverseAttr(Attr *A) {\n"
2435 << " return true;\n"
2437 << " switch (A->getKind()) {\n";
2439 for (const auto *Attr : Attrs) {
2440 const Record &R = *Attr;
2441 if (!R.getValueAsBit("ASTNode"))
2444 OS << " case attr::" << R.getName() << ":\n"
2445 << " return getDerived().Traverse" << R.getName() << "Attr("
2446 << "cast<" << R.getName() << "Attr>(A));\n";
2448 OS << " }\n"; // end switch
2449 OS << " llvm_unreachable(\"bad attribute kind\");\n";
2450 OS << "}\n"; // end function
2451 OS << "#endif // ATTR_VISITOR_DECLS_ONLY\n";
2454 // Emits code to instantiate dependent attributes on templates.
2455 void EmitClangAttrTemplateInstantiate(RecordKeeper &Records, raw_ostream &OS) {
2456 emitSourceFileHeader("Template instantiation code for attributes", OS);
2458 std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr");
2460 OS << "namespace clang {\n"
2461 << "namespace sema {\n\n"
2462 << "Attr *instantiateTemplateAttribute(const Attr *At, ASTContext &C, "
2464 << " const MultiLevelTemplateArgumentList &TemplateArgs) {\n"
2465 << " switch (At->getKind()) {\n";
2467 for (const auto *Attr : Attrs) {
2468 const Record &R = *Attr;
2469 if (!R.getValueAsBit("ASTNode"))
2472 OS << " case attr::" << R.getName() << ": {\n";
2473 bool ShouldClone = R.getValueAsBit("Clone");
2476 OS << " return nullptr;\n";
2481 OS << " const auto *A = cast<"
2482 << R.getName() << "Attr>(At);\n";
2483 bool TDependent = R.getValueAsBit("TemplateDependent");
2486 OS << " return A->clone(C);\n";
2491 std::vector<Record*> ArgRecords = R.getValueAsListOfDefs("Args");
2492 std::vector<std::unique_ptr<Argument>> Args;
2493 Args.reserve(ArgRecords.size());
2495 for (const auto *ArgRecord : ArgRecords)
2496 Args.emplace_back(createArgument(*ArgRecord, R.getName()));
2498 for (auto const &ai : Args)
2499 ai->writeTemplateInstantiation(OS);
2501 OS << " return new (C) " << R.getName() << "Attr(A->getLocation(), C";
2502 for (auto const &ai : Args) {
2504 ai->writeTemplateInstantiationArgs(OS);
2506 OS << ", A->getSpellingListIndex());\n }\n";
2508 OS << " } // end switch\n"
2509 << " llvm_unreachable(\"Unknown attribute!\");\n"
2510 << " return nullptr;\n"
2512 << "} // end namespace sema\n"
2513 << "} // end namespace clang\n";
2516 // Emits the list of parsed attributes.
2517 void EmitClangAttrParsedAttrList(RecordKeeper &Records, raw_ostream &OS) {
2518 emitSourceFileHeader("List of all attributes that Clang recognizes", OS);
2520 OS << "#ifndef PARSED_ATTR\n";
2521 OS << "#define PARSED_ATTR(NAME) NAME\n";
2524 ParsedAttrMap Names = getParsedAttrList(Records);
2525 for (const auto &I : Names) {
2526 OS << "PARSED_ATTR(" << I.first << ")\n";
2530 static bool isArgVariadic(const Record &R, StringRef AttrName) {
2531 return createArgument(R, AttrName)->isVariadic();
2534 static void emitArgInfo(const Record &R, std::stringstream &OS) {
2535 // This function will count the number of arguments specified for the
2536 // attribute and emit the number of required arguments followed by the
2537 // number of optional arguments.
2538 std::vector<Record *> Args = R.getValueAsListOfDefs("Args");
2539 unsigned ArgCount = 0, OptCount = 0;
2540 bool HasVariadic = false;
2541 for (const auto *Arg : Args) {
2542 // If the arg is fake, it's the user's job to supply it: general parsing
2543 // logic shouldn't need to know anything about it.
2544 if (Arg->getValueAsBit("Fake"))
2546 Arg->getValueAsBit("Optional") ? ++OptCount : ++ArgCount;
2547 if (!HasVariadic && isArgVariadic(*Arg, R.getName()))
2551 // If there is a variadic argument, we will set the optional argument count
2552 // to its largest value. Since it's currently a 4-bit number, we set it to 15.
2553 OS << ArgCount << ", " << (HasVariadic ? 15 : OptCount);
2556 static void GenerateDefaultAppertainsTo(raw_ostream &OS) {
2557 OS << "static bool defaultAppertainsTo(Sema &, const AttributeList &,";
2558 OS << "const Decl *) {\n";
2559 OS << " return true;\n";
2563 static std::string CalculateDiagnostic(const Record &S) {
2564 // If the SubjectList object has a custom diagnostic associated with it,
2565 // return that directly.
2566 std::string CustomDiag = S.getValueAsString("CustomDiag");
2567 if (!CustomDiag.empty())
2570 // Given the list of subjects, determine what diagnostic best fits.
2574 ObjCMethod = 1U << 2,
2577 GenericRecord = 1U << 5,
2581 ObjCInterface = 1U << 9,
2583 Namespace = 1U << 11,
2585 CXXMethod = 1U << 13,
2586 ObjCProtocol = 1U << 14,
2589 uint32_t SubMask = 0;
2591 std::vector<Record *> Subjects = S.getValueAsListOfDefs("Subjects");
2592 for (const auto *Subject : Subjects) {
2593 const Record &R = *Subject;
2596 if (R.isSubClassOf("SubsetSubject")) {
2597 PrintError(R.getLoc(), "SubsetSubjects should use a custom diagnostic");
2598 // As a fallback, look through the SubsetSubject to see what its base
2599 // type is, and use that. This needs to be updated if SubsetSubjects
2600 // are allowed within other SubsetSubjects.
2601 Name = R.getValueAsDef("Base")->getName();
2605 uint32_t V = StringSwitch<uint32_t>(Name)
2606 .Case("Function", Func)
2608 .Case("ObjCMethod", ObjCMethod)
2609 .Case("ParmVar", Param)
2610 .Case("TypedefName", Type)
2611 .Case("ObjCIvar", ObjCIVar)
2612 .Case("ObjCProperty", ObjCProp)
2613 .Case("Record", GenericRecord)
2614 .Case("ObjCInterface", ObjCInterface)
2615 .Case("ObjCProtocol", ObjCProtocol)
2616 .Case("Block", Block)
2617 .Case("CXXRecord", Class)
2618 .Case("Namespace", Namespace)
2619 .Case("Field", Field)
2620 .Case("CXXMethod", CXXMethod)
2624 // Something wasn't in our mapping, so be helpful and let the developer
2626 PrintFatalError(R.getLoc(), "Unknown subject type: " + R.getName());
2634 // For the simple cases where there's only a single entry in the mask, we
2635 // don't have to resort to bit fiddling.
2636 case Func: return "ExpectedFunction";
2637 case Var: return "ExpectedVariable";
2638 case Param: return "ExpectedParameter";
2639 case Class: return "ExpectedClass";
2640 case Enum: return "ExpectedEnum";
2642 // FIXME: Currently, this maps to ExpectedMethod based on existing code,
2643 // but should map to something a bit more accurate at some point.
2644 case ObjCMethod: return "ExpectedMethod";
2645 case Type: return "ExpectedType";
2646 case ObjCInterface: return "ExpectedObjectiveCInterface";
2647 case ObjCProtocol: return "ExpectedObjectiveCProtocol";
2649 // "GenericRecord" means struct, union or class; check the language options
2650 // and if not compiling for C++, strip off the class part. Note that this
2651 // relies on the fact that the context for this declares "Sema &S".
2653 return "(S.getLangOpts().CPlusPlus ? ExpectedStructOrUnionOrClass : "
2654 "ExpectedStructOrUnion)";
2655 case Func | ObjCMethod | Block: return "ExpectedFunctionMethodOrBlock";
2656 case Func | ObjCMethod | Class: return "ExpectedFunctionMethodOrClass";
2658 case Func | ObjCMethod | Param: return "ExpectedFunctionMethodOrParameter";
2659 case Func | ObjCMethod: return "ExpectedFunctionOrMethod";
2660 case Func | Var: return "ExpectedVariableOrFunction";
2662 // If not compiling for C++, the class portion does not apply.
2663 case Func | Var | Class:
2664 return "(S.getLangOpts().CPlusPlus ? ExpectedFunctionVariableOrClass : "
2665 "ExpectedVariableOrFunction)";
2667 case Func | Var | Class | ObjCInterface:
2668 return "(S.getLangOpts().CPlusPlus"
2669 " ? ((S.getLangOpts().ObjC1 || S.getLangOpts().ObjC2)"
2670 " ? ExpectedFunctionVariableClassOrObjCInterface"
2671 " : ExpectedFunctionVariableOrClass)"
2672 " : ((S.getLangOpts().ObjC1 || S.getLangOpts().ObjC2)"
2673 " ? ExpectedFunctionVariableOrObjCInterface"
2674 " : ExpectedVariableOrFunction))";
2676 case ObjCMethod | ObjCProp: return "ExpectedMethodOrProperty";
2677 case ObjCProtocol | ObjCInterface:
2678 return "ExpectedObjectiveCInterfaceOrProtocol";
2679 case Field | Var: return "ExpectedFieldOrGlobalVar";
2682 PrintFatalError(S.getLoc(),
2683 "Could not deduce diagnostic argument for Attr subjects");
2688 static std::string GetSubjectWithSuffix(const Record *R) {
2689 const std::string &B = R->getName();
2690 if (B == "DeclBase")
2695 static std::string GenerateCustomAppertainsTo(const Record &Subject,
2697 std::string FnName = "is" + Subject.getName().str();
2699 // If this code has already been generated, simply return the previous
2701 static std::set<std::string> CustomSubjectSet;
2702 auto I = CustomSubjectSet.find(FnName);
2703 if (I != CustomSubjectSet.end())
2706 Record *Base = Subject.getValueAsDef("Base");
2708 // Not currently support custom subjects within custom subjects.
2709 if (Base->isSubClassOf("SubsetSubject")) {
2710 PrintFatalError(Subject.getLoc(),
2711 "SubsetSubjects within SubsetSubjects is not supported");
2715 OS << "static bool " << FnName << "(const Decl *D) {\n";
2716 OS << " if (const auto *S = dyn_cast<";
2717 OS << GetSubjectWithSuffix(Base);
2719 OS << " return " << Subject.getValueAsString("CheckCode") << ";\n";
2720 OS << " return false;\n";
2723 CustomSubjectSet.insert(FnName);
2727 static std::string GenerateAppertainsTo(const Record &Attr, raw_ostream &OS) {
2728 // If the attribute does not contain a Subjects definition, then use the
2729 // default appertainsTo logic.
2730 if (Attr.isValueUnset("Subjects"))
2731 return "defaultAppertainsTo";
2733 const Record *SubjectObj = Attr.getValueAsDef("Subjects");
2734 std::vector<Record*> Subjects = SubjectObj->getValueAsListOfDefs("Subjects");
2736 // If the list of subjects is empty, it is assumed that the attribute
2737 // appertains to everything.
2738 if (Subjects.empty())
2739 return "defaultAppertainsTo";
2741 bool Warn = SubjectObj->getValueAsDef("Diag")->getValueAsBit("Warn");
2743 // Otherwise, generate an appertainsTo check specific to this attribute which
2744 // checks all of the given subjects against the Decl passed in. Return the
2745 // name of that check to the caller.
2746 std::string FnName = "check" + Attr.getName().str() + "AppertainsTo";
2747 std::stringstream SS;
2748 SS << "static bool " << FnName << "(Sema &S, const AttributeList &Attr, ";
2749 SS << "const Decl *D) {\n";
2751 for (auto I = Subjects.begin(), E = Subjects.end(); I != E; ++I) {
2752 // If the subject has custom code associated with it, generate a function
2753 // for it. The function cannot be inlined into this check (yet) because it
2754 // requires the subject to be of a specific type, and were that information
2755 // inlined here, it would not support an attribute with multiple custom
2757 if ((*I)->isSubClassOf("SubsetSubject")) {
2758 SS << "!" << GenerateCustomAppertainsTo(**I, OS) << "(D)";
2760 SS << "!isa<" << GetSubjectWithSuffix(*I) << ">(D)";
2767 SS << " S.Diag(Attr.getLoc(), diag::";
2768 SS << (Warn ? "warn_attribute_wrong_decl_type" :
2769 "err_attribute_wrong_decl_type");
2771 SS << " << Attr.getName() << ";
2772 SS << CalculateDiagnostic(*SubjectObj) << ";\n";
2773 SS << " return false;\n";
2775 SS << " return true;\n";
2782 static void GenerateDefaultLangOptRequirements(raw_ostream &OS) {
2783 OS << "static bool defaultDiagnoseLangOpts(Sema &, ";
2784 OS << "const AttributeList &) {\n";
2785 OS << " return true;\n";
2789 static std::string GenerateLangOptRequirements(const Record &R,
2791 // If the attribute has an empty or unset list of language requirements,
2792 // return the default handler.
2793 std::vector<Record *> LangOpts = R.getValueAsListOfDefs("LangOpts");
2794 if (LangOpts.empty())
2795 return "defaultDiagnoseLangOpts";
2797 // Generate the test condition, as well as a unique function name for the
2798 // diagnostic test. The list of options should usually be short (one or two
2799 // options), and the uniqueness isn't strictly necessary (it is just for
2800 // codegen efficiency).
2801 std::string FnName = "check", Test;
2802 for (auto I = LangOpts.begin(), E = LangOpts.end(); I != E; ++I) {
2803 std::string Part = (*I)->getValueAsString("Name");
2804 if ((*I)->getValueAsBit("Negated")) {
2808 Test += "S.LangOpts." + Part;
2813 FnName += "LangOpts";
2815 // If this code has already been generated, simply return the previous
2817 static std::set<std::string> CustomLangOptsSet;
2818 auto I = CustomLangOptsSet.find(FnName);
2819 if (I != CustomLangOptsSet.end())
2822 OS << "static bool " << FnName << "(Sema &S, const AttributeList &Attr) {\n";
2823 OS << " if (" << Test << ")\n";
2824 OS << " return true;\n\n";
2825 OS << " S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) ";
2826 OS << "<< Attr.getName();\n";
2827 OS << " return false;\n";
2830 CustomLangOptsSet.insert(FnName);
2834 static void GenerateDefaultTargetRequirements(raw_ostream &OS) {
2835 OS << "static bool defaultTargetRequirements(const TargetInfo &) {\n";
2836 OS << " return true;\n";
2840 static std::string GenerateTargetRequirements(const Record &Attr,
2841 const ParsedAttrMap &Dupes,
2843 // If the attribute is not a target specific attribute, return the default
2845 if (!Attr.isSubClassOf("TargetSpecificAttr"))
2846 return "defaultTargetRequirements";
2848 // Get the list of architectures to be tested for.
2849 const Record *R = Attr.getValueAsDef("Target");
2850 std::vector<std::string> Arches = R->getValueAsListOfStrings("Arches");
2851 if (Arches.empty()) {
2852 PrintError(Attr.getLoc(), "Empty list of target architectures for a "
2853 "target-specific attr");
2854 return "defaultTargetRequirements";
2857 // If there are other attributes which share the same parsed attribute kind,
2858 // such as target-specific attributes with a shared spelling, collapse the
2859 // duplicate architectures. This is required because a shared target-specific
2860 // attribute has only one AttributeList::Kind enumeration value, but it
2861 // applies to multiple target architectures. In order for the attribute to be
2862 // considered valid, all of its architectures need to be included.
2863 if (!Attr.isValueUnset("ParseKind")) {
2864 std::string APK = Attr.getValueAsString("ParseKind");
2865 for (const auto &I : Dupes) {
2866 if (I.first == APK) {
2867 std::vector<std::string> DA = I.second->getValueAsDef("Target")
2868 ->getValueAsListOfStrings("Arches");
2869 std::move(DA.begin(), DA.end(), std::back_inserter(Arches));
2874 std::string FnName = "isTarget";
2876 GenerateTargetSpecificAttrChecks(R, Arches, Test, &FnName);
2878 // If this code has already been generated, simply return the previous
2880 static std::set<std::string> CustomTargetSet;
2881 auto I = CustomTargetSet.find(FnName);
2882 if (I != CustomTargetSet.end())
2885 OS << "static bool " << FnName << "(const TargetInfo &Target) {\n";
2886 OS << " const llvm::Triple &T = Target.getTriple();\n";
2887 OS << " return " << Test << ";\n";
2890 CustomTargetSet.insert(FnName);
2894 static void GenerateDefaultSpellingIndexToSemanticSpelling(raw_ostream &OS) {
2895 OS << "static unsigned defaultSpellingIndexToSemanticSpelling("
2896 << "const AttributeList &Attr) {\n";
2897 OS << " return UINT_MAX;\n";
2901 static std::string GenerateSpellingIndexToSemanticSpelling(const Record &Attr,
2903 // If the attribute does not have a semantic form, we can bail out early.
2904 if (!Attr.getValueAsBit("ASTNode"))
2905 return "defaultSpellingIndexToSemanticSpelling";
2907 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(Attr);
2909 // If there are zero or one spellings, or all of the spellings share the same
2910 // name, we can also bail out early.
2911 if (Spellings.size() <= 1 || SpellingNamesAreCommon(Spellings))
2912 return "defaultSpellingIndexToSemanticSpelling";
2914 // Generate the enumeration we will use for the mapping.
2915 SemanticSpellingMap SemanticToSyntacticMap;
2916 std::string Enum = CreateSemanticSpellings(Spellings, SemanticToSyntacticMap);
2917 std::string Name = Attr.getName().str() + "AttrSpellingMap";
2919 OS << "static unsigned " << Name << "(const AttributeList &Attr) {\n";
2921 OS << " unsigned Idx = Attr.getAttributeSpellingListIndex();\n";
2922 WriteSemanticSpellingSwitch("Idx", SemanticToSyntacticMap, OS);
2928 static bool IsKnownToGCC(const Record &Attr) {
2929 // Look at the spellings for this subject; if there are any spellings which
2930 // claim to be known to GCC, the attribute is known to GCC.
2931 return llvm::any_of(
2932 GetFlattenedSpellings(Attr),
2933 [](const FlattenedSpelling &S) { return S.knownToGCC(); });
2936 /// Emits the parsed attribute helpers
2937 void EmitClangAttrParsedAttrImpl(RecordKeeper &Records, raw_ostream &OS) {
2938 emitSourceFileHeader("Parsed attribute helpers", OS);
2940 // Get the list of parsed attributes, and accept the optional list of
2941 // duplicates due to the ParseKind.
2942 ParsedAttrMap Dupes;
2943 ParsedAttrMap Attrs = getParsedAttrList(Records, &Dupes);
2945 // Generate the default appertainsTo, target and language option diagnostic,
2946 // and spelling list index mapping methods.
2947 GenerateDefaultAppertainsTo(OS);
2948 GenerateDefaultLangOptRequirements(OS);
2949 GenerateDefaultTargetRequirements(OS);
2950 GenerateDefaultSpellingIndexToSemanticSpelling(OS);
2952 // Generate the appertainsTo diagnostic methods and write their names into
2953 // another mapping. At the same time, generate the AttrInfoMap object
2954 // contents. Due to the reliance on generated code, use separate streams so
2955 // that code will not be interleaved.
2956 std::stringstream SS;
2957 for (auto I = Attrs.begin(), E = Attrs.end(); I != E; ++I) {
2958 // TODO: If the attribute's kind appears in the list of duplicates, that is
2959 // because it is a target-specific attribute that appears multiple times.
2960 // It would be beneficial to test whether the duplicates are "similar
2961 // enough" to each other to not cause problems. For instance, check that
2962 // the spellings are identical, and custom parsing rules match, etc.
2964 // We need to generate struct instances based off ParsedAttrInfo from
2965 // AttributeList.cpp.
2967 emitArgInfo(*I->second, SS);
2968 SS << ", " << I->second->getValueAsBit("HasCustomParsing");
2969 SS << ", " << I->second->isSubClassOf("TargetSpecificAttr");
2970 SS << ", " << I->second->isSubClassOf("TypeAttr");
2971 SS << ", " << I->second->isSubClassOf("StmtAttr");
2972 SS << ", " << IsKnownToGCC(*I->second);
2973 SS << ", " << GenerateAppertainsTo(*I->second, OS);
2974 SS << ", " << GenerateLangOptRequirements(*I->second, OS);
2975 SS << ", " << GenerateTargetRequirements(*I->second, Dupes, OS);
2976 SS << ", " << GenerateSpellingIndexToSemanticSpelling(*I->second, OS);
2982 SS << " // AT_" << I->first << "\n";
2985 OS << "static const ParsedAttrInfo AttrInfoMap[AttributeList::UnknownAttribute + 1] = {\n";
2990 // Emits the kind list of parsed attributes
2991 void EmitClangAttrParsedAttrKinds(RecordKeeper &Records, raw_ostream &OS) {
2992 emitSourceFileHeader("Attribute name matcher", OS);
2994 std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
2995 std::vector<StringMatcher::StringPair> GNU, Declspec, Microsoft, CXX11,
2997 std::set<std::string> Seen;
2998 for (const auto *A : Attrs) {
2999 const Record &Attr = *A;
3001 bool SemaHandler = Attr.getValueAsBit("SemaHandler");
3002 bool Ignored = Attr.getValueAsBit("Ignored");
3003 if (SemaHandler || Ignored) {
3004 // Attribute spellings can be shared between target-specific attributes,
3005 // and can be shared between syntaxes for the same attribute. For
3006 // instance, an attribute can be spelled GNU<"interrupt"> for an ARM-
3007 // specific attribute, or MSP430-specific attribute. Additionally, an
3008 // attribute can be spelled GNU<"dllexport"> and Declspec<"dllexport">
3009 // for the same semantic attribute. Ultimately, we need to map each of
3010 // these to a single AttributeList::Kind value, but the StringMatcher
3011 // class cannot handle duplicate match strings. So we generate a list of
3012 // string to match based on the syntax, and emit multiple string matchers
3013 // depending on the syntax used.
3014 std::string AttrName;
3015 if (Attr.isSubClassOf("TargetSpecificAttr") &&
3016 !Attr.isValueUnset("ParseKind")) {
3017 AttrName = Attr.getValueAsString("ParseKind");
3018 if (Seen.find(AttrName) != Seen.end())
3020 Seen.insert(AttrName);
3022 AttrName = NormalizeAttrName(StringRef(Attr.getName())).str();
3024 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(Attr);
3025 for (const auto &S : Spellings) {
3026 const std::string &RawSpelling = S.name();
3027 std::vector<StringMatcher::StringPair> *Matches = nullptr;
3028 std::string Spelling;
3029 const std::string &Variety = S.variety();
3030 if (Variety == "CXX11") {
3032 Spelling += S.nameSpace();
3034 } else if (Variety == "GNU")
3036 else if (Variety == "Declspec")
3037 Matches = &Declspec;
3038 else if (Variety == "Microsoft")
3039 Matches = &Microsoft;
3040 else if (Variety == "Keyword")
3041 Matches = &Keywords;
3042 else if (Variety == "Pragma")
3045 assert(Matches && "Unsupported spelling variety found");
3047 if (Variety == "GNU")
3048 Spelling += NormalizeGNUAttrSpelling(RawSpelling);
3050 Spelling += RawSpelling;
3053 Matches->push_back(StringMatcher::StringPair(Spelling,
3054 "return AttributeList::AT_" + AttrName + ";"));
3056 Matches->push_back(StringMatcher::StringPair(Spelling,
3057 "return AttributeList::IgnoredAttribute;"));
3062 OS << "static AttributeList::Kind getAttrKind(StringRef Name, ";
3063 OS << "AttributeList::Syntax Syntax) {\n";
3064 OS << " if (AttributeList::AS_GNU == Syntax) {\n";
3065 StringMatcher("Name", GNU, OS).Emit();
3066 OS << " } else if (AttributeList::AS_Declspec == Syntax) {\n";
3067 StringMatcher("Name", Declspec, OS).Emit();
3068 OS << " } else if (AttributeList::AS_Microsoft == Syntax) {\n";
3069 StringMatcher("Name", Microsoft, OS).Emit();
3070 OS << " } else if (AttributeList::AS_CXX11 == Syntax) {\n";
3071 StringMatcher("Name", CXX11, OS).Emit();
3072 OS << " } else if (AttributeList::AS_Keyword == Syntax || ";
3073 OS << "AttributeList::AS_ContextSensitiveKeyword == Syntax) {\n";
3074 StringMatcher("Name", Keywords, OS).Emit();
3075 OS << " } else if (AttributeList::AS_Pragma == Syntax) {\n";
3076 StringMatcher("Name", Pragma, OS).Emit();
3078 OS << " return AttributeList::UnknownAttribute;\n"
3082 // Emits the code to dump an attribute.
3083 void EmitClangAttrDump(RecordKeeper &Records, raw_ostream &OS) {
3084 emitSourceFileHeader("Attribute dumper", OS);
3086 OS << " switch (A->getKind()) {\n";
3087 std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr"), Args;
3088 for (const auto *Attr : Attrs) {
3089 const Record &R = *Attr;
3090 if (!R.getValueAsBit("ASTNode"))
3092 OS << " case attr::" << R.getName() << ": {\n";
3094 // If the attribute has a semantically-meaningful name (which is determined
3095 // by whether there is a Spelling enumeration for it), then write out the
3096 // spelling used for the attribute.
3097 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(R);
3098 if (Spellings.size() > 1 && !SpellingNamesAreCommon(Spellings))
3099 OS << " OS << \" \" << A->getSpelling();\n";
3101 Args = R.getValueAsListOfDefs("Args");
3102 if (!Args.empty()) {
3103 OS << " const auto *SA = cast<" << R.getName()
3105 for (const auto *Arg : Args)
3106 createArgument(*Arg, R.getName())->writeDump(OS);
3108 for (const auto *AI : Args)
3109 createArgument(*AI, R.getName())->writeDumpChildren(OS);
3118 void EmitClangAttrParserStringSwitches(RecordKeeper &Records,
3120 emitSourceFileHeader("Parser-related llvm::StringSwitch cases", OS);
3121 emitClangAttrArgContextList(Records, OS);
3122 emitClangAttrIdentifierArgList(Records, OS);
3123 emitClangAttrTypeArgList(Records, OS);
3124 emitClangAttrLateParsedList(Records, OS);
3127 class DocumentationData {
3129 const Record *Documentation;
3130 const Record *Attribute;
3132 DocumentationData(const Record &Documentation, const Record &Attribute)
3133 : Documentation(&Documentation), Attribute(&Attribute) {}
3136 static void WriteCategoryHeader(const Record *DocCategory,
3138 const std::string &Name = DocCategory->getValueAsString("Name");
3139 OS << Name << "\n" << std::string(Name.length(), '=') << "\n";
3141 // If there is content, print that as well.
3142 std::string ContentStr = DocCategory->getValueAsString("Content");
3143 // Trim leading and trailing newlines and spaces.
3144 OS << StringRef(ContentStr).trim();
3158 static void WriteDocumentation(const DocumentationData &Doc,
3160 // FIXME: there is no way to have a per-spelling category for the attribute
3161 // documentation. This may not be a limiting factor since the spellings
3162 // should generally be consistently applied across the category.
3164 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(*Doc.Attribute);
3166 // Determine the heading to be used for this attribute.
3167 std::string Heading = Doc.Documentation->getValueAsString("Heading");
3168 bool CustomHeading = !Heading.empty();
3169 if (Heading.empty()) {
3170 // If there's only one spelling, we can simply use that.
3171 if (Spellings.size() == 1)
3172 Heading = Spellings.begin()->name();
3174 std::set<std::string> Uniques;
3175 for (auto I = Spellings.begin(), E = Spellings.end();
3176 I != E && Uniques.size() <= 1; ++I) {
3177 std::string Spelling = NormalizeNameForSpellingComparison(I->name());
3178 Uniques.insert(Spelling);
3180 // If the semantic map has only one spelling, that is sufficient for our
3182 if (Uniques.size() == 1)
3183 Heading = *Uniques.begin();
3187 // If the heading is still empty, it is an error.
3188 if (Heading.empty())
3189 PrintFatalError(Doc.Attribute->getLoc(),
3190 "This attribute requires a heading to be specified");
3192 // Gather a list of unique spellings; this is not the same as the semantic
3193 // spelling for the attribute. Variations in underscores and other non-
3194 // semantic characters are still acceptable.
3195 std::vector<std::string> Names;
3197 unsigned SupportedSpellings = 0;
3198 for (const auto &I : Spellings) {
3199 SpellingKind Kind = StringSwitch<SpellingKind>(I.variety())
3201 .Case("CXX11", CXX11)
3202 .Case("Declspec", Declspec)
3203 .Case("Microsoft", Microsoft)
3204 .Case("Keyword", Keyword)
3205 .Case("Pragma", Pragma);
3207 // Mask in the supported spelling.
3208 SupportedSpellings |= Kind;
3211 if (Kind == CXX11 && !I.nameSpace().empty())
3212 Name = I.nameSpace() + "::";
3215 // If this name is the same as the heading, do not add it.
3216 if (Name != Heading)
3217 Names.push_back(Name);
3220 // Print out the heading for the attribute. If there are alternate spellings,
3221 // then display those after the heading.
3222 if (!CustomHeading && !Names.empty()) {
3224 for (auto I = Names.begin(), E = Names.end(); I != E; ++I) {
3225 if (I != Names.begin())
3231 OS << Heading << "\n" << std::string(Heading.length(), '-') << "\n";
3233 if (!SupportedSpellings)
3234 PrintFatalError(Doc.Attribute->getLoc(),
3235 "Attribute has no supported spellings; cannot be "
3238 // List what spelling syntaxes the attribute supports.
3239 OS << ".. csv-table:: Supported Syntaxes\n";
3240 OS << " :header: \"GNU\", \"C++11\", \"__declspec\", \"Keyword\",";
3241 OS << " \"Pragma\"\n\n";
3243 if (SupportedSpellings & GNU) OS << "X";
3245 if (SupportedSpellings & CXX11) OS << "X";
3247 if (SupportedSpellings & Declspec) OS << "X";
3249 if (SupportedSpellings & Keyword) OS << "X";
3251 if (SupportedSpellings & Pragma) OS << "X";
3254 // If the attribute is deprecated, print a message about it, and possibly
3255 // provide a replacement attribute.
3256 if (!Doc.Documentation->isValueUnset("Deprecated")) {
3257 OS << "This attribute has been deprecated, and may be removed in a future "
3258 << "version of Clang.";
3259 const Record &Deprecated = *Doc.Documentation->getValueAsDef("Deprecated");
3260 std::string Replacement = Deprecated.getValueAsString("Replacement");
3261 if (!Replacement.empty())
3262 OS << " This attribute has been superseded by ``"
3263 << Replacement << "``.";
3267 std::string ContentStr = Doc.Documentation->getValueAsString("Content");
3268 // Trim leading and trailing newlines and spaces.
3269 OS << StringRef(ContentStr).trim();
3274 void EmitClangAttrDocs(RecordKeeper &Records, raw_ostream &OS) {
3275 // Get the documentation introduction paragraph.
3276 const Record *Documentation = Records.getDef("GlobalDocumentation");
3277 if (!Documentation) {
3278 PrintFatalError("The Documentation top-level definition is missing, "
3279 "no documentation will be generated.");
3283 OS << Documentation->getValueAsString("Intro") << "\n";
3285 // Gather the Documentation lists from each of the attributes, based on the
3286 // category provided.
3287 std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
3288 std::map<const Record *, std::vector<DocumentationData>> SplitDocs;
3289 for (const auto *A : Attrs) {
3290 const Record &Attr = *A;
3291 std::vector<Record *> Docs = Attr.getValueAsListOfDefs("Documentation");
3292 for (const auto *D : Docs) {
3293 const Record &Doc = *D;
3294 const Record *Category = Doc.getValueAsDef("Category");
3295 // If the category is "undocumented", then there cannot be any other
3296 // documentation categories (otherwise, the attribute would become
3298 std::string Cat = Category->getValueAsString("Name");
3299 bool Undocumented = Cat == "Undocumented";
3300 if (Undocumented && Docs.size() > 1)
3301 PrintFatalError(Doc.getLoc(),
3302 "Attribute is \"Undocumented\", but has multiple "
3303 "documentation categories");
3306 SplitDocs[Category].push_back(DocumentationData(Doc, Attr));
3310 // Having split the attributes out based on what documentation goes where,
3311 // we can begin to generate sections of documentation.
3312 for (const auto &I : SplitDocs) {
3313 WriteCategoryHeader(I.first, OS);
3315 // Walk over each of the attributes in the category and write out their
3317 for (const auto &Doc : I.second)
3318 WriteDocumentation(Doc, OS);
3322 } // end namespace clang