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 static void GenerateHasAttrSpellingStringSwitch( 1864 const std::vector<Record *> &Attrs, raw_ostream &OS, 1865 const std::string &Variety = "", const std::string &Scope = "") { 1866 for (const auto *Attr : Attrs) { 1867 // C++11-style attributes have specific version information associated with 1868 // them. If the attribute has no scope, the version information must not 1869 // have the default value (1), as that's incorrect. Instead, the unscoped 1870 // attribute version information should be taken from the SD-6 standing 1871 // document, which can be found at: 1872 // https://isocpp.org/std/standing-documents/sd-6-sg10-feature-test-recommendations 1873 int Version = 1; 1874 1875 if (Variety == "CXX11") { 1876 std::vector<Record *> Spellings = Attr->getValueAsListOfDefs("Spellings"); 1877 for (const auto &Spelling : Spellings) { 1878 if (Spelling->getValueAsString("Variety") == "CXX11") { 1879 Version = static_cast<int>(Spelling->getValueAsInt("Version")); 1880 if (Scope.empty() && Version == 1) 1881 PrintError(Spelling->getLoc(), "C++ standard attributes must " 1882 "have valid version information."); 1883 break; 1884 } 1885 } 1886 } 1887 1888 // It is assumed that there will be an llvm::Triple object named T within 1889 // scope that can be used to determine whether the attribute exists in 1890 // a given target. 1891 std::string Test; 1892 if (Attr->isSubClassOf("TargetSpecificAttr")) { 1893 const Record *R = Attr->getValueAsDef("Target"); 1894 std::vector<std::string> Arches = R->getValueAsListOfStrings("Arches"); 1895 1896 Test += "("; 1897 for (auto AI = Arches.begin(), AE = Arches.end(); AI != AE; ++AI) { 1898 std::string Part = *AI; 1899 Test += "T.getArch() == llvm::Triple::" + Part; 1900 if (AI + 1 != AE) 1901 Test += " || "; 1902 } 1903 Test += ")"; 1904 1905 std::vector<std::string> OSes; 1906 if (!R->isValueUnset("OSes")) { 1907 Test += " && ("; 1908 std::vector<std::string> OSes = R->getValueAsListOfStrings("OSes"); 1909 for (auto AI = OSes.begin(), AE = OSes.end(); AI != AE; ++AI) { 1910 std::string Part = *AI; 1911 1912 Test += "T.getOS() == llvm::Triple::" + Part; 1913 if (AI + 1 != AE) 1914 Test += " || "; 1915 } 1916 Test += ")"; 1917 } 1918 1919 // If this is the C++11 variety, also add in the LangOpts test. 1920 if (Variety == "CXX11") 1921 Test += " && LangOpts.CPlusPlus11"; 1922 } else if (Variety == "CXX11") 1923 // C++11 mode should be checked against LangOpts, which is presumed to be 1924 // present in the caller. 1925 Test = "LangOpts.CPlusPlus11"; 1926 1927 std::string TestStr = 1928 !Test.empty() ? Test + " ? " + llvm::itostr(Version) + " : 0" : "1"; 1929 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(*Attr); 1930 for (const auto &S : Spellings) 1931 if (Variety.empty() || (Variety == S.variety() && 1932 (Scope.empty() || Scope == S.nameSpace()))) 1933 OS << " .Case(\"" << S.name() << "\", " << TestStr << ")\n"; 1934 } 1935 OS << " .Default(0);\n"; 1936 } 1937 1938 // Emits the list of spellings for attributes. 1939 void EmitClangAttrHasAttrImpl(RecordKeeper &Records, raw_ostream &OS) { 1940 emitSourceFileHeader("Code to implement the __has_attribute logic", OS); 1941 1942 // Separate all of the attributes out into four group: generic, C++11, GNU, 1943 // and declspecs. Then generate a big switch statement for each of them. 1944 std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr"); 1945 std::vector<Record *> Declspec, GNU, Pragma; 1946 std::map<std::string, std::vector<Record *>> CXX; 1947 1948 // Walk over the list of all attributes, and split them out based on the 1949 // spelling variety. 1950 for (auto *R : Attrs) { 1951 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(*R); 1952 for (const auto &SI : Spellings) { 1953 std::string Variety = SI.variety(); 1954 if (Variety == "GNU") 1955 GNU.push_back(R); 1956 else if (Variety == "Declspec") 1957 Declspec.push_back(R); 1958 else if (Variety == "CXX11") 1959 CXX[SI.nameSpace()].push_back(R); 1960 else if (Variety == "Pragma") 1961 Pragma.push_back(R); 1962 } 1963 } 1964 1965 OS << "switch (Syntax) {\n"; 1966 OS << "case AttrSyntax::GNU:\n"; 1967 OS << " return llvm::StringSwitch<int>(Name)\n"; 1968 GenerateHasAttrSpellingStringSwitch(GNU, OS, "GNU"); 1969 OS << "case AttrSyntax::Declspec:\n"; 1970 OS << " return llvm::StringSwitch<int>(Name)\n"; 1971 GenerateHasAttrSpellingStringSwitch(Declspec, OS, "Declspec"); 1972 OS << "case AttrSyntax::Pragma:\n"; 1973 OS << " return llvm::StringSwitch<int>(Name)\n"; 1974 GenerateHasAttrSpellingStringSwitch(Pragma, OS, "Pragma"); 1975 OS << "case AttrSyntax::CXX: {\n"; 1976 // C++11-style attributes are further split out based on the Scope. 1977 for (std::map<std::string, std::vector<Record *>>::iterator I = CXX.begin(), 1978 E = CXX.end(); 1979 I != E; ++I) { 1980 if (I != CXX.begin()) 1981 OS << " else "; 1982 if (I->first.empty()) 1983 OS << "if (!Scope || Scope->getName() == \"\") {\n"; 1984 else 1985 OS << "if (Scope->getName() == \"" << I->first << "\") {\n"; 1986 OS << " return llvm::StringSwitch<int>(Name)\n"; 1987 GenerateHasAttrSpellingStringSwitch(I->second, OS, "CXX11", I->first); 1988 OS << "}"; 1989 } 1990 OS << "\n}\n"; 1991 OS << "}\n"; 1992 } 1993 1994 void EmitClangAttrSpellingListIndex(RecordKeeper &Records, raw_ostream &OS) { 1995 emitSourceFileHeader("Code to translate different attribute spellings " 1996 "into internal identifiers", OS); 1997 1998 OS << 1999 " switch (AttrKind) {\n" 2000 " default:\n" 2001 " llvm_unreachable(\"Unknown attribute kind!\");\n" 2002 " break;\n"; 2003 2004 ParsedAttrMap Attrs = getParsedAttrList(Records); 2005 for (const auto &I : Attrs) { 2006 const Record &R = *I.second; 2007 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(R); 2008 OS << " case AT_" << I.first << ": {\n"; 2009 for (unsigned I = 0; I < Spellings.size(); ++ I) { 2010 OS << " if (Name == \"" << Spellings[I].name() << "\" && " 2011 << "SyntaxUsed == " 2012 << StringSwitch<unsigned>(Spellings[I].variety()) 2013 .Case("GNU", 0) 2014 .Case("CXX11", 1) 2015 .Case("Declspec", 2) 2016 .Case("Keyword", 3) 2017 .Case("Pragma", 4) 2018 .Default(0) 2019 << " && Scope == \"" << Spellings[I].nameSpace() << "\")\n" 2020 << " return " << I << ";\n"; 2021 } 2022 2023 OS << " break;\n"; 2024 OS << " }\n"; 2025 } 2026 2027 OS << " }\n"; 2028 OS << " return 0;\n"; 2029 } 2030 2031 // Emits code used by RecursiveASTVisitor to visit attributes 2032 void EmitClangAttrASTVisitor(RecordKeeper &Records, raw_ostream &OS) { 2033 emitSourceFileHeader("Used by RecursiveASTVisitor to visit attributes.", OS); 2034 2035 std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr"); 2036 2037 // Write method declarations for Traverse* methods. 2038 // We emit this here because we only generate methods for attributes that 2039 // are declared as ASTNodes. 2040 OS << "#ifdef ATTR_VISITOR_DECLS_ONLY\n\n"; 2041 for (const auto *Attr : Attrs) { 2042 const Record &R = *Attr; 2043 if (!R.getValueAsBit("ASTNode")) 2044 continue; 2045 OS << " bool Traverse" 2046 << R.getName() << "Attr(" << R.getName() << "Attr *A);\n"; 2047 OS << " bool Visit" 2048 << R.getName() << "Attr(" << R.getName() << "Attr *A) {\n" 2049 << " return true; \n" 2050 << " };\n"; 2051 } 2052 OS << "\n#else // ATTR_VISITOR_DECLS_ONLY\n\n"; 2053 2054 // Write individual Traverse* methods for each attribute class. 2055 for (const auto *Attr : Attrs) { 2056 const Record &R = *Attr; 2057 if (!R.getValueAsBit("ASTNode")) 2058 continue; 2059 2060 OS << "template <typename Derived>\n" 2061 << "bool VISITORCLASS<Derived>::Traverse" 2062 << R.getName() << "Attr(" << R.getName() << "Attr *A) {\n" 2063 << " if (!getDerived().VisitAttr(A))\n" 2064 << " return false;\n" 2065 << " if (!getDerived().Visit" << R.getName() << "Attr(A))\n" 2066 << " return false;\n"; 2067 2068 std::vector<Record*> ArgRecords = R.getValueAsListOfDefs("Args"); 2069 for (const auto *Arg : ArgRecords) 2070 createArgument(*Arg, R.getName())->writeASTVisitorTraversal(OS); 2071 2072 OS << " return true;\n"; 2073 OS << "}\n\n"; 2074 } 2075 2076 // Write generic Traverse routine 2077 OS << "template <typename Derived>\n" 2078 << "bool VISITORCLASS<Derived>::TraverseAttr(Attr *A) {\n" 2079 << " if (!A)\n" 2080 << " return true;\n" 2081 << "\n" 2082 << " switch (A->getKind()) {\n" 2083 << " default:\n" 2084 << " return true;\n"; 2085 2086 for (const auto *Attr : Attrs) { 2087 const Record &R = *Attr; 2088 if (!R.getValueAsBit("ASTNode")) 2089 continue; 2090 2091 OS << " case attr::" << R.getName() << ":\n" 2092 << " return getDerived().Traverse" << R.getName() << "Attr(" 2093 << "cast<" << R.getName() << "Attr>(A));\n"; 2094 } 2095 OS << " }\n"; // end case 2096 OS << "}\n"; // end function 2097 OS << "#endif // ATTR_VISITOR_DECLS_ONLY\n"; 2098 } 2099 2100 // Emits code to instantiate dependent attributes on templates. 2101 void EmitClangAttrTemplateInstantiate(RecordKeeper &Records, raw_ostream &OS) { 2102 emitSourceFileHeader("Template instantiation code for attributes", OS); 2103 2104 std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr"); 2105 2106 OS << "namespace clang {\n" 2107 << "namespace sema {\n\n" 2108 << "Attr *instantiateTemplateAttribute(const Attr *At, ASTContext &C, " 2109 << "Sema &S,\n" 2110 << " const MultiLevelTemplateArgumentList &TemplateArgs) {\n" 2111 << " switch (At->getKind()) {\n" 2112 << " default:\n" 2113 << " break;\n"; 2114 2115 for (const auto *Attr : Attrs) { 2116 const Record &R = *Attr; 2117 if (!R.getValueAsBit("ASTNode")) 2118 continue; 2119 2120 OS << " case attr::" << R.getName() << ": {\n"; 2121 bool ShouldClone = R.getValueAsBit("Clone"); 2122 2123 if (!ShouldClone) { 2124 OS << " return NULL;\n"; 2125 OS << " }\n"; 2126 continue; 2127 } 2128 2129 OS << " const " << R.getName() << "Attr *A = cast<" 2130 << R.getName() << "Attr>(At);\n"; 2131 bool TDependent = R.getValueAsBit("TemplateDependent"); 2132 2133 if (!TDependent) { 2134 OS << " return A->clone(C);\n"; 2135 OS << " }\n"; 2136 continue; 2137 } 2138 2139 std::vector<Record*> ArgRecords = R.getValueAsListOfDefs("Args"); 2140 std::vector<std::unique_ptr<Argument>> Args; 2141 Args.reserve(ArgRecords.size()); 2142 2143 for (const auto *ArgRecord : ArgRecords) 2144 Args.emplace_back(createArgument(*ArgRecord, R.getName())); 2145 2146 for (auto const &ai : Args) 2147 ai->writeTemplateInstantiation(OS); 2148 2149 OS << " return new (C) " << R.getName() << "Attr(A->getLocation(), C"; 2150 for (auto const &ai : Args) { 2151 OS << ", "; 2152 ai->writeTemplateInstantiationArgs(OS); 2153 } 2154 OS << ", A->getSpellingListIndex());\n }\n"; 2155 } 2156 OS << " } // end switch\n" 2157 << " llvm_unreachable(\"Unknown attribute!\");\n" 2158 << " return 0;\n" 2159 << "}\n\n" 2160 << "} // end namespace sema\n" 2161 << "} // end namespace clang\n"; 2162 } 2163 2164 // Emits the list of parsed attributes. 2165 void EmitClangAttrParsedAttrList(RecordKeeper &Records, raw_ostream &OS) { 2166 emitSourceFileHeader("List of all attributes that Clang recognizes", OS); 2167 2168 OS << "#ifndef PARSED_ATTR\n"; 2169 OS << "#define PARSED_ATTR(NAME) NAME\n"; 2170 OS << "#endif\n\n"; 2171 2172 ParsedAttrMap Names = getParsedAttrList(Records); 2173 for (const auto &I : Names) { 2174 OS << "PARSED_ATTR(" << I.first << ")\n"; 2175 } 2176 } 2177 2178 static bool isArgVariadic(const Record &R, StringRef AttrName) { 2179 return createArgument(R, AttrName)->isVariadic(); 2180 } 2181 2182 static void emitArgInfo(const Record &R, std::stringstream &OS) { 2183 // This function will count the number of arguments specified for the 2184 // attribute and emit the number of required arguments followed by the 2185 // number of optional arguments. 2186 std::vector<Record *> Args = R.getValueAsListOfDefs("Args"); 2187 unsigned ArgCount = 0, OptCount = 0; 2188 bool HasVariadic = false; 2189 for (const auto *Arg : Args) { 2190 Arg->getValueAsBit("Optional") ? ++OptCount : ++ArgCount; 2191 if (!HasVariadic && isArgVariadic(*Arg, R.getName())) 2192 HasVariadic = true; 2193 } 2194 2195 // If there is a variadic argument, we will set the optional argument count 2196 // to its largest value. Since it's currently a 4-bit number, we set it to 15. 2197 OS << ArgCount << ", " << (HasVariadic ? 15 : OptCount); 2198 } 2199 2200 static void GenerateDefaultAppertainsTo(raw_ostream &OS) { 2201 OS << "static bool defaultAppertainsTo(Sema &, const AttributeList &,"; 2202 OS << "const Decl *) {\n"; 2203 OS << " return true;\n"; 2204 OS << "}\n\n"; 2205 } 2206 2207 static std::string CalculateDiagnostic(const Record &S) { 2208 // If the SubjectList object has a custom diagnostic associated with it, 2209 // return that directly. 2210 std::string CustomDiag = S.getValueAsString("CustomDiag"); 2211 if (!CustomDiag.empty()) 2212 return CustomDiag; 2213 2214 // Given the list of subjects, determine what diagnostic best fits. 2215 enum { 2216 Func = 1U << 0, 2217 Var = 1U << 1, 2218 ObjCMethod = 1U << 2, 2219 Param = 1U << 3, 2220 Class = 1U << 4, 2221 GenericRecord = 1U << 5, 2222 Type = 1U << 6, 2223 ObjCIVar = 1U << 7, 2224 ObjCProp = 1U << 8, 2225 ObjCInterface = 1U << 9, 2226 Block = 1U << 10, 2227 Namespace = 1U << 11, 2228 Field = 1U << 12, 2229 CXXMethod = 1U << 13, 2230 ObjCProtocol = 1U << 14, 2231 Enum = 1U << 15 2232 }; 2233 uint32_t SubMask = 0; 2234 2235 std::vector<Record *> Subjects = S.getValueAsListOfDefs("Subjects"); 2236 for (const auto *Subject : Subjects) { 2237 const Record &R = *Subject; 2238 std::string Name; 2239 2240 if (R.isSubClassOf("SubsetSubject")) { 2241 PrintError(R.getLoc(), "SubsetSubjects should use a custom diagnostic"); 2242 // As a fallback, look through the SubsetSubject to see what its base 2243 // type is, and use that. This needs to be updated if SubsetSubjects 2244 // are allowed within other SubsetSubjects. 2245 Name = R.getValueAsDef("Base")->getName(); 2246 } else 2247 Name = R.getName(); 2248 2249 uint32_t V = StringSwitch<uint32_t>(Name) 2250 .Case("Function", Func) 2251 .Case("Var", Var) 2252 .Case("ObjCMethod", ObjCMethod) 2253 .Case("ParmVar", Param) 2254 .Case("TypedefName", Type) 2255 .Case("ObjCIvar", ObjCIVar) 2256 .Case("ObjCProperty", ObjCProp) 2257 .Case("Record", GenericRecord) 2258 .Case("ObjCInterface", ObjCInterface) 2259 .Case("ObjCProtocol", ObjCProtocol) 2260 .Case("Block", Block) 2261 .Case("CXXRecord", Class) 2262 .Case("Namespace", Namespace) 2263 .Case("Field", Field) 2264 .Case("CXXMethod", CXXMethod) 2265 .Case("Enum", Enum) 2266 .Default(0); 2267 if (!V) { 2268 // Something wasn't in our mapping, so be helpful and let the developer 2269 // know about it. 2270 PrintFatalError(R.getLoc(), "Unknown subject type: " + R.getName()); 2271 return ""; 2272 } 2273 2274 SubMask |= V; 2275 } 2276 2277 switch (SubMask) { 2278 // For the simple cases where there's only a single entry in the mask, we 2279 // don't have to resort to bit fiddling. 2280 case Func: return "ExpectedFunction"; 2281 case Var: return "ExpectedVariable"; 2282 case Param: return "ExpectedParameter"; 2283 case Class: return "ExpectedClass"; 2284 case Enum: return "ExpectedEnum"; 2285 case CXXMethod: 2286 // FIXME: Currently, this maps to ExpectedMethod based on existing code, 2287 // but should map to something a bit more accurate at some point. 2288 case ObjCMethod: return "ExpectedMethod"; 2289 case Type: return "ExpectedType"; 2290 case ObjCInterface: return "ExpectedObjectiveCInterface"; 2291 case ObjCProtocol: return "ExpectedObjectiveCProtocol"; 2292 2293 // "GenericRecord" means struct, union or class; check the language options 2294 // and if not compiling for C++, strip off the class part. Note that this 2295 // relies on the fact that the context for this declares "Sema &S". 2296 case GenericRecord: 2297 return "(S.getLangOpts().CPlusPlus ? ExpectedStructOrUnionOrClass : " 2298 "ExpectedStructOrUnion)"; 2299 case Func | ObjCMethod | Block: return "ExpectedFunctionMethodOrBlock"; 2300 case Func | ObjCMethod | Class: return "ExpectedFunctionMethodOrClass"; 2301 case Func | Param: 2302 case Func | ObjCMethod | Param: return "ExpectedFunctionMethodOrParameter"; 2303 case Func | ObjCMethod: return "ExpectedFunctionOrMethod"; 2304 case Func | Var: return "ExpectedVariableOrFunction"; 2305 2306 // If not compiling for C++, the class portion does not apply. 2307 case Func | Var | Class: 2308 return "(S.getLangOpts().CPlusPlus ? ExpectedFunctionVariableOrClass : " 2309 "ExpectedVariableOrFunction)"; 2310 2311 case ObjCMethod | ObjCProp: return "ExpectedMethodOrProperty"; 2312 case ObjCProtocol | ObjCInterface: 2313 return "ExpectedObjectiveCInterfaceOrProtocol"; 2314 case Field | Var: return "ExpectedFieldOrGlobalVar"; 2315 } 2316 2317 PrintFatalError(S.getLoc(), 2318 "Could not deduce diagnostic argument for Attr subjects"); 2319 2320 return ""; 2321 } 2322 2323 static std::string GetSubjectWithSuffix(const Record *R) { 2324 std::string B = R->getName(); 2325 if (B == "DeclBase") 2326 return "Decl"; 2327 return B + "Decl"; 2328 } 2329 static std::string GenerateCustomAppertainsTo(const Record &Subject, 2330 raw_ostream &OS) { 2331 std::string FnName = "is" + Subject.getName(); 2332 2333 // If this code has already been generated, simply return the previous 2334 // instance of it. 2335 static std::set<std::string> CustomSubjectSet; 2336 std::set<std::string>::iterator I = CustomSubjectSet.find(FnName); 2337 if (I != CustomSubjectSet.end()) 2338 return *I; 2339 2340 Record *Base = Subject.getValueAsDef("Base"); 2341 2342 // Not currently support custom subjects within custom subjects. 2343 if (Base->isSubClassOf("SubsetSubject")) { 2344 PrintFatalError(Subject.getLoc(), 2345 "SubsetSubjects within SubsetSubjects is not supported"); 2346 return ""; 2347 } 2348 2349 OS << "static bool " << FnName << "(const Decl *D) {\n"; 2350 OS << " if (const " << GetSubjectWithSuffix(Base) << " *S = dyn_cast<"; 2351 OS << GetSubjectWithSuffix(Base); 2352 OS << ">(D))\n"; 2353 OS << " return " << Subject.getValueAsString("CheckCode") << ";\n"; 2354 OS << " return false;\n"; 2355 OS << "}\n\n"; 2356 2357 CustomSubjectSet.insert(FnName); 2358 return FnName; 2359 } 2360 2361 static std::string GenerateAppertainsTo(const Record &Attr, raw_ostream &OS) { 2362 // If the attribute does not contain a Subjects definition, then use the 2363 // default appertainsTo logic. 2364 if (Attr.isValueUnset("Subjects")) 2365 return "defaultAppertainsTo"; 2366 2367 const Record *SubjectObj = Attr.getValueAsDef("Subjects"); 2368 std::vector<Record*> Subjects = SubjectObj->getValueAsListOfDefs("Subjects"); 2369 2370 // If the list of subjects is empty, it is assumed that the attribute 2371 // appertains to everything. 2372 if (Subjects.empty()) 2373 return "defaultAppertainsTo"; 2374 2375 bool Warn = SubjectObj->getValueAsDef("Diag")->getValueAsBit("Warn"); 2376 2377 // Otherwise, generate an appertainsTo check specific to this attribute which 2378 // checks all of the given subjects against the Decl passed in. Return the 2379 // name of that check to the caller. 2380 std::string FnName = "check" + Attr.getName() + "AppertainsTo"; 2381 std::stringstream SS; 2382 SS << "static bool " << FnName << "(Sema &S, const AttributeList &Attr, "; 2383 SS << "const Decl *D) {\n"; 2384 SS << " if ("; 2385 for (auto I = Subjects.begin(), E = Subjects.end(); I != E; ++I) { 2386 // If the subject has custom code associated with it, generate a function 2387 // for it. The function cannot be inlined into this check (yet) because it 2388 // requires the subject to be of a specific type, and were that information 2389 // inlined here, it would not support an attribute with multiple custom 2390 // subjects. 2391 if ((*I)->isSubClassOf("SubsetSubject")) { 2392 SS << "!" << GenerateCustomAppertainsTo(**I, OS) << "(D)"; 2393 } else { 2394 SS << "!isa<" << GetSubjectWithSuffix(*I) << ">(D)"; 2395 } 2396 2397 if (I + 1 != E) 2398 SS << " && "; 2399 } 2400 SS << ") {\n"; 2401 SS << " S.Diag(Attr.getLoc(), diag::"; 2402 SS << (Warn ? "warn_attribute_wrong_decl_type" : 2403 "err_attribute_wrong_decl_type"); 2404 SS << ")\n"; 2405 SS << " << Attr.getName() << "; 2406 SS << CalculateDiagnostic(*SubjectObj) << ";\n"; 2407 SS << " return false;\n"; 2408 SS << " }\n"; 2409 SS << " return true;\n"; 2410 SS << "}\n\n"; 2411 2412 OS << SS.str(); 2413 return FnName; 2414 } 2415 2416 static void GenerateDefaultLangOptRequirements(raw_ostream &OS) { 2417 OS << "static bool defaultDiagnoseLangOpts(Sema &, "; 2418 OS << "const AttributeList &) {\n"; 2419 OS << " return true;\n"; 2420 OS << "}\n\n"; 2421 } 2422 2423 static std::string GenerateLangOptRequirements(const Record &R, 2424 raw_ostream &OS) { 2425 // If the attribute has an empty or unset list of language requirements, 2426 // return the default handler. 2427 std::vector<Record *> LangOpts = R.getValueAsListOfDefs("LangOpts"); 2428 if (LangOpts.empty()) 2429 return "defaultDiagnoseLangOpts"; 2430 2431 // Generate the test condition, as well as a unique function name for the 2432 // diagnostic test. The list of options should usually be short (one or two 2433 // options), and the uniqueness isn't strictly necessary (it is just for 2434 // codegen efficiency). 2435 std::string FnName = "check", Test; 2436 for (auto I = LangOpts.begin(), E = LangOpts.end(); I != E; ++I) { 2437 std::string Part = (*I)->getValueAsString("Name"); 2438 if ((*I)->getValueAsBit("Negated")) 2439 Test += "!"; 2440 Test += "S.LangOpts." + Part; 2441 if (I + 1 != E) 2442 Test += " || "; 2443 FnName += Part; 2444 } 2445 FnName += "LangOpts"; 2446 2447 // If this code has already been generated, simply return the previous 2448 // instance of it. 2449 static std::set<std::string> CustomLangOptsSet; 2450 std::set<std::string>::iterator I = CustomLangOptsSet.find(FnName); 2451 if (I != CustomLangOptsSet.end()) 2452 return *I; 2453 2454 OS << "static bool " << FnName << "(Sema &S, const AttributeList &Attr) {\n"; 2455 OS << " if (" << Test << ")\n"; 2456 OS << " return true;\n\n"; 2457 OS << " S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) "; 2458 OS << "<< Attr.getName();\n"; 2459 OS << " return false;\n"; 2460 OS << "}\n\n"; 2461 2462 CustomLangOptsSet.insert(FnName); 2463 return FnName; 2464 } 2465 2466 static void GenerateDefaultTargetRequirements(raw_ostream &OS) { 2467 OS << "static bool defaultTargetRequirements(const llvm::Triple &) {\n"; 2468 OS << " return true;\n"; 2469 OS << "}\n\n"; 2470 } 2471 2472 static std::string GenerateTargetRequirements(const Record &Attr, 2473 const ParsedAttrMap &Dupes, 2474 raw_ostream &OS) { 2475 // If the attribute is not a target specific attribute, return the default 2476 // target handler. 2477 if (!Attr.isSubClassOf("TargetSpecificAttr")) 2478 return "defaultTargetRequirements"; 2479 2480 // Get the list of architectures to be tested for. 2481 const Record *R = Attr.getValueAsDef("Target"); 2482 std::vector<std::string> Arches = R->getValueAsListOfStrings("Arches"); 2483 if (Arches.empty()) { 2484 PrintError(Attr.getLoc(), "Empty list of target architectures for a " 2485 "target-specific attr"); 2486 return "defaultTargetRequirements"; 2487 } 2488 2489 // If there are other attributes which share the same parsed attribute kind, 2490 // such as target-specific attributes with a shared spelling, collapse the 2491 // duplicate architectures. This is required because a shared target-specific 2492 // attribute has only one AttributeList::Kind enumeration value, but it 2493 // applies to multiple target architectures. In order for the attribute to be 2494 // considered valid, all of its architectures need to be included. 2495 if (!Attr.isValueUnset("ParseKind")) { 2496 std::string APK = Attr.getValueAsString("ParseKind"); 2497 for (const auto &I : Dupes) { 2498 if (I.first == APK) { 2499 std::vector<std::string> DA = I.second->getValueAsDef("Target") 2500 ->getValueAsListOfStrings("Arches"); 2501 std::copy(DA.begin(), DA.end(), std::back_inserter(Arches)); 2502 } 2503 } 2504 } 2505 2506 std::string FnName = "isTarget", Test = "("; 2507 for (auto I = Arches.begin(), E = Arches.end(); I != E; ++I) { 2508 std::string Part = *I; 2509 Test += "Arch == llvm::Triple::" + Part; 2510 if (I + 1 != E) 2511 Test += " || "; 2512 FnName += Part; 2513 } 2514 Test += ")"; 2515 2516 // If the target also requires OS testing, generate those tests as well. 2517 bool UsesOS = false; 2518 if (!R->isValueUnset("OSes")) { 2519 UsesOS = true; 2520 2521 // We know that there was at least one arch test, so we need to and in the 2522 // OS tests. 2523 Test += " && ("; 2524 std::vector<std::string> OSes = R->getValueAsListOfStrings("OSes"); 2525 for (auto I = OSes.begin(), E = OSes.end(); I != E; ++I) { 2526 std::string Part = *I; 2527 2528 Test += "OS == llvm::Triple::" + Part; 2529 if (I + 1 != E) 2530 Test += " || "; 2531 FnName += Part; 2532 } 2533 Test += ")"; 2534 } 2535 2536 // If this code has already been generated, simply return the previous 2537 // instance of it. 2538 static std::set<std::string> CustomTargetSet; 2539 std::set<std::string>::iterator I = CustomTargetSet.find(FnName); 2540 if (I != CustomTargetSet.end()) 2541 return *I; 2542 2543 OS << "static bool " << FnName << "(const llvm::Triple &T) {\n"; 2544 OS << " llvm::Triple::ArchType Arch = T.getArch();\n"; 2545 if (UsesOS) 2546 OS << " llvm::Triple::OSType OS = T.getOS();\n"; 2547 OS << " return " << Test << ";\n"; 2548 OS << "}\n\n"; 2549 2550 CustomTargetSet.insert(FnName); 2551 return FnName; 2552 } 2553 2554 static void GenerateDefaultSpellingIndexToSemanticSpelling(raw_ostream &OS) { 2555 OS << "static unsigned defaultSpellingIndexToSemanticSpelling(" 2556 << "const AttributeList &Attr) {\n"; 2557 OS << " return UINT_MAX;\n"; 2558 OS << "}\n\n"; 2559 } 2560 2561 static std::string GenerateSpellingIndexToSemanticSpelling(const Record &Attr, 2562 raw_ostream &OS) { 2563 // If the attribute does not have a semantic form, we can bail out early. 2564 if (!Attr.getValueAsBit("ASTNode")) 2565 return "defaultSpellingIndexToSemanticSpelling"; 2566 2567 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(Attr); 2568 2569 // If there are zero or one spellings, or all of the spellings share the same 2570 // name, we can also bail out early. 2571 if (Spellings.size() <= 1 || SpellingNamesAreCommon(Spellings)) 2572 return "defaultSpellingIndexToSemanticSpelling"; 2573 2574 // Generate the enumeration we will use for the mapping. 2575 SemanticSpellingMap SemanticToSyntacticMap; 2576 std::string Enum = CreateSemanticSpellings(Spellings, SemanticToSyntacticMap); 2577 std::string Name = Attr.getName() + "AttrSpellingMap"; 2578 2579 OS << "static unsigned " << Name << "(const AttributeList &Attr) {\n"; 2580 OS << Enum; 2581 OS << " unsigned Idx = Attr.getAttributeSpellingListIndex();\n"; 2582 WriteSemanticSpellingSwitch("Idx", SemanticToSyntacticMap, OS); 2583 OS << "}\n\n"; 2584 2585 return Name; 2586 } 2587 2588 static bool IsKnownToGCC(const Record &Attr) { 2589 // Look at the spellings for this subject; if there are any spellings which 2590 // claim to be known to GCC, the attribute is known to GCC. 2591 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(Attr); 2592 for (const auto &I : Spellings) { 2593 if (I.knownToGCC()) 2594 return true; 2595 } 2596 return false; 2597 } 2598 2599 /// Emits the parsed attribute helpers 2600 void EmitClangAttrParsedAttrImpl(RecordKeeper &Records, raw_ostream &OS) { 2601 emitSourceFileHeader("Parsed attribute helpers", OS); 2602 2603 // Get the list of parsed attributes, and accept the optional list of 2604 // duplicates due to the ParseKind. 2605 ParsedAttrMap Dupes; 2606 ParsedAttrMap Attrs = getParsedAttrList(Records, &Dupes); 2607 2608 // Generate the default appertainsTo, target and language option diagnostic, 2609 // and spelling list index mapping methods. 2610 GenerateDefaultAppertainsTo(OS); 2611 GenerateDefaultLangOptRequirements(OS); 2612 GenerateDefaultTargetRequirements(OS); 2613 GenerateDefaultSpellingIndexToSemanticSpelling(OS); 2614 2615 // Generate the appertainsTo diagnostic methods and write their names into 2616 // another mapping. At the same time, generate the AttrInfoMap object 2617 // contents. Due to the reliance on generated code, use separate streams so 2618 // that code will not be interleaved. 2619 std::stringstream SS; 2620 for (auto I = Attrs.begin(), E = Attrs.end(); I != E; ++I) { 2621 // TODO: If the attribute's kind appears in the list of duplicates, that is 2622 // because it is a target-specific attribute that appears multiple times. 2623 // It would be beneficial to test whether the duplicates are "similar 2624 // enough" to each other to not cause problems. For instance, check that 2625 // the spellings are identical, and custom parsing rules match, etc. 2626 2627 // We need to generate struct instances based off ParsedAttrInfo from 2628 // AttributeList.cpp. 2629 SS << " { "; 2630 emitArgInfo(*I->second, SS); 2631 SS << ", " << I->second->getValueAsBit("HasCustomParsing"); 2632 SS << ", " << I->second->isSubClassOf("TargetSpecificAttr"); 2633 SS << ", " << I->second->isSubClassOf("TypeAttr"); 2634 SS << ", " << IsKnownToGCC(*I->second); 2635 SS << ", " << GenerateAppertainsTo(*I->second, OS); 2636 SS << ", " << GenerateLangOptRequirements(*I->second, OS); 2637 SS << ", " << GenerateTargetRequirements(*I->second, Dupes, OS); 2638 SS << ", " << GenerateSpellingIndexToSemanticSpelling(*I->second, OS); 2639 SS << " }"; 2640 2641 if (I + 1 != E) 2642 SS << ","; 2643 2644 SS << " // AT_" << I->first << "\n"; 2645 } 2646 2647 OS << "static const ParsedAttrInfo AttrInfoMap[AttributeList::UnknownAttribute + 1] = {\n"; 2648 OS << SS.str(); 2649 OS << "};\n\n"; 2650 } 2651 2652 // Emits the kind list of parsed attributes 2653 void EmitClangAttrParsedAttrKinds(RecordKeeper &Records, raw_ostream &OS) { 2654 emitSourceFileHeader("Attribute name matcher", OS); 2655 2656 std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr"); 2657 std::vector<StringMatcher::StringPair> GNU, Declspec, CXX11, Keywords, Pragma; 2658 std::set<std::string> Seen; 2659 for (const auto *A : Attrs) { 2660 const Record &Attr = *A; 2661 2662 bool SemaHandler = Attr.getValueAsBit("SemaHandler"); 2663 bool Ignored = Attr.getValueAsBit("Ignored"); 2664 if (SemaHandler || Ignored) { 2665 // Attribute spellings can be shared between target-specific attributes, 2666 // and can be shared between syntaxes for the same attribute. For 2667 // instance, an attribute can be spelled GNU<"interrupt"> for an ARM- 2668 // specific attribute, or MSP430-specific attribute. Additionally, an 2669 // attribute can be spelled GNU<"dllexport"> and Declspec<"dllexport"> 2670 // for the same semantic attribute. Ultimately, we need to map each of 2671 // these to a single AttributeList::Kind value, but the StringMatcher 2672 // class cannot handle duplicate match strings. So we generate a list of 2673 // string to match based on the syntax, and emit multiple string matchers 2674 // depending on the syntax used. 2675 std::string AttrName; 2676 if (Attr.isSubClassOf("TargetSpecificAttr") && 2677 !Attr.isValueUnset("ParseKind")) { 2678 AttrName = Attr.getValueAsString("ParseKind"); 2679 if (Seen.find(AttrName) != Seen.end()) 2680 continue; 2681 Seen.insert(AttrName); 2682 } else 2683 AttrName = NormalizeAttrName(StringRef(Attr.getName())).str(); 2684 2685 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(Attr); 2686 for (const auto &S : Spellings) { 2687 std::string RawSpelling = S.name(); 2688 std::vector<StringMatcher::StringPair> *Matches = nullptr; 2689 std::string Spelling, Variety = S.variety(); 2690 if (Variety == "CXX11") { 2691 Matches = &CXX11; 2692 Spelling += S.nameSpace(); 2693 Spelling += "::"; 2694 } else if (Variety == "GNU") 2695 Matches = &GNU; 2696 else if (Variety == "Declspec") 2697 Matches = &Declspec; 2698 else if (Variety == "Keyword") 2699 Matches = &Keywords; 2700 else if (Variety == "Pragma") 2701 Matches = &Pragma; 2702 2703 assert(Matches && "Unsupported spelling variety found"); 2704 2705 Spelling += NormalizeAttrSpelling(RawSpelling); 2706 if (SemaHandler) 2707 Matches->push_back(StringMatcher::StringPair(Spelling, 2708 "return AttributeList::AT_" + AttrName + ";")); 2709 else 2710 Matches->push_back(StringMatcher::StringPair(Spelling, 2711 "return AttributeList::IgnoredAttribute;")); 2712 } 2713 } 2714 } 2715 2716 OS << "static AttributeList::Kind getAttrKind(StringRef Name, "; 2717 OS << "AttributeList::Syntax Syntax) {\n"; 2718 OS << " if (AttributeList::AS_GNU == Syntax) {\n"; 2719 StringMatcher("Name", GNU, OS).Emit(); 2720 OS << " } else if (AttributeList::AS_Declspec == Syntax) {\n"; 2721 StringMatcher("Name", Declspec, OS).Emit(); 2722 OS << " } else if (AttributeList::AS_CXX11 == Syntax) {\n"; 2723 StringMatcher("Name", CXX11, OS).Emit(); 2724 OS << " } else if (AttributeList::AS_Keyword == Syntax || "; 2725 OS << "AttributeList::AS_ContextSensitiveKeyword == Syntax) {\n"; 2726 StringMatcher("Name", Keywords, OS).Emit(); 2727 OS << " } else if (AttributeList::AS_Pragma == Syntax) {\n"; 2728 StringMatcher("Name", Pragma, OS).Emit(); 2729 OS << " }\n"; 2730 OS << " return AttributeList::UnknownAttribute;\n" 2731 << "}\n"; 2732 } 2733 2734 // Emits the code to dump an attribute. 2735 void EmitClangAttrDump(RecordKeeper &Records, raw_ostream &OS) { 2736 emitSourceFileHeader("Attribute dumper", OS); 2737 2738 OS << 2739 " switch (A->getKind()) {\n" 2740 " default:\n" 2741 " llvm_unreachable(\"Unknown attribute kind!\");\n" 2742 " break;\n"; 2743 std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr"), Args; 2744 for (const auto *Attr : Attrs) { 2745 const Record &R = *Attr; 2746 if (!R.getValueAsBit("ASTNode")) 2747 continue; 2748 OS << " case attr::" << R.getName() << ": {\n"; 2749 2750 // If the attribute has a semantically-meaningful name (which is determined 2751 // by whether there is a Spelling enumeration for it), then write out the 2752 // spelling used for the attribute. 2753 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(R); 2754 if (Spellings.size() > 1 && !SpellingNamesAreCommon(Spellings)) 2755 OS << " OS << \" \" << A->getSpelling();\n"; 2756 2757 Args = R.getValueAsListOfDefs("Args"); 2758 if (!Args.empty()) { 2759 OS << " const " << R.getName() << "Attr *SA = cast<" << R.getName() 2760 << "Attr>(A);\n"; 2761 for (const auto *Arg : Args) 2762 createArgument(*Arg, R.getName())->writeDump(OS); 2763 2764 for (auto AI = Args.begin(), AE = Args.end(); AI != AE; ++AI) 2765 createArgument(**AI, R.getName())->writeDumpChildren(OS); 2766 } 2767 OS << 2768 " break;\n" 2769 " }\n"; 2770 } 2771 OS << " }\n"; 2772 } 2773 2774 void EmitClangAttrParserStringSwitches(RecordKeeper &Records, 2775 raw_ostream &OS) { 2776 emitSourceFileHeader("Parser-related llvm::StringSwitch cases", OS); 2777 emitClangAttrArgContextList(Records, OS); 2778 emitClangAttrIdentifierArgList(Records, OS); 2779 emitClangAttrTypeArgList(Records, OS); 2780 emitClangAttrLateParsedList(Records, OS); 2781 } 2782 2783 class DocumentationData { 2784 public: 2785 const Record *Documentation; 2786 const Record *Attribute; 2787 2788 DocumentationData(const Record &Documentation, const Record &Attribute) 2789 : Documentation(&Documentation), Attribute(&Attribute) {} 2790 }; 2791 2792 static void WriteCategoryHeader(const Record *DocCategory, 2793 raw_ostream &OS) { 2794 const std::string &Name = DocCategory->getValueAsString("Name"); 2795 OS << Name << "\n" << std::string(Name.length(), '=') << "\n"; 2796 2797 // If there is content, print that as well. 2798 std::string ContentStr = DocCategory->getValueAsString("Content"); 2799 // Trim leading and trailing newlines and spaces. 2800 OS << StringRef(ContentStr).trim(); 2801 2802 OS << "\n\n"; 2803 } 2804 2805 enum SpellingKind { 2806 GNU = 1 << 0, 2807 CXX11 = 1 << 1, 2808 Declspec = 1 << 2, 2809 Keyword = 1 << 3, 2810 Pragma = 1 << 4 2811 }; 2812 2813 static void WriteDocumentation(const DocumentationData &Doc, 2814 raw_ostream &OS) { 2815 // FIXME: there is no way to have a per-spelling category for the attribute 2816 // documentation. This may not be a limiting factor since the spellings 2817 // should generally be consistently applied across the category. 2818 2819 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(*Doc.Attribute); 2820 2821 // Determine the heading to be used for this attribute. 2822 std::string Heading = Doc.Documentation->getValueAsString("Heading"); 2823 bool CustomHeading = !Heading.empty(); 2824 if (Heading.empty()) { 2825 // If there's only one spelling, we can simply use that. 2826 if (Spellings.size() == 1) 2827 Heading = Spellings.begin()->name(); 2828 else { 2829 std::set<std::string> Uniques; 2830 for (auto I = Spellings.begin(), E = Spellings.end(); 2831 I != E && Uniques.size() <= 1; ++I) { 2832 std::string Spelling = NormalizeNameForSpellingComparison(I->name()); 2833 Uniques.insert(Spelling); 2834 } 2835 // If the semantic map has only one spelling, that is sufficient for our 2836 // needs. 2837 if (Uniques.size() == 1) 2838 Heading = *Uniques.begin(); 2839 } 2840 } 2841 2842 // If the heading is still empty, it is an error. 2843 if (Heading.empty()) 2844 PrintFatalError(Doc.Attribute->getLoc(), 2845 "This attribute requires a heading to be specified"); 2846 2847 // Gather a list of unique spellings; this is not the same as the semantic 2848 // spelling for the attribute. Variations in underscores and other non- 2849 // semantic characters are still acceptable. 2850 std::vector<std::string> Names; 2851 2852 unsigned SupportedSpellings = 0; 2853 for (const auto &I : Spellings) { 2854 SpellingKind Kind = StringSwitch<SpellingKind>(I.variety()) 2855 .Case("GNU", GNU) 2856 .Case("CXX11", CXX11) 2857 .Case("Declspec", Declspec) 2858 .Case("Keyword", Keyword) 2859 .Case("Pragma", Pragma); 2860 2861 // Mask in the supported spelling. 2862 SupportedSpellings |= Kind; 2863 2864 std::string Name; 2865 if (Kind == CXX11 && !I.nameSpace().empty()) 2866 Name = I.nameSpace() + "::"; 2867 Name += I.name(); 2868 2869 // If this name is the same as the heading, do not add it. 2870 if (Name != Heading) 2871 Names.push_back(Name); 2872 } 2873 2874 // Print out the heading for the attribute. If there are alternate spellings, 2875 // then display those after the heading. 2876 if (!CustomHeading && !Names.empty()) { 2877 Heading += " ("; 2878 for (auto I = Names.begin(), E = Names.end(); I != E; ++I) { 2879 if (I != Names.begin()) 2880 Heading += ", "; 2881 Heading += *I; 2882 } 2883 Heading += ")"; 2884 } 2885 OS << Heading << "\n" << std::string(Heading.length(), '-') << "\n"; 2886 2887 if (!SupportedSpellings) 2888 PrintFatalError(Doc.Attribute->getLoc(), 2889 "Attribute has no supported spellings; cannot be " 2890 "documented"); 2891 2892 // List what spelling syntaxes the attribute supports. 2893 OS << ".. csv-table:: Supported Syntaxes\n"; 2894 OS << " :header: \"GNU\", \"C++11\", \"__declspec\", \"Keyword\","; 2895 OS << " \"Pragma\"\n\n"; 2896 OS << " \""; 2897 if (SupportedSpellings & GNU) OS << "X"; 2898 OS << "\",\""; 2899 if (SupportedSpellings & CXX11) OS << "X"; 2900 OS << "\",\""; 2901 if (SupportedSpellings & Declspec) OS << "X"; 2902 OS << "\",\""; 2903 if (SupportedSpellings & Keyword) OS << "X"; 2904 OS << "\", \""; 2905 if (SupportedSpellings & Pragma) OS << "X"; 2906 OS << "\"\n\n"; 2907 2908 // If the attribute is deprecated, print a message about it, and possibly 2909 // provide a replacement attribute. 2910 if (!Doc.Documentation->isValueUnset("Deprecated")) { 2911 OS << "This attribute has been deprecated, and may be removed in a future " 2912 << "version of Clang."; 2913 const Record &Deprecated = *Doc.Documentation->getValueAsDef("Deprecated"); 2914 std::string Replacement = Deprecated.getValueAsString("Replacement"); 2915 if (!Replacement.empty()) 2916 OS << " This attribute has been superseded by ``" 2917 << Replacement << "``."; 2918 OS << "\n\n"; 2919 } 2920 2921 std::string ContentStr = Doc.Documentation->getValueAsString("Content"); 2922 // Trim leading and trailing newlines and spaces. 2923 OS << StringRef(ContentStr).trim(); 2924 2925 OS << "\n\n\n"; 2926 } 2927 2928 void EmitClangAttrDocs(RecordKeeper &Records, raw_ostream &OS) { 2929 // Get the documentation introduction paragraph. 2930 const Record *Documentation = Records.getDef("GlobalDocumentation"); 2931 if (!Documentation) { 2932 PrintFatalError("The Documentation top-level definition is missing, " 2933 "no documentation will be generated."); 2934 return; 2935 } 2936 2937 OS << Documentation->getValueAsString("Intro") << "\n"; 2938 2939 // Gather the Documentation lists from each of the attributes, based on the 2940 // category provided. 2941 std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr"); 2942 std::map<const Record *, std::vector<DocumentationData>> SplitDocs; 2943 for (const auto *A : Attrs) { 2944 const Record &Attr = *A; 2945 std::vector<Record *> Docs = Attr.getValueAsListOfDefs("Documentation"); 2946 for (const auto *D : Docs) { 2947 const Record &Doc = *D; 2948 const Record *Category = Doc.getValueAsDef("Category"); 2949 // If the category is "undocumented", then there cannot be any other 2950 // documentation categories (otherwise, the attribute would become 2951 // documented). 2952 std::string Cat = Category->getValueAsString("Name"); 2953 bool Undocumented = Cat == "Undocumented"; 2954 if (Undocumented && Docs.size() > 1) 2955 PrintFatalError(Doc.getLoc(), 2956 "Attribute is \"Undocumented\", but has multiple " 2957 "documentation categories"); 2958 2959 if (!Undocumented) 2960 SplitDocs[Category].push_back(DocumentationData(Doc, Attr)); 2961 } 2962 } 2963 2964 // Having split the attributes out based on what documentation goes where, 2965 // we can begin to generate sections of documentation. 2966 for (const auto &I : SplitDocs) { 2967 WriteCategoryHeader(I.first, OS); 2968 2969 // Walk over each of the attributes in the category and write out their 2970 // documentation. 2971 for (const auto &Doc : I.second) 2972 WriteDocumentation(Doc, OS); 2973 } 2974 } 2975 2976 } // end namespace clang 2977