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