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