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