1 //===- ClangAttrEmitter.cpp - Generate Clang attribute handling =-*- C++ -*--=//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // These tablegen backends emit Clang attribute processing code
11 //===----------------------------------------------------------------------===//
13 #include "TableGenBackends.h"
14 #include "ASTTableGen.h"
16 #include "llvm/ADT/ArrayRef.h"
17 #include "llvm/ADT/DenseMap.h"
18 #include "llvm/ADT/DenseSet.h"
19 #include "llvm/ADT/STLExtras.h"
20 #include "llvm/ADT/SmallString.h"
21 #include "llvm/ADT/StringExtras.h"
22 #include "llvm/ADT/StringRef.h"
23 #include "llvm/ADT/StringSet.h"
24 #include "llvm/ADT/StringSwitch.h"
25 #include "llvm/ADT/iterator_range.h"
26 #include "llvm/Support/ErrorHandling.h"
27 #include "llvm/Support/raw_ostream.h"
28 #include "llvm/TableGen/Error.h"
29 #include "llvm/TableGen/Record.h"
30 #include "llvm/TableGen/StringMatcher.h"
31 #include "llvm/TableGen/TableGenBackend.h"
49 class FlattenedSpelling {
54 FlattenedSpelling(const std::string &Variety, const std::string &Name,
55 const std::string &Namespace, bool KnownToGCC) :
56 V(Variety), N(Name), NS(Namespace), K(KnownToGCC) {}
57 explicit FlattenedSpelling(const Record &Spelling) :
58 V(Spelling.getValueAsString("Variety")),
59 N(Spelling.getValueAsString("Name")) {
61 assert(V != "GCC" && V != "Clang" &&
62 "Given a GCC spelling, which means this hasn't been flattened!");
63 if (V == "CXX11" || V == "C2x" || V == "Pragma")
64 NS = Spelling.getValueAsString("Namespace");
66 K = Spelling.getValueAsBitOrUnset("KnownToGCC", Unset);
69 const std::string &variety() const { return V; }
70 const std::string &name() const { return N; }
71 const std::string &nameSpace() const { return NS; }
72 bool knownToGCC() const { return K; }
75 } // end anonymous namespace
77 static std::vector<FlattenedSpelling>
78 GetFlattenedSpellings(const Record &Attr) {
79 std::vector<Record *> Spellings = Attr.getValueAsListOfDefs("Spellings");
80 std::vector<FlattenedSpelling> Ret;
82 for (const auto &Spelling : Spellings) {
83 StringRef Variety = Spelling->getValueAsString("Variety");
84 StringRef Name = Spelling->getValueAsString("Name");
85 if (Variety == "GCC") {
86 // Gin up two new spelling objects to add into the list.
87 Ret.emplace_back("GNU", Name, "", true);
88 Ret.emplace_back("CXX11", Name, "gnu", true);
89 } else if (Variety == "Clang") {
90 Ret.emplace_back("GNU", Name, "", false);
91 Ret.emplace_back("CXX11", Name, "clang", false);
92 if (Spelling->getValueAsBit("AllowInC"))
93 Ret.emplace_back("C2x", Name, "clang", false);
95 Ret.push_back(FlattenedSpelling(*Spelling));
101 static std::string ReadPCHRecord(StringRef type) {
102 return StringSwitch<std::string>(type)
103 .EndsWith("Decl *", "Record.GetLocalDeclAs<"
104 + std::string(type, 0, type.size()-1) + ">(Record.readInt())")
105 .Case("TypeSourceInfo *", "Record.readTypeSourceInfo()")
106 .Case("Expr *", "Record.readExpr()")
107 .Case("IdentifierInfo *", "Record.readIdentifier()")
108 .Case("StringRef", "Record.readString()")
109 .Case("ParamIdx", "ParamIdx::deserialize(Record.readInt())")
110 .Default("Record.readInt()");
113 // Get a type that is suitable for storing an object of the specified type.
114 static StringRef getStorageType(StringRef type) {
115 return StringSwitch<StringRef>(type)
116 .Case("StringRef", "std::string")
120 // Assumes that the way to get the value is SA->getname()
121 static std::string WritePCHRecord(StringRef type, StringRef name) {
122 return "Record." + StringSwitch<std::string>(type)
123 .EndsWith("Decl *", "AddDeclRef(" + std::string(name) + ");\n")
124 .Case("TypeSourceInfo *", "AddTypeSourceInfo(" + std::string(name) + ");\n")
125 .Case("Expr *", "AddStmt(" + std::string(name) + ");\n")
126 .Case("IdentifierInfo *", "AddIdentifierRef(" + std::string(name) + ");\n")
127 .Case("StringRef", "AddString(" + std::string(name) + ");\n")
128 .Case("ParamIdx", "push_back(" + std::string(name) + ".serialize());\n")
129 .Default("push_back(" + std::string(name) + ");\n");
132 // Normalize attribute name by removing leading and trailing
133 // underscores. For example, __foo, foo__, __foo__ would
135 static StringRef NormalizeAttrName(StringRef AttrName) {
136 AttrName.consume_front("__");
137 AttrName.consume_back("__");
141 // Normalize the name by removing any and all leading and trailing underscores.
142 // This is different from NormalizeAttrName in that it also handles names like
143 // _pascal and __pascal.
144 static StringRef NormalizeNameForSpellingComparison(StringRef Name) {
145 return Name.trim("_");
148 // Normalize the spelling of a GNU attribute (i.e. "x" in "__attribute__((x))"),
149 // removing "__" if it appears at the beginning and end of the attribute's name.
150 static StringRef NormalizeGNUAttrSpelling(StringRef AttrSpelling) {
151 if (AttrSpelling.startswith("__") && AttrSpelling.endswith("__")) {
152 AttrSpelling = AttrSpelling.substr(2, AttrSpelling.size() - 4);
158 typedef std::vector<std::pair<std::string, const Record *>> ParsedAttrMap;
160 static ParsedAttrMap getParsedAttrList(const RecordKeeper &Records,
161 ParsedAttrMap *Dupes = nullptr) {
162 std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
163 std::set<std::string> Seen;
165 for (const auto *Attr : Attrs) {
166 if (Attr->getValueAsBit("SemaHandler")) {
168 if (Attr->isSubClassOf("TargetSpecificAttr") &&
169 !Attr->isValueUnset("ParseKind")) {
170 AN = Attr->getValueAsString("ParseKind");
172 // If this attribute has already been handled, it does not need to be
174 if (Seen.find(AN) != Seen.end()) {
176 Dupes->push_back(std::make_pair(AN, Attr));
181 AN = NormalizeAttrName(Attr->getName()).str();
183 R.push_back(std::make_pair(AN, Attr));
192 std::string lowerName, upperName;
198 Argument(const Record &Arg, StringRef Attr)
199 : lowerName(Arg.getValueAsString("Name")), upperName(lowerName),
200 attrName(Attr), isOpt(false), Fake(false) {
201 if (!lowerName.empty()) {
202 lowerName[0] = std::tolower(lowerName[0]);
203 upperName[0] = std::toupper(upperName[0]);
205 // Work around MinGW's macro definition of 'interface' to 'struct'. We
206 // have an attribute argument called 'Interface', so only the lower case
207 // name conflicts with the macro definition.
208 if (lowerName == "interface")
209 lowerName = "interface_";
211 virtual ~Argument() = default;
213 StringRef getLowerName() const { return lowerName; }
214 StringRef getUpperName() const { return upperName; }
215 StringRef getAttrName() const { return attrName; }
217 bool isOptional() const { return isOpt; }
218 void setOptional(bool set) { isOpt = set; }
220 bool isFake() const { return Fake; }
221 void setFake(bool fake) { Fake = fake; }
223 // These functions print the argument contents formatted in different ways.
224 virtual void writeAccessors(raw_ostream &OS) const = 0;
225 virtual void writeAccessorDefinitions(raw_ostream &OS) const {}
226 virtual void writeASTVisitorTraversal(raw_ostream &OS) const {}
227 virtual void writeCloneArgs(raw_ostream &OS) const = 0;
228 virtual void writeTemplateInstantiationArgs(raw_ostream &OS) const = 0;
229 virtual void writeTemplateInstantiation(raw_ostream &OS) const {}
230 virtual void writeCtorBody(raw_ostream &OS) const {}
231 virtual void writeCtorInitializers(raw_ostream &OS) const = 0;
232 virtual void writeCtorDefaultInitializers(raw_ostream &OS) const = 0;
233 virtual void writeCtorParameters(raw_ostream &OS) const = 0;
234 virtual void writeDeclarations(raw_ostream &OS) const = 0;
235 virtual void writePCHReadArgs(raw_ostream &OS) const = 0;
236 virtual void writePCHReadDecls(raw_ostream &OS) const = 0;
237 virtual void writePCHWrite(raw_ostream &OS) const = 0;
238 virtual std::string getIsOmitted() const { return "false"; }
239 virtual void writeValue(raw_ostream &OS) const = 0;
240 virtual void writeDump(raw_ostream &OS) const = 0;
241 virtual void writeDumpChildren(raw_ostream &OS) const {}
242 virtual void writeHasChildren(raw_ostream &OS) const { OS << "false"; }
244 virtual bool isEnumArg() const { return false; }
245 virtual bool isVariadicEnumArg() const { return false; }
246 virtual bool isVariadic() const { return false; }
248 virtual void writeImplicitCtorArgs(raw_ostream &OS) const {
249 OS << getUpperName();
253 class SimpleArgument : public Argument {
257 SimpleArgument(const Record &Arg, StringRef Attr, std::string T)
258 : Argument(Arg, Attr), type(std::move(T)) {}
260 std::string getType() const { return type; }
262 void writeAccessors(raw_ostream &OS) const override {
263 OS << " " << type << " get" << getUpperName() << "() const {\n";
264 OS << " return " << getLowerName() << ";\n";
268 void writeCloneArgs(raw_ostream &OS) const override {
269 OS << getLowerName();
272 void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
273 OS << "A->get" << getUpperName() << "()";
276 void writeCtorInitializers(raw_ostream &OS) const override {
277 OS << getLowerName() << "(" << getUpperName() << ")";
280 void writeCtorDefaultInitializers(raw_ostream &OS) const override {
281 OS << getLowerName() << "()";
284 void writeCtorParameters(raw_ostream &OS) const override {
285 OS << type << " " << getUpperName();
288 void writeDeclarations(raw_ostream &OS) const override {
289 OS << type << " " << getLowerName() << ";";
292 void writePCHReadDecls(raw_ostream &OS) const override {
293 std::string read = ReadPCHRecord(type);
294 OS << " " << type << " " << getLowerName() << " = " << read << ";\n";
297 void writePCHReadArgs(raw_ostream &OS) const override {
298 OS << getLowerName();
301 void writePCHWrite(raw_ostream &OS) const override {
302 OS << " " << WritePCHRecord(type, "SA->get" +
303 std::string(getUpperName()) + "()");
306 std::string getIsOmitted() const override {
307 if (type == "IdentifierInfo *")
308 return "!get" + getUpperName().str() + "()";
309 if (type == "TypeSourceInfo *")
310 return "!get" + getUpperName().str() + "Loc()";
311 if (type == "ParamIdx")
312 return "!get" + getUpperName().str() + "().isValid()";
316 void writeValue(raw_ostream &OS) const override {
317 if (type == "FunctionDecl *")
318 OS << "\" << get" << getUpperName()
319 << "()->getNameInfo().getAsString() << \"";
320 else if (type == "IdentifierInfo *")
321 // Some non-optional (comma required) identifier arguments can be the
322 // empty string but are then recorded as a nullptr.
323 OS << "\" << (get" << getUpperName() << "() ? get" << getUpperName()
324 << "()->getName() : \"\") << \"";
325 else if (type == "TypeSourceInfo *")
326 OS << "\" << get" << getUpperName() << "().getAsString() << \"";
327 else if (type == "ParamIdx")
328 OS << "\" << get" << getUpperName() << "().getSourceIndex() << \"";
330 OS << "\" << get" << getUpperName() << "() << \"";
333 void writeDump(raw_ostream &OS) const override {
334 if (type == "FunctionDecl *" || type == "NamedDecl *") {
335 OS << " OS << \" \";\n";
336 OS << " dumpBareDeclRef(SA->get" << getUpperName() << "());\n";
337 } else if (type == "IdentifierInfo *") {
338 // Some non-optional (comma required) identifier arguments can be the
339 // empty string but are then recorded as a nullptr.
340 OS << " if (SA->get" << getUpperName() << "())\n"
341 << " OS << \" \" << SA->get" << getUpperName()
342 << "()->getName();\n";
343 } else if (type == "TypeSourceInfo *") {
345 OS << " if (SA->get" << getUpperName() << "Loc())";
346 OS << " OS << \" \" << SA->get" << getUpperName()
347 << "().getAsString();\n";
348 } else if (type == "bool") {
349 OS << " if (SA->get" << getUpperName() << "()) OS << \" "
350 << getUpperName() << "\";\n";
351 } else if (type == "int" || type == "unsigned") {
352 OS << " OS << \" \" << SA->get" << getUpperName() << "();\n";
353 } else if (type == "ParamIdx") {
355 OS << " if (SA->get" << getUpperName() << "().isValid())\n ";
356 OS << " OS << \" \" << SA->get" << getUpperName()
357 << "().getSourceIndex();\n";
359 llvm_unreachable("Unknown SimpleArgument type!");
364 class DefaultSimpleArgument : public SimpleArgument {
368 DefaultSimpleArgument(const Record &Arg, StringRef Attr,
369 std::string T, int64_t Default)
370 : SimpleArgument(Arg, Attr, T), Default(Default) {}
372 void writeAccessors(raw_ostream &OS) const override {
373 SimpleArgument::writeAccessors(OS);
375 OS << "\n\n static const " << getType() << " Default" << getUpperName()
377 if (getType() == "bool")
378 OS << (Default != 0 ? "true" : "false");
385 class StringArgument : public Argument {
387 StringArgument(const Record &Arg, StringRef Attr)
388 : Argument(Arg, Attr)
391 void writeAccessors(raw_ostream &OS) const override {
392 OS << " llvm::StringRef get" << getUpperName() << "() const {\n";
393 OS << " return llvm::StringRef(" << getLowerName() << ", "
394 << getLowerName() << "Length);\n";
396 OS << " unsigned get" << getUpperName() << "Length() const {\n";
397 OS << " return " << getLowerName() << "Length;\n";
399 OS << " void set" << getUpperName()
400 << "(ASTContext &C, llvm::StringRef S) {\n";
401 OS << " " << getLowerName() << "Length = S.size();\n";
402 OS << " this->" << getLowerName() << " = new (C, 1) char ["
403 << getLowerName() << "Length];\n";
404 OS << " if (!S.empty())\n";
405 OS << " std::memcpy(this->" << getLowerName() << ", S.data(), "
406 << getLowerName() << "Length);\n";
410 void writeCloneArgs(raw_ostream &OS) const override {
411 OS << "get" << getUpperName() << "()";
414 void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
415 OS << "A->get" << getUpperName() << "()";
418 void writeCtorBody(raw_ostream &OS) const override {
419 OS << " if (!" << getUpperName() << ".empty())\n";
420 OS << " std::memcpy(" << getLowerName() << ", " << getUpperName()
421 << ".data(), " << getLowerName() << "Length);\n";
424 void writeCtorInitializers(raw_ostream &OS) const override {
425 OS << getLowerName() << "Length(" << getUpperName() << ".size()),"
426 << getLowerName() << "(new (Ctx, 1) char[" << getLowerName()
430 void writeCtorDefaultInitializers(raw_ostream &OS) const override {
431 OS << getLowerName() << "Length(0)," << getLowerName() << "(nullptr)";
434 void writeCtorParameters(raw_ostream &OS) const override {
435 OS << "llvm::StringRef " << getUpperName();
438 void writeDeclarations(raw_ostream &OS) const override {
439 OS << "unsigned " << getLowerName() << "Length;\n";
440 OS << "char *" << getLowerName() << ";";
443 void writePCHReadDecls(raw_ostream &OS) const override {
444 OS << " std::string " << getLowerName()
445 << "= Record.readString();\n";
448 void writePCHReadArgs(raw_ostream &OS) const override {
449 OS << getLowerName();
452 void writePCHWrite(raw_ostream &OS) const override {
453 OS << " Record.AddString(SA->get" << getUpperName() << "());\n";
456 void writeValue(raw_ostream &OS) const override {
457 OS << "\\\"\" << get" << getUpperName() << "() << \"\\\"";
460 void writeDump(raw_ostream &OS) const override {
461 OS << " OS << \" \\\"\" << SA->get" << getUpperName()
462 << "() << \"\\\"\";\n";
466 class AlignedArgument : public Argument {
468 AlignedArgument(const Record &Arg, StringRef Attr)
469 : Argument(Arg, Attr)
472 void writeAccessors(raw_ostream &OS) const override {
473 OS << " bool is" << getUpperName() << "Dependent() const;\n";
475 OS << " unsigned get" << getUpperName() << "(ASTContext &Ctx) const;\n";
477 OS << " bool is" << getUpperName() << "Expr() const {\n";
478 OS << " return is" << getLowerName() << "Expr;\n";
481 OS << " Expr *get" << getUpperName() << "Expr() const {\n";
482 OS << " assert(is" << getLowerName() << "Expr);\n";
483 OS << " return " << getLowerName() << "Expr;\n";
486 OS << " TypeSourceInfo *get" << getUpperName() << "Type() const {\n";
487 OS << " assert(!is" << getLowerName() << "Expr);\n";
488 OS << " return " << getLowerName() << "Type;\n";
492 void writeAccessorDefinitions(raw_ostream &OS) const override {
493 OS << "bool " << getAttrName() << "Attr::is" << getUpperName()
494 << "Dependent() const {\n";
495 OS << " if (is" << getLowerName() << "Expr)\n";
496 OS << " return " << getLowerName() << "Expr && (" << getLowerName()
497 << "Expr->isValueDependent() || " << getLowerName()
498 << "Expr->isTypeDependent());\n";
500 OS << " return " << getLowerName()
501 << "Type->getType()->isDependentType();\n";
504 // FIXME: Do not do the calculation here
505 // FIXME: Handle types correctly
506 // A null pointer means maximum alignment
507 OS << "unsigned " << getAttrName() << "Attr::get" << getUpperName()
508 << "(ASTContext &Ctx) const {\n";
509 OS << " assert(!is" << getUpperName() << "Dependent());\n";
510 OS << " if (is" << getLowerName() << "Expr)\n";
511 OS << " return " << getLowerName() << "Expr ? " << getLowerName()
512 << "Expr->EvaluateKnownConstInt(Ctx).getZExtValue()"
513 << " * Ctx.getCharWidth() : "
514 << "Ctx.getTargetDefaultAlignForAttributeAligned();\n";
516 OS << " return 0; // FIXME\n";
520 void writeASTVisitorTraversal(raw_ostream &OS) const override {
521 StringRef Name = getUpperName();
522 OS << " if (A->is" << Name << "Expr()) {\n"
523 << " if (!getDerived().TraverseStmt(A->get" << Name << "Expr()))\n"
524 << " return false;\n"
525 << " } else if (auto *TSI = A->get" << Name << "Type()) {\n"
526 << " if (!getDerived().TraverseTypeLoc(TSI->getTypeLoc()))\n"
527 << " return false;\n"
531 void writeCloneArgs(raw_ostream &OS) const override {
532 OS << "is" << getLowerName() << "Expr, is" << getLowerName()
533 << "Expr ? static_cast<void*>(" << getLowerName()
534 << "Expr) : " << getLowerName()
538 void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
539 // FIXME: move the definition in Sema::InstantiateAttrs to here.
540 // In the meantime, aligned attributes are cloned.
543 void writeCtorBody(raw_ostream &OS) const override {
544 OS << " if (is" << getLowerName() << "Expr)\n";
545 OS << " " << getLowerName() << "Expr = reinterpret_cast<Expr *>("
546 << getUpperName() << ");\n";
548 OS << " " << getLowerName()
549 << "Type = reinterpret_cast<TypeSourceInfo *>(" << getUpperName()
553 void writeCtorInitializers(raw_ostream &OS) const override {
554 OS << "is" << getLowerName() << "Expr(Is" << getUpperName() << "Expr)";
557 void writeCtorDefaultInitializers(raw_ostream &OS) const override {
558 OS << "is" << getLowerName() << "Expr(false)";
561 void writeCtorParameters(raw_ostream &OS) const override {
562 OS << "bool Is" << getUpperName() << "Expr, void *" << getUpperName();
565 void writeImplicitCtorArgs(raw_ostream &OS) const override {
566 OS << "Is" << getUpperName() << "Expr, " << getUpperName();
569 void writeDeclarations(raw_ostream &OS) const override {
570 OS << "bool is" << getLowerName() << "Expr;\n";
572 OS << "Expr *" << getLowerName() << "Expr;\n";
573 OS << "TypeSourceInfo *" << getLowerName() << "Type;\n";
577 void writePCHReadArgs(raw_ostream &OS) const override {
578 OS << "is" << getLowerName() << "Expr, " << getLowerName() << "Ptr";
581 void writePCHReadDecls(raw_ostream &OS) const override {
582 OS << " bool is" << getLowerName() << "Expr = Record.readInt();\n";
583 OS << " void *" << getLowerName() << "Ptr;\n";
584 OS << " if (is" << getLowerName() << "Expr)\n";
585 OS << " " << getLowerName() << "Ptr = Record.readExpr();\n";
587 OS << " " << getLowerName()
588 << "Ptr = Record.readTypeSourceInfo();\n";
591 void writePCHWrite(raw_ostream &OS) const override {
592 OS << " Record.push_back(SA->is" << getUpperName() << "Expr());\n";
593 OS << " if (SA->is" << getUpperName() << "Expr())\n";
594 OS << " Record.AddStmt(SA->get" << getUpperName() << "Expr());\n";
596 OS << " Record.AddTypeSourceInfo(SA->get" << getUpperName()
600 std::string getIsOmitted() const override {
601 return "!is" + getLowerName().str() + "Expr || !" + getLowerName().str()
605 void writeValue(raw_ostream &OS) const override {
607 OS << " " << getLowerName()
608 << "Expr->printPretty(OS, nullptr, Policy);\n";
612 void writeDump(raw_ostream &OS) const override {
613 OS << " if (!SA->is" << getUpperName() << "Expr())\n";
614 OS << " dumpType(SA->get" << getUpperName()
615 << "Type()->getType());\n";
618 void writeDumpChildren(raw_ostream &OS) const override {
619 OS << " if (SA->is" << getUpperName() << "Expr())\n";
620 OS << " Visit(SA->get" << getUpperName() << "Expr());\n";
623 void writeHasChildren(raw_ostream &OS) const override {
624 OS << "SA->is" << getUpperName() << "Expr()";
628 class VariadicArgument : public Argument {
629 std::string Type, ArgName, ArgSizeName, RangeName;
632 // Assumed to receive a parameter: raw_ostream OS.
633 virtual void writeValueImpl(raw_ostream &OS) const {
634 OS << " OS << Val;\n";
636 // Assumed to receive a parameter: raw_ostream OS.
637 virtual void writeDumpImpl(raw_ostream &OS) const {
638 OS << " OS << \" \" << Val;\n";
642 VariadicArgument(const Record &Arg, StringRef Attr, std::string T)
643 : Argument(Arg, Attr), Type(std::move(T)),
644 ArgName(getLowerName().str() + "_"), ArgSizeName(ArgName + "Size"),
645 RangeName(getLowerName()) {}
647 const std::string &getType() const { return Type; }
648 const std::string &getArgName() const { return ArgName; }
649 const std::string &getArgSizeName() const { return ArgSizeName; }
650 bool isVariadic() const override { return true; }
652 void writeAccessors(raw_ostream &OS) const override {
653 std::string IteratorType = getLowerName().str() + "_iterator";
654 std::string BeginFn = getLowerName().str() + "_begin()";
655 std::string EndFn = getLowerName().str() + "_end()";
657 OS << " typedef " << Type << "* " << IteratorType << ";\n";
658 OS << " " << IteratorType << " " << BeginFn << " const {"
659 << " return " << ArgName << "; }\n";
660 OS << " " << IteratorType << " " << EndFn << " const {"
661 << " return " << ArgName << " + " << ArgSizeName << "; }\n";
662 OS << " unsigned " << getLowerName() << "_size() const {"
663 << " return " << ArgSizeName << "; }\n";
664 OS << " llvm::iterator_range<" << IteratorType << "> " << RangeName
665 << "() const { return llvm::make_range(" << BeginFn << ", " << EndFn
669 void writeCloneArgs(raw_ostream &OS) const override {
670 OS << ArgName << ", " << ArgSizeName;
673 void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
674 // This isn't elegant, but we have to go through public methods...
675 OS << "A->" << getLowerName() << "_begin(), "
676 << "A->" << getLowerName() << "_size()";
679 void writeASTVisitorTraversal(raw_ostream &OS) const override {
680 // FIXME: Traverse the elements.
683 void writeCtorBody(raw_ostream &OS) const override {
684 OS << " std::copy(" << getUpperName() << ", " << getUpperName()
685 << " + " << ArgSizeName << ", " << ArgName << ");\n";
688 void writeCtorInitializers(raw_ostream &OS) const override {
689 OS << ArgSizeName << "(" << getUpperName() << "Size), "
690 << ArgName << "(new (Ctx, 16) " << getType() << "["
691 << ArgSizeName << "])";
694 void writeCtorDefaultInitializers(raw_ostream &OS) const override {
695 OS << ArgSizeName << "(0), " << ArgName << "(nullptr)";
698 void writeCtorParameters(raw_ostream &OS) const override {
699 OS << getType() << " *" << getUpperName() << ", unsigned "
700 << getUpperName() << "Size";
703 void writeImplicitCtorArgs(raw_ostream &OS) const override {
704 OS << getUpperName() << ", " << getUpperName() << "Size";
707 void writeDeclarations(raw_ostream &OS) const override {
708 OS << " unsigned " << ArgSizeName << ";\n";
709 OS << " " << getType() << " *" << ArgName << ";";
712 void writePCHReadDecls(raw_ostream &OS) const override {
713 OS << " unsigned " << getLowerName() << "Size = Record.readInt();\n";
714 OS << " SmallVector<" << getType() << ", 4> "
715 << getLowerName() << ";\n";
716 OS << " " << getLowerName() << ".reserve(" << getLowerName()
719 // If we can't store the values in the current type (if it's something
720 // like StringRef), store them in a different type and convert the
721 // container afterwards.
722 std::string StorageType = getStorageType(getType());
723 std::string StorageName = getLowerName();
724 if (StorageType != getType()) {
725 StorageName += "Storage";
726 OS << " SmallVector<" << StorageType << ", 4> "
727 << StorageName << ";\n";
728 OS << " " << StorageName << ".reserve(" << getLowerName()
732 OS << " for (unsigned i = 0; i != " << getLowerName() << "Size; ++i)\n";
733 std::string read = ReadPCHRecord(Type);
734 OS << " " << StorageName << ".push_back(" << read << ");\n";
736 if (StorageType != getType()) {
737 OS << " for (unsigned i = 0; i != " << getLowerName() << "Size; ++i)\n";
738 OS << " " << getLowerName() << ".push_back("
739 << StorageName << "[i]);\n";
743 void writePCHReadArgs(raw_ostream &OS) const override {
744 OS << getLowerName() << ".data(), " << getLowerName() << "Size";
747 void writePCHWrite(raw_ostream &OS) const override {
748 OS << " Record.push_back(SA->" << getLowerName() << "_size());\n";
749 OS << " for (auto &Val : SA->" << RangeName << "())\n";
750 OS << " " << WritePCHRecord(Type, "Val");
753 void writeValue(raw_ostream &OS) const override {
755 OS << " bool isFirst = true;\n"
756 << " for (const auto &Val : " << RangeName << "()) {\n"
757 << " if (isFirst) isFirst = false;\n"
758 << " else OS << \", \";\n";
764 void writeDump(raw_ostream &OS) const override {
765 OS << " for (const auto &Val : SA->" << RangeName << "())\n";
770 class VariadicParamIdxArgument : public VariadicArgument {
772 VariadicParamIdxArgument(const Record &Arg, StringRef Attr)
773 : VariadicArgument(Arg, Attr, "ParamIdx") {}
776 void writeValueImpl(raw_ostream &OS) const override {
777 OS << " OS << Val.getSourceIndex();\n";
780 void writeDumpImpl(raw_ostream &OS) const override {
781 OS << " OS << \" \" << Val.getSourceIndex();\n";
785 struct VariadicParamOrParamIdxArgument : public VariadicArgument {
786 VariadicParamOrParamIdxArgument(const Record &Arg, StringRef Attr)
787 : VariadicArgument(Arg, Attr, "int") {}
790 // Unique the enums, but maintain the original declaration ordering.
791 std::vector<StringRef>
792 uniqueEnumsInOrder(const std::vector<StringRef> &enums) {
793 std::vector<StringRef> uniques;
794 SmallDenseSet<StringRef, 8> unique_set;
795 for (const auto &i : enums) {
796 if (unique_set.insert(i).second)
797 uniques.push_back(i);
802 class EnumArgument : public Argument {
804 std::vector<StringRef> values, enums, uniques;
807 EnumArgument(const Record &Arg, StringRef Attr)
808 : Argument(Arg, Attr), type(Arg.getValueAsString("Type")),
809 values(Arg.getValueAsListOfStrings("Values")),
810 enums(Arg.getValueAsListOfStrings("Enums")),
811 uniques(uniqueEnumsInOrder(enums))
813 // FIXME: Emit a proper error
814 assert(!uniques.empty());
817 bool isEnumArg() const override { return true; }
819 void writeAccessors(raw_ostream &OS) const override {
820 OS << " " << type << " get" << getUpperName() << "() const {\n";
821 OS << " return " << getLowerName() << ";\n";
825 void writeCloneArgs(raw_ostream &OS) const override {
826 OS << getLowerName();
829 void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
830 OS << "A->get" << getUpperName() << "()";
832 void writeCtorInitializers(raw_ostream &OS) const override {
833 OS << getLowerName() << "(" << getUpperName() << ")";
835 void writeCtorDefaultInitializers(raw_ostream &OS) const override {
836 OS << getLowerName() << "(" << type << "(0))";
838 void writeCtorParameters(raw_ostream &OS) const override {
839 OS << type << " " << getUpperName();
841 void writeDeclarations(raw_ostream &OS) const override {
842 auto i = uniques.cbegin(), e = uniques.cend();
843 // The last one needs to not have a comma.
847 OS << " enum " << type << " {\n";
849 OS << " " << *i << ",\n";
850 OS << " " << *e << "\n";
853 OS << " " << type << " " << getLowerName() << ";";
856 void writePCHReadDecls(raw_ostream &OS) const override {
857 OS << " " << getAttrName() << "Attr::" << type << " " << getLowerName()
858 << "(static_cast<" << getAttrName() << "Attr::" << type
859 << ">(Record.readInt()));\n";
862 void writePCHReadArgs(raw_ostream &OS) const override {
863 OS << getLowerName();
866 void writePCHWrite(raw_ostream &OS) const override {
867 OS << "Record.push_back(SA->get" << getUpperName() << "());\n";
870 void writeValue(raw_ostream &OS) const override {
871 // FIXME: this isn't 100% correct -- some enum arguments require printing
872 // as a string literal, while others require printing as an identifier.
873 // Tablegen currently does not distinguish between the two forms.
874 OS << "\\\"\" << " << getAttrName() << "Attr::Convert" << type << "ToStr(get"
875 << getUpperName() << "()) << \"\\\"";
878 void writeDump(raw_ostream &OS) const override {
879 OS << " switch(SA->get" << getUpperName() << "()) {\n";
880 for (const auto &I : uniques) {
881 OS << " case " << getAttrName() << "Attr::" << I << ":\n";
882 OS << " OS << \" " << I << "\";\n";
888 void writeConversion(raw_ostream &OS) const {
889 OS << " static bool ConvertStrTo" << type << "(StringRef Val, ";
890 OS << type << " &Out) {\n";
891 OS << " Optional<" << type << "> R = llvm::StringSwitch<Optional<";
892 OS << type << ">>(Val)\n";
893 for (size_t I = 0; I < enums.size(); ++I) {
894 OS << " .Case(\"" << values[I] << "\", ";
895 OS << getAttrName() << "Attr::" << enums[I] << ")\n";
897 OS << " .Default(Optional<" << type << ">());\n";
899 OS << " Out = *R;\n return true;\n }\n";
900 OS << " return false;\n";
903 // Mapping from enumeration values back to enumeration strings isn't
904 // trivial because some enumeration values have multiple named
905 // enumerators, such as type_visibility(internal) and
906 // type_visibility(hidden) both mapping to TypeVisibilityAttr::Hidden.
907 OS << " static const char *Convert" << type << "ToStr("
908 << type << " Val) {\n"
909 << " switch(Val) {\n";
910 SmallDenseSet<StringRef, 8> Uniques;
911 for (size_t I = 0; I < enums.size(); ++I) {
912 if (Uniques.insert(enums[I]).second)
913 OS << " case " << getAttrName() << "Attr::" << enums[I]
914 << ": return \"" << values[I] << "\";\n";
917 << " llvm_unreachable(\"No enumerator with that value\");\n"
922 class VariadicEnumArgument: public VariadicArgument {
923 std::string type, QualifiedTypeName;
924 std::vector<StringRef> values, enums, uniques;
927 void writeValueImpl(raw_ostream &OS) const override {
928 // FIXME: this isn't 100% correct -- some enum arguments require printing
929 // as a string literal, while others require printing as an identifier.
930 // Tablegen currently does not distinguish between the two forms.
931 OS << " OS << \"\\\"\" << " << getAttrName() << "Attr::Convert" << type
932 << "ToStr(Val)" << "<< \"\\\"\";\n";
936 VariadicEnumArgument(const Record &Arg, StringRef Attr)
937 : VariadicArgument(Arg, Attr, Arg.getValueAsString("Type")),
938 type(Arg.getValueAsString("Type")),
939 values(Arg.getValueAsListOfStrings("Values")),
940 enums(Arg.getValueAsListOfStrings("Enums")),
941 uniques(uniqueEnumsInOrder(enums))
943 QualifiedTypeName = getAttrName().str() + "Attr::" + type;
945 // FIXME: Emit a proper error
946 assert(!uniques.empty());
949 bool isVariadicEnumArg() const override { return true; }
951 void writeDeclarations(raw_ostream &OS) const override {
952 auto i = uniques.cbegin(), e = uniques.cend();
953 // The last one needs to not have a comma.
957 OS << " enum " << type << " {\n";
959 OS << " " << *i << ",\n";
960 OS << " " << *e << "\n";
964 VariadicArgument::writeDeclarations(OS);
967 void writeDump(raw_ostream &OS) const override {
968 OS << " for (" << getAttrName() << "Attr::" << getLowerName()
969 << "_iterator I = SA->" << getLowerName() << "_begin(), E = SA->"
970 << getLowerName() << "_end(); I != E; ++I) {\n";
971 OS << " switch(*I) {\n";
972 for (const auto &UI : uniques) {
973 OS << " case " << getAttrName() << "Attr::" << UI << ":\n";
974 OS << " OS << \" " << UI << "\";\n";
981 void writePCHReadDecls(raw_ostream &OS) const override {
982 OS << " unsigned " << getLowerName() << "Size = Record.readInt();\n";
983 OS << " SmallVector<" << QualifiedTypeName << ", 4> " << getLowerName()
985 OS << " " << getLowerName() << ".reserve(" << getLowerName()
987 OS << " for (unsigned i = " << getLowerName() << "Size; i; --i)\n";
988 OS << " " << getLowerName() << ".push_back(" << "static_cast<"
989 << QualifiedTypeName << ">(Record.readInt()));\n";
992 void writePCHWrite(raw_ostream &OS) const override {
993 OS << " Record.push_back(SA->" << getLowerName() << "_size());\n";
994 OS << " for (" << getAttrName() << "Attr::" << getLowerName()
995 << "_iterator i = SA->" << getLowerName() << "_begin(), e = SA->"
996 << getLowerName() << "_end(); i != e; ++i)\n";
997 OS << " " << WritePCHRecord(QualifiedTypeName, "(*i)");
1000 void writeConversion(raw_ostream &OS) const {
1001 OS << " static bool ConvertStrTo" << type << "(StringRef Val, ";
1002 OS << type << " &Out) {\n";
1003 OS << " Optional<" << type << "> R = llvm::StringSwitch<Optional<";
1004 OS << type << ">>(Val)\n";
1005 for (size_t I = 0; I < enums.size(); ++I) {
1006 OS << " .Case(\"" << values[I] << "\", ";
1007 OS << getAttrName() << "Attr::" << enums[I] << ")\n";
1009 OS << " .Default(Optional<" << type << ">());\n";
1010 OS << " if (R) {\n";
1011 OS << " Out = *R;\n return true;\n }\n";
1012 OS << " return false;\n";
1015 OS << " static const char *Convert" << type << "ToStr("
1016 << type << " Val) {\n"
1017 << " switch(Val) {\n";
1018 SmallDenseSet<StringRef, 8> Uniques;
1019 for (size_t I = 0; I < enums.size(); ++I) {
1020 if (Uniques.insert(enums[I]).second)
1021 OS << " case " << getAttrName() << "Attr::" << enums[I]
1022 << ": return \"" << values[I] << "\";\n";
1025 << " llvm_unreachable(\"No enumerator with that value\");\n"
1030 class VersionArgument : public Argument {
1032 VersionArgument(const Record &Arg, StringRef Attr)
1033 : Argument(Arg, Attr)
1036 void writeAccessors(raw_ostream &OS) const override {
1037 OS << " VersionTuple get" << getUpperName() << "() const {\n";
1038 OS << " return " << getLowerName() << ";\n";
1040 OS << " void set" << getUpperName()
1041 << "(ASTContext &C, VersionTuple V) {\n";
1042 OS << " " << getLowerName() << " = V;\n";
1046 void writeCloneArgs(raw_ostream &OS) const override {
1047 OS << "get" << getUpperName() << "()";
1050 void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
1051 OS << "A->get" << getUpperName() << "()";
1054 void writeCtorInitializers(raw_ostream &OS) const override {
1055 OS << getLowerName() << "(" << getUpperName() << ")";
1058 void writeCtorDefaultInitializers(raw_ostream &OS) const override {
1059 OS << getLowerName() << "()";
1062 void writeCtorParameters(raw_ostream &OS) const override {
1063 OS << "VersionTuple " << getUpperName();
1066 void writeDeclarations(raw_ostream &OS) const override {
1067 OS << "VersionTuple " << getLowerName() << ";\n";
1070 void writePCHReadDecls(raw_ostream &OS) const override {
1071 OS << " VersionTuple " << getLowerName()
1072 << "= Record.readVersionTuple();\n";
1075 void writePCHReadArgs(raw_ostream &OS) const override {
1076 OS << getLowerName();
1079 void writePCHWrite(raw_ostream &OS) const override {
1080 OS << " Record.AddVersionTuple(SA->get" << getUpperName() << "());\n";
1083 void writeValue(raw_ostream &OS) const override {
1084 OS << getLowerName() << "=\" << get" << getUpperName() << "() << \"";
1087 void writeDump(raw_ostream &OS) const override {
1088 OS << " OS << \" \" << SA->get" << getUpperName() << "();\n";
1092 class ExprArgument : public SimpleArgument {
1094 ExprArgument(const Record &Arg, StringRef Attr)
1095 : SimpleArgument(Arg, Attr, "Expr *")
1098 void writeASTVisitorTraversal(raw_ostream &OS) const override {
1100 << "getDerived().TraverseStmt(A->get" << getUpperName() << "()))\n";
1101 OS << " return false;\n";
1104 void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
1105 OS << "tempInst" << getUpperName();
1108 void writeTemplateInstantiation(raw_ostream &OS) const override {
1109 OS << " " << getType() << " tempInst" << getUpperName() << ";\n";
1111 OS << " EnterExpressionEvaluationContext "
1112 << "Unevaluated(S, Sema::ExpressionEvaluationContext::Unevaluated);\n";
1113 OS << " ExprResult " << "Result = S.SubstExpr("
1114 << "A->get" << getUpperName() << "(), TemplateArgs);\n";
1115 OS << " tempInst" << getUpperName() << " = "
1116 << "Result.getAs<Expr>();\n";
1120 void writeDump(raw_ostream &OS) const override {}
1122 void writeDumpChildren(raw_ostream &OS) const override {
1123 OS << " Visit(SA->get" << getUpperName() << "());\n";
1126 void writeHasChildren(raw_ostream &OS) const override { OS << "true"; }
1129 class VariadicExprArgument : public VariadicArgument {
1131 VariadicExprArgument(const Record &Arg, StringRef Attr)
1132 : VariadicArgument(Arg, Attr, "Expr *")
1135 void writeASTVisitorTraversal(raw_ostream &OS) const override {
1137 OS << " " << getType() << " *I = A->" << getLowerName()
1139 OS << " " << getType() << " *E = A->" << getLowerName()
1141 OS << " for (; I != E; ++I) {\n";
1142 OS << " if (!getDerived().TraverseStmt(*I))\n";
1143 OS << " return false;\n";
1148 void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
1149 OS << "tempInst" << getUpperName() << ", "
1150 << "A->" << getLowerName() << "_size()";
1153 void writeTemplateInstantiation(raw_ostream &OS) const override {
1154 OS << " auto *tempInst" << getUpperName()
1155 << " = new (C, 16) " << getType()
1156 << "[A->" << getLowerName() << "_size()];\n";
1158 OS << " EnterExpressionEvaluationContext "
1159 << "Unevaluated(S, Sema::ExpressionEvaluationContext::Unevaluated);\n";
1160 OS << " " << getType() << " *TI = tempInst" << getUpperName()
1162 OS << " " << getType() << " *I = A->" << getLowerName()
1164 OS << " " << getType() << " *E = A->" << getLowerName()
1166 OS << " for (; I != E; ++I, ++TI) {\n";
1167 OS << " ExprResult Result = S.SubstExpr(*I, TemplateArgs);\n";
1168 OS << " *TI = Result.getAs<Expr>();\n";
1173 void writeDump(raw_ostream &OS) const override {}
1175 void writeDumpChildren(raw_ostream &OS) const override {
1176 OS << " for (" << getAttrName() << "Attr::" << getLowerName()
1177 << "_iterator I = SA->" << getLowerName() << "_begin(), E = SA->"
1178 << getLowerName() << "_end(); I != E; ++I)\n";
1179 OS << " Visit(*I);\n";
1182 void writeHasChildren(raw_ostream &OS) const override {
1183 OS << "SA->" << getLowerName() << "_begin() != "
1184 << "SA->" << getLowerName() << "_end()";
1188 class VariadicIdentifierArgument : public VariadicArgument {
1190 VariadicIdentifierArgument(const Record &Arg, StringRef Attr)
1191 : VariadicArgument(Arg, Attr, "IdentifierInfo *")
1195 class VariadicStringArgument : public VariadicArgument {
1197 VariadicStringArgument(const Record &Arg, StringRef Attr)
1198 : VariadicArgument(Arg, Attr, "StringRef")
1201 void writeCtorBody(raw_ostream &OS) const override {
1202 OS << " for (size_t I = 0, E = " << getArgSizeName() << "; I != E;\n"
1204 " StringRef Ref = " << getUpperName() << "[I];\n"
1205 " if (!Ref.empty()) {\n"
1206 " char *Mem = new (Ctx, 1) char[Ref.size()];\n"
1207 " std::memcpy(Mem, Ref.data(), Ref.size());\n"
1208 " " << getArgName() << "[I] = StringRef(Mem, Ref.size());\n"
1213 void writeValueImpl(raw_ostream &OS) const override {
1214 OS << " OS << \"\\\"\" << Val << \"\\\"\";\n";
1218 class TypeArgument : public SimpleArgument {
1220 TypeArgument(const Record &Arg, StringRef Attr)
1221 : SimpleArgument(Arg, Attr, "TypeSourceInfo *")
1224 void writeAccessors(raw_ostream &OS) const override {
1225 OS << " QualType get" << getUpperName() << "() const {\n";
1226 OS << " return " << getLowerName() << "->getType();\n";
1228 OS << " " << getType() << " get" << getUpperName() << "Loc() const {\n";
1229 OS << " return " << getLowerName() << ";\n";
1233 void writeASTVisitorTraversal(raw_ostream &OS) const override {
1234 OS << " if (auto *TSI = A->get" << getUpperName() << "Loc())\n";
1235 OS << " if (!getDerived().TraverseTypeLoc(TSI->getTypeLoc()))\n";
1236 OS << " return false;\n";
1239 void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
1240 OS << "A->get" << getUpperName() << "Loc()";
1243 void writePCHWrite(raw_ostream &OS) const override {
1244 OS << " " << WritePCHRecord(
1245 getType(), "SA->get" + std::string(getUpperName()) + "Loc()");
1249 } // end anonymous namespace
1251 static std::unique_ptr<Argument>
1252 createArgument(const Record &Arg, StringRef Attr,
1253 const Record *Search = nullptr) {
1257 std::unique_ptr<Argument> Ptr;
1258 llvm::StringRef ArgName = Search->getName();
1260 if (ArgName == "AlignedArgument")
1261 Ptr = std::make_unique<AlignedArgument>(Arg, Attr);
1262 else if (ArgName == "EnumArgument")
1263 Ptr = std::make_unique<EnumArgument>(Arg, Attr);
1264 else if (ArgName == "ExprArgument")
1265 Ptr = std::make_unique<ExprArgument>(Arg, Attr);
1266 else if (ArgName == "FunctionArgument")
1267 Ptr = std::make_unique<SimpleArgument>(Arg, Attr, "FunctionDecl *");
1268 else if (ArgName == "NamedArgument")
1269 Ptr = std::make_unique<SimpleArgument>(Arg, Attr, "NamedDecl *");
1270 else if (ArgName == "IdentifierArgument")
1271 Ptr = std::make_unique<SimpleArgument>(Arg, Attr, "IdentifierInfo *");
1272 else if (ArgName == "DefaultBoolArgument")
1273 Ptr = std::make_unique<DefaultSimpleArgument>(
1274 Arg, Attr, "bool", Arg.getValueAsBit("Default"));
1275 else if (ArgName == "BoolArgument")
1276 Ptr = std::make_unique<SimpleArgument>(Arg, Attr, "bool");
1277 else if (ArgName == "DefaultIntArgument")
1278 Ptr = std::make_unique<DefaultSimpleArgument>(
1279 Arg, Attr, "int", Arg.getValueAsInt("Default"));
1280 else if (ArgName == "IntArgument")
1281 Ptr = std::make_unique<SimpleArgument>(Arg, Attr, "int");
1282 else if (ArgName == "StringArgument")
1283 Ptr = std::make_unique<StringArgument>(Arg, Attr);
1284 else if (ArgName == "TypeArgument")
1285 Ptr = std::make_unique<TypeArgument>(Arg, Attr);
1286 else if (ArgName == "UnsignedArgument")
1287 Ptr = std::make_unique<SimpleArgument>(Arg, Attr, "unsigned");
1288 else if (ArgName == "VariadicUnsignedArgument")
1289 Ptr = std::make_unique<VariadicArgument>(Arg, Attr, "unsigned");
1290 else if (ArgName == "VariadicStringArgument")
1291 Ptr = std::make_unique<VariadicStringArgument>(Arg, Attr);
1292 else if (ArgName == "VariadicEnumArgument")
1293 Ptr = std::make_unique<VariadicEnumArgument>(Arg, Attr);
1294 else if (ArgName == "VariadicExprArgument")
1295 Ptr = std::make_unique<VariadicExprArgument>(Arg, Attr);
1296 else if (ArgName == "VariadicParamIdxArgument")
1297 Ptr = std::make_unique<VariadicParamIdxArgument>(Arg, Attr);
1298 else if (ArgName == "VariadicParamOrParamIdxArgument")
1299 Ptr = std::make_unique<VariadicParamOrParamIdxArgument>(Arg, Attr);
1300 else if (ArgName == "ParamIdxArgument")
1301 Ptr = std::make_unique<SimpleArgument>(Arg, Attr, "ParamIdx");
1302 else if (ArgName == "VariadicIdentifierArgument")
1303 Ptr = std::make_unique<VariadicIdentifierArgument>(Arg, Attr);
1304 else if (ArgName == "VersionArgument")
1305 Ptr = std::make_unique<VersionArgument>(Arg, Attr);
1308 // Search in reverse order so that the most-derived type is handled first.
1309 ArrayRef<std::pair<Record*, SMRange>> Bases = Search->getSuperClasses();
1310 for (const auto &Base : llvm::reverse(Bases)) {
1311 if ((Ptr = createArgument(Arg, Attr, Base.first)))
1316 if (Ptr && Arg.getValueAsBit("Optional"))
1317 Ptr->setOptional(true);
1319 if (Ptr && Arg.getValueAsBit("Fake"))
1325 static void writeAvailabilityValue(raw_ostream &OS) {
1326 OS << "\" << getPlatform()->getName();\n"
1327 << " if (getStrict()) OS << \", strict\";\n"
1328 << " if (!getIntroduced().empty()) OS << \", introduced=\" << getIntroduced();\n"
1329 << " if (!getDeprecated().empty()) OS << \", deprecated=\" << getDeprecated();\n"
1330 << " if (!getObsoleted().empty()) OS << \", obsoleted=\" << getObsoleted();\n"
1331 << " if (getUnavailable()) OS << \", unavailable\";\n"
1335 static void writeDeprecatedAttrValue(raw_ostream &OS, std::string &Variety) {
1336 OS << "\\\"\" << getMessage() << \"\\\"\";\n";
1337 // Only GNU deprecated has an optional fixit argument at the second position.
1338 if (Variety == "GNU")
1339 OS << " if (!getReplacement().empty()) OS << \", \\\"\""
1340 " << getReplacement() << \"\\\"\";\n";
1344 static void writeGetSpellingFunction(Record &R, raw_ostream &OS) {
1345 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(R);
1347 OS << "const char *" << R.getName() << "Attr::getSpelling() const {\n";
1348 if (Spellings.empty()) {
1349 OS << " return \"(No spelling)\";\n}\n\n";
1353 OS << " switch (getAttributeSpellingListIndex()) {\n"
1355 " llvm_unreachable(\"Unknown attribute spelling!\");\n"
1356 " return \"(No spelling)\";\n";
1358 for (unsigned I = 0; I < Spellings.size(); ++I)
1359 OS << " case " << I << ":\n"
1360 " return \"" << Spellings[I].name() << "\";\n";
1361 // End of the switch statement.
1363 // End of the getSpelling function.
1368 writePrettyPrintFunction(Record &R,
1369 const std::vector<std::unique_ptr<Argument>> &Args,
1371 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(R);
1373 OS << "void " << R.getName() << "Attr::printPretty("
1374 << "raw_ostream &OS, const PrintingPolicy &Policy) const {\n";
1376 if (Spellings.empty()) {
1381 OS << " switch (getAttributeSpellingListIndex()) {\n"
1383 " llvm_unreachable(\"Unknown attribute spelling!\");\n"
1386 for (unsigned I = 0; I < Spellings.size(); ++ I) {
1387 llvm::SmallString<16> Prefix;
1388 llvm::SmallString<8> Suffix;
1389 // The actual spelling of the name and namespace (if applicable)
1390 // of an attribute without considering prefix and suffix.
1391 llvm::SmallString<64> Spelling;
1392 std::string Name = Spellings[I].name();
1393 std::string Variety = Spellings[I].variety();
1395 if (Variety == "GNU") {
1396 Prefix = " __attribute__((";
1398 } else if (Variety == "CXX11" || Variety == "C2x") {
1401 std::string Namespace = Spellings[I].nameSpace();
1402 if (!Namespace.empty()) {
1403 Spelling += Namespace;
1406 } else if (Variety == "Declspec") {
1407 Prefix = " __declspec(";
1409 } else if (Variety == "Microsoft") {
1412 } else if (Variety == "Keyword") {
1415 } else if (Variety == "Pragma") {
1416 Prefix = "#pragma ";
1418 std::string Namespace = Spellings[I].nameSpace();
1419 if (!Namespace.empty()) {
1420 Spelling += Namespace;
1424 llvm_unreachable("Unknown attribute syntax variety!");
1430 " case " << I << " : {\n"
1431 " OS << \"" << Prefix << Spelling;
1433 if (Variety == "Pragma") {
1435 OS << " printPrettyPragma(OS, Policy);\n";
1436 OS << " OS << \"\\n\";";
1442 if (Spelling == "availability") {
1444 writeAvailabilityValue(OS);
1446 } else if (Spelling == "deprecated" || Spelling == "gnu::deprecated") {
1448 writeDeprecatedAttrValue(OS, Variety);
1451 // To avoid printing parentheses around an empty argument list or
1452 // printing spurious commas at the end of an argument list, we need to
1453 // determine where the last provided non-fake argument is.
1454 unsigned NonFakeArgs = 0;
1455 unsigned TrailingOptArgs = 0;
1456 bool FoundNonOptArg = false;
1457 for (const auto &arg : llvm::reverse(Args)) {
1463 // FIXME: arg->getIsOmitted() == "false" means we haven't implemented
1464 // any way to detect whether the argument was omitted.
1465 if (!arg->isOptional() || arg->getIsOmitted() == "false") {
1466 FoundNonOptArg = true;
1469 if (!TrailingOptArgs++)
1471 << " unsigned TrailingOmittedArgs = 0;\n";
1472 OS << " if (" << arg->getIsOmitted() << ")\n"
1473 << " ++TrailingOmittedArgs;\n";
1475 if (TrailingOptArgs)
1477 if (TrailingOptArgs < NonFakeArgs)
1479 else if (TrailingOptArgs)
1481 << " if (TrailingOmittedArgs < " << NonFakeArgs << ")\n"
1482 << " OS << \"(\";\n"
1484 unsigned ArgIndex = 0;
1485 for (const auto &arg : Args) {
1489 if (ArgIndex >= NonFakeArgs - TrailingOptArgs)
1491 << " if (" << ArgIndex << " < " << NonFakeArgs
1492 << " - TrailingOmittedArgs)\n"
1493 << " OS << \", \";\n"
1498 std::string IsOmitted = arg->getIsOmitted();
1499 if (arg->isOptional() && IsOmitted != "false")
1501 << " if (!(" << IsOmitted << ")) {\n"
1503 arg->writeValue(OS);
1504 if (arg->isOptional() && IsOmitted != "false")
1510 if (TrailingOptArgs < NonFakeArgs)
1512 else if (TrailingOptArgs)
1514 << " if (TrailingOmittedArgs < " << NonFakeArgs << ")\n"
1515 << " OS << \")\";\n"
1519 OS << Suffix + "\";\n";
1526 // End of the switch statement.
1528 // End of the print function.
1532 /// Return the index of a spelling in a spelling list.
1534 getSpellingListIndex(const std::vector<FlattenedSpelling> &SpellingList,
1535 const FlattenedSpelling &Spelling) {
1536 assert(!SpellingList.empty() && "Spelling list is empty!");
1538 for (unsigned Index = 0; Index < SpellingList.size(); ++Index) {
1539 const FlattenedSpelling &S = SpellingList[Index];
1540 if (S.variety() != Spelling.variety())
1542 if (S.nameSpace() != Spelling.nameSpace())
1544 if (S.name() != Spelling.name())
1550 llvm_unreachable("Unknown spelling!");
1553 static void writeAttrAccessorDefinition(const Record &R, raw_ostream &OS) {
1554 std::vector<Record*> Accessors = R.getValueAsListOfDefs("Accessors");
1555 if (Accessors.empty())
1558 const std::vector<FlattenedSpelling> SpellingList = GetFlattenedSpellings(R);
1559 assert(!SpellingList.empty() &&
1560 "Attribute with empty spelling list can't have accessors!");
1561 for (const auto *Accessor : Accessors) {
1562 const StringRef Name = Accessor->getValueAsString("Name");
1563 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(*Accessor);
1565 OS << " bool " << Name
1566 << "() const { return getAttributeSpellingListIndex() == ";
1567 for (unsigned Index = 0; Index < Spellings.size(); ++Index) {
1568 OS << getSpellingListIndex(SpellingList, Spellings[Index]);
1569 if (Index != Spellings.size() - 1)
1570 OS << " ||\n getAttributeSpellingListIndex() == ";
1578 SpellingNamesAreCommon(const std::vector<FlattenedSpelling>& Spellings) {
1579 assert(!Spellings.empty() && "An empty list of spellings was provided");
1580 std::string FirstName = NormalizeNameForSpellingComparison(
1581 Spellings.front().name());
1582 for (const auto &Spelling :
1583 llvm::make_range(std::next(Spellings.begin()), Spellings.end())) {
1584 std::string Name = NormalizeNameForSpellingComparison(Spelling.name());
1585 if (Name != FirstName)
1591 typedef std::map<unsigned, std::string> SemanticSpellingMap;
1593 CreateSemanticSpellings(const std::vector<FlattenedSpelling> &Spellings,
1594 SemanticSpellingMap &Map) {
1595 // The enumerants are automatically generated based on the variety,
1596 // namespace (if present) and name for each attribute spelling. However,
1597 // care is taken to avoid trampling on the reserved namespace due to
1599 std::string Ret(" enum Spelling {\n");
1600 std::set<std::string> Uniques;
1603 // If we have a need to have this many spellings we likely need to add an
1604 // extra bit to the SpellingIndex in AttributeCommonInfo, then increase the
1605 // value of SpellingNotCalculated there and here.
1606 assert(Spellings.size() < 15 &&
1607 "Too many spellings, would step on SpellingNotCalculated in "
1608 "AttributeCommonInfo");
1609 for (auto I = Spellings.begin(), E = Spellings.end(); I != E; ++I, ++Idx) {
1610 const FlattenedSpelling &S = *I;
1611 const std::string &Variety = S.variety();
1612 const std::string &Spelling = S.name();
1613 const std::string &Namespace = S.nameSpace();
1614 std::string EnumName;
1616 EnumName += (Variety + "_");
1617 if (!Namespace.empty())
1618 EnumName += (NormalizeNameForSpellingComparison(Namespace).str() +
1620 EnumName += NormalizeNameForSpellingComparison(Spelling);
1622 // Even if the name is not unique, this spelling index corresponds to a
1623 // particular enumerant name that we've calculated.
1624 Map[Idx] = EnumName;
1626 // Since we have been stripping underscores to avoid trampling on the
1627 // reserved namespace, we may have inadvertently created duplicate
1628 // enumerant names. These duplicates are not considered part of the
1629 // semantic spelling, and can be elided.
1630 if (Uniques.find(EnumName) != Uniques.end())
1633 Uniques.insert(EnumName);
1634 if (I != Spellings.begin())
1636 // Duplicate spellings are not considered part of the semantic spelling
1637 // enumeration, but the spelling index and semantic spelling values are
1638 // meant to be equivalent, so we must specify a concrete value for each
1640 Ret += " " + EnumName + " = " + llvm::utostr(Idx);
1642 Ret += ",\n SpellingNotCalculated = 15\n";
1647 void WriteSemanticSpellingSwitch(const std::string &VarName,
1648 const SemanticSpellingMap &Map,
1650 OS << " switch (" << VarName << ") {\n default: "
1651 << "llvm_unreachable(\"Unknown spelling list index\");\n";
1652 for (const auto &I : Map)
1653 OS << " case " << I.first << ": return " << I.second << ";\n";
1657 // Emits the LateParsed property for attributes.
1658 static void emitClangAttrLateParsedList(RecordKeeper &Records, raw_ostream &OS) {
1659 OS << "#if defined(CLANG_ATTR_LATE_PARSED_LIST)\n";
1660 std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr");
1662 for (const auto *Attr : Attrs) {
1663 bool LateParsed = Attr->getValueAsBit("LateParsed");
1666 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(*Attr);
1668 // FIXME: Handle non-GNU attributes
1669 for (const auto &I : Spellings) {
1670 if (I.variety() != "GNU")
1672 OS << ".Case(\"" << I.name() << "\", " << LateParsed << ")\n";
1676 OS << "#endif // CLANG_ATTR_LATE_PARSED_LIST\n\n";
1679 static bool hasGNUorCXX11Spelling(const Record &Attribute) {
1680 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(Attribute);
1681 for (const auto &I : Spellings) {
1682 if (I.variety() == "GNU" || I.variety() == "CXX11")
1690 struct AttributeSubjectMatchRule {
1691 const Record *MetaSubject;
1692 const Record *Constraint;
1694 AttributeSubjectMatchRule(const Record *MetaSubject, const Record *Constraint)
1695 : MetaSubject(MetaSubject), Constraint(Constraint) {
1696 assert(MetaSubject && "Missing subject");
1699 bool isSubRule() const { return Constraint != nullptr; }
1701 std::vector<Record *> getSubjects() const {
1702 return (Constraint ? Constraint : MetaSubject)
1703 ->getValueAsListOfDefs("Subjects");
1706 std::vector<Record *> getLangOpts() const {
1708 // Lookup the options in the sub-rule first, in case the sub-rule
1709 // overrides the rules options.
1710 std::vector<Record *> Opts = Constraint->getValueAsListOfDefs("LangOpts");
1714 return MetaSubject->getValueAsListOfDefs("LangOpts");
1717 // Abstract rules are used only for sub-rules
1718 bool isAbstractRule() const { return getSubjects().empty(); }
1720 StringRef getName() const {
1721 return (Constraint ? Constraint : MetaSubject)->getValueAsString("Name");
1724 bool isNegatedSubRule() const {
1725 assert(isSubRule() && "Not a sub-rule");
1726 return Constraint->getValueAsBit("Negated");
1729 std::string getSpelling() const {
1730 std::string Result = MetaSubject->getValueAsString("Name");
1733 if (isNegatedSubRule())
1734 Result += "unless(";
1735 Result += getName();
1736 if (isNegatedSubRule())
1743 std::string getEnumValueName() const {
1744 SmallString<128> Result;
1745 Result += "SubjectMatchRule_";
1746 Result += MetaSubject->getValueAsString("Name");
1749 if (isNegatedSubRule())
1751 Result += Constraint->getValueAsString("Name");
1753 if (isAbstractRule())
1754 Result += "_abstract";
1755 return Result.str();
1758 std::string getEnumValue() const { return "attr::" + getEnumValueName(); }
1760 static const char *EnumName;
1763 const char *AttributeSubjectMatchRule::EnumName = "attr::SubjectMatchRule";
1765 struct PragmaClangAttributeSupport {
1766 std::vector<AttributeSubjectMatchRule> Rules;
1768 class RuleOrAggregateRuleSet {
1769 std::vector<AttributeSubjectMatchRule> Rules;
1771 RuleOrAggregateRuleSet(ArrayRef<AttributeSubjectMatchRule> Rules,
1773 : Rules(Rules), IsRule(IsRule) {}
1776 bool isRule() const { return IsRule; }
1778 const AttributeSubjectMatchRule &getRule() const {
1779 assert(IsRule && "not a rule!");
1783 ArrayRef<AttributeSubjectMatchRule> getAggregateRuleSet() const {
1787 static RuleOrAggregateRuleSet
1788 getRule(const AttributeSubjectMatchRule &Rule) {
1789 return RuleOrAggregateRuleSet(Rule, /*IsRule=*/true);
1791 static RuleOrAggregateRuleSet
1792 getAggregateRuleSet(ArrayRef<AttributeSubjectMatchRule> Rules) {
1793 return RuleOrAggregateRuleSet(Rules, /*IsRule=*/false);
1796 llvm::DenseMap<const Record *, RuleOrAggregateRuleSet> SubjectsToRules;
1798 PragmaClangAttributeSupport(RecordKeeper &Records);
1800 bool isAttributedSupported(const Record &Attribute);
1802 void emitMatchRuleList(raw_ostream &OS);
1804 std::string generateStrictConformsTo(const Record &Attr, raw_ostream &OS);
1806 void generateParsingHelpers(raw_ostream &OS);
1809 } // end anonymous namespace
1811 static bool doesDeclDeriveFrom(const Record *D, const Record *Base) {
1812 const Record *CurrentBase = D->getValueAsOptionalDef(BaseFieldName);
1815 if (CurrentBase == Base)
1817 return doesDeclDeriveFrom(CurrentBase, Base);
1820 PragmaClangAttributeSupport::PragmaClangAttributeSupport(
1821 RecordKeeper &Records) {
1822 std::vector<Record *> MetaSubjects =
1823 Records.getAllDerivedDefinitions("AttrSubjectMatcherRule");
1824 auto MapFromSubjectsToRules = [this](const Record *SubjectContainer,
1825 const Record *MetaSubject,
1826 const Record *Constraint) {
1827 Rules.emplace_back(MetaSubject, Constraint);
1828 std::vector<Record *> ApplicableSubjects =
1829 SubjectContainer->getValueAsListOfDefs("Subjects");
1830 for (const auto *Subject : ApplicableSubjects) {
1833 .try_emplace(Subject, RuleOrAggregateRuleSet::getRule(
1834 AttributeSubjectMatchRule(MetaSubject,
1838 PrintFatalError("Attribute subject match rules should not represent"
1839 "same attribute subjects.");
1843 for (const auto *MetaSubject : MetaSubjects) {
1844 MapFromSubjectsToRules(MetaSubject, MetaSubject, /*Constraints=*/nullptr);
1845 std::vector<Record *> Constraints =
1846 MetaSubject->getValueAsListOfDefs("Constraints");
1847 for (const auto *Constraint : Constraints)
1848 MapFromSubjectsToRules(Constraint, MetaSubject, Constraint);
1851 std::vector<Record *> Aggregates =
1852 Records.getAllDerivedDefinitions("AttrSubjectMatcherAggregateRule");
1853 std::vector<Record *> DeclNodes =
1854 Records.getAllDerivedDefinitions(DeclNodeClassName);
1855 for (const auto *Aggregate : Aggregates) {
1856 Record *SubjectDecl = Aggregate->getValueAsDef("Subject");
1858 // Gather sub-classes of the aggregate subject that act as attribute
1860 std::vector<AttributeSubjectMatchRule> Rules;
1861 for (const auto *D : DeclNodes) {
1862 if (doesDeclDeriveFrom(D, SubjectDecl)) {
1863 auto It = SubjectsToRules.find(D);
1864 if (It == SubjectsToRules.end())
1866 if (!It->second.isRule() || It->second.getRule().isSubRule())
1867 continue; // Assume that the rule will be included as well.
1868 Rules.push_back(It->second.getRule());
1874 .try_emplace(SubjectDecl,
1875 RuleOrAggregateRuleSet::getAggregateRuleSet(Rules))
1878 PrintFatalError("Attribute subject match rules should not represent"
1879 "same attribute subjects.");
1884 static PragmaClangAttributeSupport &
1885 getPragmaAttributeSupport(RecordKeeper &Records) {
1886 static PragmaClangAttributeSupport Instance(Records);
1890 void PragmaClangAttributeSupport::emitMatchRuleList(raw_ostream &OS) {
1891 OS << "#ifndef ATTR_MATCH_SUB_RULE\n";
1892 OS << "#define ATTR_MATCH_SUB_RULE(Value, Spelling, IsAbstract, Parent, "
1894 << "ATTR_MATCH_RULE(Value, Spelling, IsAbstract)\n";
1896 for (const auto &Rule : Rules) {
1897 OS << (Rule.isSubRule() ? "ATTR_MATCH_SUB_RULE" : "ATTR_MATCH_RULE") << '(';
1898 OS << Rule.getEnumValueName() << ", \"" << Rule.getSpelling() << "\", "
1899 << Rule.isAbstractRule();
1900 if (Rule.isSubRule())
1902 << AttributeSubjectMatchRule(Rule.MetaSubject, nullptr).getEnumValue()
1903 << ", " << Rule.isNegatedSubRule();
1906 OS << "#undef ATTR_MATCH_SUB_RULE\n";
1909 bool PragmaClangAttributeSupport::isAttributedSupported(
1910 const Record &Attribute) {
1911 // If the attribute explicitly specified whether to support #pragma clang
1912 // attribute, use that setting.
1914 bool SpecifiedResult =
1915 Attribute.getValueAsBitOrUnset("PragmaAttributeSupport", Unset);
1917 return SpecifiedResult;
1920 // An attribute requires delayed parsing (LateParsed is on)
1921 if (Attribute.getValueAsBit("LateParsed"))
1923 // An attribute has no GNU/CXX11 spelling
1924 if (!hasGNUorCXX11Spelling(Attribute))
1926 // An attribute subject list has a subject that isn't covered by one of the
1927 // subject match rules or has no subjects at all.
1928 if (Attribute.isValueUnset("Subjects"))
1930 const Record *SubjectObj = Attribute.getValueAsDef("Subjects");
1931 std::vector<Record *> Subjects = SubjectObj->getValueAsListOfDefs("Subjects");
1932 if (Subjects.empty())
1934 for (const auto *Subject : Subjects) {
1935 if (SubjectsToRules.find(Subject) == SubjectsToRules.end())
1941 static std::string GenerateTestExpression(ArrayRef<Record *> LangOpts) {
1944 for (auto *E : LangOpts) {
1948 const StringRef Code = E->getValueAsString("CustomCode");
1949 if (!Code.empty()) {
1954 Test += "LangOpts.";
1955 Test += E->getValueAsString("Name");
1966 PragmaClangAttributeSupport::generateStrictConformsTo(const Record &Attr,
1968 if (!isAttributedSupported(Attr))
1970 // Generate a function that constructs a set of matching rules that describe
1971 // to which declarations the attribute should apply to.
1972 std::string FnName = "matchRulesFor" + Attr.getName().str();
1973 OS << "static void " << FnName << "(llvm::SmallVectorImpl<std::pair<"
1974 << AttributeSubjectMatchRule::EnumName
1975 << ", bool>> &MatchRules, const LangOptions &LangOpts) {\n";
1976 if (Attr.isValueUnset("Subjects")) {
1980 const Record *SubjectObj = Attr.getValueAsDef("Subjects");
1981 std::vector<Record *> Subjects = SubjectObj->getValueAsListOfDefs("Subjects");
1982 for (const auto *Subject : Subjects) {
1983 auto It = SubjectsToRules.find(Subject);
1984 assert(It != SubjectsToRules.end() &&
1985 "This attribute is unsupported by #pragma clang attribute");
1986 for (const auto &Rule : It->getSecond().getAggregateRuleSet()) {
1987 // The rule might be language specific, so only subtract it from the given
1988 // rules if the specific language options are specified.
1989 std::vector<Record *> LangOpts = Rule.getLangOpts();
1990 OS << " MatchRules.push_back(std::make_pair(" << Rule.getEnumValue()
1991 << ", /*IsSupported=*/" << GenerateTestExpression(LangOpts)
1999 void PragmaClangAttributeSupport::generateParsingHelpers(raw_ostream &OS) {
2000 // Generate routines that check the names of sub-rules.
2001 OS << "Optional<attr::SubjectMatchRule> "
2002 "defaultIsAttributeSubjectMatchSubRuleFor(StringRef, bool) {\n";
2003 OS << " return None;\n";
2006 std::map<const Record *, std::vector<AttributeSubjectMatchRule>>
2008 for (const auto &Rule : Rules) {
2009 if (!Rule.isSubRule())
2011 SubMatchRules[Rule.MetaSubject].push_back(Rule);
2014 for (const auto &SubMatchRule : SubMatchRules) {
2015 OS << "Optional<attr::SubjectMatchRule> isAttributeSubjectMatchSubRuleFor_"
2016 << SubMatchRule.first->getValueAsString("Name")
2017 << "(StringRef Name, bool IsUnless) {\n";
2018 OS << " if (IsUnless)\n";
2020 "llvm::StringSwitch<Optional<attr::SubjectMatchRule>>(Name).\n";
2021 for (const auto &Rule : SubMatchRule.second) {
2022 if (Rule.isNegatedSubRule())
2023 OS << " Case(\"" << Rule.getName() << "\", " << Rule.getEnumValue()
2026 OS << " Default(None);\n";
2028 "llvm::StringSwitch<Optional<attr::SubjectMatchRule>>(Name).\n";
2029 for (const auto &Rule : SubMatchRule.second) {
2030 if (!Rule.isNegatedSubRule())
2031 OS << " Case(\"" << Rule.getName() << "\", " << Rule.getEnumValue()
2034 OS << " Default(None);\n";
2038 // Generate the function that checks for the top-level rules.
2039 OS << "std::pair<Optional<attr::SubjectMatchRule>, "
2040 "Optional<attr::SubjectMatchRule> (*)(StringRef, "
2041 "bool)> isAttributeSubjectMatchRule(StringRef Name) {\n";
2043 "llvm::StringSwitch<std::pair<Optional<attr::SubjectMatchRule>, "
2044 "Optional<attr::SubjectMatchRule> (*) (StringRef, "
2046 for (const auto &Rule : Rules) {
2047 if (Rule.isSubRule())
2049 std::string SubRuleFunction;
2050 if (SubMatchRules.count(Rule.MetaSubject))
2052 ("isAttributeSubjectMatchSubRuleFor_" + Rule.getName()).str();
2054 SubRuleFunction = "defaultIsAttributeSubjectMatchSubRuleFor";
2055 OS << " Case(\"" << Rule.getName() << "\", std::make_pair("
2056 << Rule.getEnumValue() << ", " << SubRuleFunction << ")).\n";
2058 OS << " Default(std::make_pair(None, "
2059 "defaultIsAttributeSubjectMatchSubRuleFor));\n";
2062 // Generate the function that checks for the submatch rules.
2063 OS << "const char *validAttributeSubjectMatchSubRules("
2064 << AttributeSubjectMatchRule::EnumName << " Rule) {\n";
2065 OS << " switch (Rule) {\n";
2066 for (const auto &SubMatchRule : SubMatchRules) {
2068 << AttributeSubjectMatchRule(SubMatchRule.first, nullptr).getEnumValue()
2070 OS << " return \"'";
2071 bool IsFirst = true;
2072 for (const auto &Rule : SubMatchRule.second) {
2076 if (Rule.isNegatedSubRule())
2078 OS << Rule.getName();
2079 if (Rule.isNegatedSubRule())
2085 OS << " default: return nullptr;\n";
2090 template <typename Fn>
2091 static void forEachUniqueSpelling(const Record &Attr, Fn &&F) {
2092 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(Attr);
2093 SmallDenseSet<StringRef, 8> Seen;
2094 for (const FlattenedSpelling &S : Spellings) {
2095 if (Seen.insert(S.name()).second)
2100 /// Emits the first-argument-is-type property for attributes.
2101 static void emitClangAttrTypeArgList(RecordKeeper &Records, raw_ostream &OS) {
2102 OS << "#if defined(CLANG_ATTR_TYPE_ARG_LIST)\n";
2103 std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
2105 for (const auto *Attr : Attrs) {
2106 // Determine whether the first argument is a type.
2107 std::vector<Record *> Args = Attr->getValueAsListOfDefs("Args");
2111 if (Args[0]->getSuperClasses().back().first->getName() != "TypeArgument")
2114 // All these spellings take a single type argument.
2115 forEachUniqueSpelling(*Attr, [&](const FlattenedSpelling &S) {
2116 OS << ".Case(\"" << S.name() << "\", " << "true" << ")\n";
2119 OS << "#endif // CLANG_ATTR_TYPE_ARG_LIST\n\n";
2122 /// Emits the parse-arguments-in-unevaluated-context property for
2124 static void emitClangAttrArgContextList(RecordKeeper &Records, raw_ostream &OS) {
2125 OS << "#if defined(CLANG_ATTR_ARG_CONTEXT_LIST)\n";
2126 ParsedAttrMap Attrs = getParsedAttrList(Records);
2127 for (const auto &I : Attrs) {
2128 const Record &Attr = *I.second;
2130 if (!Attr.getValueAsBit("ParseArgumentsAsUnevaluated"))
2133 // All these spellings take are parsed unevaluated.
2134 forEachUniqueSpelling(Attr, [&](const FlattenedSpelling &S) {
2135 OS << ".Case(\"" << S.name() << "\", " << "true" << ")\n";
2138 OS << "#endif // CLANG_ATTR_ARG_CONTEXT_LIST\n\n";
2141 static bool isIdentifierArgument(Record *Arg) {
2142 return !Arg->getSuperClasses().empty() &&
2143 llvm::StringSwitch<bool>(Arg->getSuperClasses().back().first->getName())
2144 .Case("IdentifierArgument", true)
2145 .Case("EnumArgument", true)
2146 .Case("VariadicEnumArgument", true)
2150 static bool isVariadicIdentifierArgument(Record *Arg) {
2151 return !Arg->getSuperClasses().empty() &&
2152 llvm::StringSwitch<bool>(
2153 Arg->getSuperClasses().back().first->getName())
2154 .Case("VariadicIdentifierArgument", true)
2155 .Case("VariadicParamOrParamIdxArgument", true)
2159 static void emitClangAttrVariadicIdentifierArgList(RecordKeeper &Records,
2161 OS << "#if defined(CLANG_ATTR_VARIADIC_IDENTIFIER_ARG_LIST)\n";
2162 std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
2163 for (const auto *A : Attrs) {
2164 // Determine whether the first argument is a variadic identifier.
2165 std::vector<Record *> Args = A->getValueAsListOfDefs("Args");
2166 if (Args.empty() || !isVariadicIdentifierArgument(Args[0]))
2169 // All these spellings take an identifier argument.
2170 forEachUniqueSpelling(*A, [&](const FlattenedSpelling &S) {
2171 OS << ".Case(\"" << S.name() << "\", "
2176 OS << "#endif // CLANG_ATTR_VARIADIC_IDENTIFIER_ARG_LIST\n\n";
2179 // Emits the first-argument-is-identifier property for attributes.
2180 static void emitClangAttrIdentifierArgList(RecordKeeper &Records, raw_ostream &OS) {
2181 OS << "#if defined(CLANG_ATTR_IDENTIFIER_ARG_LIST)\n";
2182 std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr");
2184 for (const auto *Attr : Attrs) {
2185 // Determine whether the first argument is an identifier.
2186 std::vector<Record *> Args = Attr->getValueAsListOfDefs("Args");
2187 if (Args.empty() || !isIdentifierArgument(Args[0]))
2190 // All these spellings take an identifier argument.
2191 forEachUniqueSpelling(*Attr, [&](const FlattenedSpelling &S) {
2192 OS << ".Case(\"" << S.name() << "\", " << "true" << ")\n";
2195 OS << "#endif // CLANG_ATTR_IDENTIFIER_ARG_LIST\n\n";
2198 static bool keywordThisIsaIdentifierInArgument(const Record *Arg) {
2199 return !Arg->getSuperClasses().empty() &&
2200 llvm::StringSwitch<bool>(
2201 Arg->getSuperClasses().back().first->getName())
2202 .Case("VariadicParamOrParamIdxArgument", true)
2206 static void emitClangAttrThisIsaIdentifierArgList(RecordKeeper &Records,
2208 OS << "#if defined(CLANG_ATTR_THIS_ISA_IDENTIFIER_ARG_LIST)\n";
2209 std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
2210 for (const auto *A : Attrs) {
2211 // Determine whether the first argument is a variadic identifier.
2212 std::vector<Record *> Args = A->getValueAsListOfDefs("Args");
2213 if (Args.empty() || !keywordThisIsaIdentifierInArgument(Args[0]))
2216 // All these spellings take an identifier argument.
2217 forEachUniqueSpelling(*A, [&](const FlattenedSpelling &S) {
2218 OS << ".Case(\"" << S.name() << "\", "
2223 OS << "#endif // CLANG_ATTR_THIS_ISA_IDENTIFIER_ARG_LIST\n\n";
2226 // Emits the class definitions for attributes.
2227 void clang::EmitClangAttrClass(RecordKeeper &Records, raw_ostream &OS) {
2228 emitSourceFileHeader("Attribute classes' definitions", OS);
2230 OS << "#ifndef LLVM_CLANG_ATTR_CLASSES_INC\n";
2231 OS << "#define LLVM_CLANG_ATTR_CLASSES_INC\n\n";
2233 std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr");
2234 ParsedAttrMap AttrMap = getParsedAttrList(Records);
2236 for (const auto *Attr : Attrs) {
2237 const Record &R = *Attr;
2239 // FIXME: Currently, documentation is generated as-needed due to the fact
2240 // that there is no way to allow a generated project "reach into" the docs
2241 // directory (for instance, it may be an out-of-tree build). However, we want
2242 // to ensure that every attribute has a Documentation field, and produce an
2243 // error if it has been neglected. Otherwise, the on-demand generation which
2244 // happens server-side will fail. This code is ensuring that functionality,
2245 // even though this Emitter doesn't technically need the documentation.
2246 // When attribute documentation can be generated as part of the build
2247 // itself, this code can be removed.
2248 (void)R.getValueAsListOfDefs("Documentation");
2250 if (!R.getValueAsBit("ASTNode"))
2253 ArrayRef<std::pair<Record *, SMRange>> Supers = R.getSuperClasses();
2254 assert(!Supers.empty() && "Forgot to specify a superclass for the attr");
2255 std::string SuperName;
2256 bool Inheritable = false;
2257 for (const auto &Super : llvm::reverse(Supers)) {
2258 const Record *R = Super.first;
2259 if (R->getName() != "TargetSpecificAttr" &&
2260 R->getName() != "DeclOrTypeAttr" && SuperName.empty())
2261 SuperName = R->getName();
2262 if (R->getName() == "InheritableAttr")
2266 OS << "class " << R.getName() << "Attr : public " << SuperName << " {\n";
2268 std::vector<Record*> ArgRecords = R.getValueAsListOfDefs("Args");
2269 std::vector<std::unique_ptr<Argument>> Args;
2270 Args.reserve(ArgRecords.size());
2272 bool HasOptArg = false;
2273 bool HasFakeArg = false;
2274 for (const auto *ArgRecord : ArgRecords) {
2275 Args.emplace_back(createArgument(*ArgRecord, R.getName()));
2276 Args.back()->writeDeclarations(OS);
2279 // For these purposes, fake takes priority over optional.
2280 if (Args.back()->isFake()) {
2282 } else if (Args.back()->isOptional()) {
2289 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(R);
2291 // If there are zero or one spellings, all spelling-related functionality
2292 // can be elided. If all of the spellings share the same name, the spelling
2293 // functionality can also be elided.
2294 bool ElideSpelling = (Spellings.size() <= 1) ||
2295 SpellingNamesAreCommon(Spellings);
2297 // This maps spelling index values to semantic Spelling enumerants.
2298 SemanticSpellingMap SemanticToSyntacticMap;
2301 OS << CreateSemanticSpellings(Spellings, SemanticToSyntacticMap);
2303 const auto &ParsedAttrSpellingItr = llvm::find_if(
2304 AttrMap, [R](const std::pair<std::string, const Record *> &P) {
2305 return &R == P.second;
2308 // Emit CreateImplicit factory methods.
2309 auto emitCreate = [&](bool Implicit, bool emitFake) {
2310 OS << " static " << R.getName() << "Attr *Create";
2314 OS << "ASTContext &Ctx";
2315 for (auto const &ai : Args) {
2316 if (ai->isFake() && !emitFake) continue;
2318 ai->writeCtorParameters(OS);
2320 OS << ", const AttributeCommonInfo &CommonInfo = {SourceRange{}}) {\n";
2321 OS << " auto *A = new (Ctx) " << R.getName();
2322 OS << "Attr(Ctx, CommonInfo";
2323 for (auto const &ai : Args) {
2324 if (ai->isFake() && !emitFake) continue;
2326 ai->writeImplicitCtorArgs(OS);
2330 OS << " A->setImplicit(true);\n";
2332 if (Implicit || ElideSpelling) {
2333 OS << " if (!A->isAttributeSpellingListCalculated() && "
2334 "!A->getAttrName())\n";
2335 OS << " A->setAttributeSpellingListIndex(0);\n";
2337 OS << " return A;\n }\n\n";
2340 auto emitCreateNoCI = [&](bool Implicit, bool emitFake) {
2341 OS <<" static " << R.getName() << "Attr *Create";
2345 OS << "ASTContext &Ctx";
2346 for (auto const &ai : Args) {
2347 if (ai->isFake() && !emitFake) continue;
2349 ai->writeCtorParameters(OS);
2351 OS << ", SourceRange Range, AttributeCommonInfo::Syntax Syntax";
2353 OS << ", " << R.getName()
2354 << "Attr::Spelling S = "
2355 "static_cast<Spelling>(SpellingNotCalculated)";
2357 OS << " AttributeCommonInfo I(Range, ";
2359 if (ParsedAttrSpellingItr != std::end(AttrMap))
2360 OS << "AT_" << ParsedAttrSpellingItr->first;
2362 OS << "NoSemaHandlerAttribute";
2368 OS << " return Create";
2372 for (auto const &ai : Args) {
2373 if (ai->isFake() && !emitFake) continue;
2375 ai->writeImplicitCtorArgs(OS);
2381 auto emitCreates = [&](bool emitFake) {
2382 emitCreate(true, emitFake);
2383 emitCreate(false, emitFake);
2384 emitCreateNoCI(true, emitFake);
2385 emitCreateNoCI(false, emitFake);
2388 // Emit a CreateImplicit that takes all the arguments.
2391 // Emit a CreateImplicit that takes all the non-fake arguments.
2395 // Emit constructors.
2396 auto emitCtor = [&](bool emitOpt, bool emitFake) {
2397 auto shouldEmitArg = [=](const std::unique_ptr<Argument> &arg) {
2398 if (arg->isFake()) return emitFake;
2399 if (arg->isOptional()) return emitOpt;
2402 OS << " " << R.getName()
2403 << "Attr(ASTContext &Ctx, const AttributeCommonInfo &CommonInfo";
2405 for (auto const &ai : Args) {
2406 if (!shouldEmitArg(ai)) continue;
2408 ai->writeCtorParameters(OS);
2413 OS << " : " << SuperName << "(Ctx, CommonInfo, ";
2414 OS << "attr::" << R.getName() << ", "
2415 << (R.getValueAsBit("LateParsed") ? "true" : "false");
2418 << (R.getValueAsBit("InheritEvenIfAlreadyPresent") ? "true"
2423 for (auto const &ai : Args) {
2425 if (!shouldEmitArg(ai)) {
2426 ai->writeCtorDefaultInitializers(OS);
2428 ai->writeCtorInitializers(OS);
2435 for (auto const &ai : Args) {
2436 if (!shouldEmitArg(ai)) continue;
2437 ai->writeCtorBody(OS);
2442 // Emit a constructor that includes all the arguments.
2443 // This is necessary for cloning.
2444 emitCtor(true, true);
2446 // Emit a constructor that takes all the non-fake arguments.
2448 emitCtor(true, false);
2450 // Emit a constructor that takes all the non-fake, non-optional arguments.
2452 emitCtor(false, false);
2454 OS << " " << R.getName() << "Attr *clone(ASTContext &C) const;\n";
2455 OS << " void printPretty(raw_ostream &OS,\n"
2456 << " const PrintingPolicy &Policy) const;\n";
2457 OS << " const char *getSpelling() const;\n";
2459 if (!ElideSpelling) {
2460 assert(!SemanticToSyntacticMap.empty() && "Empty semantic mapping list");
2461 OS << " Spelling getSemanticSpelling() const {\n";
2462 WriteSemanticSpellingSwitch("getAttributeSpellingListIndex()",
2463 SemanticToSyntacticMap, OS);
2467 writeAttrAccessorDefinition(R, OS);
2469 for (auto const &ai : Args) {
2470 ai->writeAccessors(OS);
2473 // Don't write conversion routines for fake arguments.
2474 if (ai->isFake()) continue;
2476 if (ai->isEnumArg())
2477 static_cast<const EnumArgument *>(ai.get())->writeConversion(OS);
2478 else if (ai->isVariadicEnumArg())
2479 static_cast<const VariadicEnumArgument *>(ai.get())
2480 ->writeConversion(OS);
2483 OS << R.getValueAsString("AdditionalMembers");
2486 OS << " static bool classof(const Attr *A) { return A->getKind() == "
2487 << "attr::" << R.getName() << "; }\n";
2492 OS << "#endif // LLVM_CLANG_ATTR_CLASSES_INC\n";
2495 // Emits the class method definitions for attributes.
2496 void clang::EmitClangAttrImpl(RecordKeeper &Records, raw_ostream &OS) {
2497 emitSourceFileHeader("Attribute classes' member function definitions", OS);
2499 std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr");
2501 for (auto *Attr : Attrs) {
2504 if (!R.getValueAsBit("ASTNode"))
2507 std::vector<Record*> ArgRecords = R.getValueAsListOfDefs("Args");
2508 std::vector<std::unique_ptr<Argument>> Args;
2509 for (const auto *Arg : ArgRecords)
2510 Args.emplace_back(createArgument(*Arg, R.getName()));
2512 for (auto const &ai : Args)
2513 ai->writeAccessorDefinitions(OS);
2515 OS << R.getName() << "Attr *" << R.getName()
2516 << "Attr::clone(ASTContext &C) const {\n";
2517 OS << " auto *A = new (C) " << R.getName() << "Attr(C, *this";
2518 for (auto const &ai : Args) {
2520 ai->writeCloneArgs(OS);
2523 OS << " A->Inherited = Inherited;\n";
2524 OS << " A->IsPackExpansion = IsPackExpansion;\n";
2525 OS << " A->setImplicit(Implicit);\n";
2526 OS << " return A;\n}\n\n";
2528 writePrettyPrintFunction(R, Args, OS);
2529 writeGetSpellingFunction(R, OS);
2532 // Instead of relying on virtual dispatch we just create a huge dispatch
2533 // switch. This is both smaller and faster than virtual functions.
2534 auto EmitFunc = [&](const char *Method) {
2535 OS << " switch (getKind()) {\n";
2536 for (const auto *Attr : Attrs) {
2537 const Record &R = *Attr;
2538 if (!R.getValueAsBit("ASTNode"))
2541 OS << " case attr::" << R.getName() << ":\n";
2542 OS << " return cast<" << R.getName() << "Attr>(this)->" << Method
2546 OS << " llvm_unreachable(\"Unexpected attribute kind!\");\n";
2550 OS << "const char *Attr::getSpelling() const {\n";
2551 EmitFunc("getSpelling()");
2553 OS << "Attr *Attr::clone(ASTContext &C) const {\n";
2554 EmitFunc("clone(C)");
2556 OS << "void Attr::printPretty(raw_ostream &OS, "
2557 "const PrintingPolicy &Policy) const {\n";
2558 EmitFunc("printPretty(OS, Policy)");
2561 static void emitAttrList(raw_ostream &OS, StringRef Class,
2562 const std::vector<Record*> &AttrList) {
2563 for (auto Cur : AttrList) {
2564 OS << Class << "(" << Cur->getName() << ")\n";
2568 // Determines if an attribute has a Pragma spelling.
2569 static bool AttrHasPragmaSpelling(const Record *R) {
2570 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(*R);
2571 return llvm::find_if(Spellings, [](const FlattenedSpelling &S) {
2572 return S.variety() == "Pragma";
2573 }) != Spellings.end();
2578 struct AttrClassDescriptor {
2579 const char * const MacroName;
2580 const char * const TableGenName;
2583 } // end anonymous namespace
2585 static const AttrClassDescriptor AttrClassDescriptors[] = {
2587 { "TYPE_ATTR", "TypeAttr" },
2588 { "STMT_ATTR", "StmtAttr" },
2589 { "INHERITABLE_ATTR", "InheritableAttr" },
2590 { "DECL_OR_TYPE_ATTR", "DeclOrTypeAttr" },
2591 { "INHERITABLE_PARAM_ATTR", "InheritableParamAttr" },
2592 { "PARAMETER_ABI_ATTR", "ParameterABIAttr" }
2595 static void emitDefaultDefine(raw_ostream &OS, StringRef name,
2596 const char *superName) {
2597 OS << "#ifndef " << name << "\n";
2598 OS << "#define " << name << "(NAME) ";
2599 if (superName) OS << superName << "(NAME)";
2600 OS << "\n#endif\n\n";
2605 /// A class of attributes.
2607 const AttrClassDescriptor &Descriptor;
2609 AttrClass *SuperClass = nullptr;
2610 std::vector<AttrClass*> SubClasses;
2611 std::vector<Record*> Attrs;
2613 AttrClass(const AttrClassDescriptor &Descriptor, Record *R)
2614 : Descriptor(Descriptor), TheRecord(R) {}
2616 void emitDefaultDefines(raw_ostream &OS) const {
2617 // Default the macro unless this is a root class (i.e. Attr).
2619 emitDefaultDefine(OS, Descriptor.MacroName,
2620 SuperClass->Descriptor.MacroName);
2624 void emitUndefs(raw_ostream &OS) const {
2625 OS << "#undef " << Descriptor.MacroName << "\n";
2628 void emitAttrList(raw_ostream &OS) const {
2629 for (auto SubClass : SubClasses) {
2630 SubClass->emitAttrList(OS);
2633 ::emitAttrList(OS, Descriptor.MacroName, Attrs);
2636 void classifyAttrOnRoot(Record *Attr) {
2637 bool result = classifyAttr(Attr);
2638 assert(result && "failed to classify on root"); (void) result;
2641 void emitAttrRange(raw_ostream &OS) const {
2642 OS << "ATTR_RANGE(" << Descriptor.TableGenName
2643 << ", " << getFirstAttr()->getName()
2644 << ", " << getLastAttr()->getName() << ")\n";
2648 bool classifyAttr(Record *Attr) {
2649 // Check all the subclasses.
2650 for (auto SubClass : SubClasses) {
2651 if (SubClass->classifyAttr(Attr))
2655 // It's not more specific than this class, but it might still belong here.
2656 if (Attr->isSubClassOf(TheRecord)) {
2657 Attrs.push_back(Attr);
2664 Record *getFirstAttr() const {
2665 if (!SubClasses.empty())
2666 return SubClasses.front()->getFirstAttr();
2667 return Attrs.front();
2670 Record *getLastAttr() const {
2672 return Attrs.back();
2673 return SubClasses.back()->getLastAttr();
2677 /// The entire hierarchy of attribute classes.
2678 class AttrClassHierarchy {
2679 std::vector<std::unique_ptr<AttrClass>> Classes;
2682 AttrClassHierarchy(RecordKeeper &Records) {
2683 // Find records for all the classes.
2684 for (auto &Descriptor : AttrClassDescriptors) {
2685 Record *ClassRecord = Records.getClass(Descriptor.TableGenName);
2686 AttrClass *Class = new AttrClass(Descriptor, ClassRecord);
2687 Classes.emplace_back(Class);
2690 // Link up the hierarchy.
2691 for (auto &Class : Classes) {
2692 if (AttrClass *SuperClass = findSuperClass(Class->TheRecord)) {
2693 Class->SuperClass = SuperClass;
2694 SuperClass->SubClasses.push_back(Class.get());
2699 for (auto i = Classes.begin(), e = Classes.end(); i != e; ++i) {
2700 assert((i == Classes.begin()) == ((*i)->SuperClass == nullptr) &&
2701 "only the first class should be a root class!");
2706 void emitDefaultDefines(raw_ostream &OS) const {
2707 for (auto &Class : Classes) {
2708 Class->emitDefaultDefines(OS);
2712 void emitUndefs(raw_ostream &OS) const {
2713 for (auto &Class : Classes) {
2714 Class->emitUndefs(OS);
2718 void emitAttrLists(raw_ostream &OS) const {
2719 // Just start from the root class.
2720 Classes[0]->emitAttrList(OS);
2723 void emitAttrRanges(raw_ostream &OS) const {
2724 for (auto &Class : Classes)
2725 Class->emitAttrRange(OS);
2728 void classifyAttr(Record *Attr) {
2729 // Add the attribute to the root class.
2730 Classes[0]->classifyAttrOnRoot(Attr);
2734 AttrClass *findClassByRecord(Record *R) const {
2735 for (auto &Class : Classes) {
2736 if (Class->TheRecord == R)
2742 AttrClass *findSuperClass(Record *R) const {
2743 // TableGen flattens the superclass list, so we just need to walk it
2745 auto SuperClasses = R->getSuperClasses();
2746 for (signed i = 0, e = SuperClasses.size(); i != e; ++i) {
2747 auto SuperClass = findClassByRecord(SuperClasses[e - i - 1].first);
2748 if (SuperClass) return SuperClass;
2754 } // end anonymous namespace
2758 // Emits the enumeration list for attributes.
2759 void EmitClangAttrList(RecordKeeper &Records, raw_ostream &OS) {
2760 emitSourceFileHeader("List of all attributes that Clang recognizes", OS);
2762 AttrClassHierarchy Hierarchy(Records);
2764 // Add defaulting macro definitions.
2765 Hierarchy.emitDefaultDefines(OS);
2766 emitDefaultDefine(OS, "PRAGMA_SPELLING_ATTR", nullptr);
2768 std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
2769 std::vector<Record *> PragmaAttrs;
2770 for (auto *Attr : Attrs) {
2771 if (!Attr->getValueAsBit("ASTNode"))
2774 // Add the attribute to the ad-hoc groups.
2775 if (AttrHasPragmaSpelling(Attr))
2776 PragmaAttrs.push_back(Attr);
2778 // Place it in the hierarchy.
2779 Hierarchy.classifyAttr(Attr);
2782 // Emit the main attribute list.
2783 Hierarchy.emitAttrLists(OS);
2785 // Emit the ad hoc groups.
2786 emitAttrList(OS, "PRAGMA_SPELLING_ATTR", PragmaAttrs);
2788 // Emit the attribute ranges.
2789 OS << "#ifdef ATTR_RANGE\n";
2790 Hierarchy.emitAttrRanges(OS);
2791 OS << "#undef ATTR_RANGE\n";
2794 Hierarchy.emitUndefs(OS);
2795 OS << "#undef PRAGMA_SPELLING_ATTR\n";
2798 // Emits the enumeration list for attributes.
2799 void EmitClangAttrSubjectMatchRuleList(RecordKeeper &Records, raw_ostream &OS) {
2800 emitSourceFileHeader(
2801 "List of all attribute subject matching rules that Clang recognizes", OS);
2802 PragmaClangAttributeSupport &PragmaAttributeSupport =
2803 getPragmaAttributeSupport(Records);
2804 emitDefaultDefine(OS, "ATTR_MATCH_RULE", nullptr);
2805 PragmaAttributeSupport.emitMatchRuleList(OS);
2806 OS << "#undef ATTR_MATCH_RULE\n";
2809 // Emits the code to read an attribute from a precompiled header.
2810 void EmitClangAttrPCHRead(RecordKeeper &Records, raw_ostream &OS) {
2811 emitSourceFileHeader("Attribute deserialization code", OS);
2813 Record *InhClass = Records.getClass("InheritableAttr");
2814 std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr"),
2816 std::vector<std::unique_ptr<Argument>> Args;
2818 OS << " switch (Kind) {\n";
2819 for (const auto *Attr : Attrs) {
2820 const Record &R = *Attr;
2821 if (!R.getValueAsBit("ASTNode"))
2824 OS << " case attr::" << R.getName() << ": {\n";
2825 if (R.isSubClassOf(InhClass))
2826 OS << " bool isInherited = Record.readInt();\n";
2827 OS << " bool isImplicit = Record.readInt();\n";
2828 OS << " bool isPackExpansion = Record.readInt();\n";
2829 ArgRecords = R.getValueAsListOfDefs("Args");
2831 for (const auto *Arg : ArgRecords) {
2832 Args.emplace_back(createArgument(*Arg, R.getName()));
2833 Args.back()->writePCHReadDecls(OS);
2835 OS << " New = new (Context) " << R.getName() << "Attr(Context, Info";
2836 for (auto const &ri : Args) {
2838 ri->writePCHReadArgs(OS);
2841 if (R.isSubClassOf(InhClass))
2842 OS << " cast<InheritableAttr>(New)->setInherited(isInherited);\n";
2843 OS << " New->setImplicit(isImplicit);\n";
2844 OS << " New->setPackExpansion(isPackExpansion);\n";
2851 // Emits the code to write an attribute to a precompiled header.
2852 void EmitClangAttrPCHWrite(RecordKeeper &Records, raw_ostream &OS) {
2853 emitSourceFileHeader("Attribute serialization code", OS);
2855 Record *InhClass = Records.getClass("InheritableAttr");
2856 std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr"), Args;
2858 OS << " switch (A->getKind()) {\n";
2859 for (const auto *Attr : Attrs) {
2860 const Record &R = *Attr;
2861 if (!R.getValueAsBit("ASTNode"))
2863 OS << " case attr::" << R.getName() << ": {\n";
2864 Args = R.getValueAsListOfDefs("Args");
2865 if (R.isSubClassOf(InhClass) || !Args.empty())
2866 OS << " const auto *SA = cast<" << R.getName()
2868 if (R.isSubClassOf(InhClass))
2869 OS << " Record.push_back(SA->isInherited());\n";
2870 OS << " Record.push_back(A->isImplicit());\n";
2871 OS << " Record.push_back(A->isPackExpansion());\n";
2873 for (const auto *Arg : Args)
2874 createArgument(*Arg, R.getName())->writePCHWrite(OS);
2881 // Helper function for GenerateTargetSpecificAttrChecks that alters the 'Test'
2882 // parameter with only a single check type, if applicable.
2883 static bool GenerateTargetSpecificAttrCheck(const Record *R, std::string &Test,
2884 std::string *FnName,
2886 StringRef CheckAgainst,
2888 if (!R->isValueUnset(ListName)) {
2890 std::vector<StringRef> Items = R->getValueAsListOfStrings(ListName);
2891 for (auto I = Items.begin(), E = Items.end(); I != E; ++I) {
2892 StringRef Part = *I;
2893 Test += CheckAgainst;
2908 // Generate a conditional expression to check if the current target satisfies
2909 // the conditions for a TargetSpecificAttr record, and append the code for
2910 // those checks to the Test string. If the FnName string pointer is non-null,
2911 // append a unique suffix to distinguish this set of target checks from other
2912 // TargetSpecificAttr records.
2913 static bool GenerateTargetSpecificAttrChecks(const Record *R,
2914 std::vector<StringRef> &Arches,
2916 std::string *FnName) {
2917 bool AnyTargetChecks = false;
2919 // It is assumed that there will be an llvm::Triple object
2920 // named "T" and a TargetInfo object named "Target" within
2921 // scope that can be used to determine whether the attribute exists in
2924 // If one or more architectures is specified, check those. Arches are handled
2925 // differently because GenerateTargetRequirements needs to combine the list
2927 if (!Arches.empty()) {
2928 AnyTargetChecks = true;
2930 for (auto I = Arches.begin(), E = Arches.end(); I != E; ++I) {
2931 StringRef Part = *I;
2932 Test += "T.getArch() == llvm::Triple::";
2942 // If the attribute is specific to particular OSes, check those.
2943 AnyTargetChecks |= GenerateTargetSpecificAttrCheck(
2944 R, Test, FnName, "OSes", "T.getOS()", "llvm::Triple::");
2946 // If one or more object formats is specified, check those.
2948 GenerateTargetSpecificAttrCheck(R, Test, FnName, "ObjectFormats",
2949 "T.getObjectFormat()", "llvm::Triple::");
2951 // If custom code is specified, emit it.
2952 StringRef Code = R->getValueAsString("CustomCode");
2953 if (!Code.empty()) {
2954 AnyTargetChecks = true;
2960 return AnyTargetChecks;
2963 static void GenerateHasAttrSpellingStringSwitch(
2964 const std::vector<Record *> &Attrs, raw_ostream &OS,
2965 const std::string &Variety = "", const std::string &Scope = "") {
2966 for (const auto *Attr : Attrs) {
2967 // C++11-style attributes have specific version information associated with
2968 // them. If the attribute has no scope, the version information must not
2969 // have the default value (1), as that's incorrect. Instead, the unscoped
2970 // attribute version information should be taken from the SD-6 standing
2971 // document, which can be found at:
2972 // https://isocpp.org/std/standing-documents/sd-6-sg10-feature-test-recommendations
2975 if (Variety == "CXX11") {
2976 std::vector<Record *> Spellings = Attr->getValueAsListOfDefs("Spellings");
2977 for (const auto &Spelling : Spellings) {
2978 if (Spelling->getValueAsString("Variety") == "CXX11") {
2979 Version = static_cast<int>(Spelling->getValueAsInt("Version"));
2980 if (Scope.empty() && Version == 1)
2981 PrintError(Spelling->getLoc(), "C++ standard attributes must "
2982 "have valid version information.");
2989 if (Attr->isSubClassOf("TargetSpecificAttr")) {
2990 const Record *R = Attr->getValueAsDef("Target");
2991 std::vector<StringRef> Arches = R->getValueAsListOfStrings("Arches");
2992 GenerateTargetSpecificAttrChecks(R, Arches, Test, nullptr);
2994 // If this is the C++11 variety, also add in the LangOpts test.
2995 if (Variety == "CXX11")
2996 Test += " && LangOpts.CPlusPlus11";
2997 else if (Variety == "C2x")
2998 Test += " && LangOpts.DoubleSquareBracketAttributes";
2999 } else if (Variety == "CXX11")
3000 // C++11 mode should be checked against LangOpts, which is presumed to be
3001 // present in the caller.
3002 Test = "LangOpts.CPlusPlus11";
3003 else if (Variety == "C2x")
3004 Test = "LangOpts.DoubleSquareBracketAttributes";
3006 std::string TestStr =
3007 !Test.empty() ? Test + " ? " + llvm::itostr(Version) + " : 0" : "1";
3008 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(*Attr);
3009 for (const auto &S : Spellings)
3010 if (Variety.empty() || (Variety == S.variety() &&
3011 (Scope.empty() || Scope == S.nameSpace())))
3012 OS << " .Case(\"" << S.name() << "\", " << TestStr << ")\n";
3014 OS << " .Default(0);\n";
3017 // Emits the list of spellings for attributes.
3018 void EmitClangAttrHasAttrImpl(RecordKeeper &Records, raw_ostream &OS) {
3019 emitSourceFileHeader("Code to implement the __has_attribute logic", OS);
3021 // Separate all of the attributes out into four group: generic, C++11, GNU,
3022 // and declspecs. Then generate a big switch statement for each of them.
3023 std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
3024 std::vector<Record *> Declspec, Microsoft, GNU, Pragma;
3025 std::map<std::string, std::vector<Record *>> CXX, C2x;
3027 // Walk over the list of all attributes, and split them out based on the
3028 // spelling variety.
3029 for (auto *R : Attrs) {
3030 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(*R);
3031 for (const auto &SI : Spellings) {
3032 const std::string &Variety = SI.variety();
3033 if (Variety == "GNU")
3035 else if (Variety == "Declspec")
3036 Declspec.push_back(R);
3037 else if (Variety == "Microsoft")
3038 Microsoft.push_back(R);
3039 else if (Variety == "CXX11")
3040 CXX[SI.nameSpace()].push_back(R);
3041 else if (Variety == "C2x")
3042 C2x[SI.nameSpace()].push_back(R);
3043 else if (Variety == "Pragma")
3044 Pragma.push_back(R);
3048 OS << "const llvm::Triple &T = Target.getTriple();\n";
3049 OS << "switch (Syntax) {\n";
3050 OS << "case AttrSyntax::GNU:\n";
3051 OS << " return llvm::StringSwitch<int>(Name)\n";
3052 GenerateHasAttrSpellingStringSwitch(GNU, OS, "GNU");
3053 OS << "case AttrSyntax::Declspec:\n";
3054 OS << " return llvm::StringSwitch<int>(Name)\n";
3055 GenerateHasAttrSpellingStringSwitch(Declspec, OS, "Declspec");
3056 OS << "case AttrSyntax::Microsoft:\n";
3057 OS << " return llvm::StringSwitch<int>(Name)\n";
3058 GenerateHasAttrSpellingStringSwitch(Microsoft, OS, "Microsoft");
3059 OS << "case AttrSyntax::Pragma:\n";
3060 OS << " return llvm::StringSwitch<int>(Name)\n";
3061 GenerateHasAttrSpellingStringSwitch(Pragma, OS, "Pragma");
3062 auto fn = [&OS](const char *Spelling, const char *Variety,
3063 const std::map<std::string, std::vector<Record *>> &List) {
3064 OS << "case AttrSyntax::" << Variety << ": {\n";
3065 // C++11-style attributes are further split out based on the Scope.
3066 for (auto I = List.cbegin(), E = List.cend(); I != E; ++I) {
3067 if (I != List.cbegin())
3069 if (I->first.empty())
3070 OS << "if (ScopeName == \"\") {\n";
3072 OS << "if (ScopeName == \"" << I->first << "\") {\n";
3073 OS << " return llvm::StringSwitch<int>(Name)\n";
3074 GenerateHasAttrSpellingStringSwitch(I->second, OS, Spelling, I->first);
3077 OS << "\n} break;\n";
3079 fn("CXX11", "CXX", CXX);
3080 fn("C2x", "C", C2x);
3084 void EmitClangAttrSpellingListIndex(RecordKeeper &Records, raw_ostream &OS) {
3085 emitSourceFileHeader("Code to translate different attribute spellings "
3086 "into internal identifiers", OS);
3088 OS << " switch (getParsedKind()) {\n";
3089 OS << " case IgnoredAttribute:\n";
3090 OS << " case UnknownAttribute:\n";
3091 OS << " case NoSemaHandlerAttribute:\n";
3092 OS << " llvm_unreachable(\"Ignored/unknown shouldn't get here\");\n";
3094 ParsedAttrMap Attrs = getParsedAttrList(Records);
3095 for (const auto &I : Attrs) {
3096 const Record &R = *I.second;
3097 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(R);
3098 OS << " case AT_" << I.first << ": {\n";
3099 for (unsigned I = 0; I < Spellings.size(); ++ I) {
3100 OS << " if (Name == \"" << Spellings[I].name() << "\" && "
3101 << "getSyntax() == AttributeCommonInfo::AS_" << Spellings[I].variety()
3102 << " && Scope == \"" << Spellings[I].nameSpace() << "\")\n"
3103 << " return " << I << ";\n";
3111 OS << " return 0;\n";
3114 // Emits code used by RecursiveASTVisitor to visit attributes
3115 void EmitClangAttrASTVisitor(RecordKeeper &Records, raw_ostream &OS) {
3116 emitSourceFileHeader("Used by RecursiveASTVisitor to visit attributes.", OS);
3118 std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr");
3120 // Write method declarations for Traverse* methods.
3121 // We emit this here because we only generate methods for attributes that
3122 // are declared as ASTNodes.
3123 OS << "#ifdef ATTR_VISITOR_DECLS_ONLY\n\n";
3124 for (const auto *Attr : Attrs) {
3125 const Record &R = *Attr;
3126 if (!R.getValueAsBit("ASTNode"))
3128 OS << " bool Traverse"
3129 << R.getName() << "Attr(" << R.getName() << "Attr *A);\n";
3131 << R.getName() << "Attr(" << R.getName() << "Attr *A) {\n"
3132 << " return true; \n"
3135 OS << "\n#else // ATTR_VISITOR_DECLS_ONLY\n\n";
3137 // Write individual Traverse* methods for each attribute class.
3138 for (const auto *Attr : Attrs) {
3139 const Record &R = *Attr;
3140 if (!R.getValueAsBit("ASTNode"))
3143 OS << "template <typename Derived>\n"
3144 << "bool VISITORCLASS<Derived>::Traverse"
3145 << R.getName() << "Attr(" << R.getName() << "Attr *A) {\n"
3146 << " if (!getDerived().VisitAttr(A))\n"
3147 << " return false;\n"
3148 << " if (!getDerived().Visit" << R.getName() << "Attr(A))\n"
3149 << " return false;\n";
3151 std::vector<Record*> ArgRecords = R.getValueAsListOfDefs("Args");
3152 for (const auto *Arg : ArgRecords)
3153 createArgument(*Arg, R.getName())->writeASTVisitorTraversal(OS);
3155 OS << " return true;\n";
3159 // Write generic Traverse routine
3160 OS << "template <typename Derived>\n"
3161 << "bool VISITORCLASS<Derived>::TraverseAttr(Attr *A) {\n"
3163 << " return true;\n"
3165 << " switch (A->getKind()) {\n";
3167 for (const auto *Attr : Attrs) {
3168 const Record &R = *Attr;
3169 if (!R.getValueAsBit("ASTNode"))
3172 OS << " case attr::" << R.getName() << ":\n"
3173 << " return getDerived().Traverse" << R.getName() << "Attr("
3174 << "cast<" << R.getName() << "Attr>(A));\n";
3176 OS << " }\n"; // end switch
3177 OS << " llvm_unreachable(\"bad attribute kind\");\n";
3178 OS << "}\n"; // end function
3179 OS << "#endif // ATTR_VISITOR_DECLS_ONLY\n";
3182 void EmitClangAttrTemplateInstantiateHelper(const std::vector<Record *> &Attrs,
3184 bool AppliesToDecl) {
3186 OS << " switch (At->getKind()) {\n";
3187 for (const auto *Attr : Attrs) {
3188 const Record &R = *Attr;
3189 if (!R.getValueAsBit("ASTNode"))
3191 OS << " case attr::" << R.getName() << ": {\n";
3192 bool ShouldClone = R.getValueAsBit("Clone") &&
3194 R.getValueAsBit("MeaningfulToClassTemplateDefinition"));
3197 OS << " return nullptr;\n";
3202 OS << " const auto *A = cast<"
3203 << R.getName() << "Attr>(At);\n";
3204 bool TDependent = R.getValueAsBit("TemplateDependent");
3207 OS << " return A->clone(C);\n";
3212 std::vector<Record*> ArgRecords = R.getValueAsListOfDefs("Args");
3213 std::vector<std::unique_ptr<Argument>> Args;
3214 Args.reserve(ArgRecords.size());
3216 for (const auto *ArgRecord : ArgRecords)
3217 Args.emplace_back(createArgument(*ArgRecord, R.getName()));
3219 for (auto const &ai : Args)
3220 ai->writeTemplateInstantiation(OS);
3222 OS << " return new (C) " << R.getName() << "Attr(C, *A";
3223 for (auto const &ai : Args) {
3225 ai->writeTemplateInstantiationArgs(OS);
3229 OS << " } // end switch\n"
3230 << " llvm_unreachable(\"Unknown attribute!\");\n"
3231 << " return nullptr;\n";
3234 // Emits code to instantiate dependent attributes on templates.
3235 void EmitClangAttrTemplateInstantiate(RecordKeeper &Records, raw_ostream &OS) {
3236 emitSourceFileHeader("Template instantiation code for attributes", OS);
3238 std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr");
3240 OS << "namespace clang {\n"
3241 << "namespace sema {\n\n"
3242 << "Attr *instantiateTemplateAttribute(const Attr *At, ASTContext &C, "
3244 << " const MultiLevelTemplateArgumentList &TemplateArgs) {\n";
3245 EmitClangAttrTemplateInstantiateHelper(Attrs, OS, /*AppliesToDecl*/false);
3247 << "Attr *instantiateTemplateAttributeForDecl(const Attr *At,\n"
3248 << " ASTContext &C, Sema &S,\n"
3249 << " const MultiLevelTemplateArgumentList &TemplateArgs) {\n";
3250 EmitClangAttrTemplateInstantiateHelper(Attrs, OS, /*AppliesToDecl*/true);
3252 << "} // end namespace sema\n"
3253 << "} // end namespace clang\n";
3256 // Emits the list of parsed attributes.
3257 void EmitClangAttrParsedAttrList(RecordKeeper &Records, raw_ostream &OS) {
3258 emitSourceFileHeader("List of all attributes that Clang recognizes", OS);
3260 OS << "#ifndef PARSED_ATTR\n";
3261 OS << "#define PARSED_ATTR(NAME) NAME\n";
3264 ParsedAttrMap Names = getParsedAttrList(Records);
3265 for (const auto &I : Names) {
3266 OS << "PARSED_ATTR(" << I.first << ")\n";
3270 static bool isArgVariadic(const Record &R, StringRef AttrName) {
3271 return createArgument(R, AttrName)->isVariadic();
3274 static void emitArgInfo(const Record &R, raw_ostream &OS) {
3275 // This function will count the number of arguments specified for the
3276 // attribute and emit the number of required arguments followed by the
3277 // number of optional arguments.
3278 std::vector<Record *> Args = R.getValueAsListOfDefs("Args");
3279 unsigned ArgCount = 0, OptCount = 0;
3280 bool HasVariadic = false;
3281 for (const auto *Arg : Args) {
3282 // If the arg is fake, it's the user's job to supply it: general parsing
3283 // logic shouldn't need to know anything about it.
3284 if (Arg->getValueAsBit("Fake"))
3286 Arg->getValueAsBit("Optional") ? ++OptCount : ++ArgCount;
3287 if (!HasVariadic && isArgVariadic(*Arg, R.getName()))
3291 // If there is a variadic argument, we will set the optional argument count
3292 // to its largest value. Since it's currently a 4-bit number, we set it to 15.
3293 OS << ArgCount << ", " << (HasVariadic ? 15 : OptCount);
3296 static void GenerateDefaultAppertainsTo(raw_ostream &OS) {
3297 OS << "static bool defaultAppertainsTo(Sema &, const ParsedAttr &,";
3298 OS << "const Decl *) {\n";
3299 OS << " return true;\n";
3303 static std::string GetDiagnosticSpelling(const Record &R) {
3304 std::string Ret = R.getValueAsString("DiagSpelling");
3308 // If we couldn't find the DiagSpelling in this object, we can check to see
3309 // if the object is one that has a base, and if it is, loop up to the Base
3310 // member recursively.
3311 if (auto Base = R.getValueAsOptionalDef(BaseFieldName))
3312 return GetDiagnosticSpelling(*Base);
3317 static std::string CalculateDiagnostic(const Record &S) {
3318 // If the SubjectList object has a custom diagnostic associated with it,
3319 // return that directly.
3320 const StringRef CustomDiag = S.getValueAsString("CustomDiag");
3321 if (!CustomDiag.empty())
3322 return ("\"" + Twine(CustomDiag) + "\"").str();
3324 std::vector<std::string> DiagList;
3325 std::vector<Record *> Subjects = S.getValueAsListOfDefs("Subjects");
3326 for (const auto *Subject : Subjects) {
3327 const Record &R = *Subject;
3328 // Get the diagnostic text from the Decl or Stmt node given.
3329 std::string V = GetDiagnosticSpelling(R);
3331 PrintError(R.getLoc(),
3332 "Could not determine diagnostic spelling for the node: " +
3333 R.getName() + "; please add one to DeclNodes.td");
3335 // The node may contain a list of elements itself, so split the elements
3336 // by a comma, and trim any whitespace.
3337 SmallVector<StringRef, 2> Frags;
3338 llvm::SplitString(V, Frags, ",");
3339 for (auto Str : Frags) {
3340 DiagList.push_back(Str.trim());
3345 if (DiagList.empty()) {
3346 PrintFatalError(S.getLoc(),
3347 "Could not deduce diagnostic argument for Attr subjects");
3351 // FIXME: this is not particularly good for localization purposes and ideally
3352 // should be part of the diagnostics engine itself with some sort of list
3355 // A single member of the list can be returned directly.
3356 if (DiagList.size() == 1)
3357 return '"' + DiagList.front() + '"';
3359 if (DiagList.size() == 2)
3360 return '"' + DiagList[0] + " and " + DiagList[1] + '"';
3362 // If there are more than two in the list, we serialize the first N - 1
3363 // elements with a comma. This leaves the string in the state: foo, bar,
3364 // baz (but misses quux). We can then add ", and " for the last element
3366 std::string Diag = llvm::join(DiagList.begin(), DiagList.end() - 1, ", ");
3367 return '"' + Diag + ", and " + *(DiagList.end() - 1) + '"';
3370 static std::string GetSubjectWithSuffix(const Record *R) {
3371 const std::string &B = R->getName();
3372 if (B == "DeclBase")
3377 static std::string functionNameForCustomAppertainsTo(const Record &Subject) {
3378 return "is" + Subject.getName().str();
3381 static std::string GenerateCustomAppertainsTo(const Record &Subject,
3383 std::string FnName = functionNameForCustomAppertainsTo(Subject);
3385 // If this code has already been generated, simply return the previous
3387 static std::set<std::string> CustomSubjectSet;
3388 auto I = CustomSubjectSet.find(FnName);
3389 if (I != CustomSubjectSet.end())
3392 // This only works with non-root Decls.
3393 Record *Base = Subject.getValueAsDef(BaseFieldName);
3395 // Not currently support custom subjects within custom subjects.
3396 if (Base->isSubClassOf("SubsetSubject")) {
3397 PrintFatalError(Subject.getLoc(),
3398 "SubsetSubjects within SubsetSubjects is not supported");
3402 OS << "static bool " << FnName << "(const Decl *D) {\n";
3403 OS << " if (const auto *S = dyn_cast<";
3404 OS << GetSubjectWithSuffix(Base);
3406 OS << " return " << Subject.getValueAsString("CheckCode") << ";\n";
3407 OS << " return false;\n";
3410 CustomSubjectSet.insert(FnName);
3414 static std::string GenerateAppertainsTo(const Record &Attr, raw_ostream &OS) {
3415 // If the attribute does not contain a Subjects definition, then use the
3416 // default appertainsTo logic.
3417 if (Attr.isValueUnset("Subjects"))
3418 return "defaultAppertainsTo";
3420 const Record *SubjectObj = Attr.getValueAsDef("Subjects");
3421 std::vector<Record*> Subjects = SubjectObj->getValueAsListOfDefs("Subjects");
3423 // If the list of subjects is empty, it is assumed that the attribute
3424 // appertains to everything.
3425 if (Subjects.empty())
3426 return "defaultAppertainsTo";
3428 bool Warn = SubjectObj->getValueAsDef("Diag")->getValueAsBit("Warn");
3430 // Otherwise, generate an appertainsTo check specific to this attribute which
3431 // checks all of the given subjects against the Decl passed in. Return the
3432 // name of that check to the caller.
3434 // If D is null, that means the attribute was not applied to a declaration
3435 // at all (for instance because it was applied to a type), or that the caller
3436 // has determined that the check should fail (perhaps prior to the creation
3437 // of the declaration).
3438 std::string FnName = "check" + Attr.getName().str() + "AppertainsTo";
3439 std::stringstream SS;
3440 SS << "static bool " << FnName << "(Sema &S, const ParsedAttr &Attr, ";
3441 SS << "const Decl *D) {\n";
3442 SS << " if (!D || (";
3443 for (auto I = Subjects.begin(), E = Subjects.end(); I != E; ++I) {
3444 // If the subject has custom code associated with it, generate a function
3445 // for it. The function cannot be inlined into this check (yet) because it
3446 // requires the subject to be of a specific type, and were that information
3447 // inlined here, it would not support an attribute with multiple custom
3449 if ((*I)->isSubClassOf("SubsetSubject")) {
3450 SS << "!" << GenerateCustomAppertainsTo(**I, OS) << "(D)";
3452 SS << "!isa<" << GetSubjectWithSuffix(*I) << ">(D)";
3459 SS << " S.Diag(Attr.getLoc(), diag::";
3460 SS << (Warn ? "warn_attribute_wrong_decl_type_str" :
3461 "err_attribute_wrong_decl_type_str");
3463 SS << " << Attr << ";
3464 SS << CalculateDiagnostic(*SubjectObj) << ";\n";
3465 SS << " return false;\n";
3467 SS << " return true;\n";
3475 emitAttributeMatchRules(PragmaClangAttributeSupport &PragmaAttributeSupport,
3477 OS << "static bool checkAttributeMatchRuleAppliesTo(const Decl *D, "
3478 << AttributeSubjectMatchRule::EnumName << " rule) {\n";
3479 OS << " switch (rule) {\n";
3480 for (const auto &Rule : PragmaAttributeSupport.Rules) {
3481 if (Rule.isAbstractRule()) {
3482 OS << " case " << Rule.getEnumValue() << ":\n";
3483 OS << " assert(false && \"Abstract matcher rule isn't allowed\");\n";
3484 OS << " return false;\n";
3487 std::vector<Record *> Subjects = Rule.getSubjects();
3488 assert(!Subjects.empty() && "Missing subjects");
3489 OS << " case " << Rule.getEnumValue() << ":\n";
3491 for (auto I = Subjects.begin(), E = Subjects.end(); I != E; ++I) {
3492 // If the subject has custom code associated with it, use the function
3493 // that was generated for GenerateAppertainsTo to check if the declaration
3495 if ((*I)->isSubClassOf("SubsetSubject"))
3496 OS << functionNameForCustomAppertainsTo(**I) << "(D)";
3498 OS << "isa<" << GetSubjectWithSuffix(*I) << ">(D)";
3506 OS << " llvm_unreachable(\"Invalid match rule\");\nreturn false;\n";
3510 static void GenerateDefaultLangOptRequirements(raw_ostream &OS) {
3511 OS << "static bool defaultDiagnoseLangOpts(Sema &, ";
3512 OS << "const ParsedAttr &) {\n";
3513 OS << " return true;\n";
3517 static std::string GenerateLangOptRequirements(const Record &R,
3519 // If the attribute has an empty or unset list of language requirements,
3520 // return the default handler.
3521 std::vector<Record *> LangOpts = R.getValueAsListOfDefs("LangOpts");
3522 if (LangOpts.empty())
3523 return "defaultDiagnoseLangOpts";
3525 // Generate a unique function name for the diagnostic test. The list of
3526 // options should usually be short (one or two options), and the
3527 // uniqueness isn't strictly necessary (it is just for codegen efficiency).
3528 std::string FnName = "check";
3529 for (auto I = LangOpts.begin(), E = LangOpts.end(); I != E; ++I)
3530 FnName += (*I)->getValueAsString("Name");
3531 FnName += "LangOpts";
3533 // If this code has already been generated, simply return the previous
3535 static std::set<std::string> CustomLangOptsSet;
3536 auto I = CustomLangOptsSet.find(FnName);
3537 if (I != CustomLangOptsSet.end())
3540 OS << "static bool " << FnName << "(Sema &S, const ParsedAttr &Attr) {\n";
3541 OS << " auto &LangOpts = S.LangOpts;\n";
3542 OS << " if (" << GenerateTestExpression(LangOpts) << ")\n";
3543 OS << " return true;\n\n";
3544 OS << " S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) ";
3546 OS << " return false;\n";
3549 CustomLangOptsSet.insert(FnName);
3553 static void GenerateDefaultTargetRequirements(raw_ostream &OS) {
3554 OS << "static bool defaultTargetRequirements(const TargetInfo &) {\n";
3555 OS << " return true;\n";
3559 static std::string GenerateTargetRequirements(const Record &Attr,
3560 const ParsedAttrMap &Dupes,
3562 // If the attribute is not a target specific attribute, return the default
3564 if (!Attr.isSubClassOf("TargetSpecificAttr"))
3565 return "defaultTargetRequirements";
3567 // Get the list of architectures to be tested for.
3568 const Record *R = Attr.getValueAsDef("Target");
3569 std::vector<StringRef> Arches = R->getValueAsListOfStrings("Arches");
3571 // If there are other attributes which share the same parsed attribute kind,
3572 // such as target-specific attributes with a shared spelling, collapse the
3573 // duplicate architectures. This is required because a shared target-specific
3574 // attribute has only one ParsedAttr::Kind enumeration value, but it
3575 // applies to multiple target architectures. In order for the attribute to be
3576 // considered valid, all of its architectures need to be included.
3577 if (!Attr.isValueUnset("ParseKind")) {
3578 const StringRef APK = Attr.getValueAsString("ParseKind");
3579 for (const auto &I : Dupes) {
3580 if (I.first == APK) {
3581 std::vector<StringRef> DA =
3582 I.second->getValueAsDef("Target")->getValueAsListOfStrings(
3584 Arches.insert(Arches.end(), DA.begin(), DA.end());
3589 std::string FnName = "isTarget";
3591 bool UsesT = GenerateTargetSpecificAttrChecks(R, Arches, Test, &FnName);
3593 // If this code has already been generated, simply return the previous
3595 static std::set<std::string> CustomTargetSet;
3596 auto I = CustomTargetSet.find(FnName);
3597 if (I != CustomTargetSet.end())
3600 OS << "static bool " << FnName << "(const TargetInfo &Target) {\n";
3602 OS << " const llvm::Triple &T = Target.getTriple(); (void)T;\n";
3603 OS << " return " << Test << ";\n";
3606 CustomTargetSet.insert(FnName);
3610 static void GenerateDefaultSpellingIndexToSemanticSpelling(raw_ostream &OS) {
3611 OS << "static unsigned defaultSpellingIndexToSemanticSpelling("
3612 << "const ParsedAttr &Attr) {\n";
3613 OS << " return UINT_MAX;\n";
3617 static std::string GenerateSpellingIndexToSemanticSpelling(const Record &Attr,
3619 // If the attribute does not have a semantic form, we can bail out early.
3620 if (!Attr.getValueAsBit("ASTNode"))
3621 return "defaultSpellingIndexToSemanticSpelling";
3623 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(Attr);
3625 // If there are zero or one spellings, or all of the spellings share the same
3626 // name, we can also bail out early.
3627 if (Spellings.size() <= 1 || SpellingNamesAreCommon(Spellings))
3628 return "defaultSpellingIndexToSemanticSpelling";
3630 // Generate the enumeration we will use for the mapping.
3631 SemanticSpellingMap SemanticToSyntacticMap;
3632 std::string Enum = CreateSemanticSpellings(Spellings, SemanticToSyntacticMap);
3633 std::string Name = Attr.getName().str() + "AttrSpellingMap";
3635 OS << "static unsigned " << Name << "(const ParsedAttr &Attr) {\n";
3637 OS << " unsigned Idx = Attr.getAttributeSpellingListIndex();\n";
3638 WriteSemanticSpellingSwitch("Idx", SemanticToSyntacticMap, OS);
3644 static bool IsKnownToGCC(const Record &Attr) {
3645 // Look at the spellings for this subject; if there are any spellings which
3646 // claim to be known to GCC, the attribute is known to GCC.
3647 return llvm::any_of(
3648 GetFlattenedSpellings(Attr),
3649 [](const FlattenedSpelling &S) { return S.knownToGCC(); });
3652 /// Emits the parsed attribute helpers
3653 void EmitClangAttrParsedAttrImpl(RecordKeeper &Records, raw_ostream &OS) {
3654 emitSourceFileHeader("Parsed attribute helpers", OS);
3656 PragmaClangAttributeSupport &PragmaAttributeSupport =
3657 getPragmaAttributeSupport(Records);
3659 // Get the list of parsed attributes, and accept the optional list of
3660 // duplicates due to the ParseKind.
3661 ParsedAttrMap Dupes;
3662 ParsedAttrMap Attrs = getParsedAttrList(Records, &Dupes);
3664 // Generate the default appertainsTo, target and language option diagnostic,
3665 // and spelling list index mapping methods.
3666 GenerateDefaultAppertainsTo(OS);
3667 GenerateDefaultLangOptRequirements(OS);
3668 GenerateDefaultTargetRequirements(OS);
3669 GenerateDefaultSpellingIndexToSemanticSpelling(OS);
3671 // Generate the appertainsTo diagnostic methods and write their names into
3672 // another mapping. At the same time, generate the AttrInfoMap object
3673 // contents. Due to the reliance on generated code, use separate streams so
3674 // that code will not be interleaved.
3676 raw_string_ostream SS {Buffer};
3677 for (auto I = Attrs.begin(), E = Attrs.end(); I != E; ++I) {
3678 // TODO: If the attribute's kind appears in the list of duplicates, that is
3679 // because it is a target-specific attribute that appears multiple times.
3680 // It would be beneficial to test whether the duplicates are "similar
3681 // enough" to each other to not cause problems. For instance, check that
3682 // the spellings are identical, and custom parsing rules match, etc.
3684 // We need to generate struct instances based off ParsedAttrInfo from
3687 emitArgInfo(*I->second, SS);
3688 SS << ", " << I->second->getValueAsBit("HasCustomParsing");
3689 SS << ", " << I->second->isSubClassOf("TargetSpecificAttr");
3691 << (I->second->isSubClassOf("TypeAttr") ||
3692 I->second->isSubClassOf("DeclOrTypeAttr"));
3693 SS << ", " << I->second->isSubClassOf("StmtAttr");
3694 SS << ", " << IsKnownToGCC(*I->second);
3695 SS << ", " << PragmaAttributeSupport.isAttributedSupported(*I->second);
3696 SS << ", " << GenerateAppertainsTo(*I->second, OS);
3697 SS << ", " << GenerateLangOptRequirements(*I->second, OS);
3698 SS << ", " << GenerateTargetRequirements(*I->second, Dupes, OS);
3699 SS << ", " << GenerateSpellingIndexToSemanticSpelling(*I->second, OS);
3701 << PragmaAttributeSupport.generateStrictConformsTo(*I->second, OS);
3707 SS << " // AT_" << I->first << "\n";
3710 OS << "static const ParsedAttrInfo AttrInfoMap[ParsedAttr::UnknownAttribute "
3715 // Generate the attribute match rules.
3716 emitAttributeMatchRules(PragmaAttributeSupport, OS);
3719 // Emits the kind list of parsed attributes
3720 void EmitClangAttrParsedAttrKinds(RecordKeeper &Records, raw_ostream &OS) {
3721 emitSourceFileHeader("Attribute name matcher", OS);
3723 std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
3724 std::vector<StringMatcher::StringPair> GNU, Declspec, Microsoft, CXX11,
3725 Keywords, Pragma, C2x;
3726 std::set<std::string> Seen;
3727 for (const auto *A : Attrs) {
3728 const Record &Attr = *A;
3730 bool SemaHandler = Attr.getValueAsBit("SemaHandler");
3731 bool Ignored = Attr.getValueAsBit("Ignored");
3732 if (SemaHandler || Ignored) {
3733 // Attribute spellings can be shared between target-specific attributes,
3734 // and can be shared between syntaxes for the same attribute. For
3735 // instance, an attribute can be spelled GNU<"interrupt"> for an ARM-
3736 // specific attribute, or MSP430-specific attribute. Additionally, an
3737 // attribute can be spelled GNU<"dllexport"> and Declspec<"dllexport">
3738 // for the same semantic attribute. Ultimately, we need to map each of
3739 // these to a single AttributeCommonInfo::Kind value, but the
3740 // StringMatcher class cannot handle duplicate match strings. So we
3741 // generate a list of string to match based on the syntax, and emit
3742 // multiple string matchers depending on the syntax used.
3743 std::string AttrName;
3744 if (Attr.isSubClassOf("TargetSpecificAttr") &&
3745 !Attr.isValueUnset("ParseKind")) {
3746 AttrName = Attr.getValueAsString("ParseKind");
3747 if (Seen.find(AttrName) != Seen.end())
3749 Seen.insert(AttrName);
3751 AttrName = NormalizeAttrName(StringRef(Attr.getName())).str();
3753 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(Attr);
3754 for (const auto &S : Spellings) {
3755 const std::string &RawSpelling = S.name();
3756 std::vector<StringMatcher::StringPair> *Matches = nullptr;
3757 std::string Spelling;
3758 const std::string &Variety = S.variety();
3759 if (Variety == "CXX11") {
3761 Spelling += S.nameSpace();
3763 } else if (Variety == "C2x") {
3765 Spelling += S.nameSpace();
3767 } else if (Variety == "GNU")
3769 else if (Variety == "Declspec")
3770 Matches = &Declspec;
3771 else if (Variety == "Microsoft")
3772 Matches = &Microsoft;
3773 else if (Variety == "Keyword")
3774 Matches = &Keywords;
3775 else if (Variety == "Pragma")
3778 assert(Matches && "Unsupported spelling variety found");
3780 if (Variety == "GNU")
3781 Spelling += NormalizeGNUAttrSpelling(RawSpelling);
3783 Spelling += RawSpelling;
3786 Matches->push_back(StringMatcher::StringPair(
3787 Spelling, "return AttributeCommonInfo::AT_" + AttrName + ";"));
3789 Matches->push_back(StringMatcher::StringPair(
3790 Spelling, "return AttributeCommonInfo::IgnoredAttribute;"));
3795 OS << "static AttributeCommonInfo::Kind getAttrKind(StringRef Name, ";
3796 OS << "AttributeCommonInfo::Syntax Syntax) {\n";
3797 OS << " if (AttributeCommonInfo::AS_GNU == Syntax) {\n";
3798 StringMatcher("Name", GNU, OS).Emit();
3799 OS << " } else if (AttributeCommonInfo::AS_Declspec == Syntax) {\n";
3800 StringMatcher("Name", Declspec, OS).Emit();
3801 OS << " } else if (AttributeCommonInfo::AS_Microsoft == Syntax) {\n";
3802 StringMatcher("Name", Microsoft, OS).Emit();
3803 OS << " } else if (AttributeCommonInfo::AS_CXX11 == Syntax) {\n";
3804 StringMatcher("Name", CXX11, OS).Emit();
3805 OS << " } else if (AttributeCommonInfo::AS_C2x == Syntax) {\n";
3806 StringMatcher("Name", C2x, OS).Emit();
3807 OS << " } else if (AttributeCommonInfo::AS_Keyword == Syntax || ";
3808 OS << "AttributeCommonInfo::AS_ContextSensitiveKeyword == Syntax) {\n";
3809 StringMatcher("Name", Keywords, OS).Emit();
3810 OS << " } else if (AttributeCommonInfo::AS_Pragma == Syntax) {\n";
3811 StringMatcher("Name", Pragma, OS).Emit();
3813 OS << " return AttributeCommonInfo::UnknownAttribute;\n"
3817 // Emits the code to dump an attribute.
3818 void EmitClangAttrTextNodeDump(RecordKeeper &Records, raw_ostream &OS) {
3819 emitSourceFileHeader("Attribute text node dumper", OS);
3821 std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr"), Args;
3822 for (const auto *Attr : Attrs) {
3823 const Record &R = *Attr;
3824 if (!R.getValueAsBit("ASTNode"))
3827 // If the attribute has a semantically-meaningful name (which is determined
3828 // by whether there is a Spelling enumeration for it), then write out the
3829 // spelling used for the attribute.
3831 std::string FunctionContent;
3832 llvm::raw_string_ostream SS(FunctionContent);
3834 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(R);
3835 if (Spellings.size() > 1 && !SpellingNamesAreCommon(Spellings))
3836 SS << " OS << \" \" << A->getSpelling();\n";
3838 Args = R.getValueAsListOfDefs("Args");
3839 for (const auto *Arg : Args)
3840 createArgument(*Arg, R.getName())->writeDump(SS);
3843 OS << " void Visit" << R.getName() << "Attr(const " << R.getName()
3846 OS << " const auto *SA = cast<" << R.getName()
3847 << "Attr>(A); (void)SA;\n";
3854 void EmitClangAttrNodeTraverse(RecordKeeper &Records, raw_ostream &OS) {
3855 emitSourceFileHeader("Attribute text node traverser", OS);
3857 std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr"), Args;
3858 for (const auto *Attr : Attrs) {
3859 const Record &R = *Attr;
3860 if (!R.getValueAsBit("ASTNode"))
3863 std::string FunctionContent;
3864 llvm::raw_string_ostream SS(FunctionContent);
3866 Args = R.getValueAsListOfDefs("Args");
3867 for (const auto *Arg : Args)
3868 createArgument(*Arg, R.getName())->writeDumpChildren(SS);
3870 OS << " void Visit" << R.getName() << "Attr(const " << R.getName()
3873 OS << " const auto *SA = cast<" << R.getName()
3874 << "Attr>(A); (void)SA;\n";
3881 void EmitClangAttrParserStringSwitches(RecordKeeper &Records,
3883 emitSourceFileHeader("Parser-related llvm::StringSwitch cases", OS);
3884 emitClangAttrArgContextList(Records, OS);
3885 emitClangAttrIdentifierArgList(Records, OS);
3886 emitClangAttrVariadicIdentifierArgList(Records, OS);
3887 emitClangAttrThisIsaIdentifierArgList(Records, OS);
3888 emitClangAttrTypeArgList(Records, OS);
3889 emitClangAttrLateParsedList(Records, OS);
3892 void EmitClangAttrSubjectMatchRulesParserStringSwitches(RecordKeeper &Records,
3894 getPragmaAttributeSupport(Records).generateParsingHelpers(OS);
3897 enum class SpellingKind {
3906 static const size_t NumSpellingKinds = (size_t)SpellingKind::Pragma + 1;
3908 class SpellingList {
3909 std::vector<std::string> Spellings[NumSpellingKinds];
3912 ArrayRef<std::string> operator[](SpellingKind K) const {
3913 return Spellings[(size_t)K];
3916 void add(const Record &Attr, FlattenedSpelling Spelling) {
3917 SpellingKind Kind = StringSwitch<SpellingKind>(Spelling.variety())
3918 .Case("GNU", SpellingKind::GNU)
3919 .Case("CXX11", SpellingKind::CXX11)
3920 .Case("C2x", SpellingKind::C2x)
3921 .Case("Declspec", SpellingKind::Declspec)
3922 .Case("Microsoft", SpellingKind::Microsoft)
3923 .Case("Keyword", SpellingKind::Keyword)
3924 .Case("Pragma", SpellingKind::Pragma);
3926 if (!Spelling.nameSpace().empty()) {
3928 case SpellingKind::CXX11:
3929 case SpellingKind::C2x:
3930 Name = Spelling.nameSpace() + "::";
3932 case SpellingKind::Pragma:
3933 Name = Spelling.nameSpace() + " ";
3936 PrintFatalError(Attr.getLoc(), "Unexpected namespace in spelling");
3939 Name += Spelling.name();
3941 Spellings[(size_t)Kind].push_back(Name);
3945 class DocumentationData {
3947 const Record *Documentation;
3948 const Record *Attribute;
3949 std::string Heading;
3950 SpellingList SupportedSpellings;
3952 DocumentationData(const Record &Documentation, const Record &Attribute,
3953 std::pair<std::string, SpellingList> HeadingAndSpellings)
3954 : Documentation(&Documentation), Attribute(&Attribute),
3955 Heading(std::move(HeadingAndSpellings.first)),
3956 SupportedSpellings(std::move(HeadingAndSpellings.second)) {}
3959 static void WriteCategoryHeader(const Record *DocCategory,
3961 const StringRef Name = DocCategory->getValueAsString("Name");
3962 OS << Name << "\n" << std::string(Name.size(), '=') << "\n";
3964 // If there is content, print that as well.
3965 const StringRef ContentStr = DocCategory->getValueAsString("Content");
3966 // Trim leading and trailing newlines and spaces.
3967 OS << ContentStr.trim();
3972 static std::pair<std::string, SpellingList>
3973 GetAttributeHeadingAndSpellings(const Record &Documentation,
3974 const Record &Attribute) {
3975 // FIXME: there is no way to have a per-spelling category for the attribute
3976 // documentation. This may not be a limiting factor since the spellings
3977 // should generally be consistently applied across the category.
3979 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(Attribute);
3980 if (Spellings.empty())
3981 PrintFatalError(Attribute.getLoc(),
3982 "Attribute has no supported spellings; cannot be "
3985 // Determine the heading to be used for this attribute.
3986 std::string Heading = Documentation.getValueAsString("Heading");
3987 if (Heading.empty()) {
3988 // If there's only one spelling, we can simply use that.
3989 if (Spellings.size() == 1)
3990 Heading = Spellings.begin()->name();
3992 std::set<std::string> Uniques;
3993 for (auto I = Spellings.begin(), E = Spellings.end();
3994 I != E && Uniques.size() <= 1; ++I) {
3995 std::string Spelling = NormalizeNameForSpellingComparison(I->name());
3996 Uniques.insert(Spelling);
3998 // If the semantic map has only one spelling, that is sufficient for our
4000 if (Uniques.size() == 1)
4001 Heading = *Uniques.begin();
4005 // If the heading is still empty, it is an error.
4006 if (Heading.empty())
4007 PrintFatalError(Attribute.getLoc(),
4008 "This attribute requires a heading to be specified");
4010 SpellingList SupportedSpellings;
4011 for (const auto &I : Spellings)
4012 SupportedSpellings.add(Attribute, I);
4014 return std::make_pair(std::move(Heading), std::move(SupportedSpellings));
4017 static void WriteDocumentation(RecordKeeper &Records,
4018 const DocumentationData &Doc, raw_ostream &OS) {
4019 OS << Doc.Heading << "\n" << std::string(Doc.Heading.length(), '-') << "\n";
4021 // List what spelling syntaxes the attribute supports.
4022 OS << ".. csv-table:: Supported Syntaxes\n";
4023 OS << " :header: \"GNU\", \"C++11\", \"C2x\", \"``__declspec``\",";
4024 OS << " \"Keyword\", \"``#pragma``\", \"``#pragma clang attribute``\"\n\n";
4026 for (size_t Kind = 0; Kind != NumSpellingKinds; ++Kind) {
4027 SpellingKind K = (SpellingKind)Kind;
4028 // TODO: List Microsoft (IDL-style attribute) spellings once we fully
4030 if (K == SpellingKind::Microsoft)
4033 bool PrintedAny = false;
4034 for (StringRef Spelling : Doc.SupportedSpellings[K]) {
4037 OS << "``" << Spelling << "``";
4044 if (getPragmaAttributeSupport(Records).isAttributedSupported(
4049 // If the attribute is deprecated, print a message about it, and possibly
4050 // provide a replacement attribute.
4051 if (!Doc.Documentation->isValueUnset("Deprecated")) {
4052 OS << "This attribute has been deprecated, and may be removed in a future "
4053 << "version of Clang.";
4054 const Record &Deprecated = *Doc.Documentation->getValueAsDef("Deprecated");
4055 const StringRef Replacement = Deprecated.getValueAsString("Replacement");
4056 if (!Replacement.empty())
4057 OS << " This attribute has been superseded by ``" << Replacement
4062 const StringRef ContentStr = Doc.Documentation->getValueAsString("Content");
4063 // Trim leading and trailing newlines and spaces.
4064 OS << ContentStr.trim();
4069 void EmitClangAttrDocs(RecordKeeper &Records, raw_ostream &OS) {
4070 // Get the documentation introduction paragraph.
4071 const Record *Documentation = Records.getDef("GlobalDocumentation");
4072 if (!Documentation) {
4073 PrintFatalError("The Documentation top-level definition is missing, "
4074 "no documentation will be generated.");
4078 OS << Documentation->getValueAsString("Intro") << "\n";
4080 // Gather the Documentation lists from each of the attributes, based on the
4081 // category provided.
4082 std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
4083 std::map<const Record *, std::vector<DocumentationData>> SplitDocs;
4084 for (const auto *A : Attrs) {
4085 const Record &Attr = *A;
4086 std::vector<Record *> Docs = Attr.getValueAsListOfDefs("Documentation");
4087 for (const auto *D : Docs) {
4088 const Record &Doc = *D;
4089 const Record *Category = Doc.getValueAsDef("Category");
4090 // If the category is "undocumented", then there cannot be any other
4091 // documentation categories (otherwise, the attribute would become
4093 const StringRef Cat = Category->getValueAsString("Name");
4094 bool Undocumented = Cat == "Undocumented";
4095 if (Undocumented && Docs.size() > 1)
4096 PrintFatalError(Doc.getLoc(),
4097 "Attribute is \"Undocumented\", but has multiple "
4098 "documentation categories");
4101 SplitDocs[Category].push_back(DocumentationData(
4102 Doc, Attr, GetAttributeHeadingAndSpellings(Doc, Attr)));
4106 // Having split the attributes out based on what documentation goes where,
4107 // we can begin to generate sections of documentation.
4108 for (auto &I : SplitDocs) {
4109 WriteCategoryHeader(I.first, OS);
4111 llvm::sort(I.second,
4112 [](const DocumentationData &D1, const DocumentationData &D2) {
4113 return D1.Heading < D2.Heading;
4116 // Walk over each of the attributes in the category and write out their
4118 for (const auto &Doc : I.second)
4119 WriteDocumentation(Records, Doc, OS);
4123 void EmitTestPragmaAttributeSupportedAttributes(RecordKeeper &Records,
4125 PragmaClangAttributeSupport Support = getPragmaAttributeSupport(Records);
4126 ParsedAttrMap Attrs = getParsedAttrList(Records);
4127 OS << "#pragma clang attribute supports the following attributes:\n";
4128 for (const auto &I : Attrs) {
4129 if (!Support.isAttributedSupported(*I.second))
4132 if (I.second->isValueUnset("Subjects")) {
4136 const Record *SubjectObj = I.second->getValueAsDef("Subjects");
4137 std::vector<Record *> Subjects =
4138 SubjectObj->getValueAsListOfDefs("Subjects");
4140 for (const auto &Subject : llvm::enumerate(Subjects)) {
4141 if (Subject.index())
4143 PragmaClangAttributeSupport::RuleOrAggregateRuleSet &RuleSet =
4144 Support.SubjectsToRules.find(Subject.value())->getSecond();
4145 if (RuleSet.isRule()) {
4146 OS << RuleSet.getRule().getEnumValueName();
4150 for (const auto &Rule : llvm::enumerate(RuleSet.getAggregateRuleSet())) {
4153 OS << Rule.value().getEnumValueName();
4159 OS << "End of supported attributes.\n";
4162 } // end namespace clang