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/MapVector.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/ADT/SmallString.h"
22 #include "llvm/ADT/StringExtras.h"
23 #include "llvm/ADT/StringRef.h"
24 #include "llvm/ADT/StringSet.h"
25 #include "llvm/ADT/StringSwitch.h"
26 #include "llvm/ADT/iterator_range.h"
27 #include "llvm/Support/ErrorHandling.h"
28 #include "llvm/Support/raw_ostream.h"
29 #include "llvm/TableGen/Error.h"
30 #include "llvm/TableGen/Record.h"
31 #include "llvm/TableGen/StringMatcher.h"
32 #include "llvm/TableGen/TableGenBackend.h"
51 class FlattenedSpelling
{
54 const Record
&OriginalSpelling
;
57 FlattenedSpelling(const std::string
&Variety
, const std::string
&Name
,
58 const std::string
&Namespace
, bool KnownToGCC
,
59 const Record
&OriginalSpelling
)
60 : V(Variety
), N(Name
), NS(Namespace
), K(KnownToGCC
),
61 OriginalSpelling(OriginalSpelling
) {}
62 explicit FlattenedSpelling(const Record
&Spelling
)
63 : V(std::string(Spelling
.getValueAsString("Variety"))),
64 N(std::string(Spelling
.getValueAsString("Name"))),
65 OriginalSpelling(Spelling
) {
66 assert(V
!= "GCC" && V
!= "Clang" &&
67 "Given a GCC spelling, which means this hasn't been flattened!");
68 if (V
== "CXX11" || V
== "C23" || V
== "Pragma")
69 NS
= std::string(Spelling
.getValueAsString("Namespace"));
72 const std::string
&variety() const { return V
; }
73 const std::string
&name() const { return N
; }
74 const std::string
&nameSpace() const { return NS
; }
75 bool knownToGCC() const { return K
; }
76 const Record
&getSpellingRecord() const { return OriginalSpelling
; }
79 } // end anonymous namespace
81 static std::vector
<FlattenedSpelling
>
82 GetFlattenedSpellings(const Record
&Attr
) {
83 std::vector
<Record
*> Spellings
= Attr
.getValueAsListOfDefs("Spellings");
84 std::vector
<FlattenedSpelling
> Ret
;
86 for (const auto &Spelling
: Spellings
) {
87 StringRef Variety
= Spelling
->getValueAsString("Variety");
88 StringRef Name
= Spelling
->getValueAsString("Name");
89 if (Variety
== "GCC") {
90 Ret
.emplace_back("GNU", std::string(Name
), "", true, *Spelling
);
91 Ret
.emplace_back("CXX11", std::string(Name
), "gnu", true, *Spelling
);
92 if (Spelling
->getValueAsBit("AllowInC"))
93 Ret
.emplace_back("C23", std::string(Name
), "gnu", true, *Spelling
);
94 } else if (Variety
== "Clang") {
95 Ret
.emplace_back("GNU", std::string(Name
), "", false, *Spelling
);
96 Ret
.emplace_back("CXX11", std::string(Name
), "clang", false, *Spelling
);
97 if (Spelling
->getValueAsBit("AllowInC"))
98 Ret
.emplace_back("C23", std::string(Name
), "clang", false, *Spelling
);
100 Ret
.push_back(FlattenedSpelling(*Spelling
));
106 static std::string
ReadPCHRecord(StringRef type
) {
107 return StringSwitch
<std::string
>(type
)
108 .EndsWith("Decl *", "Record.GetLocalDeclAs<" +
109 std::string(type
.data(), 0, type
.size() - 1) +
110 ">(Record.readInt())")
111 .Case("TypeSourceInfo *", "Record.readTypeSourceInfo()")
112 .Case("Expr *", "Record.readExpr()")
113 .Case("IdentifierInfo *", "Record.readIdentifier()")
114 .Case("StringRef", "Record.readString()")
115 .Case("ParamIdx", "ParamIdx::deserialize(Record.readInt())")
116 .Case("OMPTraitInfo *", "Record.readOMPTraitInfo()")
117 .Default("Record.readInt()");
120 // Get a type that is suitable for storing an object of the specified type.
121 static StringRef
getStorageType(StringRef type
) {
122 return StringSwitch
<StringRef
>(type
)
123 .Case("StringRef", "std::string")
127 // Assumes that the way to get the value is SA->getname()
128 static std::string
WritePCHRecord(StringRef type
, StringRef name
) {
130 StringSwitch
<std::string
>(type
)
131 .EndsWith("Decl *", "AddDeclRef(" + std::string(name
) + ");\n")
132 .Case("TypeSourceInfo *",
133 "AddTypeSourceInfo(" + std::string(name
) + ");\n")
134 .Case("Expr *", "AddStmt(" + std::string(name
) + ");\n")
135 .Case("IdentifierInfo *",
136 "AddIdentifierRef(" + std::string(name
) + ");\n")
137 .Case("StringRef", "AddString(" + std::string(name
) + ");\n")
139 "push_back(" + std::string(name
) + ".serialize());\n")
140 .Case("OMPTraitInfo *",
141 "writeOMPTraitInfo(" + std::string(name
) + ");\n")
142 .Default("push_back(" + std::string(name
) + ");\n");
145 // Normalize attribute name by removing leading and trailing
146 // underscores. For example, __foo, foo__, __foo__ would
148 static StringRef
NormalizeAttrName(StringRef AttrName
) {
149 AttrName
.consume_front("__");
150 AttrName
.consume_back("__");
154 // Normalize the name by removing any and all leading and trailing underscores.
155 // This is different from NormalizeAttrName in that it also handles names like
156 // _pascal and __pascal.
157 static StringRef
NormalizeNameForSpellingComparison(StringRef Name
) {
158 return Name
.trim("_");
161 // Normalize the spelling of a GNU attribute (i.e. "x" in "__attribute__((x))"),
162 // removing "__" if it appears at the beginning and end of the attribute's name.
163 static StringRef
NormalizeGNUAttrSpelling(StringRef AttrSpelling
) {
164 if (AttrSpelling
.startswith("__") && AttrSpelling
.endswith("__")) {
165 AttrSpelling
= AttrSpelling
.substr(2, AttrSpelling
.size() - 4);
171 typedef std::vector
<std::pair
<std::string
, const Record
*>> ParsedAttrMap
;
173 static ParsedAttrMap
getParsedAttrList(const RecordKeeper
&Records
,
174 ParsedAttrMap
*Dupes
= nullptr) {
175 std::vector
<Record
*> Attrs
= Records
.getAllDerivedDefinitions("Attr");
176 std::set
<std::string
> Seen
;
178 for (const auto *Attr
: Attrs
) {
179 if (Attr
->getValueAsBit("SemaHandler")) {
181 if (Attr
->isSubClassOf("TargetSpecificAttr") &&
182 !Attr
->isValueUnset("ParseKind")) {
183 AN
= std::string(Attr
->getValueAsString("ParseKind"));
185 // If this attribute has already been handled, it does not need to be
187 if (Seen
.find(AN
) != Seen
.end()) {
189 Dupes
->push_back(std::make_pair(AN
, Attr
));
194 AN
= NormalizeAttrName(Attr
->getName()).str();
196 R
.push_back(std::make_pair(AN
, Attr
));
205 std::string lowerName
, upperName
;
211 Argument(StringRef Arg
, StringRef Attr
)
212 : lowerName(std::string(Arg
)), upperName(lowerName
), attrName(Attr
),
213 isOpt(false), Fake(false) {
214 if (!lowerName
.empty()) {
215 lowerName
[0] = std::tolower(lowerName
[0]);
216 upperName
[0] = std::toupper(upperName
[0]);
218 // Work around MinGW's macro definition of 'interface' to 'struct'. We
219 // have an attribute argument called 'Interface', so only the lower case
220 // name conflicts with the macro definition.
221 if (lowerName
== "interface")
222 lowerName
= "interface_";
224 Argument(const Record
&Arg
, StringRef Attr
)
225 : Argument(Arg
.getValueAsString("Name"), Attr
) {}
226 virtual ~Argument() = default;
228 StringRef
getLowerName() const { return lowerName
; }
229 StringRef
getUpperName() const { return upperName
; }
230 StringRef
getAttrName() const { return attrName
; }
232 bool isOptional() const { return isOpt
; }
233 void setOptional(bool set
) { isOpt
= set
; }
235 bool isFake() const { return Fake
; }
236 void setFake(bool fake
) { Fake
= fake
; }
238 // These functions print the argument contents formatted in different ways.
239 virtual void writeAccessors(raw_ostream
&OS
) const = 0;
240 virtual void writeAccessorDefinitions(raw_ostream
&OS
) const {}
241 virtual void writeASTVisitorTraversal(raw_ostream
&OS
) const {}
242 virtual void writeCloneArgs(raw_ostream
&OS
) const = 0;
243 virtual void writeTemplateInstantiationArgs(raw_ostream
&OS
) const = 0;
244 virtual void writeTemplateInstantiation(raw_ostream
&OS
) const {}
245 virtual void writeCtorBody(raw_ostream
&OS
) const {}
246 virtual void writeCtorInitializers(raw_ostream
&OS
) const = 0;
247 virtual void writeCtorDefaultInitializers(raw_ostream
&OS
) const = 0;
248 virtual void writeCtorParameters(raw_ostream
&OS
) const = 0;
249 virtual void writeDeclarations(raw_ostream
&OS
) const = 0;
250 virtual void writePCHReadArgs(raw_ostream
&OS
) const = 0;
251 virtual void writePCHReadDecls(raw_ostream
&OS
) const = 0;
252 virtual void writePCHWrite(raw_ostream
&OS
) const = 0;
253 virtual std::string
getIsOmitted() const { return "false"; }
254 virtual void writeValue(raw_ostream
&OS
) const = 0;
255 virtual void writeDump(raw_ostream
&OS
) const = 0;
256 virtual void writeDumpChildren(raw_ostream
&OS
) const {}
257 virtual void writeHasChildren(raw_ostream
&OS
) const { OS
<< "false"; }
259 virtual bool isEnumArg() const { return false; }
260 virtual bool isVariadicEnumArg() const { return false; }
261 virtual bool isVariadic() const { return false; }
263 virtual void writeImplicitCtorArgs(raw_ostream
&OS
) const {
264 OS
<< getUpperName();
268 class SimpleArgument
: public Argument
{
272 SimpleArgument(const Record
&Arg
, StringRef Attr
, std::string T
)
273 : Argument(Arg
, Attr
), type(std::move(T
)) {}
275 std::string
getType() const { return type
; }
277 void writeAccessors(raw_ostream
&OS
) const override
{
278 OS
<< " " << type
<< " get" << getUpperName() << "() const {\n";
279 OS
<< " return " << getLowerName() << ";\n";
283 void writeCloneArgs(raw_ostream
&OS
) const override
{
284 OS
<< getLowerName();
287 void writeTemplateInstantiationArgs(raw_ostream
&OS
) const override
{
288 OS
<< "A->get" << getUpperName() << "()";
291 void writeCtorInitializers(raw_ostream
&OS
) const override
{
292 OS
<< getLowerName() << "(" << getUpperName() << ")";
295 void writeCtorDefaultInitializers(raw_ostream
&OS
) const override
{
296 OS
<< getLowerName() << "()";
299 void writeCtorParameters(raw_ostream
&OS
) const override
{
300 OS
<< type
<< " " << getUpperName();
303 void writeDeclarations(raw_ostream
&OS
) const override
{
304 OS
<< type
<< " " << getLowerName() << ";";
307 void writePCHReadDecls(raw_ostream
&OS
) const override
{
308 std::string read
= ReadPCHRecord(type
);
309 OS
<< " " << type
<< " " << getLowerName() << " = " << read
<< ";\n";
312 void writePCHReadArgs(raw_ostream
&OS
) const override
{
313 OS
<< getLowerName();
316 void writePCHWrite(raw_ostream
&OS
) const override
{
318 << WritePCHRecord(type
,
319 "SA->get" + std::string(getUpperName()) + "()");
322 std::string
getIsOmitted() const override
{
323 auto IsOneOf
= [](StringRef subject
, auto... list
) {
324 return ((subject
== list
) || ...);
327 if (IsOneOf(type
, "IdentifierInfo *", "Expr *"))
328 return "!get" + getUpperName().str() + "()";
329 if (IsOneOf(type
, "TypeSourceInfo *"))
330 return "!get" + getUpperName().str() + "Loc()";
331 if (IsOneOf(type
, "ParamIdx"))
332 return "!get" + getUpperName().str() + "().isValid()";
334 assert(IsOneOf(type
, "unsigned", "int", "bool", "FunctionDecl *",
339 void writeValue(raw_ostream
&OS
) const override
{
340 if (type
== "FunctionDecl *")
341 OS
<< "\" << get" << getUpperName()
342 << "()->getNameInfo().getAsString() << \"";
343 else if (type
== "IdentifierInfo *")
344 // Some non-optional (comma required) identifier arguments can be the
345 // empty string but are then recorded as a nullptr.
346 OS
<< "\" << (get" << getUpperName() << "() ? get" << getUpperName()
347 << "()->getName() : \"\") << \"";
348 else if (type
== "VarDecl *")
349 OS
<< "\" << get" << getUpperName() << "()->getName() << \"";
350 else if (type
== "TypeSourceInfo *")
351 OS
<< "\" << get" << getUpperName() << "().getAsString() << \"";
352 else if (type
== "ParamIdx")
353 OS
<< "\" << get" << getUpperName() << "().getSourceIndex() << \"";
355 OS
<< "\" << get" << getUpperName() << "() << \"";
358 void writeDump(raw_ostream
&OS
) const override
{
359 if (StringRef(type
).endswith("Decl *")) {
360 OS
<< " OS << \" \";\n";
361 OS
<< " dumpBareDeclRef(SA->get" << getUpperName() << "());\n";
362 } else if (type
== "IdentifierInfo *") {
363 // Some non-optional (comma required) identifier arguments can be the
364 // empty string but are then recorded as a nullptr.
365 OS
<< " if (SA->get" << getUpperName() << "())\n"
366 << " OS << \" \" << SA->get" << getUpperName()
367 << "()->getName();\n";
368 } else if (type
== "TypeSourceInfo *") {
370 OS
<< " if (SA->get" << getUpperName() << "Loc())";
371 OS
<< " OS << \" \" << SA->get" << getUpperName()
372 << "().getAsString();\n";
373 } else if (type
== "bool") {
374 OS
<< " if (SA->get" << getUpperName() << "()) OS << \" "
375 << getUpperName() << "\";\n";
376 } else if (type
== "int" || type
== "unsigned") {
377 OS
<< " OS << \" \" << SA->get" << getUpperName() << "();\n";
378 } else if (type
== "ParamIdx") {
380 OS
<< " if (SA->get" << getUpperName() << "().isValid())\n ";
381 OS
<< " OS << \" \" << SA->get" << getUpperName()
382 << "().getSourceIndex();\n";
383 } else if (type
== "OMPTraitInfo *") {
384 OS
<< " OS << \" \" << SA->get" << getUpperName() << "();\n";
386 llvm_unreachable("Unknown SimpleArgument type!");
391 class DefaultSimpleArgument
: public SimpleArgument
{
395 DefaultSimpleArgument(const Record
&Arg
, StringRef Attr
,
396 std::string T
, int64_t Default
)
397 : SimpleArgument(Arg
, Attr
, T
), Default(Default
) {}
399 void writeAccessors(raw_ostream
&OS
) const override
{
400 SimpleArgument::writeAccessors(OS
);
402 OS
<< "\n\n static const " << getType() << " Default" << getUpperName()
404 if (getType() == "bool")
405 OS
<< (Default
!= 0 ? "true" : "false");
412 class StringArgument
: public Argument
{
414 StringArgument(const Record
&Arg
, StringRef Attr
)
415 : Argument(Arg
, Attr
)
418 void writeAccessors(raw_ostream
&OS
) const override
{
419 OS
<< " llvm::StringRef get" << getUpperName() << "() const {\n";
420 OS
<< " return llvm::StringRef(" << getLowerName() << ", "
421 << getLowerName() << "Length);\n";
423 OS
<< " unsigned get" << getUpperName() << "Length() const {\n";
424 OS
<< " return " << getLowerName() << "Length;\n";
426 OS
<< " void set" << getUpperName()
427 << "(ASTContext &C, llvm::StringRef S) {\n";
428 OS
<< " " << getLowerName() << "Length = S.size();\n";
429 OS
<< " this->" << getLowerName() << " = new (C, 1) char ["
430 << getLowerName() << "Length];\n";
431 OS
<< " if (!S.empty())\n";
432 OS
<< " std::memcpy(this->" << getLowerName() << ", S.data(), "
433 << getLowerName() << "Length);\n";
437 void writeCloneArgs(raw_ostream
&OS
) const override
{
438 OS
<< "get" << getUpperName() << "()";
441 void writeTemplateInstantiationArgs(raw_ostream
&OS
) const override
{
442 OS
<< "A->get" << getUpperName() << "()";
445 void writeCtorBody(raw_ostream
&OS
) const override
{
446 OS
<< " if (!" << getUpperName() << ".empty())\n";
447 OS
<< " std::memcpy(" << getLowerName() << ", " << getUpperName()
448 << ".data(), " << getLowerName() << "Length);\n";
451 void writeCtorInitializers(raw_ostream
&OS
) const override
{
452 OS
<< getLowerName() << "Length(" << getUpperName() << ".size()),"
453 << getLowerName() << "(new (Ctx, 1) char[" << getLowerName()
457 void writeCtorDefaultInitializers(raw_ostream
&OS
) const override
{
458 OS
<< getLowerName() << "Length(0)," << getLowerName() << "(nullptr)";
461 void writeCtorParameters(raw_ostream
&OS
) const override
{
462 OS
<< "llvm::StringRef " << getUpperName();
465 void writeDeclarations(raw_ostream
&OS
) const override
{
466 OS
<< "unsigned " << getLowerName() << "Length;\n";
467 OS
<< "char *" << getLowerName() << ";";
470 void writePCHReadDecls(raw_ostream
&OS
) const override
{
471 OS
<< " std::string " << getLowerName()
472 << "= Record.readString();\n";
475 void writePCHReadArgs(raw_ostream
&OS
) const override
{
476 OS
<< getLowerName();
479 void writePCHWrite(raw_ostream
&OS
) const override
{
480 OS
<< " Record.AddString(SA->get" << getUpperName() << "());\n";
483 void writeValue(raw_ostream
&OS
) const override
{
484 OS
<< "\\\"\" << get" << getUpperName() << "() << \"\\\"";
487 void writeDump(raw_ostream
&OS
) const override
{
488 OS
<< " OS << \" \\\"\" << SA->get" << getUpperName()
489 << "() << \"\\\"\";\n";
493 class AlignedArgument
: public Argument
{
495 AlignedArgument(const Record
&Arg
, StringRef Attr
)
496 : Argument(Arg
, Attr
)
499 void writeAccessors(raw_ostream
&OS
) const override
{
500 OS
<< " bool is" << getUpperName() << "Dependent() const;\n";
501 OS
<< " bool is" << getUpperName() << "ErrorDependent() const;\n";
503 OS
<< " unsigned get" << getUpperName() << "(ASTContext &Ctx) const;\n";
505 OS
<< " bool is" << getUpperName() << "Expr() const {\n";
506 OS
<< " return is" << getLowerName() << "Expr;\n";
509 OS
<< " Expr *get" << getUpperName() << "Expr() const {\n";
510 OS
<< " assert(is" << getLowerName() << "Expr);\n";
511 OS
<< " return " << getLowerName() << "Expr;\n";
514 OS
<< " TypeSourceInfo *get" << getUpperName() << "Type() const {\n";
515 OS
<< " assert(!is" << getLowerName() << "Expr);\n";
516 OS
<< " return " << getLowerName() << "Type;\n";
519 OS
<< " std::optional<unsigned> getCached" << getUpperName()
520 << "Value() const {\n";
521 OS
<< " return " << getLowerName() << "Cache;\n";
524 OS
<< " void setCached" << getUpperName()
525 << "Value(unsigned AlignVal) {\n";
526 OS
<< " " << getLowerName() << "Cache = AlignVal;\n";
530 void writeAccessorDefinitions(raw_ostream
&OS
) const override
{
531 OS
<< "bool " << getAttrName() << "Attr::is" << getUpperName()
532 << "Dependent() const {\n";
533 OS
<< " if (is" << getLowerName() << "Expr)\n";
534 OS
<< " return " << getLowerName() << "Expr && (" << getLowerName()
535 << "Expr->isValueDependent() || " << getLowerName()
536 << "Expr->isTypeDependent());\n";
538 OS
<< " return " << getLowerName()
539 << "Type->getType()->isDependentType();\n";
542 OS
<< "bool " << getAttrName() << "Attr::is" << getUpperName()
543 << "ErrorDependent() const {\n";
544 OS
<< " if (is" << getLowerName() << "Expr)\n";
545 OS
<< " return " << getLowerName() << "Expr && " << getLowerName()
546 << "Expr->containsErrors();\n";
547 OS
<< " return " << getLowerName()
548 << "Type->getType()->containsErrors();\n";
552 void writeASTVisitorTraversal(raw_ostream
&OS
) const override
{
553 StringRef Name
= getUpperName();
554 OS
<< " if (A->is" << Name
<< "Expr()) {\n"
555 << " if (!getDerived().TraverseStmt(A->get" << Name
<< "Expr()))\n"
556 << " return false;\n"
557 << " } else if (auto *TSI = A->get" << Name
<< "Type()) {\n"
558 << " if (!getDerived().TraverseTypeLoc(TSI->getTypeLoc()))\n"
559 << " return false;\n"
563 void writeCloneArgs(raw_ostream
&OS
) const override
{
564 OS
<< "is" << getLowerName() << "Expr, is" << getLowerName()
565 << "Expr ? static_cast<void*>(" << getLowerName()
566 << "Expr) : " << getLowerName()
570 void writeTemplateInstantiationArgs(raw_ostream
&OS
) const override
{
571 // FIXME: move the definition in Sema::InstantiateAttrs to here.
572 // In the meantime, aligned attributes are cloned.
575 void writeCtorBody(raw_ostream
&OS
) const override
{
576 OS
<< " if (is" << getLowerName() << "Expr)\n";
577 OS
<< " " << getLowerName() << "Expr = reinterpret_cast<Expr *>("
578 << getUpperName() << ");\n";
580 OS
<< " " << getLowerName()
581 << "Type = reinterpret_cast<TypeSourceInfo *>(" << getUpperName()
585 void writeCtorInitializers(raw_ostream
&OS
) const override
{
586 OS
<< "is" << getLowerName() << "Expr(Is" << getUpperName() << "Expr)";
589 void writeCtorDefaultInitializers(raw_ostream
&OS
) const override
{
590 OS
<< "is" << getLowerName() << "Expr(false)";
593 void writeCtorParameters(raw_ostream
&OS
) const override
{
594 OS
<< "bool Is" << getUpperName() << "Expr, void *" << getUpperName();
597 void writeImplicitCtorArgs(raw_ostream
&OS
) const override
{
598 OS
<< "Is" << getUpperName() << "Expr, " << getUpperName();
601 void writeDeclarations(raw_ostream
&OS
) const override
{
602 OS
<< "bool is" << getLowerName() << "Expr;\n";
604 OS
<< "Expr *" << getLowerName() << "Expr;\n";
605 OS
<< "TypeSourceInfo *" << getLowerName() << "Type;\n";
607 OS
<< "std::optional<unsigned> " << getLowerName() << "Cache;\n";
610 void writePCHReadArgs(raw_ostream
&OS
) const override
{
611 OS
<< "is" << getLowerName() << "Expr, " << getLowerName() << "Ptr";
614 void writePCHReadDecls(raw_ostream
&OS
) const override
{
615 OS
<< " bool is" << getLowerName() << "Expr = Record.readInt();\n";
616 OS
<< " void *" << getLowerName() << "Ptr;\n";
617 OS
<< " if (is" << getLowerName() << "Expr)\n";
618 OS
<< " " << getLowerName() << "Ptr = Record.readExpr();\n";
620 OS
<< " " << getLowerName()
621 << "Ptr = Record.readTypeSourceInfo();\n";
624 void writePCHWrite(raw_ostream
&OS
) const override
{
625 OS
<< " Record.push_back(SA->is" << getUpperName() << "Expr());\n";
626 OS
<< " if (SA->is" << getUpperName() << "Expr())\n";
627 OS
<< " Record.AddStmt(SA->get" << getUpperName() << "Expr());\n";
629 OS
<< " Record.AddTypeSourceInfo(SA->get" << getUpperName()
633 std::string
getIsOmitted() const override
{
634 return "!((is" + getLowerName().str() + "Expr && " +
635 getLowerName().str() + "Expr) || (!is" + getLowerName().str() +
636 "Expr && " + getLowerName().str() + "Type))";
639 void writeValue(raw_ostream
&OS
) const override
{
641 OS
<< " if (is" << getLowerName() << "Expr && " << getLowerName()
643 OS
<< " " << getLowerName()
644 << "Expr->printPretty(OS, nullptr, Policy);\n";
645 OS
<< " if (!is" << getLowerName() << "Expr && " << getLowerName()
647 OS
<< " " << getLowerName()
648 << "Type->getType().print(OS, Policy);\n";
652 void writeDump(raw_ostream
&OS
) const override
{
653 OS
<< " if (!SA->is" << getUpperName() << "Expr())\n";
654 OS
<< " dumpType(SA->get" << getUpperName()
655 << "Type()->getType());\n";
658 void writeDumpChildren(raw_ostream
&OS
) const override
{
659 OS
<< " if (SA->is" << getUpperName() << "Expr())\n";
660 OS
<< " Visit(SA->get" << getUpperName() << "Expr());\n";
663 void writeHasChildren(raw_ostream
&OS
) const override
{
664 OS
<< "SA->is" << getUpperName() << "Expr()";
668 class VariadicArgument
: public Argument
{
669 std::string Type
, ArgName
, ArgSizeName
, RangeName
;
672 // Assumed to receive a parameter: raw_ostream OS.
673 virtual void writeValueImpl(raw_ostream
&OS
) const {
674 OS
<< " OS << Val;\n";
676 // Assumed to receive a parameter: raw_ostream OS.
677 virtual void writeDumpImpl(raw_ostream
&OS
) const {
678 OS
<< " OS << \" \" << Val;\n";
682 VariadicArgument(const Record
&Arg
, StringRef Attr
, std::string T
)
683 : Argument(Arg
, Attr
), Type(std::move(T
)),
684 ArgName(getLowerName().str() + "_"), ArgSizeName(ArgName
+ "Size"),
685 RangeName(std::string(getLowerName())) {}
687 VariadicArgument(StringRef Arg
, StringRef Attr
, std::string T
)
688 : Argument(Arg
, Attr
), Type(std::move(T
)),
689 ArgName(getLowerName().str() + "_"), ArgSizeName(ArgName
+ "Size"),
690 RangeName(std::string(getLowerName())) {}
692 const std::string
&getType() const { return Type
; }
693 const std::string
&getArgName() const { return ArgName
; }
694 const std::string
&getArgSizeName() const { return ArgSizeName
; }
695 bool isVariadic() const override
{ return true; }
697 void writeAccessors(raw_ostream
&OS
) const override
{
698 std::string IteratorType
= getLowerName().str() + "_iterator";
699 std::string BeginFn
= getLowerName().str() + "_begin()";
700 std::string EndFn
= getLowerName().str() + "_end()";
702 OS
<< " typedef " << Type
<< "* " << IteratorType
<< ";\n";
703 OS
<< " " << IteratorType
<< " " << BeginFn
<< " const {"
704 << " return " << ArgName
<< "; }\n";
705 OS
<< " " << IteratorType
<< " " << EndFn
<< " const {"
706 << " return " << ArgName
<< " + " << ArgSizeName
<< "; }\n";
707 OS
<< " unsigned " << getLowerName() << "_size() const {"
708 << " return " << ArgSizeName
<< "; }\n";
709 OS
<< " llvm::iterator_range<" << IteratorType
<< "> " << RangeName
710 << "() const { return llvm::make_range(" << BeginFn
<< ", " << EndFn
714 void writeSetter(raw_ostream
&OS
) const {
715 OS
<< " void set" << getUpperName() << "(ASTContext &Ctx, ";
716 writeCtorParameters(OS
);
718 OS
<< " " << ArgSizeName
<< " = " << getUpperName() << "Size;\n";
719 OS
<< " " << ArgName
<< " = new (Ctx, 16) " << getType() << "["
720 << ArgSizeName
<< "];\n";
726 void writeCloneArgs(raw_ostream
&OS
) const override
{
727 OS
<< ArgName
<< ", " << ArgSizeName
;
730 void writeTemplateInstantiationArgs(raw_ostream
&OS
) const override
{
731 // This isn't elegant, but we have to go through public methods...
732 OS
<< "A->" << getLowerName() << "_begin(), "
733 << "A->" << getLowerName() << "_size()";
736 void writeASTVisitorTraversal(raw_ostream
&OS
) const override
{
737 // FIXME: Traverse the elements.
740 void writeCtorBody(raw_ostream
&OS
) const override
{
741 OS
<< " std::copy(" << getUpperName() << ", " << getUpperName() << " + "
742 << ArgSizeName
<< ", " << ArgName
<< ");\n";
745 void writeCtorInitializers(raw_ostream
&OS
) const override
{
746 OS
<< ArgSizeName
<< "(" << getUpperName() << "Size), "
747 << ArgName
<< "(new (Ctx, 16) " << getType() << "["
748 << ArgSizeName
<< "])";
751 void writeCtorDefaultInitializers(raw_ostream
&OS
) const override
{
752 OS
<< ArgSizeName
<< "(0), " << ArgName
<< "(nullptr)";
755 void writeCtorParameters(raw_ostream
&OS
) const override
{
756 OS
<< getType() << " *" << getUpperName() << ", unsigned "
757 << getUpperName() << "Size";
760 void writeImplicitCtorArgs(raw_ostream
&OS
) const override
{
761 OS
<< getUpperName() << ", " << getUpperName() << "Size";
764 void writeDeclarations(raw_ostream
&OS
) const override
{
765 OS
<< " unsigned " << ArgSizeName
<< ";\n";
766 OS
<< " " << getType() << " *" << ArgName
<< ";";
769 void writePCHReadDecls(raw_ostream
&OS
) const override
{
770 OS
<< " unsigned " << getLowerName() << "Size = Record.readInt();\n";
771 OS
<< " SmallVector<" << getType() << ", 4> "
772 << getLowerName() << ";\n";
773 OS
<< " " << getLowerName() << ".reserve(" << getLowerName()
776 // If we can't store the values in the current type (if it's something
777 // like StringRef), store them in a different type and convert the
778 // container afterwards.
779 std::string StorageType
= std::string(getStorageType(getType()));
780 std::string StorageName
= std::string(getLowerName());
781 if (StorageType
!= getType()) {
782 StorageName
+= "Storage";
783 OS
<< " SmallVector<" << StorageType
<< ", 4> "
784 << StorageName
<< ";\n";
785 OS
<< " " << StorageName
<< ".reserve(" << getLowerName()
789 OS
<< " for (unsigned i = 0; i != " << getLowerName() << "Size; ++i)\n";
790 std::string read
= ReadPCHRecord(Type
);
791 OS
<< " " << StorageName
<< ".push_back(" << read
<< ");\n";
793 if (StorageType
!= getType()) {
794 OS
<< " for (unsigned i = 0; i != " << getLowerName() << "Size; ++i)\n";
795 OS
<< " " << getLowerName() << ".push_back("
796 << StorageName
<< "[i]);\n";
800 void writePCHReadArgs(raw_ostream
&OS
) const override
{
801 OS
<< getLowerName() << ".data(), " << getLowerName() << "Size";
804 void writePCHWrite(raw_ostream
&OS
) const override
{
805 OS
<< " Record.push_back(SA->" << getLowerName() << "_size());\n";
806 OS
<< " for (auto &Val : SA->" << RangeName
<< "())\n";
807 OS
<< " " << WritePCHRecord(Type
, "Val");
810 void writeValue(raw_ostream
&OS
) const override
{
812 OS
<< " for (const auto &Val : " << RangeName
<< "()) {\n"
813 << " DelimitAttributeArgument(OS, IsFirstArgument);\n";
819 void writeDump(raw_ostream
&OS
) const override
{
820 OS
<< " for (const auto &Val : SA->" << RangeName
<< "())\n";
825 class VariadicOMPInteropInfoArgument
: public VariadicArgument
{
827 VariadicOMPInteropInfoArgument(const Record
&Arg
, StringRef Attr
)
828 : VariadicArgument(Arg
, Attr
, "OMPInteropInfo") {}
830 void writeDump(raw_ostream
&OS
) const override
{
831 OS
<< " for (" << getAttrName() << "Attr::" << getLowerName()
832 << "_iterator I = SA->" << getLowerName() << "_begin(), E = SA->"
833 << getLowerName() << "_end(); I != E; ++I) {\n";
834 OS
<< " if (I->IsTarget && I->IsTargetSync)\n";
835 OS
<< " OS << \" Target_TargetSync\";\n";
836 OS
<< " else if (I->IsTarget)\n";
837 OS
<< " OS << \" Target\";\n";
839 OS
<< " OS << \" TargetSync\";\n";
843 void writePCHReadDecls(raw_ostream
&OS
) const override
{
844 OS
<< " unsigned " << getLowerName() << "Size = Record.readInt();\n";
845 OS
<< " SmallVector<OMPInteropInfo, 4> " << getLowerName() << ";\n";
846 OS
<< " " << getLowerName() << ".reserve(" << getLowerName()
848 OS
<< " for (unsigned I = 0, E = " << getLowerName() << "Size; ";
849 OS
<< "I != E; ++I) {\n";
850 OS
<< " bool IsTarget = Record.readBool();\n";
851 OS
<< " bool IsTargetSync = Record.readBool();\n";
852 OS
<< " " << getLowerName()
853 << ".emplace_back(IsTarget, IsTargetSync);\n";
857 void writePCHWrite(raw_ostream
&OS
) const override
{
858 OS
<< " Record.push_back(SA->" << getLowerName() << "_size());\n";
859 OS
<< " for (" << getAttrName() << "Attr::" << getLowerName()
860 << "_iterator I = SA->" << getLowerName() << "_begin(), E = SA->"
861 << getLowerName() << "_end(); I != E; ++I) {\n";
862 OS
<< " Record.writeBool(I->IsTarget);\n";
863 OS
<< " Record.writeBool(I->IsTargetSync);\n";
868 class VariadicParamIdxArgument
: public VariadicArgument
{
870 VariadicParamIdxArgument(const Record
&Arg
, StringRef Attr
)
871 : VariadicArgument(Arg
, Attr
, "ParamIdx") {}
874 void writeValueImpl(raw_ostream
&OS
) const override
{
875 OS
<< " OS << Val.getSourceIndex();\n";
878 void writeDumpImpl(raw_ostream
&OS
) const override
{
879 OS
<< " OS << \" \" << Val.getSourceIndex();\n";
883 struct VariadicParamOrParamIdxArgument
: public VariadicArgument
{
884 VariadicParamOrParamIdxArgument(const Record
&Arg
, StringRef Attr
)
885 : VariadicArgument(Arg
, Attr
, "int") {}
888 // Unique the enums, but maintain the original declaration ordering.
889 std::vector
<StringRef
>
890 uniqueEnumsInOrder(const std::vector
<StringRef
> &enums
) {
891 std::vector
<StringRef
> uniques
;
892 SmallDenseSet
<StringRef
, 8> unique_set
;
893 for (const auto &i
: enums
) {
894 if (unique_set
.insert(i
).second
)
895 uniques
.push_back(i
);
900 class EnumArgument
: public Argument
{
902 std::vector
<StringRef
> values
, enums
, uniques
;
905 EnumArgument(const Record
&Arg
, StringRef Attr
)
906 : Argument(Arg
, Attr
), type(std::string(Arg
.getValueAsString("Type"))),
907 values(Arg
.getValueAsListOfStrings("Values")),
908 enums(Arg
.getValueAsListOfStrings("Enums")),
909 uniques(uniqueEnumsInOrder(enums
)) {
910 // FIXME: Emit a proper error
911 assert(!uniques
.empty());
914 bool isEnumArg() const override
{ return true; }
916 void writeAccessors(raw_ostream
&OS
) const override
{
917 OS
<< " " << type
<< " get" << getUpperName() << "() const {\n";
918 OS
<< " return " << getLowerName() << ";\n";
922 void writeCloneArgs(raw_ostream
&OS
) const override
{
923 OS
<< getLowerName();
926 void writeTemplateInstantiationArgs(raw_ostream
&OS
) const override
{
927 OS
<< "A->get" << getUpperName() << "()";
929 void writeCtorInitializers(raw_ostream
&OS
) const override
{
930 OS
<< getLowerName() << "(" << getUpperName() << ")";
932 void writeCtorDefaultInitializers(raw_ostream
&OS
) const override
{
933 OS
<< getLowerName() << "(" << type
<< "(0))";
935 void writeCtorParameters(raw_ostream
&OS
) const override
{
936 OS
<< type
<< " " << getUpperName();
938 void writeDeclarations(raw_ostream
&OS
) const override
{
939 auto i
= uniques
.cbegin(), e
= uniques
.cend();
940 // The last one needs to not have a comma.
944 OS
<< " enum " << type
<< " {\n";
946 OS
<< " " << *i
<< ",\n";
947 OS
<< " " << *e
<< "\n";
950 OS
<< " " << type
<< " " << getLowerName() << ";";
953 void writePCHReadDecls(raw_ostream
&OS
) const override
{
954 OS
<< " " << getAttrName() << "Attr::" << type
<< " " << getLowerName()
955 << "(static_cast<" << getAttrName() << "Attr::" << type
956 << ">(Record.readInt()));\n";
959 void writePCHReadArgs(raw_ostream
&OS
) const override
{
960 OS
<< getLowerName();
963 void writePCHWrite(raw_ostream
&OS
) const override
{
964 OS
<< "Record.push_back(SA->get" << getUpperName() << "());\n";
967 void writeValue(raw_ostream
&OS
) const override
{
968 // FIXME: this isn't 100% correct -- some enum arguments require printing
969 // as a string literal, while others require printing as an identifier.
970 // Tablegen currently does not distinguish between the two forms.
971 OS
<< "\\\"\" << " << getAttrName() << "Attr::Convert" << type
<< "ToStr(get"
972 << getUpperName() << "()) << \"\\\"";
975 void writeDump(raw_ostream
&OS
) const override
{
976 OS
<< " switch(SA->get" << getUpperName() << "()) {\n";
977 for (const auto &I
: uniques
) {
978 OS
<< " case " << getAttrName() << "Attr::" << I
<< ":\n";
979 OS
<< " OS << \" " << I
<< "\";\n";
985 void writeConversion(raw_ostream
&OS
, bool Header
) const {
987 OS
<< " static bool ConvertStrTo" << type
<< "(StringRef Val, " << type
989 OS
<< " static const char *Convert" << type
<< "ToStr(" << type
994 OS
<< "bool " << getAttrName() << "Attr::ConvertStrTo" << type
995 << "(StringRef Val, " << type
<< " &Out) {\n";
996 OS
<< " std::optional<" << type
997 << "> R = llvm::StringSwitch<std::optional<";
998 OS
<< type
<< ">>(Val)\n";
999 for (size_t I
= 0; I
< enums
.size(); ++I
) {
1000 OS
<< " .Case(\"" << values
[I
] << "\", ";
1001 OS
<< getAttrName() << "Attr::" << enums
[I
] << ")\n";
1003 OS
<< " .Default(std::optional<" << type
<< ">());\n";
1004 OS
<< " if (R) {\n";
1005 OS
<< " Out = *R;\n return true;\n }\n";
1006 OS
<< " return false;\n";
1009 // Mapping from enumeration values back to enumeration strings isn't
1010 // trivial because some enumeration values have multiple named
1011 // enumerators, such as type_visibility(internal) and
1012 // type_visibility(hidden) both mapping to TypeVisibilityAttr::Hidden.
1013 OS
<< "const char *" << getAttrName() << "Attr::Convert" << type
1014 << "ToStr(" << type
<< " Val) {\n"
1015 << " switch(Val) {\n";
1016 SmallDenseSet
<StringRef
, 8> Uniques
;
1017 for (size_t I
= 0; I
< enums
.size(); ++I
) {
1018 if (Uniques
.insert(enums
[I
]).second
)
1019 OS
<< " case " << getAttrName() << "Attr::" << enums
[I
]
1020 << ": return \"" << values
[I
] << "\";\n";
1023 << " llvm_unreachable(\"No enumerator with that value\");\n"
1028 class VariadicEnumArgument
: public VariadicArgument
{
1029 std::string type
, QualifiedTypeName
;
1030 std::vector
<StringRef
> values
, enums
, uniques
;
1033 void writeValueImpl(raw_ostream
&OS
) const override
{
1034 // FIXME: this isn't 100% correct -- some enum arguments require printing
1035 // as a string literal, while others require printing as an identifier.
1036 // Tablegen currently does not distinguish between the two forms.
1037 OS
<< " OS << \"\\\"\" << " << getAttrName() << "Attr::Convert" << type
1038 << "ToStr(Val)" << "<< \"\\\"\";\n";
1042 VariadicEnumArgument(const Record
&Arg
, StringRef Attr
)
1043 : VariadicArgument(Arg
, Attr
,
1044 std::string(Arg
.getValueAsString("Type"))),
1045 type(std::string(Arg
.getValueAsString("Type"))),
1046 values(Arg
.getValueAsListOfStrings("Values")),
1047 enums(Arg
.getValueAsListOfStrings("Enums")),
1048 uniques(uniqueEnumsInOrder(enums
)) {
1049 QualifiedTypeName
= getAttrName().str() + "Attr::" + type
;
1051 // FIXME: Emit a proper error
1052 assert(!uniques
.empty());
1055 bool isVariadicEnumArg() const override
{ return true; }
1057 void writeDeclarations(raw_ostream
&OS
) const override
{
1058 auto i
= uniques
.cbegin(), e
= uniques
.cend();
1059 // The last one needs to not have a comma.
1063 OS
<< " enum " << type
<< " {\n";
1065 OS
<< " " << *i
<< ",\n";
1066 OS
<< " " << *e
<< "\n";
1070 VariadicArgument::writeDeclarations(OS
);
1073 void writeDump(raw_ostream
&OS
) const override
{
1074 OS
<< " for (" << getAttrName() << "Attr::" << getLowerName()
1075 << "_iterator I = SA->" << getLowerName() << "_begin(), E = SA->"
1076 << getLowerName() << "_end(); I != E; ++I) {\n";
1077 OS
<< " switch(*I) {\n";
1078 for (const auto &UI
: uniques
) {
1079 OS
<< " case " << getAttrName() << "Attr::" << UI
<< ":\n";
1080 OS
<< " OS << \" " << UI
<< "\";\n";
1087 void writePCHReadDecls(raw_ostream
&OS
) const override
{
1088 OS
<< " unsigned " << getLowerName() << "Size = Record.readInt();\n";
1089 OS
<< " SmallVector<" << QualifiedTypeName
<< ", 4> " << getLowerName()
1091 OS
<< " " << getLowerName() << ".reserve(" << getLowerName()
1093 OS
<< " for (unsigned i = " << getLowerName() << "Size; i; --i)\n";
1094 OS
<< " " << getLowerName() << ".push_back(" << "static_cast<"
1095 << QualifiedTypeName
<< ">(Record.readInt()));\n";
1098 void writePCHWrite(raw_ostream
&OS
) const override
{
1099 OS
<< " Record.push_back(SA->" << getLowerName() << "_size());\n";
1100 OS
<< " for (" << getAttrName() << "Attr::" << getLowerName()
1101 << "_iterator i = SA->" << getLowerName() << "_begin(), e = SA->"
1102 << getLowerName() << "_end(); i != e; ++i)\n";
1103 OS
<< " " << WritePCHRecord(QualifiedTypeName
, "(*i)");
1106 void writeConversion(raw_ostream
&OS
, bool Header
) const {
1108 OS
<< " static bool ConvertStrTo" << type
<< "(StringRef Val, " << type
1110 OS
<< " static const char *Convert" << type
<< "ToStr(" << type
1115 OS
<< "bool " << getAttrName() << "Attr::ConvertStrTo" << type
1116 << "(StringRef Val, ";
1117 OS
<< type
<< " &Out) {\n";
1118 OS
<< " std::optional<" << type
1119 << "> R = llvm::StringSwitch<std::optional<";
1120 OS
<< type
<< ">>(Val)\n";
1121 for (size_t I
= 0; I
< enums
.size(); ++I
) {
1122 OS
<< " .Case(\"" << values
[I
] << "\", ";
1123 OS
<< getAttrName() << "Attr::" << enums
[I
] << ")\n";
1125 OS
<< " .Default(std::optional<" << type
<< ">());\n";
1126 OS
<< " if (R) {\n";
1127 OS
<< " Out = *R;\n return true;\n }\n";
1128 OS
<< " return false;\n";
1131 OS
<< "const char *" << getAttrName() << "Attr::Convert" << type
1132 << "ToStr(" << type
<< " Val) {\n"
1133 << " switch(Val) {\n";
1134 SmallDenseSet
<StringRef
, 8> Uniques
;
1135 for (size_t I
= 0; I
< enums
.size(); ++I
) {
1136 if (Uniques
.insert(enums
[I
]).second
)
1137 OS
<< " case " << getAttrName() << "Attr::" << enums
[I
]
1138 << ": return \"" << values
[I
] << "\";\n";
1141 << " llvm_unreachable(\"No enumerator with that value\");\n"
1146 class VersionArgument
: public Argument
{
1148 VersionArgument(const Record
&Arg
, StringRef Attr
)
1149 : Argument(Arg
, Attr
)
1152 void writeAccessors(raw_ostream
&OS
) const override
{
1153 OS
<< " VersionTuple get" << getUpperName() << "() const {\n";
1154 OS
<< " return " << getLowerName() << ";\n";
1156 OS
<< " void set" << getUpperName()
1157 << "(ASTContext &C, VersionTuple V) {\n";
1158 OS
<< " " << getLowerName() << " = V;\n";
1162 void writeCloneArgs(raw_ostream
&OS
) const override
{
1163 OS
<< "get" << getUpperName() << "()";
1166 void writeTemplateInstantiationArgs(raw_ostream
&OS
) const override
{
1167 OS
<< "A->get" << getUpperName() << "()";
1170 void writeCtorInitializers(raw_ostream
&OS
) const override
{
1171 OS
<< getLowerName() << "(" << getUpperName() << ")";
1174 void writeCtorDefaultInitializers(raw_ostream
&OS
) const override
{
1175 OS
<< getLowerName() << "()";
1178 void writeCtorParameters(raw_ostream
&OS
) const override
{
1179 OS
<< "VersionTuple " << getUpperName();
1182 void writeDeclarations(raw_ostream
&OS
) const override
{
1183 OS
<< "VersionTuple " << getLowerName() << ";\n";
1186 void writePCHReadDecls(raw_ostream
&OS
) const override
{
1187 OS
<< " VersionTuple " << getLowerName()
1188 << "= Record.readVersionTuple();\n";
1191 void writePCHReadArgs(raw_ostream
&OS
) const override
{
1192 OS
<< getLowerName();
1195 void writePCHWrite(raw_ostream
&OS
) const override
{
1196 OS
<< " Record.AddVersionTuple(SA->get" << getUpperName() << "());\n";
1199 void writeValue(raw_ostream
&OS
) const override
{
1200 OS
<< getLowerName() << "=\" << get" << getUpperName() << "() << \"";
1203 void writeDump(raw_ostream
&OS
) const override
{
1204 OS
<< " OS << \" \" << SA->get" << getUpperName() << "();\n";
1208 class ExprArgument
: public SimpleArgument
{
1210 ExprArgument(const Record
&Arg
, StringRef Attr
)
1211 : SimpleArgument(Arg
, Attr
, "Expr *")
1214 void writeASTVisitorTraversal(raw_ostream
&OS
) const override
{
1216 << "getDerived().TraverseStmt(A->get" << getUpperName() << "()))\n";
1217 OS
<< " return false;\n";
1220 void writeTemplateInstantiationArgs(raw_ostream
&OS
) const override
{
1221 OS
<< "tempInst" << getUpperName();
1224 void writeTemplateInstantiation(raw_ostream
&OS
) const override
{
1225 OS
<< " " << getType() << " tempInst" << getUpperName() << ";\n";
1227 OS
<< " EnterExpressionEvaluationContext "
1228 << "Unevaluated(S, Sema::ExpressionEvaluationContext::Unevaluated);\n";
1229 OS
<< " ExprResult " << "Result = S.SubstExpr("
1230 << "A->get" << getUpperName() << "(), TemplateArgs);\n";
1231 OS
<< " if (Result.isInvalid())\n";
1232 OS
<< " return nullptr;\n";
1233 OS
<< " tempInst" << getUpperName() << " = Result.get();\n";
1237 void writeValue(raw_ostream
&OS
) const override
{
1239 OS
<< " get" << getUpperName()
1240 << "()->printPretty(OS, nullptr, Policy);\n";
1244 void writeDump(raw_ostream
&OS
) const override
{}
1246 void writeDumpChildren(raw_ostream
&OS
) const override
{
1247 OS
<< " Visit(SA->get" << getUpperName() << "());\n";
1250 void writeHasChildren(raw_ostream
&OS
) const override
{ OS
<< "true"; }
1253 class VariadicExprArgument
: public VariadicArgument
{
1255 VariadicExprArgument(const Record
&Arg
, StringRef Attr
)
1256 : VariadicArgument(Arg
, Attr
, "Expr *")
1259 VariadicExprArgument(StringRef ArgName
, StringRef Attr
)
1260 : VariadicArgument(ArgName
, Attr
, "Expr *") {}
1262 void writeASTVisitorTraversal(raw_ostream
&OS
) const override
{
1264 OS
<< " " << getType() << " *I = A->" << getLowerName()
1266 OS
<< " " << getType() << " *E = A->" << getLowerName()
1268 OS
<< " for (; I != E; ++I) {\n";
1269 OS
<< " if (!getDerived().TraverseStmt(*I))\n";
1270 OS
<< " return false;\n";
1275 void writeTemplateInstantiationArgs(raw_ostream
&OS
) const override
{
1276 OS
<< "tempInst" << getUpperName() << ", "
1277 << "A->" << getLowerName() << "_size()";
1280 void writeTemplateInstantiation(raw_ostream
&OS
) const override
{
1281 OS
<< " auto *tempInst" << getUpperName()
1282 << " = new (C, 16) " << getType()
1283 << "[A->" << getLowerName() << "_size()];\n";
1285 OS
<< " EnterExpressionEvaluationContext "
1286 << "Unevaluated(S, Sema::ExpressionEvaluationContext::Unevaluated);\n";
1287 OS
<< " " << getType() << " *TI = tempInst" << getUpperName()
1289 OS
<< " " << getType() << " *I = A->" << getLowerName()
1291 OS
<< " " << getType() << " *E = A->" << getLowerName()
1293 OS
<< " for (; I != E; ++I, ++TI) {\n";
1294 OS
<< " ExprResult Result = S.SubstExpr(*I, TemplateArgs);\n";
1295 OS
<< " if (Result.isInvalid())\n";
1296 OS
<< " return nullptr;\n";
1297 OS
<< " *TI = Result.get();\n";
1302 void writeDump(raw_ostream
&OS
) const override
{}
1304 void writeDumpChildren(raw_ostream
&OS
) const override
{
1305 OS
<< " for (" << getAttrName() << "Attr::" << getLowerName()
1306 << "_iterator I = SA->" << getLowerName() << "_begin(), E = SA->"
1307 << getLowerName() << "_end(); I != E; ++I)\n";
1308 OS
<< " Visit(*I);\n";
1311 void writeHasChildren(raw_ostream
&OS
) const override
{
1312 OS
<< "SA->" << getLowerName() << "_begin() != "
1313 << "SA->" << getLowerName() << "_end()";
1317 class VariadicIdentifierArgument
: public VariadicArgument
{
1319 VariadicIdentifierArgument(const Record
&Arg
, StringRef Attr
)
1320 : VariadicArgument(Arg
, Attr
, "IdentifierInfo *")
1324 class VariadicStringArgument
: public VariadicArgument
{
1326 VariadicStringArgument(const Record
&Arg
, StringRef Attr
)
1327 : VariadicArgument(Arg
, Attr
, "StringRef")
1330 void writeCtorBody(raw_ostream
&OS
) const override
{
1331 OS
<< " for (size_t I = 0, E = " << getArgSizeName() << "; I != E;\n"
1333 " StringRef Ref = " << getUpperName() << "[I];\n"
1334 " if (!Ref.empty()) {\n"
1335 " char *Mem = new (Ctx, 1) char[Ref.size()];\n"
1336 " std::memcpy(Mem, Ref.data(), Ref.size());\n"
1337 " " << getArgName() << "[I] = StringRef(Mem, Ref.size());\n"
1342 void writeValueImpl(raw_ostream
&OS
) const override
{
1343 OS
<< " OS << \"\\\"\" << Val << \"\\\"\";\n";
1347 class TypeArgument
: public SimpleArgument
{
1349 TypeArgument(const Record
&Arg
, StringRef Attr
)
1350 : SimpleArgument(Arg
, Attr
, "TypeSourceInfo *")
1353 void writeAccessors(raw_ostream
&OS
) const override
{
1354 OS
<< " QualType get" << getUpperName() << "() const {\n";
1355 OS
<< " return " << getLowerName() << "->getType();\n";
1357 OS
<< " " << getType() << " get" << getUpperName() << "Loc() const {\n";
1358 OS
<< " return " << getLowerName() << ";\n";
1362 void writeASTVisitorTraversal(raw_ostream
&OS
) const override
{
1363 OS
<< " if (auto *TSI = A->get" << getUpperName() << "Loc())\n";
1364 OS
<< " if (!getDerived().TraverseTypeLoc(TSI->getTypeLoc()))\n";
1365 OS
<< " return false;\n";
1368 void writeTemplateInstantiation(raw_ostream
&OS
) const override
{
1369 OS
<< " " << getType() << " tempInst" << getUpperName() << " =\n";
1370 OS
<< " S.SubstType(A->get" << getUpperName() << "Loc(), "
1371 << "TemplateArgs, A->getLoc(), A->getAttrName());\n";
1372 OS
<< " if (!tempInst" << getUpperName() << ")\n";
1373 OS
<< " return nullptr;\n";
1376 void writeTemplateInstantiationArgs(raw_ostream
&OS
) const override
{
1377 OS
<< "tempInst" << getUpperName();
1380 void writePCHWrite(raw_ostream
&OS
) const override
{
1382 << WritePCHRecord(getType(),
1383 "SA->get" + std::string(getUpperName()) + "Loc()");
1387 } // end anonymous namespace
1389 static std::unique_ptr
<Argument
>
1390 createArgument(const Record
&Arg
, StringRef Attr
,
1391 const Record
*Search
= nullptr) {
1395 std::unique_ptr
<Argument
> Ptr
;
1396 llvm::StringRef ArgName
= Search
->getName();
1398 if (ArgName
== "AlignedArgument")
1399 Ptr
= std::make_unique
<AlignedArgument
>(Arg
, Attr
);
1400 else if (ArgName
== "EnumArgument")
1401 Ptr
= std::make_unique
<EnumArgument
>(Arg
, Attr
);
1402 else if (ArgName
== "ExprArgument")
1403 Ptr
= std::make_unique
<ExprArgument
>(Arg
, Attr
);
1404 else if (ArgName
== "DeclArgument")
1405 Ptr
= std::make_unique
<SimpleArgument
>(
1406 Arg
, Attr
, (Arg
.getValueAsDef("Kind")->getName() + "Decl *").str());
1407 else if (ArgName
== "IdentifierArgument")
1408 Ptr
= std::make_unique
<SimpleArgument
>(Arg
, Attr
, "IdentifierInfo *");
1409 else if (ArgName
== "DefaultBoolArgument")
1410 Ptr
= std::make_unique
<DefaultSimpleArgument
>(
1411 Arg
, Attr
, "bool", Arg
.getValueAsBit("Default"));
1412 else if (ArgName
== "BoolArgument")
1413 Ptr
= std::make_unique
<SimpleArgument
>(Arg
, Attr
, "bool");
1414 else if (ArgName
== "DefaultIntArgument")
1415 Ptr
= std::make_unique
<DefaultSimpleArgument
>(
1416 Arg
, Attr
, "int", Arg
.getValueAsInt("Default"));
1417 else if (ArgName
== "IntArgument")
1418 Ptr
= std::make_unique
<SimpleArgument
>(Arg
, Attr
, "int");
1419 else if (ArgName
== "StringArgument")
1420 Ptr
= std::make_unique
<StringArgument
>(Arg
, Attr
);
1421 else if (ArgName
== "TypeArgument")
1422 Ptr
= std::make_unique
<TypeArgument
>(Arg
, Attr
);
1423 else if (ArgName
== "UnsignedArgument")
1424 Ptr
= std::make_unique
<SimpleArgument
>(Arg
, Attr
, "unsigned");
1425 else if (ArgName
== "VariadicUnsignedArgument")
1426 Ptr
= std::make_unique
<VariadicArgument
>(Arg
, Attr
, "unsigned");
1427 else if (ArgName
== "VariadicStringArgument")
1428 Ptr
= std::make_unique
<VariadicStringArgument
>(Arg
, Attr
);
1429 else if (ArgName
== "VariadicEnumArgument")
1430 Ptr
= std::make_unique
<VariadicEnumArgument
>(Arg
, Attr
);
1431 else if (ArgName
== "VariadicExprArgument")
1432 Ptr
= std::make_unique
<VariadicExprArgument
>(Arg
, Attr
);
1433 else if (ArgName
== "VariadicParamIdxArgument")
1434 Ptr
= std::make_unique
<VariadicParamIdxArgument
>(Arg
, Attr
);
1435 else if (ArgName
== "VariadicParamOrParamIdxArgument")
1436 Ptr
= std::make_unique
<VariadicParamOrParamIdxArgument
>(Arg
, Attr
);
1437 else if (ArgName
== "ParamIdxArgument")
1438 Ptr
= std::make_unique
<SimpleArgument
>(Arg
, Attr
, "ParamIdx");
1439 else if (ArgName
== "VariadicIdentifierArgument")
1440 Ptr
= std::make_unique
<VariadicIdentifierArgument
>(Arg
, Attr
);
1441 else if (ArgName
== "VersionArgument")
1442 Ptr
= std::make_unique
<VersionArgument
>(Arg
, Attr
);
1443 else if (ArgName
== "OMPTraitInfoArgument")
1444 Ptr
= std::make_unique
<SimpleArgument
>(Arg
, Attr
, "OMPTraitInfo *");
1445 else if (ArgName
== "VariadicOMPInteropInfoArgument")
1446 Ptr
= std::make_unique
<VariadicOMPInteropInfoArgument
>(Arg
, Attr
);
1449 // Search in reverse order so that the most-derived type is handled first.
1450 ArrayRef
<std::pair
<Record
*, SMRange
>> Bases
= Search
->getSuperClasses();
1451 for (const auto &Base
: llvm::reverse(Bases
)) {
1452 if ((Ptr
= createArgument(Arg
, Attr
, Base
.first
)))
1457 if (Ptr
&& Arg
.getValueAsBit("Optional"))
1458 Ptr
->setOptional(true);
1460 if (Ptr
&& Arg
.getValueAsBit("Fake"))
1466 static void writeAvailabilityValue(raw_ostream
&OS
) {
1467 OS
<< "\" << getPlatform()->getName();\n"
1468 << " if (getStrict()) OS << \", strict\";\n"
1469 << " if (!getIntroduced().empty()) OS << \", introduced=\" << getIntroduced();\n"
1470 << " if (!getDeprecated().empty()) OS << \", deprecated=\" << getDeprecated();\n"
1471 << " if (!getObsoleted().empty()) OS << \", obsoleted=\" << getObsoleted();\n"
1472 << " if (getUnavailable()) OS << \", unavailable\";\n"
1476 static void writeDeprecatedAttrValue(raw_ostream
&OS
, std::string
&Variety
) {
1477 OS
<< "\\\"\" << getMessage() << \"\\\"\";\n";
1478 // Only GNU deprecated has an optional fixit argument at the second position.
1479 if (Variety
== "GNU")
1480 OS
<< " if (!getReplacement().empty()) OS << \", \\\"\""
1481 " << getReplacement() << \"\\\"\";\n";
1485 static void writeGetSpellingFunction(const Record
&R
, raw_ostream
&OS
) {
1486 std::vector
<FlattenedSpelling
> Spellings
= GetFlattenedSpellings(R
);
1488 OS
<< "const char *" << R
.getName() << "Attr::getSpelling() const {\n";
1489 if (Spellings
.empty()) {
1490 OS
<< " return \"(No spelling)\";\n}\n\n";
1494 OS
<< " switch (getAttributeSpellingListIndex()) {\n"
1496 " llvm_unreachable(\"Unknown attribute spelling!\");\n"
1497 " return \"(No spelling)\";\n";
1499 for (unsigned I
= 0; I
< Spellings
.size(); ++I
)
1500 OS
<< " case " << I
<< ":\n"
1501 " return \"" << Spellings
[I
].name() << "\";\n";
1502 // End of the switch statement.
1504 // End of the getSpelling function.
1509 writePrettyPrintFunction(const Record
&R
,
1510 const std::vector
<std::unique_ptr
<Argument
>> &Args
,
1512 std::vector
<FlattenedSpelling
> Spellings
= GetFlattenedSpellings(R
);
1514 OS
<< "void " << R
.getName() << "Attr::printPretty("
1515 << "raw_ostream &OS, const PrintingPolicy &Policy) const {\n";
1517 if (Spellings
.empty()) {
1522 OS
<< " bool IsFirstArgument = true; (void)IsFirstArgument;\n"
1523 << " unsigned TrailingOmittedArgs = 0; (void)TrailingOmittedArgs;\n"
1524 << " switch (getAttributeSpellingListIndex()) {\n"
1526 << " llvm_unreachable(\"Unknown attribute spelling!\");\n"
1529 for (unsigned I
= 0; I
< Spellings
.size(); ++ I
) {
1530 llvm::SmallString
<16> Prefix
;
1531 llvm::SmallString
<8> Suffix
;
1532 // The actual spelling of the name and namespace (if applicable)
1533 // of an attribute without considering prefix and suffix.
1534 llvm::SmallString
<64> Spelling
;
1535 std::string Name
= Spellings
[I
].name();
1536 std::string Variety
= Spellings
[I
].variety();
1538 if (Variety
== "GNU") {
1539 Prefix
= " __attribute__((";
1541 } else if (Variety
== "CXX11" || Variety
== "C23") {
1544 std::string Namespace
= Spellings
[I
].nameSpace();
1545 if (!Namespace
.empty()) {
1546 Spelling
+= Namespace
;
1549 } else if (Variety
== "Declspec") {
1550 Prefix
= " __declspec(";
1552 } else if (Variety
== "Microsoft") {
1555 } else if (Variety
== "Keyword") {
1558 } else if (Variety
== "Pragma") {
1559 Prefix
= "#pragma ";
1561 std::string Namespace
= Spellings
[I
].nameSpace();
1562 if (!Namespace
.empty()) {
1563 Spelling
+= Namespace
;
1566 } else if (Variety
== "HLSLSemantic") {
1570 llvm_unreachable("Unknown attribute syntax variety!");
1575 OS
<< " case " << I
<< " : {\n"
1576 << " OS << \"" << Prefix
<< Spelling
<< "\";\n";
1578 if (Variety
== "Pragma") {
1579 OS
<< " printPrettyPragma(OS, Policy);\n";
1580 OS
<< " OS << \"\\n\";";
1586 if (Spelling
== "availability") {
1588 writeAvailabilityValue(OS
);
1590 } else if (Spelling
== "deprecated" || Spelling
== "gnu::deprecated") {
1592 writeDeprecatedAttrValue(OS
, Variety
);
1595 // To avoid printing parentheses around an empty argument list or
1596 // printing spurious commas at the end of an argument list, we need to
1597 // determine where the last provided non-fake argument is.
1598 bool FoundNonOptArg
= false;
1599 for (const auto &arg
: llvm::reverse(Args
)) {
1604 // FIXME: arg->getIsOmitted() == "false" means we haven't implemented
1605 // any way to detect whether the argument was omitted.
1606 if (!arg
->isOptional() || arg
->getIsOmitted() == "false") {
1607 FoundNonOptArg
= true;
1610 OS
<< " if (" << arg
->getIsOmitted() << ")\n"
1611 << " ++TrailingOmittedArgs;\n";
1613 unsigned ArgIndex
= 0;
1614 for (const auto &arg
: Args
) {
1617 std::string IsOmitted
= arg
->getIsOmitted();
1618 if (arg
->isOptional() && IsOmitted
!= "false")
1619 OS
<< " if (!(" << IsOmitted
<< ")) {\n";
1620 // Variadic arguments print their own leading comma.
1621 if (!arg
->isVariadic())
1622 OS
<< " DelimitAttributeArgument(OS, IsFirstArgument);\n";
1624 arg
->writeValue(OS
);
1626 if (arg
->isOptional() && IsOmitted
!= "false")
1631 OS
<< " if (!IsFirstArgument)\n"
1632 << " OS << \")\";\n";
1634 OS
<< " OS << \"" << Suffix
<< "\";\n"
1639 // End of the switch statement.
1641 // End of the print function.
1645 /// Return the index of a spelling in a spelling list.
1647 getSpellingListIndex(const std::vector
<FlattenedSpelling
> &SpellingList
,
1648 const FlattenedSpelling
&Spelling
) {
1649 assert(!SpellingList
.empty() && "Spelling list is empty!");
1651 for (unsigned Index
= 0; Index
< SpellingList
.size(); ++Index
) {
1652 const FlattenedSpelling
&S
= SpellingList
[Index
];
1653 if (S
.variety() != Spelling
.variety())
1655 if (S
.nameSpace() != Spelling
.nameSpace())
1657 if (S
.name() != Spelling
.name())
1663 llvm_unreachable("Unknown spelling!");
1666 static void writeAttrAccessorDefinition(const Record
&R
, raw_ostream
&OS
) {
1667 std::vector
<Record
*> Accessors
= R
.getValueAsListOfDefs("Accessors");
1668 if (Accessors
.empty())
1671 const std::vector
<FlattenedSpelling
> SpellingList
= GetFlattenedSpellings(R
);
1672 assert(!SpellingList
.empty() &&
1673 "Attribute with empty spelling list can't have accessors!");
1674 for (const auto *Accessor
: Accessors
) {
1675 const StringRef Name
= Accessor
->getValueAsString("Name");
1676 std::vector
<FlattenedSpelling
> Spellings
= GetFlattenedSpellings(*Accessor
);
1678 OS
<< " bool " << Name
1679 << "() const { return getAttributeSpellingListIndex() == ";
1680 for (unsigned Index
= 0; Index
< Spellings
.size(); ++Index
) {
1681 OS
<< getSpellingListIndex(SpellingList
, Spellings
[Index
]);
1682 if (Index
!= Spellings
.size() - 1)
1683 OS
<< " ||\n getAttributeSpellingListIndex() == ";
1691 SpellingNamesAreCommon(const std::vector
<FlattenedSpelling
>& Spellings
) {
1692 assert(!Spellings
.empty() && "An empty list of spellings was provided");
1693 std::string FirstName
=
1694 std::string(NormalizeNameForSpellingComparison(Spellings
.front().name()));
1695 for (const auto &Spelling
:
1696 llvm::make_range(std::next(Spellings
.begin()), Spellings
.end())) {
1698 std::string(NormalizeNameForSpellingComparison(Spelling
.name()));
1699 if (Name
!= FirstName
)
1705 typedef std::map
<unsigned, std::string
> SemanticSpellingMap
;
1707 CreateSemanticSpellings(const std::vector
<FlattenedSpelling
> &Spellings
,
1708 SemanticSpellingMap
&Map
) {
1709 // The enumerants are automatically generated based on the variety,
1710 // namespace (if present) and name for each attribute spelling. However,
1711 // care is taken to avoid trampling on the reserved namespace due to
1713 std::string
Ret(" enum Spelling {\n");
1714 std::set
<std::string
> Uniques
;
1717 // If we have a need to have this many spellings we likely need to add an
1718 // extra bit to the SpellingIndex in AttributeCommonInfo, then increase the
1719 // value of SpellingNotCalculated there and here.
1720 assert(Spellings
.size() < 15 &&
1721 "Too many spellings, would step on SpellingNotCalculated in "
1722 "AttributeCommonInfo");
1723 for (auto I
= Spellings
.begin(), E
= Spellings
.end(); I
!= E
; ++I
, ++Idx
) {
1724 const FlattenedSpelling
&S
= *I
;
1725 const std::string
&Variety
= S
.variety();
1726 const std::string
&Spelling
= S
.name();
1727 const std::string
&Namespace
= S
.nameSpace();
1728 std::string EnumName
;
1730 EnumName
+= (Variety
+ "_");
1731 if (!Namespace
.empty())
1732 EnumName
+= (NormalizeNameForSpellingComparison(Namespace
).str() +
1734 EnumName
+= NormalizeNameForSpellingComparison(Spelling
);
1736 // Even if the name is not unique, this spelling index corresponds to a
1737 // particular enumerant name that we've calculated.
1738 Map
[Idx
] = EnumName
;
1740 // Since we have been stripping underscores to avoid trampling on the
1741 // reserved namespace, we may have inadvertently created duplicate
1742 // enumerant names. These duplicates are not considered part of the
1743 // semantic spelling, and can be elided.
1744 if (Uniques
.find(EnumName
) != Uniques
.end())
1747 Uniques
.insert(EnumName
);
1748 if (I
!= Spellings
.begin())
1750 // Duplicate spellings are not considered part of the semantic spelling
1751 // enumeration, but the spelling index and semantic spelling values are
1752 // meant to be equivalent, so we must specify a concrete value for each
1754 Ret
+= " " + EnumName
+ " = " + llvm::utostr(Idx
);
1756 Ret
+= ",\n SpellingNotCalculated = 15\n";
1761 void WriteSemanticSpellingSwitch(const std::string
&VarName
,
1762 const SemanticSpellingMap
&Map
,
1764 OS
<< " switch (" << VarName
<< ") {\n default: "
1765 << "llvm_unreachable(\"Unknown spelling list index\");\n";
1766 for (const auto &I
: Map
)
1767 OS
<< " case " << I
.first
<< ": return " << I
.second
<< ";\n";
1771 // Emits the LateParsed property for attributes.
1772 static void emitClangAttrLateParsedList(RecordKeeper
&Records
, raw_ostream
&OS
) {
1773 OS
<< "#if defined(CLANG_ATTR_LATE_PARSED_LIST)\n";
1774 std::vector
<Record
*> Attrs
= Records
.getAllDerivedDefinitions("Attr");
1776 for (const auto *Attr
: Attrs
) {
1777 bool LateParsed
= Attr
->getValueAsBit("LateParsed");
1780 std::vector
<FlattenedSpelling
> Spellings
= GetFlattenedSpellings(*Attr
);
1782 // FIXME: Handle non-GNU attributes
1783 for (const auto &I
: Spellings
) {
1784 if (I
.variety() != "GNU")
1786 OS
<< ".Case(\"" << I
.name() << "\", " << LateParsed
<< ")\n";
1790 OS
<< "#endif // CLANG_ATTR_LATE_PARSED_LIST\n\n";
1793 static bool hasGNUorCXX11Spelling(const Record
&Attribute
) {
1794 std::vector
<FlattenedSpelling
> Spellings
= GetFlattenedSpellings(Attribute
);
1795 for (const auto &I
: Spellings
) {
1796 if (I
.variety() == "GNU" || I
.variety() == "CXX11")
1804 struct AttributeSubjectMatchRule
{
1805 const Record
*MetaSubject
;
1806 const Record
*Constraint
;
1808 AttributeSubjectMatchRule(const Record
*MetaSubject
, const Record
*Constraint
)
1809 : MetaSubject(MetaSubject
), Constraint(Constraint
) {
1810 assert(MetaSubject
&& "Missing subject");
1813 bool isSubRule() const { return Constraint
!= nullptr; }
1815 std::vector
<Record
*> getSubjects() const {
1816 return (Constraint
? Constraint
: MetaSubject
)
1817 ->getValueAsListOfDefs("Subjects");
1820 std::vector
<Record
*> getLangOpts() const {
1822 // Lookup the options in the sub-rule first, in case the sub-rule
1823 // overrides the rules options.
1824 std::vector
<Record
*> Opts
= Constraint
->getValueAsListOfDefs("LangOpts");
1828 return MetaSubject
->getValueAsListOfDefs("LangOpts");
1831 // Abstract rules are used only for sub-rules
1832 bool isAbstractRule() const { return getSubjects().empty(); }
1834 StringRef
getName() const {
1835 return (Constraint
? Constraint
: MetaSubject
)->getValueAsString("Name");
1838 bool isNegatedSubRule() const {
1839 assert(isSubRule() && "Not a sub-rule");
1840 return Constraint
->getValueAsBit("Negated");
1843 std::string
getSpelling() const {
1844 std::string Result
= std::string(MetaSubject
->getValueAsString("Name"));
1847 if (isNegatedSubRule())
1848 Result
+= "unless(";
1849 Result
+= getName();
1850 if (isNegatedSubRule())
1857 std::string
getEnumValueName() const {
1858 SmallString
<128> Result
;
1859 Result
+= "SubjectMatchRule_";
1860 Result
+= MetaSubject
->getValueAsString("Name");
1863 if (isNegatedSubRule())
1865 Result
+= Constraint
->getValueAsString("Name");
1867 if (isAbstractRule())
1868 Result
+= "_abstract";
1869 return std::string(Result
.str());
1872 std::string
getEnumValue() const { return "attr::" + getEnumValueName(); }
1874 static const char *EnumName
;
1877 const char *AttributeSubjectMatchRule::EnumName
= "attr::SubjectMatchRule";
1879 struct PragmaClangAttributeSupport
{
1880 std::vector
<AttributeSubjectMatchRule
> Rules
;
1882 class RuleOrAggregateRuleSet
{
1883 std::vector
<AttributeSubjectMatchRule
> Rules
;
1885 RuleOrAggregateRuleSet(ArrayRef
<AttributeSubjectMatchRule
> Rules
,
1887 : Rules(Rules
), IsRule(IsRule
) {}
1890 bool isRule() const { return IsRule
; }
1892 const AttributeSubjectMatchRule
&getRule() const {
1893 assert(IsRule
&& "not a rule!");
1897 ArrayRef
<AttributeSubjectMatchRule
> getAggregateRuleSet() const {
1901 static RuleOrAggregateRuleSet
1902 getRule(const AttributeSubjectMatchRule
&Rule
) {
1903 return RuleOrAggregateRuleSet(Rule
, /*IsRule=*/true);
1905 static RuleOrAggregateRuleSet
1906 getAggregateRuleSet(ArrayRef
<AttributeSubjectMatchRule
> Rules
) {
1907 return RuleOrAggregateRuleSet(Rules
, /*IsRule=*/false);
1910 llvm::DenseMap
<const Record
*, RuleOrAggregateRuleSet
> SubjectsToRules
;
1912 PragmaClangAttributeSupport(RecordKeeper
&Records
);
1914 bool isAttributedSupported(const Record
&Attribute
);
1916 void emitMatchRuleList(raw_ostream
&OS
);
1918 void generateStrictConformsTo(const Record
&Attr
, raw_ostream
&OS
);
1920 void generateParsingHelpers(raw_ostream
&OS
);
1923 } // end anonymous namespace
1925 static bool isSupportedPragmaClangAttributeSubject(const Record
&Subject
) {
1926 // FIXME: #pragma clang attribute does not currently support statement
1927 // attributes, so test whether the subject is one that appertains to a
1928 // declaration node. However, it may be reasonable for support for statement
1929 // attributes to be added.
1930 if (Subject
.isSubClassOf("DeclNode") || Subject
.isSubClassOf("DeclBase") ||
1931 Subject
.getName() == "DeclBase")
1934 if (Subject
.isSubClassOf("SubsetSubject"))
1935 return isSupportedPragmaClangAttributeSubject(
1936 *Subject
.getValueAsDef("Base"));
1941 static bool doesDeclDeriveFrom(const Record
*D
, const Record
*Base
) {
1942 const Record
*CurrentBase
= D
->getValueAsOptionalDef(BaseFieldName
);
1945 if (CurrentBase
== Base
)
1947 return doesDeclDeriveFrom(CurrentBase
, Base
);
1950 PragmaClangAttributeSupport::PragmaClangAttributeSupport(
1951 RecordKeeper
&Records
) {
1952 std::vector
<Record
*> MetaSubjects
=
1953 Records
.getAllDerivedDefinitions("AttrSubjectMatcherRule");
1954 auto MapFromSubjectsToRules
= [this](const Record
*SubjectContainer
,
1955 const Record
*MetaSubject
,
1956 const Record
*Constraint
) {
1957 Rules
.emplace_back(MetaSubject
, Constraint
);
1958 std::vector
<Record
*> ApplicableSubjects
=
1959 SubjectContainer
->getValueAsListOfDefs("Subjects");
1960 for (const auto *Subject
: ApplicableSubjects
) {
1963 .try_emplace(Subject
, RuleOrAggregateRuleSet::getRule(
1964 AttributeSubjectMatchRule(MetaSubject
,
1968 PrintFatalError("Attribute subject match rules should not represent"
1969 "same attribute subjects.");
1973 for (const auto *MetaSubject
: MetaSubjects
) {
1974 MapFromSubjectsToRules(MetaSubject
, MetaSubject
, /*Constraints=*/nullptr);
1975 std::vector
<Record
*> Constraints
=
1976 MetaSubject
->getValueAsListOfDefs("Constraints");
1977 for (const auto *Constraint
: Constraints
)
1978 MapFromSubjectsToRules(Constraint
, MetaSubject
, Constraint
);
1981 std::vector
<Record
*> Aggregates
=
1982 Records
.getAllDerivedDefinitions("AttrSubjectMatcherAggregateRule");
1983 std::vector
<Record
*> DeclNodes
=
1984 Records
.getAllDerivedDefinitions(DeclNodeClassName
);
1985 for (const auto *Aggregate
: Aggregates
) {
1986 Record
*SubjectDecl
= Aggregate
->getValueAsDef("Subject");
1988 // Gather sub-classes of the aggregate subject that act as attribute
1990 std::vector
<AttributeSubjectMatchRule
> Rules
;
1991 for (const auto *D
: DeclNodes
) {
1992 if (doesDeclDeriveFrom(D
, SubjectDecl
)) {
1993 auto It
= SubjectsToRules
.find(D
);
1994 if (It
== SubjectsToRules
.end())
1996 if (!It
->second
.isRule() || It
->second
.getRule().isSubRule())
1997 continue; // Assume that the rule will be included as well.
1998 Rules
.push_back(It
->second
.getRule());
2004 .try_emplace(SubjectDecl
,
2005 RuleOrAggregateRuleSet::getAggregateRuleSet(Rules
))
2008 PrintFatalError("Attribute subject match rules should not represent"
2009 "same attribute subjects.");
2014 static PragmaClangAttributeSupport
&
2015 getPragmaAttributeSupport(RecordKeeper
&Records
) {
2016 static PragmaClangAttributeSupport
Instance(Records
);
2020 void PragmaClangAttributeSupport::emitMatchRuleList(raw_ostream
&OS
) {
2021 OS
<< "#ifndef ATTR_MATCH_SUB_RULE\n";
2022 OS
<< "#define ATTR_MATCH_SUB_RULE(Value, Spelling, IsAbstract, Parent, "
2024 << "ATTR_MATCH_RULE(Value, Spelling, IsAbstract)\n";
2026 for (const auto &Rule
: Rules
) {
2027 OS
<< (Rule
.isSubRule() ? "ATTR_MATCH_SUB_RULE" : "ATTR_MATCH_RULE") << '(';
2028 OS
<< Rule
.getEnumValueName() << ", \"" << Rule
.getSpelling() << "\", "
2029 << Rule
.isAbstractRule();
2030 if (Rule
.isSubRule())
2032 << AttributeSubjectMatchRule(Rule
.MetaSubject
, nullptr).getEnumValue()
2033 << ", " << Rule
.isNegatedSubRule();
2036 OS
<< "#undef ATTR_MATCH_SUB_RULE\n";
2039 bool PragmaClangAttributeSupport::isAttributedSupported(
2040 const Record
&Attribute
) {
2041 // If the attribute explicitly specified whether to support #pragma clang
2042 // attribute, use that setting.
2044 bool SpecifiedResult
=
2045 Attribute
.getValueAsBitOrUnset("PragmaAttributeSupport", Unset
);
2047 return SpecifiedResult
;
2050 // An attribute requires delayed parsing (LateParsed is on)
2051 if (Attribute
.getValueAsBit("LateParsed"))
2053 // An attribute has no GNU/CXX11 spelling
2054 if (!hasGNUorCXX11Spelling(Attribute
))
2056 // An attribute subject list has a subject that isn't covered by one of the
2057 // subject match rules or has no subjects at all.
2058 if (Attribute
.isValueUnset("Subjects"))
2060 const Record
*SubjectObj
= Attribute
.getValueAsDef("Subjects");
2061 std::vector
<Record
*> Subjects
= SubjectObj
->getValueAsListOfDefs("Subjects");
2062 bool HasAtLeastOneValidSubject
= false;
2063 for (const auto *Subject
: Subjects
) {
2064 if (!isSupportedPragmaClangAttributeSubject(*Subject
))
2066 if (!SubjectsToRules
.contains(Subject
))
2068 HasAtLeastOneValidSubject
= true;
2070 return HasAtLeastOneValidSubject
;
2073 static std::string
GenerateTestExpression(ArrayRef
<Record
*> LangOpts
) {
2076 for (auto *E
: LangOpts
) {
2080 const StringRef Code
= E
->getValueAsString("CustomCode");
2081 if (!Code
.empty()) {
2085 if (!E
->getValueAsString("Name").empty()) {
2088 "non-empty 'Name' field ignored because 'CustomCode' was supplied");
2091 Test
+= "LangOpts.";
2092 Test
+= E
->getValueAsString("Name");
2103 PragmaClangAttributeSupport::generateStrictConformsTo(const Record
&Attr
,
2105 if (!isAttributedSupported(Attr
) || Attr
.isValueUnset("Subjects"))
2107 // Generate a function that constructs a set of matching rules that describe
2108 // to which declarations the attribute should apply to.
2109 OS
<< "void getPragmaAttributeMatchRules("
2110 << "llvm::SmallVectorImpl<std::pair<"
2111 << AttributeSubjectMatchRule::EnumName
2112 << ", bool>> &MatchRules, const LangOptions &LangOpts) const override {\n";
2113 const Record
*SubjectObj
= Attr
.getValueAsDef("Subjects");
2114 std::vector
<Record
*> Subjects
= SubjectObj
->getValueAsListOfDefs("Subjects");
2115 for (const auto *Subject
: Subjects
) {
2116 if (!isSupportedPragmaClangAttributeSubject(*Subject
))
2118 auto It
= SubjectsToRules
.find(Subject
);
2119 assert(It
!= SubjectsToRules
.end() &&
2120 "This attribute is unsupported by #pragma clang attribute");
2121 for (const auto &Rule
: It
->getSecond().getAggregateRuleSet()) {
2122 // The rule might be language specific, so only subtract it from the given
2123 // rules if the specific language options are specified.
2124 std::vector
<Record
*> LangOpts
= Rule
.getLangOpts();
2125 OS
<< " MatchRules.push_back(std::make_pair(" << Rule
.getEnumValue()
2126 << ", /*IsSupported=*/" << GenerateTestExpression(LangOpts
)
2133 void PragmaClangAttributeSupport::generateParsingHelpers(raw_ostream
&OS
) {
2134 // Generate routines that check the names of sub-rules.
2135 OS
<< "std::optional<attr::SubjectMatchRule> "
2136 "defaultIsAttributeSubjectMatchSubRuleFor(StringRef, bool) {\n";
2137 OS
<< " return std::nullopt;\n";
2140 llvm::MapVector
<const Record
*, std::vector
<AttributeSubjectMatchRule
>>
2142 for (const auto &Rule
: Rules
) {
2143 if (!Rule
.isSubRule())
2145 SubMatchRules
[Rule
.MetaSubject
].push_back(Rule
);
2148 for (const auto &SubMatchRule
: SubMatchRules
) {
2149 OS
<< "std::optional<attr::SubjectMatchRule> "
2150 "isAttributeSubjectMatchSubRuleFor_"
2151 << SubMatchRule
.first
->getValueAsString("Name")
2152 << "(StringRef Name, bool IsUnless) {\n";
2153 OS
<< " if (IsUnless)\n";
2155 "llvm::StringSwitch<std::optional<attr::SubjectMatchRule>>(Name).\n";
2156 for (const auto &Rule
: SubMatchRule
.second
) {
2157 if (Rule
.isNegatedSubRule())
2158 OS
<< " Case(\"" << Rule
.getName() << "\", " << Rule
.getEnumValue()
2161 OS
<< " Default(std::nullopt);\n";
2163 "llvm::StringSwitch<std::optional<attr::SubjectMatchRule>>(Name).\n";
2164 for (const auto &Rule
: SubMatchRule
.second
) {
2165 if (!Rule
.isNegatedSubRule())
2166 OS
<< " Case(\"" << Rule
.getName() << "\", " << Rule
.getEnumValue()
2169 OS
<< " Default(std::nullopt);\n";
2173 // Generate the function that checks for the top-level rules.
2174 OS
<< "std::pair<std::optional<attr::SubjectMatchRule>, "
2175 "std::optional<attr::SubjectMatchRule> (*)(StringRef, "
2176 "bool)> isAttributeSubjectMatchRule(StringRef Name) {\n";
2178 "llvm::StringSwitch<std::pair<std::optional<attr::SubjectMatchRule>, "
2179 "std::optional<attr::SubjectMatchRule> (*) (StringRef, "
2181 for (const auto &Rule
: Rules
) {
2182 if (Rule
.isSubRule())
2184 std::string SubRuleFunction
;
2185 if (SubMatchRules
.count(Rule
.MetaSubject
))
2187 ("isAttributeSubjectMatchSubRuleFor_" + Rule
.getName()).str();
2189 SubRuleFunction
= "defaultIsAttributeSubjectMatchSubRuleFor";
2190 OS
<< " Case(\"" << Rule
.getName() << "\", std::make_pair("
2191 << Rule
.getEnumValue() << ", " << SubRuleFunction
<< ")).\n";
2193 OS
<< " Default(std::make_pair(std::nullopt, "
2194 "defaultIsAttributeSubjectMatchSubRuleFor));\n";
2197 // Generate the function that checks for the submatch rules.
2198 OS
<< "const char *validAttributeSubjectMatchSubRules("
2199 << AttributeSubjectMatchRule::EnumName
<< " Rule) {\n";
2200 OS
<< " switch (Rule) {\n";
2201 for (const auto &SubMatchRule
: SubMatchRules
) {
2203 << AttributeSubjectMatchRule(SubMatchRule
.first
, nullptr).getEnumValue()
2205 OS
<< " return \"'";
2206 bool IsFirst
= true;
2207 for (const auto &Rule
: SubMatchRule
.second
) {
2211 if (Rule
.isNegatedSubRule())
2213 OS
<< Rule
.getName();
2214 if (Rule
.isNegatedSubRule())
2220 OS
<< " default: return nullptr;\n";
2225 template <typename Fn
>
2226 static void forEachUniqueSpelling(const Record
&Attr
, Fn
&&F
) {
2227 std::vector
<FlattenedSpelling
> Spellings
= GetFlattenedSpellings(Attr
);
2228 SmallDenseSet
<StringRef
, 8> Seen
;
2229 for (const FlattenedSpelling
&S
: Spellings
) {
2230 if (Seen
.insert(S
.name()).second
)
2235 static bool isTypeArgument(const Record
*Arg
) {
2236 return !Arg
->getSuperClasses().empty() &&
2237 Arg
->getSuperClasses().back().first
->getName() == "TypeArgument";
2240 /// Emits the first-argument-is-type property for attributes.
2241 static void emitClangAttrTypeArgList(RecordKeeper
&Records
, raw_ostream
&OS
) {
2242 OS
<< "#if defined(CLANG_ATTR_TYPE_ARG_LIST)\n";
2243 std::vector
<Record
*> Attrs
= Records
.getAllDerivedDefinitions("Attr");
2245 for (const auto *Attr
: Attrs
) {
2246 // Determine whether the first argument is a type.
2247 std::vector
<Record
*> Args
= Attr
->getValueAsListOfDefs("Args");
2251 if (!isTypeArgument(Args
[0]))
2254 // All these spellings take a single type argument.
2255 forEachUniqueSpelling(*Attr
, [&](const FlattenedSpelling
&S
) {
2256 OS
<< ".Case(\"" << S
.name() << "\", " << "true" << ")\n";
2259 OS
<< "#endif // CLANG_ATTR_TYPE_ARG_LIST\n\n";
2262 /// Emits the parse-arguments-in-unevaluated-context property for
2264 static void emitClangAttrArgContextList(RecordKeeper
&Records
, raw_ostream
&OS
) {
2265 OS
<< "#if defined(CLANG_ATTR_ARG_CONTEXT_LIST)\n";
2266 ParsedAttrMap Attrs
= getParsedAttrList(Records
);
2267 for (const auto &I
: Attrs
) {
2268 const Record
&Attr
= *I
.second
;
2270 if (!Attr
.getValueAsBit("ParseArgumentsAsUnevaluated"))
2273 // All these spellings take are parsed unevaluated.
2274 forEachUniqueSpelling(Attr
, [&](const FlattenedSpelling
&S
) {
2275 OS
<< ".Case(\"" << S
.name() << "\", " << "true" << ")\n";
2278 OS
<< "#endif // CLANG_ATTR_ARG_CONTEXT_LIST\n\n";
2281 static bool isIdentifierArgument(const Record
*Arg
) {
2282 return !Arg
->getSuperClasses().empty() &&
2283 llvm::StringSwitch
<bool>(Arg
->getSuperClasses().back().first
->getName())
2284 .Case("IdentifierArgument", true)
2285 .Case("EnumArgument", true)
2286 .Case("VariadicEnumArgument", true)
2290 static bool isVariadicIdentifierArgument(const Record
*Arg
) {
2291 return !Arg
->getSuperClasses().empty() &&
2292 llvm::StringSwitch
<bool>(
2293 Arg
->getSuperClasses().back().first
->getName())
2294 .Case("VariadicIdentifierArgument", true)
2295 .Case("VariadicParamOrParamIdxArgument", true)
2299 static bool isVariadicExprArgument(const Record
*Arg
) {
2300 return !Arg
->getSuperClasses().empty() &&
2301 llvm::StringSwitch
<bool>(
2302 Arg
->getSuperClasses().back().first
->getName())
2303 .Case("VariadicExprArgument", true)
2307 static bool isStringLiteralArgument(const Record
*Arg
) {
2308 return !Arg
->getSuperClasses().empty() &&
2309 llvm::StringSwitch
<bool>(
2310 Arg
->getSuperClasses().back().first
->getName())
2311 .Case("StringArgument", true)
2315 static bool isVariadicStringLiteralArgument(const Record
*Arg
) {
2316 return !Arg
->getSuperClasses().empty() &&
2317 llvm::StringSwitch
<bool>(
2318 Arg
->getSuperClasses().back().first
->getName())
2319 .Case("VariadicStringArgument", true)
2323 static void emitClangAttrVariadicIdentifierArgList(RecordKeeper
&Records
,
2325 OS
<< "#if defined(CLANG_ATTR_VARIADIC_IDENTIFIER_ARG_LIST)\n";
2326 std::vector
<Record
*> Attrs
= Records
.getAllDerivedDefinitions("Attr");
2327 for (const auto *A
: Attrs
) {
2328 // Determine whether the first argument is a variadic identifier.
2329 std::vector
<Record
*> Args
= A
->getValueAsListOfDefs("Args");
2330 if (Args
.empty() || !isVariadicIdentifierArgument(Args
[0]))
2333 // All these spellings take an identifier argument.
2334 forEachUniqueSpelling(*A
, [&](const FlattenedSpelling
&S
) {
2335 OS
<< ".Case(\"" << S
.name() << "\", "
2340 OS
<< "#endif // CLANG_ATTR_VARIADIC_IDENTIFIER_ARG_LIST\n\n";
2343 // Emits the list of arguments that should be parsed as unevaluated string
2344 // literals for each attribute.
2345 static void emitClangAttrUnevaluatedStringLiteralList(RecordKeeper
&Records
,
2347 OS
<< "#if defined(CLANG_ATTR_STRING_LITERAL_ARG_LIST)\n";
2348 std::vector
<Record
*> Attrs
= Records
.getAllDerivedDefinitions("Attr");
2349 for (const auto *Attr
: Attrs
) {
2350 std::vector
<Record
*> Args
= Attr
->getValueAsListOfDefs("Args");
2352 assert(Args
.size() <= 32 && "unsupported number of arguments in attribute");
2353 for (uint32_t N
= 0; N
< Args
.size(); ++N
) {
2354 Bits
|= (isStringLiteralArgument(Args
[N
]) << N
);
2355 // If we have a variadic string argument, set all the remaining bits to 1
2356 if (isVariadicStringLiteralArgument(Args
[N
])) {
2357 Bits
|= maskTrailingZeros
<decltype(Bits
)>(N
);
2363 // All these spellings have at least one string literal has argument.
2364 forEachUniqueSpelling(*Attr
, [&](const FlattenedSpelling
&S
) {
2365 OS
<< ".Case(\"" << S
.name() << "\", " << Bits
<< ")\n";
2368 OS
<< "#endif // CLANG_ATTR_STRING_LITERAL_ARG_LIST\n\n";
2371 // Emits the first-argument-is-identifier property for attributes.
2372 static void emitClangAttrIdentifierArgList(RecordKeeper
&Records
, raw_ostream
&OS
) {
2373 OS
<< "#if defined(CLANG_ATTR_IDENTIFIER_ARG_LIST)\n";
2374 std::vector
<Record
*> Attrs
= Records
.getAllDerivedDefinitions("Attr");
2376 for (const auto *Attr
: Attrs
) {
2377 // Determine whether the first argument is an identifier.
2378 std::vector
<Record
*> Args
= Attr
->getValueAsListOfDefs("Args");
2379 if (Args
.empty() || !isIdentifierArgument(Args
[0]))
2382 // All these spellings take an identifier argument.
2383 forEachUniqueSpelling(*Attr
, [&](const FlattenedSpelling
&S
) {
2384 OS
<< ".Case(\"" << S
.name() << "\", " << "true" << ")\n";
2387 OS
<< "#endif // CLANG_ATTR_IDENTIFIER_ARG_LIST\n\n";
2390 static bool keywordThisIsaIdentifierInArgument(const Record
*Arg
) {
2391 return !Arg
->getSuperClasses().empty() &&
2392 llvm::StringSwitch
<bool>(
2393 Arg
->getSuperClasses().back().first
->getName())
2394 .Case("VariadicParamOrParamIdxArgument", true)
2398 static void emitClangAttrThisIsaIdentifierArgList(RecordKeeper
&Records
,
2400 OS
<< "#if defined(CLANG_ATTR_THIS_ISA_IDENTIFIER_ARG_LIST)\n";
2401 std::vector
<Record
*> Attrs
= Records
.getAllDerivedDefinitions("Attr");
2402 for (const auto *A
: Attrs
) {
2403 // Determine whether the first argument is a variadic identifier.
2404 std::vector
<Record
*> Args
= A
->getValueAsListOfDefs("Args");
2405 if (Args
.empty() || !keywordThisIsaIdentifierInArgument(Args
[0]))
2408 // All these spellings take an identifier argument.
2409 forEachUniqueSpelling(*A
, [&](const FlattenedSpelling
&S
) {
2410 OS
<< ".Case(\"" << S
.name() << "\", "
2415 OS
<< "#endif // CLANG_ATTR_THIS_ISA_IDENTIFIER_ARG_LIST\n\n";
2418 static void emitClangAttrAcceptsExprPack(RecordKeeper
&Records
,
2420 OS
<< "#if defined(CLANG_ATTR_ACCEPTS_EXPR_PACK)\n";
2421 ParsedAttrMap Attrs
= getParsedAttrList(Records
);
2422 for (const auto &I
: Attrs
) {
2423 const Record
&Attr
= *I
.second
;
2425 if (!Attr
.getValueAsBit("AcceptsExprPack"))
2428 forEachUniqueSpelling(Attr
, [&](const FlattenedSpelling
&S
) {
2429 OS
<< ".Case(\"" << S
.name() << "\", true)\n";
2432 OS
<< "#endif // CLANG_ATTR_ACCEPTS_EXPR_PACK\n\n";
2435 static bool isRegularKeywordAttribute(const FlattenedSpelling
&S
) {
2436 return (S
.variety() == "Keyword" &&
2437 !S
.getSpellingRecord().getValueAsBit("HasOwnParseRules"));
2440 static void emitFormInitializer(raw_ostream
&OS
,
2441 const FlattenedSpelling
&Spelling
,
2442 StringRef SpellingIndex
) {
2444 (Spelling
.variety() == "Keyword" && Spelling
.name() == "alignas");
2445 OS
<< "{AttributeCommonInfo::AS_" << Spelling
.variety() << ", "
2446 << SpellingIndex
<< ", " << (IsAlignas
? "true" : "false")
2447 << " /*IsAlignas*/, "
2448 << (isRegularKeywordAttribute(Spelling
) ? "true" : "false")
2449 << " /*IsRegularKeywordAttribute*/}";
2452 static void emitAttributes(RecordKeeper
&Records
, raw_ostream
&OS
,
2454 std::vector
<Record
*> Attrs
= Records
.getAllDerivedDefinitions("Attr");
2455 ParsedAttrMap AttrMap
= getParsedAttrList(Records
);
2457 // Helper to print the starting character of an attribute argument. If there
2458 // hasn't been an argument yet, it prints an opening parenthese; otherwise it
2460 OS
<< "static inline void DelimitAttributeArgument("
2461 << "raw_ostream& OS, bool& IsFirst) {\n"
2462 << " if (IsFirst) {\n"
2463 << " IsFirst = false;\n"
2464 << " OS << \"(\";\n"
2466 << " OS << \", \";\n"
2469 for (const auto *Attr
: Attrs
) {
2470 const Record
&R
= *Attr
;
2472 // FIXME: Currently, documentation is generated as-needed due to the fact
2473 // that there is no way to allow a generated project "reach into" the docs
2474 // directory (for instance, it may be an out-of-tree build). However, we want
2475 // to ensure that every attribute has a Documentation field, and produce an
2476 // error if it has been neglected. Otherwise, the on-demand generation which
2477 // happens server-side will fail. This code is ensuring that functionality,
2478 // even though this Emitter doesn't technically need the documentation.
2479 // When attribute documentation can be generated as part of the build
2480 // itself, this code can be removed.
2481 (void)R
.getValueAsListOfDefs("Documentation");
2483 if (!R
.getValueAsBit("ASTNode"))
2486 ArrayRef
<std::pair
<Record
*, SMRange
>> Supers
= R
.getSuperClasses();
2487 assert(!Supers
.empty() && "Forgot to specify a superclass for the attr");
2488 std::string SuperName
;
2489 bool Inheritable
= false;
2490 for (const auto &Super
: llvm::reverse(Supers
)) {
2491 const Record
*R
= Super
.first
;
2492 if (R
->getName() != "TargetSpecificAttr" &&
2493 R
->getName() != "DeclOrTypeAttr" && SuperName
.empty())
2494 SuperName
= std::string(R
->getName());
2495 if (R
->getName() == "InheritableAttr")
2500 OS
<< "class " << R
.getName() << "Attr : public " << SuperName
<< " {\n";
2502 OS
<< "\n// " << R
.getName() << "Attr implementation\n\n";
2504 std::vector
<Record
*> ArgRecords
= R
.getValueAsListOfDefs("Args");
2505 std::vector
<std::unique_ptr
<Argument
>> Args
;
2506 Args
.reserve(ArgRecords
.size());
2508 bool AttrAcceptsExprPack
= Attr
->getValueAsBit("AcceptsExprPack");
2509 if (AttrAcceptsExprPack
) {
2510 for (size_t I
= 0; I
< ArgRecords
.size(); ++I
) {
2511 const Record
*ArgR
= ArgRecords
[I
];
2512 if (isIdentifierArgument(ArgR
) || isVariadicIdentifierArgument(ArgR
) ||
2513 isTypeArgument(ArgR
))
2514 PrintFatalError(Attr
->getLoc(),
2515 "Attributes accepting packs cannot also "
2516 "have identifier or type arguments.");
2517 // When trying to determine if value-dependent expressions can populate
2518 // the attribute without prior instantiation, the decision is made based
2519 // on the assumption that only the last argument is ever variadic.
2520 if (I
< (ArgRecords
.size() - 1) && isVariadicExprArgument(ArgR
))
2521 PrintFatalError(Attr
->getLoc(),
2522 "Attributes accepting packs can only have the last "
2523 "argument be variadic.");
2527 bool HasOptArg
= false;
2528 bool HasFakeArg
= false;
2529 for (const auto *ArgRecord
: ArgRecords
) {
2530 Args
.emplace_back(createArgument(*ArgRecord
, R
.getName()));
2532 Args
.back()->writeDeclarations(OS
);
2536 // For these purposes, fake takes priority over optional.
2537 if (Args
.back()->isFake()) {
2539 } else if (Args
.back()->isOptional()) {
2544 std::unique_ptr
<VariadicExprArgument
> DelayedArgs
= nullptr;
2545 if (AttrAcceptsExprPack
) {
2547 std::make_unique
<VariadicExprArgument
>("DelayedArgs", R
.getName());
2549 DelayedArgs
->writeDeclarations(OS
);
2557 std::vector
<FlattenedSpelling
> Spellings
= GetFlattenedSpellings(R
);
2559 // If there are zero or one spellings, all spelling-related functionality
2560 // can be elided. If all of the spellings share the same name, the spelling
2561 // functionality can also be elided.
2562 bool ElideSpelling
= (Spellings
.size() <= 1) ||
2563 SpellingNamesAreCommon(Spellings
);
2565 // This maps spelling index values to semantic Spelling enumerants.
2566 SemanticSpellingMap SemanticToSyntacticMap
;
2568 std::string SpellingEnum
;
2569 if (Spellings
.size() > 1)
2570 SpellingEnum
= CreateSemanticSpellings(Spellings
, SemanticToSyntacticMap
);
2574 const auto &ParsedAttrSpellingItr
= llvm::find_if(
2575 AttrMap
, [R
](const std::pair
<std::string
, const Record
*> &P
) {
2576 return &R
== P
.second
;
2579 // Emit CreateImplicit factory methods.
2580 auto emitCreate
= [&](bool Implicit
, bool DelayedArgsOnly
, bool emitFake
) {
2583 OS
<< R
.getName() << "Attr *";
2585 OS
<< R
.getName() << "Attr::";
2589 if (DelayedArgsOnly
)
2590 OS
<< "WithDelayedArgs";
2592 OS
<< "ASTContext &Ctx";
2593 if (!DelayedArgsOnly
) {
2594 for (auto const &ai
: Args
) {
2595 if (ai
->isFake() && !emitFake
)
2598 ai
->writeCtorParameters(OS
);
2602 DelayedArgs
->writeCtorParameters(OS
);
2604 OS
<< ", const AttributeCommonInfo &CommonInfo";
2612 OS
<< " auto *A = new (Ctx) " << R
.getName();
2613 OS
<< "Attr(Ctx, CommonInfo";
2615 if (!DelayedArgsOnly
) {
2616 for (auto const &ai
: Args
) {
2617 if (ai
->isFake() && !emitFake
)
2620 ai
->writeImplicitCtorArgs(OS
);
2625 OS
<< " A->setImplicit(true);\n";
2627 if (Implicit
|| ElideSpelling
) {
2628 OS
<< " if (!A->isAttributeSpellingListCalculated() && "
2629 "!A->getAttrName())\n";
2630 OS
<< " A->setAttributeSpellingListIndex(0);\n";
2632 if (DelayedArgsOnly
) {
2633 OS
<< " A->setDelayedArgs(Ctx, ";
2634 DelayedArgs
->writeImplicitCtorArgs(OS
);
2637 OS
<< " return A;\n}\n\n";
2640 auto emitCreateNoCI
= [&](bool Implicit
, bool DelayedArgsOnly
,
2644 OS
<< R
.getName() << "Attr *";
2646 OS
<< R
.getName() << "Attr::";
2650 if (DelayedArgsOnly
)
2651 OS
<< "WithDelayedArgs";
2653 OS
<< "ASTContext &Ctx";
2654 if (!DelayedArgsOnly
) {
2655 for (auto const &ai
: Args
) {
2656 if (ai
->isFake() && !emitFake
)
2659 ai
->writeCtorParameters(OS
);
2663 DelayedArgs
->writeCtorParameters(OS
);
2665 OS
<< ", SourceRange Range";
2668 if (Spellings
.size() > 1) {
2669 OS
<< ", Spelling S";
2671 OS
<< " = " << SemanticToSyntacticMap
[0];
2680 OS
<< " AttributeCommonInfo I(Range, ";
2682 if (ParsedAttrSpellingItr
!= std::end(AttrMap
))
2683 OS
<< "AT_" << ParsedAttrSpellingItr
->first
;
2685 OS
<< "NoSemaHandlerAttribute";
2687 if (Spellings
.size() == 0) {
2688 OS
<< ", AttributeCommonInfo::Form::Implicit()";
2689 } else if (Spellings
.size() == 1) {
2691 emitFormInitializer(OS
, Spellings
[0], "0");
2693 OS
<< ", [&]() {\n";
2694 OS
<< " switch (S) {\n";
2695 std::set
<std::string
> Uniques
;
2697 for (auto I
= Spellings
.begin(), E
= Spellings
.end(); I
!= E
;
2699 const FlattenedSpelling
&S
= *I
;
2700 const auto &Name
= SemanticToSyntacticMap
[Idx
];
2701 if (Uniques
.insert(Name
).second
) {
2702 OS
<< " case " << Name
<< ":\n";
2703 OS
<< " return AttributeCommonInfo::Form";
2704 emitFormInitializer(OS
, S
, Name
);
2708 OS
<< " default:\n";
2709 OS
<< " llvm_unreachable(\"Unknown attribute spelling!\");\n"
2710 << " return AttributeCommonInfo::Form";
2711 emitFormInitializer(OS
, Spellings
[0], "0");
2718 OS
<< " return Create";
2721 if (DelayedArgsOnly
)
2722 OS
<< "WithDelayedArgs";
2724 if (!DelayedArgsOnly
) {
2725 for (auto const &ai
: Args
) {
2726 if (ai
->isFake() && !emitFake
)
2729 ai
->writeImplicitCtorArgs(OS
);
2733 DelayedArgs
->writeImplicitCtorArgs(OS
);
2739 auto emitCreates
= [&](bool DelayedArgsOnly
, bool emitFake
) {
2740 emitCreate(true, DelayedArgsOnly
, emitFake
);
2741 emitCreate(false, DelayedArgsOnly
, emitFake
);
2742 emitCreateNoCI(true, DelayedArgsOnly
, emitFake
);
2743 emitCreateNoCI(false, DelayedArgsOnly
, emitFake
);
2747 OS
<< " // Factory methods\n";
2749 // Emit a CreateImplicit that takes all the arguments.
2750 emitCreates(false, true);
2752 // Emit a CreateImplicit that takes all the non-fake arguments.
2754 emitCreates(false, false);
2756 // Emit a CreateWithDelayedArgs that takes only the dependent argument
2759 emitCreates(true, false);
2761 // Emit constructors.
2762 auto emitCtor
= [&](bool emitOpt
, bool emitFake
, bool emitNoArgs
) {
2763 auto shouldEmitArg
= [=](const std::unique_ptr
<Argument
> &arg
) {
2768 if (arg
->isOptional())
2775 OS
<< R
.getName() << "Attr::";
2777 << "Attr(ASTContext &Ctx, const AttributeCommonInfo &CommonInfo";
2779 for (auto const &ai
: Args
) {
2780 if (!shouldEmitArg(ai
))
2783 ai
->writeCtorParameters(OS
);
2792 OS
<< "\n : " << SuperName
<< "(Ctx, CommonInfo, ";
2793 OS
<< "attr::" << R
.getName() << ", "
2794 << (R
.getValueAsBit("LateParsed") ? "true" : "false");
2797 << (R
.getValueAsBit("InheritEvenIfAlreadyPresent") ? "true"
2802 for (auto const &ai
: Args
) {
2804 if (!shouldEmitArg(ai
)) {
2805 ai
->writeCtorDefaultInitializers(OS
);
2807 ai
->writeCtorInitializers(OS
);
2813 DelayedArgs
->writeCtorDefaultInitializers(OS
);
2819 for (auto const &ai
: Args
) {
2820 if (!shouldEmitArg(ai
))
2822 ai
->writeCtorBody(OS
);
2828 OS
<< "\n // Constructors\n";
2830 // Emit a constructor that includes all the arguments.
2831 // This is necessary for cloning.
2832 emitCtor(true, true, false);
2834 // Emit a constructor that takes all the non-fake arguments.
2836 emitCtor(true, false, false);
2838 // Emit a constructor that takes all the non-fake, non-optional arguments.
2840 emitCtor(false, false, false);
2842 // Emit constructors that takes no arguments if none already exists.
2843 // This is used for delaying arguments.
2844 bool HasRequiredArgs
=
2845 llvm::count_if(Args
, [=](const std::unique_ptr
<Argument
> &arg
) {
2846 return !arg
->isFake() && !arg
->isOptional();
2848 if (DelayedArgs
&& HasRequiredArgs
)
2849 emitCtor(false, false, true);
2853 OS
<< " " << R
.getName() << "Attr *clone(ASTContext &C) const;\n";
2854 OS
<< " void printPretty(raw_ostream &OS,\n"
2855 << " const PrintingPolicy &Policy) const;\n";
2856 OS
<< " const char *getSpelling() const;\n";
2859 if (!ElideSpelling
) {
2860 assert(!SemanticToSyntacticMap
.empty() && "Empty semantic mapping list");
2862 OS
<< " Spelling getSemanticSpelling() const;\n";
2864 OS
<< R
.getName() << "Attr::Spelling " << R
.getName()
2865 << "Attr::getSemanticSpelling() const {\n";
2866 WriteSemanticSpellingSwitch("getAttributeSpellingListIndex()",
2867 SemanticToSyntacticMap
, OS
);
2873 writeAttrAccessorDefinition(R
, OS
);
2875 for (auto const &ai
: Args
) {
2877 ai
->writeAccessors(OS
);
2879 ai
->writeAccessorDefinitions(OS
);
2883 // Don't write conversion routines for fake arguments.
2884 if (ai
->isFake()) continue;
2886 if (ai
->isEnumArg())
2887 static_cast<const EnumArgument
*>(ai
.get())->writeConversion(OS
,
2889 else if (ai
->isVariadicEnumArg())
2890 static_cast<const VariadicEnumArgument
*>(ai
.get())->writeConversion(
2896 DelayedArgs
->writeAccessors(OS
);
2897 DelayedArgs
->writeSetter(OS
);
2900 OS
<< R
.getValueAsString("AdditionalMembers");
2903 OS
<< " static bool classof(const Attr *A) { return A->getKind() == "
2904 << "attr::" << R
.getName() << "; }\n";
2909 DelayedArgs
->writeAccessorDefinitions(OS
);
2911 OS
<< R
.getName() << "Attr *" << R
.getName()
2912 << "Attr::clone(ASTContext &C) const {\n";
2913 OS
<< " auto *A = new (C) " << R
.getName() << "Attr(C, *this";
2914 for (auto const &ai
: Args
) {
2916 ai
->writeCloneArgs(OS
);
2919 OS
<< " A->Inherited = Inherited;\n";
2920 OS
<< " A->IsPackExpansion = IsPackExpansion;\n";
2921 OS
<< " A->setImplicit(Implicit);\n";
2923 OS
<< " A->setDelayedArgs(C, ";
2924 DelayedArgs
->writeCloneArgs(OS
);
2927 OS
<< " return A;\n}\n\n";
2929 writePrettyPrintFunction(R
, Args
, OS
);
2930 writeGetSpellingFunction(R
, OS
);
2934 // Emits the class definitions for attributes.
2935 void clang::EmitClangAttrClass(RecordKeeper
&Records
, raw_ostream
&OS
) {
2936 emitSourceFileHeader("Attribute classes' definitions", OS
, Records
);
2938 OS
<< "#ifndef LLVM_CLANG_ATTR_CLASSES_INC\n";
2939 OS
<< "#define LLVM_CLANG_ATTR_CLASSES_INC\n\n";
2941 emitAttributes(Records
, OS
, true);
2943 OS
<< "#endif // LLVM_CLANG_ATTR_CLASSES_INC\n";
2946 // Emits the class method definitions for attributes.
2947 void clang::EmitClangAttrImpl(RecordKeeper
&Records
, raw_ostream
&OS
) {
2948 emitSourceFileHeader("Attribute classes' member function definitions", OS
,
2951 emitAttributes(Records
, OS
, false);
2953 std::vector
<Record
*> Attrs
= Records
.getAllDerivedDefinitions("Attr");
2955 // Instead of relying on virtual dispatch we just create a huge dispatch
2956 // switch. This is both smaller and faster than virtual functions.
2957 auto EmitFunc
= [&](const char *Method
) {
2958 OS
<< " switch (getKind()) {\n";
2959 for (const auto *Attr
: Attrs
) {
2960 const Record
&R
= *Attr
;
2961 if (!R
.getValueAsBit("ASTNode"))
2964 OS
<< " case attr::" << R
.getName() << ":\n";
2965 OS
<< " return cast<" << R
.getName() << "Attr>(this)->" << Method
2969 OS
<< " llvm_unreachable(\"Unexpected attribute kind!\");\n";
2973 OS
<< "const char *Attr::getSpelling() const {\n";
2974 EmitFunc("getSpelling()");
2976 OS
<< "Attr *Attr::clone(ASTContext &C) const {\n";
2977 EmitFunc("clone(C)");
2979 OS
<< "void Attr::printPretty(raw_ostream &OS, "
2980 "const PrintingPolicy &Policy) const {\n";
2981 EmitFunc("printPretty(OS, Policy)");
2984 static void emitAttrList(raw_ostream
&OS
, StringRef Class
,
2985 const std::vector
<Record
*> &AttrList
) {
2986 for (auto Cur
: AttrList
) {
2987 OS
<< Class
<< "(" << Cur
->getName() << ")\n";
2991 // Determines if an attribute has a Pragma spelling.
2992 static bool AttrHasPragmaSpelling(const Record
*R
) {
2993 std::vector
<FlattenedSpelling
> Spellings
= GetFlattenedSpellings(*R
);
2994 return llvm::any_of(Spellings
, [](const FlattenedSpelling
&S
) {
2995 return S
.variety() == "Pragma";
3001 struct AttrClassDescriptor
{
3002 const char * const MacroName
;
3003 const char * const TableGenName
;
3006 } // end anonymous namespace
3008 static const AttrClassDescriptor AttrClassDescriptors
[] = {
3010 { "TYPE_ATTR", "TypeAttr" },
3011 { "STMT_ATTR", "StmtAttr" },
3012 { "DECL_OR_STMT_ATTR", "DeclOrStmtAttr" },
3013 { "INHERITABLE_ATTR", "InheritableAttr" },
3014 { "DECL_OR_TYPE_ATTR", "DeclOrTypeAttr" },
3015 { "INHERITABLE_PARAM_ATTR", "InheritableParamAttr" },
3016 { "PARAMETER_ABI_ATTR", "ParameterABIAttr" },
3017 { "HLSL_ANNOTATION_ATTR", "HLSLAnnotationAttr"}
3020 static void emitDefaultDefine(raw_ostream
&OS
, StringRef name
,
3021 const char *superName
) {
3022 OS
<< "#ifndef " << name
<< "\n";
3023 OS
<< "#define " << name
<< "(NAME) ";
3024 if (superName
) OS
<< superName
<< "(NAME)";
3025 OS
<< "\n#endif\n\n";
3030 /// A class of attributes.
3032 const AttrClassDescriptor
&Descriptor
;
3034 AttrClass
*SuperClass
= nullptr;
3035 std::vector
<AttrClass
*> SubClasses
;
3036 std::vector
<Record
*> Attrs
;
3038 AttrClass(const AttrClassDescriptor
&Descriptor
, Record
*R
)
3039 : Descriptor(Descriptor
), TheRecord(R
) {}
3041 void emitDefaultDefines(raw_ostream
&OS
) const {
3042 // Default the macro unless this is a root class (i.e. Attr).
3044 emitDefaultDefine(OS
, Descriptor
.MacroName
,
3045 SuperClass
->Descriptor
.MacroName
);
3049 void emitUndefs(raw_ostream
&OS
) const {
3050 OS
<< "#undef " << Descriptor
.MacroName
<< "\n";
3053 void emitAttrList(raw_ostream
&OS
) const {
3054 for (auto SubClass
: SubClasses
) {
3055 SubClass
->emitAttrList(OS
);
3058 ::emitAttrList(OS
, Descriptor
.MacroName
, Attrs
);
3061 void classifyAttrOnRoot(Record
*Attr
) {
3062 bool result
= classifyAttr(Attr
);
3063 assert(result
&& "failed to classify on root"); (void) result
;
3066 void emitAttrRange(raw_ostream
&OS
) const {
3067 OS
<< "ATTR_RANGE(" << Descriptor
.TableGenName
3068 << ", " << getFirstAttr()->getName()
3069 << ", " << getLastAttr()->getName() << ")\n";
3073 bool classifyAttr(Record
*Attr
) {
3074 // Check all the subclasses.
3075 for (auto SubClass
: SubClasses
) {
3076 if (SubClass
->classifyAttr(Attr
))
3080 // It's not more specific than this class, but it might still belong here.
3081 if (Attr
->isSubClassOf(TheRecord
)) {
3082 Attrs
.push_back(Attr
);
3089 Record
*getFirstAttr() const {
3090 if (!SubClasses
.empty())
3091 return SubClasses
.front()->getFirstAttr();
3092 return Attrs
.front();
3095 Record
*getLastAttr() const {
3097 return Attrs
.back();
3098 return SubClasses
.back()->getLastAttr();
3102 /// The entire hierarchy of attribute classes.
3103 class AttrClassHierarchy
{
3104 std::vector
<std::unique_ptr
<AttrClass
>> Classes
;
3107 AttrClassHierarchy(RecordKeeper
&Records
) {
3108 // Find records for all the classes.
3109 for (auto &Descriptor
: AttrClassDescriptors
) {
3110 Record
*ClassRecord
= Records
.getClass(Descriptor
.TableGenName
);
3111 AttrClass
*Class
= new AttrClass(Descriptor
, ClassRecord
);
3112 Classes
.emplace_back(Class
);
3115 // Link up the hierarchy.
3116 for (auto &Class
: Classes
) {
3117 if (AttrClass
*SuperClass
= findSuperClass(Class
->TheRecord
)) {
3118 Class
->SuperClass
= SuperClass
;
3119 SuperClass
->SubClasses
.push_back(Class
.get());
3124 for (auto i
= Classes
.begin(), e
= Classes
.end(); i
!= e
; ++i
) {
3125 assert((i
== Classes
.begin()) == ((*i
)->SuperClass
== nullptr) &&
3126 "only the first class should be a root class!");
3131 void emitDefaultDefines(raw_ostream
&OS
) const {
3132 for (auto &Class
: Classes
) {
3133 Class
->emitDefaultDefines(OS
);
3137 void emitUndefs(raw_ostream
&OS
) const {
3138 for (auto &Class
: Classes
) {
3139 Class
->emitUndefs(OS
);
3143 void emitAttrLists(raw_ostream
&OS
) const {
3144 // Just start from the root class.
3145 Classes
[0]->emitAttrList(OS
);
3148 void emitAttrRanges(raw_ostream
&OS
) const {
3149 for (auto &Class
: Classes
)
3150 Class
->emitAttrRange(OS
);
3153 void classifyAttr(Record
*Attr
) {
3154 // Add the attribute to the root class.
3155 Classes
[0]->classifyAttrOnRoot(Attr
);
3159 AttrClass
*findClassByRecord(Record
*R
) const {
3160 for (auto &Class
: Classes
) {
3161 if (Class
->TheRecord
== R
)
3167 AttrClass
*findSuperClass(Record
*R
) const {
3168 // TableGen flattens the superclass list, so we just need to walk it
3170 auto SuperClasses
= R
->getSuperClasses();
3171 for (signed i
= 0, e
= SuperClasses
.size(); i
!= e
; ++i
) {
3172 auto SuperClass
= findClassByRecord(SuperClasses
[e
- i
- 1].first
);
3173 if (SuperClass
) return SuperClass
;
3179 } // end anonymous namespace
3183 // Emits the enumeration list for attributes.
3184 void EmitClangAttrList(RecordKeeper
&Records
, raw_ostream
&OS
) {
3185 emitSourceFileHeader("List of all attributes that Clang recognizes", OS
,
3188 AttrClassHierarchy
Hierarchy(Records
);
3190 // Add defaulting macro definitions.
3191 Hierarchy
.emitDefaultDefines(OS
);
3192 emitDefaultDefine(OS
, "PRAGMA_SPELLING_ATTR", nullptr);
3194 std::vector
<Record
*> Attrs
= Records
.getAllDerivedDefinitions("Attr");
3195 std::vector
<Record
*> PragmaAttrs
;
3196 for (auto *Attr
: Attrs
) {
3197 if (!Attr
->getValueAsBit("ASTNode"))
3200 // Add the attribute to the ad-hoc groups.
3201 if (AttrHasPragmaSpelling(Attr
))
3202 PragmaAttrs
.push_back(Attr
);
3204 // Place it in the hierarchy.
3205 Hierarchy
.classifyAttr(Attr
);
3208 // Emit the main attribute list.
3209 Hierarchy
.emitAttrLists(OS
);
3211 // Emit the ad hoc groups.
3212 emitAttrList(OS
, "PRAGMA_SPELLING_ATTR", PragmaAttrs
);
3214 // Emit the attribute ranges.
3215 OS
<< "#ifdef ATTR_RANGE\n";
3216 Hierarchy
.emitAttrRanges(OS
);
3217 OS
<< "#undef ATTR_RANGE\n";
3220 Hierarchy
.emitUndefs(OS
);
3221 OS
<< "#undef PRAGMA_SPELLING_ATTR\n";
3224 // Emits the enumeration list for attributes.
3225 void EmitClangAttrPrintList(const std::string
&FieldName
, RecordKeeper
&Records
,
3227 emitSourceFileHeader(
3228 "List of attributes that can be print on the left side of a decl", OS
,
3231 AttrClassHierarchy
Hierarchy(Records
);
3233 std::vector
<Record
*> Attrs
= Records
.getAllDerivedDefinitions("Attr");
3234 std::vector
<Record
*> PragmaAttrs
;
3237 for (auto *Attr
: Attrs
) {
3238 if (!Attr
->getValueAsBit("ASTNode"))
3241 if (!Attr
->getValueAsBit(FieldName
))
3246 OS
<< "#define CLANG_ATTR_LIST_" << FieldName
;
3249 OS
<< " \\\n case attr::" << Attr
->getName() << ":";
3255 // Emits the enumeration list for attributes.
3256 void EmitClangAttrSubjectMatchRuleList(RecordKeeper
&Records
, raw_ostream
&OS
) {
3257 emitSourceFileHeader(
3258 "List of all attribute subject matching rules that Clang recognizes", OS
,
3260 PragmaClangAttributeSupport
&PragmaAttributeSupport
=
3261 getPragmaAttributeSupport(Records
);
3262 emitDefaultDefine(OS
, "ATTR_MATCH_RULE", nullptr);
3263 PragmaAttributeSupport
.emitMatchRuleList(OS
);
3264 OS
<< "#undef ATTR_MATCH_RULE\n";
3267 // Emits the code to read an attribute from a precompiled header.
3268 void EmitClangAttrPCHRead(RecordKeeper
&Records
, raw_ostream
&OS
) {
3269 emitSourceFileHeader("Attribute deserialization code", OS
, Records
);
3271 Record
*InhClass
= Records
.getClass("InheritableAttr");
3272 std::vector
<Record
*> Attrs
= Records
.getAllDerivedDefinitions("Attr"),
3274 std::vector
<std::unique_ptr
<Argument
>> Args
;
3275 std::unique_ptr
<VariadicExprArgument
> DelayedArgs
;
3277 OS
<< " switch (Kind) {\n";
3278 for (const auto *Attr
: Attrs
) {
3279 const Record
&R
= *Attr
;
3280 if (!R
.getValueAsBit("ASTNode"))
3283 OS
<< " case attr::" << R
.getName() << ": {\n";
3284 if (R
.isSubClassOf(InhClass
))
3285 OS
<< " bool isInherited = Record.readInt();\n";
3286 OS
<< " bool isImplicit = Record.readInt();\n";
3287 OS
<< " bool isPackExpansion = Record.readInt();\n";
3288 DelayedArgs
= nullptr;
3289 if (Attr
->getValueAsBit("AcceptsExprPack")) {
3291 std::make_unique
<VariadicExprArgument
>("DelayedArgs", R
.getName());
3292 DelayedArgs
->writePCHReadDecls(OS
);
3294 ArgRecords
= R
.getValueAsListOfDefs("Args");
3296 for (const auto *Arg
: ArgRecords
) {
3297 Args
.emplace_back(createArgument(*Arg
, R
.getName()));
3298 Args
.back()->writePCHReadDecls(OS
);
3300 OS
<< " New = new (Context) " << R
.getName() << "Attr(Context, Info";
3301 for (auto const &ri
: Args
) {
3303 ri
->writePCHReadArgs(OS
);
3306 if (R
.isSubClassOf(InhClass
))
3307 OS
<< " cast<InheritableAttr>(New)->setInherited(isInherited);\n";
3308 OS
<< " New->setImplicit(isImplicit);\n";
3309 OS
<< " New->setPackExpansion(isPackExpansion);\n";
3311 OS
<< " cast<" << R
.getName()
3312 << "Attr>(New)->setDelayedArgs(Context, ";
3313 DelayedArgs
->writePCHReadArgs(OS
);
3322 // Emits the code to write an attribute to a precompiled header.
3323 void EmitClangAttrPCHWrite(RecordKeeper
&Records
, raw_ostream
&OS
) {
3324 emitSourceFileHeader("Attribute serialization code", OS
, Records
);
3326 Record
*InhClass
= Records
.getClass("InheritableAttr");
3327 std::vector
<Record
*> Attrs
= Records
.getAllDerivedDefinitions("Attr"), Args
;
3329 OS
<< " switch (A->getKind()) {\n";
3330 for (const auto *Attr
: Attrs
) {
3331 const Record
&R
= *Attr
;
3332 if (!R
.getValueAsBit("ASTNode"))
3334 OS
<< " case attr::" << R
.getName() << ": {\n";
3335 Args
= R
.getValueAsListOfDefs("Args");
3336 if (R
.isSubClassOf(InhClass
) || !Args
.empty())
3337 OS
<< " const auto *SA = cast<" << R
.getName()
3339 if (R
.isSubClassOf(InhClass
))
3340 OS
<< " Record.push_back(SA->isInherited());\n";
3341 OS
<< " Record.push_back(A->isImplicit());\n";
3342 OS
<< " Record.push_back(A->isPackExpansion());\n";
3343 if (Attr
->getValueAsBit("AcceptsExprPack"))
3344 VariadicExprArgument("DelayedArgs", R
.getName()).writePCHWrite(OS
);
3346 for (const auto *Arg
: Args
)
3347 createArgument(*Arg
, R
.getName())->writePCHWrite(OS
);
3354 // Helper function for GenerateTargetSpecificAttrChecks that alters the 'Test'
3355 // parameter with only a single check type, if applicable.
3356 static bool GenerateTargetSpecificAttrCheck(const Record
*R
, std::string
&Test
,
3357 std::string
*FnName
,
3359 StringRef CheckAgainst
,
3361 if (!R
->isValueUnset(ListName
)) {
3363 std::vector
<StringRef
> Items
= R
->getValueAsListOfStrings(ListName
);
3364 for (auto I
= Items
.begin(), E
= Items
.end(); I
!= E
; ++I
) {
3365 StringRef Part
= *I
;
3366 Test
+= CheckAgainst
;
3381 // Generate a conditional expression to check if the current target satisfies
3382 // the conditions for a TargetSpecificAttr record, and append the code for
3383 // those checks to the Test string. If the FnName string pointer is non-null,
3384 // append a unique suffix to distinguish this set of target checks from other
3385 // TargetSpecificAttr records.
3386 static bool GenerateTargetSpecificAttrChecks(const Record
*R
,
3387 std::vector
<StringRef
> &Arches
,
3389 std::string
*FnName
) {
3390 bool AnyTargetChecks
= false;
3392 // It is assumed that there will be an llvm::Triple object
3393 // named "T" and a TargetInfo object named "Target" within
3394 // scope that can be used to determine whether the attribute exists in
3397 // If one or more architectures is specified, check those. Arches are handled
3398 // differently because GenerateTargetRequirements needs to combine the list
3400 if (!Arches
.empty()) {
3401 AnyTargetChecks
= true;
3403 for (auto I
= Arches
.begin(), E
= Arches
.end(); I
!= E
; ++I
) {
3404 StringRef Part
= *I
;
3405 Test
+= "T.getArch() == llvm::Triple::";
3415 // If the attribute is specific to particular OSes, check those.
3416 AnyTargetChecks
|= GenerateTargetSpecificAttrCheck(
3417 R
, Test
, FnName
, "OSes", "T.getOS()", "llvm::Triple::");
3419 // If one or more object formats is specified, check those.
3421 GenerateTargetSpecificAttrCheck(R
, Test
, FnName
, "ObjectFormats",
3422 "T.getObjectFormat()", "llvm::Triple::");
3424 // If custom code is specified, emit it.
3425 StringRef Code
= R
->getValueAsString("CustomCode");
3426 if (!Code
.empty()) {
3427 AnyTargetChecks
= true;
3433 return AnyTargetChecks
;
3436 static void GenerateHasAttrSpellingStringSwitch(
3437 const std::vector
<std::pair
<const Record
*, FlattenedSpelling
>> &Attrs
,
3438 raw_ostream
&OS
, const std::string
&Variety
,
3439 const std::string
&Scope
= "") {
3440 for (const auto &[Attr
, Spelling
] : Attrs
) {
3441 // C++11-style attributes have specific version information associated with
3442 // them. If the attribute has no scope, the version information must not
3443 // have the default value (1), as that's incorrect. Instead, the unscoped
3444 // attribute version information should be taken from the SD-6 standing
3445 // document, which can be found at:
3446 // https://isocpp.org/std/standing-documents/sd-6-sg10-feature-test-recommendations
3448 // C23-style attributes have the same kind of version information
3449 // associated with them. The unscoped attribute version information should
3450 // be taken from the specification of the attribute in the C Standard.
3452 // Clang-specific attributes have the same kind of version information
3453 // associated with them. This version is typically the default value (1).
3454 // These version values are clang-specific and should typically be
3455 // incremented once the attribute changes its syntax and/or semantics in a
3456 // a way that is impactful to the end user.
3459 assert(Spelling
.variety() == Variety
);
3460 std::string Name
= "";
3461 if (Spelling
.nameSpace().empty() || Scope
== Spelling
.nameSpace()) {
3462 Name
= Spelling
.name();
3463 Version
= static_cast<int>(
3464 Spelling
.getSpellingRecord().getValueAsInt("Version"));
3465 // Verify that explicitly specified CXX11 and C23 spellings (i.e.
3466 // not inferred from Clang/GCC spellings) have a version that's
3467 // different from the default (1).
3468 bool RequiresValidVersion
=
3469 (Variety
== "CXX11" || Variety
== "C23") &&
3470 Spelling
.getSpellingRecord().getValueAsString("Variety") == Variety
;
3471 if (RequiresValidVersion
&& Scope
.empty() && Version
== 1)
3472 PrintError(Spelling
.getSpellingRecord().getLoc(),
3473 "Standard attributes must have "
3474 "valid version information.");
3478 if (Attr
->isSubClassOf("TargetSpecificAttr")) {
3479 const Record
*R
= Attr
->getValueAsDef("Target");
3480 std::vector
<StringRef
> Arches
= R
->getValueAsListOfStrings("Arches");
3481 GenerateTargetSpecificAttrChecks(R
, Arches
, Test
, nullptr);
3483 // If this is the C++11 variety, also add in the LangOpts test.
3484 if (Variety
== "CXX11")
3485 Test
+= " && LangOpts.CPlusPlus11";
3486 } else if (!Attr
->getValueAsListOfDefs("TargetSpecificSpellings").empty()) {
3487 // Add target checks if this spelling is target-specific.
3488 const std::vector
<Record
*> TargetSpellings
=
3489 Attr
->getValueAsListOfDefs("TargetSpecificSpellings");
3490 for (const auto &TargetSpelling
: TargetSpellings
) {
3491 // Find spelling that matches current scope and name.
3492 for (const auto &Spelling
: GetFlattenedSpellings(*TargetSpelling
)) {
3493 if (Scope
== Spelling
.nameSpace() && Name
== Spelling
.name()) {
3494 const Record
*Target
= TargetSpelling
->getValueAsDef("Target");
3495 std::vector
<StringRef
> Arches
=
3496 Target
->getValueAsListOfStrings("Arches");
3497 GenerateTargetSpecificAttrChecks(Target
, Arches
, Test
,
3498 /*FnName=*/nullptr);
3504 if (Variety
== "CXX11")
3505 Test
+= " && LangOpts.CPlusPlus11";
3506 } else if (Variety
== "CXX11")
3507 // C++11 mode should be checked against LangOpts, which is presumed to be
3508 // present in the caller.
3509 Test
= "LangOpts.CPlusPlus11";
3511 std::string TestStr
= !Test
.empty()
3512 ? Test
+ " ? " + llvm::itostr(Version
) + " : 0"
3513 : llvm::itostr(Version
);
3514 if (Scope
.empty() || Scope
== Spelling
.nameSpace())
3515 OS
<< " .Case(\"" << Spelling
.name() << "\", " << TestStr
<< ")\n";
3517 OS
<< " .Default(0);\n";
3520 // Emits the list of tokens for regular keyword attributes.
3521 void EmitClangAttrTokenKinds(RecordKeeper
&Records
, raw_ostream
&OS
) {
3522 emitSourceFileHeader("A list of tokens generated from the attribute"
3525 // Assume for now that the same token is not used in multiple regular
3526 // keyword attributes.
3527 for (auto *R
: Records
.getAllDerivedDefinitions("Attr"))
3528 for (const auto &S
: GetFlattenedSpellings(*R
))
3529 if (isRegularKeywordAttribute(S
)) {
3530 if (!R
->getValueAsListOfDefs("Args").empty())
3531 PrintError(R
->getLoc(),
3532 "RegularKeyword attributes with arguments are not "
3534 OS
<< "KEYWORD_ATTRIBUTE("
3535 << S
.getSpellingRecord().getValueAsString("Name") << ")\n";
3537 OS
<< "#undef KEYWORD_ATTRIBUTE\n";
3540 // Emits the list of spellings for attributes.
3541 void EmitClangAttrHasAttrImpl(RecordKeeper
&Records
, raw_ostream
&OS
) {
3542 emitSourceFileHeader("Code to implement the __has_attribute logic", OS
,
3545 // Separate all of the attributes out into four group: generic, C++11, GNU,
3546 // and declspecs. Then generate a big switch statement for each of them.
3547 std::vector
<Record
*> Attrs
= Records
.getAllDerivedDefinitions("Attr");
3548 std::vector
<std::pair
<const Record
*, FlattenedSpelling
>> Declspec
, Microsoft
,
3549 GNU
, Pragma
, HLSLSemantic
;
3550 std::map
<std::string
,
3551 std::vector
<std::pair
<const Record
*, FlattenedSpelling
>>>
3554 // Walk over the list of all attributes, and split them out based on the
3555 // spelling variety.
3556 for (auto *R
: Attrs
) {
3557 std::vector
<FlattenedSpelling
> Spellings
= GetFlattenedSpellings(*R
);
3558 for (const auto &SI
: Spellings
) {
3559 const std::string
&Variety
= SI
.variety();
3560 if (Variety
== "GNU")
3561 GNU
.emplace_back(R
, SI
);
3562 else if (Variety
== "Declspec")
3563 Declspec
.emplace_back(R
, SI
);
3564 else if (Variety
== "Microsoft")
3565 Microsoft
.emplace_back(R
, SI
);
3566 else if (Variety
== "CXX11")
3567 CXX
[SI
.nameSpace()].emplace_back(R
, SI
);
3568 else if (Variety
== "C23")
3569 C23
[SI
.nameSpace()].emplace_back(R
, SI
);
3570 else if (Variety
== "Pragma")
3571 Pragma
.emplace_back(R
, SI
);
3572 else if (Variety
== "HLSLSemantic")
3573 HLSLSemantic
.emplace_back(R
, SI
);
3577 OS
<< "const llvm::Triple &T = Target.getTriple();\n";
3578 OS
<< "switch (Syntax) {\n";
3579 OS
<< "case AttributeCommonInfo::Syntax::AS_GNU:\n";
3580 OS
<< " return llvm::StringSwitch<int>(Name)\n";
3581 GenerateHasAttrSpellingStringSwitch(GNU
, OS
, "GNU");
3582 OS
<< "case AttributeCommonInfo::Syntax::AS_Declspec:\n";
3583 OS
<< " return llvm::StringSwitch<int>(Name)\n";
3584 GenerateHasAttrSpellingStringSwitch(Declspec
, OS
, "Declspec");
3585 OS
<< "case AttributeCommonInfo::Syntax::AS_Microsoft:\n";
3586 OS
<< " return llvm::StringSwitch<int>(Name)\n";
3587 GenerateHasAttrSpellingStringSwitch(Microsoft
, OS
, "Microsoft");
3588 OS
<< "case AttributeCommonInfo::Syntax::AS_Pragma:\n";
3589 OS
<< " return llvm::StringSwitch<int>(Name)\n";
3590 GenerateHasAttrSpellingStringSwitch(Pragma
, OS
, "Pragma");
3591 OS
<< "case AttributeCommonInfo::Syntax::AS_HLSLSemantic:\n";
3592 OS
<< " return llvm::StringSwitch<int>(Name)\n";
3593 GenerateHasAttrSpellingStringSwitch(HLSLSemantic
, OS
, "HLSLSemantic");
3594 auto fn
= [&OS
](const char *Spelling
,
3597 std::vector
<std::pair
<const Record
*, FlattenedSpelling
>>>
3599 OS
<< "case AttributeCommonInfo::Syntax::AS_" << Spelling
<< ": {\n";
3600 // C++11-style attributes are further split out based on the Scope.
3601 for (auto I
= List
.cbegin(), E
= List
.cend(); I
!= E
; ++I
) {
3602 if (I
!= List
.cbegin())
3604 if (I
->first
.empty())
3605 OS
<< "if (ScopeName == \"\") {\n";
3607 OS
<< "if (ScopeName == \"" << I
->first
<< "\") {\n";
3608 OS
<< " return llvm::StringSwitch<int>(Name)\n";
3609 GenerateHasAttrSpellingStringSwitch(I
->second
, OS
, Spelling
, I
->first
);
3612 OS
<< "\n} break;\n";
3616 OS
<< "case AttributeCommonInfo::Syntax::AS_Keyword:\n";
3617 OS
<< "case AttributeCommonInfo::Syntax::AS_ContextSensitiveKeyword:\n";
3618 OS
<< " llvm_unreachable(\"hasAttribute not supported for keyword\");\n";
3619 OS
<< " return 0;\n";
3620 OS
<< "case AttributeCommonInfo::Syntax::AS_Implicit:\n";
3621 OS
<< " llvm_unreachable (\"hasAttribute not supported for "
3622 "AS_Implicit\");\n";
3623 OS
<< " return 0;\n";
3628 void EmitClangAttrSpellingListIndex(RecordKeeper
&Records
, raw_ostream
&OS
) {
3629 emitSourceFileHeader("Code to translate different attribute spellings into "
3630 "internal identifiers",
3633 OS
<< " switch (getParsedKind()) {\n";
3634 OS
<< " case IgnoredAttribute:\n";
3635 OS
<< " case UnknownAttribute:\n";
3636 OS
<< " case NoSemaHandlerAttribute:\n";
3637 OS
<< " llvm_unreachable(\"Ignored/unknown shouldn't get here\");\n";
3639 ParsedAttrMap Attrs
= getParsedAttrList(Records
);
3640 for (const auto &I
: Attrs
) {
3641 const Record
&R
= *I
.second
;
3642 std::vector
<FlattenedSpelling
> Spellings
= GetFlattenedSpellings(R
);
3643 OS
<< " case AT_" << I
.first
<< ": {\n";
3644 for (unsigned I
= 0; I
< Spellings
.size(); ++ I
) {
3645 OS
<< " if (Name == \"" << Spellings
[I
].name() << "\" && "
3646 << "getSyntax() == AttributeCommonInfo::AS_" << Spellings
[I
].variety()
3647 << " && Scope == \"" << Spellings
[I
].nameSpace() << "\")\n"
3648 << " return " << I
<< ";\n";
3656 OS
<< " return 0;\n";
3659 // Emits code used by RecursiveASTVisitor to visit attributes
3660 void EmitClangAttrASTVisitor(RecordKeeper
&Records
, raw_ostream
&OS
) {
3661 emitSourceFileHeader("Used by RecursiveASTVisitor to visit attributes.", OS
,
3664 std::vector
<Record
*> Attrs
= Records
.getAllDerivedDefinitions("Attr");
3666 // Write method declarations for Traverse* methods.
3667 // We emit this here because we only generate methods for attributes that
3668 // are declared as ASTNodes.
3669 OS
<< "#ifdef ATTR_VISITOR_DECLS_ONLY\n\n";
3670 for (const auto *Attr
: Attrs
) {
3671 const Record
&R
= *Attr
;
3672 if (!R
.getValueAsBit("ASTNode"))
3674 OS
<< " bool Traverse"
3675 << R
.getName() << "Attr(" << R
.getName() << "Attr *A);\n";
3677 << R
.getName() << "Attr(" << R
.getName() << "Attr *A) {\n"
3678 << " return true; \n"
3681 OS
<< "\n#else // ATTR_VISITOR_DECLS_ONLY\n\n";
3683 // Write individual Traverse* methods for each attribute class.
3684 for (const auto *Attr
: Attrs
) {
3685 const Record
&R
= *Attr
;
3686 if (!R
.getValueAsBit("ASTNode"))
3689 OS
<< "template <typename Derived>\n"
3690 << "bool VISITORCLASS<Derived>::Traverse"
3691 << R
.getName() << "Attr(" << R
.getName() << "Attr *A) {\n"
3692 << " if (!getDerived().VisitAttr(A))\n"
3693 << " return false;\n"
3694 << " if (!getDerived().Visit" << R
.getName() << "Attr(A))\n"
3695 << " return false;\n";
3697 std::vector
<Record
*> ArgRecords
= R
.getValueAsListOfDefs("Args");
3698 for (const auto *Arg
: ArgRecords
)
3699 createArgument(*Arg
, R
.getName())->writeASTVisitorTraversal(OS
);
3701 if (Attr
->getValueAsBit("AcceptsExprPack"))
3702 VariadicExprArgument("DelayedArgs", R
.getName())
3703 .writeASTVisitorTraversal(OS
);
3705 OS
<< " return true;\n";
3709 // Write generic Traverse routine
3710 OS
<< "template <typename Derived>\n"
3711 << "bool VISITORCLASS<Derived>::TraverseAttr(Attr *A) {\n"
3713 << " return true;\n"
3715 << " switch (A->getKind()) {\n";
3717 for (const auto *Attr
: Attrs
) {
3718 const Record
&R
= *Attr
;
3719 if (!R
.getValueAsBit("ASTNode"))
3722 OS
<< " case attr::" << R
.getName() << ":\n"
3723 << " return getDerived().Traverse" << R
.getName() << "Attr("
3724 << "cast<" << R
.getName() << "Attr>(A));\n";
3726 OS
<< " }\n"; // end switch
3727 OS
<< " llvm_unreachable(\"bad attribute kind\");\n";
3728 OS
<< "}\n"; // end function
3729 OS
<< "#endif // ATTR_VISITOR_DECLS_ONLY\n";
3732 void EmitClangAttrTemplateInstantiateHelper(const std::vector
<Record
*> &Attrs
,
3734 bool AppliesToDecl
) {
3736 OS
<< " switch (At->getKind()) {\n";
3737 for (const auto *Attr
: Attrs
) {
3738 const Record
&R
= *Attr
;
3739 if (!R
.getValueAsBit("ASTNode"))
3741 OS
<< " case attr::" << R
.getName() << ": {\n";
3742 bool ShouldClone
= R
.getValueAsBit("Clone") &&
3744 R
.getValueAsBit("MeaningfulToClassTemplateDefinition"));
3747 OS
<< " return nullptr;\n";
3752 OS
<< " const auto *A = cast<"
3753 << R
.getName() << "Attr>(At);\n";
3754 bool TDependent
= R
.getValueAsBit("TemplateDependent");
3757 OS
<< " return A->clone(C);\n";
3762 std::vector
<Record
*> ArgRecords
= R
.getValueAsListOfDefs("Args");
3763 std::vector
<std::unique_ptr
<Argument
>> Args
;
3764 Args
.reserve(ArgRecords
.size());
3766 for (const auto *ArgRecord
: ArgRecords
)
3767 Args
.emplace_back(createArgument(*ArgRecord
, R
.getName()));
3769 for (auto const &ai
: Args
)
3770 ai
->writeTemplateInstantiation(OS
);
3772 OS
<< " return new (C) " << R
.getName() << "Attr(C, *A";
3773 for (auto const &ai
: Args
) {
3775 ai
->writeTemplateInstantiationArgs(OS
);
3780 OS
<< " } // end switch\n"
3781 << " llvm_unreachable(\"Unknown attribute!\");\n"
3782 << " return nullptr;\n";
3785 // Emits code to instantiate dependent attributes on templates.
3786 void EmitClangAttrTemplateInstantiate(RecordKeeper
&Records
, raw_ostream
&OS
) {
3787 emitSourceFileHeader("Template instantiation code for attributes", OS
,
3790 std::vector
<Record
*> Attrs
= Records
.getAllDerivedDefinitions("Attr");
3792 OS
<< "namespace clang {\n"
3793 << "namespace sema {\n\n"
3794 << "Attr *instantiateTemplateAttribute(const Attr *At, ASTContext &C, "
3796 << " const MultiLevelTemplateArgumentList &TemplateArgs) {\n";
3797 EmitClangAttrTemplateInstantiateHelper(Attrs
, OS
, /*AppliesToDecl*/false);
3799 << "Attr *instantiateTemplateAttributeForDecl(const Attr *At,\n"
3800 << " ASTContext &C, Sema &S,\n"
3801 << " const MultiLevelTemplateArgumentList &TemplateArgs) {\n";
3802 EmitClangAttrTemplateInstantiateHelper(Attrs
, OS
, /*AppliesToDecl*/true);
3804 << "} // end namespace sema\n"
3805 << "} // end namespace clang\n";
3808 // Emits the list of parsed attributes.
3809 void EmitClangAttrParsedAttrList(RecordKeeper
&Records
, raw_ostream
&OS
) {
3810 emitSourceFileHeader("List of all attributes that Clang recognizes", OS
,
3813 OS
<< "#ifndef PARSED_ATTR\n";
3814 OS
<< "#define PARSED_ATTR(NAME) NAME\n";
3817 ParsedAttrMap Names
= getParsedAttrList(Records
);
3818 for (const auto &I
: Names
) {
3819 OS
<< "PARSED_ATTR(" << I
.first
<< ")\n";
3823 static bool isArgVariadic(const Record
&R
, StringRef AttrName
) {
3824 return createArgument(R
, AttrName
)->isVariadic();
3827 static void emitArgInfo(const Record
&R
, raw_ostream
&OS
) {
3828 // This function will count the number of arguments specified for the
3829 // attribute and emit the number of required arguments followed by the
3830 // number of optional arguments.
3831 std::vector
<Record
*> Args
= R
.getValueAsListOfDefs("Args");
3832 unsigned ArgCount
= 0, OptCount
= 0, ArgMemberCount
= 0;
3833 bool HasVariadic
= false;
3834 for (const auto *Arg
: Args
) {
3835 // If the arg is fake, it's the user's job to supply it: general parsing
3836 // logic shouldn't need to know anything about it.
3837 if (Arg
->getValueAsBit("Fake"))
3839 Arg
->getValueAsBit("Optional") ? ++OptCount
: ++ArgCount
;
3841 if (!HasVariadic
&& isArgVariadic(*Arg
, R
.getName()))
3845 // If there is a variadic argument, we will set the optional argument count
3846 // to its largest value. Since it's currently a 4-bit number, we set it to 15.
3847 OS
<< " /*NumArgs=*/" << ArgCount
<< ",\n";
3848 OS
<< " /*OptArgs=*/" << (HasVariadic
? 15 : OptCount
) << ",\n";
3849 OS
<< " /*NumArgMembers=*/" << ArgMemberCount
<< ",\n";
3852 static std::string
GetDiagnosticSpelling(const Record
&R
) {
3853 std::string Ret
= std::string(R
.getValueAsString("DiagSpelling"));
3857 // If we couldn't find the DiagSpelling in this object, we can check to see
3858 // if the object is one that has a base, and if it is, loop up to the Base
3859 // member recursively.
3860 if (auto Base
= R
.getValueAsOptionalDef(BaseFieldName
))
3861 return GetDiagnosticSpelling(*Base
);
3866 static std::string
CalculateDiagnostic(const Record
&S
) {
3867 // If the SubjectList object has a custom diagnostic associated with it,
3868 // return that directly.
3869 const StringRef CustomDiag
= S
.getValueAsString("CustomDiag");
3870 if (!CustomDiag
.empty())
3871 return ("\"" + Twine(CustomDiag
) + "\"").str();
3873 std::vector
<std::string
> DiagList
;
3874 std::vector
<Record
*> Subjects
= S
.getValueAsListOfDefs("Subjects");
3875 for (const auto *Subject
: Subjects
) {
3876 const Record
&R
= *Subject
;
3877 // Get the diagnostic text from the Decl or Stmt node given.
3878 std::string V
= GetDiagnosticSpelling(R
);
3880 PrintError(R
.getLoc(),
3881 "Could not determine diagnostic spelling for the node: " +
3882 R
.getName() + "; please add one to DeclNodes.td");
3884 // The node may contain a list of elements itself, so split the elements
3885 // by a comma, and trim any whitespace.
3886 SmallVector
<StringRef
, 2> Frags
;
3887 llvm::SplitString(V
, Frags
, ",");
3888 for (auto Str
: Frags
) {
3889 DiagList
.push_back(std::string(Str
.trim()));
3894 if (DiagList
.empty()) {
3895 PrintFatalError(S
.getLoc(),
3896 "Could not deduce diagnostic argument for Attr subjects");
3900 // FIXME: this is not particularly good for localization purposes and ideally
3901 // should be part of the diagnostics engine itself with some sort of list
3904 // A single member of the list can be returned directly.
3905 if (DiagList
.size() == 1)
3906 return '"' + DiagList
.front() + '"';
3908 if (DiagList
.size() == 2)
3909 return '"' + DiagList
[0] + " and " + DiagList
[1] + '"';
3911 // If there are more than two in the list, we serialize the first N - 1
3912 // elements with a comma. This leaves the string in the state: foo, bar,
3913 // baz (but misses quux). We can then add ", and " for the last element
3915 std::string Diag
= llvm::join(DiagList
.begin(), DiagList
.end() - 1, ", ");
3916 return '"' + Diag
+ ", and " + *(DiagList
.end() - 1) + '"';
3919 static std::string
GetSubjectWithSuffix(const Record
*R
) {
3920 const std::string
&B
= std::string(R
->getName());
3921 if (B
== "DeclBase")
3926 static std::string
functionNameForCustomAppertainsTo(const Record
&Subject
) {
3927 return "is" + Subject
.getName().str();
3930 static void GenerateCustomAppertainsTo(const Record
&Subject
, raw_ostream
&OS
) {
3931 std::string FnName
= functionNameForCustomAppertainsTo(Subject
);
3933 // If this code has already been generated, we don't need to do anything.
3934 static std::set
<std::string
> CustomSubjectSet
;
3935 auto I
= CustomSubjectSet
.find(FnName
);
3936 if (I
!= CustomSubjectSet
.end())
3939 // This only works with non-root Decls.
3940 Record
*Base
= Subject
.getValueAsDef(BaseFieldName
);
3942 // Not currently support custom subjects within custom subjects.
3943 if (Base
->isSubClassOf("SubsetSubject")) {
3944 PrintFatalError(Subject
.getLoc(),
3945 "SubsetSubjects within SubsetSubjects is not supported");
3949 OS
<< "static bool " << FnName
<< "(const Decl *D) {\n";
3950 OS
<< " if (const auto *S = dyn_cast<";
3951 OS
<< GetSubjectWithSuffix(Base
);
3953 OS
<< " return " << Subject
.getValueAsString("CheckCode") << ";\n";
3954 OS
<< " return false;\n";
3957 CustomSubjectSet
.insert(FnName
);
3960 static void GenerateAppertainsTo(const Record
&Attr
, raw_ostream
&OS
) {
3961 // If the attribute does not contain a Subjects definition, then use the
3962 // default appertainsTo logic.
3963 if (Attr
.isValueUnset("Subjects"))
3966 const Record
*SubjectObj
= Attr
.getValueAsDef("Subjects");
3967 std::vector
<Record
*> Subjects
= SubjectObj
->getValueAsListOfDefs("Subjects");
3969 // If the list of subjects is empty, it is assumed that the attribute
3970 // appertains to everything.
3971 if (Subjects
.empty())
3974 bool Warn
= SubjectObj
->getValueAsDef("Diag")->getValueAsBit("Warn");
3976 // Split the subjects into declaration subjects and statement subjects.
3977 // FIXME: subset subjects are added to the declaration list until there are
3978 // enough statement attributes with custom subject needs to warrant
3979 // the implementation effort.
3980 std::vector
<Record
*> DeclSubjects
, StmtSubjects
;
3982 Subjects
, std::back_inserter(DeclSubjects
), [](const Record
*R
) {
3983 return R
->isSubClassOf("SubsetSubject") || !R
->isSubClassOf("StmtNode");
3985 llvm::copy_if(Subjects
, std::back_inserter(StmtSubjects
),
3986 [](const Record
*R
) { return R
->isSubClassOf("StmtNode"); });
3988 // We should have sorted all of the subjects into two lists.
3989 // FIXME: this assertion will be wrong if we ever add type attribute subjects.
3990 assert(DeclSubjects
.size() + StmtSubjects
.size() == Subjects
.size());
3992 if (DeclSubjects
.empty()) {
3993 // If there are no decl subjects but there are stmt subjects, diagnose
3994 // trying to apply a statement attribute to a declaration.
3995 if (!StmtSubjects
.empty()) {
3996 OS
<< "bool diagAppertainsToDecl(Sema &S, const ParsedAttr &AL, ";
3997 OS
<< "const Decl *D) const override {\n";
3998 OS
<< " S.Diag(AL.getLoc(), diag::err_attribute_invalid_on_decl)\n";
3999 OS
<< " << AL << AL.isRegularKeywordAttribute() << "
4000 "D->getLocation();\n";
4001 OS
<< " return false;\n";
4005 // Otherwise, generate an appertainsTo check specific to this attribute
4006 // which checks all of the given subjects against the Decl passed in.
4007 OS
<< "bool diagAppertainsToDecl(Sema &S, ";
4008 OS
<< "const ParsedAttr &Attr, const Decl *D) const override {\n";
4010 for (auto I
= DeclSubjects
.begin(), E
= DeclSubjects
.end(); I
!= E
; ++I
) {
4011 // If the subject has custom code associated with it, use the generated
4012 // function for it. The function cannot be inlined into this check (yet)
4013 // because it requires the subject to be of a specific type, and were that
4014 // information inlined here, it would not support an attribute with
4015 // multiple custom subjects.
4016 if ((*I
)->isSubClassOf("SubsetSubject"))
4017 OS
<< "!" << functionNameForCustomAppertainsTo(**I
) << "(D)";
4019 OS
<< "!isa<" << GetSubjectWithSuffix(*I
) << ">(D)";
4025 OS
<< " S.Diag(Attr.getLoc(), diag::";
4026 OS
<< (Warn
? "warn_attribute_wrong_decl_type_str"
4027 : "err_attribute_wrong_decl_type_str");
4029 OS
<< " << Attr << Attr.isRegularKeywordAttribute() << ";
4030 OS
<< CalculateDiagnostic(*SubjectObj
) << ";\n";
4031 OS
<< " return false;\n";
4033 OS
<< " return true;\n";
4037 if (StmtSubjects
.empty()) {
4038 // If there are no stmt subjects but there are decl subjects, diagnose
4039 // trying to apply a declaration attribute to a statement.
4040 if (!DeclSubjects
.empty()) {
4041 OS
<< "bool diagAppertainsToStmt(Sema &S, const ParsedAttr &AL, ";
4042 OS
<< "const Stmt *St) const override {\n";
4043 OS
<< " S.Diag(AL.getLoc(), diag::err_decl_attribute_invalid_on_stmt)\n";
4044 OS
<< " << AL << AL.isRegularKeywordAttribute() << "
4045 "St->getBeginLoc();\n";
4046 OS
<< " return false;\n";
4050 // Now, do the same for statements.
4051 OS
<< "bool diagAppertainsToStmt(Sema &S, ";
4052 OS
<< "const ParsedAttr &Attr, const Stmt *St) const override {\n";
4054 for (auto I
= StmtSubjects
.begin(), E
= StmtSubjects
.end(); I
!= E
; ++I
) {
4055 OS
<< "!isa<" << (*I
)->getName() << ">(St)";
4060 OS
<< " S.Diag(Attr.getLoc(), diag::";
4061 OS
<< (Warn
? "warn_attribute_wrong_decl_type_str"
4062 : "err_attribute_wrong_decl_type_str");
4064 OS
<< " << Attr << Attr.isRegularKeywordAttribute() << ";
4065 OS
<< CalculateDiagnostic(*SubjectObj
) << ";\n";
4066 OS
<< " return false;\n";
4068 OS
<< " return true;\n";
4073 // Generates the mutual exclusion checks. The checks for parsed attributes are
4074 // written into OS and the checks for merging declaration attributes are
4075 // written into MergeOS.
4076 static void GenerateMutualExclusionsChecks(const Record
&Attr
,
4077 const RecordKeeper
&Records
,
4079 raw_ostream
&MergeDeclOS
,
4080 raw_ostream
&MergeStmtOS
) {
4081 // Find all of the definitions that inherit from MutualExclusions and include
4082 // the given attribute in the list of exclusions to generate the
4083 // diagMutualExclusion() check.
4084 std::vector
<Record
*> ExclusionsList
=
4085 Records
.getAllDerivedDefinitions("MutualExclusions");
4087 // We don't do any of this magic for type attributes yet.
4088 if (Attr
.isSubClassOf("TypeAttr"))
4091 // This means the attribute is either a statement attribute, a decl
4092 // attribute, or both; find out which.
4093 bool CurAttrIsStmtAttr
=
4094 Attr
.isSubClassOf("StmtAttr") || Attr
.isSubClassOf("DeclOrStmtAttr");
4095 bool CurAttrIsDeclAttr
=
4096 !CurAttrIsStmtAttr
|| Attr
.isSubClassOf("DeclOrStmtAttr");
4098 std::vector
<std::string
> DeclAttrs
, StmtAttrs
;
4100 for (const Record
*Exclusion
: ExclusionsList
) {
4101 std::vector
<Record
*> MutuallyExclusiveAttrs
=
4102 Exclusion
->getValueAsListOfDefs("Exclusions");
4103 auto IsCurAttr
= [Attr
](const Record
*R
) {
4104 return R
->getName() == Attr
.getName();
4106 if (llvm::any_of(MutuallyExclusiveAttrs
, IsCurAttr
)) {
4107 // This list of exclusions includes the attribute we're looking for, so
4108 // add the exclusive attributes to the proper list for checking.
4109 for (const Record
*AttrToExclude
: MutuallyExclusiveAttrs
) {
4110 if (IsCurAttr(AttrToExclude
))
4113 if (CurAttrIsStmtAttr
)
4114 StmtAttrs
.push_back((AttrToExclude
->getName() + "Attr").str());
4115 if (CurAttrIsDeclAttr
)
4116 DeclAttrs
.push_back((AttrToExclude
->getName() + "Attr").str());
4121 // If there are any decl or stmt attributes, silence -Woverloaded-virtual
4122 // warnings for them both.
4123 if (!DeclAttrs
.empty() || !StmtAttrs
.empty())
4124 OS
<< " using ParsedAttrInfo::diagMutualExclusion;\n\n";
4126 // If we discovered any decl or stmt attributes to test for, generate the
4127 // predicates for them now.
4128 if (!DeclAttrs
.empty()) {
4129 // Generate the ParsedAttrInfo subclass logic for declarations.
4130 OS
<< " bool diagMutualExclusion(Sema &S, const ParsedAttr &AL, "
4131 << "const Decl *D) const override {\n";
4132 for (const std::string
&A
: DeclAttrs
) {
4133 OS
<< " if (const auto *A = D->getAttr<" << A
<< ">()) {\n";
4134 OS
<< " S.Diag(AL.getLoc(), diag::err_attributes_are_not_compatible)"
4135 << " << AL << A << (AL.isRegularKeywordAttribute() ||"
4136 << " A->isRegularKeywordAttribute());\n";
4137 OS
<< " S.Diag(A->getLocation(), diag::note_conflicting_attribute);";
4138 OS
<< " \nreturn false;\n";
4141 OS
<< " return true;\n";
4144 // Also generate the declaration attribute merging logic if the current
4145 // attribute is one that can be inheritted on a declaration. It is assumed
4146 // this code will be executed in the context of a function with parameters:
4147 // Sema &S, Decl *D, Attr *A and that returns a bool (false on diagnostic,
4148 // true on success).
4149 if (Attr
.isSubClassOf("InheritableAttr")) {
4150 MergeDeclOS
<< " if (const auto *Second = dyn_cast<"
4151 << (Attr
.getName() + "Attr").str() << ">(A)) {\n";
4152 for (const std::string
&A
: DeclAttrs
) {
4153 MergeDeclOS
<< " if (const auto *First = D->getAttr<" << A
4155 MergeDeclOS
<< " S.Diag(First->getLocation(), "
4156 << "diag::err_attributes_are_not_compatible) << First << "
4157 << "Second << (First->isRegularKeywordAttribute() || "
4158 << "Second->isRegularKeywordAttribute());\n";
4159 MergeDeclOS
<< " S.Diag(Second->getLocation(), "
4160 << "diag::note_conflicting_attribute);\n";
4161 MergeDeclOS
<< " return false;\n";
4162 MergeDeclOS
<< " }\n";
4164 MergeDeclOS
<< " return true;\n";
4165 MergeDeclOS
<< " }\n";
4169 // Statement attributes are a bit different from declarations. With
4170 // declarations, each attribute is added to the declaration as it is
4171 // processed, and so you can look on the Decl * itself to see if there is a
4172 // conflicting attribute. Statement attributes are processed as a group
4173 // because AttributedStmt needs to tail-allocate all of the attribute nodes
4174 // at once. This means we cannot check whether the statement already contains
4175 // an attribute to check for the conflict. Instead, we need to check whether
4176 // the given list of semantic attributes contain any conflicts. It is assumed
4177 // this code will be executed in the context of a function with parameters:
4178 // Sema &S, const SmallVectorImpl<const Attr *> &C. The code will be within a
4179 // loop which loops over the container C with a loop variable named A to
4180 // represent the current attribute to check for conflicts.
4182 // FIXME: it would be nice not to walk over the list of potential attributes
4183 // to apply to the statement more than once, but statements typically don't
4184 // have long lists of attributes on them, so re-walking the list should not
4185 // be an expensive operation.
4186 if (!StmtAttrs
.empty()) {
4187 MergeStmtOS
<< " if (const auto *Second = dyn_cast<"
4188 << (Attr
.getName() + "Attr").str() << ">(A)) {\n";
4189 MergeStmtOS
<< " auto Iter = llvm::find_if(C, [](const Attr *Check) "
4192 StmtAttrs
, [&](const std::string
&Name
) { MergeStmtOS
<< Name
; },
4193 [&] { MergeStmtOS
<< ", "; });
4194 MergeStmtOS
<< ">(Check); });\n";
4195 MergeStmtOS
<< " if (Iter != C.end()) {\n";
4196 MergeStmtOS
<< " S.Diag((*Iter)->getLocation(), "
4197 << "diag::err_attributes_are_not_compatible) << *Iter << "
4198 << "Second << ((*Iter)->isRegularKeywordAttribute() || "
4199 << "Second->isRegularKeywordAttribute());\n";
4200 MergeStmtOS
<< " S.Diag(Second->getLocation(), "
4201 << "diag::note_conflicting_attribute);\n";
4202 MergeStmtOS
<< " return false;\n";
4203 MergeStmtOS
<< " }\n";
4204 MergeStmtOS
<< " }\n";
4209 emitAttributeMatchRules(PragmaClangAttributeSupport
&PragmaAttributeSupport
,
4211 OS
<< "static bool checkAttributeMatchRuleAppliesTo(const Decl *D, "
4212 << AttributeSubjectMatchRule::EnumName
<< " rule) {\n";
4213 OS
<< " switch (rule) {\n";
4214 for (const auto &Rule
: PragmaAttributeSupport
.Rules
) {
4215 if (Rule
.isAbstractRule()) {
4216 OS
<< " case " << Rule
.getEnumValue() << ":\n";
4217 OS
<< " assert(false && \"Abstract matcher rule isn't allowed\");\n";
4218 OS
<< " return false;\n";
4221 std::vector
<Record
*> Subjects
= Rule
.getSubjects();
4222 assert(!Subjects
.empty() && "Missing subjects");
4223 OS
<< " case " << Rule
.getEnumValue() << ":\n";
4225 for (auto I
= Subjects
.begin(), E
= Subjects
.end(); I
!= E
; ++I
) {
4226 // If the subject has custom code associated with it, use the function
4227 // that was generated for GenerateAppertainsTo to check if the declaration
4229 if ((*I
)->isSubClassOf("SubsetSubject"))
4230 OS
<< functionNameForCustomAppertainsTo(**I
) << "(D)";
4232 OS
<< "isa<" << GetSubjectWithSuffix(*I
) << ">(D)";
4240 OS
<< " llvm_unreachable(\"Invalid match rule\");\nreturn false;\n";
4244 static void GenerateLangOptRequirements(const Record
&R
,
4246 // If the attribute has an empty or unset list of language requirements,
4247 // use the default handler.
4248 std::vector
<Record
*> LangOpts
= R
.getValueAsListOfDefs("LangOpts");
4249 if (LangOpts
.empty())
4252 OS
<< "bool acceptsLangOpts(const LangOptions &LangOpts) const override {\n";
4253 OS
<< " return " << GenerateTestExpression(LangOpts
) << ";\n";
4257 static void GenerateTargetRequirements(const Record
&Attr
,
4258 const ParsedAttrMap
&Dupes
,
4260 // If the attribute is not a target specific attribute, use the default
4262 if (!Attr
.isSubClassOf("TargetSpecificAttr"))
4265 // Get the list of architectures to be tested for.
4266 const Record
*R
= Attr
.getValueAsDef("Target");
4267 std::vector
<StringRef
> Arches
= R
->getValueAsListOfStrings("Arches");
4269 // If there are other attributes which share the same parsed attribute kind,
4270 // such as target-specific attributes with a shared spelling, collapse the
4271 // duplicate architectures. This is required because a shared target-specific
4272 // attribute has only one ParsedAttr::Kind enumeration value, but it
4273 // applies to multiple target architectures. In order for the attribute to be
4274 // considered valid, all of its architectures need to be included.
4275 if (!Attr
.isValueUnset("ParseKind")) {
4276 const StringRef APK
= Attr
.getValueAsString("ParseKind");
4277 for (const auto &I
: Dupes
) {
4278 if (I
.first
== APK
) {
4279 std::vector
<StringRef
> DA
=
4280 I
.second
->getValueAsDef("Target")->getValueAsListOfStrings(
4282 Arches
.insert(Arches
.end(), DA
.begin(), DA
.end());
4287 std::string FnName
= "isTarget";
4289 bool UsesT
= GenerateTargetSpecificAttrChecks(R
, Arches
, Test
, &FnName
);
4291 OS
<< "bool existsInTarget(const TargetInfo &Target) const override {\n";
4293 OS
<< " const llvm::Triple &T = Target.getTriple(); (void)T;\n";
4294 OS
<< " return " << Test
<< ";\n";
4299 GenerateSpellingTargetRequirements(const Record
&Attr
,
4300 const std::vector
<Record
*> &TargetSpellings
,
4302 // If there are no target specific spellings, use the default target handler.
4303 if (TargetSpellings
.empty())
4308 const std::vector
<FlattenedSpelling
> SpellingList
=
4309 GetFlattenedSpellings(Attr
);
4310 for (unsigned TargetIndex
= 0; TargetIndex
< TargetSpellings
.size();
4312 const auto &TargetSpelling
= TargetSpellings
[TargetIndex
];
4313 std::vector
<FlattenedSpelling
> Spellings
=
4314 GetFlattenedSpellings(*TargetSpelling
);
4316 Test
+= "((SpellingListIndex == ";
4317 for (unsigned Index
= 0; Index
< Spellings
.size(); ++Index
) {
4319 llvm::itostr(getSpellingListIndex(SpellingList
, Spellings
[Index
]));
4320 if (Index
!= Spellings
.size() - 1)
4321 Test
+= " ||\n SpellingListIndex == ";
4326 const Record
*Target
= TargetSpelling
->getValueAsDef("Target");
4327 std::vector
<StringRef
> Arches
= Target
->getValueAsListOfStrings("Arches");
4328 std::string FnName
= "isTargetSpelling";
4329 UsesT
|= GenerateTargetSpecificAttrChecks(Target
, Arches
, Test
, &FnName
);
4331 if (TargetIndex
!= TargetSpellings
.size() - 1)
4335 OS
<< "bool spellingExistsInTarget(const TargetInfo &Target,\n";
4336 OS
<< " const unsigned SpellingListIndex) const "
4339 OS
<< " const llvm::Triple &T = Target.getTriple(); (void)T;\n";
4340 OS
<< " return " << Test
<< ";\n", OS
<< "}\n\n";
4343 static void GenerateSpellingIndexToSemanticSpelling(const Record
&Attr
,
4345 // If the attribute does not have a semantic form, we can bail out early.
4346 if (!Attr
.getValueAsBit("ASTNode"))
4349 std::vector
<FlattenedSpelling
> Spellings
= GetFlattenedSpellings(Attr
);
4351 // If there are zero or one spellings, or all of the spellings share the same
4352 // name, we can also bail out early.
4353 if (Spellings
.size() <= 1 || SpellingNamesAreCommon(Spellings
))
4356 // Generate the enumeration we will use for the mapping.
4357 SemanticSpellingMap SemanticToSyntacticMap
;
4358 std::string Enum
= CreateSemanticSpellings(Spellings
, SemanticToSyntacticMap
);
4359 std::string Name
= Attr
.getName().str() + "AttrSpellingMap";
4361 OS
<< "unsigned spellingIndexToSemanticSpelling(";
4362 OS
<< "const ParsedAttr &Attr) const override {\n";
4364 OS
<< " unsigned Idx = Attr.getAttributeSpellingListIndex();\n";
4365 WriteSemanticSpellingSwitch("Idx", SemanticToSyntacticMap
, OS
);
4369 static void GenerateHandleDeclAttribute(const Record
&Attr
, raw_ostream
&OS
) {
4370 // Only generate if Attr can be handled simply.
4371 if (!Attr
.getValueAsBit("SimpleHandler"))
4374 // Generate a function which just converts from ParsedAttr to the Attr type.
4375 OS
<< "AttrHandling handleDeclAttribute(Sema &S, Decl *D,";
4376 OS
<< "const ParsedAttr &Attr) const override {\n";
4377 OS
<< " D->addAttr(::new (S.Context) " << Attr
.getName();
4378 OS
<< "Attr(S.Context, Attr));\n";
4379 OS
<< " return AttributeApplied;\n";
4383 static bool isParamExpr(const Record
*Arg
) {
4384 return !Arg
->getSuperClasses().empty() &&
4385 llvm::StringSwitch
<bool>(
4386 Arg
->getSuperClasses().back().first
->getName())
4387 .Case("ExprArgument", true)
4388 .Case("VariadicExprArgument", true)
4392 void GenerateIsParamExpr(const Record
&Attr
, raw_ostream
&OS
) {
4393 OS
<< "bool isParamExpr(size_t N) const override {\n";
4395 auto Args
= Attr
.getValueAsListOfDefs("Args");
4396 for (size_t I
= 0; I
< Args
.size(); ++I
)
4397 if (isParamExpr(Args
[I
]))
4398 OS
<< "(N == " << I
<< ") || ";
4403 void GenerateHandleAttrWithDelayedArgs(RecordKeeper
&Records
, raw_ostream
&OS
) {
4404 OS
<< "static void handleAttrWithDelayedArgs(Sema &S, Decl *D, ";
4405 OS
<< "const ParsedAttr &Attr) {\n";
4406 OS
<< " SmallVector<Expr *, 4> ArgExprs;\n";
4407 OS
<< " ArgExprs.reserve(Attr.getNumArgs());\n";
4408 OS
<< " for (unsigned I = 0; I < Attr.getNumArgs(); ++I) {\n";
4409 OS
<< " assert(!Attr.isArgIdent(I));\n";
4410 OS
<< " ArgExprs.push_back(Attr.getArgAsExpr(I));\n";
4412 OS
<< " clang::Attr *CreatedAttr = nullptr;\n";
4413 OS
<< " switch (Attr.getKind()) {\n";
4414 OS
<< " default:\n";
4415 OS
<< " llvm_unreachable(\"Attribute cannot hold delayed arguments.\");\n";
4416 ParsedAttrMap Attrs
= getParsedAttrList(Records
);
4417 for (const auto &I
: Attrs
) {
4418 const Record
&R
= *I
.second
;
4419 if (!R
.getValueAsBit("AcceptsExprPack"))
4421 OS
<< " case ParsedAttr::AT_" << I
.first
<< ": {\n";
4422 OS
<< " CreatedAttr = " << R
.getName() << "Attr::CreateWithDelayedArgs";
4423 OS
<< "(S.Context, ArgExprs.data(), ArgExprs.size(), Attr);\n";
4428 OS
<< " D->addAttr(CreatedAttr);\n";
4432 static bool IsKnownToGCC(const Record
&Attr
) {
4433 // Look at the spellings for this subject; if there are any spellings which
4434 // claim to be known to GCC, the attribute is known to GCC.
4435 return llvm::any_of(
4436 GetFlattenedSpellings(Attr
),
4437 [](const FlattenedSpelling
&S
) { return S
.knownToGCC(); });
4440 /// Emits the parsed attribute helpers
4441 void EmitClangAttrParsedAttrImpl(RecordKeeper
&Records
, raw_ostream
&OS
) {
4442 emitSourceFileHeader("Parsed attribute helpers", OS
, Records
);
4444 OS
<< "#if !defined(WANT_DECL_MERGE_LOGIC) && "
4445 << "!defined(WANT_STMT_MERGE_LOGIC)\n";
4446 PragmaClangAttributeSupport
&PragmaAttributeSupport
=
4447 getPragmaAttributeSupport(Records
);
4449 // Get the list of parsed attributes, and accept the optional list of
4450 // duplicates due to the ParseKind.
4451 ParsedAttrMap Dupes
;
4452 ParsedAttrMap Attrs
= getParsedAttrList(Records
, &Dupes
);
4454 // Generate all of the custom appertainsTo functions that the attributes
4456 for (const auto &I
: Attrs
) {
4457 const Record
&Attr
= *I
.second
;
4458 if (Attr
.isValueUnset("Subjects"))
4460 const Record
*SubjectObj
= Attr
.getValueAsDef("Subjects");
4461 for (auto Subject
: SubjectObj
->getValueAsListOfDefs("Subjects"))
4462 if (Subject
->isSubClassOf("SubsetSubject"))
4463 GenerateCustomAppertainsTo(*Subject
, OS
);
4466 // This stream is used to collect all of the declaration attribute merging
4467 // logic for performing mutual exclusion checks. This gets emitted at the
4468 // end of the file in a helper function of its own.
4469 std::string DeclMergeChecks
, StmtMergeChecks
;
4470 raw_string_ostream
MergeDeclOS(DeclMergeChecks
), MergeStmtOS(StmtMergeChecks
);
4472 // Generate a ParsedAttrInfo struct for each of the attributes.
4473 for (auto I
= Attrs
.begin(), E
= Attrs
.end(); I
!= E
; ++I
) {
4474 // TODO: If the attribute's kind appears in the list of duplicates, that is
4475 // because it is a target-specific attribute that appears multiple times.
4476 // It would be beneficial to test whether the duplicates are "similar
4477 // enough" to each other to not cause problems. For instance, check that
4478 // the spellings are identical, and custom parsing rules match, etc.
4480 // We need to generate struct instances based off ParsedAttrInfo from
4482 const std::string
&AttrName
= I
->first
;
4483 const Record
&Attr
= *I
->second
;
4484 auto Spellings
= GetFlattenedSpellings(Attr
);
4485 if (!Spellings
.empty()) {
4486 OS
<< "static constexpr ParsedAttrInfo::Spelling " << I
->first
4487 << "Spellings[] = {\n";
4488 for (const auto &S
: Spellings
) {
4489 const std::string
&RawSpelling
= S
.name();
4490 std::string Spelling
;
4491 if (!S
.nameSpace().empty())
4492 Spelling
+= S
.nameSpace() + "::";
4493 if (S
.variety() == "GNU")
4494 Spelling
+= NormalizeGNUAttrSpelling(RawSpelling
);
4496 Spelling
+= RawSpelling
;
4497 OS
<< " {AttributeCommonInfo::AS_" << S
.variety();
4498 OS
<< ", \"" << Spelling
<< "\"},\n";
4503 std::vector
<std::string
> ArgNames
;
4504 for (const auto &Arg
: Attr
.getValueAsListOfDefs("Args")) {
4506 if (Arg
->getValueAsBitOrUnset("Fake", UnusedUnset
))
4508 ArgNames
.push_back(Arg
->getValueAsString("Name").str());
4509 for (const auto &Class
: Arg
->getSuperClasses()) {
4510 if (Class
.first
->getName().startswith("Variadic")) {
4511 ArgNames
.back().append("...");
4516 if (!ArgNames
.empty()) {
4517 OS
<< "static constexpr const char *" << I
->first
<< "ArgNames[] = {\n";
4518 for (const auto &N
: ArgNames
)
4519 OS
<< '"' << N
<< "\",";
4523 OS
<< "struct ParsedAttrInfo" << I
->first
4524 << " final : public ParsedAttrInfo {\n";
4525 OS
<< " constexpr ParsedAttrInfo" << I
->first
<< "() : ParsedAttrInfo(\n";
4526 OS
<< " /*AttrKind=*/ParsedAttr::AT_" << AttrName
<< ",\n";
4527 emitArgInfo(Attr
, OS
);
4528 OS
<< " /*HasCustomParsing=*/";
4529 OS
<< Attr
.getValueAsBit("HasCustomParsing") << ",\n";
4530 OS
<< " /*AcceptsExprPack=*/";
4531 OS
<< Attr
.getValueAsBit("AcceptsExprPack") << ",\n";
4532 OS
<< " /*IsTargetSpecific=*/";
4533 OS
<< Attr
.isSubClassOf("TargetSpecificAttr") << ",\n";
4534 OS
<< " /*IsType=*/";
4535 OS
<< (Attr
.isSubClassOf("TypeAttr") || Attr
.isSubClassOf("DeclOrTypeAttr"))
4537 OS
<< " /*IsStmt=*/";
4538 OS
<< (Attr
.isSubClassOf("StmtAttr") || Attr
.isSubClassOf("DeclOrStmtAttr"))
4540 OS
<< " /*IsKnownToGCC=*/";
4541 OS
<< IsKnownToGCC(Attr
) << ",\n";
4542 OS
<< " /*IsSupportedByPragmaAttribute=*/";
4543 OS
<< PragmaAttributeSupport
.isAttributedSupported(*I
->second
) << ",\n";
4544 if (!Spellings
.empty())
4545 OS
<< " /*Spellings=*/" << I
->first
<< "Spellings,\n";
4547 OS
<< " /*Spellings=*/{},\n";
4548 if (!ArgNames
.empty())
4549 OS
<< " /*ArgNames=*/" << I
->first
<< "ArgNames";
4551 OS
<< " /*ArgNames=*/{}";
4553 GenerateAppertainsTo(Attr
, OS
);
4554 GenerateMutualExclusionsChecks(Attr
, Records
, OS
, MergeDeclOS
, MergeStmtOS
);
4555 GenerateLangOptRequirements(Attr
, OS
);
4556 GenerateTargetRequirements(Attr
, Dupes
, OS
);
4557 GenerateSpellingTargetRequirements(
4558 Attr
, Attr
.getValueAsListOfDefs("TargetSpecificSpellings"), OS
);
4559 GenerateSpellingIndexToSemanticSpelling(Attr
, OS
);
4560 PragmaAttributeSupport
.generateStrictConformsTo(*I
->second
, OS
);
4561 GenerateHandleDeclAttribute(Attr
, OS
);
4562 GenerateIsParamExpr(Attr
, OS
);
4563 OS
<< "static const ParsedAttrInfo" << I
->first
<< " Instance;\n";
4565 OS
<< "const ParsedAttrInfo" << I
->first
<< " ParsedAttrInfo" << I
->first
4569 OS
<< "static const ParsedAttrInfo *AttrInfoMap[] = {\n";
4570 for (auto I
= Attrs
.begin(), E
= Attrs
.end(); I
!= E
; ++I
) {
4571 OS
<< "&ParsedAttrInfo" << I
->first
<< "::Instance,\n";
4575 // Generate function for handling attributes with delayed arguments
4576 GenerateHandleAttrWithDelayedArgs(Records
, OS
);
4578 // Generate the attribute match rules.
4579 emitAttributeMatchRules(PragmaAttributeSupport
, OS
);
4581 OS
<< "#elif defined(WANT_DECL_MERGE_LOGIC)\n\n";
4583 // Write out the declaration merging check logic.
4584 OS
<< "static bool DiagnoseMutualExclusions(Sema &S, const NamedDecl *D, "
4585 << "const Attr *A) {\n";
4586 OS
<< MergeDeclOS
.str();
4587 OS
<< " return true;\n";
4590 OS
<< "#elif defined(WANT_STMT_MERGE_LOGIC)\n\n";
4592 // Write out the statement merging check logic.
4593 OS
<< "static bool DiagnoseMutualExclusions(Sema &S, "
4594 << "const SmallVectorImpl<const Attr *> &C) {\n";
4595 OS
<< " for (const Attr *A : C) {\n";
4596 OS
<< MergeStmtOS
.str();
4598 OS
<< " return true;\n";
4604 // Emits the kind list of parsed attributes
4605 void EmitClangAttrParsedAttrKinds(RecordKeeper
&Records
, raw_ostream
&OS
) {
4606 emitSourceFileHeader("Attribute name matcher", OS
, Records
);
4608 std::vector
<Record
*> Attrs
= Records
.getAllDerivedDefinitions("Attr");
4609 std::vector
<StringMatcher::StringPair
> GNU
, Declspec
, Microsoft
, CXX11
,
4610 Keywords
, Pragma
, C23
, HLSLSemantic
;
4611 std::set
<std::string
> Seen
;
4612 for (const auto *A
: Attrs
) {
4613 const Record
&Attr
= *A
;
4615 bool SemaHandler
= Attr
.getValueAsBit("SemaHandler");
4616 bool Ignored
= Attr
.getValueAsBit("Ignored");
4617 if (SemaHandler
|| Ignored
) {
4618 // Attribute spellings can be shared between target-specific attributes,
4619 // and can be shared between syntaxes for the same attribute. For
4620 // instance, an attribute can be spelled GNU<"interrupt"> for an ARM-
4621 // specific attribute, or MSP430-specific attribute. Additionally, an
4622 // attribute can be spelled GNU<"dllexport"> and Declspec<"dllexport">
4623 // for the same semantic attribute. Ultimately, we need to map each of
4624 // these to a single AttributeCommonInfo::Kind value, but the
4625 // StringMatcher class cannot handle duplicate match strings. So we
4626 // generate a list of string to match based on the syntax, and emit
4627 // multiple string matchers depending on the syntax used.
4628 std::string AttrName
;
4629 if (Attr
.isSubClassOf("TargetSpecificAttr") &&
4630 !Attr
.isValueUnset("ParseKind")) {
4631 AttrName
= std::string(Attr
.getValueAsString("ParseKind"));
4632 if (!Seen
.insert(AttrName
).second
)
4635 AttrName
= NormalizeAttrName(StringRef(Attr
.getName())).str();
4637 std::vector
<FlattenedSpelling
> Spellings
= GetFlattenedSpellings(Attr
);
4638 for (const auto &S
: Spellings
) {
4639 const std::string
&RawSpelling
= S
.name();
4640 std::vector
<StringMatcher::StringPair
> *Matches
= nullptr;
4641 std::string Spelling
;
4642 const std::string
&Variety
= S
.variety();
4643 if (Variety
== "CXX11") {
4645 if (!S
.nameSpace().empty())
4646 Spelling
+= S
.nameSpace() + "::";
4647 } else if (Variety
== "C23") {
4649 if (!S
.nameSpace().empty())
4650 Spelling
+= S
.nameSpace() + "::";
4651 } else if (Variety
== "GNU")
4653 else if (Variety
== "Declspec")
4654 Matches
= &Declspec
;
4655 else if (Variety
== "Microsoft")
4656 Matches
= &Microsoft
;
4657 else if (Variety
== "Keyword")
4658 Matches
= &Keywords
;
4659 else if (Variety
== "Pragma")
4661 else if (Variety
== "HLSLSemantic")
4662 Matches
= &HLSLSemantic
;
4664 assert(Matches
&& "Unsupported spelling variety found");
4666 if (Variety
== "GNU")
4667 Spelling
+= NormalizeGNUAttrSpelling(RawSpelling
);
4669 Spelling
+= RawSpelling
;
4672 Matches
->push_back(StringMatcher::StringPair(
4673 Spelling
, "return AttributeCommonInfo::AT_" + AttrName
+ ";"));
4675 Matches
->push_back(StringMatcher::StringPair(
4676 Spelling
, "return AttributeCommonInfo::IgnoredAttribute;"));
4681 OS
<< "static AttributeCommonInfo::Kind getAttrKind(StringRef Name, ";
4682 OS
<< "AttributeCommonInfo::Syntax Syntax) {\n";
4683 OS
<< " if (AttributeCommonInfo::AS_GNU == Syntax) {\n";
4684 StringMatcher("Name", GNU
, OS
).Emit();
4685 OS
<< " } else if (AttributeCommonInfo::AS_Declspec == Syntax) {\n";
4686 StringMatcher("Name", Declspec
, OS
).Emit();
4687 OS
<< " } else if (AttributeCommonInfo::AS_Microsoft == Syntax) {\n";
4688 StringMatcher("Name", Microsoft
, OS
).Emit();
4689 OS
<< " } else if (AttributeCommonInfo::AS_CXX11 == Syntax) {\n";
4690 StringMatcher("Name", CXX11
, OS
).Emit();
4691 OS
<< " } else if (AttributeCommonInfo::AS_C23 == Syntax) {\n";
4692 StringMatcher("Name", C23
, OS
).Emit();
4693 OS
<< " } else if (AttributeCommonInfo::AS_Keyword == Syntax || ";
4694 OS
<< "AttributeCommonInfo::AS_ContextSensitiveKeyword == Syntax) {\n";
4695 StringMatcher("Name", Keywords
, OS
).Emit();
4696 OS
<< " } else if (AttributeCommonInfo::AS_Pragma == Syntax) {\n";
4697 StringMatcher("Name", Pragma
, OS
).Emit();
4698 OS
<< " } else if (AttributeCommonInfo::AS_HLSLSemantic == Syntax) {\n";
4699 StringMatcher("Name", HLSLSemantic
, OS
).Emit();
4701 OS
<< " return AttributeCommonInfo::UnknownAttribute;\n"
4705 // Emits the code to dump an attribute.
4706 void EmitClangAttrTextNodeDump(RecordKeeper
&Records
, raw_ostream
&OS
) {
4707 emitSourceFileHeader("Attribute text node dumper", OS
, Records
);
4709 std::vector
<Record
*> Attrs
= Records
.getAllDerivedDefinitions("Attr"), Args
;
4710 for (const auto *Attr
: Attrs
) {
4711 const Record
&R
= *Attr
;
4712 if (!R
.getValueAsBit("ASTNode"))
4715 // If the attribute has a semantically-meaningful name (which is determined
4716 // by whether there is a Spelling enumeration for it), then write out the
4717 // spelling used for the attribute.
4719 std::string FunctionContent
;
4720 llvm::raw_string_ostream
SS(FunctionContent
);
4722 std::vector
<FlattenedSpelling
> Spellings
= GetFlattenedSpellings(R
);
4723 if (Spellings
.size() > 1 && !SpellingNamesAreCommon(Spellings
))
4724 SS
<< " OS << \" \" << A->getSpelling();\n";
4726 Args
= R
.getValueAsListOfDefs("Args");
4727 for (const auto *Arg
: Args
)
4728 createArgument(*Arg
, R
.getName())->writeDump(SS
);
4730 if (Attr
->getValueAsBit("AcceptsExprPack"))
4731 VariadicExprArgument("DelayedArgs", R
.getName()).writeDump(OS
);
4734 OS
<< " void Visit" << R
.getName() << "Attr(const " << R
.getName()
4737 OS
<< " const auto *SA = cast<" << R
.getName()
4738 << "Attr>(A); (void)SA;\n";
4745 void EmitClangAttrNodeTraverse(RecordKeeper
&Records
, raw_ostream
&OS
) {
4746 emitSourceFileHeader("Attribute text node traverser", OS
, Records
);
4748 std::vector
<Record
*> Attrs
= Records
.getAllDerivedDefinitions("Attr"), Args
;
4749 for (const auto *Attr
: Attrs
) {
4750 const Record
&R
= *Attr
;
4751 if (!R
.getValueAsBit("ASTNode"))
4754 std::string FunctionContent
;
4755 llvm::raw_string_ostream
SS(FunctionContent
);
4757 Args
= R
.getValueAsListOfDefs("Args");
4758 for (const auto *Arg
: Args
)
4759 createArgument(*Arg
, R
.getName())->writeDumpChildren(SS
);
4760 if (Attr
->getValueAsBit("AcceptsExprPack"))
4761 VariadicExprArgument("DelayedArgs", R
.getName()).writeDumpChildren(SS
);
4763 OS
<< " void Visit" << R
.getName() << "Attr(const " << R
.getName()
4766 OS
<< " const auto *SA = cast<" << R
.getName()
4767 << "Attr>(A); (void)SA;\n";
4774 void EmitClangAttrParserStringSwitches(RecordKeeper
&Records
, raw_ostream
&OS
) {
4775 emitSourceFileHeader("Parser-related llvm::StringSwitch cases", OS
, Records
);
4776 emitClangAttrArgContextList(Records
, OS
);
4777 emitClangAttrIdentifierArgList(Records
, OS
);
4778 emitClangAttrUnevaluatedStringLiteralList(Records
, OS
);
4779 emitClangAttrVariadicIdentifierArgList(Records
, OS
);
4780 emitClangAttrThisIsaIdentifierArgList(Records
, OS
);
4781 emitClangAttrAcceptsExprPack(Records
, OS
);
4782 emitClangAttrTypeArgList(Records
, OS
);
4783 emitClangAttrLateParsedList(Records
, OS
);
4786 void EmitClangAttrSubjectMatchRulesParserStringSwitches(RecordKeeper
&Records
,
4788 getPragmaAttributeSupport(Records
).generateParsingHelpers(OS
);
4791 void EmitClangAttrDocTable(RecordKeeper
&Records
, raw_ostream
&OS
) {
4792 emitSourceFileHeader("Clang attribute documentation", OS
, Records
);
4794 std::vector
<Record
*> Attrs
= Records
.getAllDerivedDefinitions("Attr");
4795 for (const auto *A
: Attrs
) {
4796 if (!A
->getValueAsBit("ASTNode"))
4798 std::vector
<Record
*> Docs
= A
->getValueAsListOfDefs("Documentation");
4799 assert(!Docs
.empty());
4800 // Only look at the first documentation if there are several.
4801 // (Currently there's only one such attr, revisit if this becomes common).
4803 Docs
.front()->getValueAsOptionalString("Content").value_or("");
4804 OS
<< "\nstatic const char AttrDoc_" << A
->getName() << "[] = "
4805 << "R\"reST(" << Text
.trim() << ")reST\";\n";
4809 enum class SpellingKind
: size_t {
4820 static const size_t NumSpellingKinds
= (size_t)SpellingKind::NumSpellingKinds
;
4822 class SpellingList
{
4823 std::vector
<std::string
> Spellings
[NumSpellingKinds
];
4826 ArrayRef
<std::string
> operator[](SpellingKind K
) const {
4827 return Spellings
[(size_t)K
];
4830 void add(const Record
&Attr
, FlattenedSpelling Spelling
) {
4831 SpellingKind Kind
= StringSwitch
<SpellingKind
>(Spelling
.variety())
4832 .Case("GNU", SpellingKind::GNU
)
4833 .Case("CXX11", SpellingKind::CXX11
)
4834 .Case("C23", SpellingKind::C23
)
4835 .Case("Declspec", SpellingKind::Declspec
)
4836 .Case("Microsoft", SpellingKind::Microsoft
)
4837 .Case("Keyword", SpellingKind::Keyword
)
4838 .Case("Pragma", SpellingKind::Pragma
)
4839 .Case("HLSLSemantic", SpellingKind::HLSLSemantic
);
4841 if (!Spelling
.nameSpace().empty()) {
4843 case SpellingKind::CXX11
:
4844 case SpellingKind::C23
:
4845 Name
= Spelling
.nameSpace() + "::";
4847 case SpellingKind::Pragma
:
4848 Name
= Spelling
.nameSpace() + " ";
4851 PrintFatalError(Attr
.getLoc(), "Unexpected namespace in spelling");
4854 Name
+= Spelling
.name();
4856 Spellings
[(size_t)Kind
].push_back(Name
);
4860 class DocumentationData
{
4862 const Record
*Documentation
;
4863 const Record
*Attribute
;
4864 std::string Heading
;
4865 SpellingList SupportedSpellings
;
4867 DocumentationData(const Record
&Documentation
, const Record
&Attribute
,
4868 std::pair
<std::string
, SpellingList
> HeadingAndSpellings
)
4869 : Documentation(&Documentation
), Attribute(&Attribute
),
4870 Heading(std::move(HeadingAndSpellings
.first
)),
4871 SupportedSpellings(std::move(HeadingAndSpellings
.second
)) {}
4874 static void WriteCategoryHeader(const Record
*DocCategory
,
4876 const StringRef Name
= DocCategory
->getValueAsString("Name");
4877 OS
<< Name
<< "\n" << std::string(Name
.size(), '=') << "\n";
4879 // If there is content, print that as well.
4880 const StringRef ContentStr
= DocCategory
->getValueAsString("Content");
4881 // Trim leading and trailing newlines and spaces.
4882 OS
<< ContentStr
.trim();
4887 static std::pair
<std::string
, SpellingList
>
4888 GetAttributeHeadingAndSpellings(const Record
&Documentation
,
4889 const Record
&Attribute
,
4891 // FIXME: there is no way to have a per-spelling category for the attribute
4892 // documentation. This may not be a limiting factor since the spellings
4893 // should generally be consistently applied across the category.
4895 std::vector
<FlattenedSpelling
> Spellings
= GetFlattenedSpellings(Attribute
);
4896 if (Spellings
.empty())
4897 PrintFatalError(Attribute
.getLoc(),
4898 "Attribute has no supported spellings; cannot be "
4901 // Determine the heading to be used for this attribute.
4902 std::string Heading
= std::string(Documentation
.getValueAsString("Heading"));
4903 if (Heading
.empty()) {
4904 // If there's only one spelling, we can simply use that.
4905 if (Spellings
.size() == 1)
4906 Heading
= Spellings
.begin()->name();
4908 std::set
<std::string
> Uniques
;
4909 for (auto I
= Spellings
.begin(), E
= Spellings
.end();
4911 std::string Spelling
=
4912 std::string(NormalizeNameForSpellingComparison(I
->name()));
4913 Uniques
.insert(Spelling
);
4915 // If the semantic map has only one spelling, that is sufficient for our
4917 if (Uniques
.size() == 1)
4918 Heading
= *Uniques
.begin();
4919 // If it's in the undocumented category, just construct a header by
4920 // concatenating all the spellings. Might not be great, but better than
4922 else if (Cat
== "Undocumented")
4923 Heading
= llvm::join(Uniques
.begin(), Uniques
.end(), ", ");
4927 // If the heading is still empty, it is an error.
4928 if (Heading
.empty())
4929 PrintFatalError(Attribute
.getLoc(),
4930 "This attribute requires a heading to be specified");
4932 SpellingList SupportedSpellings
;
4933 for (const auto &I
: Spellings
)
4934 SupportedSpellings
.add(Attribute
, I
);
4936 return std::make_pair(std::move(Heading
), std::move(SupportedSpellings
));
4939 static void WriteDocumentation(RecordKeeper
&Records
,
4940 const DocumentationData
&Doc
, raw_ostream
&OS
) {
4941 OS
<< Doc
.Heading
<< "\n" << std::string(Doc
.Heading
.length(), '-') << "\n";
4943 // List what spelling syntaxes the attribute supports.
4944 // Note: "#pragma clang attribute" is handled outside the spelling kinds loop
4945 // so it must be last.
4946 OS
<< ".. csv-table:: Supported Syntaxes\n";
4947 OS
<< " :header: \"GNU\", \"C++11\", \"C23\", \"``__declspec``\",";
4948 OS
<< " \"Keyword\", \"``#pragma``\", \"HLSL Semantic\", \"``#pragma clang ";
4949 OS
<< "attribute``\"\n\n \"";
4950 for (size_t Kind
= 0; Kind
!= NumSpellingKinds
; ++Kind
) {
4951 SpellingKind K
= (SpellingKind
)Kind
;
4952 // TODO: List Microsoft (IDL-style attribute) spellings once we fully
4954 if (K
== SpellingKind::Microsoft
)
4957 bool PrintedAny
= false;
4958 for (StringRef Spelling
: Doc
.SupportedSpellings
[K
]) {
4961 OS
<< "``" << Spelling
<< "``";
4968 if (getPragmaAttributeSupport(Records
).isAttributedSupported(
4973 // If the attribute is deprecated, print a message about it, and possibly
4974 // provide a replacement attribute.
4975 if (!Doc
.Documentation
->isValueUnset("Deprecated")) {
4976 OS
<< "This attribute has been deprecated, and may be removed in a future "
4977 << "version of Clang.";
4978 const Record
&Deprecated
= *Doc
.Documentation
->getValueAsDef("Deprecated");
4979 const StringRef Replacement
= Deprecated
.getValueAsString("Replacement");
4980 if (!Replacement
.empty())
4981 OS
<< " This attribute has been superseded by ``" << Replacement
4986 const StringRef ContentStr
= Doc
.Documentation
->getValueAsString("Content");
4987 // Trim leading and trailing newlines and spaces.
4988 OS
<< ContentStr
.trim();
4993 void EmitClangAttrDocs(RecordKeeper
&Records
, raw_ostream
&OS
) {
4994 // Get the documentation introduction paragraph.
4995 const Record
*Documentation
= Records
.getDef("GlobalDocumentation");
4996 if (!Documentation
) {
4997 PrintFatalError("The Documentation top-level definition is missing, "
4998 "no documentation will be generated.");
5002 OS
<< Documentation
->getValueAsString("Intro") << "\n";
5004 // Gather the Documentation lists from each of the attributes, based on the
5005 // category provided.
5006 std::vector
<Record
*> Attrs
= Records
.getAllDerivedDefinitions("Attr");
5007 struct CategoryLess
{
5008 bool operator()(const Record
*L
, const Record
*R
) const {
5009 return L
->getValueAsString("Name") < R
->getValueAsString("Name");
5012 std::map
<const Record
*, std::vector
<DocumentationData
>, CategoryLess
>
5014 for (const auto *A
: Attrs
) {
5015 const Record
&Attr
= *A
;
5016 std::vector
<Record
*> Docs
= Attr
.getValueAsListOfDefs("Documentation");
5017 for (const auto *D
: Docs
) {
5018 const Record
&Doc
= *D
;
5019 const Record
*Category
= Doc
.getValueAsDef("Category");
5020 // If the category is "InternalOnly", then there cannot be any other
5021 // documentation categories (otherwise, the attribute would be
5022 // emitted into the docs).
5023 const StringRef Cat
= Category
->getValueAsString("Name");
5024 bool InternalOnly
= Cat
== "InternalOnly";
5025 if (InternalOnly
&& Docs
.size() > 1)
5026 PrintFatalError(Doc
.getLoc(),
5027 "Attribute is \"InternalOnly\", but has multiple "
5028 "documentation categories");
5031 SplitDocs
[Category
].push_back(DocumentationData(
5032 Doc
, Attr
, GetAttributeHeadingAndSpellings(Doc
, Attr
, Cat
)));
5036 // Having split the attributes out based on what documentation goes where,
5037 // we can begin to generate sections of documentation.
5038 for (auto &I
: SplitDocs
) {
5039 WriteCategoryHeader(I
.first
, OS
);
5041 llvm::sort(I
.second
,
5042 [](const DocumentationData
&D1
, const DocumentationData
&D2
) {
5043 return D1
.Heading
< D2
.Heading
;
5046 // Walk over each of the attributes in the category and write out their
5048 for (const auto &Doc
: I
.second
)
5049 WriteDocumentation(Records
, Doc
, OS
);
5053 void EmitTestPragmaAttributeSupportedAttributes(RecordKeeper
&Records
,
5055 PragmaClangAttributeSupport Support
= getPragmaAttributeSupport(Records
);
5056 ParsedAttrMap Attrs
= getParsedAttrList(Records
);
5057 OS
<< "#pragma clang attribute supports the following attributes:\n";
5058 for (const auto &I
: Attrs
) {
5059 if (!Support
.isAttributedSupported(*I
.second
))
5062 if (I
.second
->isValueUnset("Subjects")) {
5066 const Record
*SubjectObj
= I
.second
->getValueAsDef("Subjects");
5067 std::vector
<Record
*> Subjects
=
5068 SubjectObj
->getValueAsListOfDefs("Subjects");
5070 bool PrintComma
= false;
5071 for (const auto &Subject
: llvm::enumerate(Subjects
)) {
5072 if (!isSupportedPragmaClangAttributeSubject(*Subject
.value()))
5077 PragmaClangAttributeSupport::RuleOrAggregateRuleSet
&RuleSet
=
5078 Support
.SubjectsToRules
.find(Subject
.value())->getSecond();
5079 if (RuleSet
.isRule()) {
5080 OS
<< RuleSet
.getRule().getEnumValueName();
5084 for (const auto &Rule
: llvm::enumerate(RuleSet
.getAggregateRuleSet())) {
5087 OS
<< Rule
.value().getEnumValueName();
5093 OS
<< "End of supported attributes.\n";
5096 } // end namespace clang