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/SmallString.h"
15 #include "llvm/ADT/STLExtras.h"
16 #include "llvm/ADT/SmallSet.h"
17 #include "llvm/ADT/StringExtras.h"
18 #include "llvm/ADT/StringSwitch.h"
19 #include "llvm/TableGen/Error.h"
20 #include "llvm/TableGen/Record.h"
21 #include "llvm/TableGen/StringMatcher.h"
22 #include "llvm/TableGen/TableGenBackend.h"
32 class FlattenedSpelling {
37 FlattenedSpelling(const std::string &Variety, const std::string &Name,
38 const std::string &Namespace, bool KnownToGCC) :
39 V(Variety), N(Name), NS(Namespace), K(KnownToGCC) {}
40 explicit FlattenedSpelling(const Record &Spelling) :
41 V(Spelling.getValueAsString("Variety")),
42 N(Spelling.getValueAsString("Name")) {
44 assert(V != "GCC" && "Given a GCC spelling, which means this hasn't been"
46 if (V == "CXX11" || V == "Pragma")
47 NS = Spelling.getValueAsString("Namespace");
49 K = Spelling.getValueAsBitOrUnset("KnownToGCC", Unset);
52 const std::string &variety() const { return V; }
53 const std::string &name() const { return N; }
54 const std::string &nameSpace() const { return NS; }
55 bool knownToGCC() const { return K; }
59 static std::vector<FlattenedSpelling>
60 GetFlattenedSpellings(const Record &Attr) {
61 std::vector<Record *> Spellings = Attr.getValueAsListOfDefs("Spellings");
62 std::vector<FlattenedSpelling> Ret;
64 for (const auto &Spelling : Spellings) {
65 if (Spelling->getValueAsString("Variety") == "GCC") {
66 // Gin up two new spelling objects to add into the list.
67 Ret.emplace_back("GNU", Spelling->getValueAsString("Name"), "", true);
68 Ret.emplace_back("CXX11", Spelling->getValueAsString("Name"), "gnu",
71 Ret.push_back(FlattenedSpelling(*Spelling));
77 static std::string ReadPCHRecord(StringRef type) {
78 return StringSwitch<std::string>(type)
79 .EndsWith("Decl *", "GetLocalDeclAs<"
80 + std::string(type, 0, type.size()-1) + ">(F, Record[Idx++])")
81 .Case("TypeSourceInfo *", "GetTypeSourceInfo(F, Record, Idx)")
82 .Case("Expr *", "ReadExpr(F)")
83 .Case("IdentifierInfo *", "GetIdentifierInfo(F, Record, Idx)")
84 .Case("std::string", "ReadString(Record, Idx)")
85 .Default("Record[Idx++]");
88 // Assumes that the way to get the value is SA->getname()
89 static std::string WritePCHRecord(StringRef type, StringRef name) {
90 return StringSwitch<std::string>(type)
91 .EndsWith("Decl *", "AddDeclRef(" + std::string(name) +
93 .Case("TypeSourceInfo *",
94 "AddTypeSourceInfo(" + std::string(name) + ", Record);\n")
95 .Case("Expr *", "AddStmt(" + std::string(name) + ");\n")
96 .Case("IdentifierInfo *",
97 "AddIdentifierRef(" + std::string(name) + ", Record);\n")
98 .Case("std::string", "AddString(" + std::string(name) + ", Record);\n")
99 .Default("Record.push_back(" + std::string(name) + ");\n");
102 // Normalize attribute name by removing leading and trailing
103 // underscores. For example, __foo, foo__, __foo__ would
105 static StringRef NormalizeAttrName(StringRef AttrName) {
106 if (AttrName.startswith("__"))
107 AttrName = AttrName.substr(2, AttrName.size());
109 if (AttrName.endswith("__"))
110 AttrName = AttrName.substr(0, AttrName.size() - 2);
115 // Normalize the name by removing any and all leading and trailing underscores.
116 // This is different from NormalizeAttrName in that it also handles names like
117 // _pascal and __pascal.
118 static StringRef NormalizeNameForSpellingComparison(StringRef Name) {
119 return Name.trim("_");
122 // Normalize attribute spelling only if the spelling has both leading
123 // and trailing underscores. For example, __ms_struct__ will be
124 // normalized to "ms_struct"; __cdecl will remain intact.
125 static StringRef NormalizeAttrSpelling(StringRef AttrSpelling) {
126 if (AttrSpelling.startswith("__") && AttrSpelling.endswith("__")) {
127 AttrSpelling = AttrSpelling.substr(2, AttrSpelling.size() - 4);
133 typedef std::vector<std::pair<std::string, const Record *>> ParsedAttrMap;
135 static ParsedAttrMap getParsedAttrList(const RecordKeeper &Records,
136 ParsedAttrMap *Dupes = nullptr) {
137 std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
138 std::set<std::string> Seen;
140 for (const auto *Attr : Attrs) {
141 if (Attr->getValueAsBit("SemaHandler")) {
143 if (Attr->isSubClassOf("TargetSpecificAttr") &&
144 !Attr->isValueUnset("ParseKind")) {
145 AN = Attr->getValueAsString("ParseKind");
147 // If this attribute has already been handled, it does not need to be
149 if (Seen.find(AN) != Seen.end()) {
151 Dupes->push_back(std::make_pair(AN, Attr));
156 AN = NormalizeAttrName(Attr->getName()).str();
158 R.push_back(std::make_pair(AN, Attr));
166 std::string lowerName, upperName;
171 Argument(const Record &Arg, StringRef Attr)
172 : lowerName(Arg.getValueAsString("Name")), upperName(lowerName),
173 attrName(Attr), isOpt(false) {
174 if (!lowerName.empty()) {
175 lowerName[0] = std::tolower(lowerName[0]);
176 upperName[0] = std::toupper(upperName[0]);
179 virtual ~Argument() {}
181 StringRef getLowerName() const { return lowerName; }
182 StringRef getUpperName() const { return upperName; }
183 StringRef getAttrName() const { return attrName; }
185 bool isOptional() const { return isOpt; }
186 void setOptional(bool set) { isOpt = set; }
188 // These functions print the argument contents formatted in different ways.
189 virtual void writeAccessors(raw_ostream &OS) const = 0;
190 virtual void writeAccessorDefinitions(raw_ostream &OS) const {}
191 virtual void writeASTVisitorTraversal(raw_ostream &OS) const {}
192 virtual void writeCloneArgs(raw_ostream &OS) const = 0;
193 virtual void writeTemplateInstantiationArgs(raw_ostream &OS) const = 0;
194 virtual void writeTemplateInstantiation(raw_ostream &OS) const {}
195 virtual void writeCtorBody(raw_ostream &OS) const {}
196 virtual void writeCtorInitializers(raw_ostream &OS) const = 0;
197 virtual void writeCtorDefaultInitializers(raw_ostream &OS) const = 0;
198 virtual void writeCtorParameters(raw_ostream &OS) const = 0;
199 virtual void writeDeclarations(raw_ostream &OS) const = 0;
200 virtual void writePCHReadArgs(raw_ostream &OS) const = 0;
201 virtual void writePCHReadDecls(raw_ostream &OS) const = 0;
202 virtual void writePCHWrite(raw_ostream &OS) const = 0;
203 virtual void writeValue(raw_ostream &OS) const = 0;
204 virtual void writeDump(raw_ostream &OS) const = 0;
205 virtual void writeDumpChildren(raw_ostream &OS) const {}
206 virtual void writeHasChildren(raw_ostream &OS) const { OS << "false"; }
208 virtual bool isEnumArg() const { return false; }
209 virtual bool isVariadicEnumArg() const { return false; }
210 virtual bool isVariadic() const { return false; }
212 virtual void writeImplicitCtorArgs(raw_ostream &OS) const {
213 OS << getUpperName();
217 class SimpleArgument : public Argument {
221 SimpleArgument(const Record &Arg, StringRef Attr, std::string T)
222 : Argument(Arg, Attr), type(T)
225 std::string getType() const { return type; }
227 void writeAccessors(raw_ostream &OS) const override {
228 OS << " " << type << " get" << getUpperName() << "() const {\n";
229 OS << " return " << getLowerName() << ";\n";
232 void writeCloneArgs(raw_ostream &OS) const override {
233 OS << getLowerName();
235 void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
236 OS << "A->get" << getUpperName() << "()";
238 void writeCtorInitializers(raw_ostream &OS) const override {
239 OS << getLowerName() << "(" << getUpperName() << ")";
241 void writeCtorDefaultInitializers(raw_ostream &OS) const override {
242 OS << getLowerName() << "()";
244 void writeCtorParameters(raw_ostream &OS) const override {
245 OS << type << " " << getUpperName();
247 void writeDeclarations(raw_ostream &OS) const override {
248 OS << type << " " << getLowerName() << ";";
250 void writePCHReadDecls(raw_ostream &OS) const override {
251 std::string read = ReadPCHRecord(type);
252 OS << " " << type << " " << getLowerName() << " = " << read << ";\n";
254 void writePCHReadArgs(raw_ostream &OS) const override {
255 OS << getLowerName();
257 void writePCHWrite(raw_ostream &OS) const override {
258 OS << " " << WritePCHRecord(type, "SA->get" +
259 std::string(getUpperName()) + "()");
261 void writeValue(raw_ostream &OS) const override {
262 if (type == "FunctionDecl *") {
263 OS << "\" << get" << getUpperName()
264 << "()->getNameInfo().getAsString() << \"";
265 } else if (type == "IdentifierInfo *") {
266 OS << "\" << get" << getUpperName() << "()->getName() << \"";
267 } else if (type == "TypeSourceInfo *") {
268 OS << "\" << get" << getUpperName() << "().getAsString() << \"";
270 OS << "\" << get" << getUpperName() << "() << \"";
273 void writeDump(raw_ostream &OS) const override {
274 if (type == "FunctionDecl *") {
275 OS << " OS << \" \";\n";
276 OS << " dumpBareDeclRef(SA->get" << getUpperName() << "());\n";
277 } else if (type == "IdentifierInfo *") {
278 OS << " OS << \" \" << SA->get" << getUpperName()
279 << "()->getName();\n";
280 } else if (type == "TypeSourceInfo *") {
281 OS << " OS << \" \" << SA->get" << getUpperName()
282 << "().getAsString();\n";
283 } else if (type == "bool") {
284 OS << " if (SA->get" << getUpperName() << "()) OS << \" "
285 << getUpperName() << "\";\n";
286 } else if (type == "int" || type == "unsigned") {
287 OS << " OS << \" \" << SA->get" << getUpperName() << "();\n";
289 llvm_unreachable("Unknown SimpleArgument type!");
294 class DefaultSimpleArgument : public SimpleArgument {
298 DefaultSimpleArgument(const Record &Arg, StringRef Attr,
299 std::string T, int64_t Default)
300 : SimpleArgument(Arg, Attr, T), Default(Default) {}
302 void writeAccessors(raw_ostream &OS) const override {
303 SimpleArgument::writeAccessors(OS);
305 OS << "\n\n static const " << getType() << " Default" << getUpperName()
306 << " = " << Default << ";";
310 class StringArgument : public Argument {
312 StringArgument(const Record &Arg, StringRef Attr)
313 : Argument(Arg, Attr)
316 void writeAccessors(raw_ostream &OS) const override {
317 OS << " llvm::StringRef get" << getUpperName() << "() const {\n";
318 OS << " return llvm::StringRef(" << getLowerName() << ", "
319 << getLowerName() << "Length);\n";
321 OS << " unsigned get" << getUpperName() << "Length() const {\n";
322 OS << " return " << getLowerName() << "Length;\n";
324 OS << " void set" << getUpperName()
325 << "(ASTContext &C, llvm::StringRef S) {\n";
326 OS << " " << getLowerName() << "Length = S.size();\n";
327 OS << " this->" << getLowerName() << " = new (C, 1) char ["
328 << getLowerName() << "Length];\n";
329 OS << " if (!S.empty())\n";
330 OS << " std::memcpy(this->" << getLowerName() << ", S.data(), "
331 << getLowerName() << "Length);\n";
334 void writeCloneArgs(raw_ostream &OS) const override {
335 OS << "get" << getUpperName() << "()";
337 void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
338 OS << "A->get" << getUpperName() << "()";
340 void writeCtorBody(raw_ostream &OS) const override {
341 OS << " if (!" << getUpperName() << ".empty())\n";
342 OS << " std::memcpy(" << getLowerName() << ", " << getUpperName()
343 << ".data(), " << getLowerName() << "Length);";
345 void writeCtorInitializers(raw_ostream &OS) const override {
346 OS << getLowerName() << "Length(" << getUpperName() << ".size()),"
347 << getLowerName() << "(new (Ctx, 1) char[" << getLowerName()
350 void writeCtorDefaultInitializers(raw_ostream &OS) const override {
351 OS << getLowerName() << "Length(0)," << getLowerName() << "(0)";
353 void writeCtorParameters(raw_ostream &OS) const override {
354 OS << "llvm::StringRef " << getUpperName();
356 void writeDeclarations(raw_ostream &OS) const override {
357 OS << "unsigned " << getLowerName() << "Length;\n";
358 OS << "char *" << getLowerName() << ";";
360 void writePCHReadDecls(raw_ostream &OS) const override {
361 OS << " std::string " << getLowerName()
362 << "= ReadString(Record, Idx);\n";
364 void writePCHReadArgs(raw_ostream &OS) const override {
365 OS << getLowerName();
367 void writePCHWrite(raw_ostream &OS) const override {
368 OS << " AddString(SA->get" << getUpperName() << "(), Record);\n";
370 void writeValue(raw_ostream &OS) const override {
371 OS << "\\\"\" << get" << getUpperName() << "() << \"\\\"";
373 void writeDump(raw_ostream &OS) const override {
374 OS << " OS << \" \\\"\" << SA->get" << getUpperName()
375 << "() << \"\\\"\";\n";
379 class AlignedArgument : public Argument {
381 AlignedArgument(const Record &Arg, StringRef Attr)
382 : Argument(Arg, Attr)
385 void writeAccessors(raw_ostream &OS) const override {
386 OS << " bool is" << getUpperName() << "Dependent() const;\n";
388 OS << " unsigned get" << getUpperName() << "(ASTContext &Ctx) const;\n";
390 OS << " bool is" << getUpperName() << "Expr() const {\n";
391 OS << " return is" << getLowerName() << "Expr;\n";
394 OS << " Expr *get" << getUpperName() << "Expr() const {\n";
395 OS << " assert(is" << getLowerName() << "Expr);\n";
396 OS << " return " << getLowerName() << "Expr;\n";
399 OS << " TypeSourceInfo *get" << getUpperName() << "Type() const {\n";
400 OS << " assert(!is" << getLowerName() << "Expr);\n";
401 OS << " return " << getLowerName() << "Type;\n";
404 void writeAccessorDefinitions(raw_ostream &OS) const override {
405 OS << "bool " << getAttrName() << "Attr::is" << getUpperName()
406 << "Dependent() const {\n";
407 OS << " if (is" << getLowerName() << "Expr)\n";
408 OS << " return " << getLowerName() << "Expr && (" << getLowerName()
409 << "Expr->isValueDependent() || " << getLowerName()
410 << "Expr->isTypeDependent());\n";
412 OS << " return " << getLowerName()
413 << "Type->getType()->isDependentType();\n";
416 // FIXME: Do not do the calculation here
417 // FIXME: Handle types correctly
418 // A null pointer means maximum alignment
419 OS << "unsigned " << getAttrName() << "Attr::get" << getUpperName()
420 << "(ASTContext &Ctx) const {\n";
421 OS << " assert(!is" << getUpperName() << "Dependent());\n";
422 OS << " if (is" << getLowerName() << "Expr)\n";
423 OS << " return " << getLowerName() << "Expr ? " << getLowerName()
424 << "Expr->EvaluateKnownConstInt(Ctx).getZExtValue()"
425 << " * Ctx.getCharWidth() : "
426 << "Ctx.getTargetDefaultAlignForAttributeAligned();\n";
428 OS << " return 0; // FIXME\n";
431 void writeCloneArgs(raw_ostream &OS) const override {
432 OS << "is" << getLowerName() << "Expr, is" << getLowerName()
433 << "Expr ? static_cast<void*>(" << getLowerName()
434 << "Expr) : " << getLowerName()
437 void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
438 // FIXME: move the definition in Sema::InstantiateAttrs to here.
439 // In the meantime, aligned attributes are cloned.
441 void writeCtorBody(raw_ostream &OS) const override {
442 OS << " if (is" << getLowerName() << "Expr)\n";
443 OS << " " << getLowerName() << "Expr = reinterpret_cast<Expr *>("
444 << getUpperName() << ");\n";
446 OS << " " << getLowerName()
447 << "Type = reinterpret_cast<TypeSourceInfo *>(" << getUpperName()
450 void writeCtorInitializers(raw_ostream &OS) const override {
451 OS << "is" << getLowerName() << "Expr(Is" << getUpperName() << "Expr)";
453 void writeCtorDefaultInitializers(raw_ostream &OS) const override {
454 OS << "is" << getLowerName() << "Expr(false)";
456 void writeCtorParameters(raw_ostream &OS) const override {
457 OS << "bool Is" << getUpperName() << "Expr, void *" << getUpperName();
459 void writeImplicitCtorArgs(raw_ostream &OS) const override {
460 OS << "Is" << getUpperName() << "Expr, " << getUpperName();
462 void writeDeclarations(raw_ostream &OS) const override {
463 OS << "bool is" << getLowerName() << "Expr;\n";
465 OS << "Expr *" << getLowerName() << "Expr;\n";
466 OS << "TypeSourceInfo *" << getLowerName() << "Type;\n";
469 void writePCHReadArgs(raw_ostream &OS) const override {
470 OS << "is" << getLowerName() << "Expr, " << getLowerName() << "Ptr";
472 void writePCHReadDecls(raw_ostream &OS) const override {
473 OS << " bool is" << getLowerName() << "Expr = Record[Idx++];\n";
474 OS << " void *" << getLowerName() << "Ptr;\n";
475 OS << " if (is" << getLowerName() << "Expr)\n";
476 OS << " " << getLowerName() << "Ptr = ReadExpr(F);\n";
478 OS << " " << getLowerName()
479 << "Ptr = GetTypeSourceInfo(F, Record, Idx);\n";
481 void writePCHWrite(raw_ostream &OS) const override {
482 OS << " Record.push_back(SA->is" << getUpperName() << "Expr());\n";
483 OS << " if (SA->is" << getUpperName() << "Expr())\n";
484 OS << " AddStmt(SA->get" << getUpperName() << "Expr());\n";
486 OS << " AddTypeSourceInfo(SA->get" << getUpperName()
487 << "Type(), Record);\n";
489 void writeValue(raw_ostream &OS) const override {
491 // The aligned attribute argument expression is optional.
492 OS << " if (is" << getLowerName() << "Expr && "
493 << getLowerName() << "Expr)\n";
494 OS << " " << getLowerName() << "Expr->printPretty(OS, 0, Policy);\n";
497 void writeDump(raw_ostream &OS) const override {
499 void writeDumpChildren(raw_ostream &OS) const override {
500 OS << " if (SA->is" << getUpperName() << "Expr())\n";
501 OS << " dumpStmt(SA->get" << getUpperName() << "Expr());\n";
503 OS << " dumpType(SA->get" << getUpperName()
504 << "Type()->getType());\n";
506 void writeHasChildren(raw_ostream &OS) const override {
507 OS << "SA->is" << getUpperName() << "Expr()";
511 class VariadicArgument : public Argument {
512 std::string Type, ArgName, ArgSizeName, RangeName;
515 // Assumed to receive a parameter: raw_ostream OS.
516 virtual void writeValueImpl(raw_ostream &OS) const {
517 OS << " OS << Val;\n";
521 VariadicArgument(const Record &Arg, StringRef Attr, std::string T)
522 : Argument(Arg, Attr), Type(T), ArgName(getLowerName().str() + "_"),
523 ArgSizeName(ArgName + "Size"), RangeName(getLowerName()) {}
525 std::string getType() const { return Type; }
526 bool isVariadic() const override { return true; }
528 void writeAccessors(raw_ostream &OS) const override {
529 std::string IteratorType = getLowerName().str() + "_iterator";
530 std::string BeginFn = getLowerName().str() + "_begin()";
531 std::string EndFn = getLowerName().str() + "_end()";
533 OS << " typedef " << Type << "* " << IteratorType << ";\n";
534 OS << " " << IteratorType << " " << BeginFn << " const {"
535 << " return " << ArgName << "; }\n";
536 OS << " " << IteratorType << " " << EndFn << " const {"
537 << " return " << ArgName << " + " << ArgSizeName << "; }\n";
538 OS << " unsigned " << getLowerName() << "_size() const {"
539 << " return " << ArgSizeName << "; }\n";
540 OS << " llvm::iterator_range<" << IteratorType << "> " << RangeName
541 << "() const { return llvm::make_range(" << BeginFn << ", " << EndFn
544 void writeCloneArgs(raw_ostream &OS) const override {
545 OS << ArgName << ", " << ArgSizeName;
547 void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
548 // This isn't elegant, but we have to go through public methods...
549 OS << "A->" << getLowerName() << "_begin(), "
550 << "A->" << getLowerName() << "_size()";
552 void writeCtorBody(raw_ostream &OS) const override {
553 OS << " std::copy(" << getUpperName() << ", " << getUpperName()
554 << " + " << ArgSizeName << ", " << ArgName << ");";
556 void writeCtorInitializers(raw_ostream &OS) const override {
557 OS << ArgSizeName << "(" << getUpperName() << "Size), "
558 << ArgName << "(new (Ctx, 16) " << getType() << "["
559 << ArgSizeName << "])";
561 void writeCtorDefaultInitializers(raw_ostream &OS) const override {
562 OS << ArgSizeName << "(0), " << ArgName << "(nullptr)";
564 void writeCtorParameters(raw_ostream &OS) const override {
565 OS << getType() << " *" << getUpperName() << ", unsigned "
566 << getUpperName() << "Size";
568 void writeImplicitCtorArgs(raw_ostream &OS) const override {
569 OS << getUpperName() << ", " << getUpperName() << "Size";
571 void writeDeclarations(raw_ostream &OS) const override {
572 OS << " unsigned " << ArgSizeName << ";\n";
573 OS << " " << getType() << " *" << ArgName << ";";
575 void writePCHReadDecls(raw_ostream &OS) const override {
576 OS << " unsigned " << getLowerName() << "Size = Record[Idx++];\n";
577 OS << " SmallVector<" << Type << ", 4> " << getLowerName()
579 OS << " " << getLowerName() << ".reserve(" << getLowerName()
581 OS << " for (unsigned i = " << getLowerName() << "Size; i; --i)\n";
583 std::string read = ReadPCHRecord(Type);
584 OS << " " << getLowerName() << ".push_back(" << read << ");\n";
586 void writePCHReadArgs(raw_ostream &OS) const override {
587 OS << getLowerName() << ".data(), " << getLowerName() << "Size";
589 void writePCHWrite(raw_ostream &OS) const override {
590 OS << " Record.push_back(SA->" << getLowerName() << "_size());\n";
591 OS << " for (auto &Val : SA->" << RangeName << "())\n";
592 OS << " " << WritePCHRecord(Type, "Val");
594 void writeValue(raw_ostream &OS) const override {
596 OS << " bool isFirst = true;\n"
597 << " for (const auto &Val : " << RangeName << "()) {\n"
598 << " if (isFirst) isFirst = false;\n"
599 << " else OS << \", \";\n";
604 void writeDump(raw_ostream &OS) const override {
605 OS << " for (const auto &Val : SA->" << RangeName << "())\n";
606 OS << " OS << \" \" << Val;\n";
610 // Unique the enums, but maintain the original declaration ordering.
611 std::vector<std::string>
612 uniqueEnumsInOrder(const std::vector<std::string> &enums) {
613 std::vector<std::string> uniques;
614 std::set<std::string> unique_set(enums.begin(), enums.end());
615 for (const auto &i : enums) {
616 std::set<std::string>::iterator set_i = unique_set.find(i);
617 if (set_i != unique_set.end()) {
618 uniques.push_back(i);
619 unique_set.erase(set_i);
625 class EnumArgument : public Argument {
627 std::vector<std::string> values, enums, uniques;
629 EnumArgument(const Record &Arg, StringRef Attr)
630 : Argument(Arg, Attr), type(Arg.getValueAsString("Type")),
631 values(Arg.getValueAsListOfStrings("Values")),
632 enums(Arg.getValueAsListOfStrings("Enums")),
633 uniques(uniqueEnumsInOrder(enums))
635 // FIXME: Emit a proper error
636 assert(!uniques.empty());
639 bool isEnumArg() const override { return true; }
641 void writeAccessors(raw_ostream &OS) const override {
642 OS << " " << type << " get" << getUpperName() << "() const {\n";
643 OS << " return " << getLowerName() << ";\n";
646 void writeCloneArgs(raw_ostream &OS) const override {
647 OS << getLowerName();
649 void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
650 OS << "A->get" << getUpperName() << "()";
652 void writeCtorInitializers(raw_ostream &OS) const override {
653 OS << getLowerName() << "(" << getUpperName() << ")";
655 void writeCtorDefaultInitializers(raw_ostream &OS) const override {
656 OS << getLowerName() << "(" << type << "(0))";
658 void writeCtorParameters(raw_ostream &OS) const override {
659 OS << type << " " << getUpperName();
661 void writeDeclarations(raw_ostream &OS) const override {
662 std::vector<std::string>::const_iterator i = uniques.begin(),
664 // The last one needs to not have a comma.
668 OS << " enum " << type << " {\n";
670 OS << " " << *i << ",\n";
671 OS << " " << *e << "\n";
674 OS << " " << type << " " << getLowerName() << ";";
676 void writePCHReadDecls(raw_ostream &OS) const override {
677 OS << " " << getAttrName() << "Attr::" << type << " " << getLowerName()
678 << "(static_cast<" << getAttrName() << "Attr::" << type
679 << ">(Record[Idx++]));\n";
681 void writePCHReadArgs(raw_ostream &OS) const override {
682 OS << getLowerName();
684 void writePCHWrite(raw_ostream &OS) const override {
685 OS << "Record.push_back(SA->get" << getUpperName() << "());\n";
687 void writeValue(raw_ostream &OS) const override {
688 // FIXME: this isn't 100% correct -- some enum arguments require printing
689 // as a string literal, while others require printing as an identifier.
690 // Tablegen currently does not distinguish between the two forms.
691 OS << "\\\"\" << " << getAttrName() << "Attr::Convert" << type << "ToStr(get"
692 << getUpperName() << "()) << \"\\\"";
694 void writeDump(raw_ostream &OS) const override {
695 OS << " switch(SA->get" << getUpperName() << "()) {\n";
696 for (const auto &I : uniques) {
697 OS << " case " << getAttrName() << "Attr::" << I << ":\n";
698 OS << " OS << \" " << I << "\";\n";
704 void writeConversion(raw_ostream &OS) const {
705 OS << " static bool ConvertStrTo" << type << "(StringRef Val, ";
706 OS << type << " &Out) {\n";
707 OS << " Optional<" << type << "> R = llvm::StringSwitch<Optional<";
708 OS << type << ">>(Val)\n";
709 for (size_t I = 0; I < enums.size(); ++I) {
710 OS << " .Case(\"" << values[I] << "\", ";
711 OS << getAttrName() << "Attr::" << enums[I] << ")\n";
713 OS << " .Default(Optional<" << type << ">());\n";
715 OS << " Out = *R;\n return true;\n }\n";
716 OS << " return false;\n";
719 // Mapping from enumeration values back to enumeration strings isn't
720 // trivial because some enumeration values have multiple named
721 // enumerators, such as type_visibility(internal) and
722 // type_visibility(hidden) both mapping to TypeVisibilityAttr::Hidden.
723 OS << " static const char *Convert" << type << "ToStr("
724 << type << " Val) {\n"
725 << " switch(Val) {\n";
726 std::set<std::string> Uniques;
727 for (size_t I = 0; I < enums.size(); ++I) {
728 if (Uniques.insert(enums[I]).second)
729 OS << " case " << getAttrName() << "Attr::" << enums[I]
730 << ": return \"" << values[I] << "\";\n";
733 << " llvm_unreachable(\"No enumerator with that value\");\n"
738 class VariadicEnumArgument: public VariadicArgument {
739 std::string type, QualifiedTypeName;
740 std::vector<std::string> values, enums, uniques;
743 void writeValueImpl(raw_ostream &OS) const override {
744 // FIXME: this isn't 100% correct -- some enum arguments require printing
745 // as a string literal, while others require printing as an identifier.
746 // Tablegen currently does not distinguish between the two forms.
747 OS << " OS << \"\\\"\" << " << getAttrName() << "Attr::Convert" << type
748 << "ToStr(Val)" << "<< \"\\\"\";\n";
752 VariadicEnumArgument(const Record &Arg, StringRef Attr)
753 : VariadicArgument(Arg, Attr, Arg.getValueAsString("Type")),
754 type(Arg.getValueAsString("Type")),
755 values(Arg.getValueAsListOfStrings("Values")),
756 enums(Arg.getValueAsListOfStrings("Enums")),
757 uniques(uniqueEnumsInOrder(enums))
759 QualifiedTypeName = getAttrName().str() + "Attr::" + type;
761 // FIXME: Emit a proper error
762 assert(!uniques.empty());
765 bool isVariadicEnumArg() const override { return true; }
767 void writeDeclarations(raw_ostream &OS) const override {
768 std::vector<std::string>::const_iterator i = uniques.begin(),
770 // The last one needs to not have a comma.
774 OS << " enum " << type << " {\n";
776 OS << " " << *i << ",\n";
777 OS << " " << *e << "\n";
781 VariadicArgument::writeDeclarations(OS);
783 void writeDump(raw_ostream &OS) const override {
784 OS << " for (" << getAttrName() << "Attr::" << getLowerName()
785 << "_iterator I = SA->" << getLowerName() << "_begin(), E = SA->"
786 << getLowerName() << "_end(); I != E; ++I) {\n";
787 OS << " switch(*I) {\n";
788 for (const auto &UI : uniques) {
789 OS << " case " << getAttrName() << "Attr::" << UI << ":\n";
790 OS << " OS << \" " << UI << "\";\n";
796 void writePCHReadDecls(raw_ostream &OS) const override {
797 OS << " unsigned " << getLowerName() << "Size = Record[Idx++];\n";
798 OS << " SmallVector<" << QualifiedTypeName << ", 4> " << getLowerName()
800 OS << " " << getLowerName() << ".reserve(" << getLowerName()
802 OS << " for (unsigned i = " << getLowerName() << "Size; i; --i)\n";
803 OS << " " << getLowerName() << ".push_back(" << "static_cast<"
804 << QualifiedTypeName << ">(Record[Idx++]));\n";
806 void writePCHWrite(raw_ostream &OS) const override {
807 OS << " Record.push_back(SA->" << getLowerName() << "_size());\n";
808 OS << " for (" << getAttrName() << "Attr::" << getLowerName()
809 << "_iterator i = SA->" << getLowerName() << "_begin(), e = SA->"
810 << getLowerName() << "_end(); i != e; ++i)\n";
811 OS << " " << WritePCHRecord(QualifiedTypeName, "(*i)");
813 void writeConversion(raw_ostream &OS) const {
814 OS << " static bool ConvertStrTo" << type << "(StringRef Val, ";
815 OS << type << " &Out) {\n";
816 OS << " Optional<" << type << "> R = llvm::StringSwitch<Optional<";
817 OS << type << ">>(Val)\n";
818 for (size_t I = 0; I < enums.size(); ++I) {
819 OS << " .Case(\"" << values[I] << "\", ";
820 OS << getAttrName() << "Attr::" << enums[I] << ")\n";
822 OS << " .Default(Optional<" << type << ">());\n";
824 OS << " Out = *R;\n return true;\n }\n";
825 OS << " return false;\n";
828 OS << " static const char *Convert" << type << "ToStr("
829 << type << " Val) {\n"
830 << " switch(Val) {\n";
831 std::set<std::string> Uniques;
832 for (size_t I = 0; I < enums.size(); ++I) {
833 if (Uniques.insert(enums[I]).second)
834 OS << " case " << getAttrName() << "Attr::" << enums[I]
835 << ": return \"" << values[I] << "\";\n";
838 << " llvm_unreachable(\"No enumerator with that value\");\n"
843 class VersionArgument : public Argument {
845 VersionArgument(const Record &Arg, StringRef Attr)
846 : Argument(Arg, Attr)
849 void writeAccessors(raw_ostream &OS) const override {
850 OS << " VersionTuple get" << getUpperName() << "() const {\n";
851 OS << " return " << getLowerName() << ";\n";
853 OS << " void set" << getUpperName()
854 << "(ASTContext &C, VersionTuple V) {\n";
855 OS << " " << getLowerName() << " = V;\n";
858 void writeCloneArgs(raw_ostream &OS) const override {
859 OS << "get" << getUpperName() << "()";
861 void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
862 OS << "A->get" << getUpperName() << "()";
864 void writeCtorInitializers(raw_ostream &OS) const override {
865 OS << getLowerName() << "(" << getUpperName() << ")";
867 void writeCtorDefaultInitializers(raw_ostream &OS) const override {
868 OS << getLowerName() << "()";
870 void writeCtorParameters(raw_ostream &OS) const override {
871 OS << "VersionTuple " << getUpperName();
873 void writeDeclarations(raw_ostream &OS) const override {
874 OS << "VersionTuple " << getLowerName() << ";\n";
876 void writePCHReadDecls(raw_ostream &OS) const override {
877 OS << " VersionTuple " << getLowerName()
878 << "= ReadVersionTuple(Record, Idx);\n";
880 void writePCHReadArgs(raw_ostream &OS) const override {
881 OS << getLowerName();
883 void writePCHWrite(raw_ostream &OS) const override {
884 OS << " AddVersionTuple(SA->get" << getUpperName() << "(), Record);\n";
886 void writeValue(raw_ostream &OS) const override {
887 OS << getLowerName() << "=\" << get" << getUpperName() << "() << \"";
889 void writeDump(raw_ostream &OS) const override {
890 OS << " OS << \" \" << SA->get" << getUpperName() << "();\n";
894 class ExprArgument : public SimpleArgument {
896 ExprArgument(const Record &Arg, StringRef Attr)
897 : SimpleArgument(Arg, Attr, "Expr *")
900 void writeASTVisitorTraversal(raw_ostream &OS) const override {
902 << "getDerived().TraverseStmt(A->get" << getUpperName() << "()))\n";
903 OS << " return false;\n";
906 void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
907 OS << "tempInst" << getUpperName();
910 void writeTemplateInstantiation(raw_ostream &OS) const override {
911 OS << " " << getType() << " tempInst" << getUpperName() << ";\n";
913 OS << " EnterExpressionEvaluationContext "
914 << "Unevaluated(S, Sema::Unevaluated);\n";
915 OS << " ExprResult " << "Result = S.SubstExpr("
916 << "A->get" << getUpperName() << "(), TemplateArgs);\n";
917 OS << " tempInst" << getUpperName() << " = "
918 << "Result.getAs<Expr>();\n";
922 void writeDump(raw_ostream &OS) const override {}
924 void writeDumpChildren(raw_ostream &OS) const override {
925 OS << " dumpStmt(SA->get" << getUpperName() << "());\n";
927 void writeHasChildren(raw_ostream &OS) const override { OS << "true"; }
930 class VariadicExprArgument : public VariadicArgument {
932 VariadicExprArgument(const Record &Arg, StringRef Attr)
933 : VariadicArgument(Arg, Attr, "Expr *")
936 void writeASTVisitorTraversal(raw_ostream &OS) const override {
938 OS << " " << getType() << " *I = A->" << getLowerName()
940 OS << " " << getType() << " *E = A->" << getLowerName()
942 OS << " for (; I != E; ++I) {\n";
943 OS << " if (!getDerived().TraverseStmt(*I))\n";
944 OS << " return false;\n";
949 void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
950 OS << "tempInst" << getUpperName() << ", "
951 << "A->" << getLowerName() << "_size()";
954 void writeTemplateInstantiation(raw_ostream &OS) const override {
955 OS << " " << getType() << " *tempInst" << getUpperName()
956 << " = new (C, 16) " << getType()
957 << "[A->" << getLowerName() << "_size()];\n";
959 OS << " EnterExpressionEvaluationContext "
960 << "Unevaluated(S, Sema::Unevaluated);\n";
961 OS << " " << getType() << " *TI = tempInst" << getUpperName()
963 OS << " " << getType() << " *I = A->" << getLowerName()
965 OS << " " << getType() << " *E = A->" << getLowerName()
967 OS << " for (; I != E; ++I, ++TI) {\n";
968 OS << " ExprResult Result = S.SubstExpr(*I, TemplateArgs);\n";
969 OS << " *TI = Result.getAs<Expr>();\n";
974 void writeDump(raw_ostream &OS) const override {}
976 void writeDumpChildren(raw_ostream &OS) const override {
977 OS << " for (" << getAttrName() << "Attr::" << getLowerName()
978 << "_iterator I = SA->" << getLowerName() << "_begin(), E = SA->"
979 << getLowerName() << "_end(); I != E; ++I)\n";
980 OS << " dumpStmt(*I);\n";
983 void writeHasChildren(raw_ostream &OS) const override {
984 OS << "SA->" << getLowerName() << "_begin() != "
985 << "SA->" << getLowerName() << "_end()";
989 class VariadicStringArgument : public VariadicArgument {
991 VariadicStringArgument(const Record &Arg, StringRef Attr)
992 : VariadicArgument(Arg, Attr, "std::string")
994 void writeValueImpl(raw_ostream &OS) const override {
995 OS << " OS << \"\\\"\" << Val << \"\\\"\";\n";
999 class TypeArgument : public SimpleArgument {
1001 TypeArgument(const Record &Arg, StringRef Attr)
1002 : SimpleArgument(Arg, Attr, "TypeSourceInfo *")
1005 void writeAccessors(raw_ostream &OS) const override {
1006 OS << " QualType get" << getUpperName() << "() const {\n";
1007 OS << " return " << getLowerName() << "->getType();\n";
1009 OS << " " << getType() << " get" << getUpperName() << "Loc() const {\n";
1010 OS << " return " << getLowerName() << ";\n";
1013 void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
1014 OS << "A->get" << getUpperName() << "Loc()";
1016 void writePCHWrite(raw_ostream &OS) const override {
1017 OS << " " << WritePCHRecord(
1018 getType(), "SA->get" + std::string(getUpperName()) + "Loc()");
1023 static std::unique_ptr<Argument>
1024 createArgument(const Record &Arg, StringRef Attr,
1025 const Record *Search = nullptr) {
1029 std::unique_ptr<Argument> Ptr;
1030 llvm::StringRef ArgName = Search->getName();
1032 if (ArgName == "AlignedArgument")
1033 Ptr = llvm::make_unique<AlignedArgument>(Arg, Attr);
1034 else if (ArgName == "EnumArgument")
1035 Ptr = llvm::make_unique<EnumArgument>(Arg, Attr);
1036 else if (ArgName == "ExprArgument")
1037 Ptr = llvm::make_unique<ExprArgument>(Arg, Attr);
1038 else if (ArgName == "FunctionArgument")
1039 Ptr = llvm::make_unique<SimpleArgument>(Arg, Attr, "FunctionDecl *");
1040 else if (ArgName == "IdentifierArgument")
1041 Ptr = llvm::make_unique<SimpleArgument>(Arg, Attr, "IdentifierInfo *");
1042 else if (ArgName == "DefaultBoolArgument")
1043 Ptr = llvm::make_unique<DefaultSimpleArgument>(
1044 Arg, Attr, "bool", Arg.getValueAsBit("Default"));
1045 else if (ArgName == "BoolArgument")
1046 Ptr = llvm::make_unique<SimpleArgument>(Arg, Attr, "bool");
1047 else if (ArgName == "DefaultIntArgument")
1048 Ptr = llvm::make_unique<DefaultSimpleArgument>(
1049 Arg, Attr, "int", Arg.getValueAsInt("Default"));
1050 else if (ArgName == "IntArgument")
1051 Ptr = llvm::make_unique<SimpleArgument>(Arg, Attr, "int");
1052 else if (ArgName == "StringArgument")
1053 Ptr = llvm::make_unique<StringArgument>(Arg, Attr);
1054 else if (ArgName == "TypeArgument")
1055 Ptr = llvm::make_unique<TypeArgument>(Arg, Attr);
1056 else if (ArgName == "UnsignedArgument")
1057 Ptr = llvm::make_unique<SimpleArgument>(Arg, Attr, "unsigned");
1058 else if (ArgName == "VariadicUnsignedArgument")
1059 Ptr = llvm::make_unique<VariadicArgument>(Arg, Attr, "unsigned");
1060 else if (ArgName == "VariadicStringArgument")
1061 Ptr = llvm::make_unique<VariadicStringArgument>(Arg, Attr);
1062 else if (ArgName == "VariadicEnumArgument")
1063 Ptr = llvm::make_unique<VariadicEnumArgument>(Arg, Attr);
1064 else if (ArgName == "VariadicExprArgument")
1065 Ptr = llvm::make_unique<VariadicExprArgument>(Arg, Attr);
1066 else if (ArgName == "VersionArgument")
1067 Ptr = llvm::make_unique<VersionArgument>(Arg, Attr);
1070 // Search in reverse order so that the most-derived type is handled first.
1071 ArrayRef<Record*> Bases = Search->getSuperClasses();
1072 for (const auto *Base : llvm::make_range(Bases.rbegin(), Bases.rend())) {
1073 if ((Ptr = createArgument(Arg, Attr, Base)))
1078 if (Ptr && Arg.getValueAsBit("Optional"))
1079 Ptr->setOptional(true);
1084 static void writeAvailabilityValue(raw_ostream &OS) {
1085 OS << "\" << getPlatform()->getName();\n"
1086 << " if (!getIntroduced().empty()) OS << \", introduced=\" << getIntroduced();\n"
1087 << " if (!getDeprecated().empty()) OS << \", deprecated=\" << getDeprecated();\n"
1088 << " if (!getObsoleted().empty()) OS << \", obsoleted=\" << getObsoleted();\n"
1089 << " if (getUnavailable()) OS << \", unavailable\";\n"
1093 static void writeGetSpellingFunction(Record &R, raw_ostream &OS) {
1094 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(R);
1096 OS << "const char *" << R.getName() << "Attr::getSpelling() const {\n";
1097 if (Spellings.empty()) {
1098 OS << " return \"(No spelling)\";\n}\n\n";
1102 OS << " switch (SpellingListIndex) {\n"
1104 " llvm_unreachable(\"Unknown attribute spelling!\");\n"
1105 " return \"(No spelling)\";\n";
1107 for (unsigned I = 0; I < Spellings.size(); ++I)
1108 OS << " case " << I << ":\n"
1109 " return \"" << Spellings[I].name() << "\";\n";
1110 // End of the switch statement.
1112 // End of the getSpelling function.
1117 writePrettyPrintFunction(Record &R,
1118 const std::vector<std::unique_ptr<Argument>> &Args,
1120 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(R);
1122 OS << "void " << R.getName() << "Attr::printPretty("
1123 << "raw_ostream &OS, const PrintingPolicy &Policy) const {\n";
1125 if (Spellings.empty()) {
1131 " switch (SpellingListIndex) {\n"
1133 " llvm_unreachable(\"Unknown attribute spelling!\");\n"
1136 for (unsigned I = 0; I < Spellings.size(); ++ I) {
1137 llvm::SmallString<16> Prefix;
1138 llvm::SmallString<8> Suffix;
1139 // The actual spelling of the name and namespace (if applicable)
1140 // of an attribute without considering prefix and suffix.
1141 llvm::SmallString<64> Spelling;
1142 std::string Name = Spellings[I].name();
1143 std::string Variety = Spellings[I].variety();
1145 if (Variety == "GNU") {
1146 Prefix = " __attribute__((";
1148 } else if (Variety == "CXX11") {
1151 std::string Namespace = Spellings[I].nameSpace();
1152 if (!Namespace.empty()) {
1153 Spelling += Namespace;
1156 } else if (Variety == "Declspec") {
1157 Prefix = " __declspec(";
1159 } else if (Variety == "Keyword") {
1162 } else if (Variety == "Pragma") {
1163 Prefix = "#pragma ";
1165 std::string Namespace = Spellings[I].nameSpace();
1166 if (!Namespace.empty()) {
1167 Spelling += Namespace;
1171 llvm_unreachable("Unknown attribute syntax variety!");
1177 " case " << I << " : {\n"
1178 " OS << \"" << Prefix << Spelling;
1180 if (Variety == "Pragma") {
1182 OS << " printPrettyPragma(OS, Policy);\n";
1188 // FIXME: always printing the parenthesis isn't the correct behavior for
1189 // attributes which have optional arguments that were not provided. For
1190 // instance: __attribute__((aligned)) will be pretty printed as
1191 // __attribute__((aligned())). The logic should check whether there is only
1192 // a single argument, and if it is optional, whether it has been provided.
1195 if (Spelling == "availability") {
1196 writeAvailabilityValue(OS);
1198 for (auto I = Args.begin(), E = Args.end(); I != E; ++ I) {
1199 if (I != Args.begin()) OS << ", ";
1200 (*I)->writeValue(OS);
1206 OS << Suffix + "\";\n";
1213 // End of the switch statement.
1215 // End of the print function.
1219 /// \brief Return the index of a spelling in a spelling list.
1221 getSpellingListIndex(const std::vector<FlattenedSpelling> &SpellingList,
1222 const FlattenedSpelling &Spelling) {
1223 assert(!SpellingList.empty() && "Spelling list is empty!");
1225 for (unsigned Index = 0; Index < SpellingList.size(); ++Index) {
1226 const FlattenedSpelling &S = SpellingList[Index];
1227 if (S.variety() != Spelling.variety())
1229 if (S.nameSpace() != Spelling.nameSpace())
1231 if (S.name() != Spelling.name())
1237 llvm_unreachable("Unknown spelling!");
1240 static void writeAttrAccessorDefinition(const Record &R, raw_ostream &OS) {
1241 std::vector<Record*> Accessors = R.getValueAsListOfDefs("Accessors");
1242 for (const auto *Accessor : Accessors) {
1243 std::string Name = Accessor->getValueAsString("Name");
1244 std::vector<FlattenedSpelling> Spellings =
1245 GetFlattenedSpellings(*Accessor);
1246 std::vector<FlattenedSpelling> SpellingList = GetFlattenedSpellings(R);
1247 assert(!SpellingList.empty() &&
1248 "Attribute with empty spelling list can't have accessors!");
1250 OS << " bool " << Name << "() const { return SpellingListIndex == ";
1251 for (unsigned Index = 0; Index < Spellings.size(); ++Index) {
1252 OS << getSpellingListIndex(SpellingList, Spellings[Index]);
1253 if (Index != Spellings.size() -1)
1254 OS << " ||\n SpellingListIndex == ";
1262 SpellingNamesAreCommon(const std::vector<FlattenedSpelling>& Spellings) {
1263 assert(!Spellings.empty() && "An empty list of spellings was provided");
1264 std::string FirstName = NormalizeNameForSpellingComparison(
1265 Spellings.front().name());
1266 for (const auto &Spelling :
1267 llvm::make_range(std::next(Spellings.begin()), Spellings.end())) {
1268 std::string Name = NormalizeNameForSpellingComparison(Spelling.name());
1269 if (Name != FirstName)
1275 typedef std::map<unsigned, std::string> SemanticSpellingMap;
1277 CreateSemanticSpellings(const std::vector<FlattenedSpelling> &Spellings,
1278 SemanticSpellingMap &Map) {
1279 // The enumerants are automatically generated based on the variety,
1280 // namespace (if present) and name for each attribute spelling. However,
1281 // care is taken to avoid trampling on the reserved namespace due to
1283 std::string Ret(" enum Spelling {\n");
1284 std::set<std::string> Uniques;
1286 for (auto I = Spellings.begin(), E = Spellings.end(); I != E; ++I, ++Idx) {
1287 const FlattenedSpelling &S = *I;
1288 std::string Variety = S.variety();
1289 std::string Spelling = S.name();
1290 std::string Namespace = S.nameSpace();
1291 std::string EnumName = "";
1293 EnumName += (Variety + "_");
1294 if (!Namespace.empty())
1295 EnumName += (NormalizeNameForSpellingComparison(Namespace).str() +
1297 EnumName += NormalizeNameForSpellingComparison(Spelling);
1299 // Even if the name is not unique, this spelling index corresponds to a
1300 // particular enumerant name that we've calculated.
1301 Map[Idx] = EnumName;
1303 // Since we have been stripping underscores to avoid trampling on the
1304 // reserved namespace, we may have inadvertently created duplicate
1305 // enumerant names. These duplicates are not considered part of the
1306 // semantic spelling, and can be elided.
1307 if (Uniques.find(EnumName) != Uniques.end())
1310 Uniques.insert(EnumName);
1311 if (I != Spellings.begin())
1313 // Duplicate spellings are not considered part of the semantic spelling
1314 // enumeration, but the spelling index and semantic spelling values are
1315 // meant to be equivalent, so we must specify a concrete value for each
1317 Ret += " " + EnumName + " = " + llvm::utostr(Idx);
1323 void WriteSemanticSpellingSwitch(const std::string &VarName,
1324 const SemanticSpellingMap &Map,
1326 OS << " switch (" << VarName << ") {\n default: "
1327 << "llvm_unreachable(\"Unknown spelling list index\");\n";
1328 for (const auto &I : Map)
1329 OS << " case " << I.first << ": return " << I.second << ";\n";
1333 // Emits the LateParsed property for attributes.
1334 static void emitClangAttrLateParsedList(RecordKeeper &Records, raw_ostream &OS) {
1335 OS << "#if defined(CLANG_ATTR_LATE_PARSED_LIST)\n";
1336 std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr");
1338 for (const auto *Attr : Attrs) {
1339 bool LateParsed = Attr->getValueAsBit("LateParsed");
1342 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(*Attr);
1344 // FIXME: Handle non-GNU attributes
1345 for (const auto &I : Spellings) {
1346 if (I.variety() != "GNU")
1348 OS << ".Case(\"" << I.name() << "\", " << LateParsed << ")\n";
1352 OS << "#endif // CLANG_ATTR_LATE_PARSED_LIST\n\n";
1355 /// \brief Emits the first-argument-is-type property for attributes.
1356 static void emitClangAttrTypeArgList(RecordKeeper &Records, raw_ostream &OS) {
1357 OS << "#if defined(CLANG_ATTR_TYPE_ARG_LIST)\n";
1358 std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
1360 for (const auto *Attr : Attrs) {
1361 // Determine whether the first argument is a type.
1362 std::vector<Record *> Args = Attr->getValueAsListOfDefs("Args");
1366 if (Args[0]->getSuperClasses().back()->getName() != "TypeArgument")
1369 // All these spellings take a single type argument.
1370 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(*Attr);
1371 std::set<std::string> Emitted;
1372 for (const auto &S : Spellings) {
1373 if (Emitted.insert(S.name()).second)
1374 OS << ".Case(\"" << S.name() << "\", " << "true" << ")\n";
1377 OS << "#endif // CLANG_ATTR_TYPE_ARG_LIST\n\n";
1380 /// \brief Emits the parse-arguments-in-unevaluated-context property for
1382 static void emitClangAttrArgContextList(RecordKeeper &Records, raw_ostream &OS) {
1383 OS << "#if defined(CLANG_ATTR_ARG_CONTEXT_LIST)\n";
1384 ParsedAttrMap Attrs = getParsedAttrList(Records);
1385 for (const auto &I : Attrs) {
1386 const Record &Attr = *I.second;
1388 if (!Attr.getValueAsBit("ParseArgumentsAsUnevaluated"))
1391 // All these spellings take are parsed unevaluated.
1392 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(Attr);
1393 std::set<std::string> Emitted;
1394 for (const auto &S : Spellings) {
1395 if (Emitted.insert(S.name()).second)
1396 OS << ".Case(\"" << S.name() << "\", " << "true" << ")\n";
1399 OS << "#endif // CLANG_ATTR_ARG_CONTEXT_LIST\n\n";
1402 static bool isIdentifierArgument(Record *Arg) {
1403 return !Arg->getSuperClasses().empty() &&
1404 llvm::StringSwitch<bool>(Arg->getSuperClasses().back()->getName())
1405 .Case("IdentifierArgument", true)
1406 .Case("EnumArgument", true)
1407 .Case("VariadicEnumArgument", true)
1411 // Emits the first-argument-is-identifier property for attributes.
1412 static void emitClangAttrIdentifierArgList(RecordKeeper &Records, raw_ostream &OS) {
1413 OS << "#if defined(CLANG_ATTR_IDENTIFIER_ARG_LIST)\n";
1414 std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr");
1416 for (const auto *Attr : Attrs) {
1417 // Determine whether the first argument is an identifier.
1418 std::vector<Record *> Args = Attr->getValueAsListOfDefs("Args");
1419 if (Args.empty() || !isIdentifierArgument(Args[0]))
1422 // All these spellings take an identifier argument.
1423 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(*Attr);
1424 std::set<std::string> Emitted;
1425 for (const auto &S : Spellings) {
1426 if (Emitted.insert(S.name()).second)
1427 OS << ".Case(\"" << S.name() << "\", " << "true" << ")\n";
1430 OS << "#endif // CLANG_ATTR_IDENTIFIER_ARG_LIST\n\n";
1435 // Emits the class definitions for attributes.
1436 void EmitClangAttrClass(RecordKeeper &Records, raw_ostream &OS) {
1437 emitSourceFileHeader("Attribute classes' definitions", OS);
1439 OS << "#ifndef LLVM_CLANG_ATTR_CLASSES_INC\n";
1440 OS << "#define LLVM_CLANG_ATTR_CLASSES_INC\n\n";
1442 std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr");
1444 for (const auto *Attr : Attrs) {
1445 const Record &R = *Attr;
1447 // FIXME: Currently, documentation is generated as-needed due to the fact
1448 // that there is no way to allow a generated project "reach into" the docs
1449 // directory (for instance, it may be an out-of-tree build). However, we want
1450 // to ensure that every attribute has a Documentation field, and produce an
1451 // error if it has been neglected. Otherwise, the on-demand generation which
1452 // happens server-side will fail. This code is ensuring that functionality,
1453 // even though this Emitter doesn't technically need the documentation.
1454 // When attribute documentation can be generated as part of the build
1455 // itself, this code can be removed.
1456 (void)R.getValueAsListOfDefs("Documentation");
1458 if (!R.getValueAsBit("ASTNode"))
1461 ArrayRef<Record *> Supers = R.getSuperClasses();
1462 assert(!Supers.empty() && "Forgot to specify a superclass for the attr");
1463 std::string SuperName;
1464 for (const auto *Super : llvm::make_range(Supers.rbegin(), Supers.rend())) {
1465 const Record &R = *Super;
1466 if (R.getName() != "TargetSpecificAttr" && SuperName.empty())
1467 SuperName = R.getName();
1470 OS << "class " << R.getName() << "Attr : public " << SuperName << " {\n";
1472 std::vector<Record*> ArgRecords = R.getValueAsListOfDefs("Args");
1473 std::vector<std::unique_ptr<Argument>> Args;
1474 Args.reserve(ArgRecords.size());
1476 for (const auto *ArgRecord : ArgRecords) {
1477 Args.emplace_back(createArgument(*ArgRecord, R.getName()));
1478 Args.back()->writeDeclarations(OS);
1482 OS << "\npublic:\n";
1484 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(R);
1486 // If there are zero or one spellings, all spelling-related functionality
1487 // can be elided. If all of the spellings share the same name, the spelling
1488 // functionality can also be elided.
1489 bool ElideSpelling = (Spellings.size() <= 1) ||
1490 SpellingNamesAreCommon(Spellings);
1492 // This maps spelling index values to semantic Spelling enumerants.
1493 SemanticSpellingMap SemanticToSyntacticMap;
1496 OS << CreateSemanticSpellings(Spellings, SemanticToSyntacticMap);
1498 OS << " static " << R.getName() << "Attr *CreateImplicit(";
1499 OS << "ASTContext &Ctx";
1501 OS << ", Spelling S";
1502 for (auto const &ai : Args) {
1504 ai->writeCtorParameters(OS);
1506 OS << ", SourceRange Loc = SourceRange()";
1508 OS << " " << R.getName() << "Attr *A = new (Ctx) " << R.getName();
1509 OS << "Attr(Loc, Ctx, ";
1510 for (auto const &ai : Args) {
1511 ai->writeImplicitCtorArgs(OS);
1514 OS << (ElideSpelling ? "0" : "S") << ");\n";
1515 OS << " A->setImplicit(true);\n";
1516 OS << " return A;\n }\n\n";
1518 OS << " " << R.getName() << "Attr(SourceRange R, ASTContext &Ctx\n";
1520 bool HasOpt = false;
1521 for (auto const &ai : Args) {
1523 ai->writeCtorParameters(OS);
1525 if (ai->isOptional())
1530 OS << "unsigned SI\n";
1533 OS << " : " << SuperName << "(attr::" << R.getName() << ", R, SI, "
1534 << R.getValueAsBit("LateParsed") << ", "
1535 << R.getValueAsBit("DuplicatesAllowedWhileMerging") << ")\n";
1537 for (auto const &ai : Args) {
1539 ai->writeCtorInitializers(OS);
1545 for (auto const &ai : Args) {
1546 ai->writeCtorBody(OS);
1551 // If there are optional arguments, write out a constructor that elides the
1552 // optional arguments as well.
1554 OS << " " << R.getName() << "Attr(SourceRange R, ASTContext &Ctx\n";
1555 for (auto const &ai : Args) {
1556 if (!ai->isOptional()) {
1558 ai->writeCtorParameters(OS);
1564 OS << "unsigned SI\n";
1567 OS << " : " << SuperName << "(attr::" << R.getName() << ", R, SI, "
1568 << R.getValueAsBit("LateParsed") << ", "
1569 << R.getValueAsBit("DuplicatesAllowedWhileMerging") << ")\n";
1571 for (auto const &ai : Args) {
1573 ai->writeCtorDefaultInitializers(OS);
1579 for (auto const &ai : Args) {
1580 if (!ai->isOptional()) {
1581 ai->writeCtorBody(OS);
1588 OS << " " << R.getName() << "Attr *clone(ASTContext &C) const;\n";
1589 OS << " void printPretty(raw_ostream &OS,\n"
1590 << " const PrintingPolicy &Policy) const;\n";
1591 OS << " const char *getSpelling() const;\n";
1593 if (!ElideSpelling) {
1594 assert(!SemanticToSyntacticMap.empty() && "Empty semantic mapping list");
1595 OS << " Spelling getSemanticSpelling() const {\n";
1596 WriteSemanticSpellingSwitch("SpellingListIndex", SemanticToSyntacticMap,
1601 writeAttrAccessorDefinition(R, OS);
1603 for (auto const &ai : Args) {
1604 ai->writeAccessors(OS);
1607 if (ai->isEnumArg())
1608 static_cast<const EnumArgument *>(ai.get())->writeConversion(OS);
1609 else if (ai->isVariadicEnumArg())
1610 static_cast<const VariadicEnumArgument *>(ai.get())
1611 ->writeConversion(OS);
1614 OS << R.getValueAsString("AdditionalMembers");
1617 OS << " static bool classof(const Attr *A) { return A->getKind() == "
1618 << "attr::" << R.getName() << "; }\n";
1626 // Emits the class method definitions for attributes.
1627 void EmitClangAttrImpl(RecordKeeper &Records, raw_ostream &OS) {
1628 emitSourceFileHeader("Attribute classes' member function definitions", OS);
1630 std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr");
1632 for (auto *Attr : Attrs) {
1635 if (!R.getValueAsBit("ASTNode"))
1638 std::vector<Record*> ArgRecords = R.getValueAsListOfDefs("Args");
1639 std::vector<std::unique_ptr<Argument>> Args;
1640 for (const auto *Arg : ArgRecords)
1641 Args.emplace_back(createArgument(*Arg, R.getName()));
1643 for (auto const &ai : Args)
1644 ai->writeAccessorDefinitions(OS);
1646 OS << R.getName() << "Attr *" << R.getName()
1647 << "Attr::clone(ASTContext &C) const {\n";
1648 OS << " auto *A = new (C) " << R.getName() << "Attr(getLocation(), C";
1649 for (auto const &ai : Args) {
1651 ai->writeCloneArgs(OS);
1653 OS << ", getSpellingListIndex());\n";
1654 OS << " A->Inherited = Inherited;\n";
1655 OS << " A->IsPackExpansion = IsPackExpansion;\n";
1656 OS << " A->Implicit = Implicit;\n";
1657 OS << " return A;\n}\n\n";
1659 writePrettyPrintFunction(R, Args, OS);
1660 writeGetSpellingFunction(R, OS);
1663 // Instead of relying on virtual dispatch we just create a huge dispatch
1664 // switch. This is both smaller and faster than virtual functions.
1665 auto EmitFunc = [&](const char *Method) {
1666 OS << " switch (getKind()) {\n";
1667 for (const auto *Attr : Attrs) {
1668 const Record &R = *Attr;
1669 if (!R.getValueAsBit("ASTNode"))
1672 OS << " case attr::" << R.getName() << ":\n";
1673 OS << " return cast<" << R.getName() << "Attr>(this)->" << Method
1676 OS << " case attr::NUM_ATTRS:\n";
1679 OS << " llvm_unreachable(\"Unexpected attribute kind!\");\n";
1683 OS << "const char *Attr::getSpelling() const {\n";
1684 EmitFunc("getSpelling()");
1686 OS << "Attr *Attr::clone(ASTContext &C) const {\n";
1687 EmitFunc("clone(C)");
1689 OS << "void Attr::printPretty(raw_ostream &OS, "
1690 "const PrintingPolicy &Policy) const {\n";
1691 EmitFunc("printPretty(OS, Policy)");
1694 } // end namespace clang
1696 static void EmitAttrList(raw_ostream &OS, StringRef Class,
1697 const std::vector<Record*> &AttrList) {
1698 std::vector<Record*>::const_iterator i = AttrList.begin(), e = AttrList.end();
1701 // Move the end iterator back to emit the last attribute.
1702 for(--e; i != e; ++i) {
1703 if (!(*i)->getValueAsBit("ASTNode"))
1706 OS << Class << "(" << (*i)->getName() << ")\n";
1709 OS << "LAST_" << Class << "(" << (*i)->getName() << ")\n\n";
1713 // Determines if an attribute has a Pragma spelling.
1714 static bool AttrHasPragmaSpelling(const Record *R) {
1715 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(*R);
1716 return std::find_if(Spellings.begin(), Spellings.end(),
1717 [](const FlattenedSpelling &S) {
1718 return S.variety() == "Pragma";
1719 }) != Spellings.end();
1723 // Emits the enumeration list for attributes.
1724 void EmitClangAttrList(RecordKeeper &Records, raw_ostream &OS) {
1725 emitSourceFileHeader("List of all attributes that Clang recognizes", OS);
1727 OS << "#ifndef LAST_ATTR\n";
1728 OS << "#define LAST_ATTR(NAME) ATTR(NAME)\n";
1731 OS << "#ifndef INHERITABLE_ATTR\n";
1732 OS << "#define INHERITABLE_ATTR(NAME) ATTR(NAME)\n";
1735 OS << "#ifndef LAST_INHERITABLE_ATTR\n";
1736 OS << "#define LAST_INHERITABLE_ATTR(NAME) INHERITABLE_ATTR(NAME)\n";
1739 OS << "#ifndef INHERITABLE_PARAM_ATTR\n";
1740 OS << "#define INHERITABLE_PARAM_ATTR(NAME) ATTR(NAME)\n";
1743 OS << "#ifndef LAST_INHERITABLE_PARAM_ATTR\n";
1744 OS << "#define LAST_INHERITABLE_PARAM_ATTR(NAME)"
1745 " INHERITABLE_PARAM_ATTR(NAME)\n";
1748 OS << "#ifndef PRAGMA_SPELLING_ATTR\n";
1749 OS << "#define PRAGMA_SPELLING_ATTR(NAME)\n";
1752 OS << "#ifndef LAST_PRAGMA_SPELLING_ATTR\n";
1753 OS << "#define LAST_PRAGMA_SPELLING_ATTR(NAME) PRAGMA_SPELLING_ATTR(NAME)\n";
1756 Record *InhClass = Records.getClass("InheritableAttr");
1757 Record *InhParamClass = Records.getClass("InheritableParamAttr");
1758 std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr"),
1759 NonInhAttrs, InhAttrs, InhParamAttrs, PragmaAttrs;
1760 for (auto *Attr : Attrs) {
1761 if (!Attr->getValueAsBit("ASTNode"))
1764 if (AttrHasPragmaSpelling(Attr))
1765 PragmaAttrs.push_back(Attr);
1767 if (Attr->isSubClassOf(InhParamClass))
1768 InhParamAttrs.push_back(Attr);
1769 else if (Attr->isSubClassOf(InhClass))
1770 InhAttrs.push_back(Attr);
1772 NonInhAttrs.push_back(Attr);
1775 EmitAttrList(OS, "PRAGMA_SPELLING_ATTR", PragmaAttrs);
1776 EmitAttrList(OS, "INHERITABLE_PARAM_ATTR", InhParamAttrs);
1777 EmitAttrList(OS, "INHERITABLE_ATTR", InhAttrs);
1778 EmitAttrList(OS, "ATTR", NonInhAttrs);
1780 OS << "#undef LAST_ATTR\n";
1781 OS << "#undef INHERITABLE_ATTR\n";
1782 OS << "#undef LAST_INHERITABLE_ATTR\n";
1783 OS << "#undef LAST_INHERITABLE_PARAM_ATTR\n";
1784 OS << "#undef LAST_PRAGMA_ATTR\n";
1785 OS << "#undef PRAGMA_SPELLING_ATTR\n";
1786 OS << "#undef ATTR\n";
1789 // Emits the code to read an attribute from a precompiled header.
1790 void EmitClangAttrPCHRead(RecordKeeper &Records, raw_ostream &OS) {
1791 emitSourceFileHeader("Attribute deserialization code", OS);
1793 Record *InhClass = Records.getClass("InheritableAttr");
1794 std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr"),
1796 std::vector<std::unique_ptr<Argument>> Args;
1798 OS << " switch (Kind) {\n";
1799 OS << " default:\n";
1800 OS << " llvm_unreachable(\"Unknown attribute!\");\n";
1801 for (const auto *Attr : Attrs) {
1802 const Record &R = *Attr;
1803 if (!R.getValueAsBit("ASTNode"))
1806 OS << " case attr::" << R.getName() << ": {\n";
1807 if (R.isSubClassOf(InhClass))
1808 OS << " bool isInherited = Record[Idx++];\n";
1809 OS << " bool isImplicit = Record[Idx++];\n";
1810 OS << " unsigned Spelling = Record[Idx++];\n";
1811 ArgRecords = R.getValueAsListOfDefs("Args");
1813 for (const auto *Arg : ArgRecords) {
1814 Args.emplace_back(createArgument(*Arg, R.getName()));
1815 Args.back()->writePCHReadDecls(OS);
1817 OS << " New = new (Context) " << R.getName() << "Attr(Range, Context";
1818 for (auto const &ri : Args) {
1820 ri->writePCHReadArgs(OS);
1822 OS << ", Spelling);\n";
1823 if (R.isSubClassOf(InhClass))
1824 OS << " cast<InheritableAttr>(New)->setInherited(isInherited);\n";
1825 OS << " New->setImplicit(isImplicit);\n";
1832 // Emits the code to write an attribute to a precompiled header.
1833 void EmitClangAttrPCHWrite(RecordKeeper &Records, raw_ostream &OS) {
1834 emitSourceFileHeader("Attribute serialization code", OS);
1836 Record *InhClass = Records.getClass("InheritableAttr");
1837 std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr"), Args;
1839 OS << " switch (A->getKind()) {\n";
1840 OS << " default:\n";
1841 OS << " llvm_unreachable(\"Unknown attribute kind!\");\n";
1843 for (const auto *Attr : Attrs) {
1844 const Record &R = *Attr;
1845 if (!R.getValueAsBit("ASTNode"))
1847 OS << " case attr::" << R.getName() << ": {\n";
1848 Args = R.getValueAsListOfDefs("Args");
1849 if (R.isSubClassOf(InhClass) || !Args.empty())
1850 OS << " const " << R.getName() << "Attr *SA = cast<" << R.getName()
1852 if (R.isSubClassOf(InhClass))
1853 OS << " Record.push_back(SA->isInherited());\n";
1854 OS << " Record.push_back(A->isImplicit());\n";
1855 OS << " Record.push_back(A->getSpellingListIndex());\n";
1857 for (const auto *Arg : Args)
1858 createArgument(*Arg, R.getName())->writePCHWrite(OS);
1865 static void GenerateHasAttrSpellingStringSwitch(
1866 const std::vector<Record *> &Attrs, raw_ostream &OS,
1867 const std::string &Variety = "", const std::string &Scope = "") {
1868 for (const auto *Attr : Attrs) {
1869 // C++11-style attributes have specific version information associated with
1870 // them. If the attribute has no scope, the version information must not
1871 // have the default value (1), as that's incorrect. Instead, the unscoped
1872 // attribute version information should be taken from the SD-6 standing
1873 // document, which can be found at:
1874 // https://isocpp.org/std/standing-documents/sd-6-sg10-feature-test-recommendations
1877 if (Variety == "CXX11") {
1878 std::vector<Record *> Spellings = Attr->getValueAsListOfDefs("Spellings");
1879 for (const auto &Spelling : Spellings) {
1880 if (Spelling->getValueAsString("Variety") == "CXX11") {
1881 Version = static_cast<int>(Spelling->getValueAsInt("Version"));
1882 if (Scope.empty() && Version == 1)
1883 PrintError(Spelling->getLoc(), "C++ standard attributes must "
1884 "have valid version information.");
1890 // It is assumed that there will be an llvm::Triple object named T within
1891 // scope that can be used to determine whether the attribute exists in
1894 if (Attr->isSubClassOf("TargetSpecificAttr")) {
1895 const Record *R = Attr->getValueAsDef("Target");
1896 std::vector<std::string> Arches = R->getValueAsListOfStrings("Arches");
1899 for (auto AI = Arches.begin(), AE = Arches.end(); AI != AE; ++AI) {
1900 std::string Part = *AI;
1901 Test += "T.getArch() == llvm::Triple::" + Part;
1907 std::vector<std::string> OSes;
1908 if (!R->isValueUnset("OSes")) {
1910 std::vector<std::string> OSes = R->getValueAsListOfStrings("OSes");
1911 for (auto AI = OSes.begin(), AE = OSes.end(); AI != AE; ++AI) {
1912 std::string Part = *AI;
1914 Test += "T.getOS() == llvm::Triple::" + Part;
1921 // If this is the C++11 variety, also add in the LangOpts test.
1922 if (Variety == "CXX11")
1923 Test += " && LangOpts.CPlusPlus11";
1924 } else if (Variety == "CXX11")
1925 // C++11 mode should be checked against LangOpts, which is presumed to be
1926 // present in the caller.
1927 Test = "LangOpts.CPlusPlus11";
1929 std::string TestStr =
1930 !Test.empty() ? Test + " ? " + llvm::itostr(Version) + " : 0" : "1";
1931 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(*Attr);
1932 for (const auto &S : Spellings)
1933 if (Variety.empty() || (Variety == S.variety() &&
1934 (Scope.empty() || Scope == S.nameSpace())))
1935 OS << " .Case(\"" << S.name() << "\", " << TestStr << ")\n";
1937 OS << " .Default(0);\n";
1940 // Emits the list of spellings for attributes.
1941 void EmitClangAttrHasAttrImpl(RecordKeeper &Records, raw_ostream &OS) {
1942 emitSourceFileHeader("Code to implement the __has_attribute logic", OS);
1944 // Separate all of the attributes out into four group: generic, C++11, GNU,
1945 // and declspecs. Then generate a big switch statement for each of them.
1946 std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
1947 std::vector<Record *> Declspec, GNU, Pragma;
1948 std::map<std::string, std::vector<Record *>> CXX;
1950 // Walk over the list of all attributes, and split them out based on the
1951 // spelling variety.
1952 for (auto *R : Attrs) {
1953 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(*R);
1954 for (const auto &SI : Spellings) {
1955 std::string Variety = SI.variety();
1956 if (Variety == "GNU")
1958 else if (Variety == "Declspec")
1959 Declspec.push_back(R);
1960 else if (Variety == "CXX11")
1961 CXX[SI.nameSpace()].push_back(R);
1962 else if (Variety == "Pragma")
1963 Pragma.push_back(R);
1967 OS << "switch (Syntax) {\n";
1968 OS << "case AttrSyntax::GNU:\n";
1969 OS << " return llvm::StringSwitch<int>(Name)\n";
1970 GenerateHasAttrSpellingStringSwitch(GNU, OS, "GNU");
1971 OS << "case AttrSyntax::Declspec:\n";
1972 OS << " return llvm::StringSwitch<int>(Name)\n";
1973 GenerateHasAttrSpellingStringSwitch(Declspec, OS, "Declspec");
1974 OS << "case AttrSyntax::Pragma:\n";
1975 OS << " return llvm::StringSwitch<int>(Name)\n";
1976 GenerateHasAttrSpellingStringSwitch(Pragma, OS, "Pragma");
1977 OS << "case AttrSyntax::CXX: {\n";
1978 // C++11-style attributes are further split out based on the Scope.
1979 for (std::map<std::string, std::vector<Record *>>::iterator I = CXX.begin(),
1982 if (I != CXX.begin())
1984 if (I->first.empty())
1985 OS << "if (!Scope || Scope->getName() == \"\") {\n";
1987 OS << "if (Scope->getName() == \"" << I->first << "\") {\n";
1988 OS << " return llvm::StringSwitch<int>(Name)\n";
1989 GenerateHasAttrSpellingStringSwitch(I->second, OS, "CXX11", I->first);
1996 void EmitClangAttrSpellingListIndex(RecordKeeper &Records, raw_ostream &OS) {
1997 emitSourceFileHeader("Code to translate different attribute spellings "
1998 "into internal identifiers", OS);
2001 " switch (AttrKind) {\n"
2003 " llvm_unreachable(\"Unknown attribute kind!\");\n"
2006 ParsedAttrMap Attrs = getParsedAttrList(Records);
2007 for (const auto &I : Attrs) {
2008 const Record &R = *I.second;
2009 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(R);
2010 OS << " case AT_" << I.first << ": {\n";
2011 for (unsigned I = 0; I < Spellings.size(); ++ I) {
2012 OS << " if (Name == \"" << Spellings[I].name() << "\" && "
2014 << StringSwitch<unsigned>(Spellings[I].variety())
2017 .Case("Declspec", 2)
2021 << " && Scope == \"" << Spellings[I].nameSpace() << "\")\n"
2022 << " return " << I << ";\n";
2030 OS << " return 0;\n";
2033 // Emits code used by RecursiveASTVisitor to visit attributes
2034 void EmitClangAttrASTVisitor(RecordKeeper &Records, raw_ostream &OS) {
2035 emitSourceFileHeader("Used by RecursiveASTVisitor to visit attributes.", OS);
2037 std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr");
2039 // Write method declarations for Traverse* methods.
2040 // We emit this here because we only generate methods for attributes that
2041 // are declared as ASTNodes.
2042 OS << "#ifdef ATTR_VISITOR_DECLS_ONLY\n\n";
2043 for (const auto *Attr : Attrs) {
2044 const Record &R = *Attr;
2045 if (!R.getValueAsBit("ASTNode"))
2047 OS << " bool Traverse"
2048 << R.getName() << "Attr(" << R.getName() << "Attr *A);\n";
2050 << R.getName() << "Attr(" << R.getName() << "Attr *A) {\n"
2051 << " return true; \n"
2054 OS << "\n#else // ATTR_VISITOR_DECLS_ONLY\n\n";
2056 // Write individual Traverse* methods for each attribute class.
2057 for (const auto *Attr : Attrs) {
2058 const Record &R = *Attr;
2059 if (!R.getValueAsBit("ASTNode"))
2062 OS << "template <typename Derived>\n"
2063 << "bool VISITORCLASS<Derived>::Traverse"
2064 << R.getName() << "Attr(" << R.getName() << "Attr *A) {\n"
2065 << " if (!getDerived().VisitAttr(A))\n"
2066 << " return false;\n"
2067 << " if (!getDerived().Visit" << R.getName() << "Attr(A))\n"
2068 << " return false;\n";
2070 std::vector<Record*> ArgRecords = R.getValueAsListOfDefs("Args");
2071 for (const auto *Arg : ArgRecords)
2072 createArgument(*Arg, R.getName())->writeASTVisitorTraversal(OS);
2074 OS << " return true;\n";
2078 // Write generic Traverse routine
2079 OS << "template <typename Derived>\n"
2080 << "bool VISITORCLASS<Derived>::TraverseAttr(Attr *A) {\n"
2082 << " return true;\n"
2084 << " switch (A->getKind()) {\n"
2086 << " return true;\n";
2088 for (const auto *Attr : Attrs) {
2089 const Record &R = *Attr;
2090 if (!R.getValueAsBit("ASTNode"))
2093 OS << " case attr::" << R.getName() << ":\n"
2094 << " return getDerived().Traverse" << R.getName() << "Attr("
2095 << "cast<" << R.getName() << "Attr>(A));\n";
2097 OS << " }\n"; // end case
2098 OS << "}\n"; // end function
2099 OS << "#endif // ATTR_VISITOR_DECLS_ONLY\n";
2102 // Emits code to instantiate dependent attributes on templates.
2103 void EmitClangAttrTemplateInstantiate(RecordKeeper &Records, raw_ostream &OS) {
2104 emitSourceFileHeader("Template instantiation code for attributes", OS);
2106 std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr");
2108 OS << "namespace clang {\n"
2109 << "namespace sema {\n\n"
2110 << "Attr *instantiateTemplateAttribute(const Attr *At, ASTContext &C, "
2112 << " const MultiLevelTemplateArgumentList &TemplateArgs) {\n"
2113 << " switch (At->getKind()) {\n"
2117 for (const auto *Attr : Attrs) {
2118 const Record &R = *Attr;
2119 if (!R.getValueAsBit("ASTNode"))
2122 OS << " case attr::" << R.getName() << ": {\n";
2123 bool ShouldClone = R.getValueAsBit("Clone");
2126 OS << " return NULL;\n";
2131 OS << " const " << R.getName() << "Attr *A = cast<"
2132 << R.getName() << "Attr>(At);\n";
2133 bool TDependent = R.getValueAsBit("TemplateDependent");
2136 OS << " return A->clone(C);\n";
2141 std::vector<Record*> ArgRecords = R.getValueAsListOfDefs("Args");
2142 std::vector<std::unique_ptr<Argument>> Args;
2143 Args.reserve(ArgRecords.size());
2145 for (const auto *ArgRecord : ArgRecords)
2146 Args.emplace_back(createArgument(*ArgRecord, R.getName()));
2148 for (auto const &ai : Args)
2149 ai->writeTemplateInstantiation(OS);
2151 OS << " return new (C) " << R.getName() << "Attr(A->getLocation(), C";
2152 for (auto const &ai : Args) {
2154 ai->writeTemplateInstantiationArgs(OS);
2156 OS << ", A->getSpellingListIndex());\n }\n";
2158 OS << " } // end switch\n"
2159 << " llvm_unreachable(\"Unknown attribute!\");\n"
2162 << "} // end namespace sema\n"
2163 << "} // end namespace clang\n";
2166 // Emits the list of parsed attributes.
2167 void EmitClangAttrParsedAttrList(RecordKeeper &Records, raw_ostream &OS) {
2168 emitSourceFileHeader("List of all attributes that Clang recognizes", OS);
2170 OS << "#ifndef PARSED_ATTR\n";
2171 OS << "#define PARSED_ATTR(NAME) NAME\n";
2174 ParsedAttrMap Names = getParsedAttrList(Records);
2175 for (const auto &I : Names) {
2176 OS << "PARSED_ATTR(" << I.first << ")\n";
2180 static bool isArgVariadic(const Record &R, StringRef AttrName) {
2181 return createArgument(R, AttrName)->isVariadic();
2184 static void emitArgInfo(const Record &R, std::stringstream &OS) {
2185 // This function will count the number of arguments specified for the
2186 // attribute and emit the number of required arguments followed by the
2187 // number of optional arguments.
2188 std::vector<Record *> Args = R.getValueAsListOfDefs("Args");
2189 unsigned ArgCount = 0, OptCount = 0;
2190 bool HasVariadic = false;
2191 for (const auto *Arg : Args) {
2192 Arg->getValueAsBit("Optional") ? ++OptCount : ++ArgCount;
2193 if (!HasVariadic && isArgVariadic(*Arg, R.getName()))
2197 // If there is a variadic argument, we will set the optional argument count
2198 // to its largest value. Since it's currently a 4-bit number, we set it to 15.
2199 OS << ArgCount << ", " << (HasVariadic ? 15 : OptCount);
2202 static void GenerateDefaultAppertainsTo(raw_ostream &OS) {
2203 OS << "static bool defaultAppertainsTo(Sema &, const AttributeList &,";
2204 OS << "const Decl *) {\n";
2205 OS << " return true;\n";
2209 static std::string CalculateDiagnostic(const Record &S) {
2210 // If the SubjectList object has a custom diagnostic associated with it,
2211 // return that directly.
2212 std::string CustomDiag = S.getValueAsString("CustomDiag");
2213 if (!CustomDiag.empty())
2216 // Given the list of subjects, determine what diagnostic best fits.
2220 ObjCMethod = 1U << 2,
2223 GenericRecord = 1U << 5,
2227 ObjCInterface = 1U << 9,
2229 Namespace = 1U << 11,
2231 CXXMethod = 1U << 13,
2232 ObjCProtocol = 1U << 14,
2235 uint32_t SubMask = 0;
2237 std::vector<Record *> Subjects = S.getValueAsListOfDefs("Subjects");
2238 for (const auto *Subject : Subjects) {
2239 const Record &R = *Subject;
2242 if (R.isSubClassOf("SubsetSubject")) {
2243 PrintError(R.getLoc(), "SubsetSubjects should use a custom diagnostic");
2244 // As a fallback, look through the SubsetSubject to see what its base
2245 // type is, and use that. This needs to be updated if SubsetSubjects
2246 // are allowed within other SubsetSubjects.
2247 Name = R.getValueAsDef("Base")->getName();
2251 uint32_t V = StringSwitch<uint32_t>(Name)
2252 .Case("Function", Func)
2254 .Case("ObjCMethod", ObjCMethod)
2255 .Case("ParmVar", Param)
2256 .Case("TypedefName", Type)
2257 .Case("ObjCIvar", ObjCIVar)
2258 .Case("ObjCProperty", ObjCProp)
2259 .Case("Record", GenericRecord)
2260 .Case("ObjCInterface", ObjCInterface)
2261 .Case("ObjCProtocol", ObjCProtocol)
2262 .Case("Block", Block)
2263 .Case("CXXRecord", Class)
2264 .Case("Namespace", Namespace)
2265 .Case("Field", Field)
2266 .Case("CXXMethod", CXXMethod)
2270 // Something wasn't in our mapping, so be helpful and let the developer
2272 PrintFatalError(R.getLoc(), "Unknown subject type: " + R.getName());
2280 // For the simple cases where there's only a single entry in the mask, we
2281 // don't have to resort to bit fiddling.
2282 case Func: return "ExpectedFunction";
2283 case Var: return "ExpectedVariable";
2284 case Param: return "ExpectedParameter";
2285 case Class: return "ExpectedClass";
2286 case Enum: return "ExpectedEnum";
2288 // FIXME: Currently, this maps to ExpectedMethod based on existing code,
2289 // but should map to something a bit more accurate at some point.
2290 case ObjCMethod: return "ExpectedMethod";
2291 case Type: return "ExpectedType";
2292 case ObjCInterface: return "ExpectedObjectiveCInterface";
2293 case ObjCProtocol: return "ExpectedObjectiveCProtocol";
2295 // "GenericRecord" means struct, union or class; check the language options
2296 // and if not compiling for C++, strip off the class part. Note that this
2297 // relies on the fact that the context for this declares "Sema &S".
2299 return "(S.getLangOpts().CPlusPlus ? ExpectedStructOrUnionOrClass : "
2300 "ExpectedStructOrUnion)";
2301 case Func | ObjCMethod | Block: return "ExpectedFunctionMethodOrBlock";
2302 case Func | ObjCMethod | Class: return "ExpectedFunctionMethodOrClass";
2304 case Func | ObjCMethod | Param: return "ExpectedFunctionMethodOrParameter";
2305 case Func | ObjCMethod: return "ExpectedFunctionOrMethod";
2306 case Func | Var: return "ExpectedVariableOrFunction";
2308 // If not compiling for C++, the class portion does not apply.
2309 case Func | Var | Class:
2310 return "(S.getLangOpts().CPlusPlus ? ExpectedFunctionVariableOrClass : "
2311 "ExpectedVariableOrFunction)";
2313 case ObjCMethod | ObjCProp: return "ExpectedMethodOrProperty";
2314 case ObjCProtocol | ObjCInterface:
2315 return "ExpectedObjectiveCInterfaceOrProtocol";
2316 case Field | Var: return "ExpectedFieldOrGlobalVar";
2319 PrintFatalError(S.getLoc(),
2320 "Could not deduce diagnostic argument for Attr subjects");
2325 static std::string GetSubjectWithSuffix(const Record *R) {
2326 std::string B = R->getName();
2327 if (B == "DeclBase")
2331 static std::string GenerateCustomAppertainsTo(const Record &Subject,
2333 std::string FnName = "is" + Subject.getName();
2335 // If this code has already been generated, simply return the previous
2337 static std::set<std::string> CustomSubjectSet;
2338 std::set<std::string>::iterator I = CustomSubjectSet.find(FnName);
2339 if (I != CustomSubjectSet.end())
2342 Record *Base = Subject.getValueAsDef("Base");
2344 // Not currently support custom subjects within custom subjects.
2345 if (Base->isSubClassOf("SubsetSubject")) {
2346 PrintFatalError(Subject.getLoc(),
2347 "SubsetSubjects within SubsetSubjects is not supported");
2351 OS << "static bool " << FnName << "(const Decl *D) {\n";
2352 OS << " if (const " << GetSubjectWithSuffix(Base) << " *S = dyn_cast<";
2353 OS << GetSubjectWithSuffix(Base);
2355 OS << " return " << Subject.getValueAsString("CheckCode") << ";\n";
2356 OS << " return false;\n";
2359 CustomSubjectSet.insert(FnName);
2363 static std::string GenerateAppertainsTo(const Record &Attr, raw_ostream &OS) {
2364 // If the attribute does not contain a Subjects definition, then use the
2365 // default appertainsTo logic.
2366 if (Attr.isValueUnset("Subjects"))
2367 return "defaultAppertainsTo";
2369 const Record *SubjectObj = Attr.getValueAsDef("Subjects");
2370 std::vector<Record*> Subjects = SubjectObj->getValueAsListOfDefs("Subjects");
2372 // If the list of subjects is empty, it is assumed that the attribute
2373 // appertains to everything.
2374 if (Subjects.empty())
2375 return "defaultAppertainsTo";
2377 bool Warn = SubjectObj->getValueAsDef("Diag")->getValueAsBit("Warn");
2379 // Otherwise, generate an appertainsTo check specific to this attribute which
2380 // checks all of the given subjects against the Decl passed in. Return the
2381 // name of that check to the caller.
2382 std::string FnName = "check" + Attr.getName() + "AppertainsTo";
2383 std::stringstream SS;
2384 SS << "static bool " << FnName << "(Sema &S, const AttributeList &Attr, ";
2385 SS << "const Decl *D) {\n";
2387 for (auto I = Subjects.begin(), E = Subjects.end(); I != E; ++I) {
2388 // If the subject has custom code associated with it, generate a function
2389 // for it. The function cannot be inlined into this check (yet) because it
2390 // requires the subject to be of a specific type, and were that information
2391 // inlined here, it would not support an attribute with multiple custom
2393 if ((*I)->isSubClassOf("SubsetSubject")) {
2394 SS << "!" << GenerateCustomAppertainsTo(**I, OS) << "(D)";
2396 SS << "!isa<" << GetSubjectWithSuffix(*I) << ">(D)";
2403 SS << " S.Diag(Attr.getLoc(), diag::";
2404 SS << (Warn ? "warn_attribute_wrong_decl_type" :
2405 "err_attribute_wrong_decl_type");
2407 SS << " << Attr.getName() << ";
2408 SS << CalculateDiagnostic(*SubjectObj) << ";\n";
2409 SS << " return false;\n";
2411 SS << " return true;\n";
2418 static void GenerateDefaultLangOptRequirements(raw_ostream &OS) {
2419 OS << "static bool defaultDiagnoseLangOpts(Sema &, ";
2420 OS << "const AttributeList &) {\n";
2421 OS << " return true;\n";
2425 static std::string GenerateLangOptRequirements(const Record &R,
2427 // If the attribute has an empty or unset list of language requirements,
2428 // return the default handler.
2429 std::vector<Record *> LangOpts = R.getValueAsListOfDefs("LangOpts");
2430 if (LangOpts.empty())
2431 return "defaultDiagnoseLangOpts";
2433 // Generate the test condition, as well as a unique function name for the
2434 // diagnostic test. The list of options should usually be short (one or two
2435 // options), and the uniqueness isn't strictly necessary (it is just for
2436 // codegen efficiency).
2437 std::string FnName = "check", Test;
2438 for (auto I = LangOpts.begin(), E = LangOpts.end(); I != E; ++I) {
2439 std::string Part = (*I)->getValueAsString("Name");
2440 if ((*I)->getValueAsBit("Negated"))
2442 Test += "S.LangOpts." + Part;
2447 FnName += "LangOpts";
2449 // If this code has already been generated, simply return the previous
2451 static std::set<std::string> CustomLangOptsSet;
2452 std::set<std::string>::iterator I = CustomLangOptsSet.find(FnName);
2453 if (I != CustomLangOptsSet.end())
2456 OS << "static bool " << FnName << "(Sema &S, const AttributeList &Attr) {\n";
2457 OS << " if (" << Test << ")\n";
2458 OS << " return true;\n\n";
2459 OS << " S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) ";
2460 OS << "<< Attr.getName();\n";
2461 OS << " return false;\n";
2464 CustomLangOptsSet.insert(FnName);
2468 static void GenerateDefaultTargetRequirements(raw_ostream &OS) {
2469 OS << "static bool defaultTargetRequirements(const llvm::Triple &) {\n";
2470 OS << " return true;\n";
2474 static std::string GenerateTargetRequirements(const Record &Attr,
2475 const ParsedAttrMap &Dupes,
2477 // If the attribute is not a target specific attribute, return the default
2479 if (!Attr.isSubClassOf("TargetSpecificAttr"))
2480 return "defaultTargetRequirements";
2482 // Get the list of architectures to be tested for.
2483 const Record *R = Attr.getValueAsDef("Target");
2484 std::vector<std::string> Arches = R->getValueAsListOfStrings("Arches");
2485 if (Arches.empty()) {
2486 PrintError(Attr.getLoc(), "Empty list of target architectures for a "
2487 "target-specific attr");
2488 return "defaultTargetRequirements";
2491 // If there are other attributes which share the same parsed attribute kind,
2492 // such as target-specific attributes with a shared spelling, collapse the
2493 // duplicate architectures. This is required because a shared target-specific
2494 // attribute has only one AttributeList::Kind enumeration value, but it
2495 // applies to multiple target architectures. In order for the attribute to be
2496 // considered valid, all of its architectures need to be included.
2497 if (!Attr.isValueUnset("ParseKind")) {
2498 std::string APK = Attr.getValueAsString("ParseKind");
2499 for (const auto &I : Dupes) {
2500 if (I.first == APK) {
2501 std::vector<std::string> DA = I.second->getValueAsDef("Target")
2502 ->getValueAsListOfStrings("Arches");
2503 std::copy(DA.begin(), DA.end(), std::back_inserter(Arches));
2508 std::string FnName = "isTarget", Test = "(";
2509 for (auto I = Arches.begin(), E = Arches.end(); I != E; ++I) {
2510 std::string Part = *I;
2511 Test += "Arch == llvm::Triple::" + Part;
2518 // If the target also requires OS testing, generate those tests as well.
2519 bool UsesOS = false;
2520 if (!R->isValueUnset("OSes")) {
2523 // We know that there was at least one arch test, so we need to and in the
2526 std::vector<std::string> OSes = R->getValueAsListOfStrings("OSes");
2527 for (auto I = OSes.begin(), E = OSes.end(); I != E; ++I) {
2528 std::string Part = *I;
2530 Test += "OS == llvm::Triple::" + Part;
2538 // If this code has already been generated, simply return the previous
2540 static std::set<std::string> CustomTargetSet;
2541 std::set<std::string>::iterator I = CustomTargetSet.find(FnName);
2542 if (I != CustomTargetSet.end())
2545 OS << "static bool " << FnName << "(const llvm::Triple &T) {\n";
2546 OS << " llvm::Triple::ArchType Arch = T.getArch();\n";
2548 OS << " llvm::Triple::OSType OS = T.getOS();\n";
2549 OS << " return " << Test << ";\n";
2552 CustomTargetSet.insert(FnName);
2556 static void GenerateDefaultSpellingIndexToSemanticSpelling(raw_ostream &OS) {
2557 OS << "static unsigned defaultSpellingIndexToSemanticSpelling("
2558 << "const AttributeList &Attr) {\n";
2559 OS << " return UINT_MAX;\n";
2563 static std::string GenerateSpellingIndexToSemanticSpelling(const Record &Attr,
2565 // If the attribute does not have a semantic form, we can bail out early.
2566 if (!Attr.getValueAsBit("ASTNode"))
2567 return "defaultSpellingIndexToSemanticSpelling";
2569 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(Attr);
2571 // If there are zero or one spellings, or all of the spellings share the same
2572 // name, we can also bail out early.
2573 if (Spellings.size() <= 1 || SpellingNamesAreCommon(Spellings))
2574 return "defaultSpellingIndexToSemanticSpelling";
2576 // Generate the enumeration we will use for the mapping.
2577 SemanticSpellingMap SemanticToSyntacticMap;
2578 std::string Enum = CreateSemanticSpellings(Spellings, SemanticToSyntacticMap);
2579 std::string Name = Attr.getName() + "AttrSpellingMap";
2581 OS << "static unsigned " << Name << "(const AttributeList &Attr) {\n";
2583 OS << " unsigned Idx = Attr.getAttributeSpellingListIndex();\n";
2584 WriteSemanticSpellingSwitch("Idx", SemanticToSyntacticMap, OS);
2590 static bool IsKnownToGCC(const Record &Attr) {
2591 // Look at the spellings for this subject; if there are any spellings which
2592 // claim to be known to GCC, the attribute is known to GCC.
2593 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(Attr);
2594 for (const auto &I : Spellings) {
2601 /// Emits the parsed attribute helpers
2602 void EmitClangAttrParsedAttrImpl(RecordKeeper &Records, raw_ostream &OS) {
2603 emitSourceFileHeader("Parsed attribute helpers", OS);
2605 // Get the list of parsed attributes, and accept the optional list of
2606 // duplicates due to the ParseKind.
2607 ParsedAttrMap Dupes;
2608 ParsedAttrMap Attrs = getParsedAttrList(Records, &Dupes);
2610 // Generate the default appertainsTo, target and language option diagnostic,
2611 // and spelling list index mapping methods.
2612 GenerateDefaultAppertainsTo(OS);
2613 GenerateDefaultLangOptRequirements(OS);
2614 GenerateDefaultTargetRequirements(OS);
2615 GenerateDefaultSpellingIndexToSemanticSpelling(OS);
2617 // Generate the appertainsTo diagnostic methods and write their names into
2618 // another mapping. At the same time, generate the AttrInfoMap object
2619 // contents. Due to the reliance on generated code, use separate streams so
2620 // that code will not be interleaved.
2621 std::stringstream SS;
2622 for (auto I = Attrs.begin(), E = Attrs.end(); I != E; ++I) {
2623 // TODO: If the attribute's kind appears in the list of duplicates, that is
2624 // because it is a target-specific attribute that appears multiple times.
2625 // It would be beneficial to test whether the duplicates are "similar
2626 // enough" to each other to not cause problems. For instance, check that
2627 // the spellings are identical, and custom parsing rules match, etc.
2629 // We need to generate struct instances based off ParsedAttrInfo from
2630 // AttributeList.cpp.
2632 emitArgInfo(*I->second, SS);
2633 SS << ", " << I->second->getValueAsBit("HasCustomParsing");
2634 SS << ", " << I->second->isSubClassOf("TargetSpecificAttr");
2635 SS << ", " << I->second->isSubClassOf("TypeAttr");
2636 SS << ", " << IsKnownToGCC(*I->second);
2637 SS << ", " << GenerateAppertainsTo(*I->second, OS);
2638 SS << ", " << GenerateLangOptRequirements(*I->second, OS);
2639 SS << ", " << GenerateTargetRequirements(*I->second, Dupes, OS);
2640 SS << ", " << GenerateSpellingIndexToSemanticSpelling(*I->second, OS);
2646 SS << " // AT_" << I->first << "\n";
2649 OS << "static const ParsedAttrInfo AttrInfoMap[AttributeList::UnknownAttribute + 1] = {\n";
2654 // Emits the kind list of parsed attributes
2655 void EmitClangAttrParsedAttrKinds(RecordKeeper &Records, raw_ostream &OS) {
2656 emitSourceFileHeader("Attribute name matcher", OS);
2658 std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
2659 std::vector<StringMatcher::StringPair> GNU, Declspec, CXX11, Keywords, Pragma;
2660 std::set<std::string> Seen;
2661 for (const auto *A : Attrs) {
2662 const Record &Attr = *A;
2664 bool SemaHandler = Attr.getValueAsBit("SemaHandler");
2665 bool Ignored = Attr.getValueAsBit("Ignored");
2666 if (SemaHandler || Ignored) {
2667 // Attribute spellings can be shared between target-specific attributes,
2668 // and can be shared between syntaxes for the same attribute. For
2669 // instance, an attribute can be spelled GNU<"interrupt"> for an ARM-
2670 // specific attribute, or MSP430-specific attribute. Additionally, an
2671 // attribute can be spelled GNU<"dllexport"> and Declspec<"dllexport">
2672 // for the same semantic attribute. Ultimately, we need to map each of
2673 // these to a single AttributeList::Kind value, but the StringMatcher
2674 // class cannot handle duplicate match strings. So we generate a list of
2675 // string to match based on the syntax, and emit multiple string matchers
2676 // depending on the syntax used.
2677 std::string AttrName;
2678 if (Attr.isSubClassOf("TargetSpecificAttr") &&
2679 !Attr.isValueUnset("ParseKind")) {
2680 AttrName = Attr.getValueAsString("ParseKind");
2681 if (Seen.find(AttrName) != Seen.end())
2683 Seen.insert(AttrName);
2685 AttrName = NormalizeAttrName(StringRef(Attr.getName())).str();
2687 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(Attr);
2688 for (const auto &S : Spellings) {
2689 std::string RawSpelling = S.name();
2690 std::vector<StringMatcher::StringPair> *Matches = nullptr;
2691 std::string Spelling, Variety = S.variety();
2692 if (Variety == "CXX11") {
2694 Spelling += S.nameSpace();
2696 } else if (Variety == "GNU")
2698 else if (Variety == "Declspec")
2699 Matches = &Declspec;
2700 else if (Variety == "Keyword")
2701 Matches = &Keywords;
2702 else if (Variety == "Pragma")
2705 assert(Matches && "Unsupported spelling variety found");
2707 Spelling += NormalizeAttrSpelling(RawSpelling);
2709 Matches->push_back(StringMatcher::StringPair(Spelling,
2710 "return AttributeList::AT_" + AttrName + ";"));
2712 Matches->push_back(StringMatcher::StringPair(Spelling,
2713 "return AttributeList::IgnoredAttribute;"));
2718 OS << "static AttributeList::Kind getAttrKind(StringRef Name, ";
2719 OS << "AttributeList::Syntax Syntax) {\n";
2720 OS << " if (AttributeList::AS_GNU == Syntax) {\n";
2721 StringMatcher("Name", GNU, OS).Emit();
2722 OS << " } else if (AttributeList::AS_Declspec == Syntax) {\n";
2723 StringMatcher("Name", Declspec, OS).Emit();
2724 OS << " } else if (AttributeList::AS_CXX11 == Syntax) {\n";
2725 StringMatcher("Name", CXX11, OS).Emit();
2726 OS << " } else if (AttributeList::AS_Keyword == Syntax || ";
2727 OS << "AttributeList::AS_ContextSensitiveKeyword == Syntax) {\n";
2728 StringMatcher("Name", Keywords, OS).Emit();
2729 OS << " } else if (AttributeList::AS_Pragma == Syntax) {\n";
2730 StringMatcher("Name", Pragma, OS).Emit();
2732 OS << " return AttributeList::UnknownAttribute;\n"
2736 // Emits the code to dump an attribute.
2737 void EmitClangAttrDump(RecordKeeper &Records, raw_ostream &OS) {
2738 emitSourceFileHeader("Attribute dumper", OS);
2741 " switch (A->getKind()) {\n"
2743 " llvm_unreachable(\"Unknown attribute kind!\");\n"
2745 std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr"), Args;
2746 for (const auto *Attr : Attrs) {
2747 const Record &R = *Attr;
2748 if (!R.getValueAsBit("ASTNode"))
2750 OS << " case attr::" << R.getName() << ": {\n";
2752 // If the attribute has a semantically-meaningful name (which is determined
2753 // by whether there is a Spelling enumeration for it), then write out the
2754 // spelling used for the attribute.
2755 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(R);
2756 if (Spellings.size() > 1 && !SpellingNamesAreCommon(Spellings))
2757 OS << " OS << \" \" << A->getSpelling();\n";
2759 Args = R.getValueAsListOfDefs("Args");
2760 if (!Args.empty()) {
2761 OS << " const " << R.getName() << "Attr *SA = cast<" << R.getName()
2763 for (const auto *Arg : Args)
2764 createArgument(*Arg, R.getName())->writeDump(OS);
2766 for (auto AI = Args.begin(), AE = Args.end(); AI != AE; ++AI)
2767 createArgument(**AI, R.getName())->writeDumpChildren(OS);
2776 void EmitClangAttrParserStringSwitches(RecordKeeper &Records,
2778 emitSourceFileHeader("Parser-related llvm::StringSwitch cases", OS);
2779 emitClangAttrArgContextList(Records, OS);
2780 emitClangAttrIdentifierArgList(Records, OS);
2781 emitClangAttrTypeArgList(Records, OS);
2782 emitClangAttrLateParsedList(Records, OS);
2785 class DocumentationData {
2787 const Record *Documentation;
2788 const Record *Attribute;
2790 DocumentationData(const Record &Documentation, const Record &Attribute)
2791 : Documentation(&Documentation), Attribute(&Attribute) {}
2794 static void WriteCategoryHeader(const Record *DocCategory,
2796 const std::string &Name = DocCategory->getValueAsString("Name");
2797 OS << Name << "\n" << std::string(Name.length(), '=') << "\n";
2799 // If there is content, print that as well.
2800 std::string ContentStr = DocCategory->getValueAsString("Content");
2801 // Trim leading and trailing newlines and spaces.
2802 OS << StringRef(ContentStr).trim();
2815 static void WriteDocumentation(const DocumentationData &Doc,
2817 // FIXME: there is no way to have a per-spelling category for the attribute
2818 // documentation. This may not be a limiting factor since the spellings
2819 // should generally be consistently applied across the category.
2821 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(*Doc.Attribute);
2823 // Determine the heading to be used for this attribute.
2824 std::string Heading = Doc.Documentation->getValueAsString("Heading");
2825 bool CustomHeading = !Heading.empty();
2826 if (Heading.empty()) {
2827 // If there's only one spelling, we can simply use that.
2828 if (Spellings.size() == 1)
2829 Heading = Spellings.begin()->name();
2831 std::set<std::string> Uniques;
2832 for (auto I = Spellings.begin(), E = Spellings.end();
2833 I != E && Uniques.size() <= 1; ++I) {
2834 std::string Spelling = NormalizeNameForSpellingComparison(I->name());
2835 Uniques.insert(Spelling);
2837 // If the semantic map has only one spelling, that is sufficient for our
2839 if (Uniques.size() == 1)
2840 Heading = *Uniques.begin();
2844 // If the heading is still empty, it is an error.
2845 if (Heading.empty())
2846 PrintFatalError(Doc.Attribute->getLoc(),
2847 "This attribute requires a heading to be specified");
2849 // Gather a list of unique spellings; this is not the same as the semantic
2850 // spelling for the attribute. Variations in underscores and other non-
2851 // semantic characters are still acceptable.
2852 std::vector<std::string> Names;
2854 unsigned SupportedSpellings = 0;
2855 for (const auto &I : Spellings) {
2856 SpellingKind Kind = StringSwitch<SpellingKind>(I.variety())
2858 .Case("CXX11", CXX11)
2859 .Case("Declspec", Declspec)
2860 .Case("Keyword", Keyword)
2861 .Case("Pragma", Pragma);
2863 // Mask in the supported spelling.
2864 SupportedSpellings |= Kind;
2867 if (Kind == CXX11 && !I.nameSpace().empty())
2868 Name = I.nameSpace() + "::";
2871 // If this name is the same as the heading, do not add it.
2872 if (Name != Heading)
2873 Names.push_back(Name);
2876 // Print out the heading for the attribute. If there are alternate spellings,
2877 // then display those after the heading.
2878 if (!CustomHeading && !Names.empty()) {
2880 for (auto I = Names.begin(), E = Names.end(); I != E; ++I) {
2881 if (I != Names.begin())
2887 OS << Heading << "\n" << std::string(Heading.length(), '-') << "\n";
2889 if (!SupportedSpellings)
2890 PrintFatalError(Doc.Attribute->getLoc(),
2891 "Attribute has no supported spellings; cannot be "
2894 // List what spelling syntaxes the attribute supports.
2895 OS << ".. csv-table:: Supported Syntaxes\n";
2896 OS << " :header: \"GNU\", \"C++11\", \"__declspec\", \"Keyword\",";
2897 OS << " \"Pragma\"\n\n";
2899 if (SupportedSpellings & GNU) OS << "X";
2901 if (SupportedSpellings & CXX11) OS << "X";
2903 if (SupportedSpellings & Declspec) OS << "X";
2905 if (SupportedSpellings & Keyword) OS << "X";
2907 if (SupportedSpellings & Pragma) OS << "X";
2910 // If the attribute is deprecated, print a message about it, and possibly
2911 // provide a replacement attribute.
2912 if (!Doc.Documentation->isValueUnset("Deprecated")) {
2913 OS << "This attribute has been deprecated, and may be removed in a future "
2914 << "version of Clang.";
2915 const Record &Deprecated = *Doc.Documentation->getValueAsDef("Deprecated");
2916 std::string Replacement = Deprecated.getValueAsString("Replacement");
2917 if (!Replacement.empty())
2918 OS << " This attribute has been superseded by ``"
2919 << Replacement << "``.";
2923 std::string ContentStr = Doc.Documentation->getValueAsString("Content");
2924 // Trim leading and trailing newlines and spaces.
2925 OS << StringRef(ContentStr).trim();
2930 void EmitClangAttrDocs(RecordKeeper &Records, raw_ostream &OS) {
2931 // Get the documentation introduction paragraph.
2932 const Record *Documentation = Records.getDef("GlobalDocumentation");
2933 if (!Documentation) {
2934 PrintFatalError("The Documentation top-level definition is missing, "
2935 "no documentation will be generated.");
2939 OS << Documentation->getValueAsString("Intro") << "\n";
2941 // Gather the Documentation lists from each of the attributes, based on the
2942 // category provided.
2943 std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
2944 std::map<const Record *, std::vector<DocumentationData>> SplitDocs;
2945 for (const auto *A : Attrs) {
2946 const Record &Attr = *A;
2947 std::vector<Record *> Docs = Attr.getValueAsListOfDefs("Documentation");
2948 for (const auto *D : Docs) {
2949 const Record &Doc = *D;
2950 const Record *Category = Doc.getValueAsDef("Category");
2951 // If the category is "undocumented", then there cannot be any other
2952 // documentation categories (otherwise, the attribute would become
2954 std::string Cat = Category->getValueAsString("Name");
2955 bool Undocumented = Cat == "Undocumented";
2956 if (Undocumented && Docs.size() > 1)
2957 PrintFatalError(Doc.getLoc(),
2958 "Attribute is \"Undocumented\", but has multiple "
2959 "documentation categories");
2962 SplitDocs[Category].push_back(DocumentationData(Doc, Attr));
2966 // Having split the attributes out based on what documentation goes where,
2967 // we can begin to generate sections of documentation.
2968 for (const auto &I : SplitDocs) {
2969 WriteCategoryHeader(I.first, OS);
2971 // Walk over each of the attributes in the category and write out their
2973 for (const auto &Doc : I.second)
2974 WriteDocumentation(Doc, OS);
2978 } // end namespace clang