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