1 //===- ClangAttrEmitter.cpp - Generate Clang attribute handling =-*- C++ -*--=//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // These tablegen backends emit Clang attribute processing code
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/ADT/ArrayRef.h"
15 #include "llvm/ADT/DenseMap.h"
16 #include "llvm/ADT/DenseSet.h"
17 #include "llvm/ADT/STLExtras.h"
18 #include "llvm/ADT/SmallString.h"
19 #include "llvm/ADT/StringExtras.h"
20 #include "llvm/ADT/StringRef.h"
21 #include "llvm/ADT/StringSet.h"
22 #include "llvm/ADT/StringSwitch.h"
23 #include "llvm/ADT/iterator_range.h"
24 #include "llvm/Support/ErrorHandling.h"
25 #include "llvm/Support/raw_ostream.h"
26 #include "llvm/TableGen/Error.h"
27 #include "llvm/TableGen/Record.h"
28 #include "llvm/TableGen/StringMatcher.h"
29 #include "llvm/TableGen/TableGenBackend.h"
30 #include <algorithm>
31 #include <cassert>
32 #include <cctype>
33 #include <cstddef>
34 #include <cstdint>
35 #include <map>
36 #include <memory>
37 #include <set>
38 #include <sstream>
39 #include <string>
40 #include <utility>
41 #include <vector>
42
43 using namespace llvm;
44
45 namespace {
46
47 class FlattenedSpelling {
48 std::string V, N, NS;
49 bool K;
50
51 public:
FlattenedSpelling(const std::string & Variety,const std::string & Name,const std::string & Namespace,bool KnownToGCC)52 FlattenedSpelling(const std::string &Variety, const std::string &Name,
53 const std::string &Namespace, bool KnownToGCC) :
54 V(Variety), N(Name), NS(Namespace), K(KnownToGCC) {}
FlattenedSpelling(const Record & Spelling)55 explicit FlattenedSpelling(const Record &Spelling) :
56 V(Spelling.getValueAsString("Variety")),
57 N(Spelling.getValueAsString("Name")) {
58
59 assert(V != "GCC" && V != "Clang" &&
60 "Given a GCC spelling, which means this hasn't been flattened!");
61 if (V == "CXX11" || V == "C2x" || V == "Pragma")
62 NS = Spelling.getValueAsString("Namespace");
63 bool Unset;
64 K = Spelling.getValueAsBitOrUnset("KnownToGCC", Unset);
65 }
66
variety() const67 const std::string &variety() const { return V; }
name() const68 const std::string &name() const { return N; }
nameSpace() const69 const std::string &nameSpace() const { return NS; }
knownToGCC() const70 bool knownToGCC() const { return K; }
71 };
72
73 } // end anonymous namespace
74
75 static std::vector<FlattenedSpelling>
GetFlattenedSpellings(const Record & Attr)76 GetFlattenedSpellings(const Record &Attr) {
77 std::vector<Record *> Spellings = Attr.getValueAsListOfDefs("Spellings");
78 std::vector<FlattenedSpelling> Ret;
79
80 for (const auto &Spelling : Spellings) {
81 StringRef Variety = Spelling->getValueAsString("Variety");
82 StringRef Name = Spelling->getValueAsString("Name");
83 if (Variety == "GCC") {
84 // Gin up two new spelling objects to add into the list.
85 Ret.emplace_back("GNU", Name, "", true);
86 Ret.emplace_back("CXX11", Name, "gnu", true);
87 } else if (Variety == "Clang") {
88 Ret.emplace_back("GNU", Name, "", false);
89 Ret.emplace_back("CXX11", Name, "clang", false);
90 if (Spelling->getValueAsBit("AllowInC"))
91 Ret.emplace_back("C2x", Name, "clang", false);
92 } else
93 Ret.push_back(FlattenedSpelling(*Spelling));
94 }
95
96 return Ret;
97 }
98
ReadPCHRecord(StringRef type)99 static std::string ReadPCHRecord(StringRef type) {
100 return StringSwitch<std::string>(type)
101 .EndsWith("Decl *", "Record.GetLocalDeclAs<"
102 + std::string(type, 0, type.size()-1) + ">(Record.readInt())")
103 .Case("TypeSourceInfo *", "Record.getTypeSourceInfo()")
104 .Case("Expr *", "Record.readExpr()")
105 .Case("IdentifierInfo *", "Record.getIdentifierInfo()")
106 .Case("StringRef", "Record.readString()")
107 .Case("ParamIdx", "ParamIdx::deserialize(Record.readInt())")
108 .Default("Record.readInt()");
109 }
110
111 // Get a type that is suitable for storing an object of the specified type.
getStorageType(StringRef type)112 static StringRef getStorageType(StringRef type) {
113 return StringSwitch<StringRef>(type)
114 .Case("StringRef", "std::string")
115 .Default(type);
116 }
117
118 // Assumes that the way to get the value is SA->getname()
WritePCHRecord(StringRef type,StringRef name)119 static std::string WritePCHRecord(StringRef type, StringRef name) {
120 return "Record." + StringSwitch<std::string>(type)
121 .EndsWith("Decl *", "AddDeclRef(" + std::string(name) + ");\n")
122 .Case("TypeSourceInfo *", "AddTypeSourceInfo(" + std::string(name) + ");\n")
123 .Case("Expr *", "AddStmt(" + std::string(name) + ");\n")
124 .Case("IdentifierInfo *", "AddIdentifierRef(" + std::string(name) + ");\n")
125 .Case("StringRef", "AddString(" + std::string(name) + ");\n")
126 .Case("ParamIdx", "push_back(" + std::string(name) + ".serialize());\n")
127 .Default("push_back(" + std::string(name) + ");\n");
128 }
129
130 // Normalize attribute name by removing leading and trailing
131 // underscores. For example, __foo, foo__, __foo__ would
132 // become foo.
NormalizeAttrName(StringRef AttrName)133 static StringRef NormalizeAttrName(StringRef AttrName) {
134 AttrName.consume_front("__");
135 AttrName.consume_back("__");
136 return AttrName;
137 }
138
139 // Normalize the name by removing any and all leading and trailing underscores.
140 // This is different from NormalizeAttrName in that it also handles names like
141 // _pascal and __pascal.
NormalizeNameForSpellingComparison(StringRef Name)142 static StringRef NormalizeNameForSpellingComparison(StringRef Name) {
143 return Name.trim("_");
144 }
145
146 // Normalize the spelling of a GNU attribute (i.e. "x" in "__attribute__((x))"),
147 // removing "__" if it appears at the beginning and end of the attribute's name.
NormalizeGNUAttrSpelling(StringRef AttrSpelling)148 static StringRef NormalizeGNUAttrSpelling(StringRef AttrSpelling) {
149 if (AttrSpelling.startswith("__") && AttrSpelling.endswith("__")) {
150 AttrSpelling = AttrSpelling.substr(2, AttrSpelling.size() - 4);
151 }
152
153 return AttrSpelling;
154 }
155
156 typedef std::vector<std::pair<std::string, const Record *>> ParsedAttrMap;
157
getParsedAttrList(const RecordKeeper & Records,ParsedAttrMap * Dupes=nullptr)158 static ParsedAttrMap getParsedAttrList(const RecordKeeper &Records,
159 ParsedAttrMap *Dupes = nullptr) {
160 std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
161 std::set<std::string> Seen;
162 ParsedAttrMap R;
163 for (const auto *Attr : Attrs) {
164 if (Attr->getValueAsBit("SemaHandler")) {
165 std::string AN;
166 if (Attr->isSubClassOf("TargetSpecificAttr") &&
167 !Attr->isValueUnset("ParseKind")) {
168 AN = Attr->getValueAsString("ParseKind");
169
170 // If this attribute has already been handled, it does not need to be
171 // handled again.
172 if (Seen.find(AN) != Seen.end()) {
173 if (Dupes)
174 Dupes->push_back(std::make_pair(AN, Attr));
175 continue;
176 }
177 Seen.insert(AN);
178 } else
179 AN = NormalizeAttrName(Attr->getName()).str();
180
181 R.push_back(std::make_pair(AN, Attr));
182 }
183 }
184 return R;
185 }
186
187 namespace {
188
189 class Argument {
190 std::string lowerName, upperName;
191 StringRef attrName;
192 bool isOpt;
193 bool Fake;
194
195 public:
Argument(const Record & Arg,StringRef Attr)196 Argument(const Record &Arg, StringRef Attr)
197 : lowerName(Arg.getValueAsString("Name")), upperName(lowerName),
198 attrName(Attr), isOpt(false), Fake(false) {
199 if (!lowerName.empty()) {
200 lowerName[0] = std::tolower(lowerName[0]);
201 upperName[0] = std::toupper(upperName[0]);
202 }
203 // Work around MinGW's macro definition of 'interface' to 'struct'. We
204 // have an attribute argument called 'Interface', so only the lower case
205 // name conflicts with the macro definition.
206 if (lowerName == "interface")
207 lowerName = "interface_";
208 }
209 virtual ~Argument() = default;
210
getLowerName() const211 StringRef getLowerName() const { return lowerName; }
getUpperName() const212 StringRef getUpperName() const { return upperName; }
getAttrName() const213 StringRef getAttrName() const { return attrName; }
214
isOptional() const215 bool isOptional() const { return isOpt; }
setOptional(bool set)216 void setOptional(bool set) { isOpt = set; }
217
isFake() const218 bool isFake() const { return Fake; }
setFake(bool fake)219 void setFake(bool fake) { Fake = fake; }
220
221 // These functions print the argument contents formatted in different ways.
222 virtual void writeAccessors(raw_ostream &OS) const = 0;
writeAccessorDefinitions(raw_ostream & OS) const223 virtual void writeAccessorDefinitions(raw_ostream &OS) const {}
writeASTVisitorTraversal(raw_ostream & OS) const224 virtual void writeASTVisitorTraversal(raw_ostream &OS) const {}
225 virtual void writeCloneArgs(raw_ostream &OS) const = 0;
226 virtual void writeTemplateInstantiationArgs(raw_ostream &OS) const = 0;
writeTemplateInstantiation(raw_ostream & OS) const227 virtual void writeTemplateInstantiation(raw_ostream &OS) const {}
writeCtorBody(raw_ostream & OS) const228 virtual void writeCtorBody(raw_ostream &OS) const {}
229 virtual void writeCtorInitializers(raw_ostream &OS) const = 0;
230 virtual void writeCtorDefaultInitializers(raw_ostream &OS) const = 0;
231 virtual void writeCtorParameters(raw_ostream &OS) const = 0;
232 virtual void writeDeclarations(raw_ostream &OS) const = 0;
233 virtual void writePCHReadArgs(raw_ostream &OS) const = 0;
234 virtual void writePCHReadDecls(raw_ostream &OS) const = 0;
235 virtual void writePCHWrite(raw_ostream &OS) const = 0;
getIsOmitted() const236 virtual std::string getIsOmitted() const { return "false"; }
237 virtual void writeValue(raw_ostream &OS) const = 0;
238 virtual void writeDump(raw_ostream &OS) const = 0;
writeDumpChildren(raw_ostream & OS) const239 virtual void writeDumpChildren(raw_ostream &OS) const {}
writeHasChildren(raw_ostream & OS) const240 virtual void writeHasChildren(raw_ostream &OS) const { OS << "false"; }
241
isEnumArg() const242 virtual bool isEnumArg() const { return false; }
isVariadicEnumArg() const243 virtual bool isVariadicEnumArg() const { return false; }
isVariadic() const244 virtual bool isVariadic() const { return false; }
245
writeImplicitCtorArgs(raw_ostream & OS) const246 virtual void writeImplicitCtorArgs(raw_ostream &OS) const {
247 OS << getUpperName();
248 }
249 };
250
251 class SimpleArgument : public Argument {
252 std::string type;
253
254 public:
SimpleArgument(const Record & Arg,StringRef Attr,std::string T)255 SimpleArgument(const Record &Arg, StringRef Attr, std::string T)
256 : Argument(Arg, Attr), type(std::move(T)) {}
257
getType() const258 std::string getType() const { return type; }
259
writeAccessors(raw_ostream & OS) const260 void writeAccessors(raw_ostream &OS) const override {
261 OS << " " << type << " get" << getUpperName() << "() const {\n";
262 OS << " return " << getLowerName() << ";\n";
263 OS << " }";
264 }
265
writeCloneArgs(raw_ostream & OS) const266 void writeCloneArgs(raw_ostream &OS) const override {
267 OS << getLowerName();
268 }
269
writeTemplateInstantiationArgs(raw_ostream & OS) const270 void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
271 OS << "A->get" << getUpperName() << "()";
272 }
273
writeCtorInitializers(raw_ostream & OS) const274 void writeCtorInitializers(raw_ostream &OS) const override {
275 OS << getLowerName() << "(" << getUpperName() << ")";
276 }
277
writeCtorDefaultInitializers(raw_ostream & OS) const278 void writeCtorDefaultInitializers(raw_ostream &OS) const override {
279 OS << getLowerName() << "()";
280 }
281
writeCtorParameters(raw_ostream & OS) const282 void writeCtorParameters(raw_ostream &OS) const override {
283 OS << type << " " << getUpperName();
284 }
285
writeDeclarations(raw_ostream & OS) const286 void writeDeclarations(raw_ostream &OS) const override {
287 OS << type << " " << getLowerName() << ";";
288 }
289
writePCHReadDecls(raw_ostream & OS) const290 void writePCHReadDecls(raw_ostream &OS) const override {
291 std::string read = ReadPCHRecord(type);
292 OS << " " << type << " " << getLowerName() << " = " << read << ";\n";
293 }
294
writePCHReadArgs(raw_ostream & OS) const295 void writePCHReadArgs(raw_ostream &OS) const override {
296 OS << getLowerName();
297 }
298
writePCHWrite(raw_ostream & OS) const299 void writePCHWrite(raw_ostream &OS) const override {
300 OS << " " << WritePCHRecord(type, "SA->get" +
301 std::string(getUpperName()) + "()");
302 }
303
getIsOmitted() const304 std::string getIsOmitted() const override {
305 if (type == "IdentifierInfo *")
306 return "!get" + getUpperName().str() + "()";
307 if (type == "ParamIdx")
308 return "!get" + getUpperName().str() + "().isValid()";
309 return "false";
310 }
311
writeValue(raw_ostream & OS) const312 void writeValue(raw_ostream &OS) const override {
313 if (type == "FunctionDecl *")
314 OS << "\" << get" << getUpperName()
315 << "()->getNameInfo().getAsString() << \"";
316 else if (type == "IdentifierInfo *")
317 // Some non-optional (comma required) identifier arguments can be the
318 // empty string but are then recorded as a nullptr.
319 OS << "\" << (get" << getUpperName() << "() ? get" << getUpperName()
320 << "()->getName() : \"\") << \"";
321 else if (type == "TypeSourceInfo *")
322 OS << "\" << get" << getUpperName() << "().getAsString() << \"";
323 else if (type == "ParamIdx")
324 OS << "\" << get" << getUpperName() << "().getSourceIndex() << \"";
325 else
326 OS << "\" << get" << getUpperName() << "() << \"";
327 }
328
writeDump(raw_ostream & OS) const329 void writeDump(raw_ostream &OS) const override {
330 if (type == "FunctionDecl *" || type == "NamedDecl *") {
331 OS << " OS << \" \";\n";
332 OS << " dumpBareDeclRef(SA->get" << getUpperName() << "());\n";
333 } else if (type == "IdentifierInfo *") {
334 // Some non-optional (comma required) identifier arguments can be the
335 // empty string but are then recorded as a nullptr.
336 OS << " if (SA->get" << getUpperName() << "())\n"
337 << " OS << \" \" << SA->get" << getUpperName()
338 << "()->getName();\n";
339 } else if (type == "TypeSourceInfo *") {
340 OS << " OS << \" \" << SA->get" << getUpperName()
341 << "().getAsString();\n";
342 } else if (type == "bool") {
343 OS << " if (SA->get" << getUpperName() << "()) OS << \" "
344 << getUpperName() << "\";\n";
345 } else if (type == "int" || type == "unsigned") {
346 OS << " OS << \" \" << SA->get" << getUpperName() << "();\n";
347 } else if (type == "ParamIdx") {
348 if (isOptional())
349 OS << " if (SA->get" << getUpperName() << "().isValid())\n ";
350 OS << " OS << \" \" << SA->get" << getUpperName()
351 << "().getSourceIndex();\n";
352 } else {
353 llvm_unreachable("Unknown SimpleArgument type!");
354 }
355 }
356 };
357
358 class DefaultSimpleArgument : public SimpleArgument {
359 int64_t Default;
360
361 public:
DefaultSimpleArgument(const Record & Arg,StringRef Attr,std::string T,int64_t Default)362 DefaultSimpleArgument(const Record &Arg, StringRef Attr,
363 std::string T, int64_t Default)
364 : SimpleArgument(Arg, Attr, T), Default(Default) {}
365
writeAccessors(raw_ostream & OS) const366 void writeAccessors(raw_ostream &OS) const override {
367 SimpleArgument::writeAccessors(OS);
368
369 OS << "\n\n static const " << getType() << " Default" << getUpperName()
370 << " = ";
371 if (getType() == "bool")
372 OS << (Default != 0 ? "true" : "false");
373 else
374 OS << Default;
375 OS << ";";
376 }
377 };
378
379 class StringArgument : public Argument {
380 public:
StringArgument(const Record & Arg,StringRef Attr)381 StringArgument(const Record &Arg, StringRef Attr)
382 : Argument(Arg, Attr)
383 {}
384
writeAccessors(raw_ostream & OS) const385 void writeAccessors(raw_ostream &OS) const override {
386 OS << " llvm::StringRef get" << getUpperName() << "() const {\n";
387 OS << " return llvm::StringRef(" << getLowerName() << ", "
388 << getLowerName() << "Length);\n";
389 OS << " }\n";
390 OS << " unsigned get" << getUpperName() << "Length() const {\n";
391 OS << " return " << getLowerName() << "Length;\n";
392 OS << " }\n";
393 OS << " void set" << getUpperName()
394 << "(ASTContext &C, llvm::StringRef S) {\n";
395 OS << " " << getLowerName() << "Length = S.size();\n";
396 OS << " this->" << getLowerName() << " = new (C, 1) char ["
397 << getLowerName() << "Length];\n";
398 OS << " if (!S.empty())\n";
399 OS << " std::memcpy(this->" << getLowerName() << ", S.data(), "
400 << getLowerName() << "Length);\n";
401 OS << " }";
402 }
403
writeCloneArgs(raw_ostream & OS) const404 void writeCloneArgs(raw_ostream &OS) const override {
405 OS << "get" << getUpperName() << "()";
406 }
407
writeTemplateInstantiationArgs(raw_ostream & OS) const408 void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
409 OS << "A->get" << getUpperName() << "()";
410 }
411
writeCtorBody(raw_ostream & OS) const412 void writeCtorBody(raw_ostream &OS) const override {
413 OS << " if (!" << getUpperName() << ".empty())\n";
414 OS << " std::memcpy(" << getLowerName() << ", " << getUpperName()
415 << ".data(), " << getLowerName() << "Length);\n";
416 }
417
writeCtorInitializers(raw_ostream & OS) const418 void writeCtorInitializers(raw_ostream &OS) const override {
419 OS << getLowerName() << "Length(" << getUpperName() << ".size()),"
420 << getLowerName() << "(new (Ctx, 1) char[" << getLowerName()
421 << "Length])";
422 }
423
writeCtorDefaultInitializers(raw_ostream & OS) const424 void writeCtorDefaultInitializers(raw_ostream &OS) const override {
425 OS << getLowerName() << "Length(0)," << getLowerName() << "(nullptr)";
426 }
427
writeCtorParameters(raw_ostream & OS) const428 void writeCtorParameters(raw_ostream &OS) const override {
429 OS << "llvm::StringRef " << getUpperName();
430 }
431
writeDeclarations(raw_ostream & OS) const432 void writeDeclarations(raw_ostream &OS) const override {
433 OS << "unsigned " << getLowerName() << "Length;\n";
434 OS << "char *" << getLowerName() << ";";
435 }
436
writePCHReadDecls(raw_ostream & OS) const437 void writePCHReadDecls(raw_ostream &OS) const override {
438 OS << " std::string " << getLowerName()
439 << "= Record.readString();\n";
440 }
441
writePCHReadArgs(raw_ostream & OS) const442 void writePCHReadArgs(raw_ostream &OS) const override {
443 OS << getLowerName();
444 }
445
writePCHWrite(raw_ostream & OS) const446 void writePCHWrite(raw_ostream &OS) const override {
447 OS << " Record.AddString(SA->get" << getUpperName() << "());\n";
448 }
449
writeValue(raw_ostream & OS) const450 void writeValue(raw_ostream &OS) const override {
451 OS << "\\\"\" << get" << getUpperName() << "() << \"\\\"";
452 }
453
writeDump(raw_ostream & OS) const454 void writeDump(raw_ostream &OS) const override {
455 OS << " OS << \" \\\"\" << SA->get" << getUpperName()
456 << "() << \"\\\"\";\n";
457 }
458 };
459
460 class AlignedArgument : public Argument {
461 public:
AlignedArgument(const Record & Arg,StringRef Attr)462 AlignedArgument(const Record &Arg, StringRef Attr)
463 : Argument(Arg, Attr)
464 {}
465
writeAccessors(raw_ostream & OS) const466 void writeAccessors(raw_ostream &OS) const override {
467 OS << " bool is" << getUpperName() << "Dependent() const;\n";
468
469 OS << " unsigned get" << getUpperName() << "(ASTContext &Ctx) const;\n";
470
471 OS << " bool is" << getUpperName() << "Expr() const {\n";
472 OS << " return is" << getLowerName() << "Expr;\n";
473 OS << " }\n";
474
475 OS << " Expr *get" << getUpperName() << "Expr() const {\n";
476 OS << " assert(is" << getLowerName() << "Expr);\n";
477 OS << " return " << getLowerName() << "Expr;\n";
478 OS << " }\n";
479
480 OS << " TypeSourceInfo *get" << getUpperName() << "Type() const {\n";
481 OS << " assert(!is" << getLowerName() << "Expr);\n";
482 OS << " return " << getLowerName() << "Type;\n";
483 OS << " }";
484 }
485
writeAccessorDefinitions(raw_ostream & OS) const486 void writeAccessorDefinitions(raw_ostream &OS) const override {
487 OS << "bool " << getAttrName() << "Attr::is" << getUpperName()
488 << "Dependent() const {\n";
489 OS << " if (is" << getLowerName() << "Expr)\n";
490 OS << " return " << getLowerName() << "Expr && (" << getLowerName()
491 << "Expr->isValueDependent() || " << getLowerName()
492 << "Expr->isTypeDependent());\n";
493 OS << " else\n";
494 OS << " return " << getLowerName()
495 << "Type->getType()->isDependentType();\n";
496 OS << "}\n";
497
498 // FIXME: Do not do the calculation here
499 // FIXME: Handle types correctly
500 // A null pointer means maximum alignment
501 OS << "unsigned " << getAttrName() << "Attr::get" << getUpperName()
502 << "(ASTContext &Ctx) const {\n";
503 OS << " assert(!is" << getUpperName() << "Dependent());\n";
504 OS << " if (is" << getLowerName() << "Expr)\n";
505 OS << " return " << getLowerName() << "Expr ? " << getLowerName()
506 << "Expr->EvaluateKnownConstInt(Ctx).getZExtValue()"
507 << " * Ctx.getCharWidth() : "
508 << "Ctx.getTargetDefaultAlignForAttributeAligned();\n";
509 OS << " else\n";
510 OS << " return 0; // FIXME\n";
511 OS << "}\n";
512 }
513
writeASTVisitorTraversal(raw_ostream & OS) const514 void writeASTVisitorTraversal(raw_ostream &OS) const override {
515 StringRef Name = getUpperName();
516 OS << " if (A->is" << Name << "Expr()) {\n"
517 << " if (!getDerived().TraverseStmt(A->get" << Name << "Expr()))\n"
518 << " return false;\n"
519 << " } else if (auto *TSI = A->get" << Name << "Type()) {\n"
520 << " if (!getDerived().TraverseTypeLoc(TSI->getTypeLoc()))\n"
521 << " return false;\n"
522 << " }\n";
523 }
524
writeCloneArgs(raw_ostream & OS) const525 void writeCloneArgs(raw_ostream &OS) const override {
526 OS << "is" << getLowerName() << "Expr, is" << getLowerName()
527 << "Expr ? static_cast<void*>(" << getLowerName()
528 << "Expr) : " << getLowerName()
529 << "Type";
530 }
531
writeTemplateInstantiationArgs(raw_ostream & OS) const532 void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
533 // FIXME: move the definition in Sema::InstantiateAttrs to here.
534 // In the meantime, aligned attributes are cloned.
535 }
536
writeCtorBody(raw_ostream & OS) const537 void writeCtorBody(raw_ostream &OS) const override {
538 OS << " if (is" << getLowerName() << "Expr)\n";
539 OS << " " << getLowerName() << "Expr = reinterpret_cast<Expr *>("
540 << getUpperName() << ");\n";
541 OS << " else\n";
542 OS << " " << getLowerName()
543 << "Type = reinterpret_cast<TypeSourceInfo *>(" << getUpperName()
544 << ");\n";
545 }
546
writeCtorInitializers(raw_ostream & OS) const547 void writeCtorInitializers(raw_ostream &OS) const override {
548 OS << "is" << getLowerName() << "Expr(Is" << getUpperName() << "Expr)";
549 }
550
writeCtorDefaultInitializers(raw_ostream & OS) const551 void writeCtorDefaultInitializers(raw_ostream &OS) const override {
552 OS << "is" << getLowerName() << "Expr(false)";
553 }
554
writeCtorParameters(raw_ostream & OS) const555 void writeCtorParameters(raw_ostream &OS) const override {
556 OS << "bool Is" << getUpperName() << "Expr, void *" << getUpperName();
557 }
558
writeImplicitCtorArgs(raw_ostream & OS) const559 void writeImplicitCtorArgs(raw_ostream &OS) const override {
560 OS << "Is" << getUpperName() << "Expr, " << getUpperName();
561 }
562
writeDeclarations(raw_ostream & OS) const563 void writeDeclarations(raw_ostream &OS) const override {
564 OS << "bool is" << getLowerName() << "Expr;\n";
565 OS << "union {\n";
566 OS << "Expr *" << getLowerName() << "Expr;\n";
567 OS << "TypeSourceInfo *" << getLowerName() << "Type;\n";
568 OS << "};";
569 }
570
writePCHReadArgs(raw_ostream & OS) const571 void writePCHReadArgs(raw_ostream &OS) const override {
572 OS << "is" << getLowerName() << "Expr, " << getLowerName() << "Ptr";
573 }
574
writePCHReadDecls(raw_ostream & OS) const575 void writePCHReadDecls(raw_ostream &OS) const override {
576 OS << " bool is" << getLowerName() << "Expr = Record.readInt();\n";
577 OS << " void *" << getLowerName() << "Ptr;\n";
578 OS << " if (is" << getLowerName() << "Expr)\n";
579 OS << " " << getLowerName() << "Ptr = Record.readExpr();\n";
580 OS << " else\n";
581 OS << " " << getLowerName()
582 << "Ptr = Record.getTypeSourceInfo();\n";
583 }
584
writePCHWrite(raw_ostream & OS) const585 void writePCHWrite(raw_ostream &OS) const override {
586 OS << " Record.push_back(SA->is" << getUpperName() << "Expr());\n";
587 OS << " if (SA->is" << getUpperName() << "Expr())\n";
588 OS << " Record.AddStmt(SA->get" << getUpperName() << "Expr());\n";
589 OS << " else\n";
590 OS << " Record.AddTypeSourceInfo(SA->get" << getUpperName()
591 << "Type());\n";
592 }
593
getIsOmitted() const594 std::string getIsOmitted() const override {
595 return "!is" + getLowerName().str() + "Expr || !" + getLowerName().str()
596 + "Expr";
597 }
598
writeValue(raw_ostream & OS) const599 void writeValue(raw_ostream &OS) const override {
600 OS << "\";\n";
601 OS << " " << getLowerName()
602 << "Expr->printPretty(OS, nullptr, Policy);\n";
603 OS << " OS << \"";
604 }
605
writeDump(raw_ostream & OS) const606 void writeDump(raw_ostream &OS) const override {
607 OS << " if (!SA->is" << getUpperName() << "Expr())\n";
608 OS << " dumpType(SA->get" << getUpperName()
609 << "Type()->getType());\n";
610 }
611
writeDumpChildren(raw_ostream & OS) const612 void writeDumpChildren(raw_ostream &OS) const override {
613 OS << " if (SA->is" << getUpperName() << "Expr())\n";
614 OS << " dumpStmt(SA->get" << getUpperName() << "Expr());\n";
615 }
616
writeHasChildren(raw_ostream & OS) const617 void writeHasChildren(raw_ostream &OS) const override {
618 OS << "SA->is" << getUpperName() << "Expr()";
619 }
620 };
621
622 class VariadicArgument : public Argument {
623 std::string Type, ArgName, ArgSizeName, RangeName;
624
625 protected:
626 // Assumed to receive a parameter: raw_ostream OS.
writeValueImpl(raw_ostream & OS) const627 virtual void writeValueImpl(raw_ostream &OS) const {
628 OS << " OS << Val;\n";
629 }
630 // Assumed to receive a parameter: raw_ostream OS.
writeDumpImpl(raw_ostream & OS) const631 virtual void writeDumpImpl(raw_ostream &OS) const {
632 OS << " OS << \" \" << Val;\n";
633 }
634
635 public:
VariadicArgument(const Record & Arg,StringRef Attr,std::string T)636 VariadicArgument(const Record &Arg, StringRef Attr, std::string T)
637 : Argument(Arg, Attr), Type(std::move(T)),
638 ArgName(getLowerName().str() + "_"), ArgSizeName(ArgName + "Size"),
639 RangeName(getLowerName()) {}
640
getType() const641 const std::string &getType() const { return Type; }
getArgName() const642 const std::string &getArgName() const { return ArgName; }
getArgSizeName() const643 const std::string &getArgSizeName() const { return ArgSizeName; }
isVariadic() const644 bool isVariadic() const override { return true; }
645
writeAccessors(raw_ostream & OS) const646 void writeAccessors(raw_ostream &OS) const override {
647 std::string IteratorType = getLowerName().str() + "_iterator";
648 std::string BeginFn = getLowerName().str() + "_begin()";
649 std::string EndFn = getLowerName().str() + "_end()";
650
651 OS << " typedef " << Type << "* " << IteratorType << ";\n";
652 OS << " " << IteratorType << " " << BeginFn << " const {"
653 << " return " << ArgName << "; }\n";
654 OS << " " << IteratorType << " " << EndFn << " const {"
655 << " return " << ArgName << " + " << ArgSizeName << "; }\n";
656 OS << " unsigned " << getLowerName() << "_size() const {"
657 << " return " << ArgSizeName << "; }\n";
658 OS << " llvm::iterator_range<" << IteratorType << "> " << RangeName
659 << "() const { return llvm::make_range(" << BeginFn << ", " << EndFn
660 << "); }\n";
661 }
662
writeCloneArgs(raw_ostream & OS) const663 void writeCloneArgs(raw_ostream &OS) const override {
664 OS << ArgName << ", " << ArgSizeName;
665 }
666
writeTemplateInstantiationArgs(raw_ostream & OS) const667 void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
668 // This isn't elegant, but we have to go through public methods...
669 OS << "A->" << getLowerName() << "_begin(), "
670 << "A->" << getLowerName() << "_size()";
671 }
672
writeASTVisitorTraversal(raw_ostream & OS) const673 void writeASTVisitorTraversal(raw_ostream &OS) const override {
674 // FIXME: Traverse the elements.
675 }
676
writeCtorBody(raw_ostream & OS) const677 void writeCtorBody(raw_ostream &OS) const override {
678 OS << " std::copy(" << getUpperName() << ", " << getUpperName()
679 << " + " << ArgSizeName << ", " << ArgName << ");\n";
680 }
681
writeCtorInitializers(raw_ostream & OS) const682 void writeCtorInitializers(raw_ostream &OS) const override {
683 OS << ArgSizeName << "(" << getUpperName() << "Size), "
684 << ArgName << "(new (Ctx, 16) " << getType() << "["
685 << ArgSizeName << "])";
686 }
687
writeCtorDefaultInitializers(raw_ostream & OS) const688 void writeCtorDefaultInitializers(raw_ostream &OS) const override {
689 OS << ArgSizeName << "(0), " << ArgName << "(nullptr)";
690 }
691
writeCtorParameters(raw_ostream & OS) const692 void writeCtorParameters(raw_ostream &OS) const override {
693 OS << getType() << " *" << getUpperName() << ", unsigned "
694 << getUpperName() << "Size";
695 }
696
writeImplicitCtorArgs(raw_ostream & OS) const697 void writeImplicitCtorArgs(raw_ostream &OS) const override {
698 OS << getUpperName() << ", " << getUpperName() << "Size";
699 }
700
writeDeclarations(raw_ostream & OS) const701 void writeDeclarations(raw_ostream &OS) const override {
702 OS << " unsigned " << ArgSizeName << ";\n";
703 OS << " " << getType() << " *" << ArgName << ";";
704 }
705
writePCHReadDecls(raw_ostream & OS) const706 void writePCHReadDecls(raw_ostream &OS) const override {
707 OS << " unsigned " << getLowerName() << "Size = Record.readInt();\n";
708 OS << " SmallVector<" << getType() << ", 4> "
709 << getLowerName() << ";\n";
710 OS << " " << getLowerName() << ".reserve(" << getLowerName()
711 << "Size);\n";
712
713 // If we can't store the values in the current type (if it's something
714 // like StringRef), store them in a different type and convert the
715 // container afterwards.
716 std::string StorageType = getStorageType(getType());
717 std::string StorageName = getLowerName();
718 if (StorageType != getType()) {
719 StorageName += "Storage";
720 OS << " SmallVector<" << StorageType << ", 4> "
721 << StorageName << ";\n";
722 OS << " " << StorageName << ".reserve(" << getLowerName()
723 << "Size);\n";
724 }
725
726 OS << " for (unsigned i = 0; i != " << getLowerName() << "Size; ++i)\n";
727 std::string read = ReadPCHRecord(Type);
728 OS << " " << StorageName << ".push_back(" << read << ");\n";
729
730 if (StorageType != getType()) {
731 OS << " for (unsigned i = 0; i != " << getLowerName() << "Size; ++i)\n";
732 OS << " " << getLowerName() << ".push_back("
733 << StorageName << "[i]);\n";
734 }
735 }
736
writePCHReadArgs(raw_ostream & OS) const737 void writePCHReadArgs(raw_ostream &OS) const override {
738 OS << getLowerName() << ".data(), " << getLowerName() << "Size";
739 }
740
writePCHWrite(raw_ostream & OS) const741 void writePCHWrite(raw_ostream &OS) const override {
742 OS << " Record.push_back(SA->" << getLowerName() << "_size());\n";
743 OS << " for (auto &Val : SA->" << RangeName << "())\n";
744 OS << " " << WritePCHRecord(Type, "Val");
745 }
746
writeValue(raw_ostream & OS) const747 void writeValue(raw_ostream &OS) const override {
748 OS << "\";\n";
749 OS << " bool isFirst = true;\n"
750 << " for (const auto &Val : " << RangeName << "()) {\n"
751 << " if (isFirst) isFirst = false;\n"
752 << " else OS << \", \";\n";
753 writeValueImpl(OS);
754 OS << " }\n";
755 OS << " OS << \"";
756 }
757
writeDump(raw_ostream & OS) const758 void writeDump(raw_ostream &OS) const override {
759 OS << " for (const auto &Val : SA->" << RangeName << "())\n";
760 writeDumpImpl(OS);
761 }
762 };
763
764 class VariadicParamIdxArgument : public VariadicArgument {
765 public:
VariadicParamIdxArgument(const Record & Arg,StringRef Attr)766 VariadicParamIdxArgument(const Record &Arg, StringRef Attr)
767 : VariadicArgument(Arg, Attr, "ParamIdx") {}
768
769 public:
writeValueImpl(raw_ostream & OS) const770 void writeValueImpl(raw_ostream &OS) const override {
771 OS << " OS << Val.getSourceIndex();\n";
772 }
773
writeDumpImpl(raw_ostream & OS) const774 void writeDumpImpl(raw_ostream &OS) const override {
775 OS << " OS << \" \" << Val.getSourceIndex();\n";
776 }
777 };
778
779 // Unique the enums, but maintain the original declaration ordering.
780 std::vector<StringRef>
uniqueEnumsInOrder(const std::vector<StringRef> & enums)781 uniqueEnumsInOrder(const std::vector<StringRef> &enums) {
782 std::vector<StringRef> uniques;
783 SmallDenseSet<StringRef, 8> unique_set;
784 for (const auto &i : enums) {
785 if (unique_set.insert(i).second)
786 uniques.push_back(i);
787 }
788 return uniques;
789 }
790
791 class EnumArgument : public Argument {
792 std::string type;
793 std::vector<StringRef> values, enums, uniques;
794
795 public:
EnumArgument(const Record & Arg,StringRef Attr)796 EnumArgument(const Record &Arg, StringRef Attr)
797 : Argument(Arg, Attr), type(Arg.getValueAsString("Type")),
798 values(Arg.getValueAsListOfStrings("Values")),
799 enums(Arg.getValueAsListOfStrings("Enums")),
800 uniques(uniqueEnumsInOrder(enums))
801 {
802 // FIXME: Emit a proper error
803 assert(!uniques.empty());
804 }
805
isEnumArg() const806 bool isEnumArg() const override { return true; }
807
writeAccessors(raw_ostream & OS) const808 void writeAccessors(raw_ostream &OS) const override {
809 OS << " " << type << " get" << getUpperName() << "() const {\n";
810 OS << " return " << getLowerName() << ";\n";
811 OS << " }";
812 }
813
writeCloneArgs(raw_ostream & OS) const814 void writeCloneArgs(raw_ostream &OS) const override {
815 OS << getLowerName();
816 }
817
writeTemplateInstantiationArgs(raw_ostream & OS) const818 void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
819 OS << "A->get" << getUpperName() << "()";
820 }
writeCtorInitializers(raw_ostream & OS) const821 void writeCtorInitializers(raw_ostream &OS) const override {
822 OS << getLowerName() << "(" << getUpperName() << ")";
823 }
writeCtorDefaultInitializers(raw_ostream & OS) const824 void writeCtorDefaultInitializers(raw_ostream &OS) const override {
825 OS << getLowerName() << "(" << type << "(0))";
826 }
writeCtorParameters(raw_ostream & OS) const827 void writeCtorParameters(raw_ostream &OS) const override {
828 OS << type << " " << getUpperName();
829 }
writeDeclarations(raw_ostream & OS) const830 void writeDeclarations(raw_ostream &OS) const override {
831 auto i = uniques.cbegin(), e = uniques.cend();
832 // The last one needs to not have a comma.
833 --e;
834
835 OS << "public:\n";
836 OS << " enum " << type << " {\n";
837 for (; i != e; ++i)
838 OS << " " << *i << ",\n";
839 OS << " " << *e << "\n";
840 OS << " };\n";
841 OS << "private:\n";
842 OS << " " << type << " " << getLowerName() << ";";
843 }
844
writePCHReadDecls(raw_ostream & OS) const845 void writePCHReadDecls(raw_ostream &OS) const override {
846 OS << " " << getAttrName() << "Attr::" << type << " " << getLowerName()
847 << "(static_cast<" << getAttrName() << "Attr::" << type
848 << ">(Record.readInt()));\n";
849 }
850
writePCHReadArgs(raw_ostream & OS) const851 void writePCHReadArgs(raw_ostream &OS) const override {
852 OS << getLowerName();
853 }
854
writePCHWrite(raw_ostream & OS) const855 void writePCHWrite(raw_ostream &OS) const override {
856 OS << "Record.push_back(SA->get" << getUpperName() << "());\n";
857 }
858
writeValue(raw_ostream & OS) const859 void writeValue(raw_ostream &OS) const override {
860 // FIXME: this isn't 100% correct -- some enum arguments require printing
861 // as a string literal, while others require printing as an identifier.
862 // Tablegen currently does not distinguish between the two forms.
863 OS << "\\\"\" << " << getAttrName() << "Attr::Convert" << type << "ToStr(get"
864 << getUpperName() << "()) << \"\\\"";
865 }
866
writeDump(raw_ostream & OS) const867 void writeDump(raw_ostream &OS) const override {
868 OS << " switch(SA->get" << getUpperName() << "()) {\n";
869 for (const auto &I : uniques) {
870 OS << " case " << getAttrName() << "Attr::" << I << ":\n";
871 OS << " OS << \" " << I << "\";\n";
872 OS << " break;\n";
873 }
874 OS << " }\n";
875 }
876
writeConversion(raw_ostream & OS) const877 void writeConversion(raw_ostream &OS) const {
878 OS << " static bool ConvertStrTo" << type << "(StringRef Val, ";
879 OS << type << " &Out) {\n";
880 OS << " Optional<" << type << "> R = llvm::StringSwitch<Optional<";
881 OS << type << ">>(Val)\n";
882 for (size_t I = 0; I < enums.size(); ++I) {
883 OS << " .Case(\"" << values[I] << "\", ";
884 OS << getAttrName() << "Attr::" << enums[I] << ")\n";
885 }
886 OS << " .Default(Optional<" << type << ">());\n";
887 OS << " if (R) {\n";
888 OS << " Out = *R;\n return true;\n }\n";
889 OS << " return false;\n";
890 OS << " }\n\n";
891
892 // Mapping from enumeration values back to enumeration strings isn't
893 // trivial because some enumeration values have multiple named
894 // enumerators, such as type_visibility(internal) and
895 // type_visibility(hidden) both mapping to TypeVisibilityAttr::Hidden.
896 OS << " static const char *Convert" << type << "ToStr("
897 << type << " Val) {\n"
898 << " switch(Val) {\n";
899 SmallDenseSet<StringRef, 8> Uniques;
900 for (size_t I = 0; I < enums.size(); ++I) {
901 if (Uniques.insert(enums[I]).second)
902 OS << " case " << getAttrName() << "Attr::" << enums[I]
903 << ": return \"" << values[I] << "\";\n";
904 }
905 OS << " }\n"
906 << " llvm_unreachable(\"No enumerator with that value\");\n"
907 << " }\n";
908 }
909 };
910
911 class VariadicEnumArgument: public VariadicArgument {
912 std::string type, QualifiedTypeName;
913 std::vector<StringRef> values, enums, uniques;
914
915 protected:
writeValueImpl(raw_ostream & OS) const916 void writeValueImpl(raw_ostream &OS) const override {
917 // FIXME: this isn't 100% correct -- some enum arguments require printing
918 // as a string literal, while others require printing as an identifier.
919 // Tablegen currently does not distinguish between the two forms.
920 OS << " OS << \"\\\"\" << " << getAttrName() << "Attr::Convert" << type
921 << "ToStr(Val)" << "<< \"\\\"\";\n";
922 }
923
924 public:
VariadicEnumArgument(const Record & Arg,StringRef Attr)925 VariadicEnumArgument(const Record &Arg, StringRef Attr)
926 : VariadicArgument(Arg, Attr, Arg.getValueAsString("Type")),
927 type(Arg.getValueAsString("Type")),
928 values(Arg.getValueAsListOfStrings("Values")),
929 enums(Arg.getValueAsListOfStrings("Enums")),
930 uniques(uniqueEnumsInOrder(enums))
931 {
932 QualifiedTypeName = getAttrName().str() + "Attr::" + type;
933
934 // FIXME: Emit a proper error
935 assert(!uniques.empty());
936 }
937
isVariadicEnumArg() const938 bool isVariadicEnumArg() const override { return true; }
939
writeDeclarations(raw_ostream & OS) const940 void writeDeclarations(raw_ostream &OS) const override {
941 auto i = uniques.cbegin(), e = uniques.cend();
942 // The last one needs to not have a comma.
943 --e;
944
945 OS << "public:\n";
946 OS << " enum " << type << " {\n";
947 for (; i != e; ++i)
948 OS << " " << *i << ",\n";
949 OS << " " << *e << "\n";
950 OS << " };\n";
951 OS << "private:\n";
952
953 VariadicArgument::writeDeclarations(OS);
954 }
955
writeDump(raw_ostream & OS) const956 void writeDump(raw_ostream &OS) const override {
957 OS << " for (" << getAttrName() << "Attr::" << getLowerName()
958 << "_iterator I = SA->" << getLowerName() << "_begin(), E = SA->"
959 << getLowerName() << "_end(); I != E; ++I) {\n";
960 OS << " switch(*I) {\n";
961 for (const auto &UI : uniques) {
962 OS << " case " << getAttrName() << "Attr::" << UI << ":\n";
963 OS << " OS << \" " << UI << "\";\n";
964 OS << " break;\n";
965 }
966 OS << " }\n";
967 OS << " }\n";
968 }
969
writePCHReadDecls(raw_ostream & OS) const970 void writePCHReadDecls(raw_ostream &OS) const override {
971 OS << " unsigned " << getLowerName() << "Size = Record.readInt();\n";
972 OS << " SmallVector<" << QualifiedTypeName << ", 4> " << getLowerName()
973 << ";\n";
974 OS << " " << getLowerName() << ".reserve(" << getLowerName()
975 << "Size);\n";
976 OS << " for (unsigned i = " << getLowerName() << "Size; i; --i)\n";
977 OS << " " << getLowerName() << ".push_back(" << "static_cast<"
978 << QualifiedTypeName << ">(Record.readInt()));\n";
979 }
980
writePCHWrite(raw_ostream & OS) const981 void writePCHWrite(raw_ostream &OS) const override {
982 OS << " Record.push_back(SA->" << getLowerName() << "_size());\n";
983 OS << " for (" << getAttrName() << "Attr::" << getLowerName()
984 << "_iterator i = SA->" << getLowerName() << "_begin(), e = SA->"
985 << getLowerName() << "_end(); i != e; ++i)\n";
986 OS << " " << WritePCHRecord(QualifiedTypeName, "(*i)");
987 }
988
writeConversion(raw_ostream & OS) const989 void writeConversion(raw_ostream &OS) const {
990 OS << " static bool ConvertStrTo" << type << "(StringRef Val, ";
991 OS << type << " &Out) {\n";
992 OS << " Optional<" << type << "> R = llvm::StringSwitch<Optional<";
993 OS << type << ">>(Val)\n";
994 for (size_t I = 0; I < enums.size(); ++I) {
995 OS << " .Case(\"" << values[I] << "\", ";
996 OS << getAttrName() << "Attr::" << enums[I] << ")\n";
997 }
998 OS << " .Default(Optional<" << type << ">());\n";
999 OS << " if (R) {\n";
1000 OS << " Out = *R;\n return true;\n }\n";
1001 OS << " return false;\n";
1002 OS << " }\n\n";
1003
1004 OS << " static const char *Convert" << type << "ToStr("
1005 << type << " Val) {\n"
1006 << " switch(Val) {\n";
1007 SmallDenseSet<StringRef, 8> Uniques;
1008 for (size_t I = 0; I < enums.size(); ++I) {
1009 if (Uniques.insert(enums[I]).second)
1010 OS << " case " << getAttrName() << "Attr::" << enums[I]
1011 << ": return \"" << values[I] << "\";\n";
1012 }
1013 OS << " }\n"
1014 << " llvm_unreachable(\"No enumerator with that value\");\n"
1015 << " }\n";
1016 }
1017 };
1018
1019 class VersionArgument : public Argument {
1020 public:
VersionArgument(const Record & Arg,StringRef Attr)1021 VersionArgument(const Record &Arg, StringRef Attr)
1022 : Argument(Arg, Attr)
1023 {}
1024
writeAccessors(raw_ostream & OS) const1025 void writeAccessors(raw_ostream &OS) const override {
1026 OS << " VersionTuple get" << getUpperName() << "() const {\n";
1027 OS << " return " << getLowerName() << ";\n";
1028 OS << " }\n";
1029 OS << " void set" << getUpperName()
1030 << "(ASTContext &C, VersionTuple V) {\n";
1031 OS << " " << getLowerName() << " = V;\n";
1032 OS << " }";
1033 }
1034
writeCloneArgs(raw_ostream & OS) const1035 void writeCloneArgs(raw_ostream &OS) const override {
1036 OS << "get" << getUpperName() << "()";
1037 }
1038
writeTemplateInstantiationArgs(raw_ostream & OS) const1039 void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
1040 OS << "A->get" << getUpperName() << "()";
1041 }
1042
writeCtorInitializers(raw_ostream & OS) const1043 void writeCtorInitializers(raw_ostream &OS) const override {
1044 OS << getLowerName() << "(" << getUpperName() << ")";
1045 }
1046
writeCtorDefaultInitializers(raw_ostream & OS) const1047 void writeCtorDefaultInitializers(raw_ostream &OS) const override {
1048 OS << getLowerName() << "()";
1049 }
1050
writeCtorParameters(raw_ostream & OS) const1051 void writeCtorParameters(raw_ostream &OS) const override {
1052 OS << "VersionTuple " << getUpperName();
1053 }
1054
writeDeclarations(raw_ostream & OS) const1055 void writeDeclarations(raw_ostream &OS) const override {
1056 OS << "VersionTuple " << getLowerName() << ";\n";
1057 }
1058
writePCHReadDecls(raw_ostream & OS) const1059 void writePCHReadDecls(raw_ostream &OS) const override {
1060 OS << " VersionTuple " << getLowerName()
1061 << "= Record.readVersionTuple();\n";
1062 }
1063
writePCHReadArgs(raw_ostream & OS) const1064 void writePCHReadArgs(raw_ostream &OS) const override {
1065 OS << getLowerName();
1066 }
1067
writePCHWrite(raw_ostream & OS) const1068 void writePCHWrite(raw_ostream &OS) const override {
1069 OS << " Record.AddVersionTuple(SA->get" << getUpperName() << "());\n";
1070 }
1071
writeValue(raw_ostream & OS) const1072 void writeValue(raw_ostream &OS) const override {
1073 OS << getLowerName() << "=\" << get" << getUpperName() << "() << \"";
1074 }
1075
writeDump(raw_ostream & OS) const1076 void writeDump(raw_ostream &OS) const override {
1077 OS << " OS << \" \" << SA->get" << getUpperName() << "();\n";
1078 }
1079 };
1080
1081 class ExprArgument : public SimpleArgument {
1082 public:
ExprArgument(const Record & Arg,StringRef Attr)1083 ExprArgument(const Record &Arg, StringRef Attr)
1084 : SimpleArgument(Arg, Attr, "Expr *")
1085 {}
1086
writeASTVisitorTraversal(raw_ostream & OS) const1087 void writeASTVisitorTraversal(raw_ostream &OS) const override {
1088 OS << " if (!"
1089 << "getDerived().TraverseStmt(A->get" << getUpperName() << "()))\n";
1090 OS << " return false;\n";
1091 }
1092
writeTemplateInstantiationArgs(raw_ostream & OS) const1093 void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
1094 OS << "tempInst" << getUpperName();
1095 }
1096
writeTemplateInstantiation(raw_ostream & OS) const1097 void writeTemplateInstantiation(raw_ostream &OS) const override {
1098 OS << " " << getType() << " tempInst" << getUpperName() << ";\n";
1099 OS << " {\n";
1100 OS << " EnterExpressionEvaluationContext "
1101 << "Unevaluated(S, Sema::ExpressionEvaluationContext::Unevaluated);\n";
1102 OS << " ExprResult " << "Result = S.SubstExpr("
1103 << "A->get" << getUpperName() << "(), TemplateArgs);\n";
1104 OS << " tempInst" << getUpperName() << " = "
1105 << "Result.getAs<Expr>();\n";
1106 OS << " }\n";
1107 }
1108
writeDump(raw_ostream & OS) const1109 void writeDump(raw_ostream &OS) const override {}
1110
writeDumpChildren(raw_ostream & OS) const1111 void writeDumpChildren(raw_ostream &OS) const override {
1112 OS << " dumpStmt(SA->get" << getUpperName() << "());\n";
1113 }
1114
writeHasChildren(raw_ostream & OS) const1115 void writeHasChildren(raw_ostream &OS) const override { OS << "true"; }
1116 };
1117
1118 class VariadicExprArgument : public VariadicArgument {
1119 public:
VariadicExprArgument(const Record & Arg,StringRef Attr)1120 VariadicExprArgument(const Record &Arg, StringRef Attr)
1121 : VariadicArgument(Arg, Attr, "Expr *")
1122 {}
1123
writeASTVisitorTraversal(raw_ostream & OS) const1124 void writeASTVisitorTraversal(raw_ostream &OS) const override {
1125 OS << " {\n";
1126 OS << " " << getType() << " *I = A->" << getLowerName()
1127 << "_begin();\n";
1128 OS << " " << getType() << " *E = A->" << getLowerName()
1129 << "_end();\n";
1130 OS << " for (; I != E; ++I) {\n";
1131 OS << " if (!getDerived().TraverseStmt(*I))\n";
1132 OS << " return false;\n";
1133 OS << " }\n";
1134 OS << " }\n";
1135 }
1136
writeTemplateInstantiationArgs(raw_ostream & OS) const1137 void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
1138 OS << "tempInst" << getUpperName() << ", "
1139 << "A->" << getLowerName() << "_size()";
1140 }
1141
writeTemplateInstantiation(raw_ostream & OS) const1142 void writeTemplateInstantiation(raw_ostream &OS) const override {
1143 OS << " auto *tempInst" << getUpperName()
1144 << " = new (C, 16) " << getType()
1145 << "[A->" << getLowerName() << "_size()];\n";
1146 OS << " {\n";
1147 OS << " EnterExpressionEvaluationContext "
1148 << "Unevaluated(S, Sema::ExpressionEvaluationContext::Unevaluated);\n";
1149 OS << " " << getType() << " *TI = tempInst" << getUpperName()
1150 << ";\n";
1151 OS << " " << getType() << " *I = A->" << getLowerName()
1152 << "_begin();\n";
1153 OS << " " << getType() << " *E = A->" << getLowerName()
1154 << "_end();\n";
1155 OS << " for (; I != E; ++I, ++TI) {\n";
1156 OS << " ExprResult Result = S.SubstExpr(*I, TemplateArgs);\n";
1157 OS << " *TI = Result.getAs<Expr>();\n";
1158 OS << " }\n";
1159 OS << " }\n";
1160 }
1161
writeDump(raw_ostream & OS) const1162 void writeDump(raw_ostream &OS) const override {}
1163
writeDumpChildren(raw_ostream & OS) const1164 void writeDumpChildren(raw_ostream &OS) const override {
1165 OS << " for (" << getAttrName() << "Attr::" << getLowerName()
1166 << "_iterator I = SA->" << getLowerName() << "_begin(), E = SA->"
1167 << getLowerName() << "_end(); I != E; ++I)\n";
1168 OS << " dumpStmt(*I);\n";
1169 }
1170
writeHasChildren(raw_ostream & OS) const1171 void writeHasChildren(raw_ostream &OS) const override {
1172 OS << "SA->" << getLowerName() << "_begin() != "
1173 << "SA->" << getLowerName() << "_end()";
1174 }
1175 };
1176
1177 class VariadicIdentifierArgument : public VariadicArgument {
1178 public:
VariadicIdentifierArgument(const Record & Arg,StringRef Attr)1179 VariadicIdentifierArgument(const Record &Arg, StringRef Attr)
1180 : VariadicArgument(Arg, Attr, "IdentifierInfo *")
1181 {}
1182 };
1183
1184 class VariadicStringArgument : public VariadicArgument {
1185 public:
VariadicStringArgument(const Record & Arg,StringRef Attr)1186 VariadicStringArgument(const Record &Arg, StringRef Attr)
1187 : VariadicArgument(Arg, Attr, "StringRef")
1188 {}
1189
writeCtorBody(raw_ostream & OS) const1190 void writeCtorBody(raw_ostream &OS) const override {
1191 OS << " for (size_t I = 0, E = " << getArgSizeName() << "; I != E;\n"
1192 " ++I) {\n"
1193 " StringRef Ref = " << getUpperName() << "[I];\n"
1194 " if (!Ref.empty()) {\n"
1195 " char *Mem = new (Ctx, 1) char[Ref.size()];\n"
1196 " std::memcpy(Mem, Ref.data(), Ref.size());\n"
1197 " " << getArgName() << "[I] = StringRef(Mem, Ref.size());\n"
1198 " }\n"
1199 " }\n";
1200 }
1201
writeValueImpl(raw_ostream & OS) const1202 void writeValueImpl(raw_ostream &OS) const override {
1203 OS << " OS << \"\\\"\" << Val << \"\\\"\";\n";
1204 }
1205 };
1206
1207 class TypeArgument : public SimpleArgument {
1208 public:
TypeArgument(const Record & Arg,StringRef Attr)1209 TypeArgument(const Record &Arg, StringRef Attr)
1210 : SimpleArgument(Arg, Attr, "TypeSourceInfo *")
1211 {}
1212
writeAccessors(raw_ostream & OS) const1213 void writeAccessors(raw_ostream &OS) const override {
1214 OS << " QualType get" << getUpperName() << "() const {\n";
1215 OS << " return " << getLowerName() << "->getType();\n";
1216 OS << " }";
1217 OS << " " << getType() << " get" << getUpperName() << "Loc() const {\n";
1218 OS << " return " << getLowerName() << ";\n";
1219 OS << " }";
1220 }
1221
writeASTVisitorTraversal(raw_ostream & OS) const1222 void writeASTVisitorTraversal(raw_ostream &OS) const override {
1223 OS << " if (auto *TSI = A->get" << getUpperName() << "Loc())\n";
1224 OS << " if (!getDerived().TraverseTypeLoc(TSI->getTypeLoc()))\n";
1225 OS << " return false;\n";
1226 }
1227
writeTemplateInstantiationArgs(raw_ostream & OS) const1228 void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
1229 OS << "A->get" << getUpperName() << "Loc()";
1230 }
1231
writePCHWrite(raw_ostream & OS) const1232 void writePCHWrite(raw_ostream &OS) const override {
1233 OS << " " << WritePCHRecord(
1234 getType(), "SA->get" + std::string(getUpperName()) + "Loc()");
1235 }
1236 };
1237
1238 } // end anonymous namespace
1239
1240 static std::unique_ptr<Argument>
createArgument(const Record & Arg,StringRef Attr,const Record * Search=nullptr)1241 createArgument(const Record &Arg, StringRef Attr,
1242 const Record *Search = nullptr) {
1243 if (!Search)
1244 Search = &Arg;
1245
1246 std::unique_ptr<Argument> Ptr;
1247 llvm::StringRef ArgName = Search->getName();
1248
1249 if (ArgName == "AlignedArgument")
1250 Ptr = llvm::make_unique<AlignedArgument>(Arg, Attr);
1251 else if (ArgName == "EnumArgument")
1252 Ptr = llvm::make_unique<EnumArgument>(Arg, Attr);
1253 else if (ArgName == "ExprArgument")
1254 Ptr = llvm::make_unique<ExprArgument>(Arg, Attr);
1255 else if (ArgName == "FunctionArgument")
1256 Ptr = llvm::make_unique<SimpleArgument>(Arg, Attr, "FunctionDecl *");
1257 else if (ArgName == "NamedArgument")
1258 Ptr = llvm::make_unique<SimpleArgument>(Arg, Attr, "NamedDecl *");
1259 else if (ArgName == "IdentifierArgument")
1260 Ptr = llvm::make_unique<SimpleArgument>(Arg, Attr, "IdentifierInfo *");
1261 else if (ArgName == "DefaultBoolArgument")
1262 Ptr = llvm::make_unique<DefaultSimpleArgument>(
1263 Arg, Attr, "bool", Arg.getValueAsBit("Default"));
1264 else if (ArgName == "BoolArgument")
1265 Ptr = llvm::make_unique<SimpleArgument>(Arg, Attr, "bool");
1266 else if (ArgName == "DefaultIntArgument")
1267 Ptr = llvm::make_unique<DefaultSimpleArgument>(
1268 Arg, Attr, "int", Arg.getValueAsInt("Default"));
1269 else if (ArgName == "IntArgument")
1270 Ptr = llvm::make_unique<SimpleArgument>(Arg, Attr, "int");
1271 else if (ArgName == "StringArgument")
1272 Ptr = llvm::make_unique<StringArgument>(Arg, Attr);
1273 else if (ArgName == "TypeArgument")
1274 Ptr = llvm::make_unique<TypeArgument>(Arg, Attr);
1275 else if (ArgName == "UnsignedArgument")
1276 Ptr = llvm::make_unique<SimpleArgument>(Arg, Attr, "unsigned");
1277 else if (ArgName == "VariadicUnsignedArgument")
1278 Ptr = llvm::make_unique<VariadicArgument>(Arg, Attr, "unsigned");
1279 else if (ArgName == "VariadicStringArgument")
1280 Ptr = llvm::make_unique<VariadicStringArgument>(Arg, Attr);
1281 else if (ArgName == "VariadicEnumArgument")
1282 Ptr = llvm::make_unique<VariadicEnumArgument>(Arg, Attr);
1283 else if (ArgName == "VariadicExprArgument")
1284 Ptr = llvm::make_unique<VariadicExprArgument>(Arg, Attr);
1285 else if (ArgName == "VariadicParamIdxArgument")
1286 Ptr = llvm::make_unique<VariadicParamIdxArgument>(Arg, Attr);
1287 else if (ArgName == "ParamIdxArgument")
1288 Ptr = llvm::make_unique<SimpleArgument>(Arg, Attr, "ParamIdx");
1289 else if (ArgName == "VariadicIdentifierArgument")
1290 Ptr = llvm::make_unique<VariadicIdentifierArgument>(Arg, Attr);
1291 else if (ArgName == "VersionArgument")
1292 Ptr = llvm::make_unique<VersionArgument>(Arg, Attr);
1293
1294 if (!Ptr) {
1295 // Search in reverse order so that the most-derived type is handled first.
1296 ArrayRef<std::pair<Record*, SMRange>> Bases = Search->getSuperClasses();
1297 for (const auto &Base : llvm::reverse(Bases)) {
1298 if ((Ptr = createArgument(Arg, Attr, Base.first)))
1299 break;
1300 }
1301 }
1302
1303 if (Ptr && Arg.getValueAsBit("Optional"))
1304 Ptr->setOptional(true);
1305
1306 if (Ptr && Arg.getValueAsBit("Fake"))
1307 Ptr->setFake(true);
1308
1309 return Ptr;
1310 }
1311
writeAvailabilityValue(raw_ostream & OS)1312 static void writeAvailabilityValue(raw_ostream &OS) {
1313 OS << "\" << getPlatform()->getName();\n"
1314 << " if (getStrict()) OS << \", strict\";\n"
1315 << " if (!getIntroduced().empty()) OS << \", introduced=\" << getIntroduced();\n"
1316 << " if (!getDeprecated().empty()) OS << \", deprecated=\" << getDeprecated();\n"
1317 << " if (!getObsoleted().empty()) OS << \", obsoleted=\" << getObsoleted();\n"
1318 << " if (getUnavailable()) OS << \", unavailable\";\n"
1319 << " OS << \"";
1320 }
1321
writeDeprecatedAttrValue(raw_ostream & OS,std::string & Variety)1322 static void writeDeprecatedAttrValue(raw_ostream &OS, std::string &Variety) {
1323 OS << "\\\"\" << getMessage() << \"\\\"\";\n";
1324 // Only GNU deprecated has an optional fixit argument at the second position.
1325 if (Variety == "GNU")
1326 OS << " if (!getReplacement().empty()) OS << \", \\\"\""
1327 " << getReplacement() << \"\\\"\";\n";
1328 OS << " OS << \"";
1329 }
1330
writeGetSpellingFunction(Record & R,raw_ostream & OS)1331 static void writeGetSpellingFunction(Record &R, raw_ostream &OS) {
1332 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(R);
1333
1334 OS << "const char *" << R.getName() << "Attr::getSpelling() const {\n";
1335 if (Spellings.empty()) {
1336 OS << " return \"(No spelling)\";\n}\n\n";
1337 return;
1338 }
1339
1340 OS << " switch (SpellingListIndex) {\n"
1341 " default:\n"
1342 " llvm_unreachable(\"Unknown attribute spelling!\");\n"
1343 " return \"(No spelling)\";\n";
1344
1345 for (unsigned I = 0; I < Spellings.size(); ++I)
1346 OS << " case " << I << ":\n"
1347 " return \"" << Spellings[I].name() << "\";\n";
1348 // End of the switch statement.
1349 OS << " }\n";
1350 // End of the getSpelling function.
1351 OS << "}\n\n";
1352 }
1353
1354 static void
writePrettyPrintFunction(Record & R,const std::vector<std::unique_ptr<Argument>> & Args,raw_ostream & OS)1355 writePrettyPrintFunction(Record &R,
1356 const std::vector<std::unique_ptr<Argument>> &Args,
1357 raw_ostream &OS) {
1358 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(R);
1359
1360 OS << "void " << R.getName() << "Attr::printPretty("
1361 << "raw_ostream &OS, const PrintingPolicy &Policy) const {\n";
1362
1363 if (Spellings.empty()) {
1364 OS << "}\n\n";
1365 return;
1366 }
1367
1368 OS <<
1369 " switch (SpellingListIndex) {\n"
1370 " default:\n"
1371 " llvm_unreachable(\"Unknown attribute spelling!\");\n"
1372 " break;\n";
1373
1374 for (unsigned I = 0; I < Spellings.size(); ++ I) {
1375 llvm::SmallString<16> Prefix;
1376 llvm::SmallString<8> Suffix;
1377 // The actual spelling of the name and namespace (if applicable)
1378 // of an attribute without considering prefix and suffix.
1379 llvm::SmallString<64> Spelling;
1380 std::string Name = Spellings[I].name();
1381 std::string Variety = Spellings[I].variety();
1382
1383 if (Variety == "GNU") {
1384 Prefix = " __attribute__((";
1385 Suffix = "))";
1386 } else if (Variety == "CXX11" || Variety == "C2x") {
1387 Prefix = " [[";
1388 Suffix = "]]";
1389 std::string Namespace = Spellings[I].nameSpace();
1390 if (!Namespace.empty()) {
1391 Spelling += Namespace;
1392 Spelling += "::";
1393 }
1394 } else if (Variety == "Declspec") {
1395 Prefix = " __declspec(";
1396 Suffix = ")";
1397 } else if (Variety == "Microsoft") {
1398 Prefix = "[";
1399 Suffix = "]";
1400 } else if (Variety == "Keyword") {
1401 Prefix = " ";
1402 Suffix = "";
1403 } else if (Variety == "Pragma") {
1404 Prefix = "#pragma ";
1405 Suffix = "\n";
1406 std::string Namespace = Spellings[I].nameSpace();
1407 if (!Namespace.empty()) {
1408 Spelling += Namespace;
1409 Spelling += " ";
1410 }
1411 } else {
1412 llvm_unreachable("Unknown attribute syntax variety!");
1413 }
1414
1415 Spelling += Name;
1416
1417 OS <<
1418 " case " << I << " : {\n"
1419 " OS << \"" << Prefix << Spelling;
1420
1421 if (Variety == "Pragma") {
1422 OS << "\";\n";
1423 OS << " printPrettyPragma(OS, Policy);\n";
1424 OS << " OS << \"\\n\";";
1425 OS << " break;\n";
1426 OS << " }\n";
1427 continue;
1428 }
1429
1430 if (Spelling == "availability") {
1431 OS << "(";
1432 writeAvailabilityValue(OS);
1433 OS << ")";
1434 } else if (Spelling == "deprecated" || Spelling == "gnu::deprecated") {
1435 OS << "(";
1436 writeDeprecatedAttrValue(OS, Variety);
1437 OS << ")";
1438 } else {
1439 // To avoid printing parentheses around an empty argument list or
1440 // printing spurious commas at the end of an argument list, we need to
1441 // determine where the last provided non-fake argument is.
1442 unsigned NonFakeArgs = 0;
1443 unsigned TrailingOptArgs = 0;
1444 bool FoundNonOptArg = false;
1445 for (const auto &arg : llvm::reverse(Args)) {
1446 if (arg->isFake())
1447 continue;
1448 ++NonFakeArgs;
1449 if (FoundNonOptArg)
1450 continue;
1451 // FIXME: arg->getIsOmitted() == "false" means we haven't implemented
1452 // any way to detect whether the argument was omitted.
1453 if (!arg->isOptional() || arg->getIsOmitted() == "false") {
1454 FoundNonOptArg = true;
1455 continue;
1456 }
1457 if (!TrailingOptArgs++)
1458 OS << "\";\n"
1459 << " unsigned TrailingOmittedArgs = 0;\n";
1460 OS << " if (" << arg->getIsOmitted() << ")\n"
1461 << " ++TrailingOmittedArgs;\n";
1462 }
1463 if (TrailingOptArgs)
1464 OS << " OS << \"";
1465 if (TrailingOptArgs < NonFakeArgs)
1466 OS << "(";
1467 else if (TrailingOptArgs)
1468 OS << "\";\n"
1469 << " if (TrailingOmittedArgs < " << NonFakeArgs << ")\n"
1470 << " OS << \"(\";\n"
1471 << " OS << \"";
1472 unsigned ArgIndex = 0;
1473 for (const auto &arg : Args) {
1474 if (arg->isFake())
1475 continue;
1476 if (ArgIndex) {
1477 if (ArgIndex >= NonFakeArgs - TrailingOptArgs)
1478 OS << "\";\n"
1479 << " if (" << ArgIndex << " < " << NonFakeArgs
1480 << " - TrailingOmittedArgs)\n"
1481 << " OS << \", \";\n"
1482 << " OS << \"";
1483 else
1484 OS << ", ";
1485 }
1486 std::string IsOmitted = arg->getIsOmitted();
1487 if (arg->isOptional() && IsOmitted != "false")
1488 OS << "\";\n"
1489 << " if (!(" << IsOmitted << ")) {\n"
1490 << " OS << \"";
1491 arg->writeValue(OS);
1492 if (arg->isOptional() && IsOmitted != "false")
1493 OS << "\";\n"
1494 << " }\n"
1495 << " OS << \"";
1496 ++ArgIndex;
1497 }
1498 if (TrailingOptArgs < NonFakeArgs)
1499 OS << ")";
1500 else if (TrailingOptArgs)
1501 OS << "\";\n"
1502 << " if (TrailingOmittedArgs < " << NonFakeArgs << ")\n"
1503 << " OS << \")\";\n"
1504 << " OS << \"";
1505 }
1506
1507 OS << Suffix + "\";\n";
1508
1509 OS <<
1510 " break;\n"
1511 " }\n";
1512 }
1513
1514 // End of the switch statement.
1515 OS << "}\n";
1516 // End of the print function.
1517 OS << "}\n\n";
1518 }
1519
1520 /// Return the index of a spelling in a spelling list.
1521 static unsigned
getSpellingListIndex(const std::vector<FlattenedSpelling> & SpellingList,const FlattenedSpelling & Spelling)1522 getSpellingListIndex(const std::vector<FlattenedSpelling> &SpellingList,
1523 const FlattenedSpelling &Spelling) {
1524 assert(!SpellingList.empty() && "Spelling list is empty!");
1525
1526 for (unsigned Index = 0; Index < SpellingList.size(); ++Index) {
1527 const FlattenedSpelling &S = SpellingList[Index];
1528 if (S.variety() != Spelling.variety())
1529 continue;
1530 if (S.nameSpace() != Spelling.nameSpace())
1531 continue;
1532 if (S.name() != Spelling.name())
1533 continue;
1534
1535 return Index;
1536 }
1537
1538 llvm_unreachable("Unknown spelling!");
1539 }
1540
writeAttrAccessorDefinition(const Record & R,raw_ostream & OS)1541 static void writeAttrAccessorDefinition(const Record &R, raw_ostream &OS) {
1542 std::vector<Record*> Accessors = R.getValueAsListOfDefs("Accessors");
1543 if (Accessors.empty())
1544 return;
1545
1546 const std::vector<FlattenedSpelling> SpellingList = GetFlattenedSpellings(R);
1547 assert(!SpellingList.empty() &&
1548 "Attribute with empty spelling list can't have accessors!");
1549 for (const auto *Accessor : Accessors) {
1550 const StringRef Name = Accessor->getValueAsString("Name");
1551 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(*Accessor);
1552
1553 OS << " bool " << Name << "() const { return SpellingListIndex == ";
1554 for (unsigned Index = 0; Index < Spellings.size(); ++Index) {
1555 OS << getSpellingListIndex(SpellingList, Spellings[Index]);
1556 if (Index != Spellings.size() - 1)
1557 OS << " ||\n SpellingListIndex == ";
1558 else
1559 OS << "; }\n";
1560 }
1561 }
1562 }
1563
1564 static bool
SpellingNamesAreCommon(const std::vector<FlattenedSpelling> & Spellings)1565 SpellingNamesAreCommon(const std::vector<FlattenedSpelling>& Spellings) {
1566 assert(!Spellings.empty() && "An empty list of spellings was provided");
1567 std::string FirstName = NormalizeNameForSpellingComparison(
1568 Spellings.front().name());
1569 for (const auto &Spelling :
1570 llvm::make_range(std::next(Spellings.begin()), Spellings.end())) {
1571 std::string Name = NormalizeNameForSpellingComparison(Spelling.name());
1572 if (Name != FirstName)
1573 return false;
1574 }
1575 return true;
1576 }
1577
1578 typedef std::map<unsigned, std::string> SemanticSpellingMap;
1579 static std::string
CreateSemanticSpellings(const std::vector<FlattenedSpelling> & Spellings,SemanticSpellingMap & Map)1580 CreateSemanticSpellings(const std::vector<FlattenedSpelling> &Spellings,
1581 SemanticSpellingMap &Map) {
1582 // The enumerants are automatically generated based on the variety,
1583 // namespace (if present) and name for each attribute spelling. However,
1584 // care is taken to avoid trampling on the reserved namespace due to
1585 // underscores.
1586 std::string Ret(" enum Spelling {\n");
1587 std::set<std::string> Uniques;
1588 unsigned Idx = 0;
1589 for (auto I = Spellings.begin(), E = Spellings.end(); I != E; ++I, ++Idx) {
1590 const FlattenedSpelling &S = *I;
1591 const std::string &Variety = S.variety();
1592 const std::string &Spelling = S.name();
1593 const std::string &Namespace = S.nameSpace();
1594 std::string EnumName;
1595
1596 EnumName += (Variety + "_");
1597 if (!Namespace.empty())
1598 EnumName += (NormalizeNameForSpellingComparison(Namespace).str() +
1599 "_");
1600 EnumName += NormalizeNameForSpellingComparison(Spelling);
1601
1602 // Even if the name is not unique, this spelling index corresponds to a
1603 // particular enumerant name that we've calculated.
1604 Map[Idx] = EnumName;
1605
1606 // Since we have been stripping underscores to avoid trampling on the
1607 // reserved namespace, we may have inadvertently created duplicate
1608 // enumerant names. These duplicates are not considered part of the
1609 // semantic spelling, and can be elided.
1610 if (Uniques.find(EnumName) != Uniques.end())
1611 continue;
1612
1613 Uniques.insert(EnumName);
1614 if (I != Spellings.begin())
1615 Ret += ",\n";
1616 // Duplicate spellings are not considered part of the semantic spelling
1617 // enumeration, but the spelling index and semantic spelling values are
1618 // meant to be equivalent, so we must specify a concrete value for each
1619 // enumerator.
1620 Ret += " " + EnumName + " = " + llvm::utostr(Idx);
1621 }
1622 Ret += "\n };\n\n";
1623 return Ret;
1624 }
1625
WriteSemanticSpellingSwitch(const std::string & VarName,const SemanticSpellingMap & Map,raw_ostream & OS)1626 void WriteSemanticSpellingSwitch(const std::string &VarName,
1627 const SemanticSpellingMap &Map,
1628 raw_ostream &OS) {
1629 OS << " switch (" << VarName << ") {\n default: "
1630 << "llvm_unreachable(\"Unknown spelling list index\");\n";
1631 for (const auto &I : Map)
1632 OS << " case " << I.first << ": return " << I.second << ";\n";
1633 OS << " }\n";
1634 }
1635
1636 // Emits the LateParsed property for attributes.
emitClangAttrLateParsedList(RecordKeeper & Records,raw_ostream & OS)1637 static void emitClangAttrLateParsedList(RecordKeeper &Records, raw_ostream &OS) {
1638 OS << "#if defined(CLANG_ATTR_LATE_PARSED_LIST)\n";
1639 std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr");
1640
1641 for (const auto *Attr : Attrs) {
1642 bool LateParsed = Attr->getValueAsBit("LateParsed");
1643
1644 if (LateParsed) {
1645 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(*Attr);
1646
1647 // FIXME: Handle non-GNU attributes
1648 for (const auto &I : Spellings) {
1649 if (I.variety() != "GNU")
1650 continue;
1651 OS << ".Case(\"" << I.name() << "\", " << LateParsed << ")\n";
1652 }
1653 }
1654 }
1655 OS << "#endif // CLANG_ATTR_LATE_PARSED_LIST\n\n";
1656 }
1657
hasGNUorCXX11Spelling(const Record & Attribute)1658 static bool hasGNUorCXX11Spelling(const Record &Attribute) {
1659 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(Attribute);
1660 for (const auto &I : Spellings) {
1661 if (I.variety() == "GNU" || I.variety() == "CXX11")
1662 return true;
1663 }
1664 return false;
1665 }
1666
1667 namespace {
1668
1669 struct AttributeSubjectMatchRule {
1670 const Record *MetaSubject;
1671 const Record *Constraint;
1672
AttributeSubjectMatchRule__anon91f985ad0311::AttributeSubjectMatchRule1673 AttributeSubjectMatchRule(const Record *MetaSubject, const Record *Constraint)
1674 : MetaSubject(MetaSubject), Constraint(Constraint) {
1675 assert(MetaSubject && "Missing subject");
1676 }
1677
isSubRule__anon91f985ad0311::AttributeSubjectMatchRule1678 bool isSubRule() const { return Constraint != nullptr; }
1679
getSubjects__anon91f985ad0311::AttributeSubjectMatchRule1680 std::vector<Record *> getSubjects() const {
1681 return (Constraint ? Constraint : MetaSubject)
1682 ->getValueAsListOfDefs("Subjects");
1683 }
1684
getLangOpts__anon91f985ad0311::AttributeSubjectMatchRule1685 std::vector<Record *> getLangOpts() const {
1686 if (Constraint) {
1687 // Lookup the options in the sub-rule first, in case the sub-rule
1688 // overrides the rules options.
1689 std::vector<Record *> Opts = Constraint->getValueAsListOfDefs("LangOpts");
1690 if (!Opts.empty())
1691 return Opts;
1692 }
1693 return MetaSubject->getValueAsListOfDefs("LangOpts");
1694 }
1695
1696 // Abstract rules are used only for sub-rules
isAbstractRule__anon91f985ad0311::AttributeSubjectMatchRule1697 bool isAbstractRule() const { return getSubjects().empty(); }
1698
getName__anon91f985ad0311::AttributeSubjectMatchRule1699 StringRef getName() const {
1700 return (Constraint ? Constraint : MetaSubject)->getValueAsString("Name");
1701 }
1702
isNegatedSubRule__anon91f985ad0311::AttributeSubjectMatchRule1703 bool isNegatedSubRule() const {
1704 assert(isSubRule() && "Not a sub-rule");
1705 return Constraint->getValueAsBit("Negated");
1706 }
1707
getSpelling__anon91f985ad0311::AttributeSubjectMatchRule1708 std::string getSpelling() const {
1709 std::string Result = MetaSubject->getValueAsString("Name");
1710 if (isSubRule()) {
1711 Result += '(';
1712 if (isNegatedSubRule())
1713 Result += "unless(";
1714 Result += getName();
1715 if (isNegatedSubRule())
1716 Result += ')';
1717 Result += ')';
1718 }
1719 return Result;
1720 }
1721
getEnumValueName__anon91f985ad0311::AttributeSubjectMatchRule1722 std::string getEnumValueName() const {
1723 SmallString<128> Result;
1724 Result += "SubjectMatchRule_";
1725 Result += MetaSubject->getValueAsString("Name");
1726 if (isSubRule()) {
1727 Result += "_";
1728 if (isNegatedSubRule())
1729 Result += "not_";
1730 Result += Constraint->getValueAsString("Name");
1731 }
1732 if (isAbstractRule())
1733 Result += "_abstract";
1734 return Result.str();
1735 }
1736
getEnumValue__anon91f985ad0311::AttributeSubjectMatchRule1737 std::string getEnumValue() const { return "attr::" + getEnumValueName(); }
1738
1739 static const char *EnumName;
1740 };
1741
1742 const char *AttributeSubjectMatchRule::EnumName = "attr::SubjectMatchRule";
1743
1744 struct PragmaClangAttributeSupport {
1745 std::vector<AttributeSubjectMatchRule> Rules;
1746
1747 class RuleOrAggregateRuleSet {
1748 std::vector<AttributeSubjectMatchRule> Rules;
1749 bool IsRule;
RuleOrAggregateRuleSet(ArrayRef<AttributeSubjectMatchRule> Rules,bool IsRule)1750 RuleOrAggregateRuleSet(ArrayRef<AttributeSubjectMatchRule> Rules,
1751 bool IsRule)
1752 : Rules(Rules), IsRule(IsRule) {}
1753
1754 public:
isRule() const1755 bool isRule() const { return IsRule; }
1756
getRule() const1757 const AttributeSubjectMatchRule &getRule() const {
1758 assert(IsRule && "not a rule!");
1759 return Rules[0];
1760 }
1761
getAggregateRuleSet() const1762 ArrayRef<AttributeSubjectMatchRule> getAggregateRuleSet() const {
1763 return Rules;
1764 }
1765
1766 static RuleOrAggregateRuleSet
getRule(const AttributeSubjectMatchRule & Rule)1767 getRule(const AttributeSubjectMatchRule &Rule) {
1768 return RuleOrAggregateRuleSet(Rule, /*IsRule=*/true);
1769 }
1770 static RuleOrAggregateRuleSet
getAggregateRuleSet(ArrayRef<AttributeSubjectMatchRule> Rules)1771 getAggregateRuleSet(ArrayRef<AttributeSubjectMatchRule> Rules) {
1772 return RuleOrAggregateRuleSet(Rules, /*IsRule=*/false);
1773 }
1774 };
1775 llvm::DenseMap<const Record *, RuleOrAggregateRuleSet> SubjectsToRules;
1776
1777 PragmaClangAttributeSupport(RecordKeeper &Records);
1778
1779 bool isAttributedSupported(const Record &Attribute);
1780
1781 void emitMatchRuleList(raw_ostream &OS);
1782
1783 std::string generateStrictConformsTo(const Record &Attr, raw_ostream &OS);
1784
1785 void generateParsingHelpers(raw_ostream &OS);
1786 };
1787
1788 } // end anonymous namespace
1789
doesDeclDeriveFrom(const Record * D,const Record * Base)1790 static bool doesDeclDeriveFrom(const Record *D, const Record *Base) {
1791 const Record *CurrentBase = D->getValueAsDef("Base");
1792 if (!CurrentBase)
1793 return false;
1794 if (CurrentBase == Base)
1795 return true;
1796 return doesDeclDeriveFrom(CurrentBase, Base);
1797 }
1798
PragmaClangAttributeSupport(RecordKeeper & Records)1799 PragmaClangAttributeSupport::PragmaClangAttributeSupport(
1800 RecordKeeper &Records) {
1801 std::vector<Record *> MetaSubjects =
1802 Records.getAllDerivedDefinitions("AttrSubjectMatcherRule");
1803 auto MapFromSubjectsToRules = [this](const Record *SubjectContainer,
1804 const Record *MetaSubject,
1805 const Record *Constraint) {
1806 Rules.emplace_back(MetaSubject, Constraint);
1807 std::vector<Record *> ApplicableSubjects =
1808 SubjectContainer->getValueAsListOfDefs("Subjects");
1809 for (const auto *Subject : ApplicableSubjects) {
1810 bool Inserted =
1811 SubjectsToRules
1812 .try_emplace(Subject, RuleOrAggregateRuleSet::getRule(
1813 AttributeSubjectMatchRule(MetaSubject,
1814 Constraint)))
1815 .second;
1816 if (!Inserted) {
1817 PrintFatalError("Attribute subject match rules should not represent"
1818 "same attribute subjects.");
1819 }
1820 }
1821 };
1822 for (const auto *MetaSubject : MetaSubjects) {
1823 MapFromSubjectsToRules(MetaSubject, MetaSubject, /*Constraints=*/nullptr);
1824 std::vector<Record *> Constraints =
1825 MetaSubject->getValueAsListOfDefs("Constraints");
1826 for (const auto *Constraint : Constraints)
1827 MapFromSubjectsToRules(Constraint, MetaSubject, Constraint);
1828 }
1829
1830 std::vector<Record *> Aggregates =
1831 Records.getAllDerivedDefinitions("AttrSubjectMatcherAggregateRule");
1832 std::vector<Record *> DeclNodes = Records.getAllDerivedDefinitions("DDecl");
1833 for (const auto *Aggregate : Aggregates) {
1834 Record *SubjectDecl = Aggregate->getValueAsDef("Subject");
1835
1836 // Gather sub-classes of the aggregate subject that act as attribute
1837 // subject rules.
1838 std::vector<AttributeSubjectMatchRule> Rules;
1839 for (const auto *D : DeclNodes) {
1840 if (doesDeclDeriveFrom(D, SubjectDecl)) {
1841 auto It = SubjectsToRules.find(D);
1842 if (It == SubjectsToRules.end())
1843 continue;
1844 if (!It->second.isRule() || It->second.getRule().isSubRule())
1845 continue; // Assume that the rule will be included as well.
1846 Rules.push_back(It->second.getRule());
1847 }
1848 }
1849
1850 bool Inserted =
1851 SubjectsToRules
1852 .try_emplace(SubjectDecl,
1853 RuleOrAggregateRuleSet::getAggregateRuleSet(Rules))
1854 .second;
1855 if (!Inserted) {
1856 PrintFatalError("Attribute subject match rules should not represent"
1857 "same attribute subjects.");
1858 }
1859 }
1860 }
1861
1862 static PragmaClangAttributeSupport &
getPragmaAttributeSupport(RecordKeeper & Records)1863 getPragmaAttributeSupport(RecordKeeper &Records) {
1864 static PragmaClangAttributeSupport Instance(Records);
1865 return Instance;
1866 }
1867
emitMatchRuleList(raw_ostream & OS)1868 void PragmaClangAttributeSupport::emitMatchRuleList(raw_ostream &OS) {
1869 OS << "#ifndef ATTR_MATCH_SUB_RULE\n";
1870 OS << "#define ATTR_MATCH_SUB_RULE(Value, Spelling, IsAbstract, Parent, "
1871 "IsNegated) "
1872 << "ATTR_MATCH_RULE(Value, Spelling, IsAbstract)\n";
1873 OS << "#endif\n";
1874 for (const auto &Rule : Rules) {
1875 OS << (Rule.isSubRule() ? "ATTR_MATCH_SUB_RULE" : "ATTR_MATCH_RULE") << '(';
1876 OS << Rule.getEnumValueName() << ", \"" << Rule.getSpelling() << "\", "
1877 << Rule.isAbstractRule();
1878 if (Rule.isSubRule())
1879 OS << ", "
1880 << AttributeSubjectMatchRule(Rule.MetaSubject, nullptr).getEnumValue()
1881 << ", " << Rule.isNegatedSubRule();
1882 OS << ")\n";
1883 }
1884 OS << "#undef ATTR_MATCH_SUB_RULE\n";
1885 }
1886
isAttributedSupported(const Record & Attribute)1887 bool PragmaClangAttributeSupport::isAttributedSupported(
1888 const Record &Attribute) {
1889 // If the attribute explicitly specified whether to support #pragma clang
1890 // attribute, use that setting.
1891 bool Unset;
1892 bool SpecifiedResult =
1893 Attribute.getValueAsBitOrUnset("PragmaAttributeSupport", Unset);
1894 if (!Unset)
1895 return SpecifiedResult;
1896
1897 // Opt-out rules:
1898 // An attribute requires delayed parsing (LateParsed is on)
1899 if (Attribute.getValueAsBit("LateParsed"))
1900 return false;
1901 // An attribute has no GNU/CXX11 spelling
1902 if (!hasGNUorCXX11Spelling(Attribute))
1903 return false;
1904 // An attribute subject list has a subject that isn't covered by one of the
1905 // subject match rules or has no subjects at all.
1906 if (Attribute.isValueUnset("Subjects"))
1907 return false;
1908 const Record *SubjectObj = Attribute.getValueAsDef("Subjects");
1909 std::vector<Record *> Subjects = SubjectObj->getValueAsListOfDefs("Subjects");
1910 if (Subjects.empty())
1911 return false;
1912 for (const auto *Subject : Subjects) {
1913 if (SubjectsToRules.find(Subject) == SubjectsToRules.end())
1914 return false;
1915 }
1916 return true;
1917 }
1918
1919 std::string
generateStrictConformsTo(const Record & Attr,raw_ostream & OS)1920 PragmaClangAttributeSupport::generateStrictConformsTo(const Record &Attr,
1921 raw_ostream &OS) {
1922 if (!isAttributedSupported(Attr))
1923 return "nullptr";
1924 // Generate a function that constructs a set of matching rules that describe
1925 // to which declarations the attribute should apply to.
1926 std::string FnName = "matchRulesFor" + Attr.getName().str();
1927 OS << "static void " << FnName << "(llvm::SmallVectorImpl<std::pair<"
1928 << AttributeSubjectMatchRule::EnumName
1929 << ", bool>> &MatchRules, const LangOptions &LangOpts) {\n";
1930 if (Attr.isValueUnset("Subjects")) {
1931 OS << "}\n\n";
1932 return FnName;
1933 }
1934 const Record *SubjectObj = Attr.getValueAsDef("Subjects");
1935 std::vector<Record *> Subjects = SubjectObj->getValueAsListOfDefs("Subjects");
1936 for (const auto *Subject : Subjects) {
1937 auto It = SubjectsToRules.find(Subject);
1938 assert(It != SubjectsToRules.end() &&
1939 "This attribute is unsupported by #pragma clang attribute");
1940 for (const auto &Rule : It->getSecond().getAggregateRuleSet()) {
1941 // The rule might be language specific, so only subtract it from the given
1942 // rules if the specific language options are specified.
1943 std::vector<Record *> LangOpts = Rule.getLangOpts();
1944 OS << " MatchRules.push_back(std::make_pair(" << Rule.getEnumValue()
1945 << ", /*IsSupported=*/";
1946 if (!LangOpts.empty()) {
1947 for (auto I = LangOpts.begin(), E = LangOpts.end(); I != E; ++I) {
1948 const StringRef Part = (*I)->getValueAsString("Name");
1949 if ((*I)->getValueAsBit("Negated"))
1950 OS << "!";
1951 OS << "LangOpts." << Part;
1952 if (I + 1 != E)
1953 OS << " || ";
1954 }
1955 } else
1956 OS << "true";
1957 OS << "));\n";
1958 }
1959 }
1960 OS << "}\n\n";
1961 return FnName;
1962 }
1963
generateParsingHelpers(raw_ostream & OS)1964 void PragmaClangAttributeSupport::generateParsingHelpers(raw_ostream &OS) {
1965 // Generate routines that check the names of sub-rules.
1966 OS << "Optional<attr::SubjectMatchRule> "
1967 "defaultIsAttributeSubjectMatchSubRuleFor(StringRef, bool) {\n";
1968 OS << " return None;\n";
1969 OS << "}\n\n";
1970
1971 std::map<const Record *, std::vector<AttributeSubjectMatchRule>>
1972 SubMatchRules;
1973 for (const auto &Rule : Rules) {
1974 if (!Rule.isSubRule())
1975 continue;
1976 SubMatchRules[Rule.MetaSubject].push_back(Rule);
1977 }
1978
1979 for (const auto &SubMatchRule : SubMatchRules) {
1980 OS << "Optional<attr::SubjectMatchRule> isAttributeSubjectMatchSubRuleFor_"
1981 << SubMatchRule.first->getValueAsString("Name")
1982 << "(StringRef Name, bool IsUnless) {\n";
1983 OS << " if (IsUnless)\n";
1984 OS << " return "
1985 "llvm::StringSwitch<Optional<attr::SubjectMatchRule>>(Name).\n";
1986 for (const auto &Rule : SubMatchRule.second) {
1987 if (Rule.isNegatedSubRule())
1988 OS << " Case(\"" << Rule.getName() << "\", " << Rule.getEnumValue()
1989 << ").\n";
1990 }
1991 OS << " Default(None);\n";
1992 OS << " return "
1993 "llvm::StringSwitch<Optional<attr::SubjectMatchRule>>(Name).\n";
1994 for (const auto &Rule : SubMatchRule.second) {
1995 if (!Rule.isNegatedSubRule())
1996 OS << " Case(\"" << Rule.getName() << "\", " << Rule.getEnumValue()
1997 << ").\n";
1998 }
1999 OS << " Default(None);\n";
2000 OS << "}\n\n";
2001 }
2002
2003 // Generate the function that checks for the top-level rules.
2004 OS << "std::pair<Optional<attr::SubjectMatchRule>, "
2005 "Optional<attr::SubjectMatchRule> (*)(StringRef, "
2006 "bool)> isAttributeSubjectMatchRule(StringRef Name) {\n";
2007 OS << " return "
2008 "llvm::StringSwitch<std::pair<Optional<attr::SubjectMatchRule>, "
2009 "Optional<attr::SubjectMatchRule> (*) (StringRef, "
2010 "bool)>>(Name).\n";
2011 for (const auto &Rule : Rules) {
2012 if (Rule.isSubRule())
2013 continue;
2014 std::string SubRuleFunction;
2015 if (SubMatchRules.count(Rule.MetaSubject))
2016 SubRuleFunction =
2017 ("isAttributeSubjectMatchSubRuleFor_" + Rule.getName()).str();
2018 else
2019 SubRuleFunction = "defaultIsAttributeSubjectMatchSubRuleFor";
2020 OS << " Case(\"" << Rule.getName() << "\", std::make_pair("
2021 << Rule.getEnumValue() << ", " << SubRuleFunction << ")).\n";
2022 }
2023 OS << " Default(std::make_pair(None, "
2024 "defaultIsAttributeSubjectMatchSubRuleFor));\n";
2025 OS << "}\n\n";
2026
2027 // Generate the function that checks for the submatch rules.
2028 OS << "const char *validAttributeSubjectMatchSubRules("
2029 << AttributeSubjectMatchRule::EnumName << " Rule) {\n";
2030 OS << " switch (Rule) {\n";
2031 for (const auto &SubMatchRule : SubMatchRules) {
2032 OS << " case "
2033 << AttributeSubjectMatchRule(SubMatchRule.first, nullptr).getEnumValue()
2034 << ":\n";
2035 OS << " return \"'";
2036 bool IsFirst = true;
2037 for (const auto &Rule : SubMatchRule.second) {
2038 if (!IsFirst)
2039 OS << ", '";
2040 IsFirst = false;
2041 if (Rule.isNegatedSubRule())
2042 OS << "unless(";
2043 OS << Rule.getName();
2044 if (Rule.isNegatedSubRule())
2045 OS << ')';
2046 OS << "'";
2047 }
2048 OS << "\";\n";
2049 }
2050 OS << " default: return nullptr;\n";
2051 OS << " }\n";
2052 OS << "}\n\n";
2053 }
2054
2055 template <typename Fn>
forEachUniqueSpelling(const Record & Attr,Fn && F)2056 static void forEachUniqueSpelling(const Record &Attr, Fn &&F) {
2057 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(Attr);
2058 SmallDenseSet<StringRef, 8> Seen;
2059 for (const FlattenedSpelling &S : Spellings) {
2060 if (Seen.insert(S.name()).second)
2061 F(S);
2062 }
2063 }
2064
2065 /// Emits the first-argument-is-type property for attributes.
emitClangAttrTypeArgList(RecordKeeper & Records,raw_ostream & OS)2066 static void emitClangAttrTypeArgList(RecordKeeper &Records, raw_ostream &OS) {
2067 OS << "#if defined(CLANG_ATTR_TYPE_ARG_LIST)\n";
2068 std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
2069
2070 for (const auto *Attr : Attrs) {
2071 // Determine whether the first argument is a type.
2072 std::vector<Record *> Args = Attr->getValueAsListOfDefs("Args");
2073 if (Args.empty())
2074 continue;
2075
2076 if (Args[0]->getSuperClasses().back().first->getName() != "TypeArgument")
2077 continue;
2078
2079 // All these spellings take a single type argument.
2080 forEachUniqueSpelling(*Attr, [&](const FlattenedSpelling &S) {
2081 OS << ".Case(\"" << S.name() << "\", " << "true" << ")\n";
2082 });
2083 }
2084 OS << "#endif // CLANG_ATTR_TYPE_ARG_LIST\n\n";
2085 }
2086
2087 /// Emits the parse-arguments-in-unevaluated-context property for
2088 /// attributes.
emitClangAttrArgContextList(RecordKeeper & Records,raw_ostream & OS)2089 static void emitClangAttrArgContextList(RecordKeeper &Records, raw_ostream &OS) {
2090 OS << "#if defined(CLANG_ATTR_ARG_CONTEXT_LIST)\n";
2091 ParsedAttrMap Attrs = getParsedAttrList(Records);
2092 for (const auto &I : Attrs) {
2093 const Record &Attr = *I.second;
2094
2095 if (!Attr.getValueAsBit("ParseArgumentsAsUnevaluated"))
2096 continue;
2097
2098 // All these spellings take are parsed unevaluated.
2099 forEachUniqueSpelling(Attr, [&](const FlattenedSpelling &S) {
2100 OS << ".Case(\"" << S.name() << "\", " << "true" << ")\n";
2101 });
2102 }
2103 OS << "#endif // CLANG_ATTR_ARG_CONTEXT_LIST\n\n";
2104 }
2105
isIdentifierArgument(Record * Arg)2106 static bool isIdentifierArgument(Record *Arg) {
2107 return !Arg->getSuperClasses().empty() &&
2108 llvm::StringSwitch<bool>(Arg->getSuperClasses().back().first->getName())
2109 .Case("IdentifierArgument", true)
2110 .Case("EnumArgument", true)
2111 .Case("VariadicEnumArgument", true)
2112 .Default(false);
2113 }
2114
isVariadicIdentifierArgument(Record * Arg)2115 static bool isVariadicIdentifierArgument(Record *Arg) {
2116 return !Arg->getSuperClasses().empty() &&
2117 llvm::StringSwitch<bool>(
2118 Arg->getSuperClasses().back().first->getName())
2119 .Case("VariadicIdentifierArgument", true)
2120 .Default(false);
2121 }
2122
emitClangAttrVariadicIdentifierArgList(RecordKeeper & Records,raw_ostream & OS)2123 static void emitClangAttrVariadicIdentifierArgList(RecordKeeper &Records,
2124 raw_ostream &OS) {
2125 OS << "#if defined(CLANG_ATTR_VARIADIC_IDENTIFIER_ARG_LIST)\n";
2126 std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
2127 for (const auto *A : Attrs) {
2128 // Determine whether the first argument is a variadic identifier.
2129 std::vector<Record *> Args = A->getValueAsListOfDefs("Args");
2130 if (Args.empty() || !isVariadicIdentifierArgument(Args[0]))
2131 continue;
2132
2133 // All these spellings take an identifier argument.
2134 forEachUniqueSpelling(*A, [&](const FlattenedSpelling &S) {
2135 OS << ".Case(\"" << S.name() << "\", "
2136 << "true"
2137 << ")\n";
2138 });
2139 }
2140 OS << "#endif // CLANG_ATTR_VARIADIC_IDENTIFIER_ARG_LIST\n\n";
2141 }
2142
2143 // Emits the first-argument-is-identifier property for attributes.
emitClangAttrIdentifierArgList(RecordKeeper & Records,raw_ostream & OS)2144 static void emitClangAttrIdentifierArgList(RecordKeeper &Records, raw_ostream &OS) {
2145 OS << "#if defined(CLANG_ATTR_IDENTIFIER_ARG_LIST)\n";
2146 std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr");
2147
2148 for (const auto *Attr : Attrs) {
2149 // Determine whether the first argument is an identifier.
2150 std::vector<Record *> Args = Attr->getValueAsListOfDefs("Args");
2151 if (Args.empty() || !isIdentifierArgument(Args[0]))
2152 continue;
2153
2154 // All these spellings take an identifier argument.
2155 forEachUniqueSpelling(*Attr, [&](const FlattenedSpelling &S) {
2156 OS << ".Case(\"" << S.name() << "\", " << "true" << ")\n";
2157 });
2158 }
2159 OS << "#endif // CLANG_ATTR_IDENTIFIER_ARG_LIST\n\n";
2160 }
2161
2162 namespace clang {
2163
2164 // Emits the class definitions for attributes.
EmitClangAttrClass(RecordKeeper & Records,raw_ostream & OS)2165 void EmitClangAttrClass(RecordKeeper &Records, raw_ostream &OS) {
2166 emitSourceFileHeader("Attribute classes' definitions", OS);
2167
2168 OS << "#ifndef LLVM_CLANG_ATTR_CLASSES_INC\n";
2169 OS << "#define LLVM_CLANG_ATTR_CLASSES_INC\n\n";
2170
2171 std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr");
2172
2173 for (const auto *Attr : Attrs) {
2174 const Record &R = *Attr;
2175
2176 // FIXME: Currently, documentation is generated as-needed due to the fact
2177 // that there is no way to allow a generated project "reach into" the docs
2178 // directory (for instance, it may be an out-of-tree build). However, we want
2179 // to ensure that every attribute has a Documentation field, and produce an
2180 // error if it has been neglected. Otherwise, the on-demand generation which
2181 // happens server-side will fail. This code is ensuring that functionality,
2182 // even though this Emitter doesn't technically need the documentation.
2183 // When attribute documentation can be generated as part of the build
2184 // itself, this code can be removed.
2185 (void)R.getValueAsListOfDefs("Documentation");
2186
2187 if (!R.getValueAsBit("ASTNode"))
2188 continue;
2189
2190 ArrayRef<std::pair<Record *, SMRange>> Supers = R.getSuperClasses();
2191 assert(!Supers.empty() && "Forgot to specify a superclass for the attr");
2192 std::string SuperName;
2193 bool Inheritable = false;
2194 for (const auto &Super : llvm::reverse(Supers)) {
2195 const Record *R = Super.first;
2196 if (R->getName() != "TargetSpecificAttr" &&
2197 R->getName() != "DeclOrTypeAttr" && SuperName.empty())
2198 SuperName = R->getName();
2199 if (R->getName() == "InheritableAttr")
2200 Inheritable = true;
2201 }
2202
2203 OS << "class " << R.getName() << "Attr : public " << SuperName << " {\n";
2204
2205 std::vector<Record*> ArgRecords = R.getValueAsListOfDefs("Args");
2206 std::vector<std::unique_ptr<Argument>> Args;
2207 Args.reserve(ArgRecords.size());
2208
2209 bool HasOptArg = false;
2210 bool HasFakeArg = false;
2211 for (const auto *ArgRecord : ArgRecords) {
2212 Args.emplace_back(createArgument(*ArgRecord, R.getName()));
2213 Args.back()->writeDeclarations(OS);
2214 OS << "\n\n";
2215
2216 // For these purposes, fake takes priority over optional.
2217 if (Args.back()->isFake()) {
2218 HasFakeArg = true;
2219 } else if (Args.back()->isOptional()) {
2220 HasOptArg = true;
2221 }
2222 }
2223
2224 OS << "public:\n";
2225
2226 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(R);
2227
2228 // If there are zero or one spellings, all spelling-related functionality
2229 // can be elided. If all of the spellings share the same name, the spelling
2230 // functionality can also be elided.
2231 bool ElideSpelling = (Spellings.size() <= 1) ||
2232 SpellingNamesAreCommon(Spellings);
2233
2234 // This maps spelling index values to semantic Spelling enumerants.
2235 SemanticSpellingMap SemanticToSyntacticMap;
2236
2237 if (!ElideSpelling)
2238 OS << CreateSemanticSpellings(Spellings, SemanticToSyntacticMap);
2239
2240 // Emit CreateImplicit factory methods.
2241 auto emitCreateImplicit = [&](bool emitFake) {
2242 OS << " static " << R.getName() << "Attr *CreateImplicit(";
2243 OS << "ASTContext &Ctx";
2244 if (!ElideSpelling)
2245 OS << ", Spelling S";
2246 for (auto const &ai : Args) {
2247 if (ai->isFake() && !emitFake) continue;
2248 OS << ", ";
2249 ai->writeCtorParameters(OS);
2250 }
2251 OS << ", SourceRange Loc = SourceRange()";
2252 OS << ") {\n";
2253 OS << " auto *A = new (Ctx) " << R.getName();
2254 OS << "Attr(Loc, Ctx, ";
2255 for (auto const &ai : Args) {
2256 if (ai->isFake() && !emitFake) continue;
2257 ai->writeImplicitCtorArgs(OS);
2258 OS << ", ";
2259 }
2260 OS << (ElideSpelling ? "0" : "S") << ");\n";
2261 OS << " A->setImplicit(true);\n";
2262 OS << " return A;\n }\n\n";
2263 };
2264
2265 // Emit a CreateImplicit that takes all the arguments.
2266 emitCreateImplicit(true);
2267
2268 // Emit a CreateImplicit that takes all the non-fake arguments.
2269 if (HasFakeArg) {
2270 emitCreateImplicit(false);
2271 }
2272
2273 // Emit constructors.
2274 auto emitCtor = [&](bool emitOpt, bool emitFake) {
2275 auto shouldEmitArg = [=](const std::unique_ptr<Argument> &arg) {
2276 if (arg->isFake()) return emitFake;
2277 if (arg->isOptional()) return emitOpt;
2278 return true;
2279 };
2280
2281 OS << " " << R.getName() << "Attr(SourceRange R, ASTContext &Ctx\n";
2282 for (auto const &ai : Args) {
2283 if (!shouldEmitArg(ai)) continue;
2284 OS << " , ";
2285 ai->writeCtorParameters(OS);
2286 OS << "\n";
2287 }
2288
2289 OS << " , ";
2290 OS << "unsigned SI\n";
2291
2292 OS << " )\n";
2293 OS << " : " << SuperName << "(attr::" << R.getName() << ", R, SI, "
2294 << ( R.getValueAsBit("LateParsed") ? "true" : "false" );
2295 if (Inheritable) {
2296 OS << ", "
2297 << (R.getValueAsBit("InheritEvenIfAlreadyPresent") ? "true"
2298 : "false");
2299 }
2300 OS << ")\n";
2301
2302 for (auto const &ai : Args) {
2303 OS << " , ";
2304 if (!shouldEmitArg(ai)) {
2305 ai->writeCtorDefaultInitializers(OS);
2306 } else {
2307 ai->writeCtorInitializers(OS);
2308 }
2309 OS << "\n";
2310 }
2311
2312 OS << " {\n";
2313
2314 for (auto const &ai : Args) {
2315 if (!shouldEmitArg(ai)) continue;
2316 ai->writeCtorBody(OS);
2317 }
2318 OS << " }\n\n";
2319 };
2320
2321 // Emit a constructor that includes all the arguments.
2322 // This is necessary for cloning.
2323 emitCtor(true, true);
2324
2325 // Emit a constructor that takes all the non-fake arguments.
2326 if (HasFakeArg) {
2327 emitCtor(true, false);
2328 }
2329
2330 // Emit a constructor that takes all the non-fake, non-optional arguments.
2331 if (HasOptArg) {
2332 emitCtor(false, false);
2333 }
2334
2335 OS << " " << R.getName() << "Attr *clone(ASTContext &C) const;\n";
2336 OS << " void printPretty(raw_ostream &OS,\n"
2337 << " const PrintingPolicy &Policy) const;\n";
2338 OS << " const char *getSpelling() const;\n";
2339
2340 if (!ElideSpelling) {
2341 assert(!SemanticToSyntacticMap.empty() && "Empty semantic mapping list");
2342 OS << " Spelling getSemanticSpelling() const {\n";
2343 WriteSemanticSpellingSwitch("SpellingListIndex", SemanticToSyntacticMap,
2344 OS);
2345 OS << " }\n";
2346 }
2347
2348 writeAttrAccessorDefinition(R, OS);
2349
2350 for (auto const &ai : Args) {
2351 ai->writeAccessors(OS);
2352 OS << "\n\n";
2353
2354 // Don't write conversion routines for fake arguments.
2355 if (ai->isFake()) continue;
2356
2357 if (ai->isEnumArg())
2358 static_cast<const EnumArgument *>(ai.get())->writeConversion(OS);
2359 else if (ai->isVariadicEnumArg())
2360 static_cast<const VariadicEnumArgument *>(ai.get())
2361 ->writeConversion(OS);
2362 }
2363
2364 OS << R.getValueAsString("AdditionalMembers");
2365 OS << "\n\n";
2366
2367 OS << " static bool classof(const Attr *A) { return A->getKind() == "
2368 << "attr::" << R.getName() << "; }\n";
2369
2370 OS << "};\n\n";
2371 }
2372
2373 OS << "#endif // LLVM_CLANG_ATTR_CLASSES_INC\n";
2374 }
2375
2376 // Emits the class method definitions for attributes.
EmitClangAttrImpl(RecordKeeper & Records,raw_ostream & OS)2377 void EmitClangAttrImpl(RecordKeeper &Records, raw_ostream &OS) {
2378 emitSourceFileHeader("Attribute classes' member function definitions", OS);
2379
2380 std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr");
2381
2382 for (auto *Attr : Attrs) {
2383 Record &R = *Attr;
2384
2385 if (!R.getValueAsBit("ASTNode"))
2386 continue;
2387
2388 std::vector<Record*> ArgRecords = R.getValueAsListOfDefs("Args");
2389 std::vector<std::unique_ptr<Argument>> Args;
2390 for (const auto *Arg : ArgRecords)
2391 Args.emplace_back(createArgument(*Arg, R.getName()));
2392
2393 for (auto const &ai : Args)
2394 ai->writeAccessorDefinitions(OS);
2395
2396 OS << R.getName() << "Attr *" << R.getName()
2397 << "Attr::clone(ASTContext &C) const {\n";
2398 OS << " auto *A = new (C) " << R.getName() << "Attr(getLocation(), C";
2399 for (auto const &ai : Args) {
2400 OS << ", ";
2401 ai->writeCloneArgs(OS);
2402 }
2403 OS << ", getSpellingListIndex());\n";
2404 OS << " A->Inherited = Inherited;\n";
2405 OS << " A->IsPackExpansion = IsPackExpansion;\n";
2406 OS << " A->Implicit = Implicit;\n";
2407 OS << " return A;\n}\n\n";
2408
2409 writePrettyPrintFunction(R, Args, OS);
2410 writeGetSpellingFunction(R, OS);
2411 }
2412
2413 // Instead of relying on virtual dispatch we just create a huge dispatch
2414 // switch. This is both smaller and faster than virtual functions.
2415 auto EmitFunc = [&](const char *Method) {
2416 OS << " switch (getKind()) {\n";
2417 for (const auto *Attr : Attrs) {
2418 const Record &R = *Attr;
2419 if (!R.getValueAsBit("ASTNode"))
2420 continue;
2421
2422 OS << " case attr::" << R.getName() << ":\n";
2423 OS << " return cast<" << R.getName() << "Attr>(this)->" << Method
2424 << ";\n";
2425 }
2426 OS << " }\n";
2427 OS << " llvm_unreachable(\"Unexpected attribute kind!\");\n";
2428 OS << "}\n\n";
2429 };
2430
2431 OS << "const char *Attr::getSpelling() const {\n";
2432 EmitFunc("getSpelling()");
2433
2434 OS << "Attr *Attr::clone(ASTContext &C) const {\n";
2435 EmitFunc("clone(C)");
2436
2437 OS << "void Attr::printPretty(raw_ostream &OS, "
2438 "const PrintingPolicy &Policy) const {\n";
2439 EmitFunc("printPretty(OS, Policy)");
2440 }
2441
2442 } // end namespace clang
2443
emitAttrList(raw_ostream & OS,StringRef Class,const std::vector<Record * > & AttrList)2444 static void emitAttrList(raw_ostream &OS, StringRef Class,
2445 const std::vector<Record*> &AttrList) {
2446 for (auto Cur : AttrList) {
2447 OS << Class << "(" << Cur->getName() << ")\n";
2448 }
2449 }
2450
2451 // Determines if an attribute has a Pragma spelling.
AttrHasPragmaSpelling(const Record * R)2452 static bool AttrHasPragmaSpelling(const Record *R) {
2453 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(*R);
2454 return llvm::find_if(Spellings, [](const FlattenedSpelling &S) {
2455 return S.variety() == "Pragma";
2456 }) != Spellings.end();
2457 }
2458
2459 namespace {
2460
2461 struct AttrClassDescriptor {
2462 const char * const MacroName;
2463 const char * const TableGenName;
2464 };
2465
2466 } // end anonymous namespace
2467
2468 static const AttrClassDescriptor AttrClassDescriptors[] = {
2469 { "ATTR", "Attr" },
2470 { "TYPE_ATTR", "TypeAttr" },
2471 { "STMT_ATTR", "StmtAttr" },
2472 { "INHERITABLE_ATTR", "InheritableAttr" },
2473 { "DECL_OR_TYPE_ATTR", "DeclOrTypeAttr" },
2474 { "INHERITABLE_PARAM_ATTR", "InheritableParamAttr" },
2475 { "PARAMETER_ABI_ATTR", "ParameterABIAttr" }
2476 };
2477
emitDefaultDefine(raw_ostream & OS,StringRef name,const char * superName)2478 static void emitDefaultDefine(raw_ostream &OS, StringRef name,
2479 const char *superName) {
2480 OS << "#ifndef " << name << "\n";
2481 OS << "#define " << name << "(NAME) ";
2482 if (superName) OS << superName << "(NAME)";
2483 OS << "\n#endif\n\n";
2484 }
2485
2486 namespace {
2487
2488 /// A class of attributes.
2489 struct AttrClass {
2490 const AttrClassDescriptor &Descriptor;
2491 Record *TheRecord;
2492 AttrClass *SuperClass = nullptr;
2493 std::vector<AttrClass*> SubClasses;
2494 std::vector<Record*> Attrs;
2495
AttrClass__anon91f985ad0f11::AttrClass2496 AttrClass(const AttrClassDescriptor &Descriptor, Record *R)
2497 : Descriptor(Descriptor), TheRecord(R) {}
2498
emitDefaultDefines__anon91f985ad0f11::AttrClass2499 void emitDefaultDefines(raw_ostream &OS) const {
2500 // Default the macro unless this is a root class (i.e. Attr).
2501 if (SuperClass) {
2502 emitDefaultDefine(OS, Descriptor.MacroName,
2503 SuperClass->Descriptor.MacroName);
2504 }
2505 }
2506
emitUndefs__anon91f985ad0f11::AttrClass2507 void emitUndefs(raw_ostream &OS) const {
2508 OS << "#undef " << Descriptor.MacroName << "\n";
2509 }
2510
emitAttrList__anon91f985ad0f11::AttrClass2511 void emitAttrList(raw_ostream &OS) const {
2512 for (auto SubClass : SubClasses) {
2513 SubClass->emitAttrList(OS);
2514 }
2515
2516 ::emitAttrList(OS, Descriptor.MacroName, Attrs);
2517 }
2518
classifyAttrOnRoot__anon91f985ad0f11::AttrClass2519 void classifyAttrOnRoot(Record *Attr) {
2520 bool result = classifyAttr(Attr);
2521 assert(result && "failed to classify on root"); (void) result;
2522 }
2523
emitAttrRange__anon91f985ad0f11::AttrClass2524 void emitAttrRange(raw_ostream &OS) const {
2525 OS << "ATTR_RANGE(" << Descriptor.TableGenName
2526 << ", " << getFirstAttr()->getName()
2527 << ", " << getLastAttr()->getName() << ")\n";
2528 }
2529
2530 private:
classifyAttr__anon91f985ad0f11::AttrClass2531 bool classifyAttr(Record *Attr) {
2532 // Check all the subclasses.
2533 for (auto SubClass : SubClasses) {
2534 if (SubClass->classifyAttr(Attr))
2535 return true;
2536 }
2537
2538 // It's not more specific than this class, but it might still belong here.
2539 if (Attr->isSubClassOf(TheRecord)) {
2540 Attrs.push_back(Attr);
2541 return true;
2542 }
2543
2544 return false;
2545 }
2546
getFirstAttr__anon91f985ad0f11::AttrClass2547 Record *getFirstAttr() const {
2548 if (!SubClasses.empty())
2549 return SubClasses.front()->getFirstAttr();
2550 return Attrs.front();
2551 }
2552
getLastAttr__anon91f985ad0f11::AttrClass2553 Record *getLastAttr() const {
2554 if (!Attrs.empty())
2555 return Attrs.back();
2556 return SubClasses.back()->getLastAttr();
2557 }
2558 };
2559
2560 /// The entire hierarchy of attribute classes.
2561 class AttrClassHierarchy {
2562 std::vector<std::unique_ptr<AttrClass>> Classes;
2563
2564 public:
AttrClassHierarchy(RecordKeeper & Records)2565 AttrClassHierarchy(RecordKeeper &Records) {
2566 // Find records for all the classes.
2567 for (auto &Descriptor : AttrClassDescriptors) {
2568 Record *ClassRecord = Records.getClass(Descriptor.TableGenName);
2569 AttrClass *Class = new AttrClass(Descriptor, ClassRecord);
2570 Classes.emplace_back(Class);
2571 }
2572
2573 // Link up the hierarchy.
2574 for (auto &Class : Classes) {
2575 if (AttrClass *SuperClass = findSuperClass(Class->TheRecord)) {
2576 Class->SuperClass = SuperClass;
2577 SuperClass->SubClasses.push_back(Class.get());
2578 }
2579 }
2580
2581 #ifndef NDEBUG
2582 for (auto i = Classes.begin(), e = Classes.end(); i != e; ++i) {
2583 assert((i == Classes.begin()) == ((*i)->SuperClass == nullptr) &&
2584 "only the first class should be a root class!");
2585 }
2586 #endif
2587 }
2588
emitDefaultDefines(raw_ostream & OS) const2589 void emitDefaultDefines(raw_ostream &OS) const {
2590 for (auto &Class : Classes) {
2591 Class->emitDefaultDefines(OS);
2592 }
2593 }
2594
emitUndefs(raw_ostream & OS) const2595 void emitUndefs(raw_ostream &OS) const {
2596 for (auto &Class : Classes) {
2597 Class->emitUndefs(OS);
2598 }
2599 }
2600
emitAttrLists(raw_ostream & OS) const2601 void emitAttrLists(raw_ostream &OS) const {
2602 // Just start from the root class.
2603 Classes[0]->emitAttrList(OS);
2604 }
2605
emitAttrRanges(raw_ostream & OS) const2606 void emitAttrRanges(raw_ostream &OS) const {
2607 for (auto &Class : Classes)
2608 Class->emitAttrRange(OS);
2609 }
2610
classifyAttr(Record * Attr)2611 void classifyAttr(Record *Attr) {
2612 // Add the attribute to the root class.
2613 Classes[0]->classifyAttrOnRoot(Attr);
2614 }
2615
2616 private:
findClassByRecord(Record * R) const2617 AttrClass *findClassByRecord(Record *R) const {
2618 for (auto &Class : Classes) {
2619 if (Class->TheRecord == R)
2620 return Class.get();
2621 }
2622 return nullptr;
2623 }
2624
findSuperClass(Record * R) const2625 AttrClass *findSuperClass(Record *R) const {
2626 // TableGen flattens the superclass list, so we just need to walk it
2627 // in reverse.
2628 auto SuperClasses = R->getSuperClasses();
2629 for (signed i = 0, e = SuperClasses.size(); i != e; ++i) {
2630 auto SuperClass = findClassByRecord(SuperClasses[e - i - 1].first);
2631 if (SuperClass) return SuperClass;
2632 }
2633 return nullptr;
2634 }
2635 };
2636
2637 } // end anonymous namespace
2638
2639 namespace clang {
2640
2641 // Emits the enumeration list for attributes.
EmitClangAttrList(RecordKeeper & Records,raw_ostream & OS)2642 void EmitClangAttrList(RecordKeeper &Records, raw_ostream &OS) {
2643 emitSourceFileHeader("List of all attributes that Clang recognizes", OS);
2644
2645 AttrClassHierarchy Hierarchy(Records);
2646
2647 // Add defaulting macro definitions.
2648 Hierarchy.emitDefaultDefines(OS);
2649 emitDefaultDefine(OS, "PRAGMA_SPELLING_ATTR", nullptr);
2650
2651 std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
2652 std::vector<Record *> PragmaAttrs;
2653 for (auto *Attr : Attrs) {
2654 if (!Attr->getValueAsBit("ASTNode"))
2655 continue;
2656
2657 // Add the attribute to the ad-hoc groups.
2658 if (AttrHasPragmaSpelling(Attr))
2659 PragmaAttrs.push_back(Attr);
2660
2661 // Place it in the hierarchy.
2662 Hierarchy.classifyAttr(Attr);
2663 }
2664
2665 // Emit the main attribute list.
2666 Hierarchy.emitAttrLists(OS);
2667
2668 // Emit the ad hoc groups.
2669 emitAttrList(OS, "PRAGMA_SPELLING_ATTR", PragmaAttrs);
2670
2671 // Emit the attribute ranges.
2672 OS << "#ifdef ATTR_RANGE\n";
2673 Hierarchy.emitAttrRanges(OS);
2674 OS << "#undef ATTR_RANGE\n";
2675 OS << "#endif\n";
2676
2677 Hierarchy.emitUndefs(OS);
2678 OS << "#undef PRAGMA_SPELLING_ATTR\n";
2679 }
2680
2681 // Emits the enumeration list for attributes.
EmitClangAttrSubjectMatchRuleList(RecordKeeper & Records,raw_ostream & OS)2682 void EmitClangAttrSubjectMatchRuleList(RecordKeeper &Records, raw_ostream &OS) {
2683 emitSourceFileHeader(
2684 "List of all attribute subject matching rules that Clang recognizes", OS);
2685 PragmaClangAttributeSupport &PragmaAttributeSupport =
2686 getPragmaAttributeSupport(Records);
2687 emitDefaultDefine(OS, "ATTR_MATCH_RULE", nullptr);
2688 PragmaAttributeSupport.emitMatchRuleList(OS);
2689 OS << "#undef ATTR_MATCH_RULE\n";
2690 }
2691
2692 // Emits the code to read an attribute from a precompiled header.
EmitClangAttrPCHRead(RecordKeeper & Records,raw_ostream & OS)2693 void EmitClangAttrPCHRead(RecordKeeper &Records, raw_ostream &OS) {
2694 emitSourceFileHeader("Attribute deserialization code", OS);
2695
2696 Record *InhClass = Records.getClass("InheritableAttr");
2697 std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr"),
2698 ArgRecords;
2699 std::vector<std::unique_ptr<Argument>> Args;
2700
2701 OS << " switch (Kind) {\n";
2702 for (const auto *Attr : Attrs) {
2703 const Record &R = *Attr;
2704 if (!R.getValueAsBit("ASTNode"))
2705 continue;
2706
2707 OS << " case attr::" << R.getName() << ": {\n";
2708 if (R.isSubClassOf(InhClass))
2709 OS << " bool isInherited = Record.readInt();\n";
2710 OS << " bool isImplicit = Record.readInt();\n";
2711 OS << " unsigned Spelling = Record.readInt();\n";
2712 ArgRecords = R.getValueAsListOfDefs("Args");
2713 Args.clear();
2714 for (const auto *Arg : ArgRecords) {
2715 Args.emplace_back(createArgument(*Arg, R.getName()));
2716 Args.back()->writePCHReadDecls(OS);
2717 }
2718 OS << " New = new (Context) " << R.getName() << "Attr(Range, Context";
2719 for (auto const &ri : Args) {
2720 OS << ", ";
2721 ri->writePCHReadArgs(OS);
2722 }
2723 OS << ", Spelling);\n";
2724 if (R.isSubClassOf(InhClass))
2725 OS << " cast<InheritableAttr>(New)->setInherited(isInherited);\n";
2726 OS << " New->setImplicit(isImplicit);\n";
2727 OS << " break;\n";
2728 OS << " }\n";
2729 }
2730 OS << " }\n";
2731 }
2732
2733 // Emits the code to write an attribute to a precompiled header.
EmitClangAttrPCHWrite(RecordKeeper & Records,raw_ostream & OS)2734 void EmitClangAttrPCHWrite(RecordKeeper &Records, raw_ostream &OS) {
2735 emitSourceFileHeader("Attribute serialization code", OS);
2736
2737 Record *InhClass = Records.getClass("InheritableAttr");
2738 std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr"), Args;
2739
2740 OS << " switch (A->getKind()) {\n";
2741 for (const auto *Attr : Attrs) {
2742 const Record &R = *Attr;
2743 if (!R.getValueAsBit("ASTNode"))
2744 continue;
2745 OS << " case attr::" << R.getName() << ": {\n";
2746 Args = R.getValueAsListOfDefs("Args");
2747 if (R.isSubClassOf(InhClass) || !Args.empty())
2748 OS << " const auto *SA = cast<" << R.getName()
2749 << "Attr>(A);\n";
2750 if (R.isSubClassOf(InhClass))
2751 OS << " Record.push_back(SA->isInherited());\n";
2752 OS << " Record.push_back(A->isImplicit());\n";
2753 OS << " Record.push_back(A->getSpellingListIndex());\n";
2754
2755 for (const auto *Arg : Args)
2756 createArgument(*Arg, R.getName())->writePCHWrite(OS);
2757 OS << " break;\n";
2758 OS << " }\n";
2759 }
2760 OS << " }\n";
2761 }
2762
2763 // Helper function for GenerateTargetSpecificAttrChecks that alters the 'Test'
2764 // parameter with only a single check type, if applicable.
GenerateTargetSpecificAttrCheck(const Record * R,std::string & Test,std::string * FnName,StringRef ListName,StringRef CheckAgainst,StringRef Scope)2765 static void GenerateTargetSpecificAttrCheck(const Record *R, std::string &Test,
2766 std::string *FnName,
2767 StringRef ListName,
2768 StringRef CheckAgainst,
2769 StringRef Scope) {
2770 if (!R->isValueUnset(ListName)) {
2771 Test += " && (";
2772 std::vector<StringRef> Items = R->getValueAsListOfStrings(ListName);
2773 for (auto I = Items.begin(), E = Items.end(); I != E; ++I) {
2774 StringRef Part = *I;
2775 Test += CheckAgainst;
2776 Test += " == ";
2777 Test += Scope;
2778 Test += Part;
2779 if (I + 1 != E)
2780 Test += " || ";
2781 if (FnName)
2782 *FnName += Part;
2783 }
2784 Test += ")";
2785 }
2786 }
2787
2788 // Generate a conditional expression to check if the current target satisfies
2789 // the conditions for a TargetSpecificAttr record, and append the code for
2790 // those checks to the Test string. If the FnName string pointer is non-null,
2791 // append a unique suffix to distinguish this set of target checks from other
2792 // TargetSpecificAttr records.
GenerateTargetSpecificAttrChecks(const Record * R,std::vector<StringRef> & Arches,std::string & Test,std::string * FnName)2793 static void GenerateTargetSpecificAttrChecks(const Record *R,
2794 std::vector<StringRef> &Arches,
2795 std::string &Test,
2796 std::string *FnName) {
2797 // It is assumed that there will be an llvm::Triple object
2798 // named "T" and a TargetInfo object named "Target" within
2799 // scope that can be used to determine whether the attribute exists in
2800 // a given target.
2801 Test += "true";
2802 // If one or more architectures is specified, check those. Arches are handled
2803 // differently because GenerateTargetRequirements needs to combine the list
2804 // with ParseKind.
2805 if (!Arches.empty()) {
2806 Test += " && (";
2807 for (auto I = Arches.begin(), E = Arches.end(); I != E; ++I) {
2808 StringRef Part = *I;
2809 Test += "T.getArch() == llvm::Triple::";
2810 Test += Part;
2811 if (I + 1 != E)
2812 Test += " || ";
2813 if (FnName)
2814 *FnName += Part;
2815 }
2816 Test += ")";
2817 }
2818
2819 // If the attribute is specific to particular OSes, check those.
2820 GenerateTargetSpecificAttrCheck(R, Test, FnName, "OSes", "T.getOS()",
2821 "llvm::Triple::");
2822
2823 // If one or more CXX ABIs are specified, check those as well.
2824 GenerateTargetSpecificAttrCheck(R, Test, FnName, "CXXABIs",
2825 "Target.getCXXABI().getKind()",
2826 "TargetCXXABI::");
2827 // If one or more object formats is specified, check those.
2828 GenerateTargetSpecificAttrCheck(R, Test, FnName, "ObjectFormats",
2829 "T.getObjectFormat()", "llvm::Triple::");
2830 }
2831
GenerateHasAttrSpellingStringSwitch(const std::vector<Record * > & Attrs,raw_ostream & OS,const std::string & Variety="",const std::string & Scope="")2832 static void GenerateHasAttrSpellingStringSwitch(
2833 const std::vector<Record *> &Attrs, raw_ostream &OS,
2834 const std::string &Variety = "", const std::string &Scope = "") {
2835 for (const auto *Attr : Attrs) {
2836 // C++11-style attributes have specific version information associated with
2837 // them. If the attribute has no scope, the version information must not
2838 // have the default value (1), as that's incorrect. Instead, the unscoped
2839 // attribute version information should be taken from the SD-6 standing
2840 // document, which can be found at:
2841 // https://isocpp.org/std/standing-documents/sd-6-sg10-feature-test-recommendations
2842 int Version = 1;
2843
2844 if (Variety == "CXX11") {
2845 std::vector<Record *> Spellings = Attr->getValueAsListOfDefs("Spellings");
2846 for (const auto &Spelling : Spellings) {
2847 if (Spelling->getValueAsString("Variety") == "CXX11") {
2848 Version = static_cast<int>(Spelling->getValueAsInt("Version"));
2849 if (Scope.empty() && Version == 1)
2850 PrintError(Spelling->getLoc(), "C++ standard attributes must "
2851 "have valid version information.");
2852 break;
2853 }
2854 }
2855 }
2856
2857 std::string Test;
2858 if (Attr->isSubClassOf("TargetSpecificAttr")) {
2859 const Record *R = Attr->getValueAsDef("Target");
2860 std::vector<StringRef> Arches = R->getValueAsListOfStrings("Arches");
2861 GenerateTargetSpecificAttrChecks(R, Arches, Test, nullptr);
2862
2863 // If this is the C++11 variety, also add in the LangOpts test.
2864 if (Variety == "CXX11")
2865 Test += " && LangOpts.CPlusPlus11";
2866 else if (Variety == "C2x")
2867 Test += " && LangOpts.DoubleSquareBracketAttributes";
2868 } else if (Variety == "CXX11")
2869 // C++11 mode should be checked against LangOpts, which is presumed to be
2870 // present in the caller.
2871 Test = "LangOpts.CPlusPlus11";
2872 else if (Variety == "C2x")
2873 Test = "LangOpts.DoubleSquareBracketAttributes";
2874
2875 std::string TestStr =
2876 !Test.empty() ? Test + " ? " + llvm::itostr(Version) + " : 0" : "1";
2877 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(*Attr);
2878 for (const auto &S : Spellings)
2879 if (Variety.empty() || (Variety == S.variety() &&
2880 (Scope.empty() || Scope == S.nameSpace())))
2881 OS << " .Case(\"" << S.name() << "\", " << TestStr << ")\n";
2882 }
2883 OS << " .Default(0);\n";
2884 }
2885
2886 // Emits the list of spellings for attributes.
EmitClangAttrHasAttrImpl(RecordKeeper & Records,raw_ostream & OS)2887 void EmitClangAttrHasAttrImpl(RecordKeeper &Records, raw_ostream &OS) {
2888 emitSourceFileHeader("Code to implement the __has_attribute logic", OS);
2889
2890 // Separate all of the attributes out into four group: generic, C++11, GNU,
2891 // and declspecs. Then generate a big switch statement for each of them.
2892 std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
2893 std::vector<Record *> Declspec, Microsoft, GNU, Pragma;
2894 std::map<std::string, std::vector<Record *>> CXX, C2x;
2895
2896 // Walk over the list of all attributes, and split them out based on the
2897 // spelling variety.
2898 for (auto *R : Attrs) {
2899 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(*R);
2900 for (const auto &SI : Spellings) {
2901 const std::string &Variety = SI.variety();
2902 if (Variety == "GNU")
2903 GNU.push_back(R);
2904 else if (Variety == "Declspec")
2905 Declspec.push_back(R);
2906 else if (Variety == "Microsoft")
2907 Microsoft.push_back(R);
2908 else if (Variety == "CXX11")
2909 CXX[SI.nameSpace()].push_back(R);
2910 else if (Variety == "C2x")
2911 C2x[SI.nameSpace()].push_back(R);
2912 else if (Variety == "Pragma")
2913 Pragma.push_back(R);
2914 }
2915 }
2916
2917 OS << "const llvm::Triple &T = Target.getTriple();\n";
2918 OS << "switch (Syntax) {\n";
2919 OS << "case AttrSyntax::GNU:\n";
2920 OS << " return llvm::StringSwitch<int>(Name)\n";
2921 GenerateHasAttrSpellingStringSwitch(GNU, OS, "GNU");
2922 OS << "case AttrSyntax::Declspec:\n";
2923 OS << " return llvm::StringSwitch<int>(Name)\n";
2924 GenerateHasAttrSpellingStringSwitch(Declspec, OS, "Declspec");
2925 OS << "case AttrSyntax::Microsoft:\n";
2926 OS << " return llvm::StringSwitch<int>(Name)\n";
2927 GenerateHasAttrSpellingStringSwitch(Microsoft, OS, "Microsoft");
2928 OS << "case AttrSyntax::Pragma:\n";
2929 OS << " return llvm::StringSwitch<int>(Name)\n";
2930 GenerateHasAttrSpellingStringSwitch(Pragma, OS, "Pragma");
2931 auto fn = [&OS](const char *Spelling, const char *Variety,
2932 const std::map<std::string, std::vector<Record *>> &List) {
2933 OS << "case AttrSyntax::" << Variety << ": {\n";
2934 // C++11-style attributes are further split out based on the Scope.
2935 for (auto I = List.cbegin(), E = List.cend(); I != E; ++I) {
2936 if (I != List.cbegin())
2937 OS << " else ";
2938 if (I->first.empty())
2939 OS << "if (ScopeName == \"\") {\n";
2940 else
2941 OS << "if (ScopeName == \"" << I->first << "\") {\n";
2942 OS << " return llvm::StringSwitch<int>(Name)\n";
2943 GenerateHasAttrSpellingStringSwitch(I->second, OS, Spelling, I->first);
2944 OS << "}";
2945 }
2946 OS << "\n} break;\n";
2947 };
2948 fn("CXX11", "CXX", CXX);
2949 fn("C2x", "C", C2x);
2950 OS << "}\n";
2951 }
2952
EmitClangAttrSpellingListIndex(RecordKeeper & Records,raw_ostream & OS)2953 void EmitClangAttrSpellingListIndex(RecordKeeper &Records, raw_ostream &OS) {
2954 emitSourceFileHeader("Code to translate different attribute spellings "
2955 "into internal identifiers", OS);
2956
2957 OS << " switch (AttrKind) {\n";
2958
2959 ParsedAttrMap Attrs = getParsedAttrList(Records);
2960 for (const auto &I : Attrs) {
2961 const Record &R = *I.second;
2962 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(R);
2963 OS << " case AT_" << I.first << ": {\n";
2964 for (unsigned I = 0; I < Spellings.size(); ++ I) {
2965 OS << " if (Name == \"" << Spellings[I].name() << "\" && "
2966 << "SyntaxUsed == "
2967 << StringSwitch<unsigned>(Spellings[I].variety())
2968 .Case("GNU", 0)
2969 .Case("CXX11", 1)
2970 .Case("C2x", 2)
2971 .Case("Declspec", 3)
2972 .Case("Microsoft", 4)
2973 .Case("Keyword", 5)
2974 .Case("Pragma", 6)
2975 .Default(0)
2976 << " && Scope == \"" << Spellings[I].nameSpace() << "\")\n"
2977 << " return " << I << ";\n";
2978 }
2979
2980 OS << " break;\n";
2981 OS << " }\n";
2982 }
2983
2984 OS << " }\n";
2985 OS << " return 0;\n";
2986 }
2987
2988 // Emits code used by RecursiveASTVisitor to visit attributes
EmitClangAttrASTVisitor(RecordKeeper & Records,raw_ostream & OS)2989 void EmitClangAttrASTVisitor(RecordKeeper &Records, raw_ostream &OS) {
2990 emitSourceFileHeader("Used by RecursiveASTVisitor to visit attributes.", OS);
2991
2992 std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr");
2993
2994 // Write method declarations for Traverse* methods.
2995 // We emit this here because we only generate methods for attributes that
2996 // are declared as ASTNodes.
2997 OS << "#ifdef ATTR_VISITOR_DECLS_ONLY\n\n";
2998 for (const auto *Attr : Attrs) {
2999 const Record &R = *Attr;
3000 if (!R.getValueAsBit("ASTNode"))
3001 continue;
3002 OS << " bool Traverse"
3003 << R.getName() << "Attr(" << R.getName() << "Attr *A);\n";
3004 OS << " bool Visit"
3005 << R.getName() << "Attr(" << R.getName() << "Attr *A) {\n"
3006 << " return true; \n"
3007 << " }\n";
3008 }
3009 OS << "\n#else // ATTR_VISITOR_DECLS_ONLY\n\n";
3010
3011 // Write individual Traverse* methods for each attribute class.
3012 for (const auto *Attr : Attrs) {
3013 const Record &R = *Attr;
3014 if (!R.getValueAsBit("ASTNode"))
3015 continue;
3016
3017 OS << "template <typename Derived>\n"
3018 << "bool VISITORCLASS<Derived>::Traverse"
3019 << R.getName() << "Attr(" << R.getName() << "Attr *A) {\n"
3020 << " if (!getDerived().VisitAttr(A))\n"
3021 << " return false;\n"
3022 << " if (!getDerived().Visit" << R.getName() << "Attr(A))\n"
3023 << " return false;\n";
3024
3025 std::vector<Record*> ArgRecords = R.getValueAsListOfDefs("Args");
3026 for (const auto *Arg : ArgRecords)
3027 createArgument(*Arg, R.getName())->writeASTVisitorTraversal(OS);
3028
3029 OS << " return true;\n";
3030 OS << "}\n\n";
3031 }
3032
3033 // Write generic Traverse routine
3034 OS << "template <typename Derived>\n"
3035 << "bool VISITORCLASS<Derived>::TraverseAttr(Attr *A) {\n"
3036 << " if (!A)\n"
3037 << " return true;\n"
3038 << "\n"
3039 << " switch (A->getKind()) {\n";
3040
3041 for (const auto *Attr : Attrs) {
3042 const Record &R = *Attr;
3043 if (!R.getValueAsBit("ASTNode"))
3044 continue;
3045
3046 OS << " case attr::" << R.getName() << ":\n"
3047 << " return getDerived().Traverse" << R.getName() << "Attr("
3048 << "cast<" << R.getName() << "Attr>(A));\n";
3049 }
3050 OS << " }\n"; // end switch
3051 OS << " llvm_unreachable(\"bad attribute kind\");\n";
3052 OS << "}\n"; // end function
3053 OS << "#endif // ATTR_VISITOR_DECLS_ONLY\n";
3054 }
3055
EmitClangAttrTemplateInstantiateHelper(const std::vector<Record * > & Attrs,raw_ostream & OS,bool AppliesToDecl)3056 void EmitClangAttrTemplateInstantiateHelper(const std::vector<Record *> &Attrs,
3057 raw_ostream &OS,
3058 bool AppliesToDecl) {
3059
3060 OS << " switch (At->getKind()) {\n";
3061 for (const auto *Attr : Attrs) {
3062 const Record &R = *Attr;
3063 if (!R.getValueAsBit("ASTNode"))
3064 continue;
3065 OS << " case attr::" << R.getName() << ": {\n";
3066 bool ShouldClone = R.getValueAsBit("Clone") &&
3067 (!AppliesToDecl ||
3068 R.getValueAsBit("MeaningfulToClassTemplateDefinition"));
3069
3070 if (!ShouldClone) {
3071 OS << " return nullptr;\n";
3072 OS << " }\n";
3073 continue;
3074 }
3075
3076 OS << " const auto *A = cast<"
3077 << R.getName() << "Attr>(At);\n";
3078 bool TDependent = R.getValueAsBit("TemplateDependent");
3079
3080 if (!TDependent) {
3081 OS << " return A->clone(C);\n";
3082 OS << " }\n";
3083 continue;
3084 }
3085
3086 std::vector<Record*> ArgRecords = R.getValueAsListOfDefs("Args");
3087 std::vector<std::unique_ptr<Argument>> Args;
3088 Args.reserve(ArgRecords.size());
3089
3090 for (const auto *ArgRecord : ArgRecords)
3091 Args.emplace_back(createArgument(*ArgRecord, R.getName()));
3092
3093 for (auto const &ai : Args)
3094 ai->writeTemplateInstantiation(OS);
3095
3096 OS << " return new (C) " << R.getName() << "Attr(A->getLocation(), C";
3097 for (auto const &ai : Args) {
3098 OS << ", ";
3099 ai->writeTemplateInstantiationArgs(OS);
3100 }
3101 OS << ", A->getSpellingListIndex());\n }\n";
3102 }
3103 OS << " } // end switch\n"
3104 << " llvm_unreachable(\"Unknown attribute!\");\n"
3105 << " return nullptr;\n";
3106 }
3107
3108 // Emits code to instantiate dependent attributes on templates.
EmitClangAttrTemplateInstantiate(RecordKeeper & Records,raw_ostream & OS)3109 void EmitClangAttrTemplateInstantiate(RecordKeeper &Records, raw_ostream &OS) {
3110 emitSourceFileHeader("Template instantiation code for attributes", OS);
3111
3112 std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr");
3113
3114 OS << "namespace clang {\n"
3115 << "namespace sema {\n\n"
3116 << "Attr *instantiateTemplateAttribute(const Attr *At, ASTContext &C, "
3117 << "Sema &S,\n"
3118 << " const MultiLevelTemplateArgumentList &TemplateArgs) {\n";
3119 EmitClangAttrTemplateInstantiateHelper(Attrs, OS, /*AppliesToDecl*/false);
3120 OS << "}\n\n"
3121 << "Attr *instantiateTemplateAttributeForDecl(const Attr *At,\n"
3122 << " ASTContext &C, Sema &S,\n"
3123 << " const MultiLevelTemplateArgumentList &TemplateArgs) {\n";
3124 EmitClangAttrTemplateInstantiateHelper(Attrs, OS, /*AppliesToDecl*/true);
3125 OS << "}\n\n"
3126 << "} // end namespace sema\n"
3127 << "} // end namespace clang\n";
3128 }
3129
3130 // Emits the list of parsed attributes.
EmitClangAttrParsedAttrList(RecordKeeper & Records,raw_ostream & OS)3131 void EmitClangAttrParsedAttrList(RecordKeeper &Records, raw_ostream &OS) {
3132 emitSourceFileHeader("List of all attributes that Clang recognizes", OS);
3133
3134 OS << "#ifndef PARSED_ATTR\n";
3135 OS << "#define PARSED_ATTR(NAME) NAME\n";
3136 OS << "#endif\n\n";
3137
3138 ParsedAttrMap Names = getParsedAttrList(Records);
3139 for (const auto &I : Names) {
3140 OS << "PARSED_ATTR(" << I.first << ")\n";
3141 }
3142 }
3143
isArgVariadic(const Record & R,StringRef AttrName)3144 static bool isArgVariadic(const Record &R, StringRef AttrName) {
3145 return createArgument(R, AttrName)->isVariadic();
3146 }
3147
emitArgInfo(const Record & R,raw_ostream & OS)3148 static void emitArgInfo(const Record &R, raw_ostream &OS) {
3149 // This function will count the number of arguments specified for the
3150 // attribute and emit the number of required arguments followed by the
3151 // number of optional arguments.
3152 std::vector<Record *> Args = R.getValueAsListOfDefs("Args");
3153 unsigned ArgCount = 0, OptCount = 0;
3154 bool HasVariadic = false;
3155 for (const auto *Arg : Args) {
3156 // If the arg is fake, it's the user's job to supply it: general parsing
3157 // logic shouldn't need to know anything about it.
3158 if (Arg->getValueAsBit("Fake"))
3159 continue;
3160 Arg->getValueAsBit("Optional") ? ++OptCount : ++ArgCount;
3161 if (!HasVariadic && isArgVariadic(*Arg, R.getName()))
3162 HasVariadic = true;
3163 }
3164
3165 // If there is a variadic argument, we will set the optional argument count
3166 // to its largest value. Since it's currently a 4-bit number, we set it to 15.
3167 OS << ArgCount << ", " << (HasVariadic ? 15 : OptCount);
3168 }
3169
GenerateDefaultAppertainsTo(raw_ostream & OS)3170 static void GenerateDefaultAppertainsTo(raw_ostream &OS) {
3171 OS << "static bool defaultAppertainsTo(Sema &, const ParsedAttr &,";
3172 OS << "const Decl *) {\n";
3173 OS << " return true;\n";
3174 OS << "}\n\n";
3175 }
3176
GetDiagnosticSpelling(const Record & R)3177 static std::string GetDiagnosticSpelling(const Record &R) {
3178 std::string Ret = R.getValueAsString("DiagSpelling");
3179 if (!Ret.empty())
3180 return Ret;
3181
3182 // If we couldn't find the DiagSpelling in this object, we can check to see
3183 // if the object is one that has a base, and if it is, loop up to the Base
3184 // member recursively.
3185 std::string Super = R.getSuperClasses().back().first->getName();
3186 if (Super == "DDecl" || Super == "DStmt")
3187 return GetDiagnosticSpelling(*R.getValueAsDef("Base"));
3188
3189 return "";
3190 }
3191
CalculateDiagnostic(const Record & S)3192 static std::string CalculateDiagnostic(const Record &S) {
3193 // If the SubjectList object has a custom diagnostic associated with it,
3194 // return that directly.
3195 const StringRef CustomDiag = S.getValueAsString("CustomDiag");
3196 if (!CustomDiag.empty())
3197 return ("\"" + Twine(CustomDiag) + "\"").str();
3198
3199 std::vector<std::string> DiagList;
3200 std::vector<Record *> Subjects = S.getValueAsListOfDefs("Subjects");
3201 for (const auto *Subject : Subjects) {
3202 const Record &R = *Subject;
3203 // Get the diagnostic text from the Decl or Stmt node given.
3204 std::string V = GetDiagnosticSpelling(R);
3205 if (V.empty()) {
3206 PrintError(R.getLoc(),
3207 "Could not determine diagnostic spelling for the node: " +
3208 R.getName() + "; please add one to DeclNodes.td");
3209 } else {
3210 // The node may contain a list of elements itself, so split the elements
3211 // by a comma, and trim any whitespace.
3212 SmallVector<StringRef, 2> Frags;
3213 llvm::SplitString(V, Frags, ",");
3214 for (auto Str : Frags) {
3215 DiagList.push_back(Str.trim());
3216 }
3217 }
3218 }
3219
3220 if (DiagList.empty()) {
3221 PrintFatalError(S.getLoc(),
3222 "Could not deduce diagnostic argument for Attr subjects");
3223 return "";
3224 }
3225
3226 // FIXME: this is not particularly good for localization purposes and ideally
3227 // should be part of the diagnostics engine itself with some sort of list
3228 // specifier.
3229
3230 // A single member of the list can be returned directly.
3231 if (DiagList.size() == 1)
3232 return '"' + DiagList.front() + '"';
3233
3234 if (DiagList.size() == 2)
3235 return '"' + DiagList[0] + " and " + DiagList[1] + '"';
3236
3237 // If there are more than two in the list, we serialize the first N - 1
3238 // elements with a comma. This leaves the string in the state: foo, bar,
3239 // baz (but misses quux). We can then add ", and " for the last element
3240 // manually.
3241 std::string Diag = llvm::join(DiagList.begin(), DiagList.end() - 1, ", ");
3242 return '"' + Diag + ", and " + *(DiagList.end() - 1) + '"';
3243 }
3244
GetSubjectWithSuffix(const Record * R)3245 static std::string GetSubjectWithSuffix(const Record *R) {
3246 const std::string &B = R->getName();
3247 if (B == "DeclBase")
3248 return "Decl";
3249 return B + "Decl";
3250 }
3251
functionNameForCustomAppertainsTo(const Record & Subject)3252 static std::string functionNameForCustomAppertainsTo(const Record &Subject) {
3253 return "is" + Subject.getName().str();
3254 }
3255
GenerateCustomAppertainsTo(const Record & Subject,raw_ostream & OS)3256 static std::string GenerateCustomAppertainsTo(const Record &Subject,
3257 raw_ostream &OS) {
3258 std::string FnName = functionNameForCustomAppertainsTo(Subject);
3259
3260 // If this code has already been generated, simply return the previous
3261 // instance of it.
3262 static std::set<std::string> CustomSubjectSet;
3263 auto I = CustomSubjectSet.find(FnName);
3264 if (I != CustomSubjectSet.end())
3265 return *I;
3266
3267 Record *Base = Subject.getValueAsDef("Base");
3268
3269 // Not currently support custom subjects within custom subjects.
3270 if (Base->isSubClassOf("SubsetSubject")) {
3271 PrintFatalError(Subject.getLoc(),
3272 "SubsetSubjects within SubsetSubjects is not supported");
3273 return "";
3274 }
3275
3276 OS << "static bool " << FnName << "(const Decl *D) {\n";
3277 OS << " if (const auto *S = dyn_cast<";
3278 OS << GetSubjectWithSuffix(Base);
3279 OS << ">(D))\n";
3280 OS << " return " << Subject.getValueAsString("CheckCode") << ";\n";
3281 OS << " return false;\n";
3282 OS << "}\n\n";
3283
3284 CustomSubjectSet.insert(FnName);
3285 return FnName;
3286 }
3287
GenerateAppertainsTo(const Record & Attr,raw_ostream & OS)3288 static std::string GenerateAppertainsTo(const Record &Attr, raw_ostream &OS) {
3289 // If the attribute does not contain a Subjects definition, then use the
3290 // default appertainsTo logic.
3291 if (Attr.isValueUnset("Subjects"))
3292 return "defaultAppertainsTo";
3293
3294 const Record *SubjectObj = Attr.getValueAsDef("Subjects");
3295 std::vector<Record*> Subjects = SubjectObj->getValueAsListOfDefs("Subjects");
3296
3297 // If the list of subjects is empty, it is assumed that the attribute
3298 // appertains to everything.
3299 if (Subjects.empty())
3300 return "defaultAppertainsTo";
3301
3302 bool Warn = SubjectObj->getValueAsDef("Diag")->getValueAsBit("Warn");
3303
3304 // Otherwise, generate an appertainsTo check specific to this attribute which
3305 // checks all of the given subjects against the Decl passed in. Return the
3306 // name of that check to the caller.
3307 //
3308 // If D is null, that means the attribute was not applied to a declaration
3309 // at all (for instance because it was applied to a type), or that the caller
3310 // has determined that the check should fail (perhaps prior to the creation
3311 // of the declaration).
3312 std::string FnName = "check" + Attr.getName().str() + "AppertainsTo";
3313 std::stringstream SS;
3314 SS << "static bool " << FnName << "(Sema &S, const ParsedAttr &Attr, ";
3315 SS << "const Decl *D) {\n";
3316 SS << " if (!D || (";
3317 for (auto I = Subjects.begin(), E = Subjects.end(); I != E; ++I) {
3318 // If the subject has custom code associated with it, generate a function
3319 // for it. The function cannot be inlined into this check (yet) because it
3320 // requires the subject to be of a specific type, and were that information
3321 // inlined here, it would not support an attribute with multiple custom
3322 // subjects.
3323 if ((*I)->isSubClassOf("SubsetSubject")) {
3324 SS << "!" << GenerateCustomAppertainsTo(**I, OS) << "(D)";
3325 } else {
3326 SS << "!isa<" << GetSubjectWithSuffix(*I) << ">(D)";
3327 }
3328
3329 if (I + 1 != E)
3330 SS << " && ";
3331 }
3332 SS << ")) {\n";
3333 SS << " S.Diag(Attr.getLoc(), diag::";
3334 SS << (Warn ? "warn_attribute_wrong_decl_type_str" :
3335 "err_attribute_wrong_decl_type_str");
3336 SS << ")\n";
3337 SS << " << Attr << ";
3338 SS << CalculateDiagnostic(*SubjectObj) << ";\n";
3339 SS << " return false;\n";
3340 SS << " }\n";
3341 SS << " return true;\n";
3342 SS << "}\n\n";
3343
3344 OS << SS.str();
3345 return FnName;
3346 }
3347
3348 static void
emitAttributeMatchRules(PragmaClangAttributeSupport & PragmaAttributeSupport,raw_ostream & OS)3349 emitAttributeMatchRules(PragmaClangAttributeSupport &PragmaAttributeSupport,
3350 raw_ostream &OS) {
3351 OS << "static bool checkAttributeMatchRuleAppliesTo(const Decl *D, "
3352 << AttributeSubjectMatchRule::EnumName << " rule) {\n";
3353 OS << " switch (rule) {\n";
3354 for (const auto &Rule : PragmaAttributeSupport.Rules) {
3355 if (Rule.isAbstractRule()) {
3356 OS << " case " << Rule.getEnumValue() << ":\n";
3357 OS << " assert(false && \"Abstract matcher rule isn't allowed\");\n";
3358 OS << " return false;\n";
3359 continue;
3360 }
3361 std::vector<Record *> Subjects = Rule.getSubjects();
3362 assert(!Subjects.empty() && "Missing subjects");
3363 OS << " case " << Rule.getEnumValue() << ":\n";
3364 OS << " return ";
3365 for (auto I = Subjects.begin(), E = Subjects.end(); I != E; ++I) {
3366 // If the subject has custom code associated with it, use the function
3367 // that was generated for GenerateAppertainsTo to check if the declaration
3368 // is valid.
3369 if ((*I)->isSubClassOf("SubsetSubject"))
3370 OS << functionNameForCustomAppertainsTo(**I) << "(D)";
3371 else
3372 OS << "isa<" << GetSubjectWithSuffix(*I) << ">(D)";
3373
3374 if (I + 1 != E)
3375 OS << " || ";
3376 }
3377 OS << ";\n";
3378 }
3379 OS << " }\n";
3380 OS << " llvm_unreachable(\"Invalid match rule\");\nreturn false;\n";
3381 OS << "}\n\n";
3382 }
3383
GenerateDefaultLangOptRequirements(raw_ostream & OS)3384 static void GenerateDefaultLangOptRequirements(raw_ostream &OS) {
3385 OS << "static bool defaultDiagnoseLangOpts(Sema &, ";
3386 OS << "const ParsedAttr &) {\n";
3387 OS << " return true;\n";
3388 OS << "}\n\n";
3389 }
3390
GenerateLangOptRequirements(const Record & R,raw_ostream & OS)3391 static std::string GenerateLangOptRequirements(const Record &R,
3392 raw_ostream &OS) {
3393 // If the attribute has an empty or unset list of language requirements,
3394 // return the default handler.
3395 std::vector<Record *> LangOpts = R.getValueAsListOfDefs("LangOpts");
3396 if (LangOpts.empty())
3397 return "defaultDiagnoseLangOpts";
3398
3399 // Generate the test condition, as well as a unique function name for the
3400 // diagnostic test. The list of options should usually be short (one or two
3401 // options), and the uniqueness isn't strictly necessary (it is just for
3402 // codegen efficiency).
3403 std::string FnName = "check", Test;
3404 for (auto I = LangOpts.begin(), E = LangOpts.end(); I != E; ++I) {
3405 const StringRef Part = (*I)->getValueAsString("Name");
3406 if ((*I)->getValueAsBit("Negated")) {
3407 FnName += "Not";
3408 Test += "!";
3409 }
3410 Test += "S.LangOpts.";
3411 Test += Part;
3412 if (I + 1 != E)
3413 Test += " || ";
3414 FnName += Part;
3415 }
3416 FnName += "LangOpts";
3417
3418 // If this code has already been generated, simply return the previous
3419 // instance of it.
3420 static std::set<std::string> CustomLangOptsSet;
3421 auto I = CustomLangOptsSet.find(FnName);
3422 if (I != CustomLangOptsSet.end())
3423 return *I;
3424
3425 OS << "static bool " << FnName << "(Sema &S, const ParsedAttr &Attr) {\n";
3426 OS << " if (" << Test << ")\n";
3427 OS << " return true;\n\n";
3428 OS << " S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) ";
3429 OS << "<< Attr.getName();\n";
3430 OS << " return false;\n";
3431 OS << "}\n\n";
3432
3433 CustomLangOptsSet.insert(FnName);
3434 return FnName;
3435 }
3436
GenerateDefaultTargetRequirements(raw_ostream & OS)3437 static void GenerateDefaultTargetRequirements(raw_ostream &OS) {
3438 OS << "static bool defaultTargetRequirements(const TargetInfo &) {\n";
3439 OS << " return true;\n";
3440 OS << "}\n\n";
3441 }
3442
GenerateTargetRequirements(const Record & Attr,const ParsedAttrMap & Dupes,raw_ostream & OS)3443 static std::string GenerateTargetRequirements(const Record &Attr,
3444 const ParsedAttrMap &Dupes,
3445 raw_ostream &OS) {
3446 // If the attribute is not a target specific attribute, return the default
3447 // target handler.
3448 if (!Attr.isSubClassOf("TargetSpecificAttr"))
3449 return "defaultTargetRequirements";
3450
3451 // Get the list of architectures to be tested for.
3452 const Record *R = Attr.getValueAsDef("Target");
3453 std::vector<StringRef> Arches = R->getValueAsListOfStrings("Arches");
3454
3455 // If there are other attributes which share the same parsed attribute kind,
3456 // such as target-specific attributes with a shared spelling, collapse the
3457 // duplicate architectures. This is required because a shared target-specific
3458 // attribute has only one ParsedAttr::Kind enumeration value, but it
3459 // applies to multiple target architectures. In order for the attribute to be
3460 // considered valid, all of its architectures need to be included.
3461 if (!Attr.isValueUnset("ParseKind")) {
3462 const StringRef APK = Attr.getValueAsString("ParseKind");
3463 for (const auto &I : Dupes) {
3464 if (I.first == APK) {
3465 std::vector<StringRef> DA =
3466 I.second->getValueAsDef("Target")->getValueAsListOfStrings(
3467 "Arches");
3468 Arches.insert(Arches.end(), DA.begin(), DA.end());
3469 }
3470 }
3471 }
3472
3473 std::string FnName = "isTarget";
3474 std::string Test;
3475 GenerateTargetSpecificAttrChecks(R, Arches, Test, &FnName);
3476
3477 // If this code has already been generated, simply return the previous
3478 // instance of it.
3479 static std::set<std::string> CustomTargetSet;
3480 auto I = CustomTargetSet.find(FnName);
3481 if (I != CustomTargetSet.end())
3482 return *I;
3483
3484 OS << "static bool " << FnName << "(const TargetInfo &Target) {\n";
3485 OS << " const llvm::Triple &T = Target.getTriple();\n";
3486 OS << " return " << Test << ";\n";
3487 OS << "}\n\n";
3488
3489 CustomTargetSet.insert(FnName);
3490 return FnName;
3491 }
3492
GenerateDefaultSpellingIndexToSemanticSpelling(raw_ostream & OS)3493 static void GenerateDefaultSpellingIndexToSemanticSpelling(raw_ostream &OS) {
3494 OS << "static unsigned defaultSpellingIndexToSemanticSpelling("
3495 << "const ParsedAttr &Attr) {\n";
3496 OS << " return UINT_MAX;\n";
3497 OS << "}\n\n";
3498 }
3499
GenerateSpellingIndexToSemanticSpelling(const Record & Attr,raw_ostream & OS)3500 static std::string GenerateSpellingIndexToSemanticSpelling(const Record &Attr,
3501 raw_ostream &OS) {
3502 // If the attribute does not have a semantic form, we can bail out early.
3503 if (!Attr.getValueAsBit("ASTNode"))
3504 return "defaultSpellingIndexToSemanticSpelling";
3505
3506 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(Attr);
3507
3508 // If there are zero or one spellings, or all of the spellings share the same
3509 // name, we can also bail out early.
3510 if (Spellings.size() <= 1 || SpellingNamesAreCommon(Spellings))
3511 return "defaultSpellingIndexToSemanticSpelling";
3512
3513 // Generate the enumeration we will use for the mapping.
3514 SemanticSpellingMap SemanticToSyntacticMap;
3515 std::string Enum = CreateSemanticSpellings(Spellings, SemanticToSyntacticMap);
3516 std::string Name = Attr.getName().str() + "AttrSpellingMap";
3517
3518 OS << "static unsigned " << Name << "(const ParsedAttr &Attr) {\n";
3519 OS << Enum;
3520 OS << " unsigned Idx = Attr.getAttributeSpellingListIndex();\n";
3521 WriteSemanticSpellingSwitch("Idx", SemanticToSyntacticMap, OS);
3522 OS << "}\n\n";
3523
3524 return Name;
3525 }
3526
IsKnownToGCC(const Record & Attr)3527 static bool IsKnownToGCC(const Record &Attr) {
3528 // Look at the spellings for this subject; if there are any spellings which
3529 // claim to be known to GCC, the attribute is known to GCC.
3530 return llvm::any_of(
3531 GetFlattenedSpellings(Attr),
3532 [](const FlattenedSpelling &S) { return S.knownToGCC(); });
3533 }
3534
3535 /// Emits the parsed attribute helpers
EmitClangAttrParsedAttrImpl(RecordKeeper & Records,raw_ostream & OS)3536 void EmitClangAttrParsedAttrImpl(RecordKeeper &Records, raw_ostream &OS) {
3537 emitSourceFileHeader("Parsed attribute helpers", OS);
3538
3539 PragmaClangAttributeSupport &PragmaAttributeSupport =
3540 getPragmaAttributeSupport(Records);
3541
3542 // Get the list of parsed attributes, and accept the optional list of
3543 // duplicates due to the ParseKind.
3544 ParsedAttrMap Dupes;
3545 ParsedAttrMap Attrs = getParsedAttrList(Records, &Dupes);
3546
3547 // Generate the default appertainsTo, target and language option diagnostic,
3548 // and spelling list index mapping methods.
3549 GenerateDefaultAppertainsTo(OS);
3550 GenerateDefaultLangOptRequirements(OS);
3551 GenerateDefaultTargetRequirements(OS);
3552 GenerateDefaultSpellingIndexToSemanticSpelling(OS);
3553
3554 // Generate the appertainsTo diagnostic methods and write their names into
3555 // another mapping. At the same time, generate the AttrInfoMap object
3556 // contents. Due to the reliance on generated code, use separate streams so
3557 // that code will not be interleaved.
3558 std::string Buffer;
3559 raw_string_ostream SS {Buffer};
3560 for (auto I = Attrs.begin(), E = Attrs.end(); I != E; ++I) {
3561 // TODO: If the attribute's kind appears in the list of duplicates, that is
3562 // because it is a target-specific attribute that appears multiple times.
3563 // It would be beneficial to test whether the duplicates are "similar
3564 // enough" to each other to not cause problems. For instance, check that
3565 // the spellings are identical, and custom parsing rules match, etc.
3566
3567 // We need to generate struct instances based off ParsedAttrInfo from
3568 // ParsedAttr.cpp.
3569 SS << " { ";
3570 emitArgInfo(*I->second, SS);
3571 SS << ", " << I->second->getValueAsBit("HasCustomParsing");
3572 SS << ", " << I->second->isSubClassOf("TargetSpecificAttr");
3573 SS << ", "
3574 << (I->second->isSubClassOf("TypeAttr") ||
3575 I->second->isSubClassOf("DeclOrTypeAttr"));
3576 SS << ", " << I->second->isSubClassOf("StmtAttr");
3577 SS << ", " << IsKnownToGCC(*I->second);
3578 SS << ", " << PragmaAttributeSupport.isAttributedSupported(*I->second);
3579 SS << ", " << GenerateAppertainsTo(*I->second, OS);
3580 SS << ", " << GenerateLangOptRequirements(*I->second, OS);
3581 SS << ", " << GenerateTargetRequirements(*I->second, Dupes, OS);
3582 SS << ", " << GenerateSpellingIndexToSemanticSpelling(*I->second, OS);
3583 SS << ", "
3584 << PragmaAttributeSupport.generateStrictConformsTo(*I->second, OS);
3585 SS << " }";
3586
3587 if (I + 1 != E)
3588 SS << ",";
3589
3590 SS << " // AT_" << I->first << "\n";
3591 }
3592
3593 OS << "static const ParsedAttrInfo AttrInfoMap[ParsedAttr::UnknownAttribute "
3594 "+ 1] = {\n";
3595 OS << SS.str();
3596 OS << "};\n\n";
3597
3598 // Generate the attribute match rules.
3599 emitAttributeMatchRules(PragmaAttributeSupport, OS);
3600 }
3601
3602 // Emits the kind list of parsed attributes
EmitClangAttrParsedAttrKinds(RecordKeeper & Records,raw_ostream & OS)3603 void EmitClangAttrParsedAttrKinds(RecordKeeper &Records, raw_ostream &OS) {
3604 emitSourceFileHeader("Attribute name matcher", OS);
3605
3606 std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
3607 std::vector<StringMatcher::StringPair> GNU, Declspec, Microsoft, CXX11,
3608 Keywords, Pragma, C2x;
3609 std::set<std::string> Seen;
3610 for (const auto *A : Attrs) {
3611 const Record &Attr = *A;
3612
3613 bool SemaHandler = Attr.getValueAsBit("SemaHandler");
3614 bool Ignored = Attr.getValueAsBit("Ignored");
3615 if (SemaHandler || Ignored) {
3616 // Attribute spellings can be shared between target-specific attributes,
3617 // and can be shared between syntaxes for the same attribute. For
3618 // instance, an attribute can be spelled GNU<"interrupt"> for an ARM-
3619 // specific attribute, or MSP430-specific attribute. Additionally, an
3620 // attribute can be spelled GNU<"dllexport"> and Declspec<"dllexport">
3621 // for the same semantic attribute. Ultimately, we need to map each of
3622 // these to a single ParsedAttr::Kind value, but the StringMatcher
3623 // class cannot handle duplicate match strings. So we generate a list of
3624 // string to match based on the syntax, and emit multiple string matchers
3625 // depending on the syntax used.
3626 std::string AttrName;
3627 if (Attr.isSubClassOf("TargetSpecificAttr") &&
3628 !Attr.isValueUnset("ParseKind")) {
3629 AttrName = Attr.getValueAsString("ParseKind");
3630 if (Seen.find(AttrName) != Seen.end())
3631 continue;
3632 Seen.insert(AttrName);
3633 } else
3634 AttrName = NormalizeAttrName(StringRef(Attr.getName())).str();
3635
3636 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(Attr);
3637 for (const auto &S : Spellings) {
3638 const std::string &RawSpelling = S.name();
3639 std::vector<StringMatcher::StringPair> *Matches = nullptr;
3640 std::string Spelling;
3641 const std::string &Variety = S.variety();
3642 if (Variety == "CXX11") {
3643 Matches = &CXX11;
3644 Spelling += S.nameSpace();
3645 Spelling += "::";
3646 } else if (Variety == "C2x") {
3647 Matches = &C2x;
3648 Spelling += S.nameSpace();
3649 Spelling += "::";
3650 } else if (Variety == "GNU")
3651 Matches = &GNU;
3652 else if (Variety == "Declspec")
3653 Matches = &Declspec;
3654 else if (Variety == "Microsoft")
3655 Matches = &Microsoft;
3656 else if (Variety == "Keyword")
3657 Matches = &Keywords;
3658 else if (Variety == "Pragma")
3659 Matches = &Pragma;
3660
3661 assert(Matches && "Unsupported spelling variety found");
3662
3663 if (Variety == "GNU")
3664 Spelling += NormalizeGNUAttrSpelling(RawSpelling);
3665 else
3666 Spelling += RawSpelling;
3667
3668 if (SemaHandler)
3669 Matches->push_back(StringMatcher::StringPair(
3670 Spelling, "return ParsedAttr::AT_" + AttrName + ";"));
3671 else
3672 Matches->push_back(StringMatcher::StringPair(
3673 Spelling, "return ParsedAttr::IgnoredAttribute;"));
3674 }
3675 }
3676 }
3677
3678 OS << "static ParsedAttr::Kind getAttrKind(StringRef Name, ";
3679 OS << "ParsedAttr::Syntax Syntax) {\n";
3680 OS << " if (ParsedAttr::AS_GNU == Syntax) {\n";
3681 StringMatcher("Name", GNU, OS).Emit();
3682 OS << " } else if (ParsedAttr::AS_Declspec == Syntax) {\n";
3683 StringMatcher("Name", Declspec, OS).Emit();
3684 OS << " } else if (ParsedAttr::AS_Microsoft == Syntax) {\n";
3685 StringMatcher("Name", Microsoft, OS).Emit();
3686 OS << " } else if (ParsedAttr::AS_CXX11 == Syntax) {\n";
3687 StringMatcher("Name", CXX11, OS).Emit();
3688 OS << " } else if (ParsedAttr::AS_C2x == Syntax) {\n";
3689 StringMatcher("Name", C2x, OS).Emit();
3690 OS << " } else if (ParsedAttr::AS_Keyword == Syntax || ";
3691 OS << "ParsedAttr::AS_ContextSensitiveKeyword == Syntax) {\n";
3692 StringMatcher("Name", Keywords, OS).Emit();
3693 OS << " } else if (ParsedAttr::AS_Pragma == Syntax) {\n";
3694 StringMatcher("Name", Pragma, OS).Emit();
3695 OS << " }\n";
3696 OS << " return ParsedAttr::UnknownAttribute;\n"
3697 << "}\n";
3698 }
3699
3700 // Emits the code to dump an attribute.
EmitClangAttrTextNodeDump(RecordKeeper & Records,raw_ostream & OS)3701 void EmitClangAttrTextNodeDump(RecordKeeper &Records, raw_ostream &OS) {
3702 emitSourceFileHeader("Attribute text node dumper", OS);
3703
3704 std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr"), Args;
3705 for (const auto *Attr : Attrs) {
3706 const Record &R = *Attr;
3707 if (!R.getValueAsBit("ASTNode"))
3708 continue;
3709
3710 // If the attribute has a semantically-meaningful name (which is determined
3711 // by whether there is a Spelling enumeration for it), then write out the
3712 // spelling used for the attribute.
3713
3714 std::string FunctionContent;
3715 llvm::raw_string_ostream SS(FunctionContent);
3716
3717 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(R);
3718 if (Spellings.size() > 1 && !SpellingNamesAreCommon(Spellings))
3719 SS << " OS << \" \" << A->getSpelling();\n";
3720
3721 Args = R.getValueAsListOfDefs("Args");
3722 for (const auto *Arg : Args)
3723 createArgument(*Arg, R.getName())->writeDump(SS);
3724
3725 if (SS.tell()) {
3726 OS << " void Visit" << R.getName() << "Attr(const " << R.getName()
3727 << "Attr *A) {\n";
3728 if (!Args.empty())
3729 OS << " const auto *SA = cast<" << R.getName()
3730 << "Attr>(A); (void)SA;\n";
3731 OS << SS.str();
3732 OS << " }\n";
3733 }
3734 }
3735 }
3736
EmitClangAttrNodeTraverse(RecordKeeper & Records,raw_ostream & OS)3737 void EmitClangAttrNodeTraverse(RecordKeeper &Records, raw_ostream &OS) {
3738 emitSourceFileHeader("Attribute text node traverser", OS);
3739
3740 std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr"), Args;
3741 for (const auto *Attr : Attrs) {
3742 const Record &R = *Attr;
3743 if (!R.getValueAsBit("ASTNode"))
3744 continue;
3745
3746 std::string FunctionContent;
3747 llvm::raw_string_ostream SS(FunctionContent);
3748
3749 Args = R.getValueAsListOfDefs("Args");
3750 for (const auto *Arg : Args)
3751 createArgument(*Arg, R.getName())->writeDumpChildren(SS);
3752 if (SS.tell()) {
3753 OS << " void Visit" << R.getName() << "Attr(const " << R.getName()
3754 << "Attr *A) {\n";
3755 if (!Args.empty())
3756 OS << " const auto *SA = cast<" << R.getName()
3757 << "Attr>(A); (void)SA;\n";
3758 OS << SS.str();
3759 OS << " }\n";
3760 }
3761 }
3762 }
3763
EmitClangAttrParserStringSwitches(RecordKeeper & Records,raw_ostream & OS)3764 void EmitClangAttrParserStringSwitches(RecordKeeper &Records,
3765 raw_ostream &OS) {
3766 emitSourceFileHeader("Parser-related llvm::StringSwitch cases", OS);
3767 emitClangAttrArgContextList(Records, OS);
3768 emitClangAttrIdentifierArgList(Records, OS);
3769 emitClangAttrVariadicIdentifierArgList(Records, OS);
3770 emitClangAttrTypeArgList(Records, OS);
3771 emitClangAttrLateParsedList(Records, OS);
3772 }
3773
EmitClangAttrSubjectMatchRulesParserStringSwitches(RecordKeeper & Records,raw_ostream & OS)3774 void EmitClangAttrSubjectMatchRulesParserStringSwitches(RecordKeeper &Records,
3775 raw_ostream &OS) {
3776 getPragmaAttributeSupport(Records).generateParsingHelpers(OS);
3777 }
3778
3779 enum class SpellingKind {
3780 GNU,
3781 CXX11,
3782 C2x,
3783 Declspec,
3784 Microsoft,
3785 Keyword,
3786 Pragma,
3787 };
3788 static const size_t NumSpellingKinds = (size_t)SpellingKind::Pragma + 1;
3789
3790 class SpellingList {
3791 std::vector<std::string> Spellings[NumSpellingKinds];
3792
3793 public:
operator [](SpellingKind K) const3794 ArrayRef<std::string> operator[](SpellingKind K) const {
3795 return Spellings[(size_t)K];
3796 }
3797
add(const Record & Attr,FlattenedSpelling Spelling)3798 void add(const Record &Attr, FlattenedSpelling Spelling) {
3799 SpellingKind Kind = StringSwitch<SpellingKind>(Spelling.variety())
3800 .Case("GNU", SpellingKind::GNU)
3801 .Case("CXX11", SpellingKind::CXX11)
3802 .Case("C2x", SpellingKind::C2x)
3803 .Case("Declspec", SpellingKind::Declspec)
3804 .Case("Microsoft", SpellingKind::Microsoft)
3805 .Case("Keyword", SpellingKind::Keyword)
3806 .Case("Pragma", SpellingKind::Pragma);
3807 std::string Name;
3808 if (!Spelling.nameSpace().empty()) {
3809 switch (Kind) {
3810 case SpellingKind::CXX11:
3811 case SpellingKind::C2x:
3812 Name = Spelling.nameSpace() + "::";
3813 break;
3814 case SpellingKind::Pragma:
3815 Name = Spelling.nameSpace() + " ";
3816 break;
3817 default:
3818 PrintFatalError(Attr.getLoc(), "Unexpected namespace in spelling");
3819 }
3820 }
3821 Name += Spelling.name();
3822
3823 Spellings[(size_t)Kind].push_back(Name);
3824 }
3825 };
3826
3827 class DocumentationData {
3828 public:
3829 const Record *Documentation;
3830 const Record *Attribute;
3831 std::string Heading;
3832 SpellingList SupportedSpellings;
3833
DocumentationData(const Record & Documentation,const Record & Attribute,std::pair<std::string,SpellingList> HeadingAndSpellings)3834 DocumentationData(const Record &Documentation, const Record &Attribute,
3835 std::pair<std::string, SpellingList> HeadingAndSpellings)
3836 : Documentation(&Documentation), Attribute(&Attribute),
3837 Heading(std::move(HeadingAndSpellings.first)),
3838 SupportedSpellings(std::move(HeadingAndSpellings.second)) {}
3839 };
3840
WriteCategoryHeader(const Record * DocCategory,raw_ostream & OS)3841 static void WriteCategoryHeader(const Record *DocCategory,
3842 raw_ostream &OS) {
3843 const StringRef Name = DocCategory->getValueAsString("Name");
3844 OS << Name << "\n" << std::string(Name.size(), '=') << "\n";
3845
3846 // If there is content, print that as well.
3847 const StringRef ContentStr = DocCategory->getValueAsString("Content");
3848 // Trim leading and trailing newlines and spaces.
3849 OS << ContentStr.trim();
3850
3851 OS << "\n\n";
3852 }
3853
3854 static std::pair<std::string, SpellingList>
GetAttributeHeadingAndSpellings(const Record & Documentation,const Record & Attribute)3855 GetAttributeHeadingAndSpellings(const Record &Documentation,
3856 const Record &Attribute) {
3857 // FIXME: there is no way to have a per-spelling category for the attribute
3858 // documentation. This may not be a limiting factor since the spellings
3859 // should generally be consistently applied across the category.
3860
3861 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(Attribute);
3862 if (Spellings.empty())
3863 PrintFatalError(Attribute.getLoc(),
3864 "Attribute has no supported spellings; cannot be "
3865 "documented");
3866
3867 // Determine the heading to be used for this attribute.
3868 std::string Heading = Documentation.getValueAsString("Heading");
3869 if (Heading.empty()) {
3870 // If there's only one spelling, we can simply use that.
3871 if (Spellings.size() == 1)
3872 Heading = Spellings.begin()->name();
3873 else {
3874 std::set<std::string> Uniques;
3875 for (auto I = Spellings.begin(), E = Spellings.end();
3876 I != E && Uniques.size() <= 1; ++I) {
3877 std::string Spelling = NormalizeNameForSpellingComparison(I->name());
3878 Uniques.insert(Spelling);
3879 }
3880 // If the semantic map has only one spelling, that is sufficient for our
3881 // needs.
3882 if (Uniques.size() == 1)
3883 Heading = *Uniques.begin();
3884 }
3885 }
3886
3887 // If the heading is still empty, it is an error.
3888 if (Heading.empty())
3889 PrintFatalError(Attribute.getLoc(),
3890 "This attribute requires a heading to be specified");
3891
3892 SpellingList SupportedSpellings;
3893 for (const auto &I : Spellings)
3894 SupportedSpellings.add(Attribute, I);
3895
3896 return std::make_pair(std::move(Heading), std::move(SupportedSpellings));
3897 }
3898
WriteDocumentation(RecordKeeper & Records,const DocumentationData & Doc,raw_ostream & OS)3899 static void WriteDocumentation(RecordKeeper &Records,
3900 const DocumentationData &Doc, raw_ostream &OS) {
3901 OS << Doc.Heading << "\n" << std::string(Doc.Heading.length(), '-') << "\n";
3902
3903 // List what spelling syntaxes the attribute supports.
3904 OS << ".. csv-table:: Supported Syntaxes\n";
3905 OS << " :header: \"GNU\", \"C++11\", \"C2x\", \"``__declspec``\",";
3906 OS << " \"Keyword\", \"``#pragma``\", \"``#pragma clang attribute``\"\n\n";
3907 OS << " \"";
3908 for (size_t Kind = 0; Kind != NumSpellingKinds; ++Kind) {
3909 SpellingKind K = (SpellingKind)Kind;
3910 // TODO: List Microsoft (IDL-style attribute) spellings once we fully
3911 // support them.
3912 if (K == SpellingKind::Microsoft)
3913 continue;
3914
3915 bool PrintedAny = false;
3916 for (StringRef Spelling : Doc.SupportedSpellings[K]) {
3917 if (PrintedAny)
3918 OS << " |br| ";
3919 OS << "``" << Spelling << "``";
3920 PrintedAny = true;
3921 }
3922
3923 OS << "\",\"";
3924 }
3925
3926 if (getPragmaAttributeSupport(Records).isAttributedSupported(
3927 *Doc.Attribute))
3928 OS << "Yes";
3929 OS << "\"\n\n";
3930
3931 // If the attribute is deprecated, print a message about it, and possibly
3932 // provide a replacement attribute.
3933 if (!Doc.Documentation->isValueUnset("Deprecated")) {
3934 OS << "This attribute has been deprecated, and may be removed in a future "
3935 << "version of Clang.";
3936 const Record &Deprecated = *Doc.Documentation->getValueAsDef("Deprecated");
3937 const StringRef Replacement = Deprecated.getValueAsString("Replacement");
3938 if (!Replacement.empty())
3939 OS << " This attribute has been superseded by ``" << Replacement
3940 << "``.";
3941 OS << "\n\n";
3942 }
3943
3944 const StringRef ContentStr = Doc.Documentation->getValueAsString("Content");
3945 // Trim leading and trailing newlines and spaces.
3946 OS << ContentStr.trim();
3947
3948 OS << "\n\n\n";
3949 }
3950
EmitClangAttrDocs(RecordKeeper & Records,raw_ostream & OS)3951 void EmitClangAttrDocs(RecordKeeper &Records, raw_ostream &OS) {
3952 // Get the documentation introduction paragraph.
3953 const Record *Documentation = Records.getDef("GlobalDocumentation");
3954 if (!Documentation) {
3955 PrintFatalError("The Documentation top-level definition is missing, "
3956 "no documentation will be generated.");
3957 return;
3958 }
3959
3960 OS << Documentation->getValueAsString("Intro") << "\n";
3961
3962 // Gather the Documentation lists from each of the attributes, based on the
3963 // category provided.
3964 std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
3965 std::map<const Record *, std::vector<DocumentationData>> SplitDocs;
3966 for (const auto *A : Attrs) {
3967 const Record &Attr = *A;
3968 std::vector<Record *> Docs = Attr.getValueAsListOfDefs("Documentation");
3969 for (const auto *D : Docs) {
3970 const Record &Doc = *D;
3971 const Record *Category = Doc.getValueAsDef("Category");
3972 // If the category is "undocumented", then there cannot be any other
3973 // documentation categories (otherwise, the attribute would become
3974 // documented).
3975 const StringRef Cat = Category->getValueAsString("Name");
3976 bool Undocumented = Cat == "Undocumented";
3977 if (Undocumented && Docs.size() > 1)
3978 PrintFatalError(Doc.getLoc(),
3979 "Attribute is \"Undocumented\", but has multiple "
3980 "documentation categories");
3981
3982 if (!Undocumented)
3983 SplitDocs[Category].push_back(DocumentationData(
3984 Doc, Attr, GetAttributeHeadingAndSpellings(Doc, Attr)));
3985 }
3986 }
3987
3988 // Having split the attributes out based on what documentation goes where,
3989 // we can begin to generate sections of documentation.
3990 for (auto &I : SplitDocs) {
3991 WriteCategoryHeader(I.first, OS);
3992
3993 llvm::sort(I.second,
3994 [](const DocumentationData &D1, const DocumentationData &D2) {
3995 return D1.Heading < D2.Heading;
3996 });
3997
3998 // Walk over each of the attributes in the category and write out their
3999 // documentation.
4000 for (const auto &Doc : I.second)
4001 WriteDocumentation(Records, Doc, OS);
4002 }
4003 }
4004
EmitTestPragmaAttributeSupportedAttributes(RecordKeeper & Records,raw_ostream & OS)4005 void EmitTestPragmaAttributeSupportedAttributes(RecordKeeper &Records,
4006 raw_ostream &OS) {
4007 PragmaClangAttributeSupport Support = getPragmaAttributeSupport(Records);
4008 ParsedAttrMap Attrs = getParsedAttrList(Records);
4009 OS << "#pragma clang attribute supports the following attributes:\n";
4010 for (const auto &I : Attrs) {
4011 if (!Support.isAttributedSupported(*I.second))
4012 continue;
4013 OS << I.first;
4014 if (I.second->isValueUnset("Subjects")) {
4015 OS << " ()\n";
4016 continue;
4017 }
4018 const Record *SubjectObj = I.second->getValueAsDef("Subjects");
4019 std::vector<Record *> Subjects =
4020 SubjectObj->getValueAsListOfDefs("Subjects");
4021 OS << " (";
4022 for (const auto &Subject : llvm::enumerate(Subjects)) {
4023 if (Subject.index())
4024 OS << ", ";
4025 PragmaClangAttributeSupport::RuleOrAggregateRuleSet &RuleSet =
4026 Support.SubjectsToRules.find(Subject.value())->getSecond();
4027 if (RuleSet.isRule()) {
4028 OS << RuleSet.getRule().getEnumValueName();
4029 continue;
4030 }
4031 OS << "(";
4032 for (const auto &Rule : llvm::enumerate(RuleSet.getAggregateRuleSet())) {
4033 if (Rule.index())
4034 OS << ", ";
4035 OS << Rule.value().getEnumValueName();
4036 }
4037 OS << ")";
4038 }
4039 OS << ")\n";
4040 }
4041 OS << "End of supported attributes.\n";
4042 }
4043
4044 } // end namespace clang
4045