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