Guest User

Untitled

a guest
Nov 6th, 2020
25
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 189.63 KB | None | 0 0
  1. diff --git a/clang/include/clang/AST/CMakeLists.txt b/clang/include/clang/AST/CMakeLists.txt
  2. index 3a6fddb..42f100f 100644
  3. --- a/clang/include/clang/AST/CMakeLists.txt
  4. +++ b/clang/include/clang/AST/CMakeLists.txt
  5. @@ -1,75 +1,79 @@
  6. clang_tablegen(Attrs.inc -gen-clang-attr-classes
  7. SOURCE ../Basic/Attr.td
  8. TARGET ClangAttrClasses)
  9.  
  10. clang_tablegen(AttrImpl.inc -gen-clang-attr-impl
  11. SOURCE ../Basic/Attr.td
  12. TARGET ClangAttrImpl)
  13.  
  14. clang_tablegen(AttrTextNodeDump.inc -gen-clang-attr-text-node-dump
  15. SOURCE ../Basic/Attr.td
  16. TARGET ClangAttrTextDump)
  17.  
  18. +clang_tablegen(AttrJSONNodeDump.inc -gen-clang-attr-json-node-dump
  19. + SOURCE ../Basic/Attr.td
  20. + TARGET ClangAttrJSONDump)
  21. +
  22. clang_tablegen(AttrNodeTraverse.inc -gen-clang-attr-node-traverse
  23. SOURCE ../Basic/Attr.td
  24. TARGET ClangAttrTraverse)
  25.  
  26. clang_tablegen(AttrVisitor.inc -gen-clang-attr-ast-visitor
  27. SOURCE ../Basic/Attr.td
  28. TARGET ClangAttrVisitor)
  29.  
  30. clang_tablegen(StmtNodes.inc -gen-clang-stmt-nodes
  31. SOURCE ../Basic/StmtNodes.td
  32. TARGET ClangStmtNodes)
  33.  
  34. clang_tablegen(DeclNodes.inc -gen-clang-decl-nodes
  35. SOURCE ../Basic/DeclNodes.td
  36. TARGET ClangDeclNodes)
  37.  
  38. clang_tablegen(TypeNodes.inc -gen-clang-type-nodes
  39. SOURCE ../Basic/TypeNodes.td
  40. TARGET ClangTypeNodes)
  41.  
  42. clang_tablegen(AbstractBasicReader.inc -gen-clang-basic-reader
  43. SOURCE PropertiesBase.td
  44. TARGET ClangAbstractBasicReader)
  45.  
  46. clang_tablegen(AbstractBasicWriter.inc -gen-clang-basic-writer
  47. SOURCE PropertiesBase.td
  48. TARGET ClangAbstractBasicWriter)
  49.  
  50. clang_tablegen(AbstractTypeReader.inc -gen-clang-type-reader
  51. SOURCE TypeProperties.td
  52. TARGET ClangAbstractTypeReader)
  53.  
  54. clang_tablegen(AbstractTypeWriter.inc -gen-clang-type-writer
  55. SOURCE TypeProperties.td
  56. TARGET ClangAbstractTypeWriter)
  57.  
  58. clang_tablegen(CommentNodes.inc -gen-clang-comment-nodes
  59. SOURCE ../Basic/CommentNodes.td
  60. TARGET ClangCommentNodes)
  61.  
  62. clang_tablegen(CommentHTMLTags.inc -gen-clang-comment-html-tags
  63. SOURCE CommentHTMLTags.td
  64. TARGET ClangCommentHTMLTags)
  65.  
  66. clang_tablegen(CommentHTMLTagsProperties.inc -gen-clang-comment-html-tags-properties
  67. SOURCE CommentHTMLTags.td
  68. TARGET ClangCommentHTMLTagsProperties)
  69.  
  70. clang_tablegen(CommentHTMLNamedCharacterReferences.inc -gen-clang-comment-html-named-character-references
  71. SOURCE CommentHTMLNamedCharacterReferences.td
  72. TARGET ClangCommentHTMLNamedCharacterReferences)
  73.  
  74. clang_tablegen(CommentCommandInfo.inc -gen-clang-comment-command-info
  75. SOURCE CommentCommands.td
  76. TARGET ClangCommentCommandInfo)
  77.  
  78. clang_tablegen(CommentCommandList.inc -gen-clang-comment-command-list
  79. SOURCE CommentCommands.td
  80. TARGET ClangCommentCommandList)
  81.  
  82. clang_tablegen(StmtDataCollectors.inc -gen-clang-data-collectors
  83. SOURCE StmtDataCollectors.td
  84. TARGET StmtDataCollectors)
  85. diff --git a/clang/include/clang/AST/JSONNodeDumper.h b/clang/include/clang/AST/JSONNodeDumper.h
  86. index 4e71629..fd0a54c 100644
  87. --- a/clang/include/clang/AST/JSONNodeDumper.h
  88. +++ b/clang/include/clang/AST/JSONNodeDumper.h
  89. @@ -1,434 +1,437 @@
  90. //===--- JSONNodeDumper.h - Printing of AST nodes to JSON -----------------===//
  91. //
  92. // The LLVM Compiler Infrastructure
  93. //
  94. // This file is distributed under the University of Illinois Open Source
  95. // License. See LICENSE.TXT for details.
  96. //
  97. //===----------------------------------------------------------------------===//
  98. //
  99. // This file implements AST dumping of components of individual AST nodes to
  100. // a JSON.
  101. //
  102. //===----------------------------------------------------------------------===//
  103.  
  104. #ifndef LLVM_CLANG_AST_JSONNODEDUMPER_H
  105. #define LLVM_CLANG_AST_JSONNODEDUMPER_H
  106.  
  107. #include "clang/AST/ASTContext.h"
  108. #include "clang/AST/ASTDumperUtils.h"
  109. #include "clang/AST/ASTNodeTraverser.h"
  110. #include "clang/AST/AttrVisitor.h"
  111. #include "clang/AST/CommentCommandTraits.h"
  112. #include "clang/AST/CommentVisitor.h"
  113. #include "clang/AST/ExprCXX.h"
  114. #include "clang/AST/Mangle.h"
  115. #include "clang/AST/Type.h"
  116. #include "llvm/Support/JSON.h"
  117.  
  118. namespace clang {
  119.  
  120. class APValue;
  121.  
  122. class NodeStreamer {
  123. bool FirstChild = true;
  124. bool TopLevel = true;
  125. llvm::SmallVector<std::function<void(bool IsLastChild)>, 32> Pending;
  126.  
  127. protected:
  128. llvm::json::OStream JOS;
  129.  
  130. public:
  131. /// Add a child of the current node. Calls DoAddChild without arguments
  132. template <typename Fn> void AddChild(Fn DoAddChild) {
  133. return AddChild("", DoAddChild);
  134. }
  135.  
  136. /// Add a child of the current node with an optional label.
  137. /// Calls DoAddChild without arguments.
  138. template <typename Fn> void AddChild(StringRef Label, Fn DoAddChild) {
  139. // If we're at the top level, there's nothing interesting to do; just
  140. // run the dumper.
  141. if (TopLevel) {
  142. TopLevel = false;
  143. JOS.objectBegin();
  144.  
  145. DoAddChild();
  146.  
  147. while (!Pending.empty()) {
  148. Pending.back()(true);
  149. Pending.pop_back();
  150. }
  151.  
  152. JOS.objectEnd();
  153. TopLevel = true;
  154. return;
  155. }
  156.  
  157. // We need to capture an owning-string in the lambda because the lambda
  158. // is invoked in a deferred manner.
  159. std::string LabelStr(!Label.empty() ? Label : "inner");
  160. bool WasFirstChild = FirstChild;
  161. auto DumpWithIndent = [=](bool IsLastChild) {
  162. if (WasFirstChild) {
  163. JOS.attributeBegin(LabelStr);
  164. JOS.arrayBegin();
  165. }
  166.  
  167. FirstChild = true;
  168. unsigned Depth = Pending.size();
  169. JOS.objectBegin();
  170.  
  171. DoAddChild();
  172.  
  173. // If any children are left, they're the last at their nesting level.
  174. // Dump those ones out now.
  175. while (Depth < Pending.size()) {
  176. Pending.back()(true);
  177. this->Pending.pop_back();
  178. }
  179.  
  180. JOS.objectEnd();
  181.  
  182. if (IsLastChild) {
  183. JOS.arrayEnd();
  184. JOS.attributeEnd();
  185. }
  186. };
  187.  
  188. if (FirstChild) {
  189. Pending.push_back(std::move(DumpWithIndent));
  190. } else {
  191. Pending.back()(false);
  192. Pending.back() = std::move(DumpWithIndent);
  193. }
  194. FirstChild = false;
  195. }
  196.  
  197. NodeStreamer(raw_ostream &OS) : JOS(OS, 2) {}
  198. };
  199.  
  200. // Dumps AST nodes in JSON format. There is no implied stability for the
  201. // content or format of the dump between major releases of Clang, other than it
  202. // being valid JSON output. Further, there is no requirement that the
  203. // information dumped is a complete representation of the AST, only that the
  204. // information presented is correct.
  205. class JSONNodeDumper
  206. : public ConstAttrVisitor<JSONNodeDumper>,
  207. public comments::ConstCommentVisitor<JSONNodeDumper, void,
  208. const comments::FullComment *>,
  209. public ConstTemplateArgumentVisitor<JSONNodeDumper>,
  210. public ConstStmtVisitor<JSONNodeDumper>,
  211. public TypeVisitor<JSONNodeDumper>,
  212. public ConstDeclVisitor<JSONNodeDumper>,
  213. public NodeStreamer {
  214. friend class JSONDumper;
  215.  
  216. const SourceManager &SM;
  217. ASTContext& Ctx;
  218. ASTNameGenerator ASTNameGen;
  219. PrintingPolicy PrintPolicy;
  220. const comments::CommandTraits *Traits;
  221. StringRef LastLocFilename, LastLocPresumedFilename;
  222. unsigned LastLocLine, LastLocPresumedLine;
  223.  
  224. using InnerAttrVisitor = ConstAttrVisitor<JSONNodeDumper>;
  225. using InnerCommentVisitor =
  226. comments::ConstCommentVisitor<JSONNodeDumper, void,
  227. const comments::FullComment *>;
  228. using InnerTemplateArgVisitor = ConstTemplateArgumentVisitor<JSONNodeDumper>;
  229. using InnerStmtVisitor = ConstStmtVisitor<JSONNodeDumper>;
  230. using InnerTypeVisitor = TypeVisitor<JSONNodeDumper>;
  231. using InnerDeclVisitor = ConstDeclVisitor<JSONNodeDumper>;
  232.  
  233. void attributeOnlyIfTrue(StringRef Key, bool Value) {
  234. if (Value)
  235. JOS.attribute(Key, Value);
  236. }
  237.  
  238. void writeIncludeStack(PresumedLoc Loc, bool JustFirst = false);
  239.  
  240. // Writes the attributes of a SourceLocation object without.
  241. void writeBareSourceLocation(SourceLocation Loc, bool IsSpelling);
  242.  
  243. // Writes the attributes of a SourceLocation to JSON based on its presumed
  244. // spelling location. If the given location represents a macro invocation,
  245. // this outputs two sub-objects: one for the spelling and one for the
  246. // expansion location.
  247. void writeSourceLocation(SourceLocation Loc);
  248. void writeSourceRange(SourceRange R);
  249. std::string createPointerRepresentation(const void *Ptr);
  250. llvm::json::Object createQualType(QualType QT, bool Desugar = true);
  251. llvm::json::Object createBareDeclRef(const Decl *D);
  252. void writeBareDeclRef(const Decl *D);
  253. llvm::json::Object createCXXRecordDefinitionData(const CXXRecordDecl *RD);
  254. llvm::json::Object createCXXBaseSpecifier(const CXXBaseSpecifier &BS);
  255. std::string createAccessSpecifier(AccessSpecifier AS);
  256. llvm::json::Array createCastPath(const CastExpr *C);
  257.  
  258. void writePreviousDeclImpl(...) {}
  259.  
  260. template <typename T> void writePreviousDeclImpl(const Mergeable<T> *D) {
  261. const T *First = D->getFirstDecl();
  262. if (First != D)
  263. JOS.attribute("firstRedecl", createPointerRepresentation(First));
  264. }
  265.  
  266. template <typename T> void writePreviousDeclImpl(const Redeclarable<T> *D) {
  267. const T *Prev = D->getPreviousDecl();
  268. if (Prev)
  269. JOS.attribute("previousDecl", createPointerRepresentation(Prev));
  270. }
  271. void addPreviousDeclaration(const Decl *D);
  272.  
  273. StringRef getCommentCommandName(unsigned CommandID) const;
  274.  
  275. public:
  276. JSONNodeDumper(raw_ostream &OS, const SourceManager &SrcMgr, ASTContext &Ctx,
  277. const PrintingPolicy &PrintPolicy,
  278. const comments::CommandTraits *Traits)
  279. : NodeStreamer(OS), SM(SrcMgr), Ctx(Ctx), ASTNameGen(Ctx),
  280. PrintPolicy(PrintPolicy), Traits(Traits), LastLocLine(0),
  281. LastLocPresumedLine(0) {}
  282.  
  283. void Visit(const Attr *A);
  284. void Visit(const Stmt *Node);
  285. void Visit(const Type *T);
  286. void Visit(QualType T);
  287. void Visit(const Decl *D);
  288.  
  289. void Visit(const comments::Comment *C, const comments::FullComment *FC);
  290. void Visit(const TemplateArgument &TA, SourceRange R = {},
  291. const Decl *From = nullptr, StringRef Label = {});
  292. void Visit(const CXXCtorInitializer *Init);
  293. void Visit(const OMPClause *C);
  294. void Visit(const BlockDecl::Capture &C);
  295. void Visit(const GenericSelectionExpr::ConstAssociation &A);
  296. void Visit(const APValue &Value, QualType Ty);
  297.  
  298. +// Implements Visit methods for Attrs.
  299. +#include "clang/AST/AttrJSONNodeDump.inc"
  300. +
  301. void VisitTypedefType(const TypedefType *TT);
  302. void VisitFunctionType(const FunctionType *T);
  303. void VisitFunctionProtoType(const FunctionProtoType *T);
  304. void VisitRValueReferenceType(const ReferenceType *RT);
  305. void VisitArrayType(const ArrayType *AT);
  306. void VisitConstantArrayType(const ConstantArrayType *CAT);
  307. void VisitDependentSizedExtVectorType(const DependentSizedExtVectorType *VT);
  308. void VisitVectorType(const VectorType *VT);
  309. void VisitUnresolvedUsingType(const UnresolvedUsingType *UUT);
  310. void VisitUnaryTransformType(const UnaryTransformType *UTT);
  311. void VisitTagType(const TagType *TT);
  312. void VisitTemplateTypeParmType(const TemplateTypeParmType *TTPT);
  313. void VisitAutoType(const AutoType *AT);
  314. void VisitTemplateSpecializationType(const TemplateSpecializationType *TST);
  315. void VisitInjectedClassNameType(const InjectedClassNameType *ICNT);
  316. void VisitObjCInterfaceType(const ObjCInterfaceType *OIT);
  317. void VisitPackExpansionType(const PackExpansionType *PET);
  318. void VisitElaboratedType(const ElaboratedType *ET);
  319. void VisitMacroQualifiedType(const MacroQualifiedType *MQT);
  320. void VisitMemberPointerType(const MemberPointerType *MPT);
  321.  
  322. void VisitNamedDecl(const NamedDecl *ND);
  323. void VisitTypedefDecl(const TypedefDecl *TD);
  324. void VisitTypeAliasDecl(const TypeAliasDecl *TAD);
  325. void VisitNamespaceDecl(const NamespaceDecl *ND);
  326. void VisitUsingDirectiveDecl(const UsingDirectiveDecl *UDD);
  327. void VisitNamespaceAliasDecl(const NamespaceAliasDecl *NAD);
  328. void VisitUsingDecl(const UsingDecl *UD);
  329. void VisitUsingShadowDecl(const UsingShadowDecl *USD);
  330. void VisitVarDecl(const VarDecl *VD);
  331. void VisitFieldDecl(const FieldDecl *FD);
  332. void VisitFunctionDecl(const FunctionDecl *FD);
  333. void VisitEnumDecl(const EnumDecl *ED);
  334. void VisitEnumConstantDecl(const EnumConstantDecl *ECD);
  335. void VisitRecordDecl(const RecordDecl *RD);
  336. void VisitCXXRecordDecl(const CXXRecordDecl *RD);
  337. void VisitTemplateTypeParmDecl(const TemplateTypeParmDecl *D);
  338. void VisitNonTypeTemplateParmDecl(const NonTypeTemplateParmDecl *D);
  339. void VisitTemplateTemplateParmDecl(const TemplateTemplateParmDecl *D);
  340. void VisitLinkageSpecDecl(const LinkageSpecDecl *LSD);
  341. void VisitAccessSpecDecl(const AccessSpecDecl *ASD);
  342. void VisitFriendDecl(const FriendDecl *FD);
  343.  
  344. void VisitObjCIvarDecl(const ObjCIvarDecl *D);
  345. void VisitObjCMethodDecl(const ObjCMethodDecl *D);
  346. void VisitObjCTypeParamDecl(const ObjCTypeParamDecl *D);
  347. void VisitObjCCategoryDecl(const ObjCCategoryDecl *D);
  348. void VisitObjCCategoryImplDecl(const ObjCCategoryImplDecl *D);
  349. void VisitObjCProtocolDecl(const ObjCProtocolDecl *D);
  350. void VisitObjCInterfaceDecl(const ObjCInterfaceDecl *D);
  351. void VisitObjCImplementationDecl(const ObjCImplementationDecl *D);
  352. void VisitObjCCompatibleAliasDecl(const ObjCCompatibleAliasDecl *D);
  353. void VisitObjCPropertyDecl(const ObjCPropertyDecl *D);
  354. void VisitObjCPropertyImplDecl(const ObjCPropertyImplDecl *D);
  355. void VisitBlockDecl(const BlockDecl *D);
  356.  
  357. void VisitDeclRefExpr(const DeclRefExpr *DRE);
  358. void VisitPredefinedExpr(const PredefinedExpr *PE);
  359. void VisitUnaryOperator(const UnaryOperator *UO);
  360. void VisitBinaryOperator(const BinaryOperator *BO);
  361. void VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
  362. void VisitMemberExpr(const MemberExpr *ME);
  363. void VisitCXXNewExpr(const CXXNewExpr *NE);
  364. void VisitCXXDeleteExpr(const CXXDeleteExpr *DE);
  365. void VisitCXXThisExpr(const CXXThisExpr *TE);
  366. void VisitCastExpr(const CastExpr *CE);
  367. void VisitImplicitCastExpr(const ImplicitCastExpr *ICE);
  368. void VisitCallExpr(const CallExpr *CE);
  369. void VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *TTE);
  370. void VisitSizeOfPackExpr(const SizeOfPackExpr *SOPE);
  371. void VisitUnresolvedLookupExpr(const UnresolvedLookupExpr *ULE);
  372. void VisitAddrLabelExpr(const AddrLabelExpr *ALE);
  373. void VisitCXXTypeidExpr(const CXXTypeidExpr *CTE);
  374. void VisitConstantExpr(const ConstantExpr *CE);
  375. void VisitInitListExpr(const InitListExpr *ILE);
  376. void VisitGenericSelectionExpr(const GenericSelectionExpr *GSE);
  377. void VisitCXXUnresolvedConstructExpr(const CXXUnresolvedConstructExpr *UCE);
  378. void VisitCXXConstructExpr(const CXXConstructExpr *CE);
  379. void VisitExprWithCleanups(const ExprWithCleanups *EWC);
  380. void VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *BTE);
  381. void VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *MTE);
  382. void VisitCXXDependentScopeMemberExpr(const CXXDependentScopeMemberExpr *ME);
  383.  
  384. void VisitObjCEncodeExpr(const ObjCEncodeExpr *OEE);
  385. void VisitObjCMessageExpr(const ObjCMessageExpr *OME);
  386. void VisitObjCBoxedExpr(const ObjCBoxedExpr *OBE);
  387. void VisitObjCSelectorExpr(const ObjCSelectorExpr *OSE);
  388. void VisitObjCProtocolExpr(const ObjCProtocolExpr *OPE);
  389. void VisitObjCPropertyRefExpr(const ObjCPropertyRefExpr *OPRE);
  390. void VisitObjCSubscriptRefExpr(const ObjCSubscriptRefExpr *OSRE);
  391. void VisitObjCIvarRefExpr(const ObjCIvarRefExpr *OIRE);
  392. void VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *OBLE);
  393.  
  394. void VisitIntegerLiteral(const IntegerLiteral *IL);
  395. void VisitCharacterLiteral(const CharacterLiteral *CL);
  396. void VisitFixedPointLiteral(const FixedPointLiteral *FPL);
  397. void VisitFloatingLiteral(const FloatingLiteral *FL);
  398. void VisitStringLiteral(const StringLiteral *SL);
  399. void VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *BLE);
  400.  
  401. void VisitIfStmt(const IfStmt *IS);
  402. void VisitSwitchStmt(const SwitchStmt *SS);
  403. void VisitCaseStmt(const CaseStmt *CS);
  404. void VisitLabelStmt(const LabelStmt *LS);
  405. void VisitGotoStmt(const GotoStmt *GS);
  406. void VisitWhileStmt(const WhileStmt *WS);
  407. void VisitObjCAtCatchStmt(const ObjCAtCatchStmt *OACS);
  408.  
  409. void VisitNullTemplateArgument(const TemplateArgument &TA);
  410. void VisitTypeTemplateArgument(const TemplateArgument &TA);
  411. void VisitDeclarationTemplateArgument(const TemplateArgument &TA);
  412. void VisitNullPtrTemplateArgument(const TemplateArgument &TA);
  413. void VisitIntegralTemplateArgument(const TemplateArgument &TA);
  414. void VisitTemplateTemplateArgument(const TemplateArgument &TA);
  415. void VisitTemplateExpansionTemplateArgument(const TemplateArgument &TA);
  416. void VisitExpressionTemplateArgument(const TemplateArgument &TA);
  417. void VisitPackTemplateArgument(const TemplateArgument &TA);
  418.  
  419. void visitTextComment(const comments::TextComment *C,
  420. const comments::FullComment *);
  421. void visitInlineCommandComment(const comments::InlineCommandComment *C,
  422. const comments::FullComment *);
  423. void visitHTMLStartTagComment(const comments::HTMLStartTagComment *C,
  424. const comments::FullComment *);
  425. void visitHTMLEndTagComment(const comments::HTMLEndTagComment *C,
  426. const comments::FullComment *);
  427. void visitBlockCommandComment(const comments::BlockCommandComment *C,
  428. const comments::FullComment *);
  429. void visitParamCommandComment(const comments::ParamCommandComment *C,
  430. const comments::FullComment *FC);
  431. void visitTParamCommandComment(const comments::TParamCommandComment *C,
  432. const comments::FullComment *FC);
  433. void visitVerbatimBlockComment(const comments::VerbatimBlockComment *C,
  434. const comments::FullComment *);
  435. void
  436. visitVerbatimBlockLineComment(const comments::VerbatimBlockLineComment *C,
  437. const comments::FullComment *);
  438. void visitVerbatimLineComment(const comments::VerbatimLineComment *C,
  439. const comments::FullComment *);
  440. };
  441.  
  442. class JSONDumper : public ASTNodeTraverser<JSONDumper, JSONNodeDumper> {
  443. JSONNodeDumper NodeDumper;
  444.  
  445. template <typename SpecializationDecl>
  446. void writeTemplateDeclSpecialization(const SpecializationDecl *SD,
  447. bool DumpExplicitInst,
  448. bool DumpRefOnly) {
  449. bool DumpedAny = false;
  450. for (const auto *RedeclWithBadType : SD->redecls()) {
  451. // FIXME: The redecls() range sometimes has elements of a less-specific
  452. // type. (In particular, ClassTemplateSpecializationDecl::redecls() gives
  453. // us TagDecls, and should give CXXRecordDecls).
  454. const auto *Redecl = dyn_cast<SpecializationDecl>(RedeclWithBadType);
  455. if (!Redecl) {
  456. // Found the injected-class-name for a class template. This will be
  457. // dumped as part of its surrounding class so we don't need to dump it
  458. // here.
  459. assert(isa<CXXRecordDecl>(RedeclWithBadType) &&
  460. "expected an injected-class-name");
  461. continue;
  462. }
  463.  
  464. switch (Redecl->getTemplateSpecializationKind()) {
  465. case TSK_ExplicitInstantiationDeclaration:
  466. case TSK_ExplicitInstantiationDefinition:
  467. if (!DumpExplicitInst)
  468. break;
  469. LLVM_FALLTHROUGH;
  470. case TSK_Undeclared:
  471. case TSK_ImplicitInstantiation:
  472. if (DumpRefOnly)
  473. NodeDumper.AddChild([=] { NodeDumper.writeBareDeclRef(Redecl); });
  474. else
  475. Visit(Redecl);
  476. DumpedAny = true;
  477. break;
  478. case TSK_ExplicitSpecialization:
  479. break;
  480. }
  481. }
  482.  
  483. // Ensure we dump at least one decl for each specialization.
  484. if (!DumpedAny)
  485. NodeDumper.AddChild([=] { NodeDumper.writeBareDeclRef(SD); });
  486. }
  487.  
  488. template <typename TemplateDecl>
  489. void writeTemplateDecl(const TemplateDecl *TD, bool DumpExplicitInst) {
  490. // FIXME: it would be nice to dump template parameters and specializations
  491. // to their own named arrays rather than shoving them into the "inner"
  492. // array. However, template declarations are currently being handled at the
  493. // wrong "level" of the traversal hierarchy and so it is difficult to
  494. // achieve without losing information elsewhere.
  495.  
  496. dumpTemplateParameters(TD->getTemplateParameters());
  497.  
  498. Visit(TD->getTemplatedDecl());
  499.  
  500. for (const auto *Child : TD->specializations())
  501. writeTemplateDeclSpecialization(Child, DumpExplicitInst,
  502. !TD->isCanonicalDecl());
  503. }
  504.  
  505. public:
  506. JSONDumper(raw_ostream &OS, const SourceManager &SrcMgr, ASTContext &Ctx,
  507. const PrintingPolicy &PrintPolicy,
  508. const comments::CommandTraits *Traits)
  509. : NodeDumper(OS, SrcMgr, Ctx, PrintPolicy, Traits) {}
  510.  
  511. JSONNodeDumper &doGetNodeDelegate() { return NodeDumper; }
  512.  
  513. void VisitFunctionTemplateDecl(const FunctionTemplateDecl *FTD) {
  514. writeTemplateDecl(FTD, true);
  515. }
  516. void VisitClassTemplateDecl(const ClassTemplateDecl *CTD) {
  517. writeTemplateDecl(CTD, false);
  518. }
  519. void VisitVarTemplateDecl(const VarTemplateDecl *VTD) {
  520. writeTemplateDecl(VTD, false);
  521. }
  522. };
  523.  
  524. } // namespace clang
  525.  
  526. #endif // LLVM_CLANG_AST_JSONNODEDUMPER_H
  527. diff --git a/clang/utils/TableGen/ClangAttrEmitter.cpp b/clang/utils/TableGen/ClangAttrEmitter.cpp
  528. index 1ed81ee..81cfb4a 100644
  529. --- a/clang/utils/TableGen/ClangAttrEmitter.cpp
  530. +++ b/clang/utils/TableGen/ClangAttrEmitter.cpp
  531. @@ -1,2228 +1,2314 @@
  532. //===- ClangAttrEmitter.cpp - Generate Clang attribute handling =-*- C++ -*--=//
  533. //
  534. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  535. // See https://llvm.org/LICENSE.txt for license information.
  536. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  537. //
  538. //===----------------------------------------------------------------------===//
  539. //
  540. // These tablegen backends emit Clang attribute processing code
  541. //
  542. //===----------------------------------------------------------------------===//
  543.  
  544. #include "TableGenBackends.h"
  545. #include "ASTTableGen.h"
  546.  
  547. #include "llvm/ADT/ArrayRef.h"
  548. #include "llvm/ADT/DenseMap.h"
  549. #include "llvm/ADT/DenseSet.h"
  550. #include "llvm/ADT/STLExtras.h"
  551. #include "llvm/ADT/SmallString.h"
  552. #include "llvm/ADT/StringExtras.h"
  553. #include "llvm/ADT/StringRef.h"
  554. #include "llvm/ADT/StringSet.h"
  555. #include "llvm/ADT/StringSwitch.h"
  556. #include "llvm/ADT/iterator_range.h"
  557. #include "llvm/Support/ErrorHandling.h"
  558. #include "llvm/Support/raw_ostream.h"
  559. #include "llvm/TableGen/Error.h"
  560. #include "llvm/TableGen/Record.h"
  561. #include "llvm/TableGen/StringMatcher.h"
  562. #include "llvm/TableGen/TableGenBackend.h"
  563. #include <algorithm>
  564. #include <cassert>
  565. #include <cctype>
  566. #include <cstddef>
  567. #include <cstdint>
  568. #include <map>
  569. #include <memory>
  570. #include <set>
  571. #include <sstream>
  572. #include <string>
  573. #include <utility>
  574. #include <vector>
  575.  
  576. using namespace llvm;
  577.  
  578. namespace {
  579.  
  580. class FlattenedSpelling {
  581. std::string V, N, NS;
  582. bool K = false;
  583.  
  584. public:
  585. FlattenedSpelling(const std::string &Variety, const std::string &Name,
  586. const std::string &Namespace, bool KnownToGCC) :
  587. V(Variety), N(Name), NS(Namespace), K(KnownToGCC) {}
  588. explicit FlattenedSpelling(const Record &Spelling)
  589. : V(std::string(Spelling.getValueAsString("Variety"))),
  590. N(std::string(Spelling.getValueAsString("Name"))) {
  591. assert(V != "GCC" && V != "Clang" &&
  592. "Given a GCC spelling, which means this hasn't been flattened!");
  593. if (V == "CXX11" || V == "C2x" || V == "Pragma")
  594. NS = std::string(Spelling.getValueAsString("Namespace"));
  595. }
  596.  
  597. const std::string &variety() const { return V; }
  598. const std::string &name() const { return N; }
  599. const std::string &nameSpace() const { return NS; }
  600. bool knownToGCC() const { return K; }
  601. };
  602.  
  603. } // end anonymous namespace
  604.  
  605. static std::vector<FlattenedSpelling>
  606. GetFlattenedSpellings(const Record &Attr) {
  607. std::vector<Record *> Spellings = Attr.getValueAsListOfDefs("Spellings");
  608. std::vector<FlattenedSpelling> Ret;
  609.  
  610. for (const auto &Spelling : Spellings) {
  611. StringRef Variety = Spelling->getValueAsString("Variety");
  612. StringRef Name = Spelling->getValueAsString("Name");
  613. if (Variety == "GCC") {
  614. Ret.emplace_back("GNU", std::string(Name), "", true);
  615. Ret.emplace_back("CXX11", std::string(Name), "gnu", true);
  616. if (Spelling->getValueAsBit("AllowInC"))
  617. Ret.emplace_back("C2x", std::string(Name), "gnu", true);
  618. } else if (Variety == "Clang") {
  619. Ret.emplace_back("GNU", std::string(Name), "", false);
  620. Ret.emplace_back("CXX11", std::string(Name), "clang", false);
  621. if (Spelling->getValueAsBit("AllowInC"))
  622. Ret.emplace_back("C2x", std::string(Name), "clang", false);
  623. } else
  624. Ret.push_back(FlattenedSpelling(*Spelling));
  625. }
  626.  
  627. return Ret;
  628. }
  629.  
  630. static std::string ReadPCHRecord(StringRef type) {
  631. return StringSwitch<std::string>(type)
  632. .EndsWith("Decl *", "Record.GetLocalDeclAs<" +
  633. std::string(type.data(), 0, type.size() - 1) +
  634. ">(Record.readInt())")
  635. .Case("TypeSourceInfo *", "Record.readTypeSourceInfo()")
  636. .Case("Expr *", "Record.readExpr()")
  637. .Case("IdentifierInfo *", "Record.readIdentifier()")
  638. .Case("StringRef", "Record.readString()")
  639. .Case("ParamIdx", "ParamIdx::deserialize(Record.readInt())")
  640. .Case("OMPTraitInfo *", "Record.readOMPTraitInfo()")
  641. .Default("Record.readInt()");
  642. }
  643.  
  644. // Get a type that is suitable for storing an object of the specified type.
  645. static StringRef getStorageType(StringRef type) {
  646. return StringSwitch<StringRef>(type)
  647. .Case("StringRef", "std::string")
  648. .Default(type);
  649. }
  650.  
  651. // Assumes that the way to get the value is SA->getname()
  652. static std::string WritePCHRecord(StringRef type, StringRef name) {
  653. return "Record." +
  654. StringSwitch<std::string>(type)
  655. .EndsWith("Decl *", "AddDeclRef(" + std::string(name) + ");\n")
  656. .Case("TypeSourceInfo *",
  657. "AddTypeSourceInfo(" + std::string(name) + ");\n")
  658. .Case("Expr *", "AddStmt(" + std::string(name) + ");\n")
  659. .Case("IdentifierInfo *",
  660. "AddIdentifierRef(" + std::string(name) + ");\n")
  661. .Case("StringRef", "AddString(" + std::string(name) + ");\n")
  662. .Case("ParamIdx",
  663. "push_back(" + std::string(name) + ".serialize());\n")
  664. .Case("OMPTraitInfo *",
  665. "writeOMPTraitInfo(" + std::string(name) + ");\n")
  666. .Default("push_back(" + std::string(name) + ");\n");
  667. }
  668.  
  669. // Normalize attribute name by removing leading and trailing
  670. // underscores. For example, __foo, foo__, __foo__ would
  671. // become foo.
  672. static StringRef NormalizeAttrName(StringRef AttrName) {
  673. AttrName.consume_front("__");
  674. AttrName.consume_back("__");
  675. return AttrName;
  676. }
  677.  
  678. // Normalize the name by removing any and all leading and trailing underscores.
  679. // This is different from NormalizeAttrName in that it also handles names like
  680. // _pascal and __pascal.
  681. static StringRef NormalizeNameForSpellingComparison(StringRef Name) {
  682. return Name.trim("_");
  683. }
  684.  
  685. // Normalize the spelling of a GNU attribute (i.e. "x" in "__attribute__((x))"),
  686. // removing "__" if it appears at the beginning and end of the attribute's name.
  687. static StringRef NormalizeGNUAttrSpelling(StringRef AttrSpelling) {
  688. if (AttrSpelling.startswith("__") && AttrSpelling.endswith("__")) {
  689. AttrSpelling = AttrSpelling.substr(2, AttrSpelling.size() - 4);
  690. }
  691.  
  692. return AttrSpelling;
  693. }
  694.  
  695. typedef std::vector<std::pair<std::string, const Record *>> ParsedAttrMap;
  696.  
  697. static ParsedAttrMap getParsedAttrList(const RecordKeeper &Records,
  698. ParsedAttrMap *Dupes = nullptr) {
  699. std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
  700. std::set<std::string> Seen;
  701. ParsedAttrMap R;
  702. for (const auto *Attr : Attrs) {
  703. if (Attr->getValueAsBit("SemaHandler")) {
  704. std::string AN;
  705. if (Attr->isSubClassOf("TargetSpecificAttr") &&
  706. !Attr->isValueUnset("ParseKind")) {
  707. AN = std::string(Attr->getValueAsString("ParseKind"));
  708.  
  709. // If this attribute has already been handled, it does not need to be
  710. // handled again.
  711. if (Seen.find(AN) != Seen.end()) {
  712. if (Dupes)
  713. Dupes->push_back(std::make_pair(AN, Attr));
  714. continue;
  715. }
  716. Seen.insert(AN);
  717. } else
  718. AN = NormalizeAttrName(Attr->getName()).str();
  719.  
  720. R.push_back(std::make_pair(AN, Attr));
  721. }
  722. }
  723. return R;
  724. }
  725.  
  726. namespace {
  727.  
  728. class Argument {
  729. std::string lowerName, upperName;
  730. StringRef attrName;
  731. bool isOpt;
  732. bool Fake;
  733.  
  734. public:
  735. Argument(const Record &Arg, StringRef Attr)
  736. : lowerName(std::string(Arg.getValueAsString("Name"))),
  737. upperName(lowerName), attrName(Attr), isOpt(false), Fake(false) {
  738. if (!lowerName.empty()) {
  739. lowerName[0] = std::tolower(lowerName[0]);
  740. upperName[0] = std::toupper(upperName[0]);
  741. }
  742. // Work around MinGW's macro definition of 'interface' to 'struct'. We
  743. // have an attribute argument called 'Interface', so only the lower case
  744. // name conflicts with the macro definition.
  745. if (lowerName == "interface")
  746. lowerName = "interface_";
  747. }
  748. virtual ~Argument() = default;
  749.  
  750. StringRef getLowerName() const { return lowerName; }
  751. StringRef getUpperName() const { return upperName; }
  752. StringRef getAttrName() const { return attrName; }
  753.  
  754. bool isOptional() const { return isOpt; }
  755. void setOptional(bool set) { isOpt = set; }
  756.  
  757. bool isFake() const { return Fake; }
  758. void setFake(bool fake) { Fake = fake; }
  759.  
  760. // These functions print the argument contents formatted in different ways.
  761. virtual void writeAccessors(raw_ostream &OS) const = 0;
  762. virtual void writeAccessorDefinitions(raw_ostream &OS) const {}
  763. virtual void writeASTVisitorTraversal(raw_ostream &OS) const {}
  764. virtual void writeCloneArgs(raw_ostream &OS) const = 0;
  765. virtual void writeTemplateInstantiationArgs(raw_ostream &OS) const = 0;
  766. virtual void writeTemplateInstantiation(raw_ostream &OS) const {}
  767. virtual void writeCtorBody(raw_ostream &OS) const {}
  768. virtual void writeCtorInitializers(raw_ostream &OS) const = 0;
  769. virtual void writeCtorDefaultInitializers(raw_ostream &OS) const = 0;
  770. virtual void writeCtorParameters(raw_ostream &OS) const = 0;
  771. virtual void writeDeclarations(raw_ostream &OS) const = 0;
  772. virtual void writePCHReadArgs(raw_ostream &OS) const = 0;
  773. virtual void writePCHReadDecls(raw_ostream &OS) const = 0;
  774. virtual void writePCHWrite(raw_ostream &OS) const = 0;
  775. virtual std::string getIsOmitted() const { return "false"; }
  776. virtual void writeValue(raw_ostream &OS) const = 0;
  777. - virtual void writeDump(raw_ostream &OS) const = 0;
  778. + virtual void writeTextDump(raw_ostream &OS) const = 0;
  779. + virtual void writeJSONDump(raw_ostream &OS) const = 0;
  780. virtual void writeDumpChildren(raw_ostream &OS) const {}
  781. virtual void writeHasChildren(raw_ostream &OS) const { OS << "false"; }
  782.  
  783. virtual bool isEnumArg() const { return false; }
  784. virtual bool isVariadicEnumArg() const { return false; }
  785. virtual bool isVariadic() const { return false; }
  786.  
  787. virtual void writeImplicitCtorArgs(raw_ostream &OS) const {
  788. OS << getUpperName();
  789. }
  790. };
  791.  
  792. class SimpleArgument : public Argument {
  793. std::string type;
  794.  
  795. public:
  796. SimpleArgument(const Record &Arg, StringRef Attr, std::string T)
  797. : Argument(Arg, Attr), type(std::move(T)) {}
  798.  
  799. std::string getType() const { return type; }
  800.  
  801. void writeAccessors(raw_ostream &OS) const override {
  802. OS << " " << type << " get" << getUpperName() << "() const {\n";
  803. OS << " return " << getLowerName() << ";\n";
  804. OS << " }";
  805. }
  806.  
  807. void writeCloneArgs(raw_ostream &OS) const override {
  808. OS << getLowerName();
  809. }
  810.  
  811. void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
  812. OS << "A->get" << getUpperName() << "()";
  813. }
  814.  
  815. void writeCtorInitializers(raw_ostream &OS) const override {
  816. OS << getLowerName() << "(" << getUpperName() << ")";
  817. }
  818.  
  819. void writeCtorDefaultInitializers(raw_ostream &OS) const override {
  820. OS << getLowerName() << "()";
  821. }
  822.  
  823. void writeCtorParameters(raw_ostream &OS) const override {
  824. OS << type << " " << getUpperName();
  825. }
  826.  
  827. void writeDeclarations(raw_ostream &OS) const override {
  828. OS << type << " " << getLowerName() << ";";
  829. }
  830.  
  831. void writePCHReadDecls(raw_ostream &OS) const override {
  832. std::string read = ReadPCHRecord(type);
  833. OS << " " << type << " " << getLowerName() << " = " << read << ";\n";
  834. }
  835.  
  836. void writePCHReadArgs(raw_ostream &OS) const override {
  837. OS << getLowerName();
  838. }
  839.  
  840. void writePCHWrite(raw_ostream &OS) const override {
  841. OS << " "
  842. << WritePCHRecord(type,
  843. "SA->get" + std::string(getUpperName()) + "()");
  844. }
  845.  
  846. std::string getIsOmitted() const override {
  847. if (type == "IdentifierInfo *")
  848. return "!get" + getUpperName().str() + "()";
  849. if (type == "TypeSourceInfo *")
  850. return "!get" + getUpperName().str() + "Loc()";
  851. if (type == "ParamIdx")
  852. return "!get" + getUpperName().str() + "().isValid()";
  853. return "false";
  854. }
  855.  
  856. void writeValue(raw_ostream &OS) const override {
  857. if (type == "FunctionDecl *")
  858. OS << "\" << get" << getUpperName()
  859. << "()->getNameInfo().getAsString() << \"";
  860. else if (type == "IdentifierInfo *")
  861. // Some non-optional (comma required) identifier arguments can be the
  862. // empty string but are then recorded as a nullptr.
  863. OS << "\" << (get" << getUpperName() << "() ? get" << getUpperName()
  864. << "()->getName() : \"\") << \"";
  865. else if (type == "VarDecl *")
  866. OS << "\" << get" << getUpperName() << "()->getName() << \"";
  867. else if (type == "TypeSourceInfo *")
  868. OS << "\" << get" << getUpperName() << "().getAsString() << \"";
  869. else if (type == "ParamIdx")
  870. OS << "\" << get" << getUpperName() << "().getSourceIndex() << \"";
  871. else
  872. OS << "\" << get" << getUpperName() << "() << \"";
  873. }
  874.  
  875. - void writeDump(raw_ostream &OS) const override {
  876. + void writeJSONDump(raw_ostream &OS) const override {
  877. + auto wrap = [&OS](Twine Val) {
  878. + OS << " Args.push_back(" << Val << ");\n";
  879. + };
  880. + if (StringRef(type).endswith("Decl *"))
  881. + wrap("createBareDeclRef(A->get" + getUpperName() + "())");
  882. + else if (type == "IdentifierInfo *")
  883. + // Some non-optional (comma required) identifier arguments can be the
  884. + // empty string but are then recorded as a nullptr.
  885. + wrap("(A->get" + getUpperName() + "() ? A->get" + getUpperName() +
  886. + "()->getName() : \"\")");
  887. + else if (type == "VarDecl *")
  888. + wrap("A->get" + getUpperName() + "()->getName()");
  889. + else if (type == "TypeSourceInfo *")
  890. + wrap("A->get" + getUpperName() + "().getAsString()");
  891. + else if (type == "ParamIdx")
  892. + wrap("A->get" + getUpperName() + "().getSourceIndex()");
  893. + else if (type == "OMPTraitInfo *") {
  894. + // OMPTraitInfo has the ability to print into a stream, so use that to
  895. + // get a human-readable value.
  896. + OS << " {\n std::string Content;\n"
  897. + << " llvm::raw_string_ostream SS(Content);\n"
  898. + << " SS << A->get" << getUpperName() << "();\n"
  899. + << " ";
  900. + wrap("SS.str()");
  901. + OS << " }\n";
  902. + } else
  903. + wrap("A->get" + getUpperName() + "()");
  904. + }
  905. +
  906. + void writeTextDump(raw_ostream &OS) const override {
  907. if (StringRef(type).endswith("Decl *")) {
  908. OS << " OS << \" \";\n";
  909. OS << " dumpBareDeclRef(SA->get" << getUpperName() << "());\n";
  910. } else if (type == "IdentifierInfo *") {
  911. // Some non-optional (comma required) identifier arguments can be the
  912. // empty string but are then recorded as a nullptr.
  913. OS << " if (SA->get" << getUpperName() << "())\n"
  914. << " OS << \" \" << SA->get" << getUpperName()
  915. << "()->getName();\n";
  916. } else if (type == "TypeSourceInfo *") {
  917. if (isOptional())
  918. OS << " if (SA->get" << getUpperName() << "Loc())";
  919. OS << " OS << \" \" << SA->get" << getUpperName()
  920. << "().getAsString();\n";
  921. } else if (type == "bool") {
  922. OS << " if (SA->get" << getUpperName() << "()) OS << \" "
  923. << getUpperName() << "\";\n";
  924. } else if (type == "int" || type == "unsigned") {
  925. OS << " OS << \" \" << SA->get" << getUpperName() << "();\n";
  926. } else if (type == "ParamIdx") {
  927. if (isOptional())
  928. OS << " if (SA->get" << getUpperName() << "().isValid())\n ";
  929. OS << " OS << \" \" << SA->get" << getUpperName()
  930. << "().getSourceIndex();\n";
  931. } else if (type == "OMPTraitInfo *") {
  932. OS << " OS << \" \" << SA->get" << getUpperName() << "();\n";
  933. } else {
  934. llvm_unreachable("Unknown SimpleArgument type!");
  935. }
  936. }
  937. };
  938.  
  939. class DefaultSimpleArgument : public SimpleArgument {
  940. int64_t Default;
  941.  
  942. public:
  943. DefaultSimpleArgument(const Record &Arg, StringRef Attr,
  944. std::string T, int64_t Default)
  945. : SimpleArgument(Arg, Attr, T), Default(Default) {}
  946.  
  947. void writeAccessors(raw_ostream &OS) const override {
  948. SimpleArgument::writeAccessors(OS);
  949.  
  950. OS << "\n\n static const " << getType() << " Default" << getUpperName()
  951. << " = ";
  952. if (getType() == "bool")
  953. OS << (Default != 0 ? "true" : "false");
  954. else
  955. OS << Default;
  956. OS << ";";
  957. }
  958. };
  959.  
  960. class StringArgument : public Argument {
  961. public:
  962. StringArgument(const Record &Arg, StringRef Attr)
  963. : Argument(Arg, Attr)
  964. {}
  965.  
  966. void writeAccessors(raw_ostream &OS) const override {
  967. OS << " llvm::StringRef get" << getUpperName() << "() const {\n";
  968. OS << " return llvm::StringRef(" << getLowerName() << ", "
  969. << getLowerName() << "Length);\n";
  970. OS << " }\n";
  971. OS << " unsigned get" << getUpperName() << "Length() const {\n";
  972. OS << " return " << getLowerName() << "Length;\n";
  973. OS << " }\n";
  974. OS << " void set" << getUpperName()
  975. << "(ASTContext &C, llvm::StringRef S) {\n";
  976. OS << " " << getLowerName() << "Length = S.size();\n";
  977. OS << " this->" << getLowerName() << " = new (C, 1) char ["
  978. << getLowerName() << "Length];\n";
  979. OS << " if (!S.empty())\n";
  980. OS << " std::memcpy(this->" << getLowerName() << ", S.data(), "
  981. << getLowerName() << "Length);\n";
  982. OS << " }";
  983. }
  984.  
  985. void writeCloneArgs(raw_ostream &OS) const override {
  986. OS << "get" << getUpperName() << "()";
  987. }
  988.  
  989. void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
  990. OS << "A->get" << getUpperName() << "()";
  991. }
  992.  
  993. void writeCtorBody(raw_ostream &OS) const override {
  994. OS << " if (!" << getUpperName() << ".empty())\n";
  995. OS << " std::memcpy(" << getLowerName() << ", " << getUpperName()
  996. << ".data(), " << getLowerName() << "Length);\n";
  997. }
  998.  
  999. void writeCtorInitializers(raw_ostream &OS) const override {
  1000. OS << getLowerName() << "Length(" << getUpperName() << ".size()),"
  1001. << getLowerName() << "(new (Ctx, 1) char[" << getLowerName()
  1002. << "Length])";
  1003. }
  1004.  
  1005. void writeCtorDefaultInitializers(raw_ostream &OS) const override {
  1006. OS << getLowerName() << "Length(0)," << getLowerName() << "(nullptr)";
  1007. }
  1008.  
  1009. void writeCtorParameters(raw_ostream &OS) const override {
  1010. OS << "llvm::StringRef " << getUpperName();
  1011. }
  1012.  
  1013. void writeDeclarations(raw_ostream &OS) const override {
  1014. OS << "unsigned " << getLowerName() << "Length;\n";
  1015. OS << "char *" << getLowerName() << ";";
  1016. }
  1017.  
  1018. void writePCHReadDecls(raw_ostream &OS) const override {
  1019. OS << " std::string " << getLowerName()
  1020. << "= Record.readString();\n";
  1021. }
  1022.  
  1023. void writePCHReadArgs(raw_ostream &OS) const override {
  1024. OS << getLowerName();
  1025. }
  1026.  
  1027. void writePCHWrite(raw_ostream &OS) const override {
  1028. OS << " Record.AddString(SA->get" << getUpperName() << "());\n";
  1029. }
  1030.  
  1031. void writeValue(raw_ostream &OS) const override {
  1032. OS << "\\\"\" << get" << getUpperName() << "() << \"\\\"";
  1033. }
  1034.  
  1035. - void writeDump(raw_ostream &OS) const override {
  1036. + void writeJSONDump(raw_ostream &OS) const override {
  1037. + OS << " Args.push_back(A->get" << getUpperName() << "());\n";
  1038. + }
  1039. +
  1040. + void writeTextDump(raw_ostream &OS) const override {
  1041. OS << " OS << \" \\\"\" << SA->get" << getUpperName()
  1042. << "() << \"\\\"\";\n";
  1043. }
  1044. };
  1045.  
  1046. class AlignedArgument : public Argument {
  1047. public:
  1048. AlignedArgument(const Record &Arg, StringRef Attr)
  1049. : Argument(Arg, Attr)
  1050. {}
  1051.  
  1052. void writeAccessors(raw_ostream &OS) const override {
  1053. OS << " bool is" << getUpperName() << "Dependent() const;\n";
  1054. OS << " bool is" << getUpperName() << "ErrorDependent() const;\n";
  1055.  
  1056. OS << " unsigned get" << getUpperName() << "(ASTContext &Ctx) const;\n";
  1057.  
  1058. OS << " bool is" << getUpperName() << "Expr() const {\n";
  1059. OS << " return is" << getLowerName() << "Expr;\n";
  1060. OS << " }\n";
  1061.  
  1062. OS << " Expr *get" << getUpperName() << "Expr() const {\n";
  1063. OS << " assert(is" << getLowerName() << "Expr);\n";
  1064. OS << " return " << getLowerName() << "Expr;\n";
  1065. OS << " }\n";
  1066.  
  1067. OS << " TypeSourceInfo *get" << getUpperName() << "Type() const {\n";
  1068. OS << " assert(!is" << getLowerName() << "Expr);\n";
  1069. OS << " return " << getLowerName() << "Type;\n";
  1070. OS << " }";
  1071. }
  1072.  
  1073. void writeAccessorDefinitions(raw_ostream &OS) const override {
  1074. OS << "bool " << getAttrName() << "Attr::is" << getUpperName()
  1075. << "Dependent() const {\n";
  1076. OS << " if (is" << getLowerName() << "Expr)\n";
  1077. OS << " return " << getLowerName() << "Expr && (" << getLowerName()
  1078. << "Expr->isValueDependent() || " << getLowerName()
  1079. << "Expr->isTypeDependent());\n";
  1080. OS << " else\n";
  1081. OS << " return " << getLowerName()
  1082. << "Type->getType()->isDependentType();\n";
  1083. OS << "}\n";
  1084.  
  1085. OS << "bool " << getAttrName() << "Attr::is" << getUpperName()
  1086. << "ErrorDependent() const {\n";
  1087. OS << " if (is" << getLowerName() << "Expr)\n";
  1088. OS << " return " << getLowerName() << "Expr && " << getLowerName()
  1089. << "Expr->containsErrors();\n";
  1090. OS << " return " << getLowerName()
  1091. << "Type->getType()->containsErrors();\n";
  1092. OS << "}\n";
  1093.  
  1094. // FIXME: Do not do the calculation here
  1095. // FIXME: Handle types correctly
  1096. // A null pointer means maximum alignment
  1097. OS << "unsigned " << getAttrName() << "Attr::get" << getUpperName()
  1098. << "(ASTContext &Ctx) const {\n";
  1099. OS << " assert(!is" << getUpperName() << "Dependent());\n";
  1100. OS << " if (is" << getLowerName() << "Expr)\n";
  1101. OS << " return " << getLowerName() << "Expr ? " << getLowerName()
  1102. << "Expr->EvaluateKnownConstInt(Ctx).getZExtValue()"
  1103. << " * Ctx.getCharWidth() : "
  1104. << "Ctx.getTargetDefaultAlignForAttributeAligned();\n";
  1105. OS << " else\n";
  1106. OS << " return 0; // FIXME\n";
  1107. OS << "}\n";
  1108. }
  1109.  
  1110. void writeASTVisitorTraversal(raw_ostream &OS) const override {
  1111. StringRef Name = getUpperName();
  1112. OS << " if (A->is" << Name << "Expr()) {\n"
  1113. << " if (!getDerived().TraverseStmt(A->get" << Name << "Expr()))\n"
  1114. << " return false;\n"
  1115. << " } else if (auto *TSI = A->get" << Name << "Type()) {\n"
  1116. << " if (!getDerived().TraverseTypeLoc(TSI->getTypeLoc()))\n"
  1117. << " return false;\n"
  1118. << " }\n";
  1119. }
  1120.  
  1121. void writeCloneArgs(raw_ostream &OS) const override {
  1122. OS << "is" << getLowerName() << "Expr, is" << getLowerName()
  1123. << "Expr ? static_cast<void*>(" << getLowerName()
  1124. << "Expr) : " << getLowerName()
  1125. << "Type";
  1126. }
  1127.  
  1128. void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
  1129. // FIXME: move the definition in Sema::InstantiateAttrs to here.
  1130. // In the meantime, aligned attributes are cloned.
  1131. }
  1132.  
  1133. void writeCtorBody(raw_ostream &OS) const override {
  1134. OS << " if (is" << getLowerName() << "Expr)\n";
  1135. OS << " " << getLowerName() << "Expr = reinterpret_cast<Expr *>("
  1136. << getUpperName() << ");\n";
  1137. OS << " else\n";
  1138. OS << " " << getLowerName()
  1139. << "Type = reinterpret_cast<TypeSourceInfo *>(" << getUpperName()
  1140. << ");\n";
  1141. }
  1142.  
  1143. void writeCtorInitializers(raw_ostream &OS) const override {
  1144. OS << "is" << getLowerName() << "Expr(Is" << getUpperName() << "Expr)";
  1145. }
  1146.  
  1147. void writeCtorDefaultInitializers(raw_ostream &OS) const override {
  1148. OS << "is" << getLowerName() << "Expr(false)";
  1149. }
  1150.  
  1151. void writeCtorParameters(raw_ostream &OS) const override {
  1152. OS << "bool Is" << getUpperName() << "Expr, void *" << getUpperName();
  1153. }
  1154.  
  1155. void writeImplicitCtorArgs(raw_ostream &OS) const override {
  1156. OS << "Is" << getUpperName() << "Expr, " << getUpperName();
  1157. }
  1158.  
  1159. void writeDeclarations(raw_ostream &OS) const override {
  1160. OS << "bool is" << getLowerName() << "Expr;\n";
  1161. OS << "union {\n";
  1162. OS << "Expr *" << getLowerName() << "Expr;\n";
  1163. OS << "TypeSourceInfo *" << getLowerName() << "Type;\n";
  1164. OS << "};";
  1165. }
  1166.  
  1167. void writePCHReadArgs(raw_ostream &OS) const override {
  1168. OS << "is" << getLowerName() << "Expr, " << getLowerName() << "Ptr";
  1169. }
  1170.  
  1171. void writePCHReadDecls(raw_ostream &OS) const override {
  1172. OS << " bool is" << getLowerName() << "Expr = Record.readInt();\n";
  1173. OS << " void *" << getLowerName() << "Ptr;\n";
  1174. OS << " if (is" << getLowerName() << "Expr)\n";
  1175. OS << " " << getLowerName() << "Ptr = Record.readExpr();\n";
  1176. OS << " else\n";
  1177. OS << " " << getLowerName()
  1178. << "Ptr = Record.readTypeSourceInfo();\n";
  1179. }
  1180.  
  1181. void writePCHWrite(raw_ostream &OS) const override {
  1182. OS << " Record.push_back(SA->is" << getUpperName() << "Expr());\n";
  1183. OS << " if (SA->is" << getUpperName() << "Expr())\n";
  1184. OS << " Record.AddStmt(SA->get" << getUpperName() << "Expr());\n";
  1185. OS << " else\n";
  1186. OS << " Record.AddTypeSourceInfo(SA->get" << getUpperName()
  1187. << "Type());\n";
  1188. }
  1189.  
  1190. std::string getIsOmitted() const override {
  1191. return "!is" + getLowerName().str() + "Expr || !" + getLowerName().str()
  1192. + "Expr";
  1193. }
  1194.  
  1195. void writeValue(raw_ostream &OS) const override {
  1196. OS << "\";\n";
  1197. OS << " " << getLowerName()
  1198. << "Expr->printPretty(OS, nullptr, Policy);\n";
  1199. OS << " OS << \"";
  1200. }
  1201.  
  1202. - void writeDump(raw_ostream &OS) const override {
  1203. + void writeJSONDump(raw_ostream &OS) const override {
  1204. + // FIXME.
  1205. + }
  1206. +
  1207. + void writeTextDump(raw_ostream &OS) const override {
  1208. OS << " if (!SA->is" << getUpperName() << "Expr())\n";
  1209. OS << " dumpType(SA->get" << getUpperName()
  1210. << "Type()->getType());\n";
  1211. }
  1212.  
  1213. void writeDumpChildren(raw_ostream &OS) const override {
  1214. OS << " if (SA->is" << getUpperName() << "Expr())\n";
  1215. OS << " Visit(SA->get" << getUpperName() << "Expr());\n";
  1216. }
  1217.  
  1218. void writeHasChildren(raw_ostream &OS) const override {
  1219. OS << "SA->is" << getUpperName() << "Expr()";
  1220. }
  1221. };
  1222.  
  1223. class VariadicArgument : public Argument {
  1224. std::string Type, ArgName, ArgSizeName, RangeName;
  1225.  
  1226. protected:
  1227. // Assumed to receive a parameter: raw_ostream OS.
  1228. virtual void writeValueImpl(raw_ostream &OS) const {
  1229. OS << " OS << Val;\n";
  1230. }
  1231. // Assumed to receive a parameter: raw_ostream OS.
  1232. - virtual void writeDumpImpl(raw_ostream &OS) const {
  1233. + virtual void writeTextDumpImpl(raw_ostream &OS) const {
  1234. OS << " OS << \" \" << Val;\n";
  1235. }
  1236. + // Asumed to have a local variable: llvm::json::Array Args.
  1237. + virtual void writeJSONDumpImpl(raw_ostream &OS) const {
  1238. + OS << " Args.push_back(Val);\n";
  1239. + }
  1240.  
  1241. public:
  1242. VariadicArgument(const Record &Arg, StringRef Attr, std::string T)
  1243. : Argument(Arg, Attr), Type(std::move(T)),
  1244. ArgName(getLowerName().str() + "_"), ArgSizeName(ArgName + "Size"),
  1245. RangeName(std::string(getLowerName())) {}
  1246.  
  1247. const std::string &getType() const { return Type; }
  1248. const std::string &getArgName() const { return ArgName; }
  1249. const std::string &getArgSizeName() const { return ArgSizeName; }
  1250. bool isVariadic() const override { return true; }
  1251.  
  1252. void writeAccessors(raw_ostream &OS) const override {
  1253. std::string IteratorType = getLowerName().str() + "_iterator";
  1254. std::string BeginFn = getLowerName().str() + "_begin()";
  1255. std::string EndFn = getLowerName().str() + "_end()";
  1256.  
  1257. OS << " typedef " << Type << "* " << IteratorType << ";\n";
  1258. OS << " " << IteratorType << " " << BeginFn << " const {"
  1259. << " return " << ArgName << "; }\n";
  1260. OS << " " << IteratorType << " " << EndFn << " const {"
  1261. << " return " << ArgName << " + " << ArgSizeName << "; }\n";
  1262. OS << " unsigned " << getLowerName() << "_size() const {"
  1263. << " return " << ArgSizeName << "; }\n";
  1264. OS << " llvm::iterator_range<" << IteratorType << "> " << RangeName
  1265. << "() const { return llvm::make_range(" << BeginFn << ", " << EndFn
  1266. << "); }\n";
  1267. }
  1268.  
  1269. void writeCloneArgs(raw_ostream &OS) const override {
  1270. OS << ArgName << ", " << ArgSizeName;
  1271. }
  1272.  
  1273. void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
  1274. // This isn't elegant, but we have to go through public methods...
  1275. OS << "A->" << getLowerName() << "_begin(), "
  1276. << "A->" << getLowerName() << "_size()";
  1277. }
  1278.  
  1279. void writeASTVisitorTraversal(raw_ostream &OS) const override {
  1280. // FIXME: Traverse the elements.
  1281. }
  1282.  
  1283. void writeCtorBody(raw_ostream &OS) const override {
  1284. OS << " std::copy(" << getUpperName() << ", " << getUpperName() << " + "
  1285. << ArgSizeName << ", " << ArgName << ");\n";
  1286. }
  1287.  
  1288. void writeCtorInitializers(raw_ostream &OS) const override {
  1289. OS << ArgSizeName << "(" << getUpperName() << "Size), "
  1290. << ArgName << "(new (Ctx, 16) " << getType() << "["
  1291. << ArgSizeName << "])";
  1292. }
  1293.  
  1294. void writeCtorDefaultInitializers(raw_ostream &OS) const override {
  1295. OS << ArgSizeName << "(0), " << ArgName << "(nullptr)";
  1296. }
  1297.  
  1298. void writeCtorParameters(raw_ostream &OS) const override {
  1299. OS << getType() << " *" << getUpperName() << ", unsigned "
  1300. << getUpperName() << "Size";
  1301. }
  1302.  
  1303. void writeImplicitCtorArgs(raw_ostream &OS) const override {
  1304. OS << getUpperName() << ", " << getUpperName() << "Size";
  1305. }
  1306.  
  1307. void writeDeclarations(raw_ostream &OS) const override {
  1308. OS << " unsigned " << ArgSizeName << ";\n";
  1309. OS << " " << getType() << " *" << ArgName << ";";
  1310. }
  1311.  
  1312. void writePCHReadDecls(raw_ostream &OS) const override {
  1313. OS << " unsigned " << getLowerName() << "Size = Record.readInt();\n";
  1314. OS << " SmallVector<" << getType() << ", 4> "
  1315. << getLowerName() << ";\n";
  1316. OS << " " << getLowerName() << ".reserve(" << getLowerName()
  1317. << "Size);\n";
  1318.  
  1319. // If we can't store the values in the current type (if it's something
  1320. // like StringRef), store them in a different type and convert the
  1321. // container afterwards.
  1322. std::string StorageType = std::string(getStorageType(getType()));
  1323. std::string StorageName = std::string(getLowerName());
  1324. if (StorageType != getType()) {
  1325. StorageName += "Storage";
  1326. OS << " SmallVector<" << StorageType << ", 4> "
  1327. << StorageName << ";\n";
  1328. OS << " " << StorageName << ".reserve(" << getLowerName()
  1329. << "Size);\n";
  1330. }
  1331.  
  1332. OS << " for (unsigned i = 0; i != " << getLowerName() << "Size; ++i)\n";
  1333. std::string read = ReadPCHRecord(Type);
  1334. OS << " " << StorageName << ".push_back(" << read << ");\n";
  1335.  
  1336. if (StorageType != getType()) {
  1337. OS << " for (unsigned i = 0; i != " << getLowerName() << "Size; ++i)\n";
  1338. OS << " " << getLowerName() << ".push_back("
  1339. << StorageName << "[i]);\n";
  1340. }
  1341. }
  1342.  
  1343. void writePCHReadArgs(raw_ostream &OS) const override {
  1344. OS << getLowerName() << ".data(), " << getLowerName() << "Size";
  1345. }
  1346.  
  1347. void writePCHWrite(raw_ostream &OS) const override {
  1348. OS << " Record.push_back(SA->" << getLowerName() << "_size());\n";
  1349. OS << " for (auto &Val : SA->" << RangeName << "())\n";
  1350. OS << " " << WritePCHRecord(Type, "Val");
  1351. }
  1352.  
  1353. void writeValue(raw_ostream &OS) const override {
  1354. OS << "\";\n";
  1355. OS << " bool isFirst = true;\n"
  1356. << " for (const auto &Val : " << RangeName << "()) {\n"
  1357. << " if (isFirst) isFirst = false;\n"
  1358. << " else OS << \", \";\n";
  1359. writeValueImpl(OS);
  1360. OS << " }\n";
  1361. OS << " OS << \"";
  1362. }
  1363.  
  1364. - void writeDump(raw_ostream &OS) const override {
  1365. + void writeJSONDump(raw_ostream &OS) const override {
  1366. + OS << " for (const auto &Val : A->" << RangeName << "())\n";
  1367. + writeJSONDumpImpl(OS);
  1368. + }
  1369. +
  1370. + void writeTextDump(raw_ostream &OS) const override {
  1371. OS << " for (const auto &Val : SA->" << RangeName << "())\n";
  1372. - writeDumpImpl(OS);
  1373. + writeTextDumpImpl(OS);
  1374. }
  1375. };
  1376.  
  1377. class VariadicParamIdxArgument : public VariadicArgument {
  1378. public:
  1379. VariadicParamIdxArgument(const Record &Arg, StringRef Attr)
  1380. : VariadicArgument(Arg, Attr, "ParamIdx") {}
  1381.  
  1382. public:
  1383. void writeValueImpl(raw_ostream &OS) const override {
  1384. OS << " OS << Val.getSourceIndex();\n";
  1385. }
  1386.  
  1387. - void writeDumpImpl(raw_ostream &OS) const override {
  1388. + void writeJSONDumpImpl(raw_ostream &OS) const override {
  1389. + OS << " Args.push_back(Val.getSourceIndex());\n";
  1390. + }
  1391. +
  1392. + void writeTextDumpImpl(raw_ostream &OS) const override {
  1393. OS << " OS << \" \" << Val.getSourceIndex();\n";
  1394. }
  1395. };
  1396.  
  1397. struct VariadicParamOrParamIdxArgument : public VariadicArgument {
  1398. VariadicParamOrParamIdxArgument(const Record &Arg, StringRef Attr)
  1399. : VariadicArgument(Arg, Attr, "int") {}
  1400. };
  1401.  
  1402. // Unique the enums, but maintain the original declaration ordering.
  1403. std::vector<StringRef>
  1404. uniqueEnumsInOrder(const std::vector<StringRef> &enums) {
  1405. std::vector<StringRef> uniques;
  1406. SmallDenseSet<StringRef, 8> unique_set;
  1407. for (const auto &i : enums) {
  1408. if (unique_set.insert(i).second)
  1409. uniques.push_back(i);
  1410. }
  1411. return uniques;
  1412. }
  1413.  
  1414. class EnumArgument : public Argument {
  1415. std::string type;
  1416. std::vector<StringRef> values, enums, uniques;
  1417.  
  1418. public:
  1419. EnumArgument(const Record &Arg, StringRef Attr)
  1420. : Argument(Arg, Attr), type(std::string(Arg.getValueAsString("Type"))),
  1421. values(Arg.getValueAsListOfStrings("Values")),
  1422. enums(Arg.getValueAsListOfStrings("Enums")),
  1423. uniques(uniqueEnumsInOrder(enums)) {
  1424. // FIXME: Emit a proper error
  1425. assert(!uniques.empty());
  1426. }
  1427.  
  1428. bool isEnumArg() const override { return true; }
  1429.  
  1430. void writeAccessors(raw_ostream &OS) const override {
  1431. OS << " " << type << " get" << getUpperName() << "() const {\n";
  1432. OS << " return " << getLowerName() << ";\n";
  1433. OS << " }";
  1434. }
  1435.  
  1436. void writeCloneArgs(raw_ostream &OS) const override {
  1437. OS << getLowerName();
  1438. }
  1439.  
  1440. void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
  1441. OS << "A->get" << getUpperName() << "()";
  1442. }
  1443. void writeCtorInitializers(raw_ostream &OS) const override {
  1444. OS << getLowerName() << "(" << getUpperName() << ")";
  1445. }
  1446. void writeCtorDefaultInitializers(raw_ostream &OS) const override {
  1447. OS << getLowerName() << "(" << type << "(0))";
  1448. }
  1449. void writeCtorParameters(raw_ostream &OS) const override {
  1450. OS << type << " " << getUpperName();
  1451. }
  1452. void writeDeclarations(raw_ostream &OS) const override {
  1453. auto i = uniques.cbegin(), e = uniques.cend();
  1454. // The last one needs to not have a comma.
  1455. --e;
  1456.  
  1457. OS << "public:\n";
  1458. OS << " enum " << type << " {\n";
  1459. for (; i != e; ++i)
  1460. OS << " " << *i << ",\n";
  1461. OS << " " << *e << "\n";
  1462. OS << " };\n";
  1463. OS << "private:\n";
  1464. OS << " " << type << " " << getLowerName() << ";";
  1465. }
  1466.  
  1467. void writePCHReadDecls(raw_ostream &OS) const override {
  1468. OS << " " << getAttrName() << "Attr::" << type << " " << getLowerName()
  1469. << "(static_cast<" << getAttrName() << "Attr::" << type
  1470. << ">(Record.readInt()));\n";
  1471. }
  1472.  
  1473. void writePCHReadArgs(raw_ostream &OS) const override {
  1474. OS << getLowerName();
  1475. }
  1476.  
  1477. void writePCHWrite(raw_ostream &OS) const override {
  1478. OS << "Record.push_back(SA->get" << getUpperName() << "());\n";
  1479. }
  1480.  
  1481. void writeValue(raw_ostream &OS) const override {
  1482. // FIXME: this isn't 100% correct -- some enum arguments require printing
  1483. // as a string literal, while others require printing as an identifier.
  1484. // Tablegen currently does not distinguish between the two forms.
  1485. OS << "\\\"\" << " << getAttrName() << "Attr::Convert" << type << "ToStr(get"
  1486. << getUpperName() << "()) << \"\\\"";
  1487. }
  1488.  
  1489. - void writeDump(raw_ostream &OS) const override {
  1490. + void writeJSONDump(raw_ostream &OS) const override {
  1491. + OS << " switch(A->get" << getUpperName() << "()) {\n";
  1492. + for (const auto &I : uniques) {
  1493. + OS << " case " << getAttrName() << "Attr::" << I << ":\n";
  1494. + OS << " Args.push_back(\"" << I << "\");\n";
  1495. + OS << " break;\n";
  1496. + }
  1497. + OS << " }\n";
  1498. + }
  1499. +
  1500. + void writeTextDump(raw_ostream &OS) const override {
  1501. OS << " switch(SA->get" << getUpperName() << "()) {\n";
  1502. for (const auto &I : uniques) {
  1503. OS << " case " << getAttrName() << "Attr::" << I << ":\n";
  1504. OS << " OS << \" " << I << "\";\n";
  1505. OS << " break;\n";
  1506. }
  1507. OS << " }\n";
  1508. }
  1509.  
  1510. void writeConversion(raw_ostream &OS, bool Header) const {
  1511. if (Header) {
  1512. OS << " static bool ConvertStrTo" << type << "(StringRef Val, " << type
  1513. << " &Out);\n";
  1514. OS << " static const char *Convert" << type << "ToStr(" << type
  1515. << " Val);\n";
  1516. return;
  1517. }
  1518.  
  1519. OS << "bool " << getAttrName() << "Attr::ConvertStrTo" << type
  1520. << "(StringRef Val, " << type << " &Out) {\n";
  1521. OS << " Optional<" << type << "> R = llvm::StringSwitch<Optional<";
  1522. OS << type << ">>(Val)\n";
  1523. for (size_t I = 0; I < enums.size(); ++I) {
  1524. OS << " .Case(\"" << values[I] << "\", ";
  1525. OS << getAttrName() << "Attr::" << enums[I] << ")\n";
  1526. }
  1527. OS << " .Default(Optional<" << type << ">());\n";
  1528. OS << " if (R) {\n";
  1529. OS << " Out = *R;\n return true;\n }\n";
  1530. OS << " return false;\n";
  1531. OS << "}\n\n";
  1532.  
  1533. // Mapping from enumeration values back to enumeration strings isn't
  1534. // trivial because some enumeration values have multiple named
  1535. // enumerators, such as type_visibility(internal) and
  1536. // type_visibility(hidden) both mapping to TypeVisibilityAttr::Hidden.
  1537. OS << "const char *" << getAttrName() << "Attr::Convert" << type
  1538. << "ToStr(" << type << " Val) {\n"
  1539. << " switch(Val) {\n";
  1540. SmallDenseSet<StringRef, 8> Uniques;
  1541. for (size_t I = 0; I < enums.size(); ++I) {
  1542. if (Uniques.insert(enums[I]).second)
  1543. OS << " case " << getAttrName() << "Attr::" << enums[I]
  1544. << ": return \"" << values[I] << "\";\n";
  1545. }
  1546. OS << " }\n"
  1547. << " llvm_unreachable(\"No enumerator with that value\");\n"
  1548. << "}\n";
  1549. }
  1550. };
  1551.  
  1552. class VariadicEnumArgument: public VariadicArgument {
  1553. std::string type, QualifiedTypeName;
  1554. std::vector<StringRef> values, enums, uniques;
  1555.  
  1556. protected:
  1557. void writeValueImpl(raw_ostream &OS) const override {
  1558. // FIXME: this isn't 100% correct -- some enum arguments require printing
  1559. // as a string literal, while others require printing as an identifier.
  1560. // Tablegen currently does not distinguish between the two forms.
  1561. OS << " OS << \"\\\"\" << " << getAttrName() << "Attr::Convert" << type
  1562. << "ToStr(Val)" << "<< \"\\\"\";\n";
  1563. }
  1564.  
  1565. public:
  1566. VariadicEnumArgument(const Record &Arg, StringRef Attr)
  1567. : VariadicArgument(Arg, Attr,
  1568. std::string(Arg.getValueAsString("Type"))),
  1569. type(std::string(Arg.getValueAsString("Type"))),
  1570. values(Arg.getValueAsListOfStrings("Values")),
  1571. enums(Arg.getValueAsListOfStrings("Enums")),
  1572. uniques(uniqueEnumsInOrder(enums)) {
  1573. QualifiedTypeName = getAttrName().str() + "Attr::" + type;
  1574.  
  1575. // FIXME: Emit a proper error
  1576. assert(!uniques.empty());
  1577. }
  1578.  
  1579. bool isVariadicEnumArg() const override { return true; }
  1580.  
  1581. void writeDeclarations(raw_ostream &OS) const override {
  1582. auto i = uniques.cbegin(), e = uniques.cend();
  1583. // The last one needs to not have a comma.
  1584. --e;
  1585.  
  1586. OS << "public:\n";
  1587. OS << " enum " << type << " {\n";
  1588. for (; i != e; ++i)
  1589. OS << " " << *i << ",\n";
  1590. OS << " " << *e << "\n";
  1591. OS << " };\n";
  1592. OS << "private:\n";
  1593.  
  1594. VariadicArgument::writeDeclarations(OS);
  1595. }
  1596.  
  1597. - void writeDump(raw_ostream &OS) const override {
  1598. + void writeJSONDump(raw_ostream &OS) const override {
  1599. + OS << " for (" << getAttrName() << "Attr::" << getLowerName()
  1600. + << "_iterator I = A->" << getLowerName() << "_begin(), E = A->"
  1601. + << getLowerName() << "_end(); I != E; ++I) {\n";
  1602. + OS << " switch(*I) {\n";
  1603. + for (const auto &UI : uniques) {
  1604. + OS << " case " << getAttrName() << "Attr::" << UI << ":\n";
  1605. + OS << " Args.push_back(\"" << UI << "\");\n";
  1606. + OS << " break;\n";
  1607. + }
  1608. + OS << " }\n";
  1609. + OS << " }\n";
  1610. + }
  1611. +
  1612. + void writeTextDump(raw_ostream &OS) const override {
  1613. OS << " for (" << getAttrName() << "Attr::" << getLowerName()
  1614. << "_iterator I = SA->" << getLowerName() << "_begin(), E = SA->"
  1615. << getLowerName() << "_end(); I != E; ++I) {\n";
  1616. OS << " switch(*I) {\n";
  1617. for (const auto &UI : uniques) {
  1618. OS << " case " << getAttrName() << "Attr::" << UI << ":\n";
  1619. OS << " OS << \" " << UI << "\";\n";
  1620. OS << " break;\n";
  1621. }
  1622. OS << " }\n";
  1623. OS << " }\n";
  1624. }
  1625.  
  1626. void writePCHReadDecls(raw_ostream &OS) const override {
  1627. OS << " unsigned " << getLowerName() << "Size = Record.readInt();\n";
  1628. OS << " SmallVector<" << QualifiedTypeName << ", 4> " << getLowerName()
  1629. << ";\n";
  1630. OS << " " << getLowerName() << ".reserve(" << getLowerName()
  1631. << "Size);\n";
  1632. OS << " for (unsigned i = " << getLowerName() << "Size; i; --i)\n";
  1633. OS << " " << getLowerName() << ".push_back(" << "static_cast<"
  1634. << QualifiedTypeName << ">(Record.readInt()));\n";
  1635. }
  1636.  
  1637. void writePCHWrite(raw_ostream &OS) const override {
  1638. OS << " Record.push_back(SA->" << getLowerName() << "_size());\n";
  1639. OS << " for (" << getAttrName() << "Attr::" << getLowerName()
  1640. << "_iterator i = SA->" << getLowerName() << "_begin(), e = SA->"
  1641. << getLowerName() << "_end(); i != e; ++i)\n";
  1642. OS << " " << WritePCHRecord(QualifiedTypeName, "(*i)");
  1643. }
  1644.  
  1645. void writeConversion(raw_ostream &OS, bool Header) const {
  1646. if (Header) {
  1647. OS << " static bool ConvertStrTo" << type << "(StringRef Val, " << type
  1648. << " &Out);\n";
  1649. OS << " static const char *Convert" << type << "ToStr(" << type
  1650. << " Val);\n";
  1651. return;
  1652. }
  1653.  
  1654. OS << "bool " << getAttrName() << "Attr::ConvertStrTo" << type
  1655. << "(StringRef Val, ";
  1656. OS << type << " &Out) {\n";
  1657. OS << " Optional<" << type << "> R = llvm::StringSwitch<Optional<";
  1658. OS << type << ">>(Val)\n";
  1659. for (size_t I = 0; I < enums.size(); ++I) {
  1660. OS << " .Case(\"" << values[I] << "\", ";
  1661. OS << getAttrName() << "Attr::" << enums[I] << ")\n";
  1662. }
  1663. OS << " .Default(Optional<" << type << ">());\n";
  1664. OS << " if (R) {\n";
  1665. OS << " Out = *R;\n return true;\n }\n";
  1666. OS << " return false;\n";
  1667. OS << "}\n\n";
  1668.  
  1669. OS << "const char *" << getAttrName() << "Attr::Convert" << type
  1670. << "ToStr(" << type << " Val) {\n"
  1671. << " switch(Val) {\n";
  1672. SmallDenseSet<StringRef, 8> Uniques;
  1673. for (size_t I = 0; I < enums.size(); ++I) {
  1674. if (Uniques.insert(enums[I]).second)
  1675. OS << " case " << getAttrName() << "Attr::" << enums[I]
  1676. << ": return \"" << values[I] << "\";\n";
  1677. }
  1678. OS << " }\n"
  1679. << " llvm_unreachable(\"No enumerator with that value\");\n"
  1680. << "}\n";
  1681. }
  1682. };
  1683.  
  1684. class VersionArgument : public Argument {
  1685. public:
  1686. VersionArgument(const Record &Arg, StringRef Attr)
  1687. : Argument(Arg, Attr)
  1688. {}
  1689.  
  1690. void writeAccessors(raw_ostream &OS) const override {
  1691. OS << " VersionTuple get" << getUpperName() << "() const {\n";
  1692. OS << " return " << getLowerName() << ";\n";
  1693. OS << " }\n";
  1694. OS << " void set" << getUpperName()
  1695. << "(ASTContext &C, VersionTuple V) {\n";
  1696. OS << " " << getLowerName() << " = V;\n";
  1697. OS << " }";
  1698. }
  1699.  
  1700. void writeCloneArgs(raw_ostream &OS) const override {
  1701. OS << "get" << getUpperName() << "()";
  1702. }
  1703.  
  1704. void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
  1705. OS << "A->get" << getUpperName() << "()";
  1706. }
  1707.  
  1708. void writeCtorInitializers(raw_ostream &OS) const override {
  1709. OS << getLowerName() << "(" << getUpperName() << ")";
  1710. }
  1711.  
  1712. void writeCtorDefaultInitializers(raw_ostream &OS) const override {
  1713. OS << getLowerName() << "()";
  1714. }
  1715.  
  1716. void writeCtorParameters(raw_ostream &OS) const override {
  1717. OS << "VersionTuple " << getUpperName();
  1718. }
  1719.  
  1720. void writeDeclarations(raw_ostream &OS) const override {
  1721. OS << "VersionTuple " << getLowerName() << ";\n";
  1722. }
  1723.  
  1724. void writePCHReadDecls(raw_ostream &OS) const override {
  1725. OS << " VersionTuple " << getLowerName()
  1726. << "= Record.readVersionTuple();\n";
  1727. }
  1728.  
  1729. void writePCHReadArgs(raw_ostream &OS) const override {
  1730. OS << getLowerName();
  1731. }
  1732.  
  1733. void writePCHWrite(raw_ostream &OS) const override {
  1734. OS << " Record.AddVersionTuple(SA->get" << getUpperName() << "());\n";
  1735. }
  1736.  
  1737. void writeValue(raw_ostream &OS) const override {
  1738. OS << getLowerName() << "=\" << get" << getUpperName() << "() << \"";
  1739. }
  1740.  
  1741. - void writeDump(raw_ostream &OS) const override {
  1742. + void writeJSONDump(raw_ostream &OS) const override {
  1743. + OS << " Args.push_back(A->get" << getUpperName()
  1744. + << "().getAsString());\n";
  1745. + }
  1746. + void writeTextDump(raw_ostream &OS) const override {
  1747. OS << " OS << \" \" << SA->get" << getUpperName() << "();\n";
  1748. }
  1749. };
  1750.  
  1751. class ExprArgument : public SimpleArgument {
  1752. public:
  1753. ExprArgument(const Record &Arg, StringRef Attr)
  1754. : SimpleArgument(Arg, Attr, "Expr *")
  1755. {}
  1756.  
  1757. void writeASTVisitorTraversal(raw_ostream &OS) const override {
  1758. OS << " if (!"
  1759. << "getDerived().TraverseStmt(A->get" << getUpperName() << "()))\n";
  1760. OS << " return false;\n";
  1761. }
  1762.  
  1763. void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
  1764. OS << "tempInst" << getUpperName();
  1765. }
  1766.  
  1767. void writeTemplateInstantiation(raw_ostream &OS) const override {
  1768. OS << " " << getType() << " tempInst" << getUpperName() << ";\n";
  1769. OS << " {\n";
  1770. OS << " EnterExpressionEvaluationContext "
  1771. << "Unevaluated(S, Sema::ExpressionEvaluationContext::Unevaluated);\n";
  1772. OS << " ExprResult " << "Result = S.SubstExpr("
  1773. << "A->get" << getUpperName() << "(), TemplateArgs);\n";
  1774. OS << " tempInst" << getUpperName() << " = "
  1775. << "Result.getAs<Expr>();\n";
  1776. OS << " }\n";
  1777. }
  1778.  
  1779. - void writeDump(raw_ostream &OS) const override {}
  1780. + void writeJSONDump(raw_ostream &) const override {}
  1781. + void writeTextDump(raw_ostream &OS) const override {}
  1782.  
  1783. void writeDumpChildren(raw_ostream &OS) const override {
  1784. OS << " Visit(SA->get" << getUpperName() << "());\n";
  1785. }
  1786.  
  1787. void writeHasChildren(raw_ostream &OS) const override { OS << "true"; }
  1788. };
  1789.  
  1790. class VariadicExprArgument : public VariadicArgument {
  1791. public:
  1792. VariadicExprArgument(const Record &Arg, StringRef Attr)
  1793. : VariadicArgument(Arg, Attr, "Expr *")
  1794. {}
  1795.  
  1796. void writeASTVisitorTraversal(raw_ostream &OS) const override {
  1797. OS << " {\n";
  1798. OS << " " << getType() << " *I = A->" << getLowerName()
  1799. << "_begin();\n";
  1800. OS << " " << getType() << " *E = A->" << getLowerName()
  1801. << "_end();\n";
  1802. OS << " for (; I != E; ++I) {\n";
  1803. OS << " if (!getDerived().TraverseStmt(*I))\n";
  1804. OS << " return false;\n";
  1805. OS << " }\n";
  1806. OS << " }\n";
  1807. }
  1808.  
  1809. void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
  1810. OS << "tempInst" << getUpperName() << ", "
  1811. << "A->" << getLowerName() << "_size()";
  1812. }
  1813.  
  1814. void writeTemplateInstantiation(raw_ostream &OS) const override {
  1815. OS << " auto *tempInst" << getUpperName()
  1816. << " = new (C, 16) " << getType()
  1817. << "[A->" << getLowerName() << "_size()];\n";
  1818. OS << " {\n";
  1819. OS << " EnterExpressionEvaluationContext "
  1820. << "Unevaluated(S, Sema::ExpressionEvaluationContext::Unevaluated);\n";
  1821. OS << " " << getType() << " *TI = tempInst" << getUpperName()
  1822. << ";\n";
  1823. OS << " " << getType() << " *I = A->" << getLowerName()
  1824. << "_begin();\n";
  1825. OS << " " << getType() << " *E = A->" << getLowerName()
  1826. << "_end();\n";
  1827. OS << " for (; I != E; ++I, ++TI) {\n";
  1828. OS << " ExprResult Result = S.SubstExpr(*I, TemplateArgs);\n";
  1829. OS << " *TI = Result.getAs<Expr>();\n";
  1830. OS << " }\n";
  1831. OS << " }\n";
  1832. }
  1833.  
  1834. - void writeDump(raw_ostream &OS) const override {}
  1835. + void writeJSONDump(raw_ostream &) const override {}
  1836. + void writeTextDump(raw_ostream &OS) const override {}
  1837.  
  1838. void writeDumpChildren(raw_ostream &OS) const override {
  1839. OS << " for (" << getAttrName() << "Attr::" << getLowerName()
  1840. << "_iterator I = SA->" << getLowerName() << "_begin(), E = SA->"
  1841. << getLowerName() << "_end(); I != E; ++I)\n";
  1842. OS << " Visit(*I);\n";
  1843. }
  1844.  
  1845. void writeHasChildren(raw_ostream &OS) const override {
  1846. OS << "SA->" << getLowerName() << "_begin() != "
  1847. << "SA->" << getLowerName() << "_end()";
  1848. }
  1849. };
  1850.  
  1851. class VariadicIdentifierArgument : public VariadicArgument {
  1852. public:
  1853. VariadicIdentifierArgument(const Record &Arg, StringRef Attr)
  1854. : VariadicArgument(Arg, Attr, "IdentifierInfo *")
  1855. {}
  1856. +
  1857. + void writeJSONDumpImpl(raw_ostream &OS) const override {
  1858. + OS << " Args.push_back(Val ? Val->getName() : \"\");\n";
  1859. + }
  1860. };
  1861.  
  1862. class VariadicStringArgument : public VariadicArgument {
  1863. public:
  1864. VariadicStringArgument(const Record &Arg, StringRef Attr)
  1865. : VariadicArgument(Arg, Attr, "StringRef")
  1866. {}
  1867.  
  1868. void writeCtorBody(raw_ostream &OS) const override {
  1869. OS << " for (size_t I = 0, E = " << getArgSizeName() << "; I != E;\n"
  1870. " ++I) {\n"
  1871. " StringRef Ref = " << getUpperName() << "[I];\n"
  1872. " if (!Ref.empty()) {\n"
  1873. " char *Mem = new (Ctx, 1) char[Ref.size()];\n"
  1874. " std::memcpy(Mem, Ref.data(), Ref.size());\n"
  1875. " " << getArgName() << "[I] = StringRef(Mem, Ref.size());\n"
  1876. " }\n"
  1877. " }\n";
  1878. }
  1879.  
  1880. void writeValueImpl(raw_ostream &OS) const override {
  1881. OS << " OS << \"\\\"\" << Val << \"\\\"\";\n";
  1882. }
  1883. };
  1884.  
  1885. class TypeArgument : public SimpleArgument {
  1886. public:
  1887. TypeArgument(const Record &Arg, StringRef Attr)
  1888. : SimpleArgument(Arg, Attr, "TypeSourceInfo *")
  1889. {}
  1890.  
  1891. void writeAccessors(raw_ostream &OS) const override {
  1892. OS << " QualType get" << getUpperName() << "() const {\n";
  1893. OS << " return " << getLowerName() << "->getType();\n";
  1894. OS << " }";
  1895. OS << " " << getType() << " get" << getUpperName() << "Loc() const {\n";
  1896. OS << " return " << getLowerName() << ";\n";
  1897. OS << " }";
  1898. }
  1899.  
  1900. void writeASTVisitorTraversal(raw_ostream &OS) const override {
  1901. OS << " if (auto *TSI = A->get" << getUpperName() << "Loc())\n";
  1902. OS << " if (!getDerived().TraverseTypeLoc(TSI->getTypeLoc()))\n";
  1903. OS << " return false;\n";
  1904. }
  1905.  
  1906. void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
  1907. OS << "A->get" << getUpperName() << "Loc()";
  1908. }
  1909.  
  1910. void writePCHWrite(raw_ostream &OS) const override {
  1911. OS << " "
  1912. << WritePCHRecord(getType(),
  1913. "SA->get" + std::string(getUpperName()) + "Loc()");
  1914. }
  1915. };
  1916.  
  1917. } // end anonymous namespace
  1918.  
  1919. static std::unique_ptr<Argument>
  1920. createArgument(const Record &Arg, StringRef Attr,
  1921. const Record *Search = nullptr) {
  1922. if (!Search)
  1923. Search = &Arg;
  1924.  
  1925. std::unique_ptr<Argument> Ptr;
  1926. llvm::StringRef ArgName = Search->getName();
  1927.  
  1928. if (ArgName == "AlignedArgument")
  1929. Ptr = std::make_unique<AlignedArgument>(Arg, Attr);
  1930. else if (ArgName == "EnumArgument")
  1931. Ptr = std::make_unique<EnumArgument>(Arg, Attr);
  1932. else if (ArgName == "ExprArgument")
  1933. Ptr = std::make_unique<ExprArgument>(Arg, Attr);
  1934. else if (ArgName == "DeclArgument")
  1935. Ptr = std::make_unique<SimpleArgument>(
  1936. Arg, Attr, (Arg.getValueAsDef("Kind")->getName() + "Decl *").str());
  1937. else if (ArgName == "IdentifierArgument")
  1938. Ptr = std::make_unique<SimpleArgument>(Arg, Attr, "IdentifierInfo *");
  1939. else if (ArgName == "DefaultBoolArgument")
  1940. Ptr = std::make_unique<DefaultSimpleArgument>(
  1941. Arg, Attr, "bool", Arg.getValueAsBit("Default"));
  1942. else if (ArgName == "BoolArgument")
  1943. Ptr = std::make_unique<SimpleArgument>(Arg, Attr, "bool");
  1944. else if (ArgName == "DefaultIntArgument")
  1945. Ptr = std::make_unique<DefaultSimpleArgument>(
  1946. Arg, Attr, "int", Arg.getValueAsInt("Default"));
  1947. else if (ArgName == "IntArgument")
  1948. Ptr = std::make_unique<SimpleArgument>(Arg, Attr, "int");
  1949. else if (ArgName == "StringArgument")
  1950. Ptr = std::make_unique<StringArgument>(Arg, Attr);
  1951. else if (ArgName == "TypeArgument")
  1952. Ptr = std::make_unique<TypeArgument>(Arg, Attr);
  1953. else if (ArgName == "UnsignedArgument")
  1954. Ptr = std::make_unique<SimpleArgument>(Arg, Attr, "unsigned");
  1955. else if (ArgName == "VariadicUnsignedArgument")
  1956. Ptr = std::make_unique<VariadicArgument>(Arg, Attr, "unsigned");
  1957. else if (ArgName == "VariadicStringArgument")
  1958. Ptr = std::make_unique<VariadicStringArgument>(Arg, Attr);
  1959. else if (ArgName == "VariadicEnumArgument")
  1960. Ptr = std::make_unique<VariadicEnumArgument>(Arg, Attr);
  1961. else if (ArgName == "VariadicExprArgument")
  1962. Ptr = std::make_unique<VariadicExprArgument>(Arg, Attr);
  1963. else if (ArgName == "VariadicParamIdxArgument")
  1964. Ptr = std::make_unique<VariadicParamIdxArgument>(Arg, Attr);
  1965. else if (ArgName == "VariadicParamOrParamIdxArgument")
  1966. Ptr = std::make_unique<VariadicParamOrParamIdxArgument>(Arg, Attr);
  1967. else if (ArgName == "ParamIdxArgument")
  1968. Ptr = std::make_unique<SimpleArgument>(Arg, Attr, "ParamIdx");
  1969. else if (ArgName == "VariadicIdentifierArgument")
  1970. Ptr = std::make_unique<VariadicIdentifierArgument>(Arg, Attr);
  1971. else if (ArgName == "VersionArgument")
  1972. Ptr = std::make_unique<VersionArgument>(Arg, Attr);
  1973. else if (ArgName == "OMPTraitInfoArgument")
  1974. Ptr = std::make_unique<SimpleArgument>(Arg, Attr, "OMPTraitInfo *");
  1975.  
  1976. if (!Ptr) {
  1977. // Search in reverse order so that the most-derived type is handled first.
  1978. ArrayRef<std::pair<Record*, SMRange>> Bases = Search->getSuperClasses();
  1979. for (const auto &Base : llvm::reverse(Bases)) {
  1980. if ((Ptr = createArgument(Arg, Attr, Base.first)))
  1981. break;
  1982. }
  1983. }
  1984.  
  1985. if (Ptr && Arg.getValueAsBit("Optional"))
  1986. Ptr->setOptional(true);
  1987.  
  1988. if (Ptr && Arg.getValueAsBit("Fake"))
  1989. Ptr->setFake(true);
  1990.  
  1991. return Ptr;
  1992. }
  1993.  
  1994. static void writeAvailabilityValue(raw_ostream &OS) {
  1995. OS << "\" << getPlatform()->getName();\n"
  1996. << " if (getStrict()) OS << \", strict\";\n"
  1997. << " if (!getIntroduced().empty()) OS << \", introduced=\" << getIntroduced();\n"
  1998. << " if (!getDeprecated().empty()) OS << \", deprecated=\" << getDeprecated();\n"
  1999. << " if (!getObsoleted().empty()) OS << \", obsoleted=\" << getObsoleted();\n"
  2000. << " if (getUnavailable()) OS << \", unavailable\";\n"
  2001. << " OS << \"";
  2002. }
  2003.  
  2004. static void writeDeprecatedAttrValue(raw_ostream &OS, std::string &Variety) {
  2005. OS << "\\\"\" << getMessage() << \"\\\"\";\n";
  2006. // Only GNU deprecated has an optional fixit argument at the second position.
  2007. if (Variety == "GNU")
  2008. OS << " if (!getReplacement().empty()) OS << \", \\\"\""
  2009. " << getReplacement() << \"\\\"\";\n";
  2010. OS << " OS << \"";
  2011. }
  2012.  
  2013. static void writeGetSpellingFunction(const Record &R, raw_ostream &OS) {
  2014. std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(R);
  2015.  
  2016. OS << "const char *" << R.getName() << "Attr::getSpelling() const {\n";
  2017. if (Spellings.empty()) {
  2018. OS << " return \"(No spelling)\";\n}\n\n";
  2019. return;
  2020. }
  2021.  
  2022. OS << " switch (getAttributeSpellingListIndex()) {\n"
  2023. " default:\n"
  2024. " llvm_unreachable(\"Unknown attribute spelling!\");\n"
  2025. " return \"(No spelling)\";\n";
  2026.  
  2027. for (unsigned I = 0; I < Spellings.size(); ++I)
  2028. OS << " case " << I << ":\n"
  2029. " return \"" << Spellings[I].name() << "\";\n";
  2030. // End of the switch statement.
  2031. OS << " }\n";
  2032. // End of the getSpelling function.
  2033. OS << "}\n\n";
  2034. }
  2035.  
  2036. static void
  2037. writePrettyPrintFunction(const Record &R,
  2038. const std::vector<std::unique_ptr<Argument>> &Args,
  2039. raw_ostream &OS) {
  2040. std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(R);
  2041.  
  2042. OS << "void " << R.getName() << "Attr::printPretty("
  2043. << "raw_ostream &OS, const PrintingPolicy &Policy) const {\n";
  2044.  
  2045. if (Spellings.empty()) {
  2046. OS << "}\n\n";
  2047. return;
  2048. }
  2049.  
  2050. OS << " switch (getAttributeSpellingListIndex()) {\n"
  2051. " default:\n"
  2052. " llvm_unreachable(\"Unknown attribute spelling!\");\n"
  2053. " break;\n";
  2054.  
  2055. for (unsigned I = 0; I < Spellings.size(); ++ I) {
  2056. llvm::SmallString<16> Prefix;
  2057. llvm::SmallString<8> Suffix;
  2058. // The actual spelling of the name and namespace (if applicable)
  2059. // of an attribute without considering prefix and suffix.
  2060. llvm::SmallString<64> Spelling;
  2061. std::string Name = Spellings[I].name();
  2062. std::string Variety = Spellings[I].variety();
  2063.  
  2064. if (Variety == "GNU") {
  2065. Prefix = " __attribute__((";
  2066. Suffix = "))";
  2067. } else if (Variety == "CXX11" || Variety == "C2x") {
  2068. Prefix = " [[";
  2069. Suffix = "]]";
  2070. std::string Namespace = Spellings[I].nameSpace();
  2071. if (!Namespace.empty()) {
  2072. Spelling += Namespace;
  2073. Spelling += "::";
  2074. }
  2075. } else if (Variety == "Declspec") {
  2076. Prefix = " __declspec(";
  2077. Suffix = ")";
  2078. } else if (Variety == "Microsoft") {
  2079. Prefix = "[";
  2080. Suffix = "]";
  2081. } else if (Variety == "Keyword") {
  2082. Prefix = " ";
  2083. Suffix = "";
  2084. } else if (Variety == "Pragma") {
  2085. Prefix = "#pragma ";
  2086. Suffix = "\n";
  2087. std::string Namespace = Spellings[I].nameSpace();
  2088. if (!Namespace.empty()) {
  2089. Spelling += Namespace;
  2090. Spelling += " ";
  2091. }
  2092. } else {
  2093. llvm_unreachable("Unknown attribute syntax variety!");
  2094. }
  2095.  
  2096. Spelling += Name;
  2097.  
  2098. OS <<
  2099. " case " << I << " : {\n"
  2100. " OS << \"" << Prefix << Spelling;
  2101.  
  2102. if (Variety == "Pragma") {
  2103. OS << "\";\n";
  2104. OS << " printPrettyPragma(OS, Policy);\n";
  2105. OS << " OS << \"\\n\";";
  2106. OS << " break;\n";
  2107. OS << " }\n";
  2108. continue;
  2109. }
  2110.  
  2111. if (Spelling == "availability") {
  2112. OS << "(";
  2113. writeAvailabilityValue(OS);
  2114. OS << ")";
  2115. } else if (Spelling == "deprecated" || Spelling == "gnu::deprecated") {
  2116. OS << "(";
  2117. writeDeprecatedAttrValue(OS, Variety);
  2118. OS << ")";
  2119. } else {
  2120. // To avoid printing parentheses around an empty argument list or
  2121. // printing spurious commas at the end of an argument list, we need to
  2122. // determine where the last provided non-fake argument is.
  2123. unsigned NonFakeArgs = 0;
  2124. unsigned TrailingOptArgs = 0;
  2125. bool FoundNonOptArg = false;
  2126. for (const auto &arg : llvm::reverse(Args)) {
  2127. if (arg->isFake())
  2128. continue;
  2129. ++NonFakeArgs;
  2130. if (FoundNonOptArg)
  2131. continue;
  2132. // FIXME: arg->getIsOmitted() == "false" means we haven't implemented
  2133. // any way to detect whether the argument was omitted.
  2134. if (!arg->isOptional() || arg->getIsOmitted() == "false") {
  2135. FoundNonOptArg = true;
  2136. continue;
  2137. }
  2138. if (!TrailingOptArgs++)
  2139. OS << "\";\n"
  2140. << " unsigned TrailingOmittedArgs = 0;\n";
  2141. OS << " if (" << arg->getIsOmitted() << ")\n"
  2142. << " ++TrailingOmittedArgs;\n";
  2143. }
  2144. if (TrailingOptArgs)
  2145. OS << " OS << \"";
  2146. if (TrailingOptArgs < NonFakeArgs)
  2147. OS << "(";
  2148. else if (TrailingOptArgs)
  2149. OS << "\";\n"
  2150. << " if (TrailingOmittedArgs < " << NonFakeArgs << ")\n"
  2151. << " OS << \"(\";\n"
  2152. << " OS << \"";
  2153. unsigned ArgIndex = 0;
  2154. for (const auto &arg : Args) {
  2155. if (arg->isFake())
  2156. continue;
  2157. if (ArgIndex) {
  2158. if (ArgIndex >= NonFakeArgs - TrailingOptArgs)
  2159. OS << "\";\n"
  2160. << " if (" << ArgIndex << " < " << NonFakeArgs
  2161. << " - TrailingOmittedArgs)\n"
  2162. << " OS << \", \";\n"
  2163. << " OS << \"";
  2164. else
  2165. OS << ", ";
  2166. }
  2167. std::string IsOmitted = arg->getIsOmitted();
  2168. if (arg->isOptional() && IsOmitted != "false")
  2169. OS << "\";\n"
  2170. << " if (!(" << IsOmitted << ")) {\n"
  2171. << " OS << \"";
  2172. arg->writeValue(OS);
  2173. if (arg->isOptional() && IsOmitted != "false")
  2174. OS << "\";\n"
  2175. << " }\n"
  2176. << " OS << \"";
  2177. ++ArgIndex;
  2178. }
  2179. if (TrailingOptArgs < NonFakeArgs)
  2180. OS << ")";
  2181. else if (TrailingOptArgs)
  2182. OS << "\";\n"
  2183. << " if (TrailingOmittedArgs < " << NonFakeArgs << ")\n"
  2184. << " OS << \")\";\n"
  2185. << " OS << \"";
  2186. }
  2187.  
  2188. OS << Suffix + "\";\n";
  2189.  
  2190. OS <<
  2191. " break;\n"
  2192. " }\n";
  2193. }
  2194.  
  2195. // End of the switch statement.
  2196. OS << "}\n";
  2197. // End of the print function.
  2198. OS << "}\n\n";
  2199. }
  2200.  
  2201. /// Return the index of a spelling in a spelling list.
  2202. static unsigned
  2203. getSpellingListIndex(const std::vector<FlattenedSpelling> &SpellingList,
  2204. const FlattenedSpelling &Spelling) {
  2205. assert(!SpellingList.empty() && "Spelling list is empty!");
  2206.  
  2207. for (unsigned Index = 0; Index < SpellingList.size(); ++Index) {
  2208. const FlattenedSpelling &S = SpellingList[Index];
  2209. if (S.variety() != Spelling.variety())
  2210. continue;
  2211. if (S.nameSpace() != Spelling.nameSpace())
  2212. continue;
  2213. if (S.name() != Spelling.name())
  2214. continue;
  2215.  
  2216. return Index;
  2217. }
  2218.  
  2219. llvm_unreachable("Unknown spelling!");
  2220. }
  2221.  
  2222. static void writeAttrAccessorDefinition(const Record &R, raw_ostream &OS) {
  2223. std::vector<Record*> Accessors = R.getValueAsListOfDefs("Accessors");
  2224. if (Accessors.empty())
  2225. return;
  2226.  
  2227. const std::vector<FlattenedSpelling> SpellingList = GetFlattenedSpellings(R);
  2228. assert(!SpellingList.empty() &&
  2229. "Attribute with empty spelling list can't have accessors!");
  2230. for (const auto *Accessor : Accessors) {
  2231. const StringRef Name = Accessor->getValueAsString("Name");
  2232. std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(*Accessor);
  2233.  
  2234. OS << " bool " << Name
  2235. << "() const { return getAttributeSpellingListIndex() == ";
  2236. for (unsigned Index = 0; Index < Spellings.size(); ++Index) {
  2237. OS << getSpellingListIndex(SpellingList, Spellings[Index]);
  2238. if (Index != Spellings.size() - 1)
  2239. OS << " ||\n getAttributeSpellingListIndex() == ";
  2240. else
  2241. OS << "; }\n";
  2242. }
  2243. }
  2244. }
  2245.  
  2246. static bool
  2247. SpellingNamesAreCommon(const std::vector<FlattenedSpelling>& Spellings) {
  2248. assert(!Spellings.empty() && "An empty list of spellings was provided");
  2249. std::string FirstName =
  2250. std::string(NormalizeNameForSpellingComparison(Spellings.front().name()));
  2251. for (const auto &Spelling :
  2252. llvm::make_range(std::next(Spellings.begin()), Spellings.end())) {
  2253. std::string Name =
  2254. std::string(NormalizeNameForSpellingComparison(Spelling.name()));
  2255. if (Name != FirstName)
  2256. return false;
  2257. }
  2258. return true;
  2259. }
  2260.  
  2261. typedef std::map<unsigned, std::string> SemanticSpellingMap;
  2262. static std::string
  2263. CreateSemanticSpellings(const std::vector<FlattenedSpelling> &Spellings,
  2264. SemanticSpellingMap &Map) {
  2265. // The enumerants are automatically generated based on the variety,
  2266. // namespace (if present) and name for each attribute spelling. However,
  2267. // care is taken to avoid trampling on the reserved namespace due to
  2268. // underscores.
  2269. std::string Ret(" enum Spelling {\n");
  2270. std::set<std::string> Uniques;
  2271. unsigned Idx = 0;
  2272.  
  2273. // If we have a need to have this many spellings we likely need to add an
  2274. // extra bit to the SpellingIndex in AttributeCommonInfo, then increase the
  2275. // value of SpellingNotCalculated there and here.
  2276. assert(Spellings.size() < 15 &&
  2277. "Too many spellings, would step on SpellingNotCalculated in "
  2278. "AttributeCommonInfo");
  2279. for (auto I = Spellings.begin(), E = Spellings.end(); I != E; ++I, ++Idx) {
  2280. const FlattenedSpelling &S = *I;
  2281. const std::string &Variety = S.variety();
  2282. const std::string &Spelling = S.name();
  2283. const std::string &Namespace = S.nameSpace();
  2284. std::string EnumName;
  2285.  
  2286. EnumName += (Variety + "_");
  2287. if (!Namespace.empty())
  2288. EnumName += (NormalizeNameForSpellingComparison(Namespace).str() +
  2289. "_");
  2290. EnumName += NormalizeNameForSpellingComparison(Spelling);
  2291.  
  2292. // Even if the name is not unique, this spelling index corresponds to a
  2293. // particular enumerant name that we've calculated.
  2294. Map[Idx] = EnumName;
  2295.  
  2296. // Since we have been stripping underscores to avoid trampling on the
  2297. // reserved namespace, we may have inadvertently created duplicate
  2298. // enumerant names. These duplicates are not considered part of the
  2299. // semantic spelling, and can be elided.
  2300. if (Uniques.find(EnumName) != Uniques.end())
  2301. continue;
  2302.  
  2303. Uniques.insert(EnumName);
  2304. if (I != Spellings.begin())
  2305. Ret += ",\n";
  2306. // Duplicate spellings are not considered part of the semantic spelling
  2307. // enumeration, but the spelling index and semantic spelling values are
  2308. // meant to be equivalent, so we must specify a concrete value for each
  2309. // enumerator.
  2310. Ret += " " + EnumName + " = " + llvm::utostr(Idx);
  2311. }
  2312. Ret += ",\n SpellingNotCalculated = 15\n";
  2313. Ret += "\n };\n\n";
  2314. return Ret;
  2315. }
  2316.  
  2317. void WriteSemanticSpellingSwitch(const std::string &VarName,
  2318. const SemanticSpellingMap &Map,
  2319. raw_ostream &OS) {
  2320. OS << " switch (" << VarName << ") {\n default: "
  2321. << "llvm_unreachable(\"Unknown spelling list index\");\n";
  2322. for (const auto &I : Map)
  2323. OS << " case " << I.first << ": return " << I.second << ";\n";
  2324. OS << " }\n";
  2325. }
  2326.  
  2327. // Emits the LateParsed property for attributes.
  2328. static void emitClangAttrLateParsedList(RecordKeeper &Records, raw_ostream &OS) {
  2329. OS << "#if defined(CLANG_ATTR_LATE_PARSED_LIST)\n";
  2330. std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr");
  2331.  
  2332. for (const auto *Attr : Attrs) {
  2333. bool LateParsed = Attr->getValueAsBit("LateParsed");
  2334.  
  2335. if (LateParsed) {
  2336. std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(*Attr);
  2337.  
  2338. // FIXME: Handle non-GNU attributes
  2339. for (const auto &I : Spellings) {
  2340. if (I.variety() != "GNU")
  2341. continue;
  2342. OS << ".Case(\"" << I.name() << "\", " << LateParsed << ")\n";
  2343. }
  2344. }
  2345. }
  2346. OS << "#endif // CLANG_ATTR_LATE_PARSED_LIST\n\n";
  2347. }
  2348.  
  2349. static bool hasGNUorCXX11Spelling(const Record &Attribute) {
  2350. std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(Attribute);
  2351. for (const auto &I : Spellings) {
  2352. if (I.variety() == "GNU" || I.variety() == "CXX11")
  2353. return true;
  2354. }
  2355. return false;
  2356. }
  2357.  
  2358. namespace {
  2359.  
  2360. struct AttributeSubjectMatchRule {
  2361. const Record *MetaSubject;
  2362. const Record *Constraint;
  2363.  
  2364. AttributeSubjectMatchRule(const Record *MetaSubject, const Record *Constraint)
  2365. : MetaSubject(MetaSubject), Constraint(Constraint) {
  2366. assert(MetaSubject && "Missing subject");
  2367. }
  2368.  
  2369. bool isSubRule() const { return Constraint != nullptr; }
  2370.  
  2371. std::vector<Record *> getSubjects() const {
  2372. return (Constraint ? Constraint : MetaSubject)
  2373. ->getValueAsListOfDefs("Subjects");
  2374. }
  2375.  
  2376. std::vector<Record *> getLangOpts() const {
  2377. if (Constraint) {
  2378. // Lookup the options in the sub-rule first, in case the sub-rule
  2379. // overrides the rules options.
  2380. std::vector<Record *> Opts = Constraint->getValueAsListOfDefs("LangOpts");
  2381. if (!Opts.empty())
  2382. return Opts;
  2383. }
  2384. return MetaSubject->getValueAsListOfDefs("LangOpts");
  2385. }
  2386.  
  2387. // Abstract rules are used only for sub-rules
  2388. bool isAbstractRule() const { return getSubjects().empty(); }
  2389.  
  2390. StringRef getName() const {
  2391. return (Constraint ? Constraint : MetaSubject)->getValueAsString("Name");
  2392. }
  2393.  
  2394. bool isNegatedSubRule() const {
  2395. assert(isSubRule() && "Not a sub-rule");
  2396. return Constraint->getValueAsBit("Negated");
  2397. }
  2398.  
  2399. std::string getSpelling() const {
  2400. std::string Result = std::string(MetaSubject->getValueAsString("Name"));
  2401. if (isSubRule()) {
  2402. Result += '(';
  2403. if (isNegatedSubRule())
  2404. Result += "unless(";
  2405. Result += getName();
  2406. if (isNegatedSubRule())
  2407. Result += ')';
  2408. Result += ')';
  2409. }
  2410. return Result;
  2411. }
  2412.  
  2413. std::string getEnumValueName() const {
  2414. SmallString<128> Result;
  2415. Result += "SubjectMatchRule_";
  2416. Result += MetaSubject->getValueAsString("Name");
  2417. if (isSubRule()) {
  2418. Result += "_";
  2419. if (isNegatedSubRule())
  2420. Result += "not_";
  2421. Result += Constraint->getValueAsString("Name");
  2422. }
  2423. if (isAbstractRule())
  2424. Result += "_abstract";
  2425. return std::string(Result.str());
  2426. }
  2427.  
  2428. std::string getEnumValue() const { return "attr::" + getEnumValueName(); }
  2429.  
  2430. static const char *EnumName;
  2431. };
  2432.  
  2433. const char *AttributeSubjectMatchRule::EnumName = "attr::SubjectMatchRule";
  2434.  
  2435. struct PragmaClangAttributeSupport {
  2436. std::vector<AttributeSubjectMatchRule> Rules;
  2437.  
  2438. class RuleOrAggregateRuleSet {
  2439. std::vector<AttributeSubjectMatchRule> Rules;
  2440. bool IsRule;
  2441. RuleOrAggregateRuleSet(ArrayRef<AttributeSubjectMatchRule> Rules,
  2442. bool IsRule)
  2443. : Rules(Rules), IsRule(IsRule) {}
  2444.  
  2445. public:
  2446. bool isRule() const { return IsRule; }
  2447.  
  2448. const AttributeSubjectMatchRule &getRule() const {
  2449. assert(IsRule && "not a rule!");
  2450. return Rules[0];
  2451. }
  2452.  
  2453. ArrayRef<AttributeSubjectMatchRule> getAggregateRuleSet() const {
  2454. return Rules;
  2455. }
  2456.  
  2457. static RuleOrAggregateRuleSet
  2458. getRule(const AttributeSubjectMatchRule &Rule) {
  2459. return RuleOrAggregateRuleSet(Rule, /*IsRule=*/true);
  2460. }
  2461. static RuleOrAggregateRuleSet
  2462. getAggregateRuleSet(ArrayRef<AttributeSubjectMatchRule> Rules) {
  2463. return RuleOrAggregateRuleSet(Rules, /*IsRule=*/false);
  2464. }
  2465. };
  2466. llvm::DenseMap<const Record *, RuleOrAggregateRuleSet> SubjectsToRules;
  2467.  
  2468. PragmaClangAttributeSupport(RecordKeeper &Records);
  2469.  
  2470. bool isAttributedSupported(const Record &Attribute);
  2471.  
  2472. void emitMatchRuleList(raw_ostream &OS);
  2473.  
  2474. void generateStrictConformsTo(const Record &Attr, raw_ostream &OS);
  2475.  
  2476. void generateParsingHelpers(raw_ostream &OS);
  2477. };
  2478.  
  2479. } // end anonymous namespace
  2480.  
  2481. static bool doesDeclDeriveFrom(const Record *D, const Record *Base) {
  2482. const Record *CurrentBase = D->getValueAsOptionalDef(BaseFieldName);
  2483. if (!CurrentBase)
  2484. return false;
  2485. if (CurrentBase == Base)
  2486. return true;
  2487. return doesDeclDeriveFrom(CurrentBase, Base);
  2488. }
  2489.  
  2490. PragmaClangAttributeSupport::PragmaClangAttributeSupport(
  2491. RecordKeeper &Records) {
  2492. std::vector<Record *> MetaSubjects =
  2493. Records.getAllDerivedDefinitions("AttrSubjectMatcherRule");
  2494. auto MapFromSubjectsToRules = [this](const Record *SubjectContainer,
  2495. const Record *MetaSubject,
  2496. const Record *Constraint) {
  2497. Rules.emplace_back(MetaSubject, Constraint);
  2498. std::vector<Record *> ApplicableSubjects =
  2499. SubjectContainer->getValueAsListOfDefs("Subjects");
  2500. for (const auto *Subject : ApplicableSubjects) {
  2501. bool Inserted =
  2502. SubjectsToRules
  2503. .try_emplace(Subject, RuleOrAggregateRuleSet::getRule(
  2504. AttributeSubjectMatchRule(MetaSubject,
  2505. Constraint)))
  2506. .second;
  2507. if (!Inserted) {
  2508. PrintFatalError("Attribute subject match rules should not represent"
  2509. "same attribute subjects.");
  2510. }
  2511. }
  2512. };
  2513. for (const auto *MetaSubject : MetaSubjects) {
  2514. MapFromSubjectsToRules(MetaSubject, MetaSubject, /*Constraints=*/nullptr);
  2515. std::vector<Record *> Constraints =
  2516. MetaSubject->getValueAsListOfDefs("Constraints");
  2517. for (const auto *Constraint : Constraints)
  2518. MapFromSubjectsToRules(Constraint, MetaSubject, Constraint);
  2519. }
  2520.  
  2521. std::vector<Record *> Aggregates =
  2522. Records.getAllDerivedDefinitions("AttrSubjectMatcherAggregateRule");
  2523. std::vector<Record *> DeclNodes =
  2524. Records.getAllDerivedDefinitions(DeclNodeClassName);
  2525. for (const auto *Aggregate : Aggregates) {
  2526. Record *SubjectDecl = Aggregate->getValueAsDef("Subject");
  2527.  
  2528. // Gather sub-classes of the aggregate subject that act as attribute
  2529. // subject rules.
  2530. std::vector<AttributeSubjectMatchRule> Rules;
  2531. for (const auto *D : DeclNodes) {
  2532. if (doesDeclDeriveFrom(D, SubjectDecl)) {
  2533. auto It = SubjectsToRules.find(D);
  2534. if (It == SubjectsToRules.end())
  2535. continue;
  2536. if (!It->second.isRule() || It->second.getRule().isSubRule())
  2537. continue; // Assume that the rule will be included as well.
  2538. Rules.push_back(It->second.getRule());
  2539. }
  2540. }
  2541.  
  2542. bool Inserted =
  2543. SubjectsToRules
  2544. .try_emplace(SubjectDecl,
  2545. RuleOrAggregateRuleSet::getAggregateRuleSet(Rules))
  2546. .second;
  2547. if (!Inserted) {
  2548. PrintFatalError("Attribute subject match rules should not represent"
  2549. "same attribute subjects.");
  2550. }
  2551. }
  2552. }
  2553.  
  2554. static PragmaClangAttributeSupport &
  2555. getPragmaAttributeSupport(RecordKeeper &Records) {
  2556. static PragmaClangAttributeSupport Instance(Records);
  2557. return Instance;
  2558. }
  2559.  
  2560. void PragmaClangAttributeSupport::emitMatchRuleList(raw_ostream &OS) {
  2561. OS << "#ifndef ATTR_MATCH_SUB_RULE\n";
  2562. OS << "#define ATTR_MATCH_SUB_RULE(Value, Spelling, IsAbstract, Parent, "
  2563. "IsNegated) "
  2564. << "ATTR_MATCH_RULE(Value, Spelling, IsAbstract)\n";
  2565. OS << "#endif\n";
  2566. for (const auto &Rule : Rules) {
  2567. OS << (Rule.isSubRule() ? "ATTR_MATCH_SUB_RULE" : "ATTR_MATCH_RULE") << '(';
  2568. OS << Rule.getEnumValueName() << ", \"" << Rule.getSpelling() << "\", "
  2569. << Rule.isAbstractRule();
  2570. if (Rule.isSubRule())
  2571. OS << ", "
  2572. << AttributeSubjectMatchRule(Rule.MetaSubject, nullptr).getEnumValue()
  2573. << ", " << Rule.isNegatedSubRule();
  2574. OS << ")\n";
  2575. }
  2576. OS << "#undef ATTR_MATCH_SUB_RULE\n";
  2577. }
  2578.  
  2579. bool PragmaClangAttributeSupport::isAttributedSupported(
  2580. const Record &Attribute) {
  2581. // If the attribute explicitly specified whether to support #pragma clang
  2582. // attribute, use that setting.
  2583. bool Unset;
  2584. bool SpecifiedResult =
  2585. Attribute.getValueAsBitOrUnset("PragmaAttributeSupport", Unset);
  2586. if (!Unset)
  2587. return SpecifiedResult;
  2588.  
  2589. // Opt-out rules:
  2590. // An attribute requires delayed parsing (LateParsed is on)
  2591. if (Attribute.getValueAsBit("LateParsed"))
  2592. return false;
  2593. // An attribute has no GNU/CXX11 spelling
  2594. if (!hasGNUorCXX11Spelling(Attribute))
  2595. return false;
  2596. // An attribute subject list has a subject that isn't covered by one of the
  2597. // subject match rules or has no subjects at all.
  2598. if (Attribute.isValueUnset("Subjects"))
  2599. return false;
  2600. const Record *SubjectObj = Attribute.getValueAsDef("Subjects");
  2601. std::vector<Record *> Subjects = SubjectObj->getValueAsListOfDefs("Subjects");
  2602. if (Subjects.empty())
  2603. return false;
  2604. for (const auto *Subject : Subjects) {
  2605. if (SubjectsToRules.find(Subject) == SubjectsToRules.end())
  2606. return false;
  2607. }
  2608. return true;
  2609. }
  2610.  
  2611. static std::string GenerateTestExpression(ArrayRef<Record *> LangOpts) {
  2612. std::string Test;
  2613.  
  2614. for (auto *E : LangOpts) {
  2615. if (!Test.empty())
  2616. Test += " || ";
  2617.  
  2618. const StringRef Code = E->getValueAsString("CustomCode");
  2619. if (!Code.empty()) {
  2620. Test += "(";
  2621. Test += Code;
  2622. Test += ")";
  2623. if (!E->getValueAsString("Name").empty()) {
  2624. PrintWarning(
  2625. E->getLoc(),
  2626. "non-empty 'Name' field ignored because 'CustomCode' was supplied");
  2627. }
  2628. } else {
  2629. Test += "LangOpts.";
  2630. Test += E->getValueAsString("Name");
  2631. }
  2632. }
  2633.  
  2634. if (Test.empty())
  2635. return "true";
  2636.  
  2637. return Test;
  2638. }
  2639.  
  2640. void
  2641. PragmaClangAttributeSupport::generateStrictConformsTo(const Record &Attr,
  2642. raw_ostream &OS) {
  2643. if (!isAttributedSupported(Attr) || Attr.isValueUnset("Subjects"))
  2644. return;
  2645. // Generate a function that constructs a set of matching rules that describe
  2646. // to which declarations the attribute should apply to.
  2647. OS << "void getPragmaAttributeMatchRules("
  2648. << "llvm::SmallVectorImpl<std::pair<"
  2649. << AttributeSubjectMatchRule::EnumName
  2650. << ", bool>> &MatchRules, const LangOptions &LangOpts) const override {\n";
  2651. const Record *SubjectObj = Attr.getValueAsDef("Subjects");
  2652. std::vector<Record *> Subjects = SubjectObj->getValueAsListOfDefs("Subjects");
  2653. for (const auto *Subject : Subjects) {
  2654. auto It = SubjectsToRules.find(Subject);
  2655. assert(It != SubjectsToRules.end() &&
  2656. "This attribute is unsupported by #pragma clang attribute");
  2657. for (const auto &Rule : It->getSecond().getAggregateRuleSet()) {
  2658. // The rule might be language specific, so only subtract it from the given
  2659. // rules if the specific language options are specified.
  2660. std::vector<Record *> LangOpts = Rule.getLangOpts();
  2661. OS << " MatchRules.push_back(std::make_pair(" << Rule.getEnumValue()
  2662. << ", /*IsSupported=*/" << GenerateTestExpression(LangOpts)
  2663. << "));\n";
  2664. }
  2665. }
  2666. OS << "}\n\n";
  2667. }
  2668.  
  2669. void PragmaClangAttributeSupport::generateParsingHelpers(raw_ostream &OS) {
  2670. // Generate routines that check the names of sub-rules.
  2671. OS << "Optional<attr::SubjectMatchRule> "
  2672. "defaultIsAttributeSubjectMatchSubRuleFor(StringRef, bool) {\n";
  2673. OS << " return None;\n";
  2674. OS << "}\n\n";
  2675.  
  2676. std::map<const Record *, std::vector<AttributeSubjectMatchRule>>
  2677. SubMatchRules;
  2678. for (const auto &Rule : Rules) {
  2679. if (!Rule.isSubRule())
  2680. continue;
  2681. SubMatchRules[Rule.MetaSubject].push_back(Rule);
  2682. }
  2683.  
  2684. for (const auto &SubMatchRule : SubMatchRules) {
  2685. OS << "Optional<attr::SubjectMatchRule> isAttributeSubjectMatchSubRuleFor_"
  2686. << SubMatchRule.first->getValueAsString("Name")
  2687. << "(StringRef Name, bool IsUnless) {\n";
  2688. OS << " if (IsUnless)\n";
  2689. OS << " return "
  2690. "llvm::StringSwitch<Optional<attr::SubjectMatchRule>>(Name).\n";
  2691. for (const auto &Rule : SubMatchRule.second) {
  2692. if (Rule.isNegatedSubRule())
  2693. OS << " Case(\"" << Rule.getName() << "\", " << Rule.getEnumValue()
  2694. << ").\n";
  2695. }
  2696. OS << " Default(None);\n";
  2697. OS << " return "
  2698. "llvm::StringSwitch<Optional<attr::SubjectMatchRule>>(Name).\n";
  2699. for (const auto &Rule : SubMatchRule.second) {
  2700. if (!Rule.isNegatedSubRule())
  2701. OS << " Case(\"" << Rule.getName() << "\", " << Rule.getEnumValue()
  2702. << ").\n";
  2703. }
  2704. OS << " Default(None);\n";
  2705. OS << "}\n\n";
  2706. }
  2707.  
  2708. // Generate the function that checks for the top-level rules.
  2709. OS << "std::pair<Optional<attr::SubjectMatchRule>, "
  2710. "Optional<attr::SubjectMatchRule> (*)(StringRef, "
  2711. "bool)> isAttributeSubjectMatchRule(StringRef Name) {\n";
  2712. OS << " return "
  2713. "llvm::StringSwitch<std::pair<Optional<attr::SubjectMatchRule>, "
  2714. "Optional<attr::SubjectMatchRule> (*) (StringRef, "
  2715. "bool)>>(Name).\n";
  2716. for (const auto &Rule : Rules) {
  2717. if (Rule.isSubRule())
  2718. continue;
  2719. std::string SubRuleFunction;
  2720. if (SubMatchRules.count(Rule.MetaSubject))
  2721. SubRuleFunction =
  2722. ("isAttributeSubjectMatchSubRuleFor_" + Rule.getName()).str();
  2723. else
  2724. SubRuleFunction = "defaultIsAttributeSubjectMatchSubRuleFor";
  2725. OS << " Case(\"" << Rule.getName() << "\", std::make_pair("
  2726. << Rule.getEnumValue() << ", " << SubRuleFunction << ")).\n";
  2727. }
  2728. OS << " Default(std::make_pair(None, "
  2729. "defaultIsAttributeSubjectMatchSubRuleFor));\n";
  2730. OS << "}\n\n";
  2731.  
  2732. // Generate the function that checks for the submatch rules.
  2733. OS << "const char *validAttributeSubjectMatchSubRules("
  2734. << AttributeSubjectMatchRule::EnumName << " Rule) {\n";
  2735. OS << " switch (Rule) {\n";
  2736. for (const auto &SubMatchRule : SubMatchRules) {
  2737. OS << " case "
  2738. << AttributeSubjectMatchRule(SubMatchRule.first, nullptr).getEnumValue()
  2739. << ":\n";
  2740. OS << " return \"'";
  2741. bool IsFirst = true;
  2742. for (const auto &Rule : SubMatchRule.second) {
  2743. if (!IsFirst)
  2744. OS << ", '";
  2745. IsFirst = false;
  2746. if (Rule.isNegatedSubRule())
  2747. OS << "unless(";
  2748. OS << Rule.getName();
  2749. if (Rule.isNegatedSubRule())
  2750. OS << ')';
  2751. OS << "'";
  2752. }
  2753. OS << "\";\n";
  2754. }
  2755. OS << " default: return nullptr;\n";
  2756. OS << " }\n";
  2757. OS << "}\n\n";
  2758. }
  2759.  
  2760. template <typename Fn>
  2761. static void forEachUniqueSpelling(const Record &Attr, Fn &&F) {
  2762. std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(Attr);
  2763. SmallDenseSet<StringRef, 8> Seen;
  2764. for (const FlattenedSpelling &S : Spellings) {
  2765. if (Seen.insert(S.name()).second)
  2766. F(S);
  2767. }
  2768. }
  2769.  
  2770. /// Emits the first-argument-is-type property for attributes.
  2771. static void emitClangAttrTypeArgList(RecordKeeper &Records, raw_ostream &OS) {
  2772. OS << "#if defined(CLANG_ATTR_TYPE_ARG_LIST)\n";
  2773. std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
  2774.  
  2775. for (const auto *Attr : Attrs) {
  2776. // Determine whether the first argument is a type.
  2777. std::vector<Record *> Args = Attr->getValueAsListOfDefs("Args");
  2778. if (Args.empty())
  2779. continue;
  2780.  
  2781. if (Args[0]->getSuperClasses().back().first->getName() != "TypeArgument")
  2782. continue;
  2783.  
  2784. // All these spellings take a single type argument.
  2785. forEachUniqueSpelling(*Attr, [&](const FlattenedSpelling &S) {
  2786. OS << ".Case(\"" << S.name() << "\", " << "true" << ")\n";
  2787. });
  2788. }
  2789. OS << "#endif // CLANG_ATTR_TYPE_ARG_LIST\n\n";
  2790. }
  2791.  
  2792. /// Emits the parse-arguments-in-unevaluated-context property for
  2793. /// attributes.
  2794. static void emitClangAttrArgContextList(RecordKeeper &Records, raw_ostream &OS) {
  2795. OS << "#if defined(CLANG_ATTR_ARG_CONTEXT_LIST)\n";
  2796. ParsedAttrMap Attrs = getParsedAttrList(Records);
  2797. for (const auto &I : Attrs) {
  2798. const Record &Attr = *I.second;
  2799.  
  2800. if (!Attr.getValueAsBit("ParseArgumentsAsUnevaluated"))
  2801. continue;
  2802.  
  2803. // All these spellings take are parsed unevaluated.
  2804. forEachUniqueSpelling(Attr, [&](const FlattenedSpelling &S) {
  2805. OS << ".Case(\"" << S.name() << "\", " << "true" << ")\n";
  2806. });
  2807. }
  2808. OS << "#endif // CLANG_ATTR_ARG_CONTEXT_LIST\n\n";
  2809. }
  2810.  
  2811. static bool isIdentifierArgument(Record *Arg) {
  2812. return !Arg->getSuperClasses().empty() &&
  2813. llvm::StringSwitch<bool>(Arg->getSuperClasses().back().first->getName())
  2814. .Case("IdentifierArgument", true)
  2815. .Case("EnumArgument", true)
  2816. .Case("VariadicEnumArgument", true)
  2817. .Default(false);
  2818. }
  2819.  
  2820. static bool isVariadicIdentifierArgument(Record *Arg) {
  2821. return !Arg->getSuperClasses().empty() &&
  2822. llvm::StringSwitch<bool>(
  2823. Arg->getSuperClasses().back().first->getName())
  2824. .Case("VariadicIdentifierArgument", true)
  2825. .Case("VariadicParamOrParamIdxArgument", true)
  2826. .Default(false);
  2827. }
  2828.  
  2829. static void emitClangAttrVariadicIdentifierArgList(RecordKeeper &Records,
  2830. raw_ostream &OS) {
  2831. OS << "#if defined(CLANG_ATTR_VARIADIC_IDENTIFIER_ARG_LIST)\n";
  2832. std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
  2833. for (const auto *A : Attrs) {
  2834. // Determine whether the first argument is a variadic identifier.
  2835. std::vector<Record *> Args = A->getValueAsListOfDefs("Args");
  2836. if (Args.empty() || !isVariadicIdentifierArgument(Args[0]))
  2837. continue;
  2838.  
  2839. // All these spellings take an identifier argument.
  2840. forEachUniqueSpelling(*A, [&](const FlattenedSpelling &S) {
  2841. OS << ".Case(\"" << S.name() << "\", "
  2842. << "true"
  2843. << ")\n";
  2844. });
  2845. }
  2846. OS << "#endif // CLANG_ATTR_VARIADIC_IDENTIFIER_ARG_LIST\n\n";
  2847. }
  2848.  
  2849. // Emits the first-argument-is-identifier property for attributes.
  2850. static void emitClangAttrIdentifierArgList(RecordKeeper &Records, raw_ostream &OS) {
  2851. OS << "#if defined(CLANG_ATTR_IDENTIFIER_ARG_LIST)\n";
  2852. std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr");
  2853.  
  2854. for (const auto *Attr : Attrs) {
  2855. // Determine whether the first argument is an identifier.
  2856. std::vector<Record *> Args = Attr->getValueAsListOfDefs("Args");
  2857. if (Args.empty() || !isIdentifierArgument(Args[0]))
  2858. continue;
  2859. @@ -2899,1346 +2985,1381 @@ void EmitClangAttrSubjectMatchRuleList(RecordKeeper &Records, raw_ostream &OS) {
  2860. getPragmaAttributeSupport(Records);
  2861. emitDefaultDefine(OS, "ATTR_MATCH_RULE", nullptr);
  2862. PragmaAttributeSupport.emitMatchRuleList(OS);
  2863. OS << "#undef ATTR_MATCH_RULE\n";
  2864. }
  2865.  
  2866. // Emits the code to read an attribute from a precompiled header.
  2867. void EmitClangAttrPCHRead(RecordKeeper &Records, raw_ostream &OS) {
  2868. emitSourceFileHeader("Attribute deserialization code", OS);
  2869.  
  2870. Record *InhClass = Records.getClass("InheritableAttr");
  2871. std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr"),
  2872. ArgRecords;
  2873. std::vector<std::unique_ptr<Argument>> Args;
  2874.  
  2875. OS << " switch (Kind) {\n";
  2876. for (const auto *Attr : Attrs) {
  2877. const Record &R = *Attr;
  2878. if (!R.getValueAsBit("ASTNode"))
  2879. continue;
  2880.  
  2881. OS << " case attr::" << R.getName() << ": {\n";
  2882. if (R.isSubClassOf(InhClass))
  2883. OS << " bool isInherited = Record.readInt();\n";
  2884. OS << " bool isImplicit = Record.readInt();\n";
  2885. OS << " bool isPackExpansion = Record.readInt();\n";
  2886. ArgRecords = R.getValueAsListOfDefs("Args");
  2887. Args.clear();
  2888. for (const auto *Arg : ArgRecords) {
  2889. Args.emplace_back(createArgument(*Arg, R.getName()));
  2890. Args.back()->writePCHReadDecls(OS);
  2891. }
  2892. OS << " New = new (Context) " << R.getName() << "Attr(Context, Info";
  2893. for (auto const &ri : Args) {
  2894. OS << ", ";
  2895. ri->writePCHReadArgs(OS);
  2896. }
  2897. OS << ");\n";
  2898. if (R.isSubClassOf(InhClass))
  2899. OS << " cast<InheritableAttr>(New)->setInherited(isInherited);\n";
  2900. OS << " New->setImplicit(isImplicit);\n";
  2901. OS << " New->setPackExpansion(isPackExpansion);\n";
  2902. OS << " break;\n";
  2903. OS << " }\n";
  2904. }
  2905. OS << " }\n";
  2906. }
  2907.  
  2908. // Emits the code to write an attribute to a precompiled header.
  2909. void EmitClangAttrPCHWrite(RecordKeeper &Records, raw_ostream &OS) {
  2910. emitSourceFileHeader("Attribute serialization code", OS);
  2911.  
  2912. Record *InhClass = Records.getClass("InheritableAttr");
  2913. std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr"), Args;
  2914.  
  2915. OS << " switch (A->getKind()) {\n";
  2916. for (const auto *Attr : Attrs) {
  2917. const Record &R = *Attr;
  2918. if (!R.getValueAsBit("ASTNode"))
  2919. continue;
  2920. OS << " case attr::" << R.getName() << ": {\n";
  2921. Args = R.getValueAsListOfDefs("Args");
  2922. if (R.isSubClassOf(InhClass) || !Args.empty())
  2923. OS << " const auto *SA = cast<" << R.getName()
  2924. << "Attr>(A);\n";
  2925. if (R.isSubClassOf(InhClass))
  2926. OS << " Record.push_back(SA->isInherited());\n";
  2927. OS << " Record.push_back(A->isImplicit());\n";
  2928. OS << " Record.push_back(A->isPackExpansion());\n";
  2929.  
  2930. for (const auto *Arg : Args)
  2931. createArgument(*Arg, R.getName())->writePCHWrite(OS);
  2932. OS << " break;\n";
  2933. OS << " }\n";
  2934. }
  2935. OS << " }\n";
  2936. }
  2937.  
  2938. // Helper function for GenerateTargetSpecificAttrChecks that alters the 'Test'
  2939. // parameter with only a single check type, if applicable.
  2940. static bool GenerateTargetSpecificAttrCheck(const Record *R, std::string &Test,
  2941. std::string *FnName,
  2942. StringRef ListName,
  2943. StringRef CheckAgainst,
  2944. StringRef Scope) {
  2945. if (!R->isValueUnset(ListName)) {
  2946. Test += " && (";
  2947. std::vector<StringRef> Items = R->getValueAsListOfStrings(ListName);
  2948. for (auto I = Items.begin(), E = Items.end(); I != E; ++I) {
  2949. StringRef Part = *I;
  2950. Test += CheckAgainst;
  2951. Test += " == ";
  2952. Test += Scope;
  2953. Test += Part;
  2954. if (I + 1 != E)
  2955. Test += " || ";
  2956. if (FnName)
  2957. *FnName += Part;
  2958. }
  2959. Test += ")";
  2960. return true;
  2961. }
  2962. return false;
  2963. }
  2964.  
  2965. // Generate a conditional expression to check if the current target satisfies
  2966. // the conditions for a TargetSpecificAttr record, and append the code for
  2967. // those checks to the Test string. If the FnName string pointer is non-null,
  2968. // append a unique suffix to distinguish this set of target checks from other
  2969. // TargetSpecificAttr records.
  2970. static bool GenerateTargetSpecificAttrChecks(const Record *R,
  2971. std::vector<StringRef> &Arches,
  2972. std::string &Test,
  2973. std::string *FnName) {
  2974. bool AnyTargetChecks = false;
  2975.  
  2976. // It is assumed that there will be an llvm::Triple object
  2977. // named "T" and a TargetInfo object named "Target" within
  2978. // scope that can be used to determine whether the attribute exists in
  2979. // a given target.
  2980. Test += "true";
  2981. // If one or more architectures is specified, check those. Arches are handled
  2982. // differently because GenerateTargetRequirements needs to combine the list
  2983. // with ParseKind.
  2984. if (!Arches.empty()) {
  2985. AnyTargetChecks = true;
  2986. Test += " && (";
  2987. for (auto I = Arches.begin(), E = Arches.end(); I != E; ++I) {
  2988. StringRef Part = *I;
  2989. Test += "T.getArch() == llvm::Triple::";
  2990. Test += Part;
  2991. if (I + 1 != E)
  2992. Test += " || ";
  2993. if (FnName)
  2994. *FnName += Part;
  2995. }
  2996. Test += ")";
  2997. }
  2998.  
  2999. // If the attribute is specific to particular OSes, check those.
  3000. AnyTargetChecks |= GenerateTargetSpecificAttrCheck(
  3001. R, Test, FnName, "OSes", "T.getOS()", "llvm::Triple::");
  3002.  
  3003. // If one or more object formats is specified, check those.
  3004. AnyTargetChecks |=
  3005. GenerateTargetSpecificAttrCheck(R, Test, FnName, "ObjectFormats",
  3006. "T.getObjectFormat()", "llvm::Triple::");
  3007.  
  3008. // If custom code is specified, emit it.
  3009. StringRef Code = R->getValueAsString("CustomCode");
  3010. if (!Code.empty()) {
  3011. AnyTargetChecks = true;
  3012. Test += " && (";
  3013. Test += Code;
  3014. Test += ")";
  3015. }
  3016.  
  3017. return AnyTargetChecks;
  3018. }
  3019.  
  3020. static void GenerateHasAttrSpellingStringSwitch(
  3021. const std::vector<Record *> &Attrs, raw_ostream &OS,
  3022. const std::string &Variety = "", const std::string &Scope = "") {
  3023. for (const auto *Attr : Attrs) {
  3024. // C++11-style attributes have specific version information associated with
  3025. // them. If the attribute has no scope, the version information must not
  3026. // have the default value (1), as that's incorrect. Instead, the unscoped
  3027. // attribute version information should be taken from the SD-6 standing
  3028. // document, which can be found at:
  3029. // https://isocpp.org/std/standing-documents/sd-6-sg10-feature-test-recommendations
  3030. //
  3031. // C2x-style attributes have the same kind of version information
  3032. // associated with them. The unscoped attribute version information should
  3033. // be taken from the specification of the attribute in the C Standard.
  3034. int Version = 1;
  3035.  
  3036. if (Variety == "CXX11" || Variety == "C2x") {
  3037. std::vector<Record *> Spellings = Attr->getValueAsListOfDefs("Spellings");
  3038. for (const auto &Spelling : Spellings) {
  3039. if (Spelling->getValueAsString("Variety") == Variety) {
  3040. Version = static_cast<int>(Spelling->getValueAsInt("Version"));
  3041. if (Scope.empty() && Version == 1)
  3042. PrintError(Spelling->getLoc(), "Standard attributes must have "
  3043. "valid version information.");
  3044. break;
  3045. }
  3046. }
  3047. }
  3048.  
  3049. std::string Test;
  3050. if (Attr->isSubClassOf("TargetSpecificAttr")) {
  3051. const Record *R = Attr->getValueAsDef("Target");
  3052. std::vector<StringRef> Arches = R->getValueAsListOfStrings("Arches");
  3053. GenerateTargetSpecificAttrChecks(R, Arches, Test, nullptr);
  3054.  
  3055. // If this is the C++11 variety, also add in the LangOpts test.
  3056. if (Variety == "CXX11")
  3057. Test += " && LangOpts.CPlusPlus11";
  3058. else if (Variety == "C2x")
  3059. Test += " && LangOpts.DoubleSquareBracketAttributes";
  3060. } else if (Variety == "CXX11")
  3061. // C++11 mode should be checked against LangOpts, which is presumed to be
  3062. // present in the caller.
  3063. Test = "LangOpts.CPlusPlus11";
  3064. else if (Variety == "C2x")
  3065. Test = "LangOpts.DoubleSquareBracketAttributes";
  3066.  
  3067. std::string TestStr =
  3068. !Test.empty() ? Test + " ? " + llvm::itostr(Version) + " : 0" : "1";
  3069. std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(*Attr);
  3070. for (const auto &S : Spellings)
  3071. if (Variety.empty() || (Variety == S.variety() &&
  3072. (Scope.empty() || Scope == S.nameSpace())))
  3073. OS << " .Case(\"" << S.name() << "\", " << TestStr << ")\n";
  3074. }
  3075. OS << " .Default(0);\n";
  3076. }
  3077.  
  3078. // Emits the list of spellings for attributes.
  3079. void EmitClangAttrHasAttrImpl(RecordKeeper &Records, raw_ostream &OS) {
  3080. emitSourceFileHeader("Code to implement the __has_attribute logic", OS);
  3081.  
  3082. // Separate all of the attributes out into four group: generic, C++11, GNU,
  3083. // and declspecs. Then generate a big switch statement for each of them.
  3084. std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
  3085. std::vector<Record *> Declspec, Microsoft, GNU, Pragma;
  3086. std::map<std::string, std::vector<Record *>> CXX, C2x;
  3087.  
  3088. // Walk over the list of all attributes, and split them out based on the
  3089. // spelling variety.
  3090. for (auto *R : Attrs) {
  3091. std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(*R);
  3092. for (const auto &SI : Spellings) {
  3093. const std::string &Variety = SI.variety();
  3094. if (Variety == "GNU")
  3095. GNU.push_back(R);
  3096. else if (Variety == "Declspec")
  3097. Declspec.push_back(R);
  3098. else if (Variety == "Microsoft")
  3099. Microsoft.push_back(R);
  3100. else if (Variety == "CXX11")
  3101. CXX[SI.nameSpace()].push_back(R);
  3102. else if (Variety == "C2x")
  3103. C2x[SI.nameSpace()].push_back(R);
  3104. else if (Variety == "Pragma")
  3105. Pragma.push_back(R);
  3106. }
  3107. }
  3108.  
  3109. OS << "const llvm::Triple &T = Target.getTriple();\n";
  3110. OS << "switch (Syntax) {\n";
  3111. OS << "case AttrSyntax::GNU:\n";
  3112. OS << " return llvm::StringSwitch<int>(Name)\n";
  3113. GenerateHasAttrSpellingStringSwitch(GNU, OS, "GNU");
  3114. OS << "case AttrSyntax::Declspec:\n";
  3115. OS << " return llvm::StringSwitch<int>(Name)\n";
  3116. GenerateHasAttrSpellingStringSwitch(Declspec, OS, "Declspec");
  3117. OS << "case AttrSyntax::Microsoft:\n";
  3118. OS << " return llvm::StringSwitch<int>(Name)\n";
  3119. GenerateHasAttrSpellingStringSwitch(Microsoft, OS, "Microsoft");
  3120. OS << "case AttrSyntax::Pragma:\n";
  3121. OS << " return llvm::StringSwitch<int>(Name)\n";
  3122. GenerateHasAttrSpellingStringSwitch(Pragma, OS, "Pragma");
  3123. auto fn = [&OS](const char *Spelling, const char *Variety,
  3124. const std::map<std::string, std::vector<Record *>> &List) {
  3125. OS << "case AttrSyntax::" << Variety << ": {\n";
  3126. // C++11-style attributes are further split out based on the Scope.
  3127. for (auto I = List.cbegin(), E = List.cend(); I != E; ++I) {
  3128. if (I != List.cbegin())
  3129. OS << " else ";
  3130. if (I->first.empty())
  3131. OS << "if (ScopeName == \"\") {\n";
  3132. else
  3133. OS << "if (ScopeName == \"" << I->first << "\") {\n";
  3134. OS << " return llvm::StringSwitch<int>(Name)\n";
  3135. GenerateHasAttrSpellingStringSwitch(I->second, OS, Spelling, I->first);
  3136. OS << "}";
  3137. }
  3138. OS << "\n} break;\n";
  3139. };
  3140. fn("CXX11", "CXX", CXX);
  3141. fn("C2x", "C", C2x);
  3142. OS << "}\n";
  3143. }
  3144.  
  3145. void EmitClangAttrSpellingListIndex(RecordKeeper &Records, raw_ostream &OS) {
  3146. emitSourceFileHeader("Code to translate different attribute spellings "
  3147. "into internal identifiers", OS);
  3148.  
  3149. OS << " switch (getParsedKind()) {\n";
  3150. OS << " case IgnoredAttribute:\n";
  3151. OS << " case UnknownAttribute:\n";
  3152. OS << " case NoSemaHandlerAttribute:\n";
  3153. OS << " llvm_unreachable(\"Ignored/unknown shouldn't get here\");\n";
  3154.  
  3155. ParsedAttrMap Attrs = getParsedAttrList(Records);
  3156. for (const auto &I : Attrs) {
  3157. const Record &R = *I.second;
  3158. std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(R);
  3159. OS << " case AT_" << I.first << ": {\n";
  3160. for (unsigned I = 0; I < Spellings.size(); ++ I) {
  3161. OS << " if (Name == \"" << Spellings[I].name() << "\" && "
  3162. << "getSyntax() == AttributeCommonInfo::AS_" << Spellings[I].variety()
  3163. << " && Scope == \"" << Spellings[I].nameSpace() << "\")\n"
  3164. << " return " << I << ";\n";
  3165. }
  3166.  
  3167. OS << " break;\n";
  3168. OS << " }\n";
  3169. }
  3170.  
  3171. OS << " }\n";
  3172. OS << " return 0;\n";
  3173. }
  3174.  
  3175. // Emits code used by RecursiveASTVisitor to visit attributes
  3176. void EmitClangAttrASTVisitor(RecordKeeper &Records, raw_ostream &OS) {
  3177. emitSourceFileHeader("Used by RecursiveASTVisitor to visit attributes.", OS);
  3178.  
  3179. std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr");
  3180.  
  3181. // Write method declarations for Traverse* methods.
  3182. // We emit this here because we only generate methods for attributes that
  3183. // are declared as ASTNodes.
  3184. OS << "#ifdef ATTR_VISITOR_DECLS_ONLY\n\n";
  3185. for (const auto *Attr : Attrs) {
  3186. const Record &R = *Attr;
  3187. if (!R.getValueAsBit("ASTNode"))
  3188. continue;
  3189. OS << " bool Traverse"
  3190. << R.getName() << "Attr(" << R.getName() << "Attr *A);\n";
  3191. OS << " bool Visit"
  3192. << R.getName() << "Attr(" << R.getName() << "Attr *A) {\n"
  3193. << " return true; \n"
  3194. << " }\n";
  3195. }
  3196. OS << "\n#else // ATTR_VISITOR_DECLS_ONLY\n\n";
  3197.  
  3198. // Write individual Traverse* methods for each attribute class.
  3199. for (const auto *Attr : Attrs) {
  3200. const Record &R = *Attr;
  3201. if (!R.getValueAsBit("ASTNode"))
  3202. continue;
  3203.  
  3204. OS << "template <typename Derived>\n"
  3205. << "bool VISITORCLASS<Derived>::Traverse"
  3206. << R.getName() << "Attr(" << R.getName() << "Attr *A) {\n"
  3207. << " if (!getDerived().VisitAttr(A))\n"
  3208. << " return false;\n"
  3209. << " if (!getDerived().Visit" << R.getName() << "Attr(A))\n"
  3210. << " return false;\n";
  3211.  
  3212. std::vector<Record*> ArgRecords = R.getValueAsListOfDefs("Args");
  3213. for (const auto *Arg : ArgRecords)
  3214. createArgument(*Arg, R.getName())->writeASTVisitorTraversal(OS);
  3215.  
  3216. OS << " return true;\n";
  3217. OS << "}\n\n";
  3218. }
  3219.  
  3220. // Write generic Traverse routine
  3221. OS << "template <typename Derived>\n"
  3222. << "bool VISITORCLASS<Derived>::TraverseAttr(Attr *A) {\n"
  3223. << " if (!A)\n"
  3224. << " return true;\n"
  3225. << "\n"
  3226. << " switch (A->getKind()) {\n";
  3227.  
  3228. for (const auto *Attr : Attrs) {
  3229. const Record &R = *Attr;
  3230. if (!R.getValueAsBit("ASTNode"))
  3231. continue;
  3232.  
  3233. OS << " case attr::" << R.getName() << ":\n"
  3234. << " return getDerived().Traverse" << R.getName() << "Attr("
  3235. << "cast<" << R.getName() << "Attr>(A));\n";
  3236. }
  3237. OS << " }\n"; // end switch
  3238. OS << " llvm_unreachable(\"bad attribute kind\");\n";
  3239. OS << "}\n"; // end function
  3240. OS << "#endif // ATTR_VISITOR_DECLS_ONLY\n";
  3241. }
  3242.  
  3243. void EmitClangAttrTemplateInstantiateHelper(const std::vector<Record *> &Attrs,
  3244. raw_ostream &OS,
  3245. bool AppliesToDecl) {
  3246.  
  3247. OS << " switch (At->getKind()) {\n";
  3248. for (const auto *Attr : Attrs) {
  3249. const Record &R = *Attr;
  3250. if (!R.getValueAsBit("ASTNode"))
  3251. continue;
  3252. OS << " case attr::" << R.getName() << ": {\n";
  3253. bool ShouldClone = R.getValueAsBit("Clone") &&
  3254. (!AppliesToDecl ||
  3255. R.getValueAsBit("MeaningfulToClassTemplateDefinition"));
  3256.  
  3257. if (!ShouldClone) {
  3258. OS << " return nullptr;\n";
  3259. OS << " }\n";
  3260. continue;
  3261. }
  3262.  
  3263. OS << " const auto *A = cast<"
  3264. << R.getName() << "Attr>(At);\n";
  3265. bool TDependent = R.getValueAsBit("TemplateDependent");
  3266.  
  3267. if (!TDependent) {
  3268. OS << " return A->clone(C);\n";
  3269. OS << " }\n";
  3270. continue;
  3271. }
  3272.  
  3273. std::vector<Record*> ArgRecords = R.getValueAsListOfDefs("Args");
  3274. std::vector<std::unique_ptr<Argument>> Args;
  3275. Args.reserve(ArgRecords.size());
  3276.  
  3277. for (const auto *ArgRecord : ArgRecords)
  3278. Args.emplace_back(createArgument(*ArgRecord, R.getName()));
  3279.  
  3280. for (auto const &ai : Args)
  3281. ai->writeTemplateInstantiation(OS);
  3282.  
  3283. OS << " return new (C) " << R.getName() << "Attr(C, *A";
  3284. for (auto const &ai : Args) {
  3285. OS << ", ";
  3286. ai->writeTemplateInstantiationArgs(OS);
  3287. }
  3288. OS << ");\n }\n";
  3289. }
  3290. OS << " } // end switch\n"
  3291. << " llvm_unreachable(\"Unknown attribute!\");\n"
  3292. << " return nullptr;\n";
  3293. }
  3294.  
  3295. // Emits code to instantiate dependent attributes on templates.
  3296. void EmitClangAttrTemplateInstantiate(RecordKeeper &Records, raw_ostream &OS) {
  3297. emitSourceFileHeader("Template instantiation code for attributes", OS);
  3298.  
  3299. std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr");
  3300.  
  3301. OS << "namespace clang {\n"
  3302. << "namespace sema {\n\n"
  3303. << "Attr *instantiateTemplateAttribute(const Attr *At, ASTContext &C, "
  3304. << "Sema &S,\n"
  3305. << " const MultiLevelTemplateArgumentList &TemplateArgs) {\n";
  3306. EmitClangAttrTemplateInstantiateHelper(Attrs, OS, /*AppliesToDecl*/false);
  3307. OS << "}\n\n"
  3308. << "Attr *instantiateTemplateAttributeForDecl(const Attr *At,\n"
  3309. << " ASTContext &C, Sema &S,\n"
  3310. << " const MultiLevelTemplateArgumentList &TemplateArgs) {\n";
  3311. EmitClangAttrTemplateInstantiateHelper(Attrs, OS, /*AppliesToDecl*/true);
  3312. OS << "}\n\n"
  3313. << "} // end namespace sema\n"
  3314. << "} // end namespace clang\n";
  3315. }
  3316.  
  3317. // Emits the list of parsed attributes.
  3318. void EmitClangAttrParsedAttrList(RecordKeeper &Records, raw_ostream &OS) {
  3319. emitSourceFileHeader("List of all attributes that Clang recognizes", OS);
  3320.  
  3321. OS << "#ifndef PARSED_ATTR\n";
  3322. OS << "#define PARSED_ATTR(NAME) NAME\n";
  3323. OS << "#endif\n\n";
  3324.  
  3325. ParsedAttrMap Names = getParsedAttrList(Records);
  3326. for (const auto &I : Names) {
  3327. OS << "PARSED_ATTR(" << I.first << ")\n";
  3328. }
  3329. }
  3330.  
  3331. static bool isArgVariadic(const Record &R, StringRef AttrName) {
  3332. return createArgument(R, AttrName)->isVariadic();
  3333. }
  3334.  
  3335. static void emitArgInfo(const Record &R, raw_ostream &OS) {
  3336. // This function will count the number of arguments specified for the
  3337. // attribute and emit the number of required arguments followed by the
  3338. // number of optional arguments.
  3339. std::vector<Record *> Args = R.getValueAsListOfDefs("Args");
  3340. unsigned ArgCount = 0, OptCount = 0;
  3341. bool HasVariadic = false;
  3342. for (const auto *Arg : Args) {
  3343. // If the arg is fake, it's the user's job to supply it: general parsing
  3344. // logic shouldn't need to know anything about it.
  3345. if (Arg->getValueAsBit("Fake"))
  3346. continue;
  3347. Arg->getValueAsBit("Optional") ? ++OptCount : ++ArgCount;
  3348. if (!HasVariadic && isArgVariadic(*Arg, R.getName()))
  3349. HasVariadic = true;
  3350. }
  3351.  
  3352. // If there is a variadic argument, we will set the optional argument count
  3353. // to its largest value. Since it's currently a 4-bit number, we set it to 15.
  3354. OS << " NumArgs = " << ArgCount << ";\n";
  3355. OS << " OptArgs = " << (HasVariadic ? 15 : OptCount) << ";\n";
  3356. }
  3357.  
  3358. static std::string GetDiagnosticSpelling(const Record &R) {
  3359. std::string Ret = std::string(R.getValueAsString("DiagSpelling"));
  3360. if (!Ret.empty())
  3361. return Ret;
  3362.  
  3363. // If we couldn't find the DiagSpelling in this object, we can check to see
  3364. // if the object is one that has a base, and if it is, loop up to the Base
  3365. // member recursively.
  3366. if (auto Base = R.getValueAsOptionalDef(BaseFieldName))
  3367. return GetDiagnosticSpelling(*Base);
  3368.  
  3369. return "";
  3370. }
  3371.  
  3372. static std::string CalculateDiagnostic(const Record &S) {
  3373. // If the SubjectList object has a custom diagnostic associated with it,
  3374. // return that directly.
  3375. const StringRef CustomDiag = S.getValueAsString("CustomDiag");
  3376. if (!CustomDiag.empty())
  3377. return ("\"" + Twine(CustomDiag) + "\"").str();
  3378.  
  3379. std::vector<std::string> DiagList;
  3380. std::vector<Record *> Subjects = S.getValueAsListOfDefs("Subjects");
  3381. for (const auto *Subject : Subjects) {
  3382. const Record &R = *Subject;
  3383. // Get the diagnostic text from the Decl or Stmt node given.
  3384. std::string V = GetDiagnosticSpelling(R);
  3385. if (V.empty()) {
  3386. PrintError(R.getLoc(),
  3387. "Could not determine diagnostic spelling for the node: " +
  3388. R.getName() + "; please add one to DeclNodes.td");
  3389. } else {
  3390. // The node may contain a list of elements itself, so split the elements
  3391. // by a comma, and trim any whitespace.
  3392. SmallVector<StringRef, 2> Frags;
  3393. llvm::SplitString(V, Frags, ",");
  3394. for (auto Str : Frags) {
  3395. DiagList.push_back(std::string(Str.trim()));
  3396. }
  3397. }
  3398. }
  3399.  
  3400. if (DiagList.empty()) {
  3401. PrintFatalError(S.getLoc(),
  3402. "Could not deduce diagnostic argument for Attr subjects");
  3403. return "";
  3404. }
  3405.  
  3406. // FIXME: this is not particularly good for localization purposes and ideally
  3407. // should be part of the diagnostics engine itself with some sort of list
  3408. // specifier.
  3409.  
  3410. // A single member of the list can be returned directly.
  3411. if (DiagList.size() == 1)
  3412. return '"' + DiagList.front() + '"';
  3413.  
  3414. if (DiagList.size() == 2)
  3415. return '"' + DiagList[0] + " and " + DiagList[1] + '"';
  3416.  
  3417. // If there are more than two in the list, we serialize the first N - 1
  3418. // elements with a comma. This leaves the string in the state: foo, bar,
  3419. // baz (but misses quux). We can then add ", and " for the last element
  3420. // manually.
  3421. std::string Diag = llvm::join(DiagList.begin(), DiagList.end() - 1, ", ");
  3422. return '"' + Diag + ", and " + *(DiagList.end() - 1) + '"';
  3423. }
  3424.  
  3425. static std::string GetSubjectWithSuffix(const Record *R) {
  3426. const std::string &B = std::string(R->getName());
  3427. if (B == "DeclBase")
  3428. return "Decl";
  3429. return B + "Decl";
  3430. }
  3431.  
  3432. static std::string functionNameForCustomAppertainsTo(const Record &Subject) {
  3433. return "is" + Subject.getName().str();
  3434. }
  3435.  
  3436. static void GenerateCustomAppertainsTo(const Record &Subject, raw_ostream &OS) {
  3437. std::string FnName = functionNameForCustomAppertainsTo(Subject);
  3438.  
  3439. // If this code has already been generated, we don't need to do anything.
  3440. static std::set<std::string> CustomSubjectSet;
  3441. auto I = CustomSubjectSet.find(FnName);
  3442. if (I != CustomSubjectSet.end())
  3443. return;
  3444.  
  3445. // This only works with non-root Decls.
  3446. Record *Base = Subject.getValueAsDef(BaseFieldName);
  3447.  
  3448. // Not currently support custom subjects within custom subjects.
  3449. if (Base->isSubClassOf("SubsetSubject")) {
  3450. PrintFatalError(Subject.getLoc(),
  3451. "SubsetSubjects within SubsetSubjects is not supported");
  3452. return;
  3453. }
  3454.  
  3455. OS << "static bool " << FnName << "(const Decl *D) {\n";
  3456. OS << " if (const auto *S = dyn_cast<";
  3457. OS << GetSubjectWithSuffix(Base);
  3458. OS << ">(D))\n";
  3459. OS << " return " << Subject.getValueAsString("CheckCode") << ";\n";
  3460. OS << " return false;\n";
  3461. OS << "}\n\n";
  3462.  
  3463. CustomSubjectSet.insert(FnName);
  3464. }
  3465.  
  3466. static void GenerateAppertainsTo(const Record &Attr, raw_ostream &OS) {
  3467. // If the attribute does not contain a Subjects definition, then use the
  3468. // default appertainsTo logic.
  3469. if (Attr.isValueUnset("Subjects"))
  3470. return;
  3471.  
  3472. const Record *SubjectObj = Attr.getValueAsDef("Subjects");
  3473. std::vector<Record*> Subjects = SubjectObj->getValueAsListOfDefs("Subjects");
  3474.  
  3475. // If the list of subjects is empty, it is assumed that the attribute
  3476. // appertains to everything.
  3477. if (Subjects.empty())
  3478. return;
  3479.  
  3480. bool Warn = SubjectObj->getValueAsDef("Diag")->getValueAsBit("Warn");
  3481.  
  3482. // Otherwise, generate an appertainsTo check specific to this attribute which
  3483. // checks all of the given subjects against the Decl passed in.
  3484. //
  3485. // If D is null, that means the attribute was not applied to a declaration
  3486. // at all (for instance because it was applied to a type), or that the caller
  3487. // has determined that the check should fail (perhaps prior to the creation
  3488. // of the declaration).
  3489. OS << "bool diagAppertainsToDecl(Sema &S, ";
  3490. OS << "const ParsedAttr &Attr, const Decl *D) const override {\n";
  3491. OS << " if (";
  3492. for (auto I = Subjects.begin(), E = Subjects.end(); I != E; ++I) {
  3493. // If the subject has custom code associated with it, use the generated
  3494. // function for it. The function cannot be inlined into this check (yet)
  3495. // because it requires the subject to be of a specific type, and were that
  3496. // information inlined here, it would not support an attribute with multiple
  3497. // custom subjects.
  3498. if ((*I)->isSubClassOf("SubsetSubject")) {
  3499. OS << "!" << functionNameForCustomAppertainsTo(**I) << "(D)";
  3500. } else {
  3501. OS << "!isa<" << GetSubjectWithSuffix(*I) << ">(D)";
  3502. }
  3503.  
  3504. if (I + 1 != E)
  3505. OS << " && ";
  3506. }
  3507. OS << ") {\n";
  3508. OS << " S.Diag(Attr.getLoc(), diag::";
  3509. OS << (Warn ? "warn_attribute_wrong_decl_type_str" :
  3510. "err_attribute_wrong_decl_type_str");
  3511. OS << ")\n";
  3512. OS << " << Attr << ";
  3513. OS << CalculateDiagnostic(*SubjectObj) << ";\n";
  3514. OS << " return false;\n";
  3515. OS << " }\n";
  3516. OS << " return true;\n";
  3517. OS << "}\n\n";
  3518. }
  3519.  
  3520. static void
  3521. emitAttributeMatchRules(PragmaClangAttributeSupport &PragmaAttributeSupport,
  3522. raw_ostream &OS) {
  3523. OS << "static bool checkAttributeMatchRuleAppliesTo(const Decl *D, "
  3524. << AttributeSubjectMatchRule::EnumName << " rule) {\n";
  3525. OS << " switch (rule) {\n";
  3526. for (const auto &Rule : PragmaAttributeSupport.Rules) {
  3527. if (Rule.isAbstractRule()) {
  3528. OS << " case " << Rule.getEnumValue() << ":\n";
  3529. OS << " assert(false && \"Abstract matcher rule isn't allowed\");\n";
  3530. OS << " return false;\n";
  3531. continue;
  3532. }
  3533. std::vector<Record *> Subjects = Rule.getSubjects();
  3534. assert(!Subjects.empty() && "Missing subjects");
  3535. OS << " case " << Rule.getEnumValue() << ":\n";
  3536. OS << " return ";
  3537. for (auto I = Subjects.begin(), E = Subjects.end(); I != E; ++I) {
  3538. // If the subject has custom code associated with it, use the function
  3539. // that was generated for GenerateAppertainsTo to check if the declaration
  3540. // is valid.
  3541. if ((*I)->isSubClassOf("SubsetSubject"))
  3542. OS << functionNameForCustomAppertainsTo(**I) << "(D)";
  3543. else
  3544. OS << "isa<" << GetSubjectWithSuffix(*I) << ">(D)";
  3545.  
  3546. if (I + 1 != E)
  3547. OS << " || ";
  3548. }
  3549. OS << ";\n";
  3550. }
  3551. OS << " }\n";
  3552. OS << " llvm_unreachable(\"Invalid match rule\");\nreturn false;\n";
  3553. OS << "}\n\n";
  3554. }
  3555.  
  3556. static void GenerateLangOptRequirements(const Record &R,
  3557. raw_ostream &OS) {
  3558. // If the attribute has an empty or unset list of language requirements,
  3559. // use the default handler.
  3560. std::vector<Record *> LangOpts = R.getValueAsListOfDefs("LangOpts");
  3561. if (LangOpts.empty())
  3562. return;
  3563.  
  3564. OS << "bool diagLangOpts(Sema &S, const ParsedAttr &Attr) ";
  3565. OS << "const override {\n";
  3566. OS << " auto &LangOpts = S.LangOpts;\n";
  3567. OS << " if (" << GenerateTestExpression(LangOpts) << ")\n";
  3568. OS << " return true;\n\n";
  3569. OS << " S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) ";
  3570. OS << "<< Attr;\n";
  3571. OS << " return false;\n";
  3572. OS << "}\n\n";
  3573. }
  3574.  
  3575. static void GenerateTargetRequirements(const Record &Attr,
  3576. const ParsedAttrMap &Dupes,
  3577. raw_ostream &OS) {
  3578. // If the attribute is not a target specific attribute, use the default
  3579. // target handler.
  3580. if (!Attr.isSubClassOf("TargetSpecificAttr"))
  3581. return;
  3582.  
  3583. // Get the list of architectures to be tested for.
  3584. const Record *R = Attr.getValueAsDef("Target");
  3585. std::vector<StringRef> Arches = R->getValueAsListOfStrings("Arches");
  3586.  
  3587. // If there are other attributes which share the same parsed attribute kind,
  3588. // such as target-specific attributes with a shared spelling, collapse the
  3589. // duplicate architectures. This is required because a shared target-specific
  3590. // attribute has only one ParsedAttr::Kind enumeration value, but it
  3591. // applies to multiple target architectures. In order for the attribute to be
  3592. // considered valid, all of its architectures need to be included.
  3593. if (!Attr.isValueUnset("ParseKind")) {
  3594. const StringRef APK = Attr.getValueAsString("ParseKind");
  3595. for (const auto &I : Dupes) {
  3596. if (I.first == APK) {
  3597. std::vector<StringRef> DA =
  3598. I.second->getValueAsDef("Target")->getValueAsListOfStrings(
  3599. "Arches");
  3600. Arches.insert(Arches.end(), DA.begin(), DA.end());
  3601. }
  3602. }
  3603. }
  3604.  
  3605. std::string FnName = "isTarget";
  3606. std::string Test;
  3607. bool UsesT = GenerateTargetSpecificAttrChecks(R, Arches, Test, &FnName);
  3608.  
  3609. OS << "bool existsInTarget(const TargetInfo &Target) const override {\n";
  3610. if (UsesT)
  3611. OS << " const llvm::Triple &T = Target.getTriple(); (void)T;\n";
  3612. OS << " return " << Test << ";\n";
  3613. OS << "}\n\n";
  3614. }
  3615.  
  3616. static void GenerateSpellingIndexToSemanticSpelling(const Record &Attr,
  3617. raw_ostream &OS) {
  3618. // If the attribute does not have a semantic form, we can bail out early.
  3619. if (!Attr.getValueAsBit("ASTNode"))
  3620. return;
  3621.  
  3622. std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(Attr);
  3623.  
  3624. // If there are zero or one spellings, or all of the spellings share the same
  3625. // name, we can also bail out early.
  3626. if (Spellings.size() <= 1 || SpellingNamesAreCommon(Spellings))
  3627. return;
  3628.  
  3629. // Generate the enumeration we will use for the mapping.
  3630. SemanticSpellingMap SemanticToSyntacticMap;
  3631. std::string Enum = CreateSemanticSpellings(Spellings, SemanticToSyntacticMap);
  3632. std::string Name = Attr.getName().str() + "AttrSpellingMap";
  3633.  
  3634. OS << "unsigned spellingIndexToSemanticSpelling(";
  3635. OS << "const ParsedAttr &Attr) const override {\n";
  3636. OS << Enum;
  3637. OS << " unsigned Idx = Attr.getAttributeSpellingListIndex();\n";
  3638. WriteSemanticSpellingSwitch("Idx", SemanticToSyntacticMap, OS);
  3639. OS << "}\n\n";
  3640. }
  3641.  
  3642. static void GenerateHandleDeclAttribute(const Record &Attr, raw_ostream &OS) {
  3643. // Only generate if Attr can be handled simply.
  3644. if (!Attr.getValueAsBit("SimpleHandler"))
  3645. return;
  3646.  
  3647. // Generate a function which just converts from ParsedAttr to the Attr type.
  3648. OS << "AttrHandling handleDeclAttribute(Sema &S, Decl *D,";
  3649. OS << "const ParsedAttr &Attr) const override {\n";
  3650. OS << " D->addAttr(::new (S.Context) " << Attr.getName();
  3651. OS << "Attr(S.Context, Attr));\n";
  3652. OS << " return AttributeApplied;\n";
  3653. OS << "}\n\n";
  3654. }
  3655.  
  3656. static bool IsKnownToGCC(const Record &Attr) {
  3657. // Look at the spellings for this subject; if there are any spellings which
  3658. // claim to be known to GCC, the attribute is known to GCC.
  3659. return llvm::any_of(
  3660. GetFlattenedSpellings(Attr),
  3661. [](const FlattenedSpelling &S) { return S.knownToGCC(); });
  3662. }
  3663.  
  3664. /// Emits the parsed attribute helpers
  3665. void EmitClangAttrParsedAttrImpl(RecordKeeper &Records, raw_ostream &OS) {
  3666. emitSourceFileHeader("Parsed attribute helpers", OS);
  3667.  
  3668. PragmaClangAttributeSupport &PragmaAttributeSupport =
  3669. getPragmaAttributeSupport(Records);
  3670.  
  3671. // Get the list of parsed attributes, and accept the optional list of
  3672. // duplicates due to the ParseKind.
  3673. ParsedAttrMap Dupes;
  3674. ParsedAttrMap Attrs = getParsedAttrList(Records, &Dupes);
  3675.  
  3676. // Generate all of the custom appertainsTo functions that the attributes
  3677. // will be using.
  3678. for (auto I : Attrs) {
  3679. const Record &Attr = *I.second;
  3680. if (Attr.isValueUnset("Subjects"))
  3681. continue;
  3682. const Record *SubjectObj = Attr.getValueAsDef("Subjects");
  3683. for (auto Subject : SubjectObj->getValueAsListOfDefs("Subjects"))
  3684. if (Subject->isSubClassOf("SubsetSubject"))
  3685. GenerateCustomAppertainsTo(*Subject, OS);
  3686. }
  3687.  
  3688. // Generate a ParsedAttrInfo struct for each of the attributes.
  3689. for (auto I = Attrs.begin(), E = Attrs.end(); I != E; ++I) {
  3690. // TODO: If the attribute's kind appears in the list of duplicates, that is
  3691. // because it is a target-specific attribute that appears multiple times.
  3692. // It would be beneficial to test whether the duplicates are "similar
  3693. // enough" to each other to not cause problems. For instance, check that
  3694. // the spellings are identical, and custom parsing rules match, etc.
  3695.  
  3696. // We need to generate struct instances based off ParsedAttrInfo from
  3697. // ParsedAttr.cpp.
  3698. const std::string &AttrName = I->first;
  3699. const Record &Attr = *I->second;
  3700. auto Spellings = GetFlattenedSpellings(Attr);
  3701. if (!Spellings.empty()) {
  3702. OS << "static constexpr ParsedAttrInfo::Spelling " << I->first
  3703. << "Spellings[] = {\n";
  3704. for (const auto &S : Spellings) {
  3705. const std::string &RawSpelling = S.name();
  3706. std::string Spelling;
  3707. if (!S.nameSpace().empty())
  3708. Spelling += S.nameSpace() + "::";
  3709. if (S.variety() == "GNU")
  3710. Spelling += NormalizeGNUAttrSpelling(RawSpelling);
  3711. else
  3712. Spelling += RawSpelling;
  3713. OS << " {AttributeCommonInfo::AS_" << S.variety();
  3714. OS << ", \"" << Spelling << "\"},\n";
  3715. }
  3716. OS << "};\n";
  3717. }
  3718. OS << "struct ParsedAttrInfo" << I->first
  3719. << " final : public ParsedAttrInfo {\n";
  3720. OS << " ParsedAttrInfo" << I->first << "() {\n";
  3721. OS << " AttrKind = ParsedAttr::AT_" << AttrName << ";\n";
  3722. emitArgInfo(Attr, OS);
  3723. OS << " HasCustomParsing = ";
  3724. OS << Attr.getValueAsBit("HasCustomParsing") << ";\n";
  3725. OS << " IsTargetSpecific = ";
  3726. OS << Attr.isSubClassOf("TargetSpecificAttr") << ";\n";
  3727. OS << " IsType = ";
  3728. OS << (Attr.isSubClassOf("TypeAttr") ||
  3729. Attr.isSubClassOf("DeclOrTypeAttr")) << ";\n";
  3730. OS << " IsStmt = ";
  3731. OS << Attr.isSubClassOf("StmtAttr") << ";\n";
  3732. OS << " IsKnownToGCC = ";
  3733. OS << IsKnownToGCC(Attr) << ";\n";
  3734. OS << " IsSupportedByPragmaAttribute = ";
  3735. OS << PragmaAttributeSupport.isAttributedSupported(*I->second) << ";\n";
  3736. if (!Spellings.empty())
  3737. OS << " Spellings = " << I->first << "Spellings;\n";
  3738. OS << " }\n";
  3739. GenerateAppertainsTo(Attr, OS);
  3740. GenerateLangOptRequirements(Attr, OS);
  3741. GenerateTargetRequirements(Attr, Dupes, OS);
  3742. GenerateSpellingIndexToSemanticSpelling(Attr, OS);
  3743. PragmaAttributeSupport.generateStrictConformsTo(*I->second, OS);
  3744. GenerateHandleDeclAttribute(Attr, OS);
  3745. OS << "static const ParsedAttrInfo" << I->first << " Instance;\n";
  3746. OS << "};\n";
  3747. OS << "const ParsedAttrInfo" << I->first << " ParsedAttrInfo" << I->first
  3748. << "::Instance;\n";
  3749. }
  3750.  
  3751. OS << "static const ParsedAttrInfo *AttrInfoMap[] = {\n";
  3752. for (auto I = Attrs.begin(), E = Attrs.end(); I != E; ++I) {
  3753. OS << "&ParsedAttrInfo" << I->first << "::Instance,\n";
  3754. }
  3755. OS << "};\n\n";
  3756.  
  3757. // Generate the attribute match rules.
  3758. emitAttributeMatchRules(PragmaAttributeSupport, OS);
  3759. }
  3760.  
  3761. // Emits the kind list of parsed attributes
  3762. void EmitClangAttrParsedAttrKinds(RecordKeeper &Records, raw_ostream &OS) {
  3763. emitSourceFileHeader("Attribute name matcher", OS);
  3764.  
  3765. std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
  3766. std::vector<StringMatcher::StringPair> GNU, Declspec, Microsoft, CXX11,
  3767. Keywords, Pragma, C2x;
  3768. std::set<std::string> Seen;
  3769. for (const auto *A : Attrs) {
  3770. const Record &Attr = *A;
  3771.  
  3772. bool SemaHandler = Attr.getValueAsBit("SemaHandler");
  3773. bool Ignored = Attr.getValueAsBit("Ignored");
  3774. if (SemaHandler || Ignored) {
  3775. // Attribute spellings can be shared between target-specific attributes,
  3776. // and can be shared between syntaxes for the same attribute. For
  3777. // instance, an attribute can be spelled GNU<"interrupt"> for an ARM-
  3778. // specific attribute, or MSP430-specific attribute. Additionally, an
  3779. // attribute can be spelled GNU<"dllexport"> and Declspec<"dllexport">
  3780. // for the same semantic attribute. Ultimately, we need to map each of
  3781. // these to a single AttributeCommonInfo::Kind value, but the
  3782. // StringMatcher class cannot handle duplicate match strings. So we
  3783. // generate a list of string to match based on the syntax, and emit
  3784. // multiple string matchers depending on the syntax used.
  3785. std::string AttrName;
  3786. if (Attr.isSubClassOf("TargetSpecificAttr") &&
  3787. !Attr.isValueUnset("ParseKind")) {
  3788. AttrName = std::string(Attr.getValueAsString("ParseKind"));
  3789. if (Seen.find(AttrName) != Seen.end())
  3790. continue;
  3791. Seen.insert(AttrName);
  3792. } else
  3793. AttrName = NormalizeAttrName(StringRef(Attr.getName())).str();
  3794.  
  3795. std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(Attr);
  3796. for (const auto &S : Spellings) {
  3797. const std::string &RawSpelling = S.name();
  3798. std::vector<StringMatcher::StringPair> *Matches = nullptr;
  3799. std::string Spelling;
  3800. const std::string &Variety = S.variety();
  3801. if (Variety == "CXX11") {
  3802. Matches = &CXX11;
  3803. if (!S.nameSpace().empty())
  3804. Spelling += S.nameSpace() + "::";
  3805. } else if (Variety == "C2x") {
  3806. Matches = &C2x;
  3807. if (!S.nameSpace().empty())
  3808. Spelling += S.nameSpace() + "::";
  3809. } else if (Variety == "GNU")
  3810. Matches = &GNU;
  3811. else if (Variety == "Declspec")
  3812. Matches = &Declspec;
  3813. else if (Variety == "Microsoft")
  3814. Matches = &Microsoft;
  3815. else if (Variety == "Keyword")
  3816. Matches = &Keywords;
  3817. else if (Variety == "Pragma")
  3818. Matches = &Pragma;
  3819.  
  3820. assert(Matches && "Unsupported spelling variety found");
  3821.  
  3822. if (Variety == "GNU")
  3823. Spelling += NormalizeGNUAttrSpelling(RawSpelling);
  3824. else
  3825. Spelling += RawSpelling;
  3826.  
  3827. if (SemaHandler)
  3828. Matches->push_back(StringMatcher::StringPair(
  3829. Spelling, "return AttributeCommonInfo::AT_" + AttrName + ";"));
  3830. else
  3831. Matches->push_back(StringMatcher::StringPair(
  3832. Spelling, "return AttributeCommonInfo::IgnoredAttribute;"));
  3833. }
  3834. }
  3835. }
  3836.  
  3837. OS << "static AttributeCommonInfo::Kind getAttrKind(StringRef Name, ";
  3838. OS << "AttributeCommonInfo::Syntax Syntax) {\n";
  3839. OS << " if (AttributeCommonInfo::AS_GNU == Syntax) {\n";
  3840. StringMatcher("Name", GNU, OS).Emit();
  3841. OS << " } else if (AttributeCommonInfo::AS_Declspec == Syntax) {\n";
  3842. StringMatcher("Name", Declspec, OS).Emit();
  3843. OS << " } else if (AttributeCommonInfo::AS_Microsoft == Syntax) {\n";
  3844. StringMatcher("Name", Microsoft, OS).Emit();
  3845. OS << " } else if (AttributeCommonInfo::AS_CXX11 == Syntax) {\n";
  3846. StringMatcher("Name", CXX11, OS).Emit();
  3847. OS << " } else if (AttributeCommonInfo::AS_C2x == Syntax) {\n";
  3848. StringMatcher("Name", C2x, OS).Emit();
  3849. OS << " } else if (AttributeCommonInfo::AS_Keyword == Syntax || ";
  3850. OS << "AttributeCommonInfo::AS_ContextSensitiveKeyword == Syntax) {\n";
  3851. StringMatcher("Name", Keywords, OS).Emit();
  3852. OS << " } else if (AttributeCommonInfo::AS_Pragma == Syntax) {\n";
  3853. StringMatcher("Name", Pragma, OS).Emit();
  3854. OS << " }\n";
  3855. OS << " return AttributeCommonInfo::UnknownAttribute;\n"
  3856. << "}\n";
  3857. }
  3858.  
  3859. -// Emits the code to dump an attribute.
  3860. +// Emits the code to dump an attribute for a JSON AST dump.
  3861. +void EmitClangAttrJSONNodeDump(llvm::RecordKeeper &Records,
  3862. + llvm::raw_ostream &OS) {
  3863. + emitSourceFileHeader("Attribute JSON node dumper", OS);
  3864. +
  3865. + std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr"), Args;
  3866. + for (const auto *Attr : Attrs) {
  3867. + const Record &R = *Attr;
  3868. + if (!R.getValueAsBit("ASTNode"))
  3869. + continue;
  3870. +
  3871. + // If the attribute has a semantically-meaningful name (which is determined
  3872. + // by whether there is a Spelling enumeration for it), then write out the
  3873. + // spelling used for the attribute.
  3874. +
  3875. + std::string FunctionContent;
  3876. + llvm::raw_string_ostream SS(FunctionContent);
  3877. +
  3878. + Args = R.getValueAsListOfDefs("Args");
  3879. + if (!Args.empty()) {
  3880. + for (const auto *Arg : Args)
  3881. + createArgument(*Arg, R.getName())->writeJSONDump(SS);
  3882. + }
  3883. +
  3884. + if (SS.tell()) {
  3885. + OS << "void Visit" << R.getName() << "Attr(const " << R.getName()
  3886. + << "Attr *A) {\n";
  3887. + OS << " llvm::json::Array Args;\n";
  3888. + OS << SS.str();
  3889. + OS << " JOS.attribute(\"args\", std::move(Args));\n";
  3890. + OS << "}\n";
  3891. + }
  3892. + }
  3893. +}
  3894. +
  3895. +// Emits the code to dump an attribute for a textual AST dump.
  3896. void EmitClangAttrTextNodeDump(RecordKeeper &Records, raw_ostream &OS) {
  3897. emitSourceFileHeader("Attribute text node dumper", OS);
  3898.  
  3899. std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr"), Args;
  3900. for (const auto *Attr : Attrs) {
  3901. const Record &R = *Attr;
  3902. if (!R.getValueAsBit("ASTNode"))
  3903. continue;
  3904.  
  3905. // If the attribute has a semantically-meaningful name (which is determined
  3906. // by whether there is a Spelling enumeration for it), then write out the
  3907. // spelling used for the attribute.
  3908.  
  3909. std::string FunctionContent;
  3910. llvm::raw_string_ostream SS(FunctionContent);
  3911.  
  3912. std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(R);
  3913. if (Spellings.size() > 1 && !SpellingNamesAreCommon(Spellings))
  3914. SS << " OS << \" \" << A->getSpelling();\n";
  3915.  
  3916. Args = R.getValueAsListOfDefs("Args");
  3917. for (const auto *Arg : Args)
  3918. - createArgument(*Arg, R.getName())->writeDump(SS);
  3919. + createArgument(*Arg, R.getName())->writeTextDump(SS);
  3920.  
  3921. if (SS.tell()) {
  3922. OS << " void Visit" << R.getName() << "Attr(const " << R.getName()
  3923. << "Attr *A) {\n";
  3924. if (!Args.empty())
  3925. OS << " const auto *SA = cast<" << R.getName()
  3926. << "Attr>(A); (void)SA;\n";
  3927. OS << SS.str();
  3928. OS << " }\n";
  3929. }
  3930. }
  3931. }
  3932.  
  3933. void EmitClangAttrNodeTraverse(RecordKeeper &Records, raw_ostream &OS) {
  3934. emitSourceFileHeader("Attribute text node traverser", OS);
  3935.  
  3936. std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr"), Args;
  3937. for (const auto *Attr : Attrs) {
  3938. const Record &R = *Attr;
  3939. if (!R.getValueAsBit("ASTNode"))
  3940. continue;
  3941.  
  3942. std::string FunctionContent;
  3943. llvm::raw_string_ostream SS(FunctionContent);
  3944.  
  3945. Args = R.getValueAsListOfDefs("Args");
  3946. for (const auto *Arg : Args)
  3947. createArgument(*Arg, R.getName())->writeDumpChildren(SS);
  3948. if (SS.tell()) {
  3949. OS << " void Visit" << R.getName() << "Attr(const " << R.getName()
  3950. << "Attr *A) {\n";
  3951. if (!Args.empty())
  3952. OS << " const auto *SA = cast<" << R.getName()
  3953. << "Attr>(A); (void)SA;\n";
  3954. OS << SS.str();
  3955. OS << " }\n";
  3956. }
  3957. }
  3958. }
  3959.  
  3960. void EmitClangAttrParserStringSwitches(RecordKeeper &Records,
  3961. raw_ostream &OS) {
  3962. emitSourceFileHeader("Parser-related llvm::StringSwitch cases", OS);
  3963. emitClangAttrArgContextList(Records, OS);
  3964. emitClangAttrIdentifierArgList(Records, OS);
  3965. emitClangAttrVariadicIdentifierArgList(Records, OS);
  3966. emitClangAttrThisIsaIdentifierArgList(Records, OS);
  3967. emitClangAttrTypeArgList(Records, OS);
  3968. emitClangAttrLateParsedList(Records, OS);
  3969. }
  3970.  
  3971. void EmitClangAttrSubjectMatchRulesParserStringSwitches(RecordKeeper &Records,
  3972. raw_ostream &OS) {
  3973. getPragmaAttributeSupport(Records).generateParsingHelpers(OS);
  3974. }
  3975.  
  3976. enum class SpellingKind {
  3977. GNU,
  3978. CXX11,
  3979. C2x,
  3980. Declspec,
  3981. Microsoft,
  3982. Keyword,
  3983. Pragma,
  3984. };
  3985. static const size_t NumSpellingKinds = (size_t)SpellingKind::Pragma + 1;
  3986.  
  3987. class SpellingList {
  3988. std::vector<std::string> Spellings[NumSpellingKinds];
  3989.  
  3990. public:
  3991. ArrayRef<std::string> operator[](SpellingKind K) const {
  3992. return Spellings[(size_t)K];
  3993. }
  3994.  
  3995. void add(const Record &Attr, FlattenedSpelling Spelling) {
  3996. SpellingKind Kind = StringSwitch<SpellingKind>(Spelling.variety())
  3997. .Case("GNU", SpellingKind::GNU)
  3998. .Case("CXX11", SpellingKind::CXX11)
  3999. .Case("C2x", SpellingKind::C2x)
  4000. .Case("Declspec", SpellingKind::Declspec)
  4001. .Case("Microsoft", SpellingKind::Microsoft)
  4002. .Case("Keyword", SpellingKind::Keyword)
  4003. .Case("Pragma", SpellingKind::Pragma);
  4004. std::string Name;
  4005. if (!Spelling.nameSpace().empty()) {
  4006. switch (Kind) {
  4007. case SpellingKind::CXX11:
  4008. case SpellingKind::C2x:
  4009. Name = Spelling.nameSpace() + "::";
  4010. break;
  4011. case SpellingKind::Pragma:
  4012. Name = Spelling.nameSpace() + " ";
  4013. break;
  4014. default:
  4015. PrintFatalError(Attr.getLoc(), "Unexpected namespace in spelling");
  4016. }
  4017. }
  4018. Name += Spelling.name();
  4019.  
  4020. Spellings[(size_t)Kind].push_back(Name);
  4021. }
  4022. };
  4023.  
  4024. class DocumentationData {
  4025. public:
  4026. const Record *Documentation;
  4027. const Record *Attribute;
  4028. std::string Heading;
  4029. SpellingList SupportedSpellings;
  4030.  
  4031. DocumentationData(const Record &Documentation, const Record &Attribute,
  4032. std::pair<std::string, SpellingList> HeadingAndSpellings)
  4033. : Documentation(&Documentation), Attribute(&Attribute),
  4034. Heading(std::move(HeadingAndSpellings.first)),
  4035. SupportedSpellings(std::move(HeadingAndSpellings.second)) {}
  4036. };
  4037.  
  4038. static void WriteCategoryHeader(const Record *DocCategory,
  4039. raw_ostream &OS) {
  4040. const StringRef Name = DocCategory->getValueAsString("Name");
  4041. OS << Name << "\n" << std::string(Name.size(), '=') << "\n";
  4042.  
  4043. // If there is content, print that as well.
  4044. const StringRef ContentStr = DocCategory->getValueAsString("Content");
  4045. // Trim leading and trailing newlines and spaces.
  4046. OS << ContentStr.trim();
  4047.  
  4048. OS << "\n\n";
  4049. }
  4050.  
  4051. static std::pair<std::string, SpellingList>
  4052. GetAttributeHeadingAndSpellings(const Record &Documentation,
  4053. const Record &Attribute) {
  4054. // FIXME: there is no way to have a per-spelling category for the attribute
  4055. // documentation. This may not be a limiting factor since the spellings
  4056. // should generally be consistently applied across the category.
  4057.  
  4058. std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(Attribute);
  4059. if (Spellings.empty())
  4060. PrintFatalError(Attribute.getLoc(),
  4061. "Attribute has no supported spellings; cannot be "
  4062. "documented");
  4063.  
  4064. // Determine the heading to be used for this attribute.
  4065. std::string Heading = std::string(Documentation.getValueAsString("Heading"));
  4066. if (Heading.empty()) {
  4067. // If there's only one spelling, we can simply use that.
  4068. if (Spellings.size() == 1)
  4069. Heading = Spellings.begin()->name();
  4070. else {
  4071. std::set<std::string> Uniques;
  4072. for (auto I = Spellings.begin(), E = Spellings.end();
  4073. I != E && Uniques.size() <= 1; ++I) {
  4074. std::string Spelling =
  4075. std::string(NormalizeNameForSpellingComparison(I->name()));
  4076. Uniques.insert(Spelling);
  4077. }
  4078. // If the semantic map has only one spelling, that is sufficient for our
  4079. // needs.
  4080. if (Uniques.size() == 1)
  4081. Heading = *Uniques.begin();
  4082. }
  4083. }
  4084.  
  4085. // If the heading is still empty, it is an error.
  4086. if (Heading.empty())
  4087. PrintFatalError(Attribute.getLoc(),
  4088. "This attribute requires a heading to be specified");
  4089.  
  4090. SpellingList SupportedSpellings;
  4091. for (const auto &I : Spellings)
  4092. SupportedSpellings.add(Attribute, I);
  4093.  
  4094. return std::make_pair(std::move(Heading), std::move(SupportedSpellings));
  4095. }
  4096.  
  4097. static void WriteDocumentation(RecordKeeper &Records,
  4098. const DocumentationData &Doc, raw_ostream &OS) {
  4099. OS << Doc.Heading << "\n" << std::string(Doc.Heading.length(), '-') << "\n";
  4100.  
  4101. // List what spelling syntaxes the attribute supports.
  4102. OS << ".. csv-table:: Supported Syntaxes\n";
  4103. OS << " :header: \"GNU\", \"C++11\", \"C2x\", \"``__declspec``\",";
  4104. OS << " \"Keyword\", \"``#pragma``\", \"``#pragma clang attribute``\"\n\n";
  4105. OS << " \"";
  4106. for (size_t Kind = 0; Kind != NumSpellingKinds; ++Kind) {
  4107. SpellingKind K = (SpellingKind)Kind;
  4108. // TODO: List Microsoft (IDL-style attribute) spellings once we fully
  4109. // support them.
  4110. if (K == SpellingKind::Microsoft)
  4111. continue;
  4112.  
  4113. bool PrintedAny = false;
  4114. for (StringRef Spelling : Doc.SupportedSpellings[K]) {
  4115. if (PrintedAny)
  4116. OS << " |br| ";
  4117. OS << "``" << Spelling << "``";
  4118. PrintedAny = true;
  4119. }
  4120.  
  4121. OS << "\",\"";
  4122. }
  4123.  
  4124. if (getPragmaAttributeSupport(Records).isAttributedSupported(
  4125. *Doc.Attribute))
  4126. OS << "Yes";
  4127. OS << "\"\n\n";
  4128.  
  4129. // If the attribute is deprecated, print a message about it, and possibly
  4130. // provide a replacement attribute.
  4131. if (!Doc.Documentation->isValueUnset("Deprecated")) {
  4132. OS << "This attribute has been deprecated, and may be removed in a future "
  4133. << "version of Clang.";
  4134. const Record &Deprecated = *Doc.Documentation->getValueAsDef("Deprecated");
  4135. const StringRef Replacement = Deprecated.getValueAsString("Replacement");
  4136. if (!Replacement.empty())
  4137. OS << " This attribute has been superseded by ``" << Replacement
  4138. << "``.";
  4139. OS << "\n\n";
  4140. }
  4141.  
  4142. const StringRef ContentStr = Doc.Documentation->getValueAsString("Content");
  4143. // Trim leading and trailing newlines and spaces.
  4144. OS << ContentStr.trim();
  4145.  
  4146. OS << "\n\n\n";
  4147. }
  4148.  
  4149. void EmitClangAttrDocs(RecordKeeper &Records, raw_ostream &OS) {
  4150. // Get the documentation introduction paragraph.
  4151. const Record *Documentation = Records.getDef("GlobalDocumentation");
  4152. if (!Documentation) {
  4153. PrintFatalError("The Documentation top-level definition is missing, "
  4154. "no documentation will be generated.");
  4155. return;
  4156. }
  4157.  
  4158. OS << Documentation->getValueAsString("Intro") << "\n";
  4159.  
  4160. // Gather the Documentation lists from each of the attributes, based on the
  4161. // category provided.
  4162. std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
  4163. std::map<const Record *, std::vector<DocumentationData>> SplitDocs;
  4164. for (const auto *A : Attrs) {
  4165. const Record &Attr = *A;
  4166. std::vector<Record *> Docs = Attr.getValueAsListOfDefs("Documentation");
  4167. for (const auto *D : Docs) {
  4168. const Record &Doc = *D;
  4169. const Record *Category = Doc.getValueAsDef("Category");
  4170. // If the category is "undocumented", then there cannot be any other
  4171. // documentation categories (otherwise, the attribute would become
  4172. // documented).
  4173. const StringRef Cat = Category->getValueAsString("Name");
  4174. bool Undocumented = Cat == "Undocumented";
  4175. if (Undocumented && Docs.size() > 1)
  4176. PrintFatalError(Doc.getLoc(),
  4177. "Attribute is \"Undocumented\", but has multiple "
  4178. "documentation categories");
  4179.  
  4180. if (!Undocumented)
  4181. SplitDocs[Category].push_back(DocumentationData(
  4182. Doc, Attr, GetAttributeHeadingAndSpellings(Doc, Attr)));
  4183. }
  4184. }
  4185.  
  4186. // Having split the attributes out based on what documentation goes where,
  4187. // we can begin to generate sections of documentation.
  4188. for (auto &I : SplitDocs) {
  4189. WriteCategoryHeader(I.first, OS);
  4190.  
  4191. llvm::sort(I.second,
  4192. [](const DocumentationData &D1, const DocumentationData &D2) {
  4193. return D1.Heading < D2.Heading;
  4194. });
  4195.  
  4196. // Walk over each of the attributes in the category and write out their
  4197. // documentation.
  4198. for (const auto &Doc : I.second)
  4199. WriteDocumentation(Records, Doc, OS);
  4200. }
  4201. }
  4202.  
  4203. void EmitTestPragmaAttributeSupportedAttributes(RecordKeeper &Records,
  4204. raw_ostream &OS) {
  4205. PragmaClangAttributeSupport Support = getPragmaAttributeSupport(Records);
  4206. ParsedAttrMap Attrs = getParsedAttrList(Records);
  4207. OS << "#pragma clang attribute supports the following attributes:\n";
  4208. for (const auto &I : Attrs) {
  4209. if (!Support.isAttributedSupported(*I.second))
  4210. continue;
  4211. OS << I.first;
  4212. if (I.second->isValueUnset("Subjects")) {
  4213. OS << " ()\n";
  4214. continue;
  4215. }
  4216. const Record *SubjectObj = I.second->getValueAsDef("Subjects");
  4217. std::vector<Record *> Subjects =
  4218. SubjectObj->getValueAsListOfDefs("Subjects");
  4219. OS << " (";
  4220. for (const auto &Subject : llvm::enumerate(Subjects)) {
  4221. if (Subject.index())
  4222. OS << ", ";
  4223. PragmaClangAttributeSupport::RuleOrAggregateRuleSet &RuleSet =
  4224. Support.SubjectsToRules.find(Subject.value())->getSecond();
  4225. if (RuleSet.isRule()) {
  4226. OS << RuleSet.getRule().getEnumValueName();
  4227. continue;
  4228. }
  4229. OS << "(";
  4230. for (const auto &Rule : llvm::enumerate(RuleSet.getAggregateRuleSet())) {
  4231. if (Rule.index())
  4232. OS << ", ";
  4233. OS << Rule.value().getEnumValueName();
  4234. }
  4235. OS << ")";
  4236. }
  4237. OS << ")\n";
  4238. }
  4239. OS << "End of supported attributes.\n";
  4240. }
  4241.  
  4242. } // end namespace clang
  4243. diff --git a/clang/utils/TableGen/TableGen.cpp b/clang/utils/TableGen/TableGen.cpp
  4244. index 1d6ef80..ff2fc436 100644
  4245. --- a/clang/utils/TableGen/TableGen.cpp
  4246. +++ b/clang/utils/TableGen/TableGen.cpp
  4247. @@ -1,457 +1,463 @@
  4248. //===- TableGen.cpp - Top-Level TableGen implementation for Clang ---------===//
  4249. //
  4250. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4251. // See https://llvm.org/LICENSE.txt for license information.
  4252. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  4253. //
  4254. //===----------------------------------------------------------------------===//
  4255. //
  4256. // This file contains the main function for Clang's TableGen.
  4257. //
  4258. //===----------------------------------------------------------------------===//
  4259.  
  4260. #include "TableGenBackends.h" // Declares all backends.
  4261. #include "ASTTableGen.h"
  4262. #include "llvm/Support/CommandLine.h"
  4263. #include "llvm/Support/PrettyStackTrace.h"
  4264. #include "llvm/Support/Signals.h"
  4265. #include "llvm/TableGen/Error.h"
  4266. #include "llvm/TableGen/Main.h"
  4267. #include "llvm/TableGen/Record.h"
  4268.  
  4269. using namespace llvm;
  4270. using namespace clang;
  4271.  
  4272. enum ActionType {
  4273. PrintRecords,
  4274. DumpJSON,
  4275. GenClangAttrClasses,
  4276. GenClangAttrParserStringSwitches,
  4277. GenClangAttrSubjectMatchRulesParserStringSwitches,
  4278. GenClangAttrImpl,
  4279. GenClangAttrList,
  4280. GenClangAttrSubjectMatchRuleList,
  4281. GenClangAttrPCHRead,
  4282. GenClangAttrPCHWrite,
  4283. GenClangAttrHasAttributeImpl,
  4284. GenClangAttrSpellingListIndex,
  4285. GenClangAttrASTVisitor,
  4286. GenClangAttrTemplateInstantiate,
  4287. GenClangAttrParsedAttrList,
  4288. GenClangAttrParsedAttrImpl,
  4289. GenClangAttrParsedAttrKinds,
  4290. + GenClangAttrJSONNodeDump,
  4291. GenClangAttrTextNodeDump,
  4292. GenClangAttrNodeTraverse,
  4293. GenClangBasicReader,
  4294. GenClangBasicWriter,
  4295. GenClangDiagsDefs,
  4296. GenClangDiagGroups,
  4297. GenClangDiagsIndexName,
  4298. GenClangCommentNodes,
  4299. GenClangDeclNodes,
  4300. GenClangStmtNodes,
  4301. GenClangTypeNodes,
  4302. GenClangTypeReader,
  4303. GenClangTypeWriter,
  4304. GenClangOpcodes,
  4305. GenClangSACheckers,
  4306. GenClangCommentHTMLTags,
  4307. GenClangCommentHTMLTagsProperties,
  4308. GenClangCommentHTMLNamedCharacterReferences,
  4309. GenClangCommentCommandInfo,
  4310. GenClangCommentCommandList,
  4311. GenClangOpenCLBuiltins,
  4312. GenArmNeon,
  4313. GenArmFP16,
  4314. GenArmBF16,
  4315. GenArmNeonSema,
  4316. GenArmNeonTest,
  4317. GenArmMveHeader,
  4318. GenArmMveBuiltinDef,
  4319. GenArmMveBuiltinSema,
  4320. GenArmMveBuiltinCG,
  4321. GenArmMveBuiltinAliases,
  4322. GenArmSveHeader,
  4323. GenArmSveBuiltins,
  4324. GenArmSveBuiltinCG,
  4325. GenArmSveTypeFlags,
  4326. GenArmSveRangeChecks,
  4327. GenArmCdeHeader,
  4328. GenArmCdeBuiltinDef,
  4329. GenArmCdeBuiltinSema,
  4330. GenArmCdeBuiltinCG,
  4331. GenArmCdeBuiltinAliases,
  4332. GenAttrDocs,
  4333. GenDiagDocs,
  4334. GenOptDocs,
  4335. GenDataCollectors,
  4336. GenTestPragmaAttributeSupportedAttributes
  4337. };
  4338.  
  4339. namespace {
  4340. cl::opt<ActionType> Action(
  4341. cl::desc("Action to perform:"),
  4342. cl::values(
  4343. clEnumValN(PrintRecords, "print-records",
  4344. "Print all records to stdout (default)"),
  4345. clEnumValN(DumpJSON, "dump-json",
  4346. "Dump all records as machine-readable JSON"),
  4347. clEnumValN(GenClangAttrClasses, "gen-clang-attr-classes",
  4348. "Generate clang attribute clases"),
  4349. clEnumValN(GenClangAttrParserStringSwitches,
  4350. "gen-clang-attr-parser-string-switches",
  4351. "Generate all parser-related attribute string switches"),
  4352. clEnumValN(GenClangAttrSubjectMatchRulesParserStringSwitches,
  4353. "gen-clang-attr-subject-match-rules-parser-string-switches",
  4354. "Generate all parser-related attribute subject match rule"
  4355. "string switches"),
  4356. clEnumValN(GenClangAttrImpl, "gen-clang-attr-impl",
  4357. "Generate clang attribute implementations"),
  4358. clEnumValN(GenClangAttrList, "gen-clang-attr-list",
  4359. "Generate a clang attribute list"),
  4360. clEnumValN(GenClangAttrSubjectMatchRuleList,
  4361. "gen-clang-attr-subject-match-rule-list",
  4362. "Generate a clang attribute subject match rule list"),
  4363. clEnumValN(GenClangAttrPCHRead, "gen-clang-attr-pch-read",
  4364. "Generate clang PCH attribute reader"),
  4365. clEnumValN(GenClangAttrPCHWrite, "gen-clang-attr-pch-write",
  4366. "Generate clang PCH attribute writer"),
  4367. clEnumValN(GenClangAttrHasAttributeImpl,
  4368. "gen-clang-attr-has-attribute-impl",
  4369. "Generate a clang attribute spelling list"),
  4370. clEnumValN(GenClangAttrSpellingListIndex,
  4371. "gen-clang-attr-spelling-index",
  4372. "Generate a clang attribute spelling index"),
  4373. clEnumValN(GenClangAttrASTVisitor, "gen-clang-attr-ast-visitor",
  4374. "Generate a recursive AST visitor for clang attributes"),
  4375. clEnumValN(GenClangAttrTemplateInstantiate,
  4376. "gen-clang-attr-template-instantiate",
  4377. "Generate a clang template instantiate code"),
  4378. clEnumValN(GenClangAttrParsedAttrList,
  4379. "gen-clang-attr-parsed-attr-list",
  4380. "Generate a clang parsed attribute list"),
  4381. clEnumValN(GenClangAttrParsedAttrImpl,
  4382. "gen-clang-attr-parsed-attr-impl",
  4383. "Generate the clang parsed attribute helpers"),
  4384. clEnumValN(GenClangAttrParsedAttrKinds,
  4385. "gen-clang-attr-parsed-attr-kinds",
  4386. "Generate a clang parsed attribute kinds"),
  4387. + clEnumValN(GenClangAttrJSONNodeDump, "gen-clang-attr-json-node-dump",
  4388. + "Generate clang attribute JSON node dumper"),
  4389. clEnumValN(GenClangAttrTextNodeDump, "gen-clang-attr-text-node-dump",
  4390. "Generate clang attribute text node dumper"),
  4391. clEnumValN(GenClangAttrNodeTraverse, "gen-clang-attr-node-traverse",
  4392. "Generate clang attribute traverser"),
  4393. clEnumValN(GenClangDiagsDefs, "gen-clang-diags-defs",
  4394. "Generate Clang diagnostics definitions"),
  4395. clEnumValN(GenClangDiagGroups, "gen-clang-diag-groups",
  4396. "Generate Clang diagnostic groups"),
  4397. clEnumValN(GenClangDiagsIndexName, "gen-clang-diags-index-name",
  4398. "Generate Clang diagnostic name index"),
  4399. clEnumValN(GenClangBasicReader, "gen-clang-basic-reader",
  4400. "Generate Clang BasicReader classes"),
  4401. clEnumValN(GenClangBasicWriter, "gen-clang-basic-writer",
  4402. "Generate Clang BasicWriter classes"),
  4403. clEnumValN(GenClangCommentNodes, "gen-clang-comment-nodes",
  4404. "Generate Clang AST comment nodes"),
  4405. clEnumValN(GenClangDeclNodes, "gen-clang-decl-nodes",
  4406. "Generate Clang AST declaration nodes"),
  4407. clEnumValN(GenClangStmtNodes, "gen-clang-stmt-nodes",
  4408. "Generate Clang AST statement nodes"),
  4409. clEnumValN(GenClangTypeNodes, "gen-clang-type-nodes",
  4410. "Generate Clang AST type nodes"),
  4411. clEnumValN(GenClangTypeReader, "gen-clang-type-reader",
  4412. "Generate Clang AbstractTypeReader class"),
  4413. clEnumValN(GenClangTypeWriter, "gen-clang-type-writer",
  4414. "Generate Clang AbstractTypeWriter class"),
  4415. clEnumValN(GenClangOpcodes, "gen-clang-opcodes",
  4416. "Generate Clang constexpr interpreter opcodes"),
  4417. clEnumValN(GenClangSACheckers, "gen-clang-sa-checkers",
  4418. "Generate Clang Static Analyzer checkers"),
  4419. clEnumValN(GenClangCommentHTMLTags, "gen-clang-comment-html-tags",
  4420. "Generate efficient matchers for HTML tag "
  4421. "names that are used in documentation comments"),
  4422. clEnumValN(GenClangCommentHTMLTagsProperties,
  4423. "gen-clang-comment-html-tags-properties",
  4424. "Generate efficient matchers for HTML tag "
  4425. "properties"),
  4426. clEnumValN(GenClangCommentHTMLNamedCharacterReferences,
  4427. "gen-clang-comment-html-named-character-references",
  4428. "Generate function to translate named character "
  4429. "references to UTF-8 sequences"),
  4430. clEnumValN(GenClangCommentCommandInfo, "gen-clang-comment-command-info",
  4431. "Generate command properties for commands that "
  4432. "are used in documentation comments"),
  4433. clEnumValN(GenClangCommentCommandList, "gen-clang-comment-command-list",
  4434. "Generate list of commands that are used in "
  4435. "documentation comments"),
  4436. clEnumValN(GenClangOpenCLBuiltins, "gen-clang-opencl-builtins",
  4437. "Generate OpenCL builtin declaration handlers"),
  4438. clEnumValN(GenArmNeon, "gen-arm-neon", "Generate arm_neon.h for clang"),
  4439. clEnumValN(GenArmFP16, "gen-arm-fp16", "Generate arm_fp16.h for clang"),
  4440. clEnumValN(GenArmBF16, "gen-arm-bf16", "Generate arm_bf16.h for clang"),
  4441. clEnumValN(GenArmNeonSema, "gen-arm-neon-sema",
  4442. "Generate ARM NEON sema support for clang"),
  4443. clEnumValN(GenArmNeonTest, "gen-arm-neon-test",
  4444. "Generate ARM NEON tests for clang"),
  4445. clEnumValN(GenArmSveHeader, "gen-arm-sve-header",
  4446. "Generate arm_sve.h for clang"),
  4447. clEnumValN(GenArmSveBuiltins, "gen-arm-sve-builtins",
  4448. "Generate arm_sve_builtins.inc for clang"),
  4449. clEnumValN(GenArmSveBuiltinCG, "gen-arm-sve-builtin-codegen",
  4450. "Generate arm_sve_builtin_cg_map.inc for clang"),
  4451. clEnumValN(GenArmSveTypeFlags, "gen-arm-sve-typeflags",
  4452. "Generate arm_sve_typeflags.inc for clang"),
  4453. clEnumValN(GenArmSveRangeChecks, "gen-arm-sve-sema-rangechecks",
  4454. "Generate arm_sve_sema_rangechecks.inc for clang"),
  4455. clEnumValN(GenArmMveHeader, "gen-arm-mve-header",
  4456. "Generate arm_mve.h for clang"),
  4457. clEnumValN(GenArmMveBuiltinDef, "gen-arm-mve-builtin-def",
  4458. "Generate ARM MVE builtin definitions for clang"),
  4459. clEnumValN(GenArmMveBuiltinSema, "gen-arm-mve-builtin-sema",
  4460. "Generate ARM MVE builtin sema checks for clang"),
  4461. clEnumValN(GenArmMveBuiltinCG, "gen-arm-mve-builtin-codegen",
  4462. "Generate ARM MVE builtin code-generator for clang"),
  4463. clEnumValN(GenArmMveBuiltinAliases, "gen-arm-mve-builtin-aliases",
  4464. "Generate list of valid ARM MVE builtin aliases for clang"),
  4465. clEnumValN(GenArmCdeHeader, "gen-arm-cde-header",
  4466. "Generate arm_cde.h for clang"),
  4467. clEnumValN(GenArmCdeBuiltinDef, "gen-arm-cde-builtin-def",
  4468. "Generate ARM CDE builtin definitions for clang"),
  4469. clEnumValN(GenArmCdeBuiltinSema, "gen-arm-cde-builtin-sema",
  4470. "Generate ARM CDE builtin sema checks for clang"),
  4471. clEnumValN(GenArmCdeBuiltinCG, "gen-arm-cde-builtin-codegen",
  4472. "Generate ARM CDE builtin code-generator for clang"),
  4473. clEnumValN(GenArmCdeBuiltinAliases, "gen-arm-cde-builtin-aliases",
  4474. "Generate list of valid ARM CDE builtin aliases for clang"),
  4475. clEnumValN(GenAttrDocs, "gen-attr-docs",
  4476. "Generate attribute documentation"),
  4477. clEnumValN(GenDiagDocs, "gen-diag-docs",
  4478. "Generate diagnostic documentation"),
  4479. clEnumValN(GenOptDocs, "gen-opt-docs", "Generate option documentation"),
  4480. clEnumValN(GenDataCollectors, "gen-clang-data-collectors",
  4481. "Generate data collectors for AST nodes"),
  4482. clEnumValN(GenTestPragmaAttributeSupportedAttributes,
  4483. "gen-clang-test-pragma-attribute-supported-attributes",
  4484. "Generate a list of attributes supported by #pragma clang "
  4485. "attribute for testing purposes")));
  4486.  
  4487. cl::opt<std::string>
  4488. ClangComponent("clang-component",
  4489. cl::desc("Only use warnings from specified component"),
  4490. cl::value_desc("component"), cl::Hidden);
  4491.  
  4492. bool ClangTableGenMain(raw_ostream &OS, RecordKeeper &Records) {
  4493. switch (Action) {
  4494. case PrintRecords:
  4495. OS << Records; // No argument, dump all contents
  4496. break;
  4497. case DumpJSON:
  4498. EmitJSON(Records, OS);
  4499. break;
  4500. case GenClangAttrClasses:
  4501. EmitClangAttrClass(Records, OS);
  4502. break;
  4503. case GenClangAttrParserStringSwitches:
  4504. EmitClangAttrParserStringSwitches(Records, OS);
  4505. break;
  4506. case GenClangAttrSubjectMatchRulesParserStringSwitches:
  4507. EmitClangAttrSubjectMatchRulesParserStringSwitches(Records, OS);
  4508. break;
  4509. case GenClangAttrImpl:
  4510. EmitClangAttrImpl(Records, OS);
  4511. break;
  4512. case GenClangAttrList:
  4513. EmitClangAttrList(Records, OS);
  4514. break;
  4515. case GenClangAttrSubjectMatchRuleList:
  4516. EmitClangAttrSubjectMatchRuleList(Records, OS);
  4517. break;
  4518. case GenClangAttrPCHRead:
  4519. EmitClangAttrPCHRead(Records, OS);
  4520. break;
  4521. case GenClangAttrPCHWrite:
  4522. EmitClangAttrPCHWrite(Records, OS);
  4523. break;
  4524. case GenClangAttrHasAttributeImpl:
  4525. EmitClangAttrHasAttrImpl(Records, OS);
  4526. break;
  4527. case GenClangAttrSpellingListIndex:
  4528. EmitClangAttrSpellingListIndex(Records, OS);
  4529. break;
  4530. case GenClangAttrASTVisitor:
  4531. EmitClangAttrASTVisitor(Records, OS);
  4532. break;
  4533. case GenClangAttrTemplateInstantiate:
  4534. EmitClangAttrTemplateInstantiate(Records, OS);
  4535. break;
  4536. case GenClangAttrParsedAttrList:
  4537. EmitClangAttrParsedAttrList(Records, OS);
  4538. break;
  4539. case GenClangAttrParsedAttrImpl:
  4540. EmitClangAttrParsedAttrImpl(Records, OS);
  4541. break;
  4542. case GenClangAttrParsedAttrKinds:
  4543. EmitClangAttrParsedAttrKinds(Records, OS);
  4544. break;
  4545. + case GenClangAttrJSONNodeDump:
  4546. + EmitClangAttrJSONNodeDump(Records, OS);
  4547. + break;
  4548. case GenClangAttrTextNodeDump:
  4549. EmitClangAttrTextNodeDump(Records, OS);
  4550. break;
  4551. case GenClangAttrNodeTraverse:
  4552. EmitClangAttrNodeTraverse(Records, OS);
  4553. break;
  4554. case GenClangDiagsDefs:
  4555. EmitClangDiagsDefs(Records, OS, ClangComponent);
  4556. break;
  4557. case GenClangDiagGroups:
  4558. EmitClangDiagGroups(Records, OS);
  4559. break;
  4560. case GenClangDiagsIndexName:
  4561. EmitClangDiagsIndexName(Records, OS);
  4562. break;
  4563. case GenClangCommentNodes:
  4564. EmitClangASTNodes(Records, OS, CommentNodeClassName, "");
  4565. break;
  4566. case GenClangDeclNodes:
  4567. EmitClangASTNodes(Records, OS, DeclNodeClassName, "Decl");
  4568. EmitClangDeclContext(Records, OS);
  4569. break;
  4570. case GenClangStmtNodes:
  4571. EmitClangASTNodes(Records, OS, StmtNodeClassName, "");
  4572. break;
  4573. case GenClangTypeNodes:
  4574. EmitClangTypeNodes(Records, OS);
  4575. break;
  4576. case GenClangTypeReader:
  4577. EmitClangTypeReader(Records, OS);
  4578. break;
  4579. case GenClangTypeWriter:
  4580. EmitClangTypeWriter(Records, OS);
  4581. break;
  4582. case GenClangBasicReader:
  4583. EmitClangBasicReader(Records, OS);
  4584. break;
  4585. case GenClangBasicWriter:
  4586. EmitClangBasicWriter(Records, OS);
  4587. break;
  4588. case GenClangOpcodes:
  4589. EmitClangOpcodes(Records, OS);
  4590. break;
  4591. case GenClangSACheckers:
  4592. EmitClangSACheckers(Records, OS);
  4593. break;
  4594. case GenClangCommentHTMLTags:
  4595. EmitClangCommentHTMLTags(Records, OS);
  4596. break;
  4597. case GenClangCommentHTMLTagsProperties:
  4598. EmitClangCommentHTMLTagsProperties(Records, OS);
  4599. break;
  4600. case GenClangCommentHTMLNamedCharacterReferences:
  4601. EmitClangCommentHTMLNamedCharacterReferences(Records, OS);
  4602. break;
  4603. case GenClangCommentCommandInfo:
  4604. EmitClangCommentCommandInfo(Records, OS);
  4605. break;
  4606. case GenClangCommentCommandList:
  4607. EmitClangCommentCommandList(Records, OS);
  4608. break;
  4609. case GenClangOpenCLBuiltins:
  4610. EmitClangOpenCLBuiltins(Records, OS);
  4611. break;
  4612. case GenArmNeon:
  4613. EmitNeon(Records, OS);
  4614. break;
  4615. case GenArmFP16:
  4616. EmitFP16(Records, OS);
  4617. break;
  4618. case GenArmBF16:
  4619. EmitBF16(Records, OS);
  4620. break;
  4621. case GenArmNeonSema:
  4622. EmitNeonSema(Records, OS);
  4623. break;
  4624. case GenArmNeonTest:
  4625. EmitNeonTest(Records, OS);
  4626. break;
  4627. case GenArmMveHeader:
  4628. EmitMveHeader(Records, OS);
  4629. break;
  4630. case GenArmMveBuiltinDef:
  4631. EmitMveBuiltinDef(Records, OS);
  4632. break;
  4633. case GenArmMveBuiltinSema:
  4634. EmitMveBuiltinSema(Records, OS);
  4635. break;
  4636. case GenArmMveBuiltinCG:
  4637. EmitMveBuiltinCG(Records, OS);
  4638. break;
  4639. case GenArmMveBuiltinAliases:
  4640. EmitMveBuiltinAliases(Records, OS);
  4641. break;
  4642. case GenArmSveHeader:
  4643. EmitSveHeader(Records, OS);
  4644. break;
  4645. case GenArmSveBuiltins:
  4646. EmitSveBuiltins(Records, OS);
  4647. break;
  4648. case GenArmSveBuiltinCG:
  4649. EmitSveBuiltinCG(Records, OS);
  4650. break;
  4651. case GenArmSveTypeFlags:
  4652. EmitSveTypeFlags(Records, OS);
  4653. break;
  4654. case GenArmSveRangeChecks:
  4655. EmitSveRangeChecks(Records, OS);
  4656. break;
  4657. case GenArmCdeHeader:
  4658. EmitCdeHeader(Records, OS);
  4659. break;
  4660. case GenArmCdeBuiltinDef:
  4661. EmitCdeBuiltinDef(Records, OS);
  4662. break;
  4663. case GenArmCdeBuiltinSema:
  4664. EmitCdeBuiltinSema(Records, OS);
  4665. break;
  4666. case GenArmCdeBuiltinCG:
  4667. EmitCdeBuiltinCG(Records, OS);
  4668. break;
  4669. case GenArmCdeBuiltinAliases:
  4670. EmitCdeBuiltinAliases(Records, OS);
  4671. break;
  4672. case GenAttrDocs:
  4673. EmitClangAttrDocs(Records, OS);
  4674. break;
  4675. case GenDiagDocs:
  4676. EmitClangDiagDocs(Records, OS);
  4677. break;
  4678. case GenOptDocs:
  4679. EmitClangOptDocs(Records, OS);
  4680. break;
  4681. case GenDataCollectors:
  4682. EmitClangDataCollectors(Records, OS);
  4683. break;
  4684. case GenTestPragmaAttributeSupportedAttributes:
  4685. EmitTestPragmaAttributeSupportedAttributes(Records, OS);
  4686. break;
  4687. }
  4688.  
  4689. return false;
  4690. }
  4691. }
  4692.  
  4693. int main(int argc, char **argv) {
  4694. sys::PrintStackTraceOnErrorSignal(argv[0]);
  4695. PrettyStackTraceProgram X(argc, argv);
  4696. cl::ParseCommandLineOptions(argc, argv);
  4697.  
  4698. llvm_shutdown_obj Y;
  4699.  
  4700. return TableGenMain(argv[0], &ClangTableGenMain);
  4701. }
  4702.  
  4703. #ifdef __has_feature
  4704. #if __has_feature(address_sanitizer)
  4705. #include <sanitizer/lsan_interface.h>
  4706. // Disable LeakSanitizer for this binary as it has too many leaks that are not
  4707. // very interesting to fix. See compiler-rt/include/sanitizer/lsan_interface.h .
  4708. int __lsan_is_turned_off() { return 1; }
  4709. #endif // __has_feature(address_sanitizer)
  4710. #endif // defined(__has_feature)
  4711. diff --git a/clang/utils/TableGen/TableGenBackends.h b/clang/utils/TableGen/TableGenBackends.h
  4712. index 9717903..21127d4 100644
  4713. --- a/clang/utils/TableGen/TableGenBackends.h
  4714. +++ b/clang/utils/TableGen/TableGenBackends.h
  4715. @@ -1,128 +1,130 @@
  4716. //===- TableGenBackends.h - Declarations for Clang TableGen Backends ------===//
  4717. //
  4718. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4719. // See https://llvm.org/LICENSE.txt for license information.
  4720. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  4721. //
  4722. //===----------------------------------------------------------------------===//
  4723. //
  4724. // This file contains the declarations for all of the Clang TableGen
  4725. // backends. A "TableGen backend" is just a function. See
  4726. // "$LLVM_ROOT/utils/TableGen/TableGenBackends.h" for more info.
  4727. //
  4728. //===----------------------------------------------------------------------===//
  4729.  
  4730. #ifndef LLVM_CLANG_UTILS_TABLEGEN_TABLEGENBACKENDS_H
  4731. #define LLVM_CLANG_UTILS_TABLEGEN_TABLEGENBACKENDS_H
  4732.  
  4733. #include <string>
  4734.  
  4735. namespace llvm {
  4736. class raw_ostream;
  4737. class RecordKeeper;
  4738. } // namespace llvm
  4739.  
  4740. namespace clang {
  4741.  
  4742. void EmitClangDeclContext(llvm::RecordKeeper &RK, llvm::raw_ostream &OS);
  4743. void EmitClangASTNodes(llvm::RecordKeeper &RK, llvm::raw_ostream &OS,
  4744. const std::string &N, const std::string &S);
  4745. void EmitClangBasicReader(llvm::RecordKeeper &Records, llvm::raw_ostream &OS);
  4746. void EmitClangBasicWriter(llvm::RecordKeeper &Records, llvm::raw_ostream &OS);
  4747. void EmitClangTypeNodes(llvm::RecordKeeper &Records, llvm::raw_ostream &OS);
  4748. void EmitClangTypeReader(llvm::RecordKeeper &Records, llvm::raw_ostream &OS);
  4749. void EmitClangTypeWriter(llvm::RecordKeeper &Records, llvm::raw_ostream &OS);
  4750. void EmitClangAttrParserStringSwitches(llvm::RecordKeeper &Records,
  4751. llvm::raw_ostream &OS);
  4752. void EmitClangAttrSubjectMatchRulesParserStringSwitches(
  4753. llvm::RecordKeeper &Records, llvm::raw_ostream &OS);
  4754. void EmitClangAttrClass(llvm::RecordKeeper &Records, llvm::raw_ostream &OS);
  4755. void EmitClangAttrImpl(llvm::RecordKeeper &Records, llvm::raw_ostream &OS);
  4756. void EmitClangAttrList(llvm::RecordKeeper &Records, llvm::raw_ostream &OS);
  4757. void EmitClangAttrSubjectMatchRuleList(llvm::RecordKeeper &Records,
  4758. llvm::raw_ostream &OS);
  4759. void EmitClangAttrPCHRead(llvm::RecordKeeper &Records, llvm::raw_ostream &OS);
  4760. void EmitClangAttrPCHWrite(llvm::RecordKeeper &Records, llvm::raw_ostream &OS);
  4761. void EmitClangAttrHasAttrImpl(llvm::RecordKeeper &Records,
  4762. llvm::raw_ostream &OS);
  4763. void EmitClangAttrSpellingListIndex(llvm::RecordKeeper &Records,
  4764. llvm::raw_ostream &OS);
  4765. void EmitClangAttrASTVisitor(llvm::RecordKeeper &Records,
  4766. llvm::raw_ostream &OS);
  4767. void EmitClangAttrTemplateInstantiate(llvm::RecordKeeper &Records,
  4768. llvm::raw_ostream &OS);
  4769. void EmitClangAttrParsedAttrList(llvm::RecordKeeper &Records,
  4770. llvm::raw_ostream &OS);
  4771. void EmitClangAttrParsedAttrImpl(llvm::RecordKeeper &Records,
  4772. llvm::raw_ostream &OS);
  4773. void EmitClangAttrParsedAttrKinds(llvm::RecordKeeper &Records,
  4774. llvm::raw_ostream &OS);
  4775. +void EmitClangAttrJSONNodeDump(llvm::RecordKeeper &Records,
  4776. + llvm::raw_ostream &OS);
  4777. void EmitClangAttrTextNodeDump(llvm::RecordKeeper &Records,
  4778. llvm::raw_ostream &OS);
  4779. void EmitClangAttrNodeTraverse(llvm::RecordKeeper &Records,
  4780. llvm::raw_ostream &OS);
  4781.  
  4782. void EmitClangDiagsDefs(llvm::RecordKeeper &Records, llvm::raw_ostream &OS,
  4783. const std::string &Component);
  4784. void EmitClangDiagGroups(llvm::RecordKeeper &Records, llvm::raw_ostream &OS);
  4785. void EmitClangDiagsIndexName(llvm::RecordKeeper &Records,
  4786. llvm::raw_ostream &OS);
  4787.  
  4788. void EmitClangSACheckers(llvm::RecordKeeper &Records, llvm::raw_ostream &OS);
  4789.  
  4790. void EmitClangCommentHTMLTags(llvm::RecordKeeper &Records,
  4791. llvm::raw_ostream &OS);
  4792. void EmitClangCommentHTMLTagsProperties(llvm::RecordKeeper &Records,
  4793. llvm::raw_ostream &OS);
  4794. void EmitClangCommentHTMLNamedCharacterReferences(llvm::RecordKeeper &Records,
  4795. llvm::raw_ostream &OS);
  4796.  
  4797. void EmitClangCommentCommandInfo(llvm::RecordKeeper &Records,
  4798. llvm::raw_ostream &OS);
  4799. void EmitClangCommentCommandList(llvm::RecordKeeper &Records,
  4800. llvm::raw_ostream &OS);
  4801. void EmitClangOpcodes(llvm::RecordKeeper &Records, llvm::raw_ostream &OS);
  4802.  
  4803. void EmitNeon(llvm::RecordKeeper &Records, llvm::raw_ostream &OS);
  4804. void EmitFP16(llvm::RecordKeeper &Records, llvm::raw_ostream &OS);
  4805. void EmitBF16(llvm::RecordKeeper &Records, llvm::raw_ostream &OS);
  4806. void EmitNeonSema(llvm::RecordKeeper &Records, llvm::raw_ostream &OS);
  4807. void EmitNeonTest(llvm::RecordKeeper &Records, llvm::raw_ostream &OS);
  4808. void EmitNeon2(llvm::RecordKeeper &Records, llvm::raw_ostream &OS);
  4809. void EmitNeonSema2(llvm::RecordKeeper &Records, llvm::raw_ostream &OS);
  4810. void EmitNeonTest2(llvm::RecordKeeper &Records, llvm::raw_ostream &OS);
  4811.  
  4812. void EmitSveHeader(llvm::RecordKeeper &Records, llvm::raw_ostream &OS);
  4813. void EmitSveBuiltins(llvm::RecordKeeper &Records, llvm::raw_ostream &OS);
  4814. void EmitSveBuiltinCG(llvm::RecordKeeper &Records, llvm::raw_ostream &OS);
  4815. void EmitSveTypeFlags(llvm::RecordKeeper &Records, llvm::raw_ostream &OS);
  4816. void EmitSveRangeChecks(llvm::RecordKeeper &Records, llvm::raw_ostream &OS);
  4817.  
  4818. void EmitMveHeader(llvm::RecordKeeper &Records, llvm::raw_ostream &OS);
  4819. void EmitMveBuiltinDef(llvm::RecordKeeper &Records, llvm::raw_ostream &OS);
  4820. void EmitMveBuiltinSema(llvm::RecordKeeper &Records, llvm::raw_ostream &OS);
  4821. void EmitMveBuiltinCG(llvm::RecordKeeper &Records, llvm::raw_ostream &OS);
  4822. void EmitMveBuiltinAliases(llvm::RecordKeeper &Records, llvm::raw_ostream &OS);
  4823.  
  4824. void EmitCdeHeader(llvm::RecordKeeper &Records, llvm::raw_ostream &OS);
  4825. void EmitCdeBuiltinDef(llvm::RecordKeeper &Records, llvm::raw_ostream &OS);
  4826. void EmitCdeBuiltinSema(llvm::RecordKeeper &Records, llvm::raw_ostream &OS);
  4827. void EmitCdeBuiltinCG(llvm::RecordKeeper &Records, llvm::raw_ostream &OS);
  4828. void EmitCdeBuiltinAliases(llvm::RecordKeeper &Records, llvm::raw_ostream &OS);
  4829.  
  4830. void EmitClangAttrDocs(llvm::RecordKeeper &Records, llvm::raw_ostream &OS);
  4831. void EmitClangDiagDocs(llvm::RecordKeeper &Records, llvm::raw_ostream &OS);
  4832. void EmitClangOptDocs(llvm::RecordKeeper &Records, llvm::raw_ostream &OS);
  4833.  
  4834. void EmitClangOpenCLBuiltins(llvm::RecordKeeper &Records,
  4835. llvm::raw_ostream &OS);
  4836.  
  4837. void EmitClangDataCollectors(llvm::RecordKeeper &Records,
  4838. llvm::raw_ostream &OS);
  4839.  
  4840. void EmitTestPragmaAttributeSupportedAttributes(llvm::RecordKeeper &Records,
  4841. llvm::raw_ostream &OS);
  4842.  
  4843. } // end namespace clang
  4844.  
  4845. #endif
  4846.  
Add Comment
Please, Sign In to add comment