1//===-- ClangAttrEmitter.cpp - Generate Clang attribute handling ----------===//
2//
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
6//
7//===----------------------------------------------------------------------===//
8//
9// These tablegen backends emit Clang attribute processing code
10//
11//===----------------------------------------------------------------------===//
12
13#include "TableGenBackends.h"
14#include "ASTTableGen.h"
15
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/StringMap.h"
24#include "llvm/ADT/StringRef.h"
25#include "llvm/ADT/StringSwitch.h"
26#include "llvm/Support/ErrorHandling.h"
27#include "llvm/Support/raw_ostream.h"
28#include "llvm/TableGen/Error.h"
29#include "llvm/TableGen/Record.h"
30#include "llvm/TableGen/StringMatcher.h"
31#include "llvm/TableGen/TableGenBackend.h"
32#include <cassert>
33#include <cctype>
34#include <cstddef>
35#include <cstdint>
36#include <map>
37#include <memory>
38#include <optional>
39#include <set>
40#include <string>
41#include <utility>
42#include <vector>
43
44using namespace llvm;
45
46namespace {
47
48class FlattenedSpelling {
49 StringRef V, N, NS;
50 bool K = false;
51 const Record &OriginalSpelling;
52
53public:
54 FlattenedSpelling(StringRef Variety, StringRef Name, StringRef Namespace,
55 bool KnownToGCC, const Record &OriginalSpelling)
56 : V(Variety), N(Name), NS(Namespace), K(KnownToGCC),
57 OriginalSpelling(OriginalSpelling) {}
58 explicit FlattenedSpelling(const Record &Spelling)
59 : V(Spelling.getValueAsString(FieldName: "Variety")),
60 N(Spelling.getValueAsString(FieldName: "Name")), OriginalSpelling(Spelling) {
61 assert(V != "GCC" && V != "Clang" &&
62 "Given a GCC spelling, which means this hasn't been flattened!");
63 if (V == "CXX11" || V == "C23" || V == "Pragma")
64 NS = Spelling.getValueAsString(FieldName: "Namespace");
65 }
66
67 StringRef variety() const { return V; }
68 StringRef name() const { return N; }
69 StringRef nameSpace() const { return NS; }
70 bool knownToGCC() const { return K; }
71 const Record &getSpellingRecord() const { return OriginalSpelling; }
72};
73
74struct FlattenedSpellingInfo {
75 FlattenedSpellingInfo(StringRef Syntax, StringRef Scope,
76 const std::string &TargetTest, uint32_t ArgMask)
77 : Syntax(Syntax), Scope(Scope), TargetTest(TargetTest), ArgMask(ArgMask) {
78 }
79 StringRef Syntax;
80 StringRef Scope;
81 std::string TargetTest;
82 uint32_t ArgMask;
83};
84using FSIVecTy = std::vector<FlattenedSpellingInfo>;
85
86} // end anonymous namespace
87
88static bool GenerateTargetSpecificAttrChecks(const Record *R,
89 std::vector<StringRef> &Arches,
90 std::string &Test,
91 std::string *FnName);
92static bool isStringLiteralArgument(const Record *Arg);
93static bool isVariadicStringLiteralArgument(const Record *Arg);
94
95static std::vector<FlattenedSpelling>
96GetFlattenedSpellings(const Record &Attr) {
97 std::vector<FlattenedSpelling> Ret;
98
99 for (const auto &Spelling : Attr.getValueAsListOfDefs(FieldName: "Spellings")) {
100 StringRef Variety = Spelling->getValueAsString(FieldName: "Variety");
101 StringRef Name = Spelling->getValueAsString(FieldName: "Name");
102 if (Variety == "GCC") {
103 Ret.emplace_back(args: "GNU", args&: Name, args: "", args: true, args: *Spelling);
104 Ret.emplace_back(args: "CXX11", args&: Name, args: "gnu", args: true, args: *Spelling);
105 if (Spelling->getValueAsBit(FieldName: "AllowInC"))
106 Ret.emplace_back(args: "C23", args&: Name, args: "gnu", args: true, args: *Spelling);
107 } else if (Variety == "Clang") {
108 Ret.emplace_back(args: "GNU", args&: Name, args: "", args: false, args: *Spelling);
109 Ret.emplace_back(args: "CXX11", args&: Name, args: "clang", args: false, args: *Spelling);
110 if (Spelling->getValueAsBit(FieldName: "AllowInC"))
111 Ret.emplace_back(args: "C23", args&: Name, args: "clang", args: false, args: *Spelling);
112 } else if (Variety == "ClangGCC") {
113 Ret.emplace_back(args: "GNU", args&: Name, args: "", args: false, args: *Spelling);
114 Ret.emplace_back(args: "CXX11", args&: Name, args: "clang", args: false, args: *Spelling);
115 Ret.emplace_back(args: "CXX11", args&: Name, args: "gnu", args: false, args: *Spelling);
116 if (Spelling->getValueAsBit(FieldName: "AllowInC")) {
117 Ret.emplace_back(args: "C23", args&: Name, args: "clang", args: false, args: *Spelling);
118 Ret.emplace_back(args: "C23", args&: Name, args: "gnu", args: false, args: *Spelling);
119 }
120 } else {
121 Ret.push_back(x: FlattenedSpelling(*Spelling));
122 }
123 }
124
125 return Ret;
126}
127
128static std::string ReadPCHRecord(StringRef type) {
129 return StringSwitch<std::string>(type)
130 .EndsWith(S: "Decl *", Value: "Record.readDeclAs<" + type.drop_back().str() + ">()")
131 .Case(S: "TypeSourceInfo *", Value: "Record.readTypeSourceInfo()")
132 .Case(S: "Expr *", Value: "Record.readExpr()")
133 .Case(S: "const IdentifierInfo *", Value: "Record.readIdentifier()")
134 .Case(S: "StringRef", Value: "Record.readString()")
135 .Case(S: "ParamIdx", Value: "ParamIdx::deserialize(Record.readInt())")
136 .Case(S: "OMPTraitInfo *", Value: "Record.readOMPTraitInfo()")
137 .Default(Value: "Record.readInt()");
138}
139
140// Get a type that is suitable for storing an object of the specified type.
141static StringRef getStorageType(StringRef type) {
142 return StringSwitch<StringRef>(type)
143 .Case(S: "StringRef", Value: "std::string")
144 .Default(Value: type);
145}
146
147// Assumes that the way to get the value is SA->getname()
148static std::string WritePCHRecord(StringRef type, StringRef name) {
149 return "Record." +
150 StringSwitch<std::string>(type)
151 .EndsWith(S: "Decl *", Value: "AddDeclRef(" + name.str() + ");\n")
152 .Case(S: "TypeSourceInfo *",
153 Value: "AddTypeSourceInfo(" + name.str() + ");\n")
154 .Case(S: "Expr *", Value: "AddStmt(" + name.str() + ");\n")
155 .Case(S: "const IdentifierInfo *",
156 Value: "AddIdentifierRef(" + name.str() + ");\n")
157 .Case(S: "StringRef", Value: "AddString(" + name.str() + ");\n")
158 .Case(S: "ParamIdx", Value: "push_back(" + name.str() + ".serialize());\n")
159 .Case(S: "OMPTraitInfo *", Value: "writeOMPTraitInfo(" + name.str() + ");\n")
160 .Default(Value: "push_back(" + name.str() + ");\n");
161}
162
163// Normalize attribute name by removing leading and trailing
164// underscores. For example, __foo, foo__, __foo__ would
165// become foo.
166static StringRef NormalizeAttrName(StringRef AttrName) {
167 AttrName.consume_front(Prefix: "__");
168 AttrName.consume_back(Suffix: "__");
169 return AttrName;
170}
171
172// Normalize the name by removing any and all leading and trailing underscores.
173// This is different from NormalizeAttrName in that it also handles names like
174// _pascal and __pascal.
175static StringRef NormalizeNameForSpellingComparison(StringRef Name) {
176 return Name.trim(Chars: "_");
177}
178
179// Normalize the spelling of a GNU attribute (i.e. "x" in "__attribute__((x))"),
180// removing "__" if it appears at the beginning and end of the attribute's name.
181static StringRef NormalizeGNUAttrSpelling(StringRef AttrSpelling) {
182 if (AttrSpelling.starts_with(Prefix: "__") && AttrSpelling.ends_with(Suffix: "__")) {
183 AttrSpelling = AttrSpelling.substr(Start: 2, N: AttrSpelling.size() - 4);
184 }
185
186 return AttrSpelling;
187}
188
189typedef std::vector<std::pair<std::string, const Record *>> ParsedAttrMap;
190
191static ParsedAttrMap getParsedAttrList(const RecordKeeper &Records,
192 ParsedAttrMap *Dupes = nullptr,
193 bool SemaOnly = true) {
194 std::set<std::string> Seen;
195 ParsedAttrMap R;
196 for (const Record *Attr : Records.getAllDerivedDefinitions(ClassName: "Attr")) {
197 if (!SemaOnly || Attr->getValueAsBit(FieldName: "SemaHandler")) {
198 std::string AN;
199 if (Attr->isSubClassOf(Name: "TargetSpecificAttr") &&
200 !Attr->isValueUnset(FieldName: "ParseKind")) {
201 AN = Attr->getValueAsString(FieldName: "ParseKind").str();
202
203 // If this attribute has already been handled, it does not need to be
204 // handled again.
205 if (!Seen.insert(x: AN).second) {
206 if (Dupes)
207 Dupes->push_back(x: std::make_pair(x&: AN, y&: Attr));
208 continue;
209 }
210 } else
211 AN = NormalizeAttrName(AttrName: Attr->getName()).str();
212
213 R.push_back(x: std::make_pair(x&: AN, y&: Attr));
214 }
215 }
216 return R;
217}
218
219namespace {
220
221 class Argument {
222 std::string lowerName, upperName;
223 StringRef attrName;
224 bool isOpt;
225 bool Fake;
226
227 public:
228 Argument(StringRef Arg, StringRef Attr)
229 : lowerName(Arg.str()), upperName(lowerName), attrName(Attr),
230 isOpt(false), Fake(false) {
231 if (!lowerName.empty()) {
232 lowerName[0] = std::tolower(c: lowerName[0]);
233 upperName[0] = std::toupper(c: upperName[0]);
234 }
235 // Work around MinGW's macro definition of 'interface' to 'struct'. We
236 // have an attribute argument called 'Interface', so only the lower case
237 // name conflicts with the macro definition.
238 if (lowerName == "interface")
239 lowerName = "interface_";
240 }
241 Argument(const Record &Arg, StringRef Attr)
242 : Argument(Arg.getValueAsString(FieldName: "Name"), Attr) {}
243 virtual ~Argument() = default;
244
245 StringRef getLowerName() const { return lowerName; }
246 StringRef getUpperName() const { return upperName; }
247 StringRef getAttrName() const { return attrName; }
248
249 bool isOptional() const { return isOpt; }
250 void setOptional(bool set) { isOpt = set; }
251
252 bool isFake() const { return Fake; }
253 void setFake(bool fake) { Fake = fake; }
254
255 // These functions print the argument contents formatted in different ways.
256 virtual void writeAccessors(raw_ostream &OS) const = 0;
257 virtual void writeAccessorDefinitions(raw_ostream &OS) const {}
258 virtual void writeASTVisitorTraversal(raw_ostream &OS) const {}
259 virtual void writeCloneArgs(raw_ostream &OS) const = 0;
260 virtual void writeTemplateInstantiationArgs(raw_ostream &OS) const = 0;
261 virtual void writeTemplateInstantiation(raw_ostream &OS) const {}
262 virtual void writeCtorBody(raw_ostream &OS) const {}
263 virtual void writeCtorInitializers(raw_ostream &OS) const = 0;
264 virtual void writeCtorDefaultInitializers(raw_ostream &OS) const = 0;
265 virtual void writeCtorParameters(raw_ostream &OS) const = 0;
266 virtual void writeDeclarations(raw_ostream &OS) const = 0;
267 virtual void writePCHReadArgs(raw_ostream &OS) const = 0;
268 virtual void writePCHReadDecls(raw_ostream &OS) const = 0;
269 virtual void writePCHWrite(raw_ostream &OS) const = 0;
270 virtual std::string getIsOmitted() const { return "false"; }
271 virtual void writeValue(raw_ostream &OS) const = 0;
272 virtual void writeDump(raw_ostream &OS) const = 0;
273 virtual void writeDumpChildren(raw_ostream &OS) const {}
274 virtual void writeHasChildren(raw_ostream &OS) const { OS << "false"; }
275
276 virtual bool isEnumArg() const { return false; }
277 virtual bool isVariadicEnumArg() const { return false; }
278 virtual bool isVariadic() const { return false; }
279
280 virtual void writeImplicitCtorArgs(raw_ostream &OS) const {
281 OS << getUpperName();
282 }
283
284 constexpr StringRef getArgEqualityFn() const { return "equalAttrArgs"; }
285
286 virtual std::string emitAttrArgEqualityCheck() const {
287 std::string S = std::string("get") + std::string(getUpperName()) + "()";
288 return getArgEqualityFn().str() + "(" + S + ", Other." + S + ", Context)";
289 }
290
291 virtual std::string emitAttrArgProfileCall() const {
292 return "profileAttrArg(ID, Ctx, get" + getUpperName().str() + "())";
293 }
294 };
295
296 class SimpleArgument : public Argument {
297 std::string type;
298
299 public:
300 SimpleArgument(const Record &Arg, StringRef Attr, std::string T)
301 : Argument(Arg, Attr), type(std::move(T)) {}
302
303 std::string getType() const { return type; }
304
305 void writeAccessors(raw_ostream &OS) const override {
306 OS << " " << type << " get" << getUpperName() << "() const {\n";
307 OS << " return " << getLowerName() << ";\n";
308 OS << " }";
309 }
310
311 void writeCloneArgs(raw_ostream &OS) const override {
312 OS << getLowerName();
313 }
314
315 void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
316 OS << "A->get" << getUpperName() << "()";
317 }
318
319 void writeCtorInitializers(raw_ostream &OS) const override {
320 OS << getLowerName() << "(" << getUpperName() << ")";
321 }
322
323 void writeCtorDefaultInitializers(raw_ostream &OS) const override {
324 OS << getLowerName() << "()";
325 }
326
327 void writeCtorParameters(raw_ostream &OS) const override {
328 OS << type << " " << getUpperName();
329 }
330
331 void writeDeclarations(raw_ostream &OS) const override {
332 OS << type << " " << getLowerName() << ";";
333 }
334
335 void writePCHReadDecls(raw_ostream &OS) const override {
336 std::string read = ReadPCHRecord(type);
337 OS << " " << type << " " << getLowerName() << " = " << read << ";\n";
338 }
339
340 void writePCHReadArgs(raw_ostream &OS) const override {
341 OS << getLowerName();
342 }
343
344 void writePCHWrite(raw_ostream &OS) const override {
345 OS << " "
346 << WritePCHRecord(type, name: "SA->get" + getUpperName().str() + "()");
347 }
348
349 std::string getIsOmitted() const override {
350 auto IsOneOf = [](StringRef subject, auto... list) {
351 return ((subject == list) || ...);
352 };
353
354 if (IsOneOf(type, "const IdentifierInfo *", "Expr *"))
355 return "!get" + getUpperName().str() + "()";
356 if (IsOneOf(type, "TypeSourceInfo *"))
357 return "!get" + getUpperName().str() + "Loc()";
358 if (IsOneOf(type, "ParamIdx"))
359 return "!get" + getUpperName().str() + "().isValid()";
360
361 assert(IsOneOf(type, "unsigned", "int", "bool", "FunctionDecl *",
362 "VarDecl *"));
363 return "false";
364 }
365
366 void writeValue(raw_ostream &OS) const override {
367 if (type == "FunctionDecl *")
368 OS << "\" << get" << getUpperName()
369 << "()->getNameInfo().getAsString() << \"";
370 else if (type == "const IdentifierInfo *")
371 // Some non-optional (comma required) identifier arguments can be the
372 // empty string but are then recorded as a nullptr.
373 OS << "\" << (get" << getUpperName() << "() ? get" << getUpperName()
374 << "()->getName() : \"\") << \"";
375 else if (type == "VarDecl *")
376 OS << "\" << get" << getUpperName() << "()->getName() << \"";
377 else if (type == "TypeSourceInfo *")
378 OS << "\" << get" << getUpperName() << "().getAsString() << \"";
379 else if (type == "ParamIdx")
380 OS << "\" << get" << getUpperName() << "().getSourceIndex() << \"";
381 else
382 OS << "\" << get" << getUpperName() << "() << \"";
383 }
384
385 void writeDump(raw_ostream &OS) const override {
386 if (StringRef(type).ends_with(Suffix: "Decl *")) {
387 OS << " OS << \" \";\n";
388 OS << " dumpBareDeclRef(SA->get" << getUpperName() << "());\n";
389 } else if (type == "const IdentifierInfo *") {
390 // Some non-optional (comma required) identifier arguments can be the
391 // empty string but are then recorded as a nullptr.
392 OS << " if (SA->get" << getUpperName() << "())\n"
393 << " OS << \" \" << SA->get" << getUpperName()
394 << "()->getName();\n";
395 } else if (type == "TypeSourceInfo *") {
396 if (isOptional())
397 OS << " if (SA->get" << getUpperName() << "Loc())";
398 OS << " OS << \" \" << SA->get" << getUpperName()
399 << "().getAsString();\n";
400 } else if (type == "bool") {
401 OS << " if (SA->get" << getUpperName() << "()) OS << \" "
402 << getUpperName() << "\";\n";
403 } else if (type == "int" || type == "unsigned") {
404 OS << " OS << \" \" << SA->get" << getUpperName() << "();\n";
405 } else if (type == "ParamIdx") {
406 if (isOptional())
407 OS << " if (SA->get" << getUpperName() << "().isValid())\n ";
408 OS << " OS << \" \" << SA->get" << getUpperName()
409 << "().getSourceIndex();\n";
410 } else if (type == "OMPTraitInfo *") {
411 OS << " OS << \" \" << SA->get" << getUpperName() << "();\n";
412 } else {
413 llvm_unreachable("Unknown SimpleArgument type!");
414 }
415 }
416 };
417
418 class DefaultSimpleArgument : public SimpleArgument {
419 int64_t Default;
420
421 public:
422 DefaultSimpleArgument(const Record &Arg, StringRef Attr, std::string T,
423 int64_t Default)
424 : SimpleArgument(Arg, Attr, std::move(T)), Default(Default) {}
425
426 void writeAccessors(raw_ostream &OS) const override {
427 SimpleArgument::writeAccessors(OS);
428
429 OS << "\n\n static const " << getType() << " Default" << getUpperName()
430 << " = ";
431 if (getType() == "bool")
432 OS << (Default != 0 ? "true" : "false");
433 else
434 OS << Default;
435 OS << ";";
436 }
437 };
438
439 class StringArgument : public Argument {
440 public:
441 StringArgument(const Record &Arg, StringRef Attr)
442 : Argument(Arg, Attr)
443 {}
444
445 void writeAccessors(raw_ostream &OS) const override {
446 OS << " llvm::StringRef get" << getUpperName() << "() const {\n";
447 OS << " return llvm::StringRef(" << getLowerName() << ", "
448 << getLowerName() << "Length);\n";
449 OS << " }\n";
450 OS << " unsigned get" << getUpperName() << "Length() const {\n";
451 OS << " return " << getLowerName() << "Length;\n";
452 OS << " }\n";
453 OS << " void set" << getUpperName()
454 << "(ASTContext &C, llvm::StringRef S) {\n";
455 OS << " " << getLowerName() << "Length = S.size();\n";
456 OS << " this->" << getLowerName() << " = new (C, 1) char ["
457 << getLowerName() << "Length];\n";
458 OS << " if (!S.empty())\n";
459 OS << " std::memcpy(this->" << getLowerName() << ", S.data(), "
460 << getLowerName() << "Length);\n";
461 OS << " }";
462 }
463
464 void writeCloneArgs(raw_ostream &OS) const override {
465 OS << "get" << getUpperName() << "()";
466 }
467
468 void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
469 OS << "A->get" << getUpperName() << "()";
470 }
471
472 void writeCtorBody(raw_ostream &OS) const override {
473 OS << " if (!" << getUpperName() << ".empty())\n";
474 OS << " std::memcpy(" << getLowerName() << ", " << getUpperName()
475 << ".data(), " << getLowerName() << "Length);\n";
476 }
477
478 void writeCtorInitializers(raw_ostream &OS) const override {
479 OS << getLowerName() << "Length(" << getUpperName() << ".size()),"
480 << getLowerName() << "(new (Ctx, 1) char[" << getLowerName()
481 << "Length])";
482 }
483
484 void writeCtorDefaultInitializers(raw_ostream &OS) const override {
485 OS << getLowerName() << "Length(0)," << getLowerName() << "(nullptr)";
486 }
487
488 void writeCtorParameters(raw_ostream &OS) const override {
489 OS << "llvm::StringRef " << getUpperName();
490 }
491
492 void writeDeclarations(raw_ostream &OS) const override {
493 OS << "unsigned " << getLowerName() << "Length;\n";
494 OS << "char *" << getLowerName() << ";";
495 }
496
497 void writePCHReadDecls(raw_ostream &OS) const override {
498 OS << " std::string " << getLowerName()
499 << "= Record.readString();\n";
500 }
501
502 void writePCHReadArgs(raw_ostream &OS) const override {
503 OS << getLowerName();
504 }
505
506 void writePCHWrite(raw_ostream &OS) const override {
507 OS << " Record.AddString(SA->get" << getUpperName() << "());\n";
508 }
509
510 void writeValue(raw_ostream &OS) const override {
511 OS << "\\\"\" << get" << getUpperName() << "() << \"\\\"";
512 }
513
514 void writeDump(raw_ostream &OS) const override {
515 OS << " OS << \" \\\"\" << SA->get" << getUpperName()
516 << "() << \"\\\"\";\n";
517 }
518 };
519
520 class AlignedArgument : public Argument {
521 public:
522 AlignedArgument(const Record &Arg, StringRef Attr)
523 : Argument(Arg, Attr)
524 {}
525
526 void writeAccessors(raw_ostream &OS) const override {
527 OS << " bool is" << getUpperName() << "Dependent() const;\n";
528 OS << " bool is" << getUpperName() << "ErrorDependent() const;\n";
529
530 OS << " unsigned get" << getUpperName() << "(ASTContext &Ctx) const;\n";
531
532 OS << " bool is" << getUpperName() << "Expr() const {\n";
533 OS << " return is" << getLowerName() << "Expr;\n";
534 OS << " }\n";
535
536 OS << " Expr *get" << getUpperName() << "Expr() const {\n";
537 OS << " assert(is" << getLowerName() << "Expr);\n";
538 OS << " return " << getLowerName() << "Expr;\n";
539 OS << " }\n";
540
541 OS << " TypeSourceInfo *get" << getUpperName() << "Type() const {\n";
542 OS << " assert(!is" << getLowerName() << "Expr);\n";
543 OS << " return " << getLowerName() << "Type;\n";
544 OS << " }";
545
546 OS << " std::optional<unsigned> getCached" << getUpperName()
547 << "Value() const {\n";
548 OS << " return " << getLowerName() << "Cache;\n";
549 OS << " }";
550
551 OS << " void setCached" << getUpperName()
552 << "Value(unsigned AlignVal) {\n";
553 OS << " " << getLowerName() << "Cache = AlignVal;\n";
554 OS << " }";
555 }
556
557 void writeAccessorDefinitions(raw_ostream &OS) const override {
558 OS << "bool " << getAttrName() << "Attr::is" << getUpperName()
559 << "Dependent() const {\n";
560 OS << " if (is" << getLowerName() << "Expr)\n";
561 OS << " return " << getLowerName() << "Expr && (" << getLowerName()
562 << "Expr->isValueDependent() || " << getLowerName()
563 << "Expr->isTypeDependent());\n";
564 OS << " else\n";
565 OS << " return " << getLowerName()
566 << "Type->getType()->isDependentType();\n";
567 OS << "}\n";
568
569 OS << "bool " << getAttrName() << "Attr::is" << getUpperName()
570 << "ErrorDependent() const {\n";
571 OS << " if (is" << getLowerName() << "Expr)\n";
572 OS << " return " << getLowerName() << "Expr && " << getLowerName()
573 << "Expr->containsErrors();\n";
574 OS << " return " << getLowerName()
575 << "Type->getType()->containsErrors();\n";
576 OS << "}\n";
577 }
578
579 void writeASTVisitorTraversal(raw_ostream &OS) const override {
580 StringRef Name = getUpperName();
581 OS << " if (A->is" << Name << "Expr()) {\n"
582 << " if (!getDerived().TraverseStmt(A->get" << Name << "Expr()))\n"
583 << " return false;\n"
584 << " } else if (auto *TSI = A->get" << Name << "Type()) {\n"
585 << " if (!getDerived().TraverseTypeLoc(TSI->getTypeLoc()))\n"
586 << " return false;\n"
587 << " }\n";
588 }
589
590 void writeCloneArgs(raw_ostream &OS) const override {
591 OS << "is" << getLowerName() << "Expr, is" << getLowerName()
592 << "Expr ? static_cast<void*>(" << getLowerName()
593 << "Expr) : " << getLowerName()
594 << "Type";
595 }
596
597 void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
598 // FIXME: move the definition in Sema::InstantiateAttrs to here.
599 // In the meantime, aligned attributes are cloned.
600 }
601
602 void writeCtorBody(raw_ostream &OS) const override {
603 OS << " if (is" << getLowerName() << "Expr)\n";
604 OS << " " << getLowerName() << "Expr = reinterpret_cast<Expr *>("
605 << getUpperName() << ");\n";
606 OS << " else\n";
607 OS << " " << getLowerName()
608 << "Type = reinterpret_cast<TypeSourceInfo *>(" << getUpperName()
609 << ");\n";
610 }
611
612 void writeCtorInitializers(raw_ostream &OS) const override {
613 OS << "is" << getLowerName() << "Expr(Is" << getUpperName() << "Expr)";
614 }
615
616 void writeCtorDefaultInitializers(raw_ostream &OS) const override {
617 OS << "is" << getLowerName() << "Expr(false)";
618 }
619
620 void writeCtorParameters(raw_ostream &OS) const override {
621 OS << "bool Is" << getUpperName() << "Expr, void *" << getUpperName();
622 }
623
624 void writeImplicitCtorArgs(raw_ostream &OS) const override {
625 OS << "Is" << getUpperName() << "Expr, " << getUpperName();
626 }
627
628 void writeDeclarations(raw_ostream &OS) const override {
629 OS << "bool is" << getLowerName() << "Expr;\n";
630 OS << "union {\n";
631 OS << "Expr *" << getLowerName() << "Expr;\n";
632 OS << "TypeSourceInfo *" << getLowerName() << "Type;\n";
633 OS << "};\n";
634 OS << "std::optional<unsigned> " << getLowerName() << "Cache;\n";
635 }
636
637 void writePCHReadArgs(raw_ostream &OS) const override {
638 OS << "is" << getLowerName() << "Expr, " << getLowerName() << "Ptr";
639 }
640
641 void writePCHReadDecls(raw_ostream &OS) const override {
642 OS << " bool is" << getLowerName() << "Expr = Record.readInt();\n";
643 OS << " void *" << getLowerName() << "Ptr;\n";
644 OS << " if (is" << getLowerName() << "Expr)\n";
645 OS << " " << getLowerName() << "Ptr = Record.readExpr();\n";
646 OS << " else\n";
647 OS << " " << getLowerName()
648 << "Ptr = Record.readTypeSourceInfo();\n";
649 }
650
651 void writePCHWrite(raw_ostream &OS) const override {
652 OS << " Record.push_back(SA->is" << getUpperName() << "Expr());\n";
653 OS << " if (SA->is" << getUpperName() << "Expr())\n";
654 OS << " Record.AddStmt(SA->get" << getUpperName() << "Expr());\n";
655 OS << " else\n";
656 OS << " Record.AddTypeSourceInfo(SA->get" << getUpperName()
657 << "Type());\n";
658 }
659
660 std::string getIsOmitted() const override {
661 return "!((is" + getLowerName().str() + "Expr && " +
662 getLowerName().str() + "Expr) || (!is" + getLowerName().str() +
663 "Expr && " + getLowerName().str() + "Type))";
664 }
665
666 void writeValue(raw_ostream &OS) const override {
667 OS << "\";\n";
668 OS << " if (is" << getLowerName() << "Expr && " << getLowerName()
669 << "Expr)";
670 OS << " " << getLowerName()
671 << "Expr->printPretty(OS, nullptr, Policy);\n";
672 OS << " if (!is" << getLowerName() << "Expr && " << getLowerName()
673 << "Type)";
674 OS << " " << getLowerName()
675 << "Type->getType().print(OS, Policy);\n";
676 OS << " OS << \"";
677 }
678
679 void writeDump(raw_ostream &OS) const override {
680 OS << " if (!SA->is" << getUpperName() << "Expr())\n";
681 OS << " dumpType(SA->get" << getUpperName()
682 << "Type()->getType());\n";
683 }
684
685 void writeDumpChildren(raw_ostream &OS) const override {
686 OS << " if (SA->is" << getUpperName() << "Expr())\n";
687 OS << " Visit(SA->get" << getUpperName() << "Expr());\n";
688 }
689
690 void writeHasChildren(raw_ostream &OS) const override {
691 OS << "SA->is" << getUpperName() << "Expr()";
692 }
693
694 std::string emitAttrArgEqualityCheck() const override {
695 auto GetStr = [&](bool Other) {
696 std::string CtxStr = Other ? "Context.ToCtx" : "Context.FromCtx";
697 std::string S = std::string("get") + std::string(getUpperName()) + "(" +
698 CtxStr + ")";
699 return S;
700 };
701 return getArgEqualityFn().str() + "(" + GetStr(false) + ", Other." +
702 GetStr(true) + ", Context)";
703 }
704 };
705
706 class VariadicArgument : public Argument {
707 std::string Type, ArgName, ArgSizeName, RangeName;
708
709 protected:
710 // Assumed to receive a parameter: raw_ostream OS.
711 virtual void writeValueImpl(raw_ostream &OS) const {
712 OS << " OS << Val;\n";
713 }
714 // Assumed to receive a parameter: raw_ostream OS.
715 virtual void writeDumpImpl(raw_ostream &OS) const {
716 OS << " OS << \" \" << Val;\n";
717 }
718
719 public:
720 VariadicArgument(const Record &Arg, StringRef Attr, std::string T)
721 : Argument(Arg, Attr), Type(std::move(T)),
722 ArgName(getLowerName().str() + "_"), ArgSizeName(ArgName + "Size"),
723 RangeName(getLowerName().str()) {}
724
725 VariadicArgument(StringRef Arg, StringRef Attr, std::string T)
726 : Argument(Arg, Attr), Type(std::move(T)),
727 ArgName(getLowerName().str() + "_"), ArgSizeName(ArgName + "Size"),
728 RangeName(getLowerName().str()) {}
729
730 const std::string &getType() const { return Type; }
731 const std::string &getArgName() const { return ArgName; }
732 const std::string &getArgSizeName() const { return ArgSizeName; }
733 bool isVariadic() const override { return true; }
734
735 void writeAccessors(raw_ostream &OS) const override {
736 std::string IteratorType = getLowerName().str() + "_iterator";
737 std::string BeginFn = getLowerName().str() + "_begin()";
738 std::string EndFn = getLowerName().str() + "_end()";
739
740 OS << " typedef " << Type << "* " << IteratorType << ";\n";
741 OS << " " << IteratorType << " " << BeginFn << " const {"
742 << " return " << ArgName << "; }\n";
743 OS << " " << IteratorType << " " << EndFn << " const {"
744 << " return " << ArgName << " + " << ArgSizeName << "; }\n";
745 OS << " unsigned " << getLowerName() << "_size() const {"
746 << " return " << ArgSizeName << "; }\n";
747 OS << " llvm::iterator_range<" << IteratorType << "> " << RangeName
748 << "() const { return llvm::make_range(" << BeginFn << ", " << EndFn
749 << "); }\n";
750 }
751
752 void writeSetter(raw_ostream &OS) const {
753 OS << " void set" << getUpperName() << "(ASTContext &Ctx, ";
754 writeCtorParameters(OS);
755 OS << ") {\n";
756 OS << " " << ArgSizeName << " = " << getUpperName() << "Size;\n";
757 OS << " " << ArgName << " = new (Ctx, 16) " << getType() << "["
758 << ArgSizeName << "];\n";
759 OS << " ";
760 writeCtorBody(OS);
761 OS << " }\n";
762 }
763
764 void writeCloneArgs(raw_ostream &OS) const override {
765 OS << ArgName << ", " << ArgSizeName;
766 }
767
768 void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
769 // This isn't elegant, but we have to go through public methods...
770 OS << "A->" << getLowerName() << "_begin(), "
771 << "A->" << getLowerName() << "_size()";
772 }
773
774 void writeASTVisitorTraversal(raw_ostream &OS) const override {
775 // FIXME: Traverse the elements.
776 }
777
778 void writeCtorBody(raw_ostream &OS) const override {
779 OS << " std::copy(" << getUpperName() << ", " << getUpperName() << " + "
780 << ArgSizeName << ", " << ArgName << ");\n";
781 }
782
783 void writeCtorInitializers(raw_ostream &OS) const override {
784 OS << ArgSizeName << "(" << getUpperName() << "Size), "
785 << ArgName << "(new (Ctx, 16) " << getType() << "["
786 << ArgSizeName << "])";
787 }
788
789 void writeCtorDefaultInitializers(raw_ostream &OS) const override {
790 OS << ArgSizeName << "(0), " << ArgName << "(nullptr)";
791 }
792
793 void writeCtorParameters(raw_ostream &OS) const override {
794 OS << getType() << " *" << getUpperName() << ", unsigned "
795 << getUpperName() << "Size";
796 }
797
798 void writeImplicitCtorArgs(raw_ostream &OS) const override {
799 OS << getUpperName() << ", " << getUpperName() << "Size";
800 }
801
802 void writeDeclarations(raw_ostream &OS) const override {
803 OS << " unsigned " << ArgSizeName << ";\n";
804 OS << " " << getType() << " *" << ArgName << ";";
805 }
806
807 void writePCHReadDecls(raw_ostream &OS) const override {
808 OS << " unsigned " << getLowerName() << "Size = Record.readInt();\n";
809 OS << " SmallVector<" << getType() << ", 4> "
810 << getLowerName() << ";\n";
811 OS << " " << getLowerName() << ".reserve(" << getLowerName()
812 << "Size);\n";
813
814 // If we can't store the values in the current type (if it's something
815 // like StringRef), store them in a different type and convert the
816 // container afterwards.
817 std::string StorageType = getStorageType(type: getType()).str();
818 std::string StorageName = getLowerName().str();
819 if (StorageType != getType()) {
820 StorageName += "Storage";
821 OS << " SmallVector<" << StorageType << ", 4> "
822 << StorageName << ";\n";
823 OS << " " << StorageName << ".reserve(" << getLowerName()
824 << "Size);\n";
825 }
826
827 OS << " for (unsigned i = 0; i != " << getLowerName() << "Size; ++i)\n";
828 std::string read = ReadPCHRecord(type: Type);
829 OS << " " << StorageName << ".push_back(" << read << ");\n";
830
831 if (StorageType != getType()) {
832 OS << " for (unsigned i = 0; i != " << getLowerName() << "Size; ++i)\n";
833 OS << " " << getLowerName() << ".push_back("
834 << StorageName << "[i]);\n";
835 }
836 }
837
838 void writePCHReadArgs(raw_ostream &OS) const override {
839 OS << getLowerName() << ".data(), " << getLowerName() << "Size";
840 }
841
842 void writePCHWrite(raw_ostream &OS) const override {
843 OS << " Record.push_back(SA->" << getLowerName() << "_size());\n";
844 OS << " for (auto &Val : SA->" << RangeName << "())\n";
845 OS << " " << WritePCHRecord(type: Type, name: "Val");
846 }
847
848 void writeValue(raw_ostream &OS) const override {
849 OS << "\";\n";
850 OS << " for (const auto &Val : " << RangeName << "()) {\n"
851 << " DelimitAttributeArgument(OS, IsFirstArgument);\n";
852 writeValueImpl(OS);
853 OS << " }\n";
854 OS << " OS << \"";
855 }
856
857 void writeDump(raw_ostream &OS) const override {
858 OS << " for (const auto &Val : SA->" << RangeName << "())\n";
859 writeDumpImpl(OS);
860 }
861
862 std::string emitAttrArgEqualityCheck() const override {
863 auto GenIter = [&](bool IsOther, const std::string &Suffix) {
864 std::string S = IsOther ? "Other." : "";
865 std::string LN = getLowerName().str();
866 S += LN + "_" + Suffix + "()";
867 return S;
868 };
869
870 return getArgEqualityFn().str() + "(" + GenIter(false, "begin") + ", " +
871 GenIter(false, "end") + ", " + GenIter(true, "begin") + ", " +
872 GenIter(true, "end") + ", Context)";
873 }
874
875 std::string emitAttrArgProfileCall() const override {
876 std::string LN = getLowerName().str();
877 return "profileAttrArg(ID, Ctx, " + LN + "_begin(), " + LN + "_end())";
878 }
879 };
880
881 class VariadicOMPInteropInfoArgument : public VariadicArgument {
882 public:
883 VariadicOMPInteropInfoArgument(const Record &Arg, StringRef Attr)
884 : VariadicArgument(Arg, Attr, "OMPInteropInfo") {}
885
886 void writeDump(raw_ostream &OS) const override {
887 OS << " for (" << getAttrName() << "Attr::" << getLowerName()
888 << "_iterator I = SA->" << getLowerName() << "_begin(), E = SA->"
889 << getLowerName() << "_end(); I != E; ++I) {\n";
890 OS << " if (I->IsTarget && I->IsTargetSync)\n";
891 OS << " OS << \" Target_TargetSync\";\n";
892 OS << " else if (I->IsTarget)\n";
893 OS << " OS << \" Target\";\n";
894 OS << " else\n";
895 OS << " OS << \" TargetSync\";\n";
896 OS << " }\n";
897 }
898
899 void writePCHReadDecls(raw_ostream &OS) const override {
900 OS << " unsigned " << getLowerName() << "Size = Record.readInt();\n";
901 OS << " SmallVector<OMPInteropInfo, 4> " << getLowerName() << ";\n";
902 OS << " " << getLowerName() << ".reserve(" << getLowerName()
903 << "Size);\n";
904 OS << " for (unsigned I = 0, E = " << getLowerName() << "Size; ";
905 OS << "I != E; ++I) {\n";
906 OS << " bool IsTarget = Record.readBool();\n";
907 OS << " bool IsTargetSync = Record.readBool();\n";
908 OS << " OMPInteropInfo Info(IsTarget, IsTargetSync);\n";
909 OS << " Info.HasPreferAttrs = Record.readBool();\n";
910 OS << " unsigned prefsSize = Record.readInt();\n";
911 OS << " Info.Prefs.reserve(prefsSize);\n";
912 OS << " for (unsigned J = 0; J < prefsSize; ++J) {\n";
913 OS << " bool hasFr = Record.readBool();\n";
914 OS << " Expr *Fr = hasFr ? Record.readExpr() : nullptr;\n";
915 OS << " unsigned attrsSize = Record.readInt();\n";
916 OS << " llvm::SmallVector<Expr *, 2> Attrs;\n";
917 OS << " Attrs.reserve(attrsSize);\n";
918 OS << " for (unsigned K = 0; K < attrsSize; ++K)\n";
919 OS << " Attrs.push_back(Record.readExpr());\n";
920 OS << " Info.Prefs.emplace_back(Fr, std::move(Attrs));\n";
921 OS << " }\n";
922 OS << " " << getLowerName() << ".push_back(Info);\n";
923 OS << " }\n";
924 }
925
926 void writePCHWrite(raw_ostream &OS) const override {
927 OS << " Record.push_back(SA->" << getLowerName() << "_size());\n";
928 OS << " for (" << getAttrName() << "Attr::" << getLowerName()
929 << "_iterator I = SA->" << getLowerName() << "_begin(), E = SA->"
930 << getLowerName() << "_end(); I != E; ++I) {\n";
931 OS << " Record.writeBool(I->IsTarget);\n";
932 OS << " Record.writeBool(I->IsTargetSync);\n";
933 OS << " Record.writeBool(I->HasPreferAttrs);\n";
934 OS << " Record.push_back(I->Prefs.size());\n";
935 OS << " for (auto &P : I->Prefs) {\n";
936 OS << " Record.writeBool(P.Fr != nullptr);\n";
937 OS << " if (P.Fr) Record.AddStmt(P.Fr);\n";
938 OS << " Record.push_back(P.Attrs.size());\n";
939 OS << " for (Expr *A : P.Attrs) Record.AddStmt(A);\n";
940 OS << " }\n";
941 OS << " }\n";
942 }
943
944 void writeASTVisitorTraversal(raw_ostream &OS) const override {
945 OS << " {\n";
946 OS << " OMPInteropInfo *I = A->" << getLowerName() << "_begin();\n";
947 OS << " " << getType() << " *E = A->" << getLowerName() << "_end();\n";
948 OS << " for (; I != E; ++I) {\n";
949 OS << " for (auto &P : I->Prefs) {\n";
950 OS << " if (P.Fr && !getDerived().TraverseStmt(P.Fr))\n";
951 OS << " return false;\n";
952 OS << " for (Expr *A : P.Attrs)\n";
953 OS << " if (!getDerived().TraverseStmt(A))\n";
954 OS << " return false;\n";
955 OS << " }\n";
956 OS << " }\n";
957 OS << " }\n";
958 }
959
960 void writeDumpChildren(raw_ostream &OS) const override {
961 OS << " for (" << getAttrName() << "Attr::" << getLowerName()
962 << "_iterator I = SA->" << getLowerName() << "_begin(), E = SA->"
963 << getLowerName() << "_end(); I != E; ++I) {\n";
964 OS << " for (auto &P : I->Prefs) {\n";
965 OS << " if (P.Fr) Visit(P.Fr);\n";
966 OS << " for (Expr *A : P.Attrs) Visit(A);\n";
967 OS << " }\n";
968 OS << " }\n";
969 }
970 };
971
972 class VariadicParamIdxArgument : public VariadicArgument {
973 public:
974 VariadicParamIdxArgument(const Record &Arg, StringRef Attr)
975 : VariadicArgument(Arg, Attr, "ParamIdx") {}
976
977 public:
978 void writeValueImpl(raw_ostream &OS) const override {
979 OS << " OS << Val.getSourceIndex();\n";
980 }
981
982 void writeDumpImpl(raw_ostream &OS) const override {
983 OS << " OS << \" \" << Val.getSourceIndex();\n";
984 }
985 };
986
987 struct VariadicParamOrParamIdxArgument : public VariadicArgument {
988 VariadicParamOrParamIdxArgument(const Record &Arg, StringRef Attr)
989 : VariadicArgument(Arg, Attr, "int") {}
990 };
991
992 // Unique the enums, but maintain the original declaration ordering.
993 std::vector<StringRef>
994 uniqueEnumsInOrder(const std::vector<StringRef> &enums) {
995 std::vector<StringRef> uniques;
996 SmallDenseSet<StringRef, 8> unique_set;
997 for (const auto &i : enums) {
998 if (unique_set.insert(V: i).second)
999 uniques.push_back(x: i);
1000 }
1001 return uniques;
1002 }
1003
1004 class EnumArgument : public Argument {
1005 std::string fullType;
1006 StringRef shortType;
1007 std::vector<StringRef> values, enums, uniques;
1008 bool isExternal;
1009 bool isCovered;
1010
1011 public:
1012 EnumArgument(const Record &Arg, StringRef Attr)
1013 : Argument(Arg, Attr), values(Arg.getValueAsListOfStrings(FieldName: "Values")),
1014 enums(Arg.getValueAsListOfStrings(FieldName: "Enums")),
1015 uniques(uniqueEnumsInOrder(enums)),
1016 isExternal(Arg.getValueAsBit(FieldName: "IsExternalType")),
1017 isCovered(Arg.getValueAsBit(FieldName: "IsCovered")) {
1018 StringRef Type = Arg.getValueAsString(FieldName: "Type");
1019 shortType = isExternal ? Type.rsplit(Separator: "::").second : Type;
1020 // If shortType didn't contain :: at all rsplit will give us an empty
1021 // string.
1022 if (shortType.empty())
1023 shortType = Type;
1024 fullType = isExternal ? Type : (getAttrName() + "Attr::" + Type).str();
1025
1026 // FIXME: Emit a proper error
1027 assert(!uniques.empty());
1028 }
1029
1030 bool isEnumArg() const override { return true; }
1031
1032 void writeAccessors(raw_ostream &OS) const override {
1033 OS << " " << fullType << " get" << getUpperName() << "() const {\n";
1034 OS << " return " << getLowerName() << ";\n";
1035 OS << " }";
1036 }
1037
1038 void writeCloneArgs(raw_ostream &OS) const override {
1039 OS << getLowerName();
1040 }
1041
1042 void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
1043 OS << "A->get" << getUpperName() << "()";
1044 }
1045 void writeCtorInitializers(raw_ostream &OS) const override {
1046 OS << getLowerName() << "(" << getUpperName() << ")";
1047 }
1048 void writeCtorDefaultInitializers(raw_ostream &OS) const override {
1049 OS << getLowerName() << "(" << fullType << "(0))";
1050 }
1051 void writeCtorParameters(raw_ostream &OS) const override {
1052 OS << fullType << " " << getUpperName();
1053 }
1054 void writeDeclarations(raw_ostream &OS) const override {
1055 if (!isExternal) {
1056 auto i = uniques.cbegin(), e = uniques.cend();
1057 // The last one needs to not have a comma.
1058 --e;
1059
1060 OS << "public:\n";
1061 OS << " enum " << shortType << " {\n";
1062 for (; i != e; ++i)
1063 OS << " " << *i << ",\n";
1064 OS << " " << *e << "\n";
1065 OS << " };\n";
1066 }
1067
1068 OS << "private:\n";
1069 OS << " " << fullType << " " << getLowerName() << ";";
1070 }
1071
1072 void writePCHReadDecls(raw_ostream &OS) const override {
1073 OS << " " << fullType << " " << getLowerName() << "(static_cast<"
1074 << fullType << ">(Record.readInt()));\n";
1075 }
1076
1077 void writePCHReadArgs(raw_ostream &OS) const override {
1078 OS << getLowerName();
1079 }
1080
1081 void writePCHWrite(raw_ostream &OS) const override {
1082 OS << "Record.push_back(static_cast<uint64_t>(SA->get" << getUpperName()
1083 << "()));\n";
1084 }
1085
1086 void writeValue(raw_ostream &OS) const override {
1087 // FIXME: this isn't 100% correct -- some enum arguments require printing
1088 // as a string literal, while others require printing as an identifier.
1089 // Tablegen currently does not distinguish between the two forms.
1090 OS << "\\\"\" << " << getAttrName() << "Attr::Convert" << shortType
1091 << "ToStr(get" << getUpperName() << "()) << \"\\\"";
1092 }
1093
1094 void writeDump(raw_ostream &OS) const override {
1095 OS << " switch(SA->get" << getUpperName() << "()) {\n";
1096 for (const auto &I : uniques) {
1097 OS << " case " << fullType << "::" << I << ":\n";
1098 OS << " OS << \" " << I << "\";\n";
1099 OS << " break;\n";
1100 }
1101 if (!isCovered) {
1102 OS << " default:\n";
1103 OS << " llvm_unreachable(\"Invalid attribute value\");\n";
1104 }
1105 OS << " }\n";
1106 }
1107
1108 void writeConversion(raw_ostream &OS, bool Header) const {
1109 if (Header) {
1110 OS << " static bool ConvertStrTo" << shortType << "(StringRef Val, "
1111 << fullType << " &Out);\n";
1112 OS << " static const char *Convert" << shortType << "ToStr("
1113 << fullType << " Val);\n";
1114 return;
1115 }
1116
1117 OS << "bool " << getAttrName() << "Attr::ConvertStrTo" << shortType
1118 << "(StringRef Val, " << fullType << " &Out) {\n";
1119 OS << " std::optional<" << fullType << "> "
1120 << "R = llvm::StringSwitch<std::optional<" << fullType << ">>(Val)\n";
1121 for (size_t I = 0; I < enums.size(); ++I) {
1122 OS << " .Case(\"" << values[I] << "\", ";
1123 OS << fullType << "::" << enums[I] << ")\n";
1124 }
1125 OS << " .Default(std::optional<" << fullType << ">());\n";
1126 OS << " if (R) {\n";
1127 OS << " Out = *R;\n return true;\n }\n";
1128 OS << " return false;\n";
1129 OS << "}\n\n";
1130
1131 // Mapping from enumeration values back to enumeration strings isn't
1132 // trivial because some enumeration values have multiple named
1133 // enumerators, such as type_visibility(internal) and
1134 // type_visibility(hidden) both mapping to TypeVisibilityAttr::Hidden.
1135 OS << "const char *" << getAttrName() << "Attr::Convert" << shortType
1136 << "ToStr(" << fullType << " Val) {\n"
1137 << " switch(Val) {\n";
1138 SmallDenseSet<StringRef, 8> Uniques;
1139 for (size_t I = 0; I < enums.size(); ++I) {
1140 if (Uniques.insert(V: enums[I]).second)
1141 OS << " case " << fullType << "::" << enums[I] << ": return \""
1142 << values[I] << "\";\n";
1143 }
1144 if (!isCovered) {
1145 OS << " default: llvm_unreachable(\"Invalid attribute value\");\n";
1146 }
1147 OS << " }\n"
1148 << " llvm_unreachable(\"No enumerator with that value\");\n"
1149 << "}\n";
1150 }
1151 };
1152
1153 class VariadicEnumArgument: public VariadicArgument {
1154 std::string fullType;
1155 StringRef shortType;
1156 std::vector<StringRef> values, enums, uniques;
1157 bool isExternal;
1158 bool isCovered;
1159
1160 protected:
1161 void writeValueImpl(raw_ostream &OS) const override {
1162 // FIXME: this isn't 100% correct -- some enum arguments require printing
1163 // as a string literal, while others require printing as an identifier.
1164 // Tablegen currently does not distinguish between the two forms.
1165 OS << " OS << \"\\\"\" << " << getAttrName() << "Attr::Convert"
1166 << shortType << "ToStr(Val)"
1167 << "<< \"\\\"\";\n";
1168 }
1169
1170 public:
1171 VariadicEnumArgument(const Record &Arg, StringRef Attr)
1172 : VariadicArgument(Arg, Attr, Arg.getValueAsString(FieldName: "Type").str()),
1173 values(Arg.getValueAsListOfStrings(FieldName: "Values")),
1174 enums(Arg.getValueAsListOfStrings(FieldName: "Enums")),
1175 uniques(uniqueEnumsInOrder(enums)),
1176 isExternal(Arg.getValueAsBit(FieldName: "IsExternalType")),
1177 isCovered(Arg.getValueAsBit(FieldName: "IsCovered")) {
1178 StringRef Type = Arg.getValueAsString(FieldName: "Type");
1179 shortType = isExternal ? Type.rsplit(Separator: "::").second : Type;
1180 // If shortType didn't contain :: at all rsplit will give us an empty
1181 // string.
1182 if (shortType.empty())
1183 shortType = Type;
1184 fullType = isExternal ? Type : (getAttrName() + "Attr::" + Type).str();
1185
1186 // FIXME: Emit a proper error
1187 assert(!uniques.empty());
1188 }
1189
1190 bool isVariadicEnumArg() const override { return true; }
1191
1192 void writeDeclarations(raw_ostream &OS) const override {
1193 if (!isExternal) {
1194 auto i = uniques.cbegin(), e = uniques.cend();
1195 // The last one needs to not have a comma.
1196 --e;
1197
1198 OS << "public:\n";
1199 OS << " enum " << shortType << " {\n";
1200 for (; i != e; ++i)
1201 OS << " " << *i << ",\n";
1202 OS << " " << *e << "\n";
1203 OS << " };\n";
1204 }
1205 OS << "private:\n";
1206
1207 VariadicArgument::writeDeclarations(OS);
1208 }
1209
1210 void writeDump(raw_ostream &OS) const override {
1211 OS << " for (" << getAttrName() << "Attr::" << getLowerName()
1212 << "_iterator I = SA->" << getLowerName() << "_begin(), E = SA->"
1213 << getLowerName() << "_end(); I != E; ++I) {\n";
1214 OS << " switch(*I) {\n";
1215 for (const auto &UI : uniques) {
1216 OS << " case " << fullType << "::" << UI << ":\n";
1217 OS << " OS << \" " << UI << "\";\n";
1218 OS << " break;\n";
1219 }
1220 if (!isCovered) {
1221 OS << " default:\n";
1222 OS << " llvm_unreachable(\"Invalid attribute value\");\n";
1223 }
1224 OS << " }\n";
1225 OS << " }\n";
1226 }
1227
1228 void writePCHReadDecls(raw_ostream &OS) const override {
1229 OS << " unsigned " << getLowerName() << "Size = Record.readInt();\n";
1230 OS << " SmallVector<" << fullType << ", 4> " << getLowerName()
1231 << ";\n";
1232 OS << " " << getLowerName() << ".reserve(" << getLowerName()
1233 << "Size);\n";
1234 OS << " for (unsigned i = " << getLowerName() << "Size; i; --i)\n";
1235 OS << " " << getLowerName() << ".push_back("
1236 << "static_cast<" << fullType << ">(Record.readInt()));\n";
1237 }
1238
1239 void writePCHWrite(raw_ostream &OS) const override {
1240 OS << " Record.push_back(SA->" << getLowerName() << "_size());\n";
1241 OS << " for (" << getAttrName() << "Attr::" << getLowerName()
1242 << "_iterator i = SA->" << getLowerName() << "_begin(), e = SA->"
1243 << getLowerName() << "_end(); i != e; ++i)\n";
1244 OS << " " << WritePCHRecord(type: fullType, name: "(*i)");
1245 }
1246
1247 void writeConversion(raw_ostream &OS, bool Header) const {
1248 if (Header) {
1249 OS << " static bool ConvertStrTo" << shortType << "(StringRef Val, "
1250 << fullType << " &Out);\n";
1251 OS << " static const char *Convert" << shortType << "ToStr("
1252 << fullType << " Val);\n";
1253 return;
1254 }
1255
1256 OS << "bool " << getAttrName() << "Attr::ConvertStrTo" << shortType
1257 << "(StringRef Val, ";
1258 OS << fullType << " &Out) {\n";
1259 OS << " std::optional<" << fullType
1260 << "> R = llvm::StringSwitch<std::optional<";
1261 OS << fullType << ">>(Val)\n";
1262 for (size_t I = 0; I < enums.size(); ++I) {
1263 OS << " .Case(\"" << values[I] << "\", ";
1264 OS << fullType << "::" << enums[I] << ")\n";
1265 }
1266 OS << " .Default(std::optional<" << fullType << ">());\n";
1267 OS << " if (R) {\n";
1268 OS << " Out = *R;\n return true;\n }\n";
1269 OS << " return false;\n";
1270 OS << "}\n\n";
1271
1272 OS << "const char *" << getAttrName() << "Attr::Convert" << shortType
1273 << "ToStr(" << fullType << " Val) {\n"
1274 << " switch(Val) {\n";
1275 SmallDenseSet<StringRef, 8> Uniques;
1276 for (size_t I = 0; I < enums.size(); ++I) {
1277 if (Uniques.insert(V: enums[I]).second)
1278 OS << " case " << fullType << "::" << enums[I] << ": return \""
1279 << values[I] << "\";\n";
1280 }
1281 if (!isCovered) {
1282 OS << " default: llvm_unreachable(\"Invalid attribute value\");\n";
1283 }
1284 OS << " }\n"
1285 << " llvm_unreachable(\"No enumerator with that value\");\n"
1286 << "}\n";
1287 }
1288 };
1289
1290 class VersionArgument : public Argument {
1291 public:
1292 VersionArgument(const Record &Arg, StringRef Attr)
1293 : Argument(Arg, Attr)
1294 {}
1295
1296 void writeAccessors(raw_ostream &OS) const override {
1297 OS << " VersionTuple get" << getUpperName() << "() const {\n";
1298 OS << " return " << getLowerName() << ";\n";
1299 OS << " }\n";
1300 OS << " void set" << getUpperName()
1301 << "(ASTContext &C, VersionTuple V) {\n";
1302 OS << " " << getLowerName() << " = V;\n";
1303 OS << " }";
1304 }
1305
1306 void writeCloneArgs(raw_ostream &OS) const override {
1307 OS << "get" << getUpperName() << "()";
1308 }
1309
1310 void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
1311 OS << "A->get" << getUpperName() << "()";
1312 }
1313
1314 void writeCtorInitializers(raw_ostream &OS) const override {
1315 OS << getLowerName() << "(" << getUpperName() << ")";
1316 }
1317
1318 void writeCtorDefaultInitializers(raw_ostream &OS) const override {
1319 OS << getLowerName() << "()";
1320 }
1321
1322 void writeCtorParameters(raw_ostream &OS) const override {
1323 OS << "VersionTuple " << getUpperName();
1324 }
1325
1326 void writeDeclarations(raw_ostream &OS) const override {
1327 OS << "VersionTuple " << getLowerName() << ";\n";
1328 }
1329
1330 void writePCHReadDecls(raw_ostream &OS) const override {
1331 OS << " VersionTuple " << getLowerName()
1332 << "= Record.readVersionTuple();\n";
1333 }
1334
1335 void writePCHReadArgs(raw_ostream &OS) const override {
1336 OS << getLowerName();
1337 }
1338
1339 void writePCHWrite(raw_ostream &OS) const override {
1340 OS << " Record.AddVersionTuple(SA->get" << getUpperName() << "());\n";
1341 }
1342
1343 void writeValue(raw_ostream &OS) const override {
1344 OS << getLowerName() << "=\" << get" << getUpperName() << "() << \"";
1345 }
1346
1347 void writeDump(raw_ostream &OS) const override {
1348 OS << " OS << \" \" << SA->get" << getUpperName() << "();\n";
1349 }
1350 };
1351
1352 class ExprArgument : public SimpleArgument {
1353 public:
1354 ExprArgument(const Record &Arg, StringRef Attr)
1355 : SimpleArgument(Arg, Attr, "Expr *")
1356 {}
1357
1358 void writeASTVisitorTraversal(raw_ostream &OS) const override {
1359 OS << " if (!"
1360 << "getDerived().TraverseStmt(A->get" << getUpperName() << "()))\n";
1361 OS << " return false;\n";
1362 }
1363
1364 void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
1365 OS << "tempInst" << getUpperName();
1366 }
1367
1368 void writeTemplateInstantiation(raw_ostream &OS) const override {
1369 OS << " " << getType() << " tempInst" << getUpperName() << ";\n";
1370 OS << " {\n";
1371 OS << " EnterExpressionEvaluationContext "
1372 << "Unevaluated(S, Sema::ExpressionEvaluationContext::Unevaluated);\n";
1373 OS << " ExprResult " << "Result = S.SubstExpr("
1374 << "A->get" << getUpperName() << "(), TemplateArgs);\n";
1375 OS << " if (Result.isInvalid())\n";
1376 OS << " return nullptr;\n";
1377 OS << " tempInst" << getUpperName() << " = Result.get();\n";
1378 OS << " }\n";
1379 }
1380
1381 void writeValue(raw_ostream &OS) const override {
1382 OS << "\";\n";
1383 OS << " get" << getUpperName()
1384 << "()->printPretty(OS, nullptr, Policy);\n";
1385 OS << " OS << \"";
1386 }
1387
1388 void writeDump(raw_ostream &OS) const override {}
1389
1390 void writeDumpChildren(raw_ostream &OS) const override {
1391 OS << " Visit(SA->get" << getUpperName() << "());\n";
1392 }
1393
1394 void writeHasChildren(raw_ostream &OS) const override { OS << "true"; }
1395 };
1396
1397 class VariadicExprArgument : public VariadicArgument {
1398 public:
1399 VariadicExprArgument(const Record &Arg, StringRef Attr)
1400 : VariadicArgument(Arg, Attr, "Expr *")
1401 {}
1402
1403 VariadicExprArgument(StringRef ArgName, StringRef Attr)
1404 : VariadicArgument(ArgName, Attr, "Expr *") {}
1405
1406 void writeASTVisitorTraversal(raw_ostream &OS) const override {
1407 OS << " {\n";
1408 OS << " " << getType() << " *I = A->" << getLowerName()
1409 << "_begin();\n";
1410 OS << " " << getType() << " *E = A->" << getLowerName()
1411 << "_end();\n";
1412 OS << " for (; I != E; ++I) {\n";
1413 OS << " if (!getDerived().TraverseStmt(*I))\n";
1414 OS << " return false;\n";
1415 OS << " }\n";
1416 OS << " }\n";
1417 }
1418
1419 void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
1420 OS << "tempInst" << getUpperName() << ", "
1421 << "numTempInst" << getUpperName();
1422 }
1423
1424 void writeTemplateInstantiation(raw_ostream &OS) const override {
1425 OS << " size_t numTempInst" << getUpperName() << ";\n";
1426 OS << " " << getType() << "*tempInst" << getUpperName() << ";\n";
1427 OS << " {\n";
1428 OS << " EnterExpressionEvaluationContext "
1429 << "Unevaluated(S, Sema::ExpressionEvaluationContext::Unevaluated);\n";
1430 OS << " ArrayRef<" << getType() << "> ArgsToInstantiate(A->"
1431 << getLowerName() << "_begin(), A->" << getLowerName() << "_end());\n";
1432 OS << " SmallVector<" << getType() << ", 4> InstArgs;\n";
1433 OS << " if (S.SubstExprs(ArgsToInstantiate, /*IsCall=*/false, "
1434 "TemplateArgs, InstArgs))\n";
1435 OS << " return nullptr;\n";
1436 OS << " numTempInst" << getUpperName() << " = InstArgs.size();\n";
1437 OS << " tempInst" << getUpperName() << " = new (C, 16) "
1438 << getType() << "[numTempInst" << getUpperName() << "];\n";
1439 OS << " std::copy(InstArgs.begin(), InstArgs.end(), tempInst"
1440 << getUpperName() << ");\n";
1441 OS << " }\n";
1442 }
1443
1444 void writeDump(raw_ostream &OS) const override {}
1445
1446 void writeDumpChildren(raw_ostream &OS) const override {
1447 OS << " for (" << getAttrName() << "Attr::" << getLowerName()
1448 << "_iterator I = SA->" << getLowerName() << "_begin(), E = SA->"
1449 << getLowerName() << "_end(); I != E; ++I)\n";
1450 OS << " Visit(*I);\n";
1451 }
1452
1453 void writeHasChildren(raw_ostream &OS) const override {
1454 OS << "SA->" << getLowerName() << "_begin() != "
1455 << "SA->" << getLowerName() << "_end()";
1456 }
1457 };
1458
1459 class VariadicIdentifierArgument : public VariadicArgument {
1460 public:
1461 VariadicIdentifierArgument(const Record &Arg, StringRef Attr)
1462 : VariadicArgument(Arg, Attr, "const IdentifierInfo *") {}
1463 };
1464
1465 class VariadicStringArgument : public VariadicArgument {
1466 public:
1467 VariadicStringArgument(const Record &Arg, StringRef Attr)
1468 : VariadicArgument(Arg, Attr, "StringRef")
1469 {}
1470
1471 void writeCtorBody(raw_ostream &OS) const override {
1472 OS << " for (size_t I = 0, E = " << getArgSizeName() << "; I != E;\n"
1473 " ++I) {\n"
1474 " StringRef Ref = " << getUpperName() << "[I];\n"
1475 " if (!Ref.empty()) {\n"
1476 " char *Mem = new (Ctx, 1) char[Ref.size()];\n"
1477 " std::memcpy(Mem, Ref.data(), Ref.size());\n"
1478 " " << getArgName() << "[I] = StringRef(Mem, Ref.size());\n"
1479 " }\n"
1480 " }\n";
1481 }
1482
1483 void writeValueImpl(raw_ostream &OS) const override {
1484 OS << " OS << \"\\\"\" << Val << \"\\\"\";\n";
1485 }
1486 };
1487
1488 class TypeArgument : public SimpleArgument {
1489 public:
1490 TypeArgument(const Record &Arg, StringRef Attr)
1491 : SimpleArgument(Arg, Attr, "TypeSourceInfo *")
1492 {}
1493
1494 void writeAccessors(raw_ostream &OS) const override {
1495 OS << " QualType get" << getUpperName() << "() const {\n";
1496 OS << " return " << getLowerName() << "->getType();\n";
1497 OS << " }";
1498 OS << " " << getType() << " get" << getUpperName() << "Loc() const {\n";
1499 OS << " return " << getLowerName() << ";\n";
1500 OS << " }";
1501 }
1502
1503 void writeASTVisitorTraversal(raw_ostream &OS) const override {
1504 OS << " if (auto *TSI = A->get" << getUpperName() << "Loc())\n";
1505 OS << " if (!getDerived().TraverseTypeLoc(TSI->getTypeLoc()))\n";
1506 OS << " return false;\n";
1507 }
1508
1509 void writeTemplateInstantiation(raw_ostream &OS) const override {
1510 OS << " " << getType() << " tempInst" << getUpperName() << " =\n";
1511 OS << " S.SubstType(A->get" << getUpperName() << "Loc(), "
1512 << "TemplateArgs, A->getLoc(), A->getAttrName());\n";
1513 OS << " if (!tempInst" << getUpperName() << ")\n";
1514 OS << " return nullptr;\n";
1515 }
1516
1517 void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
1518 OS << "tempInst" << getUpperName();
1519 }
1520
1521 void writePCHWrite(raw_ostream &OS) const override {
1522 OS << " "
1523 << WritePCHRecord(type: getType(),
1524 name: "SA->get" + getUpperName().str() + "Loc()");
1525 }
1526 };
1527
1528 class WrappedAttr : public SimpleArgument {
1529 std::string AttrType; // C++ class name for the wrapped attr
1530
1531 public:
1532 WrappedAttr(const Record &Arg, StringRef Attr)
1533 : SimpleArgument(Arg, Attr, "Attr *"),
1534 AttrType(Arg.getValueAsString(FieldName: "AttrType")) {}
1535
1536 void writeAccessors(raw_ostream &OS) const override {
1537 // The field is always stored as Attr * regardless of AttrType. This is
1538 // required because the generated isEquivalent method calls
1539 // equalAttrArgs(getInferredAttr(), Other.getInferredAttr(), Context).
1540 // If the field were AttrType * (e.g. AvailabilityAttr *), that call
1541 // would instantiate equalAttrArgs<AvailabilityAttr *>, which has no
1542 // specialization and returns false. Storing Attr * routes the call
1543 // through equalAttrArgs<Attr *>, which handles null and calls
1544 // isEquivalent. Typed get<Name>As() / set<Name>As() accessors are
1545 // provided for callers that need the specific type.
1546 OS << " Attr *get" << getUpperName() << "() const {\n";
1547 OS << " return " << getLowerName() << ";\n";
1548 OS << " }\n";
1549 OS << " void set" << getUpperName() << "(Attr *V) {\n";
1550 OS << " " << getLowerName() << " = V;\n";
1551 OS << " }";
1552 if (!AttrType.empty()) {
1553 OS << "\n";
1554 OS << " " << AttrType << " *get" << getUpperName() << "As() const {\n";
1555 OS << " return llvm::cast_or_null<" << AttrType << ">("
1556 << getLowerName() << ");\n";
1557 OS << " }\n";
1558 OS << " void set" << getUpperName() << "As(" << AttrType << " *V) {\n";
1559 OS << " " << getLowerName() << " = V;\n";
1560 OS << " }";
1561 }
1562 }
1563
1564 void writePCHReadDecls(raw_ostream &OS) const override {
1565 OS << " Attr *" << getLowerName() << " = Record.readAttr();";
1566 }
1567
1568 void writePCHWrite(raw_ostream &OS) const override {
1569 OS << " AddAttr(SA->get" << getUpperName() << "());";
1570 }
1571
1572 std::string getIsOmitted() const override {
1573 if (isOptional())
1574 return "!get" + getUpperName().str() + "()";
1575 return "false";
1576 }
1577
1578 void writeValue(raw_ostream &OS) const override {}
1579
1580 void writeDump(raw_ostream &OS) const override {}
1581
1582 void writeDumpChildren(raw_ostream &OS) const override {
1583 if (isOptional()) {
1584 OS << " if (auto *W = SA->get" << getUpperName() << "())\n";
1585 OS << " Visit(W);\n";
1586 } else {
1587 OS << " Visit(SA->get" << getUpperName() << "());\n";
1588 }
1589 }
1590
1591 void writeHasChildren(raw_ostream &OS) const override {
1592 if (isOptional())
1593 OS << "SA->get" << getUpperName() << "() != nullptr";
1594 else
1595 OS << "true";
1596 }
1597 };
1598
1599 } // end anonymous namespace
1600
1601static std::unique_ptr<Argument>
1602createArgument(const Record &Arg, StringRef Attr,
1603 const Record *Search = nullptr) {
1604 if (!Search)
1605 Search = &Arg;
1606
1607 std::unique_ptr<Argument> Ptr;
1608 StringRef ArgName = Search->getName();
1609
1610 if (ArgName == "AlignedArgument")
1611 Ptr = std::make_unique<AlignedArgument>(args: Arg, args&: Attr);
1612 else if (ArgName == "EnumArgument")
1613 Ptr = std::make_unique<EnumArgument>(args: Arg, args&: Attr);
1614 else if (ArgName == "ExprArgument")
1615 Ptr = std::make_unique<ExprArgument>(args: Arg, args&: Attr);
1616 else if (ArgName == "DeclArgument")
1617 Ptr = std::make_unique<SimpleArgument>(
1618 args: Arg, args&: Attr, args: (Arg.getValueAsDef(FieldName: "Kind")->getName() + "Decl *").str());
1619 else if (ArgName == "IdentifierArgument")
1620 Ptr = std::make_unique<SimpleArgument>(args: Arg, args&: Attr, args: "const IdentifierInfo *");
1621 else if (ArgName == "DefaultBoolArgument")
1622 Ptr = std::make_unique<DefaultSimpleArgument>(
1623 args: Arg, args&: Attr, args: "bool", args: Arg.getValueAsBit(FieldName: "Default"));
1624 else if (ArgName == "BoolArgument")
1625 Ptr = std::make_unique<SimpleArgument>(args: Arg, args&: Attr, args: "bool");
1626 else if (ArgName == "DefaultIntArgument")
1627 Ptr = std::make_unique<DefaultSimpleArgument>(
1628 args: Arg, args&: Attr, args: "int", args: Arg.getValueAsInt(FieldName: "Default"));
1629 else if (ArgName == "IntArgument")
1630 Ptr = std::make_unique<SimpleArgument>(args: Arg, args&: Attr, args: "int");
1631 else if (ArgName == "StringArgument")
1632 Ptr = std::make_unique<StringArgument>(args: Arg, args&: Attr);
1633 else if (ArgName == "TypeArgument")
1634 Ptr = std::make_unique<TypeArgument>(args: Arg, args&: Attr);
1635 else if (ArgName == "UnsignedArgument")
1636 Ptr = std::make_unique<SimpleArgument>(args: Arg, args&: Attr, args: "unsigned");
1637 else if (ArgName == "VariadicUnsignedArgument")
1638 Ptr = std::make_unique<VariadicArgument>(args: Arg, args&: Attr, args: "unsigned");
1639 else if (ArgName == "VariadicStringArgument")
1640 Ptr = std::make_unique<VariadicStringArgument>(args: Arg, args&: Attr);
1641 else if (ArgName == "VariadicEnumArgument")
1642 Ptr = std::make_unique<VariadicEnumArgument>(args: Arg, args&: Attr);
1643 else if (ArgName == "VariadicExprArgument")
1644 Ptr = std::make_unique<VariadicExprArgument>(args: Arg, args&: Attr);
1645 else if (ArgName == "VariadicParamIdxArgument")
1646 Ptr = std::make_unique<VariadicParamIdxArgument>(args: Arg, args&: Attr);
1647 else if (ArgName == "VariadicParamOrParamIdxArgument")
1648 Ptr = std::make_unique<VariadicParamOrParamIdxArgument>(args: Arg, args&: Attr);
1649 else if (ArgName == "ParamIdxArgument")
1650 Ptr = std::make_unique<SimpleArgument>(args: Arg, args&: Attr, args: "ParamIdx");
1651 else if (ArgName == "VariadicIdentifierArgument")
1652 Ptr = std::make_unique<VariadicIdentifierArgument>(args: Arg, args&: Attr);
1653 else if (ArgName == "VersionArgument")
1654 Ptr = std::make_unique<VersionArgument>(args: Arg, args&: Attr);
1655 else if (ArgName == "WrappedAttr")
1656 Ptr = std::make_unique<WrappedAttr>(args: Arg, args&: Attr);
1657 else if (ArgName == "OMPTraitInfoArgument")
1658 Ptr = std::make_unique<SimpleArgument>(args: Arg, args&: Attr, args: "OMPTraitInfo *");
1659 else if (ArgName == "VariadicOMPInteropInfoArgument")
1660 Ptr = std::make_unique<VariadicOMPInteropInfoArgument>(args: Arg, args&: Attr);
1661
1662 if (!Ptr) {
1663 // Search in reverse order so that the most-derived type is handled first.
1664 std::vector<const Record *> SCs = Search->getSuperClasses();
1665 for (const Record *Base : reverse(C&: SCs)) {
1666 if ((Ptr = createArgument(Arg, Attr, Search: Base)))
1667 break;
1668 }
1669 }
1670
1671 if (Ptr && Arg.getValueAsBit(FieldName: "Optional"))
1672 Ptr->setOptional(true);
1673
1674 if (Ptr && Arg.getValueAsBit(FieldName: "Fake"))
1675 Ptr->setFake(true);
1676
1677 return Ptr;
1678}
1679
1680static void writeAvailabilityValue(raw_ostream &OS) {
1681 OS << "\" << getPlatform()->getName();\n"
1682 << " if (getStrict()) OS << \", strict\";\n"
1683 << " if (!getIntroduced().empty()) OS << \", introduced=\" << getIntroduced();\n"
1684 << " if (!getDeprecated().empty()) OS << \", deprecated=\" << getDeprecated();\n"
1685 << " if (!getObsoleted().empty()) OS << \", obsoleted=\" << getObsoleted();\n"
1686 << " if (getUnavailable()) OS << \", unavailable\";\n"
1687 << " OS << \"";
1688}
1689
1690static void writeDeprecatedAttrValue(raw_ostream &OS, StringRef Variety) {
1691 OS << "\\\"\" << getMessage() << \"\\\"\";\n";
1692 // Only GNU deprecated has an optional fixit argument at the second position.
1693 if (Variety == "GNU")
1694 OS << " if (!getReplacement().empty()) OS << \", \\\"\""
1695 " << getReplacement() << \"\\\"\";\n";
1696 OS << " OS << \"";
1697}
1698
1699static void writeGetSpellingFunction(const Record &R, raw_ostream &OS) {
1700 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(Attr: R);
1701
1702 OS << "const char *" << R.getName() << "Attr::getSpelling() const {\n";
1703 if (Spellings.empty()) {
1704 OS << " return \"(No spelling)\";\n}\n\n";
1705 return;
1706 }
1707
1708 OS << " switch (getAttributeSpellingListIndex()) {\n"
1709 " default:\n"
1710 " llvm_unreachable(\"Unknown attribute spelling!\");\n"
1711 " return \"(No spelling)\";\n";
1712
1713 for (const auto &[Idx, S] : enumerate(First&: Spellings)) {
1714 // clang-format off
1715 OS << " case " << Idx << ":\n"
1716 " return \"" << S.name() << "\";\n";
1717 // clang-format on
1718 }
1719 // End of the switch statement.
1720 OS << " }\n";
1721 // End of the getSpelling function.
1722 OS << "}\n\n";
1723}
1724
1725static void
1726writePrettyPrintFunction(const Record &R,
1727 const std::vector<std::unique_ptr<Argument>> &Args,
1728 raw_ostream &OS) {
1729 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(Attr: R);
1730
1731 OS << "void " << R.getName() << "Attr::printPretty("
1732 << "raw_ostream &OS, const PrintingPolicy &Policy) const {\n";
1733
1734 if (Spellings.empty()) {
1735 OS << "}\n\n";
1736 return;
1737 }
1738
1739 OS << " bool IsFirstArgument = true; (void)IsFirstArgument;\n"
1740 << " unsigned TrailingOmittedArgs = 0; (void)TrailingOmittedArgs;\n"
1741 << " switch (getAttributeSpellingListIndex()) {\n"
1742 << " default:\n"
1743 << " llvm_unreachable(\"Unknown attribute spelling!\");\n"
1744 << " break;\n";
1745
1746 for (const auto &[Idx, S] : enumerate(First&: Spellings)) {
1747 SmallString<16> Prefix;
1748 SmallString<8> Suffix;
1749 // The actual spelling of the name and namespace (if applicable)
1750 // of an attribute without considering prefix and suffix.
1751 SmallString<64> Spelling;
1752 StringRef Name = S.name();
1753 StringRef Variety = S.variety();
1754
1755 if (Variety == "GNU") {
1756 Prefix = "__attribute__((";
1757 Suffix = "))";
1758 } else if (Variety == "CXX11" || Variety == "C23") {
1759 Prefix = "[[";
1760 Suffix = "]]";
1761 StringRef Namespace = S.nameSpace();
1762 if (!Namespace.empty()) {
1763 Spelling += Namespace;
1764 Spelling += "::";
1765 }
1766 } else if (Variety == "Declspec") {
1767 Prefix = "__declspec(";
1768 Suffix = ")";
1769 } else if (Variety == "Microsoft") {
1770 Prefix = "[";
1771 Suffix = "]";
1772 } else if (Variety == "Keyword") {
1773 Prefix = "";
1774 Suffix = "";
1775 } else if (Variety == "Pragma") {
1776 Prefix = "#pragma ";
1777 Suffix = "\n";
1778 StringRef Namespace = S.nameSpace();
1779 if (!Namespace.empty()) {
1780 Spelling += Namespace;
1781 Spelling += " ";
1782 }
1783 } else if (Variety == "HLSLAnnotation") {
1784 Prefix = ":";
1785 Suffix = "";
1786 } else {
1787 llvm_unreachable("Unknown attribute syntax variety!");
1788 }
1789
1790 Spelling += Name;
1791
1792 OS << " case " << Idx << " : {\n"
1793 << " OS << \"" << Prefix << Spelling << "\";\n";
1794
1795 if (Variety == "Pragma") {
1796 OS << " printPrettyPragma(OS, Policy);\n";
1797 OS << " OS << \"\\n\";";
1798 OS << " break;\n";
1799 OS << " }\n";
1800 continue;
1801 }
1802
1803 if (Spelling == "availability") {
1804 OS << " OS << \"(";
1805 writeAvailabilityValue(OS);
1806 OS << ")\";\n";
1807 } else if (Spelling == "deprecated" || Spelling == "gnu::deprecated") {
1808 OS << " OS << \"(";
1809 writeDeprecatedAttrValue(OS, Variety);
1810 OS << ")\";\n";
1811 } else {
1812 // To avoid printing parentheses around an empty argument list or
1813 // printing spurious commas at the end of an argument list, we need to
1814 // determine where the last provided non-fake argument is.
1815 bool FoundNonOptArg = false;
1816 for (const auto &arg : reverse(C: Args)) {
1817 if (arg->isFake())
1818 continue;
1819 if (FoundNonOptArg)
1820 continue;
1821 // FIXME: arg->getIsOmitted() == "false" means we haven't implemented
1822 // any way to detect whether the argument was omitted.
1823 if (!arg->isOptional() || arg->getIsOmitted() == "false") {
1824 FoundNonOptArg = true;
1825 continue;
1826 }
1827 OS << " if (" << arg->getIsOmitted() << ")\n"
1828 << " ++TrailingOmittedArgs;\n";
1829 }
1830 unsigned ArgIndex = 0;
1831 for (const auto &arg : Args) {
1832 if (arg->isFake())
1833 continue;
1834 std::string IsOmitted = arg->getIsOmitted();
1835 if (arg->isOptional() && IsOmitted != "false")
1836 OS << " if (!(" << IsOmitted << ")) {\n";
1837 // Variadic arguments print their own leading comma.
1838 if (!arg->isVariadic())
1839 OS << " DelimitAttributeArgument(OS, IsFirstArgument);\n";
1840 OS << " OS << \"";
1841 arg->writeValue(OS);
1842 OS << "\";\n";
1843 if (arg->isOptional() && IsOmitted != "false")
1844 OS << " }\n";
1845 ++ArgIndex;
1846 }
1847 if (ArgIndex != 0)
1848 OS << " if (!IsFirstArgument)\n"
1849 << " OS << \")\";\n";
1850 }
1851 OS << " OS << \"" << Suffix << "\";\n"
1852 << " break;\n"
1853 << " }\n";
1854 }
1855
1856 // End of the switch statement.
1857 OS << "}\n";
1858 // End of the print function.
1859 OS << "}\n\n";
1860}
1861
1862/// Return the index of a spelling in a spelling list.
1863static unsigned getSpellingListIndex(ArrayRef<FlattenedSpelling> SpellingList,
1864 const FlattenedSpelling &Spelling) {
1865 assert(!SpellingList.empty() && "Spelling list is empty!");
1866
1867 for (const auto &[Index, S] : enumerate(First&: SpellingList)) {
1868 if (S.variety() == Spelling.variety() &&
1869 S.nameSpace() == Spelling.nameSpace() && S.name() == Spelling.name())
1870 return Index;
1871 }
1872
1873 PrintFatalError(Msg: "Unknown spelling: " + Spelling.name());
1874}
1875
1876static void writeAttrAccessorDefinition(const Record &R, raw_ostream &OS) {
1877 std::vector<const Record *> Accessors = R.getValueAsListOfDefs(FieldName: "Accessors");
1878 if (Accessors.empty())
1879 return;
1880
1881 const std::vector<FlattenedSpelling> SpellingList = GetFlattenedSpellings(Attr: R);
1882 assert(!SpellingList.empty() &&
1883 "Attribute with empty spelling list can't have accessors!");
1884 for (const auto *Accessor : Accessors) {
1885 const StringRef Name = Accessor->getValueAsString(FieldName: "Name");
1886 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(Attr: *Accessor);
1887
1888 OS << " bool " << Name
1889 << "() const { return getAttributeSpellingListIndex() == ";
1890 for (unsigned Index = 0; Index < Spellings.size(); ++Index) {
1891 OS << getSpellingListIndex(SpellingList, Spelling: Spellings[Index]);
1892 if (Index != Spellings.size() - 1)
1893 OS << " ||\n getAttributeSpellingListIndex() == ";
1894 else
1895 OS << "; }\n";
1896 }
1897 }
1898}
1899
1900static bool
1901SpellingNamesAreCommon(const std::vector<FlattenedSpelling>& Spellings) {
1902 assert(!Spellings.empty() && "An empty list of spellings was provided");
1903 StringRef FirstName =
1904 NormalizeNameForSpellingComparison(Name: Spellings.front().name());
1905 for (const auto &Spelling : drop_begin(RangeOrContainer: Spellings)) {
1906 StringRef Name = NormalizeNameForSpellingComparison(Name: Spelling.name());
1907 if (Name != FirstName)
1908 return false;
1909 }
1910 return true;
1911}
1912
1913typedef std::map<unsigned, std::string> SemanticSpellingMap;
1914static std::string
1915CreateSemanticSpellings(const std::vector<FlattenedSpelling> &Spellings,
1916 SemanticSpellingMap &Map) {
1917 // The enumerants are automatically generated based on the variety,
1918 // namespace (if present) and name for each attribute spelling. However,
1919 // care is taken to avoid trampling on the reserved namespace due to
1920 // underscores.
1921 std::string Ret(" enum Spelling {\n");
1922 std::set<std::string> Uniques;
1923 unsigned Idx = 0;
1924
1925 // If we have a need to have this many spellings we likely need to add an
1926 // extra bit to the SpellingIndex in AttributeCommonInfo, then increase the
1927 // value of SpellingNotCalculated there and here.
1928 assert(Spellings.size() < 15 &&
1929 "Too many spellings, would step on SpellingNotCalculated in "
1930 "AttributeCommonInfo");
1931 for (auto I = Spellings.begin(), E = Spellings.end(); I != E; ++I, ++Idx) {
1932 const FlattenedSpelling &S = *I;
1933 StringRef Variety = S.variety();
1934 StringRef Spelling = S.name();
1935 StringRef Namespace = S.nameSpace();
1936 std::string EnumName;
1937
1938 EnumName += Variety;
1939 EnumName += "_";
1940 if (!Namespace.empty())
1941 EnumName += NormalizeNameForSpellingComparison(Name: Namespace).str() + "_";
1942 EnumName += NormalizeNameForSpellingComparison(Name: Spelling);
1943
1944 // Even if the name is not unique, this spelling index corresponds to a
1945 // particular enumerant name that we've calculated.
1946 Map[Idx] = EnumName;
1947
1948 // Since we have been stripping underscores to avoid trampling on the
1949 // reserved namespace, we may have inadvertently created duplicate
1950 // enumerant names. These duplicates are not considered part of the
1951 // semantic spelling, and can be elided.
1952 if (!Uniques.insert(x: EnumName).second)
1953 continue;
1954
1955 if (I != Spellings.begin())
1956 Ret += ",\n";
1957 // Duplicate spellings are not considered part of the semantic spelling
1958 // enumeration, but the spelling index and semantic spelling values are
1959 // meant to be equivalent, so we must specify a concrete value for each
1960 // enumerator.
1961 Ret += " " + EnumName + " = " + utostr(X: Idx);
1962 }
1963 Ret += ",\n SpellingNotCalculated = 15\n";
1964 Ret += "\n };\n\n";
1965 return Ret;
1966}
1967
1968static void WriteSemanticSpellingSwitch(StringRef VarName,
1969 const SemanticSpellingMap &Map,
1970 raw_ostream &OS) {
1971 OS << " switch (" << VarName << ") {\n default: "
1972 << "llvm_unreachable(\"Unknown spelling list index\");\n";
1973 for (const auto &I : Map)
1974 OS << " case " << I.first << ": return " << I.second << ";\n";
1975 OS << " }\n";
1976}
1977
1978// Note: these values need to match the values used by LateAttrParseKind in
1979// `Attr.td`
1980enum class LateAttrParseKind { Never = 0, Standard = 1, ExperimentalExt = 2 };
1981
1982static LateAttrParseKind getLateAttrParseKind(const Record *Attr) {
1983 // This function basically does
1984 // `Attr->getValueAsDef("LateParsed")->getValueAsInt("Kind")` but does a bunch
1985 // of sanity checking to ensure that `LateAttrParseMode` in `Attr.td` is in
1986 // sync with the `LateAttrParseKind` enum in this source file.
1987
1988 static constexpr StringRef LateParsedStr = "LateParsed";
1989 static constexpr StringRef LateAttrParseKindStr = "LateAttrParseKind";
1990 static constexpr StringRef KindFieldStr = "Kind";
1991
1992 auto *LAPK = Attr->getValueAsDef(FieldName: LateParsedStr);
1993
1994 // Typecheck the `LateParsed` field.
1995 if (LAPK->getDirectSuperClasses().size() != 1)
1996 PrintFatalError(Rec: Attr, Msg: "Field `" + Twine(LateParsedStr) +
1997 "`should only have one super class");
1998
1999 const Record *SuperClass = LAPK->getDirectSuperClasses()[0].first;
2000 if (SuperClass->getName() != LateAttrParseKindStr)
2001 PrintFatalError(
2002 Rec: Attr, Msg: "Field `" + Twine(LateParsedStr) + "`should only have type `" +
2003 Twine(LateAttrParseKindStr) + "` but found type `" +
2004 SuperClass->getName() + "`");
2005
2006 // Get Kind and verify the enum name matches the name in `Attr.td`.
2007 unsigned Kind = LAPK->getValueAsInt(FieldName: KindFieldStr);
2008 switch (LateAttrParseKind(Kind)) {
2009#define CASE(X) \
2010 case LateAttrParseKind::X: \
2011 if (LAPK->getName().compare("LateAttrParse" #X) != 0) { \
2012 PrintFatalError( \
2013 Attr, \
2014 "Field `" + Twine(LateParsedStr) + "` set to `" + LAPK->getName() + \
2015 "` but this converts to `LateAttrParseKind::" + Twine(#X) + \
2016 "`"); \
2017 } \
2018 return LateAttrParseKind::X;
2019
2020 CASE(Never)
2021 CASE(Standard)
2022 CASE(ExperimentalExt)
2023#undef CASE
2024 }
2025
2026 // The Kind value is completely invalid
2027 auto KindValueStr = utostr(X: Kind);
2028 PrintFatalError(Rec: Attr, Msg: "Field `" + Twine(LateParsedStr) + "` set to `" +
2029 LAPK->getName() + "` has unexpected `" +
2030 Twine(KindFieldStr) + "` value of " + KindValueStr);
2031}
2032
2033// Emits the LateParsed property for attributes.
2034static void emitClangAttrLateParsedListImpl(const RecordKeeper &Records,
2035 raw_ostream &OS,
2036 LateAttrParseKind LateParseMode) {
2037 for (const auto *Attr : Records.getAllDerivedDefinitions(ClassName: "Attr")) {
2038 if (LateAttrParseKind LateParsed = getLateAttrParseKind(Attr);
2039 LateParsed != LateParseMode)
2040 continue;
2041
2042 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(Attr: *Attr);
2043
2044 // FIXME: Handle non-GNU attributes
2045 for (const auto &I : Spellings) {
2046 if (I.variety() != "GNU")
2047 continue;
2048 OS << ".Case(\"" << I.name() << "\", 1)\n";
2049 }
2050 }
2051}
2052
2053static void emitClangAttrLateParsedList(const RecordKeeper &Records,
2054 raw_ostream &OS) {
2055 OS << "#if defined(CLANG_ATTR_LATE_PARSED_LIST)\n";
2056 emitClangAttrLateParsedListImpl(Records, OS, LateParseMode: LateAttrParseKind::Standard);
2057 OS << "#endif // CLANG_ATTR_LATE_PARSED_LIST\n\n";
2058}
2059
2060static void emitClangAttrLateParsedExperimentalList(const RecordKeeper &Records,
2061 raw_ostream &OS) {
2062 OS << "#if defined(CLANG_ATTR_LATE_PARSED_EXPERIMENTAL_EXT_LIST)\n";
2063 emitClangAttrLateParsedListImpl(Records, OS,
2064 LateParseMode: LateAttrParseKind::ExperimentalExt);
2065 OS << "#endif // CLANG_ATTR_LATE_PARSED_EXPERIMENTAL_EXT_LIST\n\n";
2066}
2067
2068// Emits a list of attributes whose argument list is parsed inside a function
2069// prototype scope so it can refer to the enclosing function's parameters.
2070static void
2071emitClangAttrParseArgsInFunctionScopeList(const RecordKeeper &Records,
2072 raw_ostream &OS) {
2073 OS << "#if defined(CLANG_ATTR_PARSE_ARGS_IN_FUNCTION_SCOPE_LIST)\n";
2074 for (const auto *Attr : Records.getAllDerivedDefinitions(ClassName: "Attr")) {
2075 if (!Attr->getValueAsBit(FieldName: "ParseArgsInFunctionScope"))
2076 continue;
2077 // FIXME: Handle non-GNU attributes
2078 for (const auto &I : GetFlattenedSpellings(Attr: *Attr))
2079 if (I.variety() == "GNU")
2080 OS << ".Case(\"" << I.name() << "\", 1)\n";
2081 }
2082 OS << "#endif // CLANG_ATTR_PARSE_ARGS_IN_FUNCTION_SCOPE_LIST\n\n";
2083}
2084
2085static bool hasGNUorCXX11Spelling(const Record &Attribute) {
2086 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(Attr: Attribute);
2087 for (const auto &I : Spellings) {
2088 if (I.variety() == "GNU" || I.variety() == "CXX11")
2089 return true;
2090 }
2091 return false;
2092}
2093
2094namespace {
2095
2096struct AttributeSubjectMatchRule {
2097 const Record *MetaSubject;
2098 const Record *Constraint;
2099
2100 AttributeSubjectMatchRule(const Record *MetaSubject, const Record *Constraint)
2101 : MetaSubject(MetaSubject), Constraint(Constraint) {
2102 assert(MetaSubject && "Missing subject");
2103 }
2104
2105 bool isSubRule() const { return Constraint != nullptr; }
2106
2107 std::vector<const Record *> getSubjects() const {
2108 return (Constraint ? Constraint : MetaSubject)
2109 ->getValueAsListOfDefs(FieldName: "Subjects");
2110 }
2111
2112 std::vector<const Record *> getLangOpts() const {
2113 if (Constraint) {
2114 // Lookup the options in the sub-rule first, in case the sub-rule
2115 // overrides the rules options.
2116 std::vector<const Record *> Opts =
2117 Constraint->getValueAsListOfDefs(FieldName: "LangOpts");
2118 if (!Opts.empty())
2119 return Opts;
2120 }
2121 return MetaSubject->getValueAsListOfDefs(FieldName: "LangOpts");
2122 }
2123
2124 // Abstract rules are used only for sub-rules
2125 bool isAbstractRule() const { return getSubjects().empty(); }
2126
2127 StringRef getName() const {
2128 return (Constraint ? Constraint : MetaSubject)->getValueAsString(FieldName: "Name");
2129 }
2130
2131 bool isNegatedSubRule() const {
2132 assert(isSubRule() && "Not a sub-rule");
2133 return Constraint->getValueAsBit(FieldName: "Negated");
2134 }
2135
2136 std::string getSpelling() const {
2137 std::string Result = MetaSubject->getValueAsString(FieldName: "Name").str();
2138 if (isSubRule()) {
2139 Result += '(';
2140 if (isNegatedSubRule())
2141 Result += "unless(";
2142 Result += getName();
2143 if (isNegatedSubRule())
2144 Result += ')';
2145 Result += ')';
2146 }
2147 return Result;
2148 }
2149
2150 std::string getEnumValueName() const {
2151 SmallString<128> Result;
2152 Result += "SubjectMatchRule_";
2153 Result += MetaSubject->getValueAsString(FieldName: "Name");
2154 if (isSubRule()) {
2155 Result += "_";
2156 if (isNegatedSubRule())
2157 Result += "not_";
2158 Result += Constraint->getValueAsString(FieldName: "Name");
2159 }
2160 if (isAbstractRule())
2161 Result += "_abstract";
2162 return std::string(Result);
2163 }
2164
2165 std::string getEnumValue() const { return "attr::" + getEnumValueName(); }
2166
2167 static const char *EnumName;
2168};
2169
2170const char *AttributeSubjectMatchRule::EnumName = "attr::SubjectMatchRule";
2171
2172struct PragmaClangAttributeSupport {
2173 std::vector<AttributeSubjectMatchRule> Rules;
2174
2175 class RuleOrAggregateRuleSet {
2176 std::vector<AttributeSubjectMatchRule> Rules;
2177 bool IsRule;
2178 RuleOrAggregateRuleSet(ArrayRef<AttributeSubjectMatchRule> Rules,
2179 bool IsRule)
2180 : Rules(Rules), IsRule(IsRule) {}
2181
2182 public:
2183 bool isRule() const { return IsRule; }
2184
2185 const AttributeSubjectMatchRule &getRule() const {
2186 assert(IsRule && "not a rule!");
2187 return Rules[0];
2188 }
2189
2190 ArrayRef<AttributeSubjectMatchRule> getAggregateRuleSet() const {
2191 return Rules;
2192 }
2193
2194 static RuleOrAggregateRuleSet
2195 getRule(const AttributeSubjectMatchRule &Rule) {
2196 return RuleOrAggregateRuleSet(Rule, /*IsRule=*/true);
2197 }
2198 static RuleOrAggregateRuleSet
2199 getAggregateRuleSet(ArrayRef<AttributeSubjectMatchRule> Rules) {
2200 return RuleOrAggregateRuleSet(Rules, /*IsRule=*/false);
2201 }
2202 };
2203 DenseMap<const Record *, RuleOrAggregateRuleSet> SubjectsToRules;
2204
2205 PragmaClangAttributeSupport(const RecordKeeper &Records);
2206
2207 bool isAttributedSupported(const Record &Attribute);
2208
2209 void emitMatchRuleList(raw_ostream &OS);
2210
2211 void generateStrictConformsTo(const Record &Attr, raw_ostream &OS);
2212
2213 void generateParsingHelpers(raw_ostream &OS);
2214};
2215
2216} // end anonymous namespace
2217
2218static bool isSupportedPragmaClangAttributeSubject(const Record &Subject) {
2219 // FIXME: #pragma clang attribute does not currently support statement
2220 // attributes, so test whether the subject is one that appertains to a
2221 // declaration node. However, it may be reasonable for support for statement
2222 // attributes to be added.
2223 if (Subject.isSubClassOf(Name: "DeclNode") || Subject.isSubClassOf(Name: "DeclBase") ||
2224 Subject.getName() == "DeclBase")
2225 return true;
2226
2227 if (Subject.isSubClassOf(Name: "SubsetSubject"))
2228 return isSupportedPragmaClangAttributeSubject(
2229 Subject: *Subject.getValueAsDef(FieldName: "Base"));
2230
2231 return false;
2232}
2233
2234static bool doesDeclDeriveFrom(const Record *D, const Record *Base) {
2235 const Record *CurrentBase = D->getValueAsOptionalDef(BaseFieldName);
2236 if (!CurrentBase)
2237 return false;
2238 if (CurrentBase == Base)
2239 return true;
2240 return doesDeclDeriveFrom(D: CurrentBase, Base);
2241}
2242
2243PragmaClangAttributeSupport::PragmaClangAttributeSupport(
2244 const RecordKeeper &Records) {
2245 auto MapFromSubjectsToRules = [this](const Record *SubjectContainer,
2246 const Record *MetaSubject,
2247 const Record *Constraint) {
2248 Rules.emplace_back(args&: MetaSubject, args&: Constraint);
2249 for (const Record *Subject :
2250 SubjectContainer->getValueAsListOfDefs(FieldName: "Subjects")) {
2251 bool Inserted =
2252 SubjectsToRules
2253 .try_emplace(Key: Subject, Args: RuleOrAggregateRuleSet::getRule(
2254 Rule: AttributeSubjectMatchRule(MetaSubject,
2255 Constraint)))
2256 .second;
2257 if (!Inserted) {
2258 PrintFatalError(Msg: "Attribute subject match rules should not represent"
2259 "same attribute subjects.");
2260 }
2261 }
2262 };
2263 for (const auto *MetaSubject :
2264 Records.getAllDerivedDefinitions(ClassName: "AttrSubjectMatcherRule")) {
2265 MapFromSubjectsToRules(MetaSubject, MetaSubject, /*Constraints=*/nullptr);
2266 for (const Record *Constraint :
2267 MetaSubject->getValueAsListOfDefs(FieldName: "Constraints"))
2268 MapFromSubjectsToRules(Constraint, MetaSubject, Constraint);
2269 }
2270
2271 ArrayRef<const Record *> DeclNodes =
2272 Records.getAllDerivedDefinitions(DeclNodeClassName);
2273 for (const auto *Aggregate :
2274 Records.getAllDerivedDefinitions(ClassName: "AttrSubjectMatcherAggregateRule")) {
2275 const Record *SubjectDecl = Aggregate->getValueAsDef(FieldName: "Subject");
2276
2277 // Gather sub-classes of the aggregate subject that act as attribute
2278 // subject rules.
2279 std::vector<AttributeSubjectMatchRule> Rules;
2280 for (const auto *D : DeclNodes) {
2281 if (doesDeclDeriveFrom(D, Base: SubjectDecl)) {
2282 auto It = SubjectsToRules.find(Val: D);
2283 if (It == SubjectsToRules.end())
2284 continue;
2285 if (!It->second.isRule() || It->second.getRule().isSubRule())
2286 continue; // Assume that the rule will be included as well.
2287 Rules.push_back(x: It->second.getRule());
2288 }
2289 }
2290
2291 bool Inserted =
2292 SubjectsToRules
2293 .try_emplace(Key: SubjectDecl,
2294 Args: RuleOrAggregateRuleSet::getAggregateRuleSet(Rules))
2295 .second;
2296 if (!Inserted) {
2297 PrintFatalError(Msg: "Attribute subject match rules should not represent"
2298 "same attribute subjects.");
2299 }
2300 }
2301}
2302
2303static PragmaClangAttributeSupport &
2304getPragmaAttributeSupport(const RecordKeeper &Records) {
2305 static PragmaClangAttributeSupport Instance(Records);
2306 return Instance;
2307}
2308
2309void PragmaClangAttributeSupport::emitMatchRuleList(raw_ostream &OS) {
2310 OS << "#ifndef ATTR_MATCH_SUB_RULE\n";
2311 OS << "#define ATTR_MATCH_SUB_RULE(Value, Spelling, IsAbstract, Parent, "
2312 "IsNegated) "
2313 << "ATTR_MATCH_RULE(Value, Spelling, IsAbstract)\n";
2314 OS << "#endif\n";
2315 for (const auto &Rule : Rules) {
2316 OS << (Rule.isSubRule() ? "ATTR_MATCH_SUB_RULE" : "ATTR_MATCH_RULE") << '(';
2317 OS << Rule.getEnumValueName() << ", \"" << Rule.getSpelling() << "\", "
2318 << Rule.isAbstractRule();
2319 if (Rule.isSubRule())
2320 OS << ", "
2321 << AttributeSubjectMatchRule(Rule.MetaSubject, nullptr).getEnumValue()
2322 << ", " << Rule.isNegatedSubRule();
2323 OS << ")\n";
2324 }
2325 OS << "#undef ATTR_MATCH_SUB_RULE\n";
2326}
2327
2328bool PragmaClangAttributeSupport::isAttributedSupported(
2329 const Record &Attribute) {
2330 // If the attribute explicitly specified whether to support #pragma clang
2331 // attribute, use that setting.
2332 bool Unset;
2333 bool SpecifiedResult =
2334 Attribute.getValueAsBitOrUnset(FieldName: "PragmaAttributeSupport", Unset);
2335 if (!Unset)
2336 return SpecifiedResult;
2337
2338 // Opt-out rules:
2339
2340 // An attribute requires delayed parsing (LateParsed is on).
2341 switch (getLateAttrParseKind(Attr: &Attribute)) {
2342 case LateAttrParseKind::Never:
2343 break;
2344 case LateAttrParseKind::Standard:
2345 return false;
2346 case LateAttrParseKind::ExperimentalExt:
2347 // This is only late parsed in certain parsing contexts when
2348 // `LangOpts.ExperimentalLateParseAttributes` is true. Information about the
2349 // parsing context and `LangOpts` is not available in this method so just
2350 // opt this attribute out.
2351 return false;
2352 }
2353
2354 // An attribute has no GNU/CXX11 spelling
2355 if (!hasGNUorCXX11Spelling(Attribute))
2356 return false;
2357 // An attribute subject list has a subject that isn't covered by one of the
2358 // subject match rules or has no subjects at all.
2359 if (Attribute.isValueUnset(FieldName: "Subjects"))
2360 return false;
2361 const Record *SubjectObj = Attribute.getValueAsDef(FieldName: "Subjects");
2362 bool HasAtLeastOneValidSubject = false;
2363 for (const auto *Subject : SubjectObj->getValueAsListOfDefs(FieldName: "Subjects")) {
2364 if (!isSupportedPragmaClangAttributeSubject(Subject: *Subject))
2365 continue;
2366 if (!SubjectsToRules.contains(Val: Subject))
2367 return false;
2368 HasAtLeastOneValidSubject = true;
2369 }
2370 return HasAtLeastOneValidSubject;
2371}
2372
2373static std::string GenerateTestExpression(ArrayRef<const Record *> LangOpts) {
2374 std::string Test;
2375
2376 for (auto *E : LangOpts) {
2377 if (!Test.empty())
2378 Test += " || ";
2379
2380 const StringRef Code = E->getValueAsString(FieldName: "CustomCode");
2381 if (!Code.empty()) {
2382 Test += "(";
2383 Test += Code;
2384 Test += ")";
2385 if (!E->getValueAsString(FieldName: "Name").empty()) {
2386 PrintWarning(
2387 WarningLoc: E->getLoc(),
2388 Msg: "non-empty 'Name' field ignored because 'CustomCode' was supplied");
2389 }
2390 } else {
2391 Test += "LangOpts.";
2392 Test += E->getValueAsString(FieldName: "Name");
2393 }
2394 }
2395
2396 if (Test.empty())
2397 return "true";
2398
2399 return Test;
2400}
2401
2402void
2403PragmaClangAttributeSupport::generateStrictConformsTo(const Record &Attr,
2404 raw_ostream &OS) {
2405 if (!isAttributedSupported(Attribute: Attr) || Attr.isValueUnset(FieldName: "Subjects"))
2406 return;
2407 // Generate a function that constructs a set of matching rules that describe
2408 // to which declarations the attribute should apply to.
2409 OS << "void getPragmaAttributeMatchRules("
2410 << "llvm::SmallVectorImpl<std::pair<"
2411 << AttributeSubjectMatchRule::EnumName
2412 << ", bool>> &MatchRules, const LangOptions &LangOpts) const override {\n";
2413 const Record *SubjectObj = Attr.getValueAsDef(FieldName: "Subjects");
2414 for (const auto *Subject : SubjectObj->getValueAsListOfDefs(FieldName: "Subjects")) {
2415 if (!isSupportedPragmaClangAttributeSubject(Subject: *Subject))
2416 continue;
2417 auto It = SubjectsToRules.find(Val: Subject);
2418 assert(It != SubjectsToRules.end() &&
2419 "This attribute is unsupported by #pragma clang attribute");
2420 for (const auto &Rule : It->getSecond().getAggregateRuleSet()) {
2421 // The rule might be language specific, so only subtract it from the given
2422 // rules if the specific language options are specified.
2423 std::vector<const Record *> LangOpts = Rule.getLangOpts();
2424 OS << " MatchRules.push_back(std::make_pair(" << Rule.getEnumValue()
2425 << ", /*IsSupported=*/" << GenerateTestExpression(LangOpts)
2426 << "));\n";
2427 }
2428 }
2429 OS << "}\n\n";
2430}
2431
2432void PragmaClangAttributeSupport::generateParsingHelpers(raw_ostream &OS) {
2433 // Generate routines that check the names of sub-rules.
2434 OS << "std::optional<attr::SubjectMatchRule> "
2435 "defaultIsAttributeSubjectMatchSubRuleFor(StringRef, bool) {\n";
2436 OS << " return std::nullopt;\n";
2437 OS << "}\n\n";
2438
2439 MapVector<const Record *, std::vector<AttributeSubjectMatchRule>>
2440 SubMatchRules;
2441 for (const auto &Rule : Rules) {
2442 if (!Rule.isSubRule())
2443 continue;
2444 SubMatchRules[Rule.MetaSubject].push_back(x: Rule);
2445 }
2446
2447 for (const auto &SubMatchRule : SubMatchRules) {
2448 OS << "std::optional<attr::SubjectMatchRule> "
2449 "isAttributeSubjectMatchSubRuleFor_"
2450 << SubMatchRule.first->getValueAsString(FieldName: "Name")
2451 << "(StringRef Name, bool IsUnless) {\n";
2452 OS << " if (IsUnless)\n";
2453 OS << " return "
2454 "llvm::StringSwitch<std::optional<attr::SubjectMatchRule>>(Name).\n";
2455 for (const auto &Rule : SubMatchRule.second) {
2456 if (Rule.isNegatedSubRule())
2457 OS << " Case(\"" << Rule.getName() << "\", " << Rule.getEnumValue()
2458 << ").\n";
2459 }
2460 OS << " Default(std::nullopt);\n";
2461 OS << " return "
2462 "llvm::StringSwitch<std::optional<attr::SubjectMatchRule>>(Name).\n";
2463 for (const auto &Rule : SubMatchRule.second) {
2464 if (!Rule.isNegatedSubRule())
2465 OS << " Case(\"" << Rule.getName() << "\", " << Rule.getEnumValue()
2466 << ").\n";
2467 }
2468 OS << " Default(std::nullopt);\n";
2469 OS << "}\n\n";
2470 }
2471
2472 // Generate the function that checks for the top-level rules.
2473 OS << "std::pair<std::optional<attr::SubjectMatchRule>, "
2474 "std::optional<attr::SubjectMatchRule> (*)(StringRef, "
2475 "bool)> isAttributeSubjectMatchRule(StringRef Name) {\n";
2476 OS << " return "
2477 "llvm::StringSwitch<std::pair<std::optional<attr::SubjectMatchRule>, "
2478 "std::optional<attr::SubjectMatchRule> (*) (StringRef, "
2479 "bool)>>(Name).\n";
2480 for (const auto &Rule : Rules) {
2481 if (Rule.isSubRule())
2482 continue;
2483 std::string SubRuleFunction;
2484 if (SubMatchRules.count(Key: Rule.MetaSubject))
2485 SubRuleFunction =
2486 ("isAttributeSubjectMatchSubRuleFor_" + Rule.getName()).str();
2487 else
2488 SubRuleFunction = "defaultIsAttributeSubjectMatchSubRuleFor";
2489 OS << " Case(\"" << Rule.getName() << "\", std::make_pair("
2490 << Rule.getEnumValue() << ", " << SubRuleFunction << ")).\n";
2491 }
2492 OS << " Default(std::make_pair(std::nullopt, "
2493 "defaultIsAttributeSubjectMatchSubRuleFor));\n";
2494 OS << "}\n\n";
2495
2496 // Generate the function that checks for the submatch rules.
2497 OS << "const char *validAttributeSubjectMatchSubRules("
2498 << AttributeSubjectMatchRule::EnumName << " Rule) {\n";
2499 OS << " switch (Rule) {\n";
2500 for (const auto &SubMatchRule : SubMatchRules) {
2501 OS << " case "
2502 << AttributeSubjectMatchRule(SubMatchRule.first, nullptr).getEnumValue()
2503 << ":\n";
2504 OS << " return \"'";
2505 bool IsFirst = true;
2506 for (const auto &Rule : SubMatchRule.second) {
2507 if (!IsFirst)
2508 OS << ", '";
2509 IsFirst = false;
2510 if (Rule.isNegatedSubRule())
2511 OS << "unless(";
2512 OS << Rule.getName();
2513 if (Rule.isNegatedSubRule())
2514 OS << ')';
2515 OS << "'";
2516 }
2517 OS << "\";\n";
2518 }
2519 OS << " default: return nullptr;\n";
2520 OS << " }\n";
2521 OS << "}\n\n";
2522}
2523
2524template <typename Fn> static void forEachSpelling(const Record &Attr, Fn &&F) {
2525 for (const FlattenedSpelling &S : GetFlattenedSpellings(Attr)) {
2526 F(S);
2527 }
2528}
2529
2530static std::map<StringRef, std::vector<const Record *>> NameToAttrsMap;
2531
2532/// Build a map from the attribute name to the Attrs that use that name. If more
2533/// than one Attr use a name, the arguments could be different so a more complex
2534/// check is needed in the generated switch.
2535static void generateNameToAttrsMap(const RecordKeeper &Records) {
2536 for (const auto *A : Records.getAllDerivedDefinitions(ClassName: "Attr")) {
2537 for (const FlattenedSpelling &S : GetFlattenedSpellings(Attr: *A)) {
2538 auto [It, Inserted] = NameToAttrsMap.try_emplace(k: S.name());
2539 if (Inserted || !is_contained(Range&: It->second, Element: A))
2540 It->second.emplace_back(args&: A);
2541 }
2542 }
2543}
2544
2545/// Generate the info needed to produce the case values in case more than one
2546/// attribute has the same name. Store the info in a map that can be processed
2547/// after all attributes are seen.
2548static void generateFlattenedSpellingInfo(const Record &Attr,
2549 std::map<StringRef, FSIVecTy> &Map,
2550 uint32_t ArgMask = 0) {
2551 std::string TargetTest;
2552 if (Attr.isSubClassOf(Name: "TargetSpecificAttr") &&
2553 !Attr.isValueUnset(FieldName: "ParseKind")) {
2554 const Record *T = Attr.getValueAsDef(FieldName: "Target");
2555 std::vector<StringRef> Arches = T->getValueAsListOfStrings(FieldName: "Arches");
2556 (void)GenerateTargetSpecificAttrChecks(R: T, Arches, Test&: TargetTest, FnName: nullptr);
2557 }
2558
2559 forEachSpelling(Attr, F: [&](const FlattenedSpelling &S) {
2560 Map[S.name()].emplace_back(args: S.variety(), args: S.nameSpace(), args&: TargetTest, args&: ArgMask);
2561 });
2562}
2563
2564static bool nameAppliesToOneAttribute(StringRef Name) {
2565 auto It = NameToAttrsMap.find(x: Name);
2566 assert(It != NameToAttrsMap.end());
2567 return It->second.size() == 1;
2568}
2569
2570static bool emitIfSimpleValue(StringRef Name, uint32_t ArgMask,
2571 raw_ostream &OS) {
2572 if (nameAppliesToOneAttribute(Name)) {
2573 OS << ".Case(\"" << Name << "\", ";
2574 if (ArgMask != 0)
2575 OS << ArgMask << ")\n";
2576 else
2577 OS << "true)\n";
2578 return true;
2579 }
2580 return false;
2581}
2582
2583static void emitSingleCondition(const FlattenedSpellingInfo &FSI,
2584 raw_ostream &OS) {
2585 OS << "(Syntax==AttributeCommonInfo::AS_" << FSI.Syntax << " && ";
2586 if (!FSI.Scope.empty())
2587 OS << "ScopeName && ScopeName->getName()==\"" << FSI.Scope << "\"";
2588 else
2589 OS << "!ScopeName";
2590 if (!FSI.TargetTest.empty())
2591 OS << " && " << FSI.TargetTest;
2592 OS << ")";
2593}
2594
2595static void emitStringSwitchCases(std::map<StringRef, FSIVecTy> &Map,
2596 raw_ostream &OS) {
2597 for (const auto &[Name, Vec] : Map) {
2598 if (emitIfSimpleValue(Name, ArgMask: Vec[0].ArgMask, OS))
2599 continue;
2600
2601 // Not simple, build expressions for each case.
2602 OS << ".Case(\"" << Name << "\", ";
2603 for (unsigned I = 0, E = Vec.size(); I < E; ++I) {
2604 emitSingleCondition(FSI: Vec[I], OS);
2605 uint32_t ArgMask = Vec[I].ArgMask;
2606 if (E == 1 && ArgMask == 0)
2607 continue;
2608
2609 // More than one or it's the Mask form. Create a conditional expression.
2610 uint32_t SuccessValue = ArgMask != 0 ? ArgMask : 1;
2611 OS << " ? " << SuccessValue << " : ";
2612 if (I == E - 1)
2613 OS << 0;
2614 }
2615 OS << ")\n";
2616 }
2617}
2618
2619static bool isTypeArgument(const Record *Arg) {
2620 return !Arg->getDirectSuperClasses().empty() &&
2621 Arg->getDirectSuperClasses().back().first->getName() == "TypeArgument";
2622}
2623
2624/// Emits the first-argument-is-type property for attributes.
2625static void emitClangAttrTypeArgList(const RecordKeeper &Records,
2626 raw_ostream &OS) {
2627 OS << "#if defined(CLANG_ATTR_TYPE_ARG_LIST)\n";
2628 std::map<StringRef, FSIVecTy> FSIMap;
2629 for (const auto *Attr : Records.getAllDerivedDefinitions(ClassName: "Attr")) {
2630 // Determine whether the first argument is a type.
2631 std::vector<const Record *> Args = Attr->getValueAsListOfDefs(FieldName: "Args");
2632 if (Args.empty())
2633 continue;
2634
2635 if (!isTypeArgument(Arg: Args[0]))
2636 continue;
2637 generateFlattenedSpellingInfo(Attr: *Attr, Map&: FSIMap);
2638 }
2639 emitStringSwitchCases(Map&: FSIMap, OS);
2640 OS << "#endif // CLANG_ATTR_TYPE_ARG_LIST\n\n";
2641}
2642
2643/// Emits the parse-arguments-in-unevaluated-context property for
2644/// attributes.
2645static void emitClangAttrArgContextList(const RecordKeeper &Records,
2646 raw_ostream &OS) {
2647 OS << "#if defined(CLANG_ATTR_ARG_CONTEXT_LIST)\n";
2648 std::map<StringRef, FSIVecTy> FSIMap;
2649 ParsedAttrMap Attrs = getParsedAttrList(Records);
2650 for (const auto &I : Attrs) {
2651 const Record &Attr = *I.second;
2652
2653 if (!Attr.getValueAsBit(FieldName: "ParseArgumentsAsUnevaluated"))
2654 continue;
2655 generateFlattenedSpellingInfo(Attr, Map&: FSIMap);
2656 }
2657 emitStringSwitchCases(Map&: FSIMap, OS);
2658 OS << "#endif // CLANG_ATTR_ARG_CONTEXT_LIST\n\n";
2659}
2660
2661static bool isIdentifierArgument(const Record *Arg) {
2662 return !Arg->getDirectSuperClasses().empty() &&
2663 StringSwitch<bool>(
2664 Arg->getDirectSuperClasses().back().first->getName())
2665 .Case(S: "IdentifierArgument", Value: true)
2666 .Case(S: "EnumArgument", Value: true)
2667 .Case(S: "VariadicEnumArgument", Value: true)
2668 .Default(Value: false);
2669}
2670
2671static bool isVariadicIdentifierArgument(const Record *Arg) {
2672 return !Arg->getDirectSuperClasses().empty() &&
2673 StringSwitch<bool>(
2674 Arg->getDirectSuperClasses().back().first->getName())
2675 .Case(S: "VariadicIdentifierArgument", Value: true)
2676 .Case(S: "VariadicParamOrParamIdxArgument", Value: true)
2677 .Default(Value: false);
2678}
2679
2680static bool isVariadicExprArgument(const Record *Arg) {
2681 return !Arg->getDirectSuperClasses().empty() &&
2682 StringSwitch<bool>(
2683 Arg->getDirectSuperClasses().back().first->getName())
2684 .Case(S: "VariadicExprArgument", Value: true)
2685 .Default(Value: false);
2686}
2687
2688static bool isStringLiteralArgument(const Record *Arg) {
2689 if (Arg->getDirectSuperClasses().empty())
2690 return false;
2691 StringRef ArgKind = Arg->getDirectSuperClasses().back().first->getName();
2692 if (ArgKind == "EnumArgument")
2693 return Arg->getValueAsBit(FieldName: "IsString");
2694 return ArgKind == "StringArgument";
2695}
2696
2697static bool isVariadicStringLiteralArgument(const Record *Arg) {
2698 if (Arg->getDirectSuperClasses().empty())
2699 return false;
2700 StringRef ArgKind = Arg->getDirectSuperClasses().back().first->getName();
2701 if (ArgKind == "VariadicEnumArgument")
2702 return Arg->getValueAsBit(FieldName: "IsString");
2703 return ArgKind == "VariadicStringArgument";
2704}
2705
2706static void emitClangAttrVariadicIdentifierArgList(const RecordKeeper &Records,
2707 raw_ostream &OS) {
2708 OS << "#if defined(CLANG_ATTR_VARIADIC_IDENTIFIER_ARG_LIST)\n";
2709 std::map<StringRef, FSIVecTy> FSIMap;
2710 for (const auto *A : Records.getAllDerivedDefinitions(ClassName: "Attr")) {
2711 // Determine whether the first argument is a variadic identifier.
2712 std::vector<const Record *> Args = A->getValueAsListOfDefs(FieldName: "Args");
2713 if (Args.empty() || !isVariadicIdentifierArgument(Arg: Args[0]))
2714 continue;
2715 generateFlattenedSpellingInfo(Attr: *A, Map&: FSIMap);
2716 }
2717 emitStringSwitchCases(Map&: FSIMap, OS);
2718 OS << "#endif // CLANG_ATTR_VARIADIC_IDENTIFIER_ARG_LIST\n\n";
2719}
2720
2721// Emits the list of arguments that should be parsed as unevaluated string
2722// literals for each attribute.
2723static void
2724emitClangAttrUnevaluatedStringLiteralList(const RecordKeeper &Records,
2725 raw_ostream &OS) {
2726 OS << "#if defined(CLANG_ATTR_STRING_LITERAL_ARG_LIST)\n";
2727
2728 auto MakeMask = [](ArrayRef<const Record *> Args) {
2729 uint32_t Bits = 0;
2730 assert(Args.size() <= 32 && "unsupported number of arguments in attribute");
2731 for (uint32_t N = 0; N < Args.size(); ++N) {
2732 Bits |= (isStringLiteralArgument(Arg: Args[N]) << N);
2733 // If we have a variadic string argument, set all the remaining bits to 1
2734 if (isVariadicStringLiteralArgument(Arg: Args[N])) {
2735 Bits |= maskTrailingZeros<decltype(Bits)>(N);
2736 break;
2737 }
2738 }
2739 return Bits;
2740 };
2741
2742 std::map<StringRef, FSIVecTy> FSIMap;
2743 for (const auto *Attr : Records.getAllDerivedDefinitions(ClassName: "Attr")) {
2744 // Determine whether there are any string arguments.
2745 uint32_t ArgMask = MakeMask(Attr->getValueAsListOfDefs(FieldName: "Args"));
2746 if (!ArgMask)
2747 continue;
2748 generateFlattenedSpellingInfo(Attr: *Attr, Map&: FSIMap, ArgMask);
2749 }
2750 emitStringSwitchCases(Map&: FSIMap, OS);
2751 OS << "#endif // CLANG_ATTR_STRING_LITERAL_ARG_LIST\n\n";
2752}
2753
2754// Emits the first-argument-is-identifier property for attributes.
2755static void emitClangAttrIdentifierArgList(const RecordKeeper &Records,
2756 raw_ostream &OS) {
2757 OS << "#if defined(CLANG_ATTR_IDENTIFIER_ARG_LIST)\n";
2758 std::map<StringRef, FSIVecTy> FSIMap;
2759 for (const auto *Attr : Records.getAllDerivedDefinitions(ClassName: "Attr")) {
2760 // Determine whether the first argument is an identifier.
2761 std::vector<const Record *> Args = Attr->getValueAsListOfDefs(FieldName: "Args");
2762 if (Args.empty() || !isIdentifierArgument(Arg: Args[0]))
2763 continue;
2764 generateFlattenedSpellingInfo(Attr: *Attr, Map&: FSIMap);
2765 }
2766 emitStringSwitchCases(Map&: FSIMap, OS);
2767 OS << "#endif // CLANG_ATTR_IDENTIFIER_ARG_LIST\n\n";
2768}
2769
2770// Emits the list for attributes having StrictEnumParameters.
2771static void emitClangAttrStrictIdentifierArgList(const RecordKeeper &Records,
2772 raw_ostream &OS) {
2773 OS << "#if defined(CLANG_ATTR_STRICT_IDENTIFIER_ARG_LIST)\n";
2774 std::map<StringRef, FSIVecTy> FSIMap;
2775 for (const auto *Attr : Records.getAllDerivedDefinitions(ClassName: "Attr")) {
2776 if (!Attr->getValueAsBit(FieldName: "StrictEnumParameters"))
2777 continue;
2778 // Check that there is really an identifier argument.
2779 std::vector<const Record *> Args = Attr->getValueAsListOfDefs(FieldName: "Args");
2780 if (none_of(Range&: Args, P: [&](const Record *R) { return isIdentifierArgument(Arg: R); }))
2781 continue;
2782 generateFlattenedSpellingInfo(Attr: *Attr, Map&: FSIMap);
2783 }
2784 emitStringSwitchCases(Map&: FSIMap, OS);
2785 OS << "#endif // CLANG_ATTR_STRICT_IDENTIFIER_ARG_LIST\n\n";
2786}
2787
2788static bool keywordThisIsaIdentifierInArgument(const Record *Arg) {
2789 return !Arg->getDirectSuperClasses().empty() &&
2790 StringSwitch<bool>(
2791 Arg->getDirectSuperClasses().back().first->getName())
2792 .Case(S: "VariadicParamOrParamIdxArgument", Value: true)
2793 .Default(Value: false);
2794}
2795
2796static void emitClangAttrThisIsaIdentifierArgList(const RecordKeeper &Records,
2797 raw_ostream &OS) {
2798 OS << "#if defined(CLANG_ATTR_THIS_ISA_IDENTIFIER_ARG_LIST)\n";
2799 std::map<StringRef, FSIVecTy> FSIMap;
2800 for (const auto *A : Records.getAllDerivedDefinitions(ClassName: "Attr")) {
2801 // Determine whether the first argument is a variadic identifier.
2802 std::vector<const Record *> Args = A->getValueAsListOfDefs(FieldName: "Args");
2803 if (Args.empty() || !keywordThisIsaIdentifierInArgument(Arg: Args[0]))
2804 continue;
2805 generateFlattenedSpellingInfo(Attr: *A, Map&: FSIMap);
2806 }
2807 emitStringSwitchCases(Map&: FSIMap, OS);
2808 OS << "#endif // CLANG_ATTR_THIS_ISA_IDENTIFIER_ARG_LIST\n\n";
2809}
2810
2811static void emitClangAttrAcceptsExprPack(const RecordKeeper &Records,
2812 raw_ostream &OS) {
2813 OS << "#if defined(CLANG_ATTR_ACCEPTS_EXPR_PACK)\n";
2814 ParsedAttrMap Attrs = getParsedAttrList(Records);
2815 std::map<StringRef, FSIVecTy> FSIMap;
2816 for (const auto &I : Attrs) {
2817 const Record &Attr = *I.second;
2818
2819 if (!Attr.getValueAsBit(FieldName: "AcceptsExprPack"))
2820 continue;
2821 generateFlattenedSpellingInfo(Attr, Map&: FSIMap);
2822 }
2823 emitStringSwitchCases(Map&: FSIMap, OS);
2824 OS << "#endif // CLANG_ATTR_ACCEPTS_EXPR_PACK\n\n";
2825}
2826
2827static bool isRegularKeywordAttribute(const FlattenedSpelling &S) {
2828 return (S.variety() == "Keyword" &&
2829 !S.getSpellingRecord().getValueAsBit(FieldName: "HasOwnParseRules"));
2830}
2831
2832static void emitFormInitializer(raw_ostream &OS,
2833 const FlattenedSpelling &Spelling,
2834 StringRef SpellingIndex) {
2835 bool IsAlignas =
2836 (Spelling.variety() == "Keyword" && Spelling.name() == "alignas");
2837 OS << "{AttributeCommonInfo::AS_" << Spelling.variety() << ", "
2838 << SpellingIndex << ", " << (IsAlignas ? "true" : "false")
2839 << " /*IsAlignas*/, "
2840 << (isRegularKeywordAttribute(S: Spelling) ? "true" : "false")
2841 << " /*IsRegularKeywordAttribute*/}";
2842}
2843
2844static void emitAttributes(const RecordKeeper &Records, raw_ostream &OS,
2845 bool Header) {
2846 ParsedAttrMap AttrMap = getParsedAttrList(Records);
2847
2848 // Helper to print the starting character of an attribute argument. If there
2849 // hasn't been an argument yet, it prints an opening parenthese; otherwise it
2850 // prints a comma.
2851 OS << "static inline void DelimitAttributeArgument("
2852 << "raw_ostream& OS, bool& IsFirst) {\n"
2853 << " if (IsFirst) {\n"
2854 << " IsFirst = false;\n"
2855 << " OS << \"(\";\n"
2856 << " } else\n"
2857 << " OS << \", \";\n"
2858 << "}\n";
2859
2860 for (const auto *Attr : Records.getAllDerivedDefinitions(ClassName: "Attr")) {
2861 const Record &R = *Attr;
2862
2863 // FIXME: Currently, documentation is generated as-needed due to the fact
2864 // that there is no way to allow a generated project "reach into" the docs
2865 // directory (for instance, it may be an out-of-tree build). However, we want
2866 // to ensure that every attribute has a Documentation field, and produce an
2867 // error if it has been neglected. Otherwise, the on-demand generation which
2868 // happens server-side will fail. This code is ensuring that functionality,
2869 // even though this Emitter doesn't technically need the documentation.
2870 // When attribute documentation can be generated as part of the build
2871 // itself, this code can be removed.
2872 (void)R.getValueAsListOfDefs(FieldName: "Documentation");
2873
2874 if (!R.getValueAsBit(FieldName: "ASTNode"))
2875 continue;
2876
2877 std::vector<const Record *> Supers = R.getSuperClasses();
2878 assert(!Supers.empty() && "Forgot to specify a superclass for the attr");
2879 std::string SuperName;
2880 bool Inheritable = false;
2881 for (const Record *R : reverse(C&: Supers)) {
2882 if (R->getName() != "TargetSpecificAttr" &&
2883 R->getName() != "DeclOrTypeAttr" && SuperName.empty())
2884 SuperName = R->getName().str();
2885 if (R->getName() == "InheritableAttr")
2886 Inheritable = true;
2887 }
2888
2889 if (Header)
2890 OS << "class CLANG_ABI " << R.getName() << "Attr : public " << SuperName
2891 << " {\n";
2892 else
2893 OS << "\n// " << R.getName() << "Attr implementation\n\n";
2894
2895 std::vector<const Record *> ArgRecords = R.getValueAsListOfDefs(FieldName: "Args");
2896 std::vector<std::unique_ptr<Argument>> Args;
2897 Args.reserve(n: ArgRecords.size());
2898
2899 bool AttrAcceptsExprPack = Attr->getValueAsBit(FieldName: "AcceptsExprPack");
2900 if (AttrAcceptsExprPack) {
2901 for (size_t I = 0; I < ArgRecords.size(); ++I) {
2902 const Record *ArgR = ArgRecords[I];
2903 if (isIdentifierArgument(Arg: ArgR) || isVariadicIdentifierArgument(Arg: ArgR) ||
2904 isTypeArgument(Arg: ArgR))
2905 PrintFatalError(ErrorLoc: Attr->getLoc(),
2906 Msg: "Attributes accepting packs cannot also "
2907 "have identifier or type arguments.");
2908 // When trying to determine if value-dependent expressions can populate
2909 // the attribute without prior instantiation, the decision is made based
2910 // on the assumption that only the last argument is ever variadic.
2911 if (I < (ArgRecords.size() - 1) && isVariadicExprArgument(Arg: ArgR))
2912 PrintFatalError(ErrorLoc: Attr->getLoc(),
2913 Msg: "Attributes accepting packs can only have the last "
2914 "argument be variadic.");
2915 }
2916 }
2917
2918 bool HasOptArg = false;
2919 bool HasFakeArg = false;
2920 for (const auto *ArgRecord : ArgRecords) {
2921 Args.emplace_back(args: createArgument(Arg: *ArgRecord, Attr: R.getName()));
2922 if (Header) {
2923 Args.back()->writeDeclarations(OS);
2924 OS << "\n\n";
2925 }
2926
2927 // For these purposes, fake takes priority over optional.
2928 if (Args.back()->isFake()) {
2929 HasFakeArg = true;
2930 } else if (Args.back()->isOptional()) {
2931 HasOptArg = true;
2932 }
2933 }
2934
2935 std::unique_ptr<VariadicExprArgument> DelayedArgs = nullptr;
2936 if (AttrAcceptsExprPack) {
2937 DelayedArgs =
2938 std::make_unique<VariadicExprArgument>(args: "DelayedArgs", args: R.getName());
2939 if (Header) {
2940 DelayedArgs->writeDeclarations(OS);
2941 OS << "\n\n";
2942 }
2943 }
2944
2945 if (Header)
2946 OS << "public:\n";
2947
2948 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(Attr: R);
2949
2950 // If there are zero or one spellings, all spelling-related functionality
2951 // can be elided. If all of the spellings share the same name, the spelling
2952 // functionality can also be elided.
2953 bool ElideSpelling = (Spellings.size() <= 1) ||
2954 SpellingNamesAreCommon(Spellings);
2955
2956 // This maps spelling index values to semantic Spelling enumerants.
2957 SemanticSpellingMap SemanticToSyntacticMap;
2958
2959 std::string SpellingEnum;
2960 if (Spellings.size() > 1)
2961 SpellingEnum = CreateSemanticSpellings(Spellings, Map&: SemanticToSyntacticMap);
2962 if (Header)
2963 OS << SpellingEnum;
2964
2965 const auto &ParsedAttrSpellingItr =
2966 find_if(Range&: AttrMap, P: [R](const std::pair<std::string, const Record *> &P) {
2967 return &R == P.second;
2968 });
2969
2970 // Emit CreateImplicit factory methods.
2971 auto emitCreate = [&](bool Implicit, bool DelayedArgsOnly, bool emitFake) {
2972 if (Header)
2973 OS << " static ";
2974 OS << R.getName() << "Attr *";
2975 if (!Header)
2976 OS << R.getName() << "Attr::";
2977 OS << "Create";
2978 if (Implicit)
2979 OS << "Implicit";
2980 if (DelayedArgsOnly)
2981 OS << "WithDelayedArgs";
2982 OS << "(";
2983 OS << "ASTContext &Ctx";
2984 if (!DelayedArgsOnly) {
2985 for (auto const &ai : Args) {
2986 if (ai->isFake() && !emitFake)
2987 continue;
2988 OS << ", ";
2989 ai->writeCtorParameters(OS);
2990 }
2991 } else {
2992 OS << ", ";
2993 DelayedArgs->writeCtorParameters(OS);
2994 }
2995 OS << ", const AttributeCommonInfo &CommonInfo";
2996 OS << ")";
2997 if (Header) {
2998 OS << ";\n";
2999 return;
3000 }
3001
3002 OS << " {\n";
3003 OS << " auto *A = new (Ctx) " << R.getName();
3004 OS << "Attr(Ctx, CommonInfo";
3005
3006 if (!DelayedArgsOnly) {
3007 for (auto const &ai : Args) {
3008 if (ai->isFake() && !emitFake)
3009 continue;
3010 OS << ", ";
3011 ai->writeImplicitCtorArgs(OS);
3012 }
3013 }
3014 OS << ");\n";
3015 if (Implicit) {
3016 OS << " A->setImplicit(true);\n";
3017 }
3018 if (Implicit || ElideSpelling) {
3019 OS << " if (!A->isAttributeSpellingListCalculated() && "
3020 "!A->getAttrName())\n";
3021 OS << " A->setAttributeSpellingListIndex(0);\n";
3022 }
3023 if (DelayedArgsOnly) {
3024 OS << " A->setDelayedArgs(Ctx, ";
3025 DelayedArgs->writeImplicitCtorArgs(OS);
3026 OS << ");\n";
3027 }
3028 OS << " return A;\n}\n\n";
3029 };
3030
3031 auto emitCreateNoCI = [&](bool Implicit, bool DelayedArgsOnly,
3032 bool emitFake) {
3033 if (Header)
3034 OS << " static ";
3035 OS << R.getName() << "Attr *";
3036 if (!Header)
3037 OS << R.getName() << "Attr::";
3038 OS << "Create";
3039 if (Implicit)
3040 OS << "Implicit";
3041 if (DelayedArgsOnly)
3042 OS << "WithDelayedArgs";
3043 OS << "(";
3044 OS << "ASTContext &Ctx";
3045 if (!DelayedArgsOnly) {
3046 for (auto const &ai : Args) {
3047 if (ai->isFake() && !emitFake)
3048 continue;
3049 OS << ", ";
3050 ai->writeCtorParameters(OS);
3051 }
3052 } else {
3053 OS << ", ";
3054 DelayedArgs->writeCtorParameters(OS);
3055 }
3056 OS << ", SourceRange Range";
3057 if (Header)
3058 OS << " = {}";
3059 if (Spellings.size() > 1) {
3060 OS << ", Spelling S";
3061 if (Header)
3062 OS << " = " << SemanticToSyntacticMap[0];
3063 }
3064 OS << ")";
3065 if (Header) {
3066 OS << ";\n";
3067 return;
3068 }
3069
3070 OS << " {\n";
3071 OS << " AttributeCommonInfo I(Range, ";
3072
3073 if (ParsedAttrSpellingItr != std::end(cont&: AttrMap))
3074 OS << "AT_" << ParsedAttrSpellingItr->first;
3075 else
3076 OS << "NoSemaHandlerAttribute";
3077
3078 if (Spellings.size() == 0) {
3079 OS << ", AttributeCommonInfo::Form::Implicit()";
3080 } else if (Spellings.size() == 1) {
3081 OS << ", ";
3082 emitFormInitializer(OS, Spelling: Spellings[0], SpellingIndex: "0");
3083 } else {
3084 OS << ", [&]() {\n";
3085 OS << " switch (S) {\n";
3086 std::set<std::string> Uniques;
3087 unsigned Idx = 0;
3088 for (auto I = Spellings.begin(), E = Spellings.end(); I != E;
3089 ++I, ++Idx) {
3090 const FlattenedSpelling &S = *I;
3091 const auto &Name = SemanticToSyntacticMap[Idx];
3092 if (Uniques.insert(x: Name).second) {
3093 OS << " case " << Name << ":\n";
3094 OS << " return AttributeCommonInfo::Form";
3095 emitFormInitializer(OS, Spelling: S, SpellingIndex: Name);
3096 OS << ";\n";
3097 }
3098 }
3099 OS << " default:\n";
3100 OS << " llvm_unreachable(\"Unknown attribute spelling!\");\n"
3101 << " return AttributeCommonInfo::Form";
3102 emitFormInitializer(OS, Spelling: Spellings[0], SpellingIndex: "0");
3103 OS << ";\n"
3104 << " }\n"
3105 << " }()";
3106 }
3107
3108 OS << ");\n";
3109 OS << " return Create";
3110 if (Implicit)
3111 OS << "Implicit";
3112 if (DelayedArgsOnly)
3113 OS << "WithDelayedArgs";
3114 OS << "(Ctx";
3115 if (!DelayedArgsOnly) {
3116 for (auto const &ai : Args) {
3117 if (ai->isFake() && !emitFake)
3118 continue;
3119 OS << ", ";
3120 ai->writeImplicitCtorArgs(OS);
3121 }
3122 } else {
3123 OS << ", ";
3124 DelayedArgs->writeImplicitCtorArgs(OS);
3125 }
3126 OS << ", I);\n";
3127 OS << "}\n\n";
3128 };
3129
3130 auto emitCreates = [&](bool DelayedArgsOnly, bool emitFake) {
3131 emitCreate(true, DelayedArgsOnly, emitFake);
3132 emitCreate(false, DelayedArgsOnly, emitFake);
3133 emitCreateNoCI(true, DelayedArgsOnly, emitFake);
3134 emitCreateNoCI(false, DelayedArgsOnly, emitFake);
3135 };
3136
3137 if (Header)
3138 OS << " // Factory methods\n";
3139
3140 // Emit a CreateImplicit that takes all the arguments.
3141 emitCreates(false, true);
3142
3143 // Emit a CreateImplicit that takes all the non-fake arguments.
3144 if (HasFakeArg)
3145 emitCreates(false, false);
3146
3147 // Emit a CreateWithDelayedArgs that takes only the dependent argument
3148 // expressions.
3149 if (DelayedArgs)
3150 emitCreates(true, false);
3151
3152 // Emit constructors.
3153 auto emitCtor = [&](bool emitOpt, bool emitFake, bool emitNoArgs) {
3154 auto shouldEmitArg = [=](const std::unique_ptr<Argument> &arg) {
3155 if (emitNoArgs)
3156 return false;
3157 if (arg->isFake())
3158 return emitFake;
3159 if (arg->isOptional())
3160 return emitOpt;
3161 return true;
3162 };
3163 if (Header)
3164 OS << " ";
3165 else
3166 OS << R.getName() << "Attr::";
3167 OS << R.getName()
3168 << "Attr(ASTContext &Ctx, const AttributeCommonInfo &CommonInfo";
3169 OS << '\n';
3170 for (auto const &ai : Args) {
3171 if (!shouldEmitArg(ai))
3172 continue;
3173 OS << " , ";
3174 ai->writeCtorParameters(OS);
3175 OS << "\n";
3176 }
3177
3178 OS << " )";
3179 if (Header) {
3180 OS << ";\n";
3181 return;
3182 }
3183 OS << "\n : " << SuperName << "(Ctx, CommonInfo, ";
3184 OS << "attr::" << R.getName() << ", ";
3185
3186 // Handle different late parsing modes.
3187 OS << "/*IsLateParsed=*/";
3188 switch (getLateAttrParseKind(Attr: &R)) {
3189 case LateAttrParseKind::Never:
3190 OS << "false";
3191 break;
3192 case LateAttrParseKind::ExperimentalExt:
3193 // Currently no clients need to know the distinction between `Standard`
3194 // and `ExperimentalExt` so treat `ExperimentalExt` just like
3195 // `Standard` for now.
3196 case LateAttrParseKind::Standard:
3197 // Note: This is misleading. `IsLateParsed` doesn't mean the
3198 // attribute was actually late parsed. Instead it means the attribute in
3199 // `Attr.td` is marked as being late parsed. Maybe it should be called
3200 // `IsLateParseable`?
3201 OS << "true";
3202 break;
3203 }
3204
3205 if (Inheritable) {
3206 OS << ", "
3207 << (R.getValueAsBit(FieldName: "InheritEvenIfAlreadyPresent") ? "true"
3208 : "false");
3209 }
3210 OS << ")\n";
3211
3212 for (auto const &ai : Args) {
3213 OS << " , ";
3214 if (!shouldEmitArg(ai)) {
3215 ai->writeCtorDefaultInitializers(OS);
3216 } else {
3217 ai->writeCtorInitializers(OS);
3218 }
3219 OS << "\n";
3220 }
3221 if (DelayedArgs) {
3222 OS << " , ";
3223 DelayedArgs->writeCtorDefaultInitializers(OS);
3224 OS << "\n";
3225 }
3226
3227 OS << " {\n";
3228
3229 for (auto const &ai : Args) {
3230 if (!shouldEmitArg(ai))
3231 continue;
3232 ai->writeCtorBody(OS);
3233 }
3234 OS << "}\n\n";
3235 };
3236
3237 if (Header)
3238 OS << "\n // Constructors\n";
3239
3240 // Emit a constructor that includes all the arguments.
3241 // This is necessary for cloning.
3242 emitCtor(true, true, false);
3243
3244 // Emit a constructor that takes all the non-fake arguments.
3245 if (HasFakeArg)
3246 emitCtor(true, false, false);
3247
3248 // Emit a constructor that takes all the non-fake, non-optional arguments.
3249 if (HasOptArg)
3250 emitCtor(false, false, false);
3251
3252 // Emit constructors that takes no arguments if none already exists.
3253 // This is used for delaying arguments.
3254 bool HasRequiredArgs =
3255 count_if(Range&: Args, P: [=](const std::unique_ptr<Argument> &arg) {
3256 return !arg->isFake() && !arg->isOptional();
3257 });
3258 if (DelayedArgs && HasRequiredArgs)
3259 emitCtor(false, false, true);
3260
3261 if (Header) {
3262 OS << '\n';
3263 OS << " " << R.getName() << "Attr *clone(ASTContext &C) const;\n";
3264 OS << " void printPretty(raw_ostream &OS,\n"
3265 << " const PrintingPolicy &Policy) const;\n";
3266 OS << " const char *getSpelling() const;\n";
3267 }
3268
3269 if (!ElideSpelling) {
3270 assert(!SemanticToSyntacticMap.empty() && "Empty semantic mapping list");
3271 if (Header)
3272 OS << " Spelling getSemanticSpelling() const;\n";
3273 else {
3274 OS << R.getName() << "Attr::Spelling " << R.getName()
3275 << "Attr::getSemanticSpelling() const {\n";
3276 WriteSemanticSpellingSwitch(VarName: "getAttributeSpellingListIndex()",
3277 Map: SemanticToSyntacticMap, OS);
3278 OS << "}\n";
3279 }
3280 }
3281
3282 if (Header)
3283 writeAttrAccessorDefinition(R, OS);
3284
3285 for (auto const &ai : Args) {
3286 if (Header) {
3287 ai->writeAccessors(OS);
3288 } else {
3289 ai->writeAccessorDefinitions(OS);
3290 }
3291 OS << "\n\n";
3292
3293 // Don't write conversion routines for fake arguments.
3294 if (ai->isFake()) continue;
3295
3296 if (ai->isEnumArg())
3297 static_cast<const EnumArgument *>(ai.get())->writeConversion(OS,
3298 Header);
3299 else if (ai->isVariadicEnumArg())
3300 static_cast<const VariadicEnumArgument *>(ai.get())->writeConversion(
3301 OS, Header);
3302 }
3303
3304 std::string FnStr = "isEquivalent(const ";
3305 FnStr += R.getName();
3306 FnStr += "Attr &Other, StructuralEquivalenceContext &Context) const";
3307 if (Header) {
3308 OS << " bool " << FnStr << ";\n";
3309 } else {
3310 OS << "bool " << R.getName() << "Attr::" << FnStr << " {\n";
3311 std::string CustomFn = R.getValueAsString(FieldName: "comparisonFn").str();
3312 if (CustomFn.empty()) {
3313 if (!ElideSpelling)
3314 OS << " if (getSpelling() != Other.getSpelling()) return false;\n\n";
3315 for (const auto &ai : Args) {
3316 OS << " if (!" << ai->emitAttrArgEqualityCheck() << ")\n";
3317 OS << " return false;\n";
3318 }
3319 OS << " return true;\n";
3320 } else {
3321 OS << " return " + CustomFn + "(*this, Other, Context);\n";
3322 }
3323 OS << "}\n\n";
3324 }
3325
3326 StringRef ProfileSig = "Profile(llvm::FoldingSetNodeID &ID, "
3327 "const ASTContext &Ctx) const";
3328 if (Header) {
3329 OS << " void " << ProfileSig << ";\n";
3330 } else {
3331 OS << "void " << R.getName() << "Attr::" << ProfileSig << " {\n";
3332 std::string CustomFn = R.getValueAsString(FieldName: "profileFn").str();
3333 if (CustomFn.empty()) {
3334 for (const auto &ai : Args)
3335 OS << " " << ai->emitAttrArgProfileCall() << ";\n";
3336 } else {
3337 OS << " " << CustomFn << "(*this, ID, Ctx);\n";
3338 }
3339 OS << "}\n\n";
3340 }
3341
3342 if (Header) {
3343 if (DelayedArgs) {
3344 DelayedArgs->writeAccessors(OS);
3345 DelayedArgs->writeSetter(OS);
3346 }
3347
3348 OS << R.getValueAsString(FieldName: "AdditionalMembers");
3349 OS << "\n\n";
3350
3351 OS << " static bool classof(const Attr *A) { return A->getKind() == "
3352 << "attr::" << R.getName() << "; }\n";
3353
3354 OS << "};\n\n";
3355 } else {
3356 if (DelayedArgs)
3357 DelayedArgs->writeAccessorDefinitions(OS);
3358
3359 OS << R.getName() << "Attr *" << R.getName()
3360 << "Attr::clone(ASTContext &C) const {\n";
3361 OS << " auto *A = new (C) " << R.getName() << "Attr(C, *this";
3362 for (auto const &ai : Args) {
3363 OS << ", ";
3364 ai->writeCloneArgs(OS);
3365 }
3366 OS << ");\n";
3367 OS << " A->Inherited = Inherited;\n";
3368 OS << " A->IsPackExpansion = IsPackExpansion;\n";
3369 OS << " A->setImplicit(Implicit);\n";
3370 if (DelayedArgs) {
3371 OS << " A->setDelayedArgs(C, ";
3372 DelayedArgs->writeCloneArgs(OS);
3373 OS << ");\n";
3374 }
3375 OS << " return A;\n}\n\n";
3376
3377 writePrettyPrintFunction(R, Args, OS);
3378 writeGetSpellingFunction(R, OS);
3379 }
3380 }
3381}
3382// Emits the class definitions for attributes.
3383void clang::EmitClangAttrClass(const RecordKeeper &Records, raw_ostream &OS) {
3384 emitSourceFileHeader(Desc: "Attribute classes' definitions", OS, Record: Records);
3385
3386 OS << "#ifndef LLVM_CLANG_ATTR_CLASSES_INC\n";
3387 OS << "#define LLVM_CLANG_ATTR_CLASSES_INC\n";
3388
3389 emitAttributes(Records, OS, Header: true);
3390
3391 OS << "#endif // LLVM_CLANG_ATTR_CLASSES_INC\n";
3392}
3393
3394static void emitEquivalenceFunction(const RecordKeeper &Records,
3395 raw_ostream &OS) {
3396 OS << "bool Attr::isEquivalent(const Attr &Other, "
3397 "StructuralEquivalenceContext &Context) const {\n";
3398 OS << "if (getKind() != Other.getKind()) return false;\n\n";
3399 OS << " switch (getKind()) {\n";
3400 for (const auto *Attr : Records.getAllDerivedDefinitions(ClassName: "Attr")) {
3401 const Record &R = *Attr;
3402 if (!R.getValueAsBit(FieldName: "ASTNode"))
3403 continue;
3404
3405 OS << " case attr::" << R.getName() << ":\n";
3406 OS << " return cast<" << R.getName() << "Attr>(this)->isEquivalent(cast<"
3407 << R.getName() << "Attr>(Other), Context);\n";
3408 }
3409 OS << " }\n";
3410 OS << " llvm_unreachable(\"Unexpected attribute kind!\");\n";
3411 OS << "}\n\n";
3412}
3413
3414static void emitProfileFunction(const RecordKeeper &Records, raw_ostream &OS) {
3415 OS << "void Attr::Profile(llvm::FoldingSetNodeID &ID, "
3416 "const ASTContext &Ctx) const {\n";
3417 OS << " switch (getKind()) {\n";
3418 for (const auto *Attr : Records.getAllDerivedDefinitions(ClassName: "Attr")) {
3419 const Record &R = *Attr;
3420 if (!R.getValueAsBit(FieldName: "ASTNode"))
3421 continue;
3422 OS << " case attr::" << R.getName() << ":\n";
3423 OS << " return cast<" << R.getName()
3424 << "Attr>(this)->Profile(ID, Ctx);\n";
3425 }
3426 OS << " }\n";
3427 OS << " llvm_unreachable(\"Unexpected attribute kind!\");\n";
3428 OS << "}\n\n";
3429}
3430
3431// Emits the class method definitions for attributes.
3432void clang::EmitClangAttrImpl(const RecordKeeper &Records, raw_ostream &OS) {
3433 emitSourceFileHeader(Desc: "Attribute classes' member function definitions", OS,
3434 Record: Records);
3435
3436 emitAttributes(Records, OS, Header: false);
3437
3438 // Instead of relying on virtual dispatch we just create a huge dispatch
3439 // switch. This is both smaller and faster than virtual functions.
3440 auto EmitFunc = [&](const char *Method) {
3441 OS << " switch (getKind()) {\n";
3442 for (const auto *Attr : Records.getAllDerivedDefinitions(ClassName: "Attr")) {
3443 const Record &R = *Attr;
3444 if (!R.getValueAsBit(FieldName: "ASTNode"))
3445 continue;
3446
3447 OS << " case attr::" << R.getName() << ":\n";
3448 OS << " return cast<" << R.getName() << "Attr>(this)->" << Method
3449 << ";\n";
3450 }
3451 OS << " }\n";
3452 OS << " llvm_unreachable(\"Unexpected attribute kind!\");\n";
3453 OS << "}\n\n";
3454 };
3455
3456 OS << "const char *Attr::getSpelling() const {\n";
3457 EmitFunc("getSpelling()");
3458
3459 OS << "Attr *Attr::clone(ASTContext &C) const {\n";
3460 EmitFunc("clone(C)");
3461
3462 OS << "void Attr::printPretty(raw_ostream &OS, "
3463 "const PrintingPolicy &Policy) const {\n";
3464 EmitFunc("printPretty(OS, Policy)");
3465
3466 emitEquivalenceFunction(Records, OS);
3467 emitProfileFunction(Records, OS);
3468}
3469
3470static void emitAttrList(raw_ostream &OS, StringRef Class,
3471 ArrayRef<const Record *> AttrList) {
3472 for (auto Cur : AttrList) {
3473 OS << Class << "(" << Cur->getName() << ")\n";
3474 }
3475}
3476
3477// Determines if an attribute has a Pragma spelling.
3478static bool AttrHasPragmaSpelling(const Record *R) {
3479 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(Attr: *R);
3480 return any_of(Range&: Spellings, P: [](const FlattenedSpelling &S) {
3481 return S.variety() == "Pragma";
3482 });
3483}
3484
3485namespace {
3486
3487 struct AttrClassDescriptor {
3488 const char * const MacroName;
3489 const char * const TableGenName;
3490 };
3491
3492} // end anonymous namespace
3493
3494static const AttrClassDescriptor AttrClassDescriptors[] = {
3495 {.MacroName: "ATTR", .TableGenName: "Attr"},
3496 {.MacroName: "TYPE_ATTR", .TableGenName: "TypeAttr"},
3497 {.MacroName: "STMT_ATTR", .TableGenName: "StmtAttr"},
3498 {.MacroName: "DECL_OR_STMT_ATTR", .TableGenName: "DeclOrStmtAttr"},
3499 {.MacroName: "INHERITABLE_ATTR", .TableGenName: "InheritableAttr"},
3500 {.MacroName: "DECL_OR_TYPE_ATTR", .TableGenName: "DeclOrTypeAttr"},
3501 {.MacroName: "INHERITABLE_PARAM_ATTR", .TableGenName: "InheritableParamAttr"},
3502 {.MacroName: "INHERITABLE_PARAM_OR_STMT_ATTR", .TableGenName: "InheritableParamOrStmtAttr"},
3503 {.MacroName: "PARAMETER_ABI_ATTR", .TableGenName: "ParameterABIAttr"},
3504 {.MacroName: "HLSL_ANNOTATION_ATTR", .TableGenName: "HLSLAnnotationAttr"},
3505 {.MacroName: "HLSL_SEMANTIC_ATTR", .TableGenName: "HLSLSemanticBaseAttr"}};
3506
3507static void emitDefaultDefine(raw_ostream &OS, StringRef name,
3508 const char *superName) {
3509 OS << "#ifndef " << name << "\n";
3510 OS << "#define " << name << "(NAME) ";
3511 if (superName) OS << superName << "(NAME)";
3512 OS << "\n#endif\n\n";
3513}
3514
3515namespace {
3516
3517 /// A class of attributes.
3518 struct AttrClass {
3519 const AttrClassDescriptor &Descriptor;
3520 const Record *TheRecord;
3521 AttrClass *SuperClass = nullptr;
3522 std::vector<AttrClass*> SubClasses;
3523 std::vector<const Record *> Attrs;
3524
3525 AttrClass(const AttrClassDescriptor &Descriptor, const Record *R)
3526 : Descriptor(Descriptor), TheRecord(R) {}
3527
3528 void emitDefaultDefines(raw_ostream &OS) const {
3529 // Default the macro unless this is a root class (i.e. Attr).
3530 if (SuperClass) {
3531 emitDefaultDefine(OS, name: Descriptor.MacroName,
3532 superName: SuperClass->Descriptor.MacroName);
3533 }
3534 }
3535
3536 void emitUndefs(raw_ostream &OS) const {
3537 OS << "#undef " << Descriptor.MacroName << "\n";
3538 }
3539
3540 void emitAttrList(raw_ostream &OS) const {
3541 for (auto SubClass : SubClasses) {
3542 SubClass->emitAttrList(OS);
3543 }
3544
3545 ::emitAttrList(OS, Class: Descriptor.MacroName, AttrList: Attrs);
3546 }
3547
3548 void classifyAttrOnRoot(const Record *Attr) {
3549 bool result = classifyAttr(Attr);
3550 assert(result && "failed to classify on root"); (void) result;
3551 }
3552
3553 void emitAttrRange(raw_ostream &OS) const {
3554 OS << "ATTR_RANGE(" << Descriptor.TableGenName
3555 << ", " << getFirstAttr()->getName()
3556 << ", " << getLastAttr()->getName() << ")\n";
3557 }
3558
3559 private:
3560 bool classifyAttr(const Record *Attr) {
3561 // Check all the subclasses.
3562 for (auto SubClass : SubClasses) {
3563 if (SubClass->classifyAttr(Attr))
3564 return true;
3565 }
3566
3567 // It's not more specific than this class, but it might still belong here.
3568 if (Attr->isSubClassOf(R: TheRecord)) {
3569 Attrs.push_back(x: Attr);
3570 return true;
3571 }
3572
3573 return false;
3574 }
3575
3576 const Record *getFirstAttr() const {
3577 if (!SubClasses.empty())
3578 return SubClasses.front()->getFirstAttr();
3579 return Attrs.front();
3580 }
3581
3582 const Record *getLastAttr() const {
3583 if (!Attrs.empty())
3584 return Attrs.back();
3585 return SubClasses.back()->getLastAttr();
3586 }
3587 };
3588
3589 /// The entire hierarchy of attribute classes.
3590 class AttrClassHierarchy {
3591 std::vector<std::unique_ptr<AttrClass>> Classes;
3592
3593 public:
3594 AttrClassHierarchy(const RecordKeeper &Records) {
3595 // Find records for all the classes.
3596 for (auto &Descriptor : AttrClassDescriptors) {
3597 const Record *ClassRecord = Records.getClass(Name: Descriptor.TableGenName);
3598 AttrClass *Class = new AttrClass(Descriptor, ClassRecord);
3599 Classes.emplace_back(args&: Class);
3600 }
3601
3602 // Link up the hierarchy.
3603 for (auto &Class : Classes) {
3604 if (AttrClass *SuperClass = findSuperClass(R: Class->TheRecord)) {
3605 Class->SuperClass = SuperClass;
3606 SuperClass->SubClasses.push_back(x: Class.get());
3607 }
3608 }
3609
3610#ifndef NDEBUG
3611 for (auto i = Classes.begin(), e = Classes.end(); i != e; ++i) {
3612 assert((i == Classes.begin()) == ((*i)->SuperClass == nullptr) &&
3613 "only the first class should be a root class!");
3614 }
3615#endif
3616 }
3617
3618 void emitDefaultDefines(raw_ostream &OS) const {
3619 for (auto &Class : Classes) {
3620 Class->emitDefaultDefines(OS);
3621 }
3622 }
3623
3624 void emitUndefs(raw_ostream &OS) const {
3625 for (auto &Class : Classes) {
3626 Class->emitUndefs(OS);
3627 }
3628 }
3629
3630 void emitAttrLists(raw_ostream &OS) const {
3631 // Just start from the root class.
3632 Classes[0]->emitAttrList(OS);
3633 }
3634
3635 void emitAttrRanges(raw_ostream &OS) const {
3636 for (auto &Class : Classes)
3637 Class->emitAttrRange(OS);
3638 }
3639
3640 void classifyAttr(const Record *Attr) {
3641 // Add the attribute to the root class.
3642 Classes[0]->classifyAttrOnRoot(Attr);
3643 }
3644
3645 private:
3646 AttrClass *findClassByRecord(const Record *R) const {
3647 for (auto &Class : Classes) {
3648 if (Class->TheRecord == R)
3649 return Class.get();
3650 }
3651 return nullptr;
3652 }
3653
3654 AttrClass *findSuperClass(const Record *R) const {
3655 // TableGen flattens the superclass list, so we just need to walk it
3656 // in reverse.
3657 std::vector<const Record *> SuperClasses = R->getSuperClasses();
3658 for (const Record *R : reverse(C&: SuperClasses)) {
3659 if (AttrClass *SuperClass = findClassByRecord(R))
3660 return SuperClass;
3661 }
3662 return nullptr;
3663 }
3664 };
3665
3666} // end anonymous namespace
3667
3668namespace clang {
3669
3670// Emits the enumeration list for attributes.
3671void EmitClangAttrList(const RecordKeeper &Records, raw_ostream &OS) {
3672 emitSourceFileHeader(Desc: "List of all attributes that Clang recognizes", OS,
3673 Record: Records);
3674
3675 AttrClassHierarchy Hierarchy(Records);
3676
3677 // Add defaulting macro definitions.
3678 Hierarchy.emitDefaultDefines(OS);
3679 emitDefaultDefine(OS, name: "PRAGMA_SPELLING_ATTR", superName: nullptr);
3680
3681 std::vector<const Record *> PragmaAttrs;
3682 for (auto *Attr : Records.getAllDerivedDefinitions(ClassName: "Attr")) {
3683 if (!Attr->getValueAsBit(FieldName: "ASTNode"))
3684 continue;
3685
3686 // Add the attribute to the ad-hoc groups.
3687 if (AttrHasPragmaSpelling(R: Attr))
3688 PragmaAttrs.push_back(x: Attr);
3689
3690 // Place it in the hierarchy.
3691 Hierarchy.classifyAttr(Attr);
3692 }
3693
3694 // Emit the main attribute list.
3695 Hierarchy.emitAttrLists(OS);
3696
3697 // Emit the ad hoc groups.
3698 emitAttrList(OS, Class: "PRAGMA_SPELLING_ATTR", AttrList: PragmaAttrs);
3699
3700 // Emit the attribute ranges.
3701 OS << "#ifdef ATTR_RANGE\n";
3702 Hierarchy.emitAttrRanges(OS);
3703 OS << "#undef ATTR_RANGE\n";
3704 OS << "#endif\n";
3705
3706 Hierarchy.emitUndefs(OS);
3707 OS << "#undef PRAGMA_SPELLING_ATTR\n";
3708}
3709
3710// Emits the enumeration list for attributes.
3711void EmitClangAttrSubjectMatchRuleList(const RecordKeeper &Records,
3712 raw_ostream &OS) {
3713 emitSourceFileHeader(
3714 Desc: "List of all attribute subject matching rules that Clang recognizes", OS,
3715 Record: Records);
3716 PragmaClangAttributeSupport &PragmaAttributeSupport =
3717 getPragmaAttributeSupport(Records);
3718 emitDefaultDefine(OS, name: "ATTR_MATCH_RULE", superName: nullptr);
3719 PragmaAttributeSupport.emitMatchRuleList(OS);
3720 OS << "#undef ATTR_MATCH_RULE\n";
3721}
3722
3723// Emits the code to read an attribute from a precompiled header.
3724void EmitClangAttrPCHRead(const RecordKeeper &Records, raw_ostream &OS) {
3725 emitSourceFileHeader(Desc: "Attribute deserialization code", OS, Record: Records);
3726
3727 const Record *InhClass = Records.getClass(Name: "InheritableAttr");
3728 std::vector<const Record *> ArgRecords;
3729 std::vector<std::unique_ptr<Argument>> Args;
3730 std::unique_ptr<VariadicExprArgument> DelayedArgs;
3731
3732 OS << " switch (Kind) {\n";
3733 for (const auto *Attr : Records.getAllDerivedDefinitions(ClassName: "Attr")) {
3734 const Record &R = *Attr;
3735 if (!R.getValueAsBit(FieldName: "ASTNode"))
3736 continue;
3737
3738 OS << " case attr::" << R.getName() << ": {\n";
3739 if (R.isSubClassOf(R: InhClass))
3740 OS << " bool isInherited = Record.readInt();\n";
3741 OS << " bool isImplicit = Record.readInt();\n";
3742 OS << " bool isPackExpansion = Record.readInt();\n";
3743 DelayedArgs = nullptr;
3744 if (Attr->getValueAsBit(FieldName: "AcceptsExprPack")) {
3745 DelayedArgs =
3746 std::make_unique<VariadicExprArgument>(args: "DelayedArgs", args: R.getName());
3747 DelayedArgs->writePCHReadDecls(OS);
3748 }
3749 ArgRecords = R.getValueAsListOfDefs(FieldName: "Args");
3750 Args.clear();
3751 for (const auto *Arg : ArgRecords) {
3752 Args.emplace_back(args: createArgument(Arg: *Arg, Attr: R.getName()));
3753 Args.back()->writePCHReadDecls(OS);
3754 }
3755 OS << " New = new (Context) " << R.getName() << "Attr(Context, Info";
3756 for (auto const &ri : Args) {
3757 OS << ", ";
3758 ri->writePCHReadArgs(OS);
3759 }
3760 OS << ");\n";
3761 if (R.isSubClassOf(R: InhClass))
3762 OS << " cast<InheritableAttr>(New)->setInherited(isInherited);\n";
3763 OS << " New->setImplicit(isImplicit);\n";
3764 OS << " New->setPackExpansion(isPackExpansion);\n";
3765 if (DelayedArgs) {
3766 OS << " cast<" << R.getName()
3767 << "Attr>(New)->setDelayedArgs(Context, ";
3768 DelayedArgs->writePCHReadArgs(OS);
3769 OS << ");\n";
3770 }
3771
3772 if (Attr->getValueAsBit(FieldName: "HasCustomSerialization"))
3773 OS << " read" << R.getName() << "Attr(cast<" << R.getName()
3774 << "Attr>(New));\n";
3775
3776 OS << " break;\n";
3777 OS << " }\n";
3778 }
3779 OS << " }\n";
3780}
3781
3782// Emits the code to write an attribute to a precompiled header.
3783void EmitClangAttrPCHWrite(const RecordKeeper &Records, raw_ostream &OS) {
3784 emitSourceFileHeader(Desc: "Attribute serialization code", OS, Record: Records);
3785
3786 const Record *InhClass = Records.getClass(Name: "InheritableAttr");
3787 OS << " switch (A->getKind()) {\n";
3788 for (const auto *Attr : Records.getAllDerivedDefinitions(ClassName: "Attr")) {
3789 const Record &R = *Attr;
3790 if (!R.getValueAsBit(FieldName: "ASTNode"))
3791 continue;
3792 OS << " case attr::" << R.getName() << ": {\n";
3793 std::vector<const Record *> Args = R.getValueAsListOfDefs(FieldName: "Args");
3794 if (R.isSubClassOf(R: InhClass) || !Args.empty())
3795 OS << " const auto *SA = cast<" << R.getName()
3796 << "Attr>(A);\n";
3797 if (R.isSubClassOf(R: InhClass))
3798 OS << " Record.push_back(SA->isInherited());\n";
3799 OS << " Record.push_back(A->isImplicit());\n";
3800 OS << " Record.push_back(A->isPackExpansion());\n";
3801 if (Attr->getValueAsBit(FieldName: "AcceptsExprPack"))
3802 VariadicExprArgument("DelayedArgs", R.getName()).writePCHWrite(OS);
3803
3804 for (const auto *Arg : Args)
3805 createArgument(Arg: *Arg, Attr: R.getName())->writePCHWrite(OS);
3806
3807 if (Attr->getValueAsBit(FieldName: "HasCustomSerialization"))
3808 OS << " Record.Add" << R.getName() << "Attr(SA);\n";
3809
3810 OS << " break;\n";
3811 OS << " }\n";
3812 }
3813 OS << " }\n";
3814}
3815
3816} // namespace clang
3817
3818// Helper function for GenerateTargetSpecificAttrChecks that alters the 'Test'
3819// parameter with only a single check type, if applicable.
3820static bool GenerateTargetSpecificAttrCheck(const Record *R, std::string &Test,
3821 std::string *FnName,
3822 StringRef ListName,
3823 StringRef CheckAgainst,
3824 StringRef Scope) {
3825 if (!R->isValueUnset(FieldName: ListName)) {
3826 Test += " && (";
3827 std::vector<StringRef> Items = R->getValueAsListOfStrings(FieldName: ListName);
3828 for (auto I = Items.begin(), E = Items.end(); I != E; ++I) {
3829 StringRef Part = *I;
3830 Test += CheckAgainst;
3831 Test += " == ";
3832 Test += Scope;
3833 Test += Part;
3834 if (I + 1 != E)
3835 Test += " || ";
3836 if (FnName)
3837 *FnName += Part;
3838 }
3839 Test += ")";
3840 return true;
3841 }
3842 return false;
3843}
3844
3845// Generate a conditional expression to check if the current target satisfies
3846// the conditions for a TargetSpecificAttr record, and append the code for
3847// those checks to the Test string. If the FnName string pointer is non-null,
3848// append a unique suffix to distinguish this set of target checks from other
3849// TargetSpecificAttr records.
3850static bool GenerateTargetSpecificAttrChecks(const Record *R,
3851 std::vector<StringRef> &Arches,
3852 std::string &Test,
3853 std::string *FnName) {
3854 bool AnyTargetChecks = false;
3855
3856 // It is assumed that there will be an Triple object
3857 // named "T" and a TargetInfo object named "Target" within
3858 // scope that can be used to determine whether the attribute exists in
3859 // a given target.
3860 Test += "true";
3861 // If one or more architectures is specified, check those. Arches are handled
3862 // differently because GenerateTargetRequirements needs to combine the list
3863 // with ParseKind.
3864 if (!Arches.empty()) {
3865 AnyTargetChecks = true;
3866 Test += " && (";
3867 for (auto I = Arches.begin(), E = Arches.end(); I != E; ++I) {
3868 StringRef Part = *I;
3869 Test += "T.getArch() == llvm::Triple::";
3870 Test += Part;
3871 if (I + 1 != E)
3872 Test += " || ";
3873 if (FnName)
3874 *FnName += Part;
3875 }
3876 Test += ")";
3877 }
3878
3879 // If the attribute is specific to particular OSes, check those.
3880 AnyTargetChecks |= GenerateTargetSpecificAttrCheck(
3881 R, Test, FnName, ListName: "OSes", CheckAgainst: "T.getOS()", Scope: "llvm::Triple::");
3882
3883 // If one or more object formats is specified, check those.
3884 AnyTargetChecks |=
3885 GenerateTargetSpecificAttrCheck(R, Test, FnName, ListName: "ObjectFormats",
3886 CheckAgainst: "T.getObjectFormat()", Scope: "llvm::Triple::");
3887
3888 // If custom code is specified, emit it.
3889 StringRef Code = R->getValueAsString(FieldName: "CustomCode");
3890 if (!Code.empty()) {
3891 AnyTargetChecks = true;
3892 Test += " && (";
3893 Test += Code;
3894 Test += ")";
3895 }
3896
3897 return AnyTargetChecks;
3898}
3899
3900static void GenerateHasAttrSpellingStringSwitch(
3901 ArrayRef<std::pair<const Record *, FlattenedSpelling>> Attrs,
3902 raw_ostream &OS, StringRef Variety, StringRef Scope = "") {
3903
3904 // It turns out that there are duplicate records for a given spelling. This
3905 // map combines matching test strings using '||'. For example, if there are
3906 // three conditions A, B, and C, the final result will be: A || B || C.
3907 llvm::StringMap<std::string> TestStringMap;
3908
3909 for (const auto &[Attr, Spelling] : Attrs) {
3910 // C++11-style attributes have specific version information associated with
3911 // them. If the attribute has no scope, the version information must not
3912 // have the default value (1), as that's incorrect. Instead, the unscoped
3913 // attribute version information should be taken from the SD-6 standing
3914 // document, which can be found at:
3915 // https://isocpp.org/std/standing-documents/sd-6-sg10-feature-test-recommendations
3916 //
3917 // C23-style attributes have the same kind of version information
3918 // associated with them. The unscoped attribute version information should
3919 // be taken from the specification of the attribute in the C Standard.
3920 //
3921 // Clang-specific attributes have the same kind of version information
3922 // associated with them. This version is typically the default value (1).
3923 // These version values are clang-specific and should typically be
3924 // incremented once the attribute changes its syntax and/or semantics in a
3925 // a way that is impactful to the end user.
3926 int Version = 1;
3927
3928 assert(Spelling.variety() == Variety);
3929 std::string Name = "";
3930 if (Spelling.nameSpace().empty() || Scope == Spelling.nameSpace()) {
3931 Name = Spelling.name();
3932 Version = static_cast<int>(
3933 Spelling.getSpellingRecord().getValueAsInt(FieldName: "Version"));
3934 // Verify that explicitly specified CXX11 and C23 spellings (i.e.
3935 // not inferred from Clang/GCC spellings) have a version that's
3936 // different from the default (1).
3937 bool RequiresValidVersion =
3938 (Variety == "CXX11" || Variety == "C23") &&
3939 Spelling.getSpellingRecord().getValueAsString(FieldName: "Variety") == Variety;
3940 if (RequiresValidVersion && Scope.empty() && Version == 1)
3941 PrintError(ErrorLoc: Spelling.getSpellingRecord().getLoc(),
3942 Msg: "Standard attributes must have "
3943 "valid version information.");
3944 }
3945
3946 std::string Test;
3947 if (Attr->isSubClassOf(Name: "TargetSpecificAttr")) {
3948 const Record *R = Attr->getValueAsDef(FieldName: "Target");
3949 std::vector<StringRef> Arches = R->getValueAsListOfStrings(FieldName: "Arches");
3950 GenerateTargetSpecificAttrChecks(R, Arches, Test, FnName: nullptr);
3951 } else if (!Attr->getValueAsListOfDefs(FieldName: "TargetSpecificSpellings").empty()) {
3952 // Add target checks if this spelling is target-specific.
3953 for (const auto &TargetSpelling :
3954 Attr->getValueAsListOfDefs(FieldName: "TargetSpecificSpellings")) {
3955 // Find spelling that matches current scope and name.
3956 for (const auto &Spelling : GetFlattenedSpellings(Attr: *TargetSpelling)) {
3957 if (Scope == Spelling.nameSpace() && Name == Spelling.name()) {
3958 const Record *Target = TargetSpelling->getValueAsDef(FieldName: "Target");
3959 std::vector<StringRef> Arches =
3960 Target->getValueAsListOfStrings(FieldName: "Arches");
3961 GenerateTargetSpecificAttrChecks(R: Target, Arches, Test,
3962 /*FnName=*/nullptr);
3963 break;
3964 }
3965 }
3966 }
3967 }
3968
3969 std::string TestStr =
3970 !Test.empty() ? '(' + Test + " ? " + itostr(X: Version) + " : 0" + ')'
3971 : '(' + itostr(X: Version) + ')';
3972
3973 if (Scope.empty() || Scope == Spelling.nameSpace()) {
3974 if (TestStringMap.contains(Key: Spelling.name()) &&
3975 TestStringMap[Spelling.name()] != TestStr)
3976 TestStringMap[Spelling.name()] += " || " + TestStr;
3977 else
3978 TestStringMap[Spelling.name()] = TestStr;
3979 }
3980 }
3981
3982 // Create the actual string switch statement after all the attributes have
3983 // been parsed.
3984 for (auto &Entry : TestStringMap) {
3985 OS << " .Case(\"" << Entry.getKey() << "\", " << Entry.getValue()
3986 << ")\n";
3987 }
3988
3989 OS << " .Default(0);\n";
3990}
3991
3992namespace clang {
3993
3994// Emits list of regular keyword attributes with info about their arguments.
3995void EmitClangRegularKeywordAttributeInfo(const RecordKeeper &Records,
3996 raw_ostream &OS) {
3997 emitSourceFileHeader(
3998 Desc: "A list of regular keyword attributes generated from the attribute"
3999 " definitions",
4000 OS);
4001 // Assume for now that the same token is not used in multiple regular
4002 // keyword attributes.
4003 for (auto *R : Records.getAllDerivedDefinitions(ClassName: "Attr"))
4004 for (const auto &S : GetFlattenedSpellings(Attr: *R)) {
4005 if (!isRegularKeywordAttribute(S))
4006 continue;
4007 std::vector<const Record *> Args = R->getValueAsListOfDefs(FieldName: "Args");
4008 bool HasArgs = any_of(
4009 Range&: Args, P: [](const Record *Arg) { return !Arg->getValueAsBit(FieldName: "Fake"); });
4010
4011 OS << "KEYWORD_ATTRIBUTE("
4012 << S.getSpellingRecord().getValueAsString(FieldName: "Name") << ", "
4013 << (HasArgs ? "true" : "false") << ", )\n";
4014 }
4015 OS << "#undef KEYWORD_ATTRIBUTE\n";
4016}
4017
4018void EmitCXX11AttributeInfo(const RecordKeeper &Records, raw_ostream &OS) {
4019 OS << "#if defined(CXX11_ATTR_ARGS_INFO)\n";
4020 for (auto *R : Records.getAllDerivedDefinitions(ClassName: "Attr")) {
4021 for (const FlattenedSpelling &SI : GetFlattenedSpellings(Attr: *R)) {
4022 if (SI.variety() == "CXX11" && SI.nameSpace().empty()) {
4023 unsigned RequiredArgs = 0;
4024 unsigned OptionalArgs = 0;
4025 for (const auto *Arg : R->getValueAsListOfDefs(FieldName: "Args")) {
4026 if (Arg->getValueAsBit(FieldName: "Fake"))
4027 continue;
4028
4029 if (Arg->getValueAsBit(FieldName: "Optional"))
4030 OptionalArgs++;
4031 else
4032 RequiredArgs++;
4033 }
4034 OS << ".Case(\"" << SI.getSpellingRecord().getValueAsString(FieldName: "Name")
4035 << "\","
4036 << "AttributeCommonInfo::AttrArgsInfo::"
4037 << (RequiredArgs ? "Required"
4038 : OptionalArgs ? "Optional"
4039 : "None")
4040 << ")"
4041 << "\n";
4042 }
4043 }
4044 }
4045 OS << "#endif // CXX11_ATTR_ARGS_INFO\n";
4046}
4047
4048// Emits the list of spellings for attributes.
4049void EmitClangAttrHasAttrImpl(const RecordKeeper &Records, raw_ostream &OS) {
4050 emitSourceFileHeader(Desc: "Code to implement the __has_attribute logic", OS,
4051 Record: Records);
4052
4053 // Separate all of the attributes out into four group: generic, C++11, GNU,
4054 // and declspecs. Then generate a big switch statement for each of them.
4055 using PairTy = std::pair<const Record *, FlattenedSpelling>;
4056 std::vector<PairTy> Declspec, Microsoft, GNU, Pragma, HLSLAnnotation;
4057 std::map<StringRef, std::vector<PairTy>> CXX, C23;
4058
4059 // Walk over the list of all attributes, and split them out based on the
4060 // spelling variety.
4061 for (auto *R : Records.getAllDerivedDefinitions(ClassName: "Attr")) {
4062 for (const FlattenedSpelling &SI : GetFlattenedSpellings(Attr: *R)) {
4063 StringRef Variety = SI.variety();
4064 if (Variety == "GNU")
4065 GNU.emplace_back(args&: R, args: SI);
4066 else if (Variety == "Declspec")
4067 Declspec.emplace_back(args&: R, args: SI);
4068 else if (Variety == "Microsoft")
4069 Microsoft.emplace_back(args&: R, args: SI);
4070 else if (Variety == "CXX11")
4071 CXX[SI.nameSpace()].emplace_back(args&: R, args: SI);
4072 else if (Variety == "C23")
4073 C23[SI.nameSpace()].emplace_back(args&: R, args: SI);
4074 else if (Variety == "Pragma")
4075 Pragma.emplace_back(args&: R, args: SI);
4076 else if (Variety == "HLSLAnnotation")
4077 HLSLAnnotation.emplace_back(args&: R, args: SI);
4078 }
4079 }
4080
4081 OS << "const llvm::Triple &T = Target.getTriple();\n";
4082 OS << "switch (Syntax) {\n";
4083 OS << "case AttributeCommonInfo::Syntax::AS_GNU:\n";
4084 OS << " return llvm::StringSwitch<int>(Name)\n";
4085 GenerateHasAttrSpellingStringSwitch(Attrs: GNU, OS, Variety: "GNU");
4086 OS << "case AttributeCommonInfo::Syntax::AS_Declspec:\n";
4087 OS << " return llvm::StringSwitch<int>(Name)\n";
4088 GenerateHasAttrSpellingStringSwitch(Attrs: Declspec, OS, Variety: "Declspec");
4089 OS << "case AttributeCommonInfo::Syntax::AS_Microsoft:\n";
4090 OS << " return llvm::StringSwitch<int>(Name)\n";
4091 GenerateHasAttrSpellingStringSwitch(Attrs: Microsoft, OS, Variety: "Microsoft");
4092 OS << "case AttributeCommonInfo::Syntax::AS_Pragma:\n";
4093 OS << " return llvm::StringSwitch<int>(Name)\n";
4094 GenerateHasAttrSpellingStringSwitch(Attrs: Pragma, OS, Variety: "Pragma");
4095 OS << "case AttributeCommonInfo::Syntax::AS_HLSLAnnotation:\n";
4096 OS << " return llvm::StringSwitch<int>(Name)\n";
4097 GenerateHasAttrSpellingStringSwitch(Attrs: HLSLAnnotation, OS, Variety: "HLSLAnnotation");
4098 auto fn = [&OS](StringRef Spelling,
4099 const std::map<StringRef, std::vector<PairTy>> &Map) {
4100 OS << "case AttributeCommonInfo::Syntax::AS_" << Spelling << ": {\n";
4101 // C++11-style attributes are further split out based on the Scope.
4102 ListSeparator LS(" else ");
4103 for (const auto &[Scope, List] : Map) {
4104 OS << LS;
4105 OS << "if (ScopeName == \"" << Scope << "\") {\n";
4106 OS << " return llvm::StringSwitch<int>(Name)\n";
4107 GenerateHasAttrSpellingStringSwitch(Attrs: List, OS, Variety: Spelling, Scope);
4108 OS << "}";
4109 }
4110 OS << "\n} break;\n";
4111 };
4112 fn("CXX11", CXX);
4113 fn("C23", C23);
4114 OS << "case AttributeCommonInfo::Syntax::AS_Keyword:\n";
4115 OS << "case AttributeCommonInfo::Syntax::AS_ContextSensitiveKeyword:\n";
4116 OS << " llvm_unreachable(\"hasAttribute not supported for keyword\");\n";
4117 OS << " return 0;\n";
4118 OS << "case AttributeCommonInfo::Syntax::AS_Implicit:\n";
4119 OS << " llvm_unreachable (\"hasAttribute not supported for "
4120 "AS_Implicit\");\n";
4121 OS << " return 0;\n";
4122
4123 OS << "}\n";
4124}
4125
4126void EmitClangAttrSpellingListIndex(const RecordKeeper &Records,
4127 raw_ostream &OS) {
4128 emitSourceFileHeader(Desc: "Code to translate different attribute spellings into "
4129 "internal identifiers",
4130 OS, Record: Records);
4131
4132 OS << " switch (getParsedKind()) {\n";
4133 OS << " case IgnoredAttribute:\n";
4134 OS << " case UnknownAttribute:\n";
4135 OS << " case NoSemaHandlerAttribute:\n";
4136 OS << " llvm_unreachable(\"Ignored/unknown shouldn't get here\");\n";
4137
4138 ParsedAttrMap Attrs = getParsedAttrList(Records);
4139 for (const auto &I : Attrs) {
4140 const Record &R = *I.second;
4141 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(Attr: R);
4142 OS << " case AT_" << I.first << ": {\n";
4143
4144 // If there are none or one spelling to check, resort to the default
4145 // behavior of returning index as 0.
4146 if (Spellings.size() <= 1) {
4147 OS << " return 0;\n"
4148 << " break;\n"
4149 << " }\n";
4150 continue;
4151 }
4152
4153 std::vector<StringRef> Names;
4154 llvm::transform(Range&: Spellings, d_first: std::back_inserter(x&: Names),
4155 F: [](const FlattenedSpelling &FS) { return FS.name(); });
4156 llvm::sort(C&: Names);
4157 Names.erase(first: llvm::unique(R&: Names), last: Names.end());
4158
4159 for (const auto &[Idx, FS] : enumerate(First&: Spellings)) {
4160 OS << " if (";
4161 if (Names.size() > 1) {
4162 SmallVector<StringRef, 6> SameLenNames;
4163 StringRef FSName = FS.name();
4164 llvm::copy_if(
4165 Range&: Names, Out: std::back_inserter(x&: SameLenNames),
4166 P: [&](StringRef N) { return N.size() == FSName.size(); });
4167
4168 if (SameLenNames.size() == 1) {
4169 OS << "Name.size() == " << FS.name().size() << " && ";
4170 } else {
4171 // FIXME: We currently fall back to comparing entire strings if there
4172 // are 2 or more spelling names with the same length. This can be
4173 // optimized to check only for the the first differing character
4174 // between them instead.
4175 OS << "Name == \"" << FS.name() << "\""
4176 << " && ";
4177 }
4178 }
4179
4180 OS << "getSyntax() == AttributeCommonInfo::AS_" << FS.variety()
4181 << " && ComputedScope == ";
4182 if (FS.nameSpace() == "")
4183 OS << "AttributeCommonInfo::Scope::NONE";
4184 else
4185 OS << "AttributeCommonInfo::Scope::" + FS.nameSpace().upper();
4186
4187 OS << ")\n"
4188 << " return " << Idx << ";\n";
4189 }
4190
4191 OS << " break;\n"
4192 << " }\n";
4193 }
4194
4195 OS << " }\n"
4196 << " return 0;\n";
4197}
4198
4199// Emits code used by RecursiveASTVisitor to visit attributes
4200void EmitClangAttrASTVisitor(const RecordKeeper &Records, raw_ostream &OS) {
4201 emitSourceFileHeader(Desc: "Used by RecursiveASTVisitor to visit attributes.", OS,
4202 Record: Records);
4203 // Write method declarations for Traverse* methods.
4204 // We emit this here because we only generate methods for attributes that
4205 // are declared as ASTNodes.
4206 OS << "#ifdef ATTR_VISITOR_DECLS_ONLY\n\n";
4207 ArrayRef<const Record *> Attrs = Records.getAllDerivedDefinitions(ClassName: "Attr");
4208 for (const auto *Attr : Attrs) {
4209 const Record &R = *Attr;
4210 if (!R.getValueAsBit(FieldName: "ASTNode"))
4211 continue;
4212 OS << " bool Traverse"
4213 << R.getName() << "Attr(" << R.getName() << "Attr *A);\n";
4214 OS << " bool Visit"
4215 << R.getName() << "Attr(" << R.getName() << "Attr *A) {\n"
4216 << " return true; \n"
4217 << " }\n";
4218 }
4219 OS << "\n#else // ATTR_VISITOR_DECLS_ONLY\n\n";
4220
4221 // Write individual Traverse* methods for each attribute class.
4222 for (const auto *Attr : Attrs) {
4223 const Record &R = *Attr;
4224 if (!R.getValueAsBit(FieldName: "ASTNode"))
4225 continue;
4226
4227 OS << "template <typename Derived>\n"
4228 << "bool VISITORCLASS<Derived>::Traverse"
4229 << R.getName() << "Attr(" << R.getName() << "Attr *A) {\n"
4230 << " if (!getDerived().VisitAttr(A))\n"
4231 << " return false;\n"
4232 << " if (!getDerived().Visit" << R.getName() << "Attr(A))\n"
4233 << " return false;\n";
4234
4235 for (const auto *Arg : R.getValueAsListOfDefs(FieldName: "Args"))
4236 createArgument(Arg: *Arg, Attr: R.getName())->writeASTVisitorTraversal(OS);
4237
4238 if (Attr->getValueAsBit(FieldName: "AcceptsExprPack"))
4239 VariadicExprArgument("DelayedArgs", R.getName())
4240 .writeASTVisitorTraversal(OS);
4241
4242 OS << " return true;\n";
4243 OS << "}\n\n";
4244 }
4245
4246 // Write generic Traverse routine
4247 OS << "template <typename Derived>\n"
4248 << "bool VISITORCLASS<Derived>::TraverseAttr(Attr *A) {\n"
4249 << " if (!A)\n"
4250 << " return true;\n"
4251 << "\n"
4252 << " switch (A->getKind()) {\n";
4253
4254 for (const auto *Attr : Attrs) {
4255 const Record &R = *Attr;
4256 if (!R.getValueAsBit(FieldName: "ASTNode"))
4257 continue;
4258
4259 OS << " case attr::" << R.getName() << ":\n"
4260 << " return getDerived().Traverse" << R.getName() << "Attr("
4261 << "cast<" << R.getName() << "Attr>(A));\n";
4262 }
4263 OS << " }\n"; // end switch
4264 OS << " llvm_unreachable(\"bad attribute kind\");\n";
4265 OS << "}\n"; // end function
4266 OS << "#endif // ATTR_VISITOR_DECLS_ONLY\n";
4267}
4268
4269static void
4270EmitClangAttrTemplateInstantiateHelper(ArrayRef<const Record *> Attrs,
4271 raw_ostream &OS, bool AppliesToDecl) {
4272
4273 OS << " switch (At->getKind()) {\n";
4274 for (const auto *Attr : Attrs) {
4275 const Record &R = *Attr;
4276 if (!R.getValueAsBit(FieldName: "ASTNode"))
4277 continue;
4278 OS << " case attr::" << R.getName() << ": {\n";
4279 bool ShouldClone = R.getValueAsBit(FieldName: "Clone") &&
4280 (!AppliesToDecl ||
4281 R.getValueAsBit(FieldName: "MeaningfulToClassTemplateDefinition"));
4282
4283 if (!ShouldClone) {
4284 OS << " return nullptr;\n";
4285 OS << " }\n";
4286 continue;
4287 }
4288
4289 OS << " const auto *A = cast<"
4290 << R.getName() << "Attr>(At);\n";
4291 bool TDependent = R.getValueAsBit(FieldName: "TemplateDependent");
4292
4293 if (!TDependent) {
4294 OS << " return A->clone(C);\n";
4295 OS << " }\n";
4296 continue;
4297 }
4298
4299 std::vector<const Record *> ArgRecords = R.getValueAsListOfDefs(FieldName: "Args");
4300 std::vector<std::unique_ptr<Argument>> Args;
4301 Args.reserve(n: ArgRecords.size());
4302
4303 for (const auto *ArgRecord : ArgRecords)
4304 Args.emplace_back(args: createArgument(Arg: *ArgRecord, Attr: R.getName()));
4305
4306 for (auto const &ai : Args)
4307 ai->writeTemplateInstantiation(OS);
4308
4309 OS << " return new (C) " << R.getName() << "Attr(C, *A";
4310 for (auto const &ai : Args) {
4311 OS << ", ";
4312 ai->writeTemplateInstantiationArgs(OS);
4313 }
4314 OS << ");\n"
4315 << " }\n";
4316 }
4317 OS << " } // end switch\n"
4318 << " llvm_unreachable(\"Unknown attribute!\");\n"
4319 << " return nullptr;\n";
4320}
4321
4322// Emits code to instantiate dependent attributes on templates.
4323void EmitClangAttrTemplateInstantiate(const RecordKeeper &Records,
4324 raw_ostream &OS) {
4325 emitSourceFileHeader(Desc: "Template instantiation code for attributes", OS,
4326 Record: Records);
4327
4328 ArrayRef<const Record *> Attrs = Records.getAllDerivedDefinitions(ClassName: "Attr");
4329
4330 OS << "namespace clang {\n"
4331 << "namespace sema {\n\n"
4332 << "Attr *instantiateTemplateAttribute(const Attr *At, ASTContext &C, "
4333 << "Sema &S,\n"
4334 << " const MultiLevelTemplateArgumentList &TemplateArgs) {\n";
4335 EmitClangAttrTemplateInstantiateHelper(Attrs, OS, /*AppliesToDecl*/false);
4336 OS << "}\n\n"
4337 << "Attr *instantiateTemplateAttributeForDecl(const Attr *At,\n"
4338 << " ASTContext &C, Sema &S,\n"
4339 << " const MultiLevelTemplateArgumentList &TemplateArgs) {\n";
4340 EmitClangAttrTemplateInstantiateHelper(Attrs, OS, /*AppliesToDecl*/true);
4341 OS << "}\n\n"
4342 << "} // end namespace sema\n"
4343 << "} // end namespace clang\n";
4344}
4345
4346// Emits the list of parsed attributes.
4347void EmitClangAttrParsedAttrList(const RecordKeeper &Records, raw_ostream &OS) {
4348 emitSourceFileHeader(Desc: "List of all attributes that Clang recognizes", OS,
4349 Record: Records);
4350
4351 OS << "#ifndef PARSED_ATTR\n";
4352 OS << "#define PARSED_ATTR(NAME) NAME\n";
4353 OS << "#endif\n\n";
4354
4355 ParsedAttrMap Names = getParsedAttrList(Records);
4356 for (const auto &I : Names) {
4357 OS << "PARSED_ATTR(" << I.first << ")\n";
4358 }
4359}
4360
4361void EmitAttributeSpellingList(const RecordKeeper &Records, raw_ostream &OS) {
4362 emitSourceFileHeader(Desc: "List of attribute names", OS, Record: Records);
4363
4364 std::set<StringRef> AttrSpellingList;
4365 std::set<StringRef> AttrScopeSpellingList;
4366
4367 for (const auto *A : Records.getAllDerivedDefinitions(ClassName: "Attr")) {
4368 for (const auto &S : GetFlattenedSpellings(Attr: *A)) {
4369 AttrSpellingList.insert(x: S.name());
4370 if (S.nameSpace().size())
4371 AttrScopeSpellingList.insert(x: S.nameSpace());
4372 }
4373 }
4374
4375 OS << "#ifndef ATTR_NAME" << "\n";
4376 OS << "#define ATTR_NAME(NAME) NAME" << "\n";
4377 OS << "#endif" << "\n" << "\n";
4378 for (const auto &AttrName : AttrSpellingList) {
4379 OS << "ATTR_NAME(\"" << AttrName << "\")\n";
4380 }
4381 OS << "\n";
4382 OS << "#undef ATTR_NAME" << "\n";
4383 OS << "\n";
4384
4385 OS << "#ifndef ATTR_SCOPE_NAME" << "\n";
4386 OS << "#define ATTR_SCOPE_NAME(SCOPE_NAME) SCOPE_NAME" << "\n";
4387 OS << "#endif" << "\n" << "\n";
4388 for (const auto &AttrScopeName : AttrScopeSpellingList) {
4389 OS << "ATTR_SCOPE_NAME(\"" << AttrScopeName << "\")\n";
4390 }
4391 OS << "\n";
4392 OS << "#undef ATTR_SCOPE_NAME" << "\n";
4393 OS << "\n";
4394}
4395
4396static bool isArgVariadic(const Record &R, StringRef AttrName) {
4397 return createArgument(Arg: R, Attr: AttrName)->isVariadic();
4398}
4399
4400static void emitArgInfo(const Record &R, raw_ostream &OS) {
4401 // This function will count the number of arguments specified for the
4402 // attribute and emit the number of required arguments followed by the
4403 // number of optional arguments.
4404 unsigned ArgCount = 0, OptCount = 0, ArgMemberCount = 0;
4405 bool HasVariadic = false;
4406 for (const auto *Arg : R.getValueAsListOfDefs(FieldName: "Args")) {
4407 // If the arg is fake, it's the user's job to supply it: general parsing
4408 // logic shouldn't need to know anything about it.
4409 if (Arg->getValueAsBit(FieldName: "Fake"))
4410 continue;
4411 Arg->getValueAsBit(FieldName: "Optional") ? ++OptCount : ++ArgCount;
4412 ++ArgMemberCount;
4413 if (!HasVariadic && isArgVariadic(R: *Arg, AttrName: R.getName()))
4414 HasVariadic = true;
4415 }
4416
4417 // If there is a variadic argument, we will set the optional argument count
4418 // to its largest value. Since it's currently a 4-bit number, we set it to 15.
4419 OS << " /*NumArgs=*/" << ArgCount << ",\n";
4420 OS << " /*OptArgs=*/" << (HasVariadic ? 15 : OptCount) << ",\n";
4421 OS << " /*NumArgMembers=*/" << ArgMemberCount << ",\n";
4422}
4423
4424static std::string GetDiagnosticSpelling(const Record &R) {
4425 StringRef Ret = R.getValueAsString(FieldName: "DiagSpelling");
4426 if (!Ret.empty())
4427 return Ret.str();
4428
4429 // If we couldn't find the DiagSpelling in this object, we can check to see
4430 // if the object is one that has a base, and if it is, loop up to the Base
4431 // member recursively.
4432 if (auto Base = R.getValueAsOptionalDef(BaseFieldName))
4433 return GetDiagnosticSpelling(R: *Base);
4434
4435 return "";
4436}
4437
4438static std::string CalculateDiagnostic(const Record &S) {
4439 // If the SubjectList object has a custom diagnostic associated with it,
4440 // return that directly.
4441 const StringRef CustomDiag = S.getValueAsString(FieldName: "CustomDiag");
4442 if (!CustomDiag.empty())
4443 return ("\"" + Twine(CustomDiag) + "\"").str();
4444
4445 std::vector<std::string> DiagList;
4446 for (const auto *Subject : S.getValueAsListOfDefs(FieldName: "Subjects")) {
4447 const Record &R = *Subject;
4448 // Get the diagnostic text from the Decl or Stmt node given.
4449 std::string V = GetDiagnosticSpelling(R);
4450 if (V.empty()) {
4451 PrintError(ErrorLoc: R.getLoc(),
4452 Msg: "Could not determine diagnostic spelling for the node: " +
4453 R.getName() + "; please add one to DeclNodes.td");
4454 } else {
4455 // The node may contain a list of elements itself, so split the elements
4456 // by a comma, and trim any whitespace.
4457 SmallVector<StringRef, 2> Frags;
4458 SplitString(Source: V, OutFragments&: Frags, Delimiters: ",");
4459 for (auto Str : Frags) {
4460 DiagList.push_back(x: Str.trim().str());
4461 }
4462 }
4463 }
4464
4465 if (DiagList.empty()) {
4466 PrintFatalError(ErrorLoc: S.getLoc(),
4467 Msg: "Could not deduce diagnostic argument for Attr subjects");
4468 return "";
4469 }
4470
4471 // FIXME: this is not particularly good for localization purposes and ideally
4472 // should be part of the diagnostics engine itself with some sort of list
4473 // specifier.
4474
4475 // A single member of the list can be returned directly.
4476 if (DiagList.size() == 1)
4477 return '"' + DiagList.front() + '"';
4478
4479 if (DiagList.size() == 2)
4480 return '"' + DiagList[0] + " and " + DiagList[1] + '"';
4481
4482 // If there are more than two in the list, we serialize the first N - 1
4483 // elements with a comma. This leaves the string in the state: foo, bar,
4484 // baz (but misses quux). We can then add ", and " for the last element
4485 // manually.
4486 std::string Diag = join(Begin: DiagList.begin(), End: DiagList.end() - 1, Separator: ", ");
4487 return '"' + Diag + ", and " + *(DiagList.end() - 1) + '"';
4488}
4489
4490static std::string GetSubjectWithSuffix(const Record *R) {
4491 const std::string B = R->getName().str();
4492 if (B == "DeclBase")
4493 return "Decl";
4494 return B + "Decl";
4495}
4496
4497static std::string functionNameForCustomAppertainsTo(const Record &Subject) {
4498 return "is" + Subject.getName().str();
4499}
4500
4501static void GenerateCustomAppertainsTo(const Record &Subject, raw_ostream &OS) {
4502 std::string FnName = functionNameForCustomAppertainsTo(Subject);
4503
4504 // If this code has already been generated, we don't need to do anything.
4505 static std::set<std::string> CustomSubjectSet;
4506 auto I = CustomSubjectSet.find(x: FnName);
4507 if (I != CustomSubjectSet.end())
4508 return;
4509
4510 // This only works with non-root Decls.
4511 const Record *Base = Subject.getValueAsDef(BaseFieldName);
4512
4513 // Not currently support custom subjects within custom subjects.
4514 if (Base->isSubClassOf(Name: "SubsetSubject")) {
4515 PrintFatalError(ErrorLoc: Subject.getLoc(),
4516 Msg: "SubsetSubjects within SubsetSubjects is not supported");
4517 return;
4518 }
4519
4520 OS << "static bool " << FnName << "(const Decl *D) {\n";
4521 OS << " if (const auto *S = dyn_cast<";
4522 OS << GetSubjectWithSuffix(R: Base);
4523 OS << ">(D))\n";
4524 OS << " return " << Subject.getValueAsString(FieldName: "CheckCode") << ";\n";
4525 OS << " return false;\n";
4526 OS << "}\n\n";
4527
4528 CustomSubjectSet.insert(x: FnName);
4529}
4530
4531static void GenerateAppertainsTo(const Record &Attr, raw_ostream &OS) {
4532 // If the attribute does not contain a Subjects definition, then use the
4533 // default appertainsTo logic.
4534 if (Attr.isValueUnset(FieldName: "Subjects"))
4535 return;
4536
4537 const Record *SubjectObj = Attr.getValueAsDef(FieldName: "Subjects");
4538 std::vector<const Record *> Subjects =
4539 SubjectObj->getValueAsListOfDefs(FieldName: "Subjects");
4540
4541 // If the list of subjects is empty, it is assumed that the attribute
4542 // appertains to everything.
4543 if (Subjects.empty())
4544 return;
4545
4546 bool Warn = SubjectObj->getValueAsDef(FieldName: "Diag")->getValueAsBit(FieldName: "Warn");
4547
4548 // Split the subjects into declaration subjects and statement subjects.
4549 // FIXME: subset subjects are added to the declaration list until there are
4550 // enough statement attributes with custom subject needs to warrant
4551 // the implementation effort.
4552 std::vector<const Record *> DeclSubjects, StmtSubjects;
4553 copy_if(Range&: Subjects, Out: std::back_inserter(x&: DeclSubjects), P: [](const Record *R) {
4554 return R->isSubClassOf(Name: "SubsetSubject") || !R->isSubClassOf(Name: "StmtNode");
4555 });
4556 copy_if(Range&: Subjects, Out: std::back_inserter(x&: StmtSubjects),
4557 P: [](const Record *R) { return R->isSubClassOf(Name: "StmtNode"); });
4558
4559 // We should have sorted all of the subjects into two lists.
4560 // FIXME: this assertion will be wrong if we ever add type attribute subjects.
4561 assert(DeclSubjects.size() + StmtSubjects.size() == Subjects.size());
4562
4563 if (DeclSubjects.empty()) {
4564 // If there are no decl subjects but there are stmt subjects, diagnose
4565 // trying to apply a statement attribute to a declaration.
4566 if (!StmtSubjects.empty()) {
4567 OS << "bool diagAppertainsToDecl(Sema &S, const ParsedAttr &AL, ";
4568 OS << "const Decl *D) const override {\n";
4569 OS << " S.Diag(AL.getLoc(), diag::err_attribute_invalid_on_decl)\n";
4570 OS << " << AL << AL.isRegularKeywordAttribute() << "
4571 "D->getLocation();\n";
4572 OS << " return false;\n";
4573 OS << "}\n\n";
4574 }
4575 } else {
4576 // Otherwise, generate an appertainsTo check specific to this attribute
4577 // which checks all of the given subjects against the Decl passed in.
4578 OS << "bool diagAppertainsToDecl(Sema &S, ";
4579 OS << "const ParsedAttr &Attr, const Decl *D) const override {\n";
4580 OS << " if (";
4581 for (auto I = DeclSubjects.begin(), E = DeclSubjects.end(); I != E; ++I) {
4582 // If the subject has custom code associated with it, use the generated
4583 // function for it. The function cannot be inlined into this check (yet)
4584 // because it requires the subject to be of a specific type, and were that
4585 // information inlined here, it would not support an attribute with
4586 // multiple custom subjects.
4587 if ((*I)->isSubClassOf(Name: "SubsetSubject"))
4588 OS << "!" << functionNameForCustomAppertainsTo(Subject: **I) << "(D)";
4589 else
4590 OS << "!isa<" << GetSubjectWithSuffix(R: *I) << ">(D)";
4591
4592 if (I + 1 != E)
4593 OS << " && ";
4594 }
4595 OS << ") {\n";
4596 OS << " S.Diag(Attr.getLoc(), diag::";
4597 OS << (Warn ? "warn_attribute_wrong_decl_type_str"
4598 : "err_attribute_wrong_decl_type_str");
4599 OS << ")\n";
4600 OS << " << Attr << Attr.isRegularKeywordAttribute() << ";
4601 OS << CalculateDiagnostic(S: *SubjectObj) << ";\n";
4602 OS << " return false;\n";
4603 OS << " }\n";
4604 OS << " return true;\n";
4605 OS << "}\n\n";
4606 }
4607
4608 if (StmtSubjects.empty()) {
4609 // If there are no stmt subjects but there are decl subjects, diagnose
4610 // trying to apply a declaration attribute to a statement.
4611 if (!DeclSubjects.empty()) {
4612 OS << "bool diagAppertainsToStmt(Sema &S, const ParsedAttr &AL, ";
4613 OS << "const Stmt *St) const override {\n";
4614 OS << " S.Diag(AL.getLoc(), diag::err_decl_attribute_invalid_on_stmt)\n";
4615 OS << " << AL << AL.isRegularKeywordAttribute() << "
4616 "St->getBeginLoc();\n";
4617 OS << " return false;\n";
4618 OS << "}\n\n";
4619 }
4620 } else {
4621 // Now, do the same for statements.
4622 OS << "bool diagAppertainsToStmt(Sema &S, ";
4623 OS << "const ParsedAttr &Attr, const Stmt *St) const override {\n";
4624 OS << " if (";
4625 for (auto I = StmtSubjects.begin(), E = StmtSubjects.end(); I != E; ++I) {
4626 OS << "!isa<" << (*I)->getName() << ">(St)";
4627 if (I + 1 != E)
4628 OS << " && ";
4629 }
4630 OS << ") {\n";
4631 OS << " S.Diag(Attr.getLoc(), diag::";
4632 OS << (Warn ? "warn_attribute_wrong_decl_type_str"
4633 : "err_attribute_wrong_decl_type_str");
4634 OS << ")\n";
4635 OS << " << Attr << Attr.isRegularKeywordAttribute() << ";
4636 OS << CalculateDiagnostic(S: *SubjectObj) << ";\n";
4637 OS << " return false;\n";
4638 OS << " }\n";
4639 OS << " return true;\n";
4640 OS << "}\n\n";
4641 }
4642}
4643
4644// Generates the mutual exclusion checks. The checks for parsed attributes are
4645// written into OS and the checks for merging declaration attributes are
4646// written into MergeOS.
4647static void GenerateMutualExclusionsChecks(const Record &Attr,
4648 const RecordKeeper &Records,
4649 raw_ostream &OS,
4650 raw_ostream &MergeDeclOS,
4651 raw_ostream &MergeStmtOS) {
4652 // We don't do any of this magic for type attributes yet.
4653 if (Attr.isSubClassOf(Name: "TypeAttr"))
4654 return;
4655
4656 // This means the attribute is either a statement attribute, a decl
4657 // attribute, or both; find out which.
4658 bool CurAttrIsStmtAttr = Attr.isSubClassOf(Name: "StmtAttr") ||
4659 Attr.isSubClassOf(Name: "DeclOrStmtAttr") ||
4660 Attr.isSubClassOf(Name: "InheritableParamOrStmtAttr");
4661 bool CurAttrIsDeclAttr = !CurAttrIsStmtAttr ||
4662 Attr.isSubClassOf(Name: "DeclOrStmtAttr") ||
4663 Attr.isSubClassOf(Name: "InheritableParamOrStmtAttr");
4664
4665 std::vector<std::string> DeclAttrs, StmtAttrs;
4666
4667 // Find all of the definitions that inherit from MutualExclusions and include
4668 // the given attribute in the list of exclusions to generate the
4669 // diagMutualExclusion() check.
4670 for (const Record *Exclusion :
4671 Records.getAllDerivedDefinitions(ClassName: "MutualExclusions")) {
4672 std::vector<const Record *> MutuallyExclusiveAttrs =
4673 Exclusion->getValueAsListOfDefs(FieldName: "Exclusions");
4674 auto IsCurAttr = [Attr](const Record *R) {
4675 return R->getName() == Attr.getName();
4676 };
4677 if (any_of(Range&: MutuallyExclusiveAttrs, P: IsCurAttr)) {
4678 // This list of exclusions includes the attribute we're looking for, so
4679 // add the exclusive attributes to the proper list for checking.
4680 for (const Record *AttrToExclude : MutuallyExclusiveAttrs) {
4681 if (IsCurAttr(AttrToExclude))
4682 continue;
4683
4684 if (CurAttrIsStmtAttr)
4685 StmtAttrs.push_back(x: (AttrToExclude->getName() + "Attr").str());
4686 if (CurAttrIsDeclAttr)
4687 DeclAttrs.push_back(x: (AttrToExclude->getName() + "Attr").str());
4688 }
4689 }
4690 }
4691
4692 // If there are any decl or stmt attributes, silence -Woverloaded-virtual
4693 // warnings for them both.
4694 if (!DeclAttrs.empty() || !StmtAttrs.empty())
4695 OS << " using ParsedAttrInfo::diagMutualExclusion;\n\n";
4696
4697 // If we discovered any decl or stmt attributes to test for, generate the
4698 // predicates for them now.
4699 if (!DeclAttrs.empty()) {
4700 // Generate the ParsedAttrInfo subclass logic for declarations.
4701 OS << " bool diagMutualExclusion(Sema &S, const ParsedAttr &AL, "
4702 << "const Decl *D) const override {\n";
4703 for (const std::string &A : DeclAttrs) {
4704 OS << " if (const auto *A = D->getAttr<" << A << ">()) {\n";
4705 OS << " S.Diag(AL.getLoc(), diag::err_attributes_are_not_compatible)"
4706 << " << AL << A << (AL.isRegularKeywordAttribute() ||"
4707 << " A->isRegularKeywordAttribute());\n";
4708 OS << " S.Diag(A->getLocation(), diag::note_conflicting_attribute);";
4709 OS << " \nreturn false;\n";
4710 OS << " }\n";
4711 }
4712 OS << " return true;\n";
4713 OS << " }\n\n";
4714
4715 // Also generate the declaration attribute merging logic if the current
4716 // attribute is one that can be inheritted on a declaration. It is assumed
4717 // this code will be executed in the context of a function with parameters:
4718 // Sema &S, Decl *D, Attr *A and that returns a bool (false on diagnostic,
4719 // true on success).
4720 if (Attr.isSubClassOf(Name: "InheritableAttr")) {
4721 MergeDeclOS << " if (const auto *Second = dyn_cast<"
4722 << (Attr.getName() + "Attr").str() << ">(A)) {\n";
4723 for (const std::string &A : DeclAttrs) {
4724 MergeDeclOS << " if (const auto *First = D->getAttr<" << A
4725 << ">()) {\n";
4726 MergeDeclOS << " S.Diag(First->getLocation(), "
4727 << "diag::err_attributes_are_not_compatible) << First << "
4728 << "Second << (First->isRegularKeywordAttribute() || "
4729 << "Second->isRegularKeywordAttribute());\n";
4730 MergeDeclOS << " S.Diag(Second->getLocation(), "
4731 << "diag::note_conflicting_attribute);\n";
4732 MergeDeclOS << " return false;\n";
4733 MergeDeclOS << " }\n";
4734 }
4735 MergeDeclOS << " return true;\n";
4736 MergeDeclOS << " }\n";
4737 }
4738 }
4739
4740 // Statement attributes are a bit different from declarations. With
4741 // declarations, each attribute is added to the declaration as it is
4742 // processed, and so you can look on the Decl * itself to see if there is a
4743 // conflicting attribute. Statement attributes are processed as a group
4744 // because AttributedStmt needs to tail-allocate all of the attribute nodes
4745 // at once. This means we cannot check whether the statement already contains
4746 // an attribute to check for the conflict. Instead, we need to check whether
4747 // the given list of semantic attributes contain any conflicts. It is assumed
4748 // this code will be executed in the context of a function with parameters:
4749 // Sema &S, const SmallVectorImpl<const Attr *> &C. The code will be within a
4750 // loop which loops over the container C with a loop variable named A to
4751 // represent the current attribute to check for conflicts.
4752 //
4753 // FIXME: it would be nice not to walk over the list of potential attributes
4754 // to apply to the statement more than once, but statements typically don't
4755 // have long lists of attributes on them, so re-walking the list should not
4756 // be an expensive operation.
4757 if (!StmtAttrs.empty()) {
4758 MergeStmtOS << " if (const auto *Second = dyn_cast<"
4759 << (Attr.getName() + "Attr").str() << ">(A)) {\n";
4760 MergeStmtOS << " auto Iter = llvm::find_if(C, [](const Attr *Check) "
4761 << "{ return isa<";
4762 interleave(
4763 c: StmtAttrs, each_fn: [&](StringRef Name) { MergeStmtOS << Name; },
4764 between_fn: [&] { MergeStmtOS << ", "; });
4765 MergeStmtOS << ">(Check); });\n";
4766 MergeStmtOS << " if (Iter != C.end()) {\n";
4767 MergeStmtOS << " S.Diag((*Iter)->getLocation(), "
4768 << "diag::err_attributes_are_not_compatible) << *Iter << "
4769 << "Second << ((*Iter)->isRegularKeywordAttribute() || "
4770 << "Second->isRegularKeywordAttribute());\n";
4771 MergeStmtOS << " S.Diag(Second->getLocation(), "
4772 << "diag::note_conflicting_attribute);\n";
4773 MergeStmtOS << " return false;\n";
4774 MergeStmtOS << " }\n";
4775 MergeStmtOS << " }\n";
4776 }
4777}
4778
4779static void
4780emitAttributeMatchRules(PragmaClangAttributeSupport &PragmaAttributeSupport,
4781 raw_ostream &OS) {
4782 OS << "static bool checkAttributeMatchRuleAppliesTo(const Decl *D, "
4783 << AttributeSubjectMatchRule::EnumName << " rule) {\n";
4784 OS << " switch (rule) {\n";
4785 for (const auto &Rule : PragmaAttributeSupport.Rules) {
4786 if (Rule.isAbstractRule()) {
4787 OS << " case " << Rule.getEnumValue() << ":\n";
4788 OS << " assert(false && \"Abstract matcher rule isn't allowed\");\n";
4789 OS << " return false;\n";
4790 continue;
4791 }
4792 std::vector<const Record *> Subjects = Rule.getSubjects();
4793 assert(!Subjects.empty() && "Missing subjects");
4794 OS << " case " << Rule.getEnumValue() << ":\n";
4795 OS << " return ";
4796 for (auto I = Subjects.begin(), E = Subjects.end(); I != E; ++I) {
4797 // If the subject has custom code associated with it, use the function
4798 // that was generated for GenerateAppertainsTo to check if the declaration
4799 // is valid.
4800 if ((*I)->isSubClassOf(Name: "SubsetSubject"))
4801 OS << functionNameForCustomAppertainsTo(Subject: **I) << "(D)";
4802 else
4803 OS << "isa<" << GetSubjectWithSuffix(R: *I) << ">(D)";
4804
4805 if (I + 1 != E)
4806 OS << " || ";
4807 }
4808 OS << ";\n";
4809 }
4810 OS << " }\n";
4811 OS << " llvm_unreachable(\"Invalid match rule\");\nreturn false;\n";
4812 OS << "}\n\n";
4813}
4814
4815static void GenerateLangOptRequirements(const Record &R,
4816 raw_ostream &OS) {
4817 // If the attribute has an empty or unset list of language requirements,
4818 // use the default handler.
4819 std::vector<const Record *> LangOpts = R.getValueAsListOfDefs(FieldName: "LangOpts");
4820 if (LangOpts.empty())
4821 return;
4822
4823 OS << "bool acceptsLangOpts(const LangOptions &LangOpts) const override {\n";
4824 OS << " return " << GenerateTestExpression(LangOpts) << ";\n";
4825 OS << "}\n\n";
4826}
4827
4828static void GenerateTargetRequirements(const Record &Attr,
4829 const ParsedAttrMap &Dupes,
4830 raw_ostream &OS) {
4831 // If the attribute is not a target specific attribute, use the default
4832 // target handler.
4833 if (!Attr.isSubClassOf(Name: "TargetSpecificAttr"))
4834 return;
4835
4836 // Get the list of architectures to be tested for.
4837 const Record *R = Attr.getValueAsDef(FieldName: "Target");
4838 std::vector<StringRef> Arches = R->getValueAsListOfStrings(FieldName: "Arches");
4839
4840 // If there are other attributes which share the same parsed attribute kind,
4841 // such as target-specific attributes with a shared spelling, collapse the
4842 // duplicate architectures. This is required because a shared target-specific
4843 // attribute has only one ParsedAttr::Kind enumeration value, but it
4844 // applies to multiple target architectures. In order for the attribute to be
4845 // considered valid, all of its architectures need to be included.
4846 if (!Attr.isValueUnset(FieldName: "ParseKind")) {
4847 const StringRef APK = Attr.getValueAsString(FieldName: "ParseKind");
4848 for (const auto &I : Dupes) {
4849 if (I.first == APK) {
4850 std::vector<StringRef> DA =
4851 I.second->getValueAsDef(FieldName: "Target")->getValueAsListOfStrings(
4852 FieldName: "Arches");
4853 llvm::append_range(C&: Arches, R&: DA);
4854 }
4855 }
4856 }
4857
4858 std::string FnName = "isTarget";
4859 std::string Test;
4860 bool UsesT = GenerateTargetSpecificAttrChecks(R, Arches, Test, FnName: &FnName);
4861
4862 OS << "bool existsInTarget(const TargetInfo &Target) const override {\n";
4863 if (UsesT)
4864 OS << " const llvm::Triple &T = Target.getTriple(); (void)T;\n";
4865 OS << " return " << Test << ";\n";
4866 OS << "}\n\n";
4867}
4868
4869static void
4870GenerateSpellingTargetRequirements(const Record &Attr,
4871 ArrayRef<const Record *> TargetSpellings,
4872 raw_ostream &OS) {
4873 // If there are no target specific spellings, use the default target handler.
4874 if (TargetSpellings.empty())
4875 return;
4876
4877 std::string Test;
4878 bool UsesT = false;
4879 const std::vector<FlattenedSpelling> SpellingList =
4880 GetFlattenedSpellings(Attr);
4881 for (unsigned TargetIndex = 0; TargetIndex < TargetSpellings.size();
4882 ++TargetIndex) {
4883 const auto &TargetSpelling = TargetSpellings[TargetIndex];
4884 std::vector<FlattenedSpelling> Spellings =
4885 GetFlattenedSpellings(Attr: *TargetSpelling);
4886
4887 Test += "((SpellingListIndex == ";
4888 for (unsigned Index = 0; Index < Spellings.size(); ++Index) {
4889 Test += itostr(X: getSpellingListIndex(SpellingList, Spelling: Spellings[Index]));
4890 if (Index != Spellings.size() - 1)
4891 Test += " ||\n SpellingListIndex == ";
4892 else
4893 Test += ") && ";
4894 }
4895
4896 const Record *Target = TargetSpelling->getValueAsDef(FieldName: "Target");
4897 std::vector<StringRef> Arches = Target->getValueAsListOfStrings(FieldName: "Arches");
4898 std::string FnName = "isTargetSpelling";
4899 UsesT |= GenerateTargetSpecificAttrChecks(R: Target, Arches, Test, FnName: &FnName);
4900 Test += ")";
4901 if (TargetIndex != TargetSpellings.size() - 1)
4902 Test += " || ";
4903 }
4904
4905 OS << "bool spellingExistsInTarget(const TargetInfo &Target,\n";
4906 OS << " const unsigned SpellingListIndex) const "
4907 "override {\n";
4908 if (UsesT)
4909 OS << " const llvm::Triple &T = Target.getTriple(); (void)T;\n";
4910 OS << " return " << Test << ";\n", OS << "}\n\n";
4911}
4912
4913static void GenerateSpellingIndexToSemanticSpelling(const Record &Attr,
4914 raw_ostream &OS) {
4915 // If the attribute does not have a semantic form, we can bail out early.
4916 if (!Attr.getValueAsBit(FieldName: "ASTNode"))
4917 return;
4918
4919 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(Attr);
4920
4921 // If there are zero or one spellings, or all of the spellings share the same
4922 // name, we can also bail out early.
4923 if (Spellings.size() <= 1 || SpellingNamesAreCommon(Spellings))
4924 return;
4925
4926 // Generate the enumeration we will use for the mapping.
4927 SemanticSpellingMap SemanticToSyntacticMap;
4928 std::string Enum = CreateSemanticSpellings(Spellings, Map&: SemanticToSyntacticMap);
4929
4930 OS << "unsigned spellingIndexToSemanticSpelling(";
4931 OS << "const ParsedAttr &Attr) const override {\n";
4932 OS << Enum;
4933 OS << " unsigned Idx = Attr.getAttributeSpellingListIndex();\n";
4934 WriteSemanticSpellingSwitch(VarName: "Idx", Map: SemanticToSyntacticMap, OS);
4935 OS << "}\n\n";
4936}
4937
4938static void GenerateHandleDeclAttribute(const Record &Attr, raw_ostream &OS) {
4939 // Only generate if Attr can be handled simply.
4940 if (!Attr.getValueAsBit(FieldName: "SimpleHandler"))
4941 return;
4942
4943 // Generate a function which just converts from ParsedAttr to the Attr type.
4944 OS << "AttrHandling handleDeclAttribute(Sema &S, Decl *D,";
4945 OS << "const ParsedAttr &Attr) const override {\n";
4946 OS << " D->addAttr(::new (S.Context) " << Attr.getName();
4947 OS << "Attr(S.Context, Attr));\n";
4948 OS << " return AttributeApplied;\n";
4949 OS << "}\n\n";
4950}
4951
4952static bool isParamExpr(const Record *Arg) {
4953 return !Arg->getDirectSuperClasses().empty() &&
4954 StringSwitch<bool>(
4955 Arg->getDirectSuperClasses().back().first->getName())
4956 .Case(S: "ExprArgument", Value: true)
4957 .Case(S: "VariadicExprArgument", Value: true)
4958 .Default(Value: false);
4959}
4960
4961static void GenerateIsParamExpr(const Record &Attr, raw_ostream &OS) {
4962 OS << "bool isParamExpr(size_t N) const override {\n";
4963 OS << " return ";
4964 auto Args = Attr.getValueAsListOfDefs(FieldName: "Args");
4965 for (size_t I = 0; I < Args.size(); ++I)
4966 if (isParamExpr(Arg: Args[I]))
4967 OS << "(N == " << I << ") || ";
4968 OS << "false;\n";
4969 OS << "}\n\n";
4970}
4971
4972static void GenerateHandleAttrWithDelayedArgs(const RecordKeeper &Records,
4973 raw_ostream &OS) {
4974 OS << "static void handleAttrWithDelayedArgs(Sema &S, Decl *D, ";
4975 OS << "const ParsedAttr &Attr) {\n";
4976 OS << " SmallVector<Expr *, 4> ArgExprs;\n";
4977 OS << " ArgExprs.reserve(Attr.getNumArgs());\n";
4978 OS << " for (unsigned I = 0; I < Attr.getNumArgs(); ++I) {\n";
4979 OS << " assert(!Attr.isArgIdent(I));\n";
4980 OS << " ArgExprs.push_back(Attr.getArgAsExpr(I));\n";
4981 OS << " }\n";
4982 OS << " clang::Attr *CreatedAttr = nullptr;\n";
4983 OS << " switch (Attr.getKind()) {\n";
4984 OS << " default:\n";
4985 OS << " llvm_unreachable(\"Attribute cannot hold delayed arguments.\");\n";
4986 ParsedAttrMap Attrs = getParsedAttrList(Records);
4987 for (const auto &I : Attrs) {
4988 const Record &R = *I.second;
4989 if (!R.getValueAsBit(FieldName: "AcceptsExprPack"))
4990 continue;
4991 OS << " case ParsedAttr::AT_" << I.first << ": {\n";
4992 OS << " CreatedAttr = " << R.getName() << "Attr::CreateWithDelayedArgs";
4993 OS << "(S.Context, ArgExprs.data(), ArgExprs.size(), Attr);\n";
4994 OS << " break;\n";
4995 OS << " }\n";
4996 }
4997 OS << " }\n";
4998 OS << " D->addAttr(CreatedAttr);\n";
4999 OS << "}\n\n";
5000}
5001
5002static bool IsKnownToGCC(const Record &Attr) {
5003 // Look at the spellings for this subject; if there are any spellings which
5004 // claim to be known to GCC, the attribute is known to GCC.
5005 return any_of(Range: GetFlattenedSpellings(Attr),
5006 P: [](const FlattenedSpelling &S) { return S.knownToGCC(); });
5007}
5008
5009/// Emits the parsed attribute helpers
5010void EmitClangAttrParsedAttrImpl(const RecordKeeper &Records, raw_ostream &OS) {
5011 emitSourceFileHeader(Desc: "Parsed attribute helpers", OS, Record: Records);
5012
5013 OS << "#if !defined(WANT_DECL_MERGE_LOGIC) && "
5014 << "!defined(WANT_STMT_MERGE_LOGIC)\n";
5015 PragmaClangAttributeSupport &PragmaAttributeSupport =
5016 getPragmaAttributeSupport(Records);
5017
5018 // Get the list of parsed attributes, and accept the optional list of
5019 // duplicates due to the ParseKind.
5020 ParsedAttrMap Dupes;
5021 ParsedAttrMap Attrs = getParsedAttrList(Records, Dupes: &Dupes);
5022
5023 // Generate all of the custom appertainsTo functions that the attributes
5024 // will be using.
5025 for (const auto &I : Attrs) {
5026 const Record &Attr = *I.second;
5027 if (Attr.isValueUnset(FieldName: "Subjects"))
5028 continue;
5029 const Record *SubjectObj = Attr.getValueAsDef(FieldName: "Subjects");
5030 for (const Record *Subject : SubjectObj->getValueAsListOfDefs(FieldName: "Subjects"))
5031 if (Subject->isSubClassOf(Name: "SubsetSubject"))
5032 GenerateCustomAppertainsTo(Subject: *Subject, OS);
5033 }
5034
5035 // This stream is used to collect all of the declaration attribute merging
5036 // logic for performing mutual exclusion checks. This gets emitted at the
5037 // end of the file in a helper function of its own.
5038 std::string DeclMergeChecks, StmtMergeChecks;
5039 raw_string_ostream MergeDeclOS(DeclMergeChecks), MergeStmtOS(StmtMergeChecks);
5040
5041 // Generate a ParsedAttrInfo struct for each of the attributes.
5042 for (auto I = Attrs.begin(), E = Attrs.end(); I != E; ++I) {
5043 // TODO: If the attribute's kind appears in the list of duplicates, that is
5044 // because it is a target-specific attribute that appears multiple times.
5045 // It would be beneficial to test whether the duplicates are "similar
5046 // enough" to each other to not cause problems. For instance, check that
5047 // the spellings are identical, and custom parsing rules match, etc.
5048
5049 // We need to generate struct instances based off ParsedAttrInfo from
5050 // ParsedAttr.cpp.
5051 const std::string &AttrName = I->first;
5052 const Record &Attr = *I->second;
5053 auto Spellings = GetFlattenedSpellings(Attr);
5054 if (!Spellings.empty()) {
5055 OS << "static constexpr ParsedAttrInfo::Spelling " << I->first
5056 << "Spellings[] = {\n";
5057 for (const auto &S : Spellings) {
5058 StringRef RawSpelling = S.name();
5059 std::string Spelling;
5060 if (!S.nameSpace().empty())
5061 Spelling += S.nameSpace().str() + "::";
5062 if (S.variety() == "GNU")
5063 Spelling += NormalizeGNUAttrSpelling(AttrSpelling: RawSpelling);
5064 else
5065 Spelling += RawSpelling;
5066 OS << " {AttributeCommonInfo::AS_" << S.variety();
5067 OS << ", \"" << Spelling << "\"},\n";
5068 }
5069 OS << "};\n";
5070 }
5071
5072 std::vector<std::string> ArgNames;
5073 for (const auto *Arg : Attr.getValueAsListOfDefs(FieldName: "Args")) {
5074 bool UnusedUnset;
5075 if (Arg->getValueAsBitOrUnset(FieldName: "Fake", Unset&: UnusedUnset))
5076 continue;
5077 ArgNames.push_back(x: Arg->getValueAsString(FieldName: "Name").str());
5078 for (const Record *Class : Arg->getSuperClasses()) {
5079 if (Class->getName().starts_with(Prefix: "Variadic")) {
5080 ArgNames.back().append(s: "...");
5081 break;
5082 }
5083 }
5084 }
5085 if (!ArgNames.empty()) {
5086 OS << "static constexpr const char *" << I->first << "ArgNames[] = {\n";
5087 for (const auto &N : ArgNames)
5088 OS << '"' << N << "\",";
5089 OS << "};\n";
5090 }
5091
5092 OS << "struct ParsedAttrInfo" << I->first
5093 << " final : public ParsedAttrInfo {\n";
5094 OS << " constexpr ParsedAttrInfo" << I->first << "() : ParsedAttrInfo(\n";
5095 OS << " /*AttrKind=*/ParsedAttr::AT_" << AttrName << ",\n";
5096 emitArgInfo(R: Attr, OS);
5097 OS << " /*HasCustomParsing=*/";
5098 OS << Attr.getValueAsBit(FieldName: "HasCustomParsing") << ",\n";
5099 OS << " /*AcceptsExprPack=*/";
5100 OS << Attr.getValueAsBit(FieldName: "AcceptsExprPack") << ",\n";
5101 OS << " /*IsTargetSpecific=*/";
5102 OS << Attr.isSubClassOf(Name: "TargetSpecificAttr") << ",\n";
5103 OS << " /*IsType=*/";
5104 OS << (Attr.isSubClassOf(Name: "TypeAttr") || Attr.isSubClassOf(Name: "DeclOrTypeAttr"))
5105 << ",\n";
5106 OS << " /*IsStmt=*/";
5107 OS << (Attr.isSubClassOf(Name: "StmtAttr") || Attr.isSubClassOf(Name: "DeclOrStmtAttr"))
5108 << ",\n";
5109 OS << " /*IsKnownToGCC=*/";
5110 OS << IsKnownToGCC(Attr) << ",\n";
5111 OS << " /*IsSupportedByPragmaAttribute=*/";
5112 OS << PragmaAttributeSupport.isAttributedSupported(Attribute: *I->second) << ",\n";
5113 if (!Spellings.empty())
5114 OS << " /*Spellings=*/" << I->first << "Spellings,\n";
5115 else
5116 OS << " /*Spellings=*/{},\n";
5117 if (!ArgNames.empty())
5118 OS << " /*ArgNames=*/" << I->first << "ArgNames";
5119 else
5120 OS << " /*ArgNames=*/{}";
5121 OS << ") {}\n";
5122 GenerateAppertainsTo(Attr, OS);
5123 GenerateMutualExclusionsChecks(Attr, Records, OS, MergeDeclOS, MergeStmtOS);
5124 GenerateLangOptRequirements(R: Attr, OS);
5125 GenerateTargetRequirements(Attr, Dupes, OS);
5126 GenerateSpellingTargetRequirements(
5127 Attr, TargetSpellings: Attr.getValueAsListOfDefs(FieldName: "TargetSpecificSpellings"), OS);
5128 GenerateSpellingIndexToSemanticSpelling(Attr, OS);
5129 PragmaAttributeSupport.generateStrictConformsTo(Attr: *I->second, OS);
5130 GenerateHandleDeclAttribute(Attr, OS);
5131 GenerateIsParamExpr(Attr, OS);
5132 OS << "static const ParsedAttrInfo" << I->first << " Instance;\n";
5133 OS << "};\n";
5134 OS << "const ParsedAttrInfo" << I->first << " ParsedAttrInfo" << I->first
5135 << "::Instance;\n";
5136 }
5137
5138 OS << "static const ParsedAttrInfo *AttrInfoMap[] = {\n";
5139 for (const auto &Attr : Attrs)
5140 OS << "&ParsedAttrInfo" << Attr.first << "::Instance,\n";
5141 OS << "};\n\n";
5142
5143 // Generate function for handling attributes with delayed arguments
5144 GenerateHandleAttrWithDelayedArgs(Records, OS);
5145
5146 // Generate the attribute match rules.
5147 emitAttributeMatchRules(PragmaAttributeSupport, OS);
5148
5149 OS << "#elif defined(WANT_DECL_MERGE_LOGIC)\n\n";
5150
5151 // Write out the declaration merging check logic.
5152 OS << "static bool DiagnoseMutualExclusions(Sema &S, const NamedDecl *D, "
5153 << "const Attr *A) {\n";
5154 OS << DeclMergeChecks;
5155 OS << " return true;\n";
5156 OS << "}\n\n";
5157
5158 OS << "#elif defined(WANT_STMT_MERGE_LOGIC)\n\n";
5159
5160 // Write out the statement merging check logic.
5161 OS << "static bool DiagnoseMutualExclusions(Sema &S, "
5162 << "const SmallVectorImpl<const Attr *> &C) {\n";
5163 OS << " for (const Attr *A : C) {\n";
5164 OS << StmtMergeChecks;
5165 OS << " }\n";
5166 OS << " return true;\n";
5167 OS << "}\n\n";
5168
5169 OS << "#endif\n";
5170}
5171
5172// Emits the kind list of parsed attributes
5173void EmitClangAttrParsedAttrKinds(const RecordKeeper &Records,
5174 raw_ostream &OS) {
5175 emitSourceFileHeader(Desc: "Attribute name matcher", OS, Record: Records);
5176
5177 std::vector<StringMatcher::StringPair> GNU, Declspec, Microsoft, CXX11,
5178 Keywords, Pragma, C23, HLSLAnnotation;
5179 std::set<StringRef> Seen;
5180 for (const auto *A : Records.getAllDerivedDefinitions(ClassName: "Attr")) {
5181 const Record &Attr = *A;
5182
5183 bool SemaHandler = Attr.getValueAsBit(FieldName: "SemaHandler");
5184 bool Ignored = Attr.getValueAsBit(FieldName: "Ignored");
5185 if (SemaHandler || Ignored) {
5186 // Attribute spellings can be shared between target-specific attributes,
5187 // and can be shared between syntaxes for the same attribute. For
5188 // instance, an attribute can be spelled GNU<"interrupt"> for an ARM-
5189 // specific attribute, or MSP430-specific attribute. Additionally, an
5190 // attribute can be spelled GNU<"dllexport"> and Declspec<"dllexport">
5191 // for the same semantic attribute. Ultimately, we need to map each of
5192 // these to a single AttributeCommonInfo::Kind value, but the
5193 // StringMatcher class cannot handle duplicate match strings. So we
5194 // generate a list of string to match based on the syntax, and emit
5195 // multiple string matchers depending on the syntax used.
5196 std::string AttrName;
5197 if (Attr.isSubClassOf(Name: "TargetSpecificAttr") &&
5198 !Attr.isValueUnset(FieldName: "ParseKind")) {
5199 StringRef ParseKind = Attr.getValueAsString(FieldName: "ParseKind");
5200 if (!Seen.insert(x: ParseKind).second)
5201 continue;
5202 AttrName = ParseKind.str();
5203 } else {
5204 AttrName = NormalizeAttrName(AttrName: Attr.getName()).str();
5205 }
5206
5207 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(Attr);
5208 for (const auto &S : Spellings) {
5209 StringRef RawSpelling = S.name();
5210 std::vector<StringMatcher::StringPair> *Matches = nullptr;
5211 std::string Spelling;
5212 StringRef Variety = S.variety();
5213 if (Variety == "CXX11") {
5214 Matches = &CXX11;
5215 if (!S.nameSpace().empty())
5216 Spelling += S.nameSpace().str() + "::";
5217 } else if (Variety == "C23") {
5218 Matches = &C23;
5219 if (!S.nameSpace().empty())
5220 Spelling += S.nameSpace().str() + "::";
5221 } else if (Variety == "GNU") {
5222 Matches = &GNU;
5223 } else if (Variety == "Declspec") {
5224 Matches = &Declspec;
5225 } else if (Variety == "Microsoft") {
5226 Matches = &Microsoft;
5227 } else if (Variety == "Keyword") {
5228 Matches = &Keywords;
5229 } else if (Variety == "Pragma") {
5230 Matches = &Pragma;
5231 } else if (Variety == "HLSLAnnotation") {
5232 Matches = &HLSLAnnotation;
5233 if (RawSpelling.compare(RHS: RawSpelling.lower()) != 0)
5234 PrintError(ErrorLoc: S.getSpellingRecord().getLoc(),
5235 Msg: "HLSLAnnotation Attribute must be lower case.");
5236 }
5237
5238 assert(Matches && "Unsupported spelling variety found");
5239
5240 if (Variety == "GNU")
5241 Spelling += NormalizeGNUAttrSpelling(AttrSpelling: RawSpelling);
5242 else
5243 Spelling += RawSpelling;
5244
5245 if (SemaHandler)
5246 Matches->push_back(x: StringMatcher::StringPair(
5247 Spelling, "return AttributeCommonInfo::AT_" + AttrName + ";"));
5248 else
5249 Matches->push_back(x: StringMatcher::StringPair(
5250 Spelling, "return AttributeCommonInfo::IgnoredAttribute;"));
5251 }
5252 }
5253 }
5254
5255 OS << "static AttributeCommonInfo::Kind getAttrKind(StringRef Name, ";
5256 OS << "AttributeCommonInfo::Syntax Syntax) {\n";
5257 OS << " if (AttributeCommonInfo::AS_GNU == Syntax) {\n";
5258 StringMatcher("Name", GNU, OS).Emit();
5259 OS << " } else if (AttributeCommonInfo::AS_Declspec == Syntax) {\n";
5260 StringMatcher("Name", Declspec, OS).Emit();
5261 OS << " } else if (AttributeCommonInfo::AS_Microsoft == Syntax) {\n";
5262 StringMatcher("Name", Microsoft, OS).Emit();
5263 OS << " } else if (AttributeCommonInfo::AS_CXX11 == Syntax) {\n";
5264 StringMatcher("Name", CXX11, OS).Emit();
5265 OS << " } else if (AttributeCommonInfo::AS_C23 == Syntax) {\n";
5266 StringMatcher("Name", C23, OS).Emit();
5267 OS << " } else if (AttributeCommonInfo::AS_Keyword == Syntax || ";
5268 OS << "AttributeCommonInfo::AS_ContextSensitiveKeyword == Syntax) {\n";
5269 StringMatcher("Name", Keywords, OS).Emit();
5270 OS << " } else if (AttributeCommonInfo::AS_Pragma == Syntax) {\n";
5271 StringMatcher("Name", Pragma, OS).Emit();
5272 OS << " } else if (AttributeCommonInfo::AS_HLSLAnnotation == Syntax) {\n";
5273 StringMatcher("Name", HLSLAnnotation, OS).Emit();
5274 OS << " }\n";
5275 OS << " return AttributeCommonInfo::UnknownAttribute;\n"
5276 << "}\n";
5277}
5278
5279// Emits Sema calls for type dependent attributes
5280void EmitClangAttrIsTypeDependent(const RecordKeeper &Records,
5281 raw_ostream &OS) {
5282 emitSourceFileHeader(Desc: "Attribute is type dependent", OS, Record: Records);
5283
5284 OS << "void checkAttrIsTypeDependent(Decl *D, const Attr *A) {\n";
5285 OS << " switch (A->getKind()) {\n";
5286 OS << " default:\n";
5287 OS << " break;\n";
5288 for (const auto *A : Records.getAllDerivedDefinitions(ClassName: "Attr")) {
5289 if (A->getValueAsBit(FieldName: "IsTypeDependent")) {
5290 OS << " case attr::" << A->getName() << ":\n";
5291 OS << " ActOn" << A->getName() << "Attr(D, A);\n";
5292 OS << " break;\n";
5293 }
5294 }
5295 OS << " }\n";
5296 OS << "}\n";
5297}
5298
5299// Emits the code to dump an attribute.
5300void EmitClangAttrTextNodeDump(const RecordKeeper &Records, raw_ostream &OS) {
5301 emitSourceFileHeader(Desc: "Attribute text node dumper", OS, Record: Records);
5302
5303 for (const auto *Attr : Records.getAllDerivedDefinitions(ClassName: "Attr")) {
5304 const Record &R = *Attr;
5305 if (!R.getValueAsBit(FieldName: "ASTNode"))
5306 continue;
5307
5308 // If the attribute has a semantically-meaningful name (which is determined
5309 // by whether there is a Spelling enumeration for it), then write out the
5310 // spelling used for the attribute.
5311
5312 std::string FunctionContent;
5313 raw_string_ostream SS(FunctionContent);
5314
5315 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(Attr: R);
5316 if (Spellings.size() > 1 && !SpellingNamesAreCommon(Spellings))
5317 SS << " OS << \" \" << A->getSpelling();\n";
5318
5319 std::vector<const Record *> Args = R.getValueAsListOfDefs(FieldName: "Args");
5320 for (const auto *Arg : Args)
5321 createArgument(Arg: *Arg, Attr: R.getName())->writeDump(OS&: SS);
5322
5323 if (Attr->getValueAsBit(FieldName: "AcceptsExprPack"))
5324 VariadicExprArgument("DelayedArgs", R.getName()).writeDump(OS);
5325
5326 if (SS.tell()) {
5327 OS << " void Visit" << R.getName() << "Attr(const " << R.getName()
5328 << "Attr *A) {\n";
5329 if (!Args.empty())
5330 OS << " const auto *SA = cast<" << R.getName()
5331 << "Attr>(A); (void)SA;\n";
5332 OS << FunctionContent;
5333 OS << " }\n";
5334 }
5335 }
5336}
5337
5338void EmitClangAttrNodeTraverse(const RecordKeeper &Records, raw_ostream &OS) {
5339 emitSourceFileHeader(Desc: "Attribute text node traverser", OS, Record: Records);
5340
5341 for (const auto *Attr : Records.getAllDerivedDefinitions(ClassName: "Attr")) {
5342 const Record &R = *Attr;
5343 if (!R.getValueAsBit(FieldName: "ASTNode"))
5344 continue;
5345
5346 std::string FunctionContent;
5347 raw_string_ostream SS(FunctionContent);
5348
5349 std::vector<const Record *> Args = R.getValueAsListOfDefs(FieldName: "Args");
5350 for (const auto *Arg : Args)
5351 createArgument(Arg: *Arg, Attr: R.getName())->writeDumpChildren(OS&: SS);
5352 if (Attr->getValueAsBit(FieldName: "AcceptsExprPack"))
5353 VariadicExprArgument("DelayedArgs", R.getName()).writeDumpChildren(OS&: SS);
5354 if (SS.tell()) {
5355 OS << " void Visit" << R.getName() << "Attr(const " << R.getName()
5356 << "Attr *A) {\n";
5357 if (!Args.empty())
5358 OS << " const auto *SA = cast<" << R.getName()
5359 << "Attr>(A); (void)SA;\n";
5360 OS << FunctionContent;
5361 OS << " }\n";
5362 }
5363 }
5364}
5365
5366void EmitClangAttrParserStringSwitches(const RecordKeeper &Records,
5367 raw_ostream &OS) {
5368 generateNameToAttrsMap(Records);
5369 emitSourceFileHeader(Desc: "Parser-related llvm::StringSwitch cases", OS, Record: Records);
5370 emitClangAttrArgContextList(Records, OS);
5371 emitClangAttrIdentifierArgList(Records, OS);
5372 emitClangAttrUnevaluatedStringLiteralList(Records, OS);
5373 emitClangAttrVariadicIdentifierArgList(Records, OS);
5374 emitClangAttrThisIsaIdentifierArgList(Records, OS);
5375 emitClangAttrAcceptsExprPack(Records, OS);
5376 emitClangAttrTypeArgList(Records, OS);
5377 emitClangAttrLateParsedList(Records, OS);
5378 emitClangAttrLateParsedExperimentalList(Records, OS);
5379 emitClangAttrParseArgsInFunctionScopeList(Records, OS);
5380 emitClangAttrStrictIdentifierArgList(Records, OS);
5381}
5382
5383void EmitClangAttrSubjectMatchRulesParserStringSwitches(
5384 const RecordKeeper &Records, raw_ostream &OS) {
5385 getPragmaAttributeSupport(Records).generateParsingHelpers(OS);
5386}
5387
5388void EmitClangAttrDocTable(const RecordKeeper &Records, raw_ostream &OS) {
5389 emitSourceFileHeader(Desc: "Clang attribute documentation", OS, Record: Records);
5390
5391 for (const auto *A : Records.getAllDerivedDefinitions(ClassName: "Attr")) {
5392 if (!A->getValueAsBit(FieldName: "ASTNode"))
5393 continue;
5394 std::vector<const Record *> Docs = A->getValueAsListOfDefs(FieldName: "Documentation");
5395 assert(!Docs.empty());
5396 // Only look at the first documentation if there are several.
5397 // (Currently there's only one such attr, revisit if this becomes common).
5398 StringRef Text =
5399 Docs.front()->getValueAsOptionalString(FieldName: "Content").value_or(u: "");
5400 OS << "\nstatic const char AttrDoc_" << A->getName() << "[] = "
5401 << "R\"reST(" << Text.trim() << ")reST\";\n";
5402 }
5403}
5404
5405enum class SpellingKind : size_t {
5406 GNU,
5407 CXX11,
5408 C23,
5409 Declspec,
5410 Microsoft,
5411 Keyword,
5412 Pragma,
5413 HLSLAnnotation,
5414 NumSpellingKinds
5415};
5416static const size_t NumSpellingKinds = (size_t)SpellingKind::NumSpellingKinds;
5417
5418class SpellingList {
5419 std::array<std::vector<std::string>, NumSpellingKinds> Spellings;
5420
5421public:
5422 ArrayRef<std::string> operator[](SpellingKind K) const {
5423 return Spellings[(size_t)K];
5424 }
5425
5426 void add(const Record &Attr, const FlattenedSpelling &Spelling) {
5427 SpellingKind Kind =
5428 StringSwitch<SpellingKind>(Spelling.variety())
5429 .Case(S: "GNU", Value: SpellingKind::GNU)
5430 .Case(S: "CXX11", Value: SpellingKind::CXX11)
5431 .Case(S: "C23", Value: SpellingKind::C23)
5432 .Case(S: "Declspec", Value: SpellingKind::Declspec)
5433 .Case(S: "Microsoft", Value: SpellingKind::Microsoft)
5434 .Case(S: "Keyword", Value: SpellingKind::Keyword)
5435 .Case(S: "Pragma", Value: SpellingKind::Pragma)
5436 .Case(S: "HLSLAnnotation", Value: SpellingKind::HLSLAnnotation);
5437 std::string Name;
5438 StringRef NameSpace = Spelling.nameSpace();
5439 if (!NameSpace.empty()) {
5440 Name = NameSpace;
5441 switch (Kind) {
5442 case SpellingKind::CXX11:
5443 case SpellingKind::C23:
5444 Name += "::";
5445 break;
5446 case SpellingKind::Pragma:
5447 Name = " ";
5448 break;
5449 default:
5450 PrintFatalError(ErrorLoc: Attr.getLoc(), Msg: "Unexpected namespace in spelling");
5451 }
5452 }
5453 Name += Spelling.name();
5454
5455 Spellings[(size_t)Kind].push_back(x: Name);
5456 }
5457
5458 void merge(const SpellingList &Other) {
5459 for (size_t Kind = 0; Kind < NumSpellingKinds; ++Kind) {
5460 Spellings[Kind].insert(position: Spellings[Kind].end(),
5461 first: Other.Spellings[Kind].begin(),
5462 last: Other.Spellings[Kind].end());
5463 }
5464 }
5465
5466 bool hasSpelling() const {
5467 return llvm::any_of(Range: Spellings, P: [](const auto &L) { return !L.empty(); });
5468 }
5469};
5470
5471class DocumentationData {
5472public:
5473 const Record *Documentation;
5474 const Record *Attribute;
5475 std::string Heading;
5476 SpellingList SupportedSpellings;
5477
5478 DocumentationData(const Record &Documentation, const Record &Attribute,
5479 std::pair<std::string, SpellingList> HeadingAndSpellings)
5480 : Documentation(&Documentation), Attribute(&Attribute),
5481 Heading(std::move(HeadingAndSpellings.first)),
5482 SupportedSpellings(std::move(HeadingAndSpellings.second)) {}
5483};
5484
5485static void WriteCategoryHeader(const Record *DocCategory,
5486 raw_ostream &OS) {
5487 const StringRef Name = DocCategory->getValueAsString(FieldName: "Name");
5488 OS << "## " << Name << "\n\n";
5489
5490 // If there is content, print that as well.
5491 const StringRef ContentStr = DocCategory->getValueAsString(FieldName: "Content");
5492 // Trim leading and trailing newlines and spaces.
5493 OS << ContentStr.trim();
5494
5495 OS << "\n\n";
5496}
5497
5498static std::pair<std::string, SpellingList>
5499GetAttributeHeadingAndSpellings(const Record &Documentation,
5500 const Record &Attribute,
5501 StringRef Cat) {
5502 // FIXME: there is no way to have a per-spelling category for the attribute
5503 // documentation. This may not be a limiting factor since the spellings
5504 // should generally be consistently applied across the category.
5505
5506 if (Cat == "HLSL Semantics") {
5507 if (!Attribute.getName().starts_with(Prefix: "HLSL"))
5508 PrintFatalError(ErrorLoc: Attribute.getLoc(),
5509 Msg: "HLSL semantic attribute name must start with HLSL");
5510
5511 assert(Attribute.getName().size() > 4);
5512 std::string Name = Attribute.getName().substr(Start: 4).str();
5513 return std::make_pair(x: std::move(Name), y: SpellingList());
5514 }
5515
5516 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(Attr: Attribute);
5517 if (Spellings.empty())
5518 PrintFatalError(ErrorLoc: Attribute.getLoc(),
5519 Msg: "Attribute has no supported spellings; cannot be "
5520 "documented");
5521
5522 // Determine the heading to be used for this attribute.
5523 std::string Heading = Documentation.getValueAsString(FieldName: "Heading").str();
5524 if (Heading.empty()) {
5525 // If there's only one spelling, we can simply use that.
5526 if (Spellings.size() == 1)
5527 Heading = Spellings.begin()->name();
5528 else {
5529 std::set<std::string> Uniques;
5530 for (const FlattenedSpelling &FS : Spellings) {
5531 std::string Spelling =
5532 NormalizeNameForSpellingComparison(Name: FS.name()).str();
5533 Uniques.insert(x: Spelling);
5534 }
5535 // If the semantic map has only one spelling, that is sufficient for our
5536 // needs.
5537 if (Uniques.size() == 1)
5538 Heading = *Uniques.begin();
5539 // If it's in the undocumented category, just construct a header by
5540 // concatenating all the spellings. Might not be great, but better than
5541 // nothing.
5542 else if (Cat == "Undocumented")
5543 Heading = join(Begin: Uniques.begin(), End: Uniques.end(), Separator: ", ");
5544 }
5545 }
5546
5547 // If the heading is still empty, it is an error.
5548 if (Heading.empty())
5549 PrintFatalError(ErrorLoc: Attribute.getLoc(),
5550 Msg: "This attribute requires a heading to be specified");
5551
5552 SpellingList SupportedSpellings;
5553 for (const auto &I : Spellings)
5554 SupportedSpellings.add(Attr: Attribute, Spelling: I);
5555
5556 return std::make_pair(x: std::move(Heading), y: std::move(SupportedSpellings));
5557}
5558
5559static void WriteDocumentation(const RecordKeeper &Records,
5560 const DocumentationData &Doc, raw_ostream &OS) {
5561 if (StringRef Label = Doc.Documentation->getValueAsString(FieldName: "Label");
5562 !Label.empty())
5563 OS << "(" << Label << ")=\n\n";
5564 OS << "### " << Doc.Heading << "\n\n";
5565
5566 if (Doc.SupportedSpellings.hasSpelling()) {
5567 // List what spelling syntaxes the attribute supports.
5568 // Note: "#pragma clang attribute" is handled outside the spelling kinds
5569 // loop so it must be last.
5570 OS << ":::{list-table} Supported Syntaxes\n";
5571 OS << ":header-rows: 1\n\n";
5572 OS << "* - GNU\n";
5573 OS << " - C++11\n";
5574 OS << " - C23\n";
5575 OS << " - `__declspec`\n";
5576 OS << " - Keyword\n";
5577 OS << " - `#pragma`\n";
5578 OS << " - HLSL Annotation\n";
5579 OS << " - `#pragma clang attribute`\n";
5580 OS << "*";
5581 for (size_t Kind = 0; Kind != NumSpellingKinds; ++Kind) {
5582 SpellingKind K = (SpellingKind)Kind;
5583 // TODO: List Microsoft (IDL-style attribute) spellings once we fully
5584 // support them.
5585 if (K == SpellingKind::Microsoft)
5586 continue;
5587
5588 OS << " - ";
5589 bool PrintedAny = false;
5590 for (StringRef Spelling : Doc.SupportedSpellings[K]) {
5591 if (PrintedAny)
5592 OS << " <br/> ";
5593 OS << "`" << Spelling << "`";
5594 PrintedAny = true;
5595 }
5596
5597 OS << "\n ";
5598 }
5599
5600 OS << " - ";
5601 if (getPragmaAttributeSupport(Records).isAttributedSupported(
5602 Attribute: *Doc.Attribute))
5603 OS << "Yes";
5604 OS << "\n:::\n\n";
5605 }
5606
5607 // If the attribute is deprecated, print a message about it, and possibly
5608 // provide a replacement attribute.
5609 if (!Doc.Documentation->isValueUnset(FieldName: "Deprecated")) {
5610 OS << "This attribute has been deprecated, and may be removed in a future "
5611 << "version of Clang.";
5612 const Record &Deprecated = *Doc.Documentation->getValueAsDef(FieldName: "Deprecated");
5613 const StringRef Replacement = Deprecated.getValueAsString(FieldName: "Replacement");
5614 if (!Replacement.empty())
5615 OS << " This attribute has been superseded by `" << Replacement << "`.";
5616 OS << "\n\n";
5617 }
5618
5619 const StringRef ContentStr = Doc.Documentation->getValueAsString(FieldName: "Content");
5620 // Trim leading and trailing newlines and spaces.
5621 OS << ContentStr.trim();
5622
5623 OS << "\n\n\n";
5624}
5625
5626void GetListOfUndocumentedAttributes(
5627 const RecordKeeper &Records,
5628 std::vector<const Record *> &UndocumentedAttrs) {
5629 const Record *Documentation = Records.getDef(Name: "GlobalDocumentation");
5630 if (!Documentation) {
5631 PrintFatalError(Msg: "The Documentation top-level definition is missing.");
5632 return;
5633 }
5634
5635 for (const auto *A : Records.getAllDerivedDefinitions(ClassName: "Attr")) {
5636 const Record &Attr = *A;
5637 std::vector<const Record *> Docs =
5638 Attr.getValueAsListOfDefs(FieldName: "Documentation");
5639 for (const auto *D : Docs) {
5640 const Record &Doc = *D;
5641 const Record *Category = Doc.getValueAsDef(FieldName: "Category");
5642 if (Category->getValueAsString(FieldName: "Name") == "Undocumented")
5643 UndocumentedAttrs.push_back(x: A);
5644 }
5645 }
5646}
5647
5648void EmitClangUndocumentedAttrList(const llvm::RecordKeeper &Records,
5649 llvm::raw_ostream &OS) {
5650 // Emit a newline separated list of attributes whose Documentation is set to
5651 // Undocumented.
5652 std::vector<const Record *> UndocumentedAttrs;
5653 GetListOfUndocumentedAttributes(Records, UndocumentedAttrs);
5654
5655 // Print a small header; this helps catch the situation where someone adds an
5656 // attribute without documentation but it is alphabetically before the first
5657 // attribute in the test file.
5658 OS << "Undocumented attributes:\n";
5659
5660 for (const auto *A : UndocumentedAttrs) {
5661 OS << A->getName() << "\n";
5662 }
5663
5664 // Also print the count; this helps catch attributes after the last one in
5665 // the test file.
5666 OS << "Total: " << UndocumentedAttrs.size() << "\n";
5667}
5668
5669void EmitClangAttrDocs(const RecordKeeper &Records, raw_ostream &OS) {
5670 // Get the documentation introduction paragraph.
5671 const Record *Documentation = Records.getDef(Name: "GlobalDocumentation");
5672 if (!Documentation) {
5673 PrintFatalError(Msg: "The Documentation top-level definition is missing, "
5674 "no documentation will be generated.");
5675 return;
5676 }
5677
5678 OS << Documentation->getValueAsString(FieldName: "Intro") << "\n";
5679
5680 // Gather the Documentation lists from each of the attributes, based on the
5681 // category provided.
5682 struct CategoryLess {
5683 bool operator()(const Record *L, const Record *R) const {
5684 return L->getValueAsString(FieldName: "Name") < R->getValueAsString(FieldName: "Name");
5685 }
5686 };
5687
5688 std::map<const Record *, std::map<uint32_t, DocumentationData>, CategoryLess>
5689 MergedDocs;
5690
5691 std::vector<DocumentationData> UndocumentedDocs;
5692 const Record *UndocumentedCategory = nullptr;
5693
5694 // Collect documentation data, grouping by category and heading.
5695 for (const auto *A : Records.getAllDerivedDefinitions(ClassName: "Attr")) {
5696 const Record &Attr = *A;
5697 std::vector<const Record *> Docs =
5698 Attr.getValueAsListOfDefs(FieldName: "Documentation");
5699
5700 for (const auto *D : Docs) {
5701 const Record &Doc = *D;
5702 const Record *Category = Doc.getValueAsDef(FieldName: "Category");
5703 // If the category is "InternalOnly", then there cannot be any other
5704 // documentation categories (otherwise, the attribute would be
5705 // emitted into the docs).
5706 StringRef Cat = Category->getValueAsString(FieldName: "Name");
5707 if (Cat == "InternalOnly" && Docs.size() > 1)
5708 PrintFatalError(ErrorLoc: Doc.getLoc(),
5709 Msg: "Attribute is \"InternalOnly\", but has multiple "
5710 "documentation categories");
5711
5712 if (Cat == "InternalOnly")
5713 continue;
5714
5715 // Track the Undocumented category Record for later grouping
5716 if (Cat == "Undocumented" && !UndocumentedCategory)
5717 UndocumentedCategory = Category;
5718
5719 // Generate Heading and Spellings.
5720 auto HeadingAndSpellings =
5721 GetAttributeHeadingAndSpellings(Documentation: Doc, Attribute: Attr, Cat);
5722
5723 // Handle Undocumented category separately - no content merging
5724 if (Cat == "Undocumented" && UndocumentedCategory) {
5725 UndocumentedDocs.push_back(
5726 x: DocumentationData(Doc, Attr, std::move(HeadingAndSpellings)));
5727 continue;
5728 }
5729
5730 auto &CategoryDocs = MergedDocs[Category];
5731
5732 std::string key = Doc.getValueAsString(FieldName: "Content").str();
5733 uint32_t keyHash = llvm::hash_value(arg: key);
5734
5735 // If the content already exists, merge the documentation.
5736 auto It = CategoryDocs.find(x: keyHash);
5737 if (It != CategoryDocs.end()) {
5738 // Merge heading
5739 if (It->second.Heading != HeadingAndSpellings.first)
5740 It->second.Heading += ", " + HeadingAndSpellings.first;
5741 // Merge spellings
5742 It->second.SupportedSpellings.merge(Other: HeadingAndSpellings.second);
5743 // Merge content
5744 It->second.Documentation = &Doc; // Update reference
5745 } else {
5746 // Create new entry for unique content
5747 CategoryDocs.emplace(args&: keyHash,
5748 args: DocumentationData(Doc, Attr, HeadingAndSpellings));
5749 }
5750 }
5751 }
5752
5753 std::map<const Record *, std::vector<DocumentationData>, CategoryLess>
5754 SplitDocs;
5755
5756 for (auto &CategoryPair : MergedDocs) {
5757
5758 std::vector<DocumentationData> MD;
5759 for (auto &DocPair : CategoryPair.second)
5760 MD.push_back(x: std::move(DocPair.second));
5761
5762 SplitDocs.emplace(args: CategoryPair.first, args&: MD);
5763 }
5764
5765 // Append Undocumented category entries
5766 if (!UndocumentedDocs.empty() && UndocumentedCategory) {
5767 SplitDocs.emplace(args&: UndocumentedCategory, args&: UndocumentedDocs);
5768 }
5769
5770 // Having split the attributes out based on what documentation goes where,
5771 // we can begin to generate sections of documentation.
5772 for (auto &I : SplitDocs) {
5773 WriteCategoryHeader(DocCategory: I.first, OS);
5774
5775 sort(C&: I.second,
5776 Comp: [](const DocumentationData &D1, const DocumentationData &D2) {
5777 return D1.Heading < D2.Heading;
5778 });
5779
5780 // Walk over each of the attributes in the category and write out their
5781 // documentation.
5782 for (const auto &Doc : I.second)
5783 WriteDocumentation(Records, Doc, OS);
5784 }
5785}
5786
5787void EmitTestPragmaAttributeSupportedAttributes(const RecordKeeper &Records,
5788 raw_ostream &OS) {
5789 PragmaClangAttributeSupport Support = getPragmaAttributeSupport(Records);
5790 ParsedAttrMap Attrs = getParsedAttrList(Records);
5791 OS << "#pragma clang attribute supports the following attributes:\n";
5792 for (const auto &I : Attrs) {
5793 if (!Support.isAttributedSupported(Attribute: *I.second))
5794 continue;
5795 OS << I.first;
5796 if (I.second->isValueUnset(FieldName: "Subjects")) {
5797 OS << " ()\n";
5798 continue;
5799 }
5800 const Record *SubjectObj = I.second->getValueAsDef(FieldName: "Subjects");
5801 OS << " (";
5802 ListSeparator LS;
5803 for (const auto &Subject :
5804 enumerate(First: SubjectObj->getValueAsListOfDefs(FieldName: "Subjects"))) {
5805 if (!isSupportedPragmaClangAttributeSubject(Subject: *Subject.value()))
5806 continue;
5807 OS << LS;
5808 PragmaClangAttributeSupport::RuleOrAggregateRuleSet &RuleSet =
5809 Support.SubjectsToRules.find(Val: Subject.value())->getSecond();
5810 if (RuleSet.isRule()) {
5811 OS << RuleSet.getRule().getEnumValueName();
5812 continue;
5813 }
5814 OS << "(";
5815 for (const auto &Rule : enumerate(First: RuleSet.getAggregateRuleSet())) {
5816 if (Rule.index())
5817 OS << ", ";
5818 OS << Rule.value().getEnumValueName();
5819 }
5820 OS << ")";
5821 }
5822 OS << ")\n";
5823 }
5824 OS << "End of supported attributes.\n";
5825}
5826
5827} // end namespace clang
5828