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