ClangAttrEmitter.cpp 109 KB

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