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