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