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