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