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