Record.cpp 81 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736
  1. //===- Record.cpp - Record implementation ---------------------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // Implement the tablegen record classes.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "llvm/ADT/ArrayRef.h"
  13. #include "llvm/ADT/DenseMap.h"
  14. #include "llvm/ADT/FoldingSet.h"
  15. #include "llvm/ADT/SmallString.h"
  16. #include "llvm/ADT/SmallVector.h"
  17. #include "llvm/ADT/Statistic.h"
  18. #include "llvm/ADT/StringExtras.h"
  19. #include "llvm/ADT/StringMap.h"
  20. #include "llvm/ADT/StringRef.h"
  21. #include "llvm/ADT/StringSet.h"
  22. #include "llvm/Config/llvm-config.h"
  23. #include "llvm/Support/Allocator.h"
  24. #include "llvm/Support/Casting.h"
  25. #include "llvm/Support/Compiler.h"
  26. #include "llvm/Support/ErrorHandling.h"
  27. #include "llvm/Support/SMLoc.h"
  28. #include "llvm/Support/raw_ostream.h"
  29. #include "llvm/TableGen/Error.h"
  30. #include "llvm/TableGen/Record.h"
  31. #include <cassert>
  32. #include <cstdint>
  33. #include <memory>
  34. #include <map>
  35. #include <string>
  36. #include <utility>
  37. #include <vector>
  38. using namespace llvm;
  39. #define DEBUG_TYPE "tblgen-records"
  40. static BumpPtrAllocator Allocator;
  41. //===----------------------------------------------------------------------===//
  42. // Type implementations
  43. //===----------------------------------------------------------------------===//
  44. BitRecTy BitRecTy::Shared;
  45. IntRecTy IntRecTy::Shared;
  46. StringRecTy StringRecTy::Shared;
  47. DagRecTy DagRecTy::Shared;
  48. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  49. LLVM_DUMP_METHOD void RecTy::dump() const { print(errs()); }
  50. #endif
  51. ListRecTy *RecTy::getListTy() {
  52. if (!ListTy)
  53. ListTy = new(Allocator) ListRecTy(this);
  54. return ListTy;
  55. }
  56. bool RecTy::typeIsConvertibleTo(const RecTy *RHS) const {
  57. assert(RHS && "NULL pointer");
  58. return Kind == RHS->getRecTyKind();
  59. }
  60. bool RecTy::typeIsA(const RecTy *RHS) const { return this == RHS; }
  61. bool BitRecTy::typeIsConvertibleTo(const RecTy *RHS) const{
  62. if (RecTy::typeIsConvertibleTo(RHS) || RHS->getRecTyKind() == IntRecTyKind)
  63. return true;
  64. if (const BitsRecTy *BitsTy = dyn_cast<BitsRecTy>(RHS))
  65. return BitsTy->getNumBits() == 1;
  66. return false;
  67. }
  68. BitsRecTy *BitsRecTy::get(unsigned Sz) {
  69. static std::vector<BitsRecTy*> Shared;
  70. if (Sz >= Shared.size())
  71. Shared.resize(Sz + 1);
  72. BitsRecTy *&Ty = Shared[Sz];
  73. if (!Ty)
  74. Ty = new(Allocator) BitsRecTy(Sz);
  75. return Ty;
  76. }
  77. std::string BitsRecTy::getAsString() const {
  78. return "bits<" + utostr(Size) + ">";
  79. }
  80. bool BitsRecTy::typeIsConvertibleTo(const RecTy *RHS) const {
  81. if (RecTy::typeIsConvertibleTo(RHS)) //argument and the sender are same type
  82. return cast<BitsRecTy>(RHS)->Size == Size;
  83. RecTyKind kind = RHS->getRecTyKind();
  84. return (kind == BitRecTyKind && Size == 1) || (kind == IntRecTyKind);
  85. }
  86. bool BitsRecTy::typeIsA(const RecTy *RHS) const {
  87. if (const BitsRecTy *RHSb = dyn_cast<BitsRecTy>(RHS))
  88. return RHSb->Size == Size;
  89. return false;
  90. }
  91. bool IntRecTy::typeIsConvertibleTo(const RecTy *RHS) const {
  92. RecTyKind kind = RHS->getRecTyKind();
  93. return kind==BitRecTyKind || kind==BitsRecTyKind || kind==IntRecTyKind;
  94. }
  95. std::string StringRecTy::getAsString() const {
  96. return "string";
  97. }
  98. bool StringRecTy::typeIsConvertibleTo(const RecTy *RHS) const {
  99. RecTyKind Kind = RHS->getRecTyKind();
  100. return Kind == StringRecTyKind;
  101. }
  102. std::string ListRecTy::getAsString() const {
  103. return "list<" + ElementTy->getAsString() + ">";
  104. }
  105. bool ListRecTy::typeIsConvertibleTo(const RecTy *RHS) const {
  106. if (const auto *ListTy = dyn_cast<ListRecTy>(RHS))
  107. return ElementTy->typeIsConvertibleTo(ListTy->getElementType());
  108. return false;
  109. }
  110. bool ListRecTy::typeIsA(const RecTy *RHS) const {
  111. if (const ListRecTy *RHSl = dyn_cast<ListRecTy>(RHS))
  112. return getElementType()->typeIsA(RHSl->getElementType());
  113. return false;
  114. }
  115. std::string DagRecTy::getAsString() const {
  116. return "dag";
  117. }
  118. static void ProfileRecordRecTy(FoldingSetNodeID &ID,
  119. ArrayRef<Record *> Classes) {
  120. ID.AddInteger(Classes.size());
  121. for (Record *R : Classes)
  122. ID.AddPointer(R);
  123. }
  124. RecordRecTy *RecordRecTy::get(ArrayRef<Record *> UnsortedClasses) {
  125. if (UnsortedClasses.empty()) {
  126. static RecordRecTy AnyRecord(0);
  127. return &AnyRecord;
  128. }
  129. FoldingSet<RecordRecTy> &ThePool =
  130. UnsortedClasses[0]->getRecords().RecordTypePool;
  131. SmallVector<Record *, 4> Classes(UnsortedClasses.begin(),
  132. UnsortedClasses.end());
  133. llvm::sort(Classes, [](Record *LHS, Record *RHS) {
  134. return LHS->getNameInitAsString() < RHS->getNameInitAsString();
  135. });
  136. FoldingSetNodeID ID;
  137. ProfileRecordRecTy(ID, Classes);
  138. void *IP = nullptr;
  139. if (RecordRecTy *Ty = ThePool.FindNodeOrInsertPos(ID, IP))
  140. return Ty;
  141. #ifndef NDEBUG
  142. // Check for redundancy.
  143. for (unsigned i = 0; i < Classes.size(); ++i) {
  144. for (unsigned j = 0; j < Classes.size(); ++j) {
  145. assert(i == j || !Classes[i]->isSubClassOf(Classes[j]));
  146. }
  147. assert(&Classes[0]->getRecords() == &Classes[i]->getRecords());
  148. }
  149. #endif
  150. void *Mem = Allocator.Allocate(totalSizeToAlloc<Record *>(Classes.size()),
  151. alignof(RecordRecTy));
  152. RecordRecTy *Ty = new(Mem) RecordRecTy(Classes.size());
  153. std::uninitialized_copy(Classes.begin(), Classes.end(),
  154. Ty->getTrailingObjects<Record *>());
  155. ThePool.InsertNode(Ty, IP);
  156. return Ty;
  157. }
  158. void RecordRecTy::Profile(FoldingSetNodeID &ID) const {
  159. ProfileRecordRecTy(ID, getClasses());
  160. }
  161. std::string RecordRecTy::getAsString() const {
  162. if (NumClasses == 1)
  163. return getClasses()[0]->getNameInitAsString();
  164. std::string Str = "{";
  165. bool First = true;
  166. for (Record *R : getClasses()) {
  167. if (!First)
  168. Str += ", ";
  169. First = false;
  170. Str += R->getNameInitAsString();
  171. }
  172. Str += "}";
  173. return Str;
  174. }
  175. bool RecordRecTy::isSubClassOf(Record *Class) const {
  176. return llvm::any_of(getClasses(), [Class](Record *MySuperClass) {
  177. return MySuperClass == Class ||
  178. MySuperClass->isSubClassOf(Class);
  179. });
  180. }
  181. bool RecordRecTy::typeIsConvertibleTo(const RecTy *RHS) const {
  182. if (this == RHS)
  183. return true;
  184. const RecordRecTy *RTy = dyn_cast<RecordRecTy>(RHS);
  185. if (!RTy)
  186. return false;
  187. return llvm::all_of(RTy->getClasses(), [this](Record *TargetClass) {
  188. return isSubClassOf(TargetClass);
  189. });
  190. }
  191. bool RecordRecTy::typeIsA(const RecTy *RHS) const {
  192. return typeIsConvertibleTo(RHS);
  193. }
  194. static RecordRecTy *resolveRecordTypes(RecordRecTy *T1, RecordRecTy *T2) {
  195. SmallVector<Record *, 4> CommonSuperClasses;
  196. SmallVector<Record *, 4> Stack(T1->classes_begin(), T1->classes_end());
  197. while (!Stack.empty()) {
  198. Record *R = Stack.pop_back_val();
  199. if (T2->isSubClassOf(R)) {
  200. CommonSuperClasses.push_back(R);
  201. } else {
  202. R->getDirectSuperClasses(Stack);
  203. }
  204. }
  205. return RecordRecTy::get(CommonSuperClasses);
  206. }
  207. RecTy *llvm::resolveTypes(RecTy *T1, RecTy *T2) {
  208. if (T1 == T2)
  209. return T1;
  210. if (RecordRecTy *RecTy1 = dyn_cast<RecordRecTy>(T1)) {
  211. if (RecordRecTy *RecTy2 = dyn_cast<RecordRecTy>(T2))
  212. return resolveRecordTypes(RecTy1, RecTy2);
  213. }
  214. if (T1->typeIsConvertibleTo(T2))
  215. return T2;
  216. if (T2->typeIsConvertibleTo(T1))
  217. return T1;
  218. if (ListRecTy *ListTy1 = dyn_cast<ListRecTy>(T1)) {
  219. if (ListRecTy *ListTy2 = dyn_cast<ListRecTy>(T2)) {
  220. RecTy* NewType = resolveTypes(ListTy1->getElementType(),
  221. ListTy2->getElementType());
  222. if (NewType)
  223. return NewType->getListTy();
  224. }
  225. }
  226. return nullptr;
  227. }
  228. //===----------------------------------------------------------------------===//
  229. // Initializer implementations
  230. //===----------------------------------------------------------------------===//
  231. void Init::anchor() {}
  232. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  233. LLVM_DUMP_METHOD void Init::dump() const { return print(errs()); }
  234. #endif
  235. UnsetInit *UnsetInit::get() {
  236. static UnsetInit TheInit;
  237. return &TheInit;
  238. }
  239. Init *UnsetInit::getCastTo(RecTy *Ty) const {
  240. return const_cast<UnsetInit *>(this);
  241. }
  242. Init *UnsetInit::convertInitializerTo(RecTy *Ty) const {
  243. return const_cast<UnsetInit *>(this);
  244. }
  245. BitInit *BitInit::get(bool V) {
  246. static BitInit True(true);
  247. static BitInit False(false);
  248. return V ? &True : &False;
  249. }
  250. Init *BitInit::convertInitializerTo(RecTy *Ty) const {
  251. if (isa<BitRecTy>(Ty))
  252. return const_cast<BitInit *>(this);
  253. if (isa<IntRecTy>(Ty))
  254. return IntInit::get(getValue());
  255. if (auto *BRT = dyn_cast<BitsRecTy>(Ty)) {
  256. // Can only convert single bit.
  257. if (BRT->getNumBits() == 1)
  258. return BitsInit::get(const_cast<BitInit *>(this));
  259. }
  260. return nullptr;
  261. }
  262. static void
  263. ProfileBitsInit(FoldingSetNodeID &ID, ArrayRef<Init *> Range) {
  264. ID.AddInteger(Range.size());
  265. for (Init *I : Range)
  266. ID.AddPointer(I);
  267. }
  268. BitsInit *BitsInit::get(ArrayRef<Init *> Range) {
  269. static FoldingSet<BitsInit> ThePool;
  270. FoldingSetNodeID ID;
  271. ProfileBitsInit(ID, Range);
  272. void *IP = nullptr;
  273. if (BitsInit *I = ThePool.FindNodeOrInsertPos(ID, IP))
  274. return I;
  275. void *Mem = Allocator.Allocate(totalSizeToAlloc<Init *>(Range.size()),
  276. alignof(BitsInit));
  277. BitsInit *I = new(Mem) BitsInit(Range.size());
  278. std::uninitialized_copy(Range.begin(), Range.end(),
  279. I->getTrailingObjects<Init *>());
  280. ThePool.InsertNode(I, IP);
  281. return I;
  282. }
  283. void BitsInit::Profile(FoldingSetNodeID &ID) const {
  284. ProfileBitsInit(ID, makeArrayRef(getTrailingObjects<Init *>(), NumBits));
  285. }
  286. Init *BitsInit::convertInitializerTo(RecTy *Ty) const {
  287. if (isa<BitRecTy>(Ty)) {
  288. if (getNumBits() != 1) return nullptr; // Only accept if just one bit!
  289. return getBit(0);
  290. }
  291. if (auto *BRT = dyn_cast<BitsRecTy>(Ty)) {
  292. // If the number of bits is right, return it. Otherwise we need to expand
  293. // or truncate.
  294. if (getNumBits() != BRT->getNumBits()) return nullptr;
  295. return const_cast<BitsInit *>(this);
  296. }
  297. if (isa<IntRecTy>(Ty)) {
  298. int64_t Result = 0;
  299. for (unsigned i = 0, e = getNumBits(); i != e; ++i)
  300. if (auto *Bit = dyn_cast<BitInit>(getBit(i)))
  301. Result |= static_cast<int64_t>(Bit->getValue()) << i;
  302. else
  303. return nullptr;
  304. return IntInit::get(Result);
  305. }
  306. return nullptr;
  307. }
  308. Init *
  309. BitsInit::convertInitializerBitRange(ArrayRef<unsigned> Bits) const {
  310. SmallVector<Init *, 16> NewBits(Bits.size());
  311. for (unsigned i = 0, e = Bits.size(); i != e; ++i) {
  312. if (Bits[i] >= getNumBits())
  313. return nullptr;
  314. NewBits[i] = getBit(Bits[i]);
  315. }
  316. return BitsInit::get(NewBits);
  317. }
  318. bool BitsInit::isConcrete() const {
  319. for (unsigned i = 0, e = getNumBits(); i != e; ++i) {
  320. if (!getBit(i)->isConcrete())
  321. return false;
  322. }
  323. return true;
  324. }
  325. std::string BitsInit::getAsString() const {
  326. std::string Result = "{ ";
  327. for (unsigned i = 0, e = getNumBits(); i != e; ++i) {
  328. if (i) Result += ", ";
  329. if (Init *Bit = getBit(e-i-1))
  330. Result += Bit->getAsString();
  331. else
  332. Result += "*";
  333. }
  334. return Result + " }";
  335. }
  336. // resolveReferences - If there are any field references that refer to fields
  337. // that have been filled in, we can propagate the values now.
  338. Init *BitsInit::resolveReferences(Resolver &R) const {
  339. bool Changed = false;
  340. SmallVector<Init *, 16> NewBits(getNumBits());
  341. Init *CachedBitVarRef = nullptr;
  342. Init *CachedBitVarResolved = nullptr;
  343. for (unsigned i = 0, e = getNumBits(); i != e; ++i) {
  344. Init *CurBit = getBit(i);
  345. Init *NewBit = CurBit;
  346. if (VarBitInit *CurBitVar = dyn_cast<VarBitInit>(CurBit)) {
  347. if (CurBitVar->getBitVar() != CachedBitVarRef) {
  348. CachedBitVarRef = CurBitVar->getBitVar();
  349. CachedBitVarResolved = CachedBitVarRef->resolveReferences(R);
  350. }
  351. assert(CachedBitVarResolved && "Unresolved bitvar reference");
  352. NewBit = CachedBitVarResolved->getBit(CurBitVar->getBitNum());
  353. } else {
  354. // getBit(0) implicitly converts int and bits<1> values to bit.
  355. NewBit = CurBit->resolveReferences(R)->getBit(0);
  356. }
  357. if (isa<UnsetInit>(NewBit) && R.keepUnsetBits())
  358. NewBit = CurBit;
  359. NewBits[i] = NewBit;
  360. Changed |= CurBit != NewBit;
  361. }
  362. if (Changed)
  363. return BitsInit::get(NewBits);
  364. return const_cast<BitsInit *>(this);
  365. }
  366. IntInit *IntInit::get(int64_t V) {
  367. static std::map<int64_t, IntInit*> ThePool;
  368. IntInit *&I = ThePool[V];
  369. if (!I) I = new(Allocator) IntInit(V);
  370. return I;
  371. }
  372. std::string IntInit::getAsString() const {
  373. return itostr(Value);
  374. }
  375. static bool canFitInBitfield(int64_t Value, unsigned NumBits) {
  376. // For example, with NumBits == 4, we permit Values from [-7 .. 15].
  377. return (NumBits >= sizeof(Value) * 8) ||
  378. (Value >> NumBits == 0) || (Value >> (NumBits-1) == -1);
  379. }
  380. Init *IntInit::convertInitializerTo(RecTy *Ty) const {
  381. if (isa<IntRecTy>(Ty))
  382. return const_cast<IntInit *>(this);
  383. if (isa<BitRecTy>(Ty)) {
  384. int64_t Val = getValue();
  385. if (Val != 0 && Val != 1) return nullptr; // Only accept 0 or 1 for a bit!
  386. return BitInit::get(Val != 0);
  387. }
  388. if (auto *BRT = dyn_cast<BitsRecTy>(Ty)) {
  389. int64_t Value = getValue();
  390. // Make sure this bitfield is large enough to hold the integer value.
  391. if (!canFitInBitfield(Value, BRT->getNumBits()))
  392. return nullptr;
  393. SmallVector<Init *, 16> NewBits(BRT->getNumBits());
  394. for (unsigned i = 0; i != BRT->getNumBits(); ++i)
  395. NewBits[i] = BitInit::get(Value & ((i < 64) ? (1LL << i) : 0));
  396. return BitsInit::get(NewBits);
  397. }
  398. return nullptr;
  399. }
  400. Init *
  401. IntInit::convertInitializerBitRange(ArrayRef<unsigned> Bits) const {
  402. SmallVector<Init *, 16> NewBits(Bits.size());
  403. for (unsigned i = 0, e = Bits.size(); i != e; ++i) {
  404. if (Bits[i] >= 64)
  405. return nullptr;
  406. NewBits[i] = BitInit::get(Value & (INT64_C(1) << Bits[i]));
  407. }
  408. return BitsInit::get(NewBits);
  409. }
  410. StringInit *StringInit::get(StringRef V, StringFormat Fmt) {
  411. static StringMap<StringInit*, BumpPtrAllocator &> StringPool(Allocator);
  412. static StringMap<StringInit*, BumpPtrAllocator &> CodePool(Allocator);
  413. if (Fmt == SF_String) {
  414. auto &Entry = *StringPool.insert(std::make_pair(V, nullptr)).first;
  415. if (!Entry.second)
  416. Entry.second = new (Allocator) StringInit(Entry.getKey(), Fmt);
  417. return Entry.second;
  418. } else {
  419. auto &Entry = *CodePool.insert(std::make_pair(V, nullptr)).first;
  420. if (!Entry.second)
  421. Entry.second = new (Allocator) StringInit(Entry.getKey(), Fmt);
  422. return Entry.second;
  423. }
  424. }
  425. Init *StringInit::convertInitializerTo(RecTy *Ty) const {
  426. if (isa<StringRecTy>(Ty))
  427. return const_cast<StringInit *>(this);
  428. return nullptr;
  429. }
  430. static void ProfileListInit(FoldingSetNodeID &ID,
  431. ArrayRef<Init *> Range,
  432. RecTy *EltTy) {
  433. ID.AddInteger(Range.size());
  434. ID.AddPointer(EltTy);
  435. for (Init *I : Range)
  436. ID.AddPointer(I);
  437. }
  438. ListInit *ListInit::get(ArrayRef<Init *> Range, RecTy *EltTy) {
  439. static FoldingSet<ListInit> ThePool;
  440. FoldingSetNodeID ID;
  441. ProfileListInit(ID, Range, EltTy);
  442. void *IP = nullptr;
  443. if (ListInit *I = ThePool.FindNodeOrInsertPos(ID, IP))
  444. return I;
  445. assert(Range.empty() || !isa<TypedInit>(Range[0]) ||
  446. cast<TypedInit>(Range[0])->getType()->typeIsConvertibleTo(EltTy));
  447. void *Mem = Allocator.Allocate(totalSizeToAlloc<Init *>(Range.size()),
  448. alignof(ListInit));
  449. ListInit *I = new(Mem) ListInit(Range.size(), EltTy);
  450. std::uninitialized_copy(Range.begin(), Range.end(),
  451. I->getTrailingObjects<Init *>());
  452. ThePool.InsertNode(I, IP);
  453. return I;
  454. }
  455. void ListInit::Profile(FoldingSetNodeID &ID) const {
  456. RecTy *EltTy = cast<ListRecTy>(getType())->getElementType();
  457. ProfileListInit(ID, getValues(), EltTy);
  458. }
  459. Init *ListInit::convertInitializerTo(RecTy *Ty) const {
  460. if (getType() == Ty)
  461. return const_cast<ListInit*>(this);
  462. if (auto *LRT = dyn_cast<ListRecTy>(Ty)) {
  463. SmallVector<Init*, 8> Elements;
  464. Elements.reserve(getValues().size());
  465. // Verify that all of the elements of the list are subclasses of the
  466. // appropriate class!
  467. bool Changed = false;
  468. RecTy *ElementType = LRT->getElementType();
  469. for (Init *I : getValues())
  470. if (Init *CI = I->convertInitializerTo(ElementType)) {
  471. Elements.push_back(CI);
  472. if (CI != I)
  473. Changed = true;
  474. } else
  475. return nullptr;
  476. if (!Changed)
  477. return const_cast<ListInit*>(this);
  478. return ListInit::get(Elements, ElementType);
  479. }
  480. return nullptr;
  481. }
  482. Init *ListInit::convertInitListSlice(ArrayRef<unsigned> Elements) const {
  483. SmallVector<Init*, 8> Vals;
  484. Vals.reserve(Elements.size());
  485. for (unsigned Element : Elements) {
  486. if (Element >= size())
  487. return nullptr;
  488. Vals.push_back(getElement(Element));
  489. }
  490. return ListInit::get(Vals, getElementType());
  491. }
  492. Record *ListInit::getElementAsRecord(unsigned i) const {
  493. assert(i < NumValues && "List element index out of range!");
  494. DefInit *DI = dyn_cast<DefInit>(getElement(i));
  495. if (!DI)
  496. PrintFatalError("Expected record in list!");
  497. return DI->getDef();
  498. }
  499. Init *ListInit::resolveReferences(Resolver &R) const {
  500. SmallVector<Init*, 8> Resolved;
  501. Resolved.reserve(size());
  502. bool Changed = false;
  503. for (Init *CurElt : getValues()) {
  504. Init *E = CurElt->resolveReferences(R);
  505. Changed |= E != CurElt;
  506. Resolved.push_back(E);
  507. }
  508. if (Changed)
  509. return ListInit::get(Resolved, getElementType());
  510. return const_cast<ListInit *>(this);
  511. }
  512. bool ListInit::isConcrete() const {
  513. for (Init *Element : *this) {
  514. if (!Element->isConcrete())
  515. return false;
  516. }
  517. return true;
  518. }
  519. std::string ListInit::getAsString() const {
  520. std::string Result = "[";
  521. const char *sep = "";
  522. for (Init *Element : *this) {
  523. Result += sep;
  524. sep = ", ";
  525. Result += Element->getAsString();
  526. }
  527. return Result + "]";
  528. }
  529. Init *OpInit::getBit(unsigned Bit) const {
  530. if (getType() == BitRecTy::get())
  531. return const_cast<OpInit*>(this);
  532. return VarBitInit::get(const_cast<OpInit*>(this), Bit);
  533. }
  534. static void
  535. ProfileUnOpInit(FoldingSetNodeID &ID, unsigned Opcode, Init *Op, RecTy *Type) {
  536. ID.AddInteger(Opcode);
  537. ID.AddPointer(Op);
  538. ID.AddPointer(Type);
  539. }
  540. UnOpInit *UnOpInit::get(UnaryOp Opc, Init *LHS, RecTy *Type) {
  541. static FoldingSet<UnOpInit> ThePool;
  542. FoldingSetNodeID ID;
  543. ProfileUnOpInit(ID, Opc, LHS, Type);
  544. void *IP = nullptr;
  545. if (UnOpInit *I = ThePool.FindNodeOrInsertPos(ID, IP))
  546. return I;
  547. UnOpInit *I = new(Allocator) UnOpInit(Opc, LHS, Type);
  548. ThePool.InsertNode(I, IP);
  549. return I;
  550. }
  551. void UnOpInit::Profile(FoldingSetNodeID &ID) const {
  552. ProfileUnOpInit(ID, getOpcode(), getOperand(), getType());
  553. }
  554. Init *UnOpInit::Fold(Record *CurRec, bool IsFinal) const {
  555. switch (getOpcode()) {
  556. case CAST:
  557. if (isa<StringRecTy>(getType())) {
  558. if (StringInit *LHSs = dyn_cast<StringInit>(LHS))
  559. return LHSs;
  560. if (DefInit *LHSd = dyn_cast<DefInit>(LHS))
  561. return StringInit::get(LHSd->getAsString());
  562. if (IntInit *LHSi =
  563. dyn_cast_or_null<IntInit>(LHS->convertInitializerTo(IntRecTy::get())))
  564. return StringInit::get(LHSi->getAsString());
  565. } else if (isa<RecordRecTy>(getType())) {
  566. if (StringInit *Name = dyn_cast<StringInit>(LHS)) {
  567. if (!CurRec && !IsFinal)
  568. break;
  569. assert(CurRec && "NULL pointer");
  570. Record *D;
  571. // Self-references are allowed, but their resolution is delayed until
  572. // the final resolve to ensure that we get the correct type for them.
  573. if (Name == CurRec->getNameInit()) {
  574. if (!IsFinal)
  575. break;
  576. D = CurRec;
  577. } else {
  578. D = CurRec->getRecords().getDef(Name->getValue());
  579. if (!D) {
  580. if (IsFinal)
  581. PrintFatalError(CurRec->getLoc(),
  582. Twine("Undefined reference to record: '") +
  583. Name->getValue() + "'\n");
  584. break;
  585. }
  586. }
  587. DefInit *DI = DefInit::get(D);
  588. if (!DI->getType()->typeIsA(getType())) {
  589. PrintFatalError(CurRec->getLoc(),
  590. Twine("Expected type '") +
  591. getType()->getAsString() + "', got '" +
  592. DI->getType()->getAsString() + "' in: " +
  593. getAsString() + "\n");
  594. }
  595. return DI;
  596. }
  597. }
  598. if (Init *NewInit = LHS->convertInitializerTo(getType()))
  599. return NewInit;
  600. break;
  601. case NOT:
  602. if (IntInit *LHSi =
  603. dyn_cast_or_null<IntInit>(LHS->convertInitializerTo(IntRecTy::get())))
  604. return IntInit::get(LHSi->getValue() ? 0 : 1);
  605. break;
  606. case HEAD:
  607. if (ListInit *LHSl = dyn_cast<ListInit>(LHS)) {
  608. assert(!LHSl->empty() && "Empty list in head");
  609. return LHSl->getElement(0);
  610. }
  611. break;
  612. case TAIL:
  613. if (ListInit *LHSl = dyn_cast<ListInit>(LHS)) {
  614. assert(!LHSl->empty() && "Empty list in tail");
  615. // Note the +1. We can't just pass the result of getValues()
  616. // directly.
  617. return ListInit::get(LHSl->getValues().slice(1), LHSl->getElementType());
  618. }
  619. break;
  620. case SIZE:
  621. if (ListInit *LHSl = dyn_cast<ListInit>(LHS))
  622. return IntInit::get(LHSl->size());
  623. if (DagInit *LHSd = dyn_cast<DagInit>(LHS))
  624. return IntInit::get(LHSd->arg_size());
  625. if (StringInit *LHSs = dyn_cast<StringInit>(LHS))
  626. return IntInit::get(LHSs->getValue().size());
  627. break;
  628. case EMPTY:
  629. if (ListInit *LHSl = dyn_cast<ListInit>(LHS))
  630. return IntInit::get(LHSl->empty());
  631. if (DagInit *LHSd = dyn_cast<DagInit>(LHS))
  632. return IntInit::get(LHSd->arg_empty());
  633. if (StringInit *LHSs = dyn_cast<StringInit>(LHS))
  634. return IntInit::get(LHSs->getValue().empty());
  635. break;
  636. case GETDAGOP:
  637. if (DagInit *Dag = dyn_cast<DagInit>(LHS)) {
  638. DefInit *DI = DefInit::get(Dag->getOperatorAsDef({}));
  639. if (!DI->getType()->typeIsA(getType())) {
  640. PrintFatalError(CurRec->getLoc(),
  641. Twine("Expected type '") +
  642. getType()->getAsString() + "', got '" +
  643. DI->getType()->getAsString() + "' in: " +
  644. getAsString() + "\n");
  645. } else {
  646. return DI;
  647. }
  648. }
  649. break;
  650. }
  651. return const_cast<UnOpInit *>(this);
  652. }
  653. Init *UnOpInit::resolveReferences(Resolver &R) const {
  654. Init *lhs = LHS->resolveReferences(R);
  655. if (LHS != lhs || (R.isFinal() && getOpcode() == CAST))
  656. return (UnOpInit::get(getOpcode(), lhs, getType()))
  657. ->Fold(R.getCurrentRecord(), R.isFinal());
  658. return const_cast<UnOpInit *>(this);
  659. }
  660. std::string UnOpInit::getAsString() const {
  661. std::string Result;
  662. switch (getOpcode()) {
  663. case CAST: Result = "!cast<" + getType()->getAsString() + ">"; break;
  664. case NOT: Result = "!not"; break;
  665. case HEAD: Result = "!head"; break;
  666. case TAIL: Result = "!tail"; break;
  667. case SIZE: Result = "!size"; break;
  668. case EMPTY: Result = "!empty"; break;
  669. case GETDAGOP: Result = "!getdagop"; break;
  670. }
  671. return Result + "(" + LHS->getAsString() + ")";
  672. }
  673. static void
  674. ProfileBinOpInit(FoldingSetNodeID &ID, unsigned Opcode, Init *LHS, Init *RHS,
  675. RecTy *Type) {
  676. ID.AddInteger(Opcode);
  677. ID.AddPointer(LHS);
  678. ID.AddPointer(RHS);
  679. ID.AddPointer(Type);
  680. }
  681. BinOpInit *BinOpInit::get(BinaryOp Opc, Init *LHS,
  682. Init *RHS, RecTy *Type) {
  683. static FoldingSet<BinOpInit> ThePool;
  684. FoldingSetNodeID ID;
  685. ProfileBinOpInit(ID, Opc, LHS, RHS, Type);
  686. void *IP = nullptr;
  687. if (BinOpInit *I = ThePool.FindNodeOrInsertPos(ID, IP))
  688. return I;
  689. BinOpInit *I = new(Allocator) BinOpInit(Opc, LHS, RHS, Type);
  690. ThePool.InsertNode(I, IP);
  691. return I;
  692. }
  693. void BinOpInit::Profile(FoldingSetNodeID &ID) const {
  694. ProfileBinOpInit(ID, getOpcode(), getLHS(), getRHS(), getType());
  695. }
  696. static StringInit *ConcatStringInits(const StringInit *I0,
  697. const StringInit *I1) {
  698. SmallString<80> Concat(I0->getValue());
  699. Concat.append(I1->getValue());
  700. return StringInit::get(Concat,
  701. StringInit::determineFormat(I0->getFormat(),
  702. I1->getFormat()));
  703. }
  704. static StringInit *interleaveStringList(const ListInit *List,
  705. const StringInit *Delim) {
  706. if (List->size() == 0)
  707. return StringInit::get("");
  708. StringInit *Element = dyn_cast<StringInit>(List->getElement(0));
  709. if (!Element)
  710. return nullptr;
  711. SmallString<80> Result(Element->getValue());
  712. StringInit::StringFormat Fmt = StringInit::SF_String;
  713. for (unsigned I = 1, E = List->size(); I < E; ++I) {
  714. Result.append(Delim->getValue());
  715. StringInit *Element = dyn_cast<StringInit>(List->getElement(I));
  716. if (!Element)
  717. return nullptr;
  718. Result.append(Element->getValue());
  719. Fmt = StringInit::determineFormat(Fmt, Element->getFormat());
  720. }
  721. return StringInit::get(Result, Fmt);
  722. }
  723. static StringInit *interleaveIntList(const ListInit *List,
  724. const StringInit *Delim) {
  725. if (List->size() == 0)
  726. return StringInit::get("");
  727. IntInit *Element =
  728. dyn_cast_or_null<IntInit>(List->getElement(0)
  729. ->convertInitializerTo(IntRecTy::get()));
  730. if (!Element)
  731. return nullptr;
  732. SmallString<80> Result(Element->getAsString());
  733. for (unsigned I = 1, E = List->size(); I < E; ++I) {
  734. Result.append(Delim->getValue());
  735. IntInit *Element =
  736. dyn_cast_or_null<IntInit>(List->getElement(I)
  737. ->convertInitializerTo(IntRecTy::get()));
  738. if (!Element)
  739. return nullptr;
  740. Result.append(Element->getAsString());
  741. }
  742. return StringInit::get(Result);
  743. }
  744. Init *BinOpInit::getStrConcat(Init *I0, Init *I1) {
  745. // Shortcut for the common case of concatenating two strings.
  746. if (const StringInit *I0s = dyn_cast<StringInit>(I0))
  747. if (const StringInit *I1s = dyn_cast<StringInit>(I1))
  748. return ConcatStringInits(I0s, I1s);
  749. return BinOpInit::get(BinOpInit::STRCONCAT, I0, I1, StringRecTy::get());
  750. }
  751. static ListInit *ConcatListInits(const ListInit *LHS,
  752. const ListInit *RHS) {
  753. SmallVector<Init *, 8> Args;
  754. llvm::append_range(Args, *LHS);
  755. llvm::append_range(Args, *RHS);
  756. return ListInit::get(Args, LHS->getElementType());
  757. }
  758. Init *BinOpInit::getListConcat(TypedInit *LHS, Init *RHS) {
  759. assert(isa<ListRecTy>(LHS->getType()) && "First arg must be a list");
  760. // Shortcut for the common case of concatenating two lists.
  761. if (const ListInit *LHSList = dyn_cast<ListInit>(LHS))
  762. if (const ListInit *RHSList = dyn_cast<ListInit>(RHS))
  763. return ConcatListInits(LHSList, RHSList);
  764. return BinOpInit::get(BinOpInit::LISTCONCAT, LHS, RHS, LHS->getType());
  765. }
  766. Init *BinOpInit::Fold(Record *CurRec) const {
  767. switch (getOpcode()) {
  768. case CONCAT: {
  769. DagInit *LHSs = dyn_cast<DagInit>(LHS);
  770. DagInit *RHSs = dyn_cast<DagInit>(RHS);
  771. if (LHSs && RHSs) {
  772. DefInit *LOp = dyn_cast<DefInit>(LHSs->getOperator());
  773. DefInit *ROp = dyn_cast<DefInit>(RHSs->getOperator());
  774. if ((!LOp && !isa<UnsetInit>(LHSs->getOperator())) ||
  775. (!ROp && !isa<UnsetInit>(RHSs->getOperator())))
  776. break;
  777. if (LOp && ROp && LOp->getDef() != ROp->getDef()) {
  778. PrintFatalError(Twine("Concatenated Dag operators do not match: '") +
  779. LHSs->getAsString() + "' vs. '" + RHSs->getAsString() +
  780. "'");
  781. }
  782. Init *Op = LOp ? LOp : ROp;
  783. if (!Op)
  784. Op = UnsetInit::get();
  785. SmallVector<Init*, 8> Args;
  786. SmallVector<StringInit*, 8> ArgNames;
  787. for (unsigned i = 0, e = LHSs->getNumArgs(); i != e; ++i) {
  788. Args.push_back(LHSs->getArg(i));
  789. ArgNames.push_back(LHSs->getArgName(i));
  790. }
  791. for (unsigned i = 0, e = RHSs->getNumArgs(); i != e; ++i) {
  792. Args.push_back(RHSs->getArg(i));
  793. ArgNames.push_back(RHSs->getArgName(i));
  794. }
  795. return DagInit::get(Op, nullptr, Args, ArgNames);
  796. }
  797. break;
  798. }
  799. case LISTCONCAT: {
  800. ListInit *LHSs = dyn_cast<ListInit>(LHS);
  801. ListInit *RHSs = dyn_cast<ListInit>(RHS);
  802. if (LHSs && RHSs) {
  803. SmallVector<Init *, 8> Args;
  804. llvm::append_range(Args, *LHSs);
  805. llvm::append_range(Args, *RHSs);
  806. return ListInit::get(Args, LHSs->getElementType());
  807. }
  808. break;
  809. }
  810. case LISTSPLAT: {
  811. TypedInit *Value = dyn_cast<TypedInit>(LHS);
  812. IntInit *Size = dyn_cast<IntInit>(RHS);
  813. if (Value && Size) {
  814. SmallVector<Init *, 8> Args(Size->getValue(), Value);
  815. return ListInit::get(Args, Value->getType());
  816. }
  817. break;
  818. }
  819. case STRCONCAT: {
  820. StringInit *LHSs = dyn_cast<StringInit>(LHS);
  821. StringInit *RHSs = dyn_cast<StringInit>(RHS);
  822. if (LHSs && RHSs)
  823. return ConcatStringInits(LHSs, RHSs);
  824. break;
  825. }
  826. case INTERLEAVE: {
  827. ListInit *List = dyn_cast<ListInit>(LHS);
  828. StringInit *Delim = dyn_cast<StringInit>(RHS);
  829. if (List && Delim) {
  830. StringInit *Result;
  831. if (isa<StringRecTy>(List->getElementType()))
  832. Result = interleaveStringList(List, Delim);
  833. else
  834. Result = interleaveIntList(List, Delim);
  835. if (Result)
  836. return Result;
  837. }
  838. break;
  839. }
  840. case EQ:
  841. case NE:
  842. case LE:
  843. case LT:
  844. case GE:
  845. case GT: {
  846. // First see if we have two bit, bits, or int.
  847. IntInit *LHSi =
  848. dyn_cast_or_null<IntInit>(LHS->convertInitializerTo(IntRecTy::get()));
  849. IntInit *RHSi =
  850. dyn_cast_or_null<IntInit>(RHS->convertInitializerTo(IntRecTy::get()));
  851. if (LHSi && RHSi) {
  852. bool Result;
  853. switch (getOpcode()) {
  854. case EQ: Result = LHSi->getValue() == RHSi->getValue(); break;
  855. case NE: Result = LHSi->getValue() != RHSi->getValue(); break;
  856. case LE: Result = LHSi->getValue() <= RHSi->getValue(); break;
  857. case LT: Result = LHSi->getValue() < RHSi->getValue(); break;
  858. case GE: Result = LHSi->getValue() >= RHSi->getValue(); break;
  859. case GT: Result = LHSi->getValue() > RHSi->getValue(); break;
  860. default: llvm_unreachable("unhandled comparison");
  861. }
  862. return BitInit::get(Result);
  863. }
  864. // Next try strings.
  865. StringInit *LHSs = dyn_cast<StringInit>(LHS);
  866. StringInit *RHSs = dyn_cast<StringInit>(RHS);
  867. if (LHSs && RHSs) {
  868. bool Result;
  869. switch (getOpcode()) {
  870. case EQ: Result = LHSs->getValue() == RHSs->getValue(); break;
  871. case NE: Result = LHSs->getValue() != RHSs->getValue(); break;
  872. case LE: Result = LHSs->getValue() <= RHSs->getValue(); break;
  873. case LT: Result = LHSs->getValue() < RHSs->getValue(); break;
  874. case GE: Result = LHSs->getValue() >= RHSs->getValue(); break;
  875. case GT: Result = LHSs->getValue() > RHSs->getValue(); break;
  876. default: llvm_unreachable("unhandled comparison");
  877. }
  878. return BitInit::get(Result);
  879. }
  880. // Finally, !eq and !ne can be used with records.
  881. if (getOpcode() == EQ || getOpcode() == NE) {
  882. DefInit *LHSd = dyn_cast<DefInit>(LHS);
  883. DefInit *RHSd = dyn_cast<DefInit>(RHS);
  884. if (LHSd && RHSd)
  885. return BitInit::get((getOpcode() == EQ) ? LHSd == RHSd
  886. : LHSd != RHSd);
  887. }
  888. break;
  889. }
  890. case SETDAGOP: {
  891. DagInit *Dag = dyn_cast<DagInit>(LHS);
  892. DefInit *Op = dyn_cast<DefInit>(RHS);
  893. if (Dag && Op) {
  894. SmallVector<Init*, 8> Args;
  895. SmallVector<StringInit*, 8> ArgNames;
  896. for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i) {
  897. Args.push_back(Dag->getArg(i));
  898. ArgNames.push_back(Dag->getArgName(i));
  899. }
  900. return DagInit::get(Op, nullptr, Args, ArgNames);
  901. }
  902. break;
  903. }
  904. case ADD:
  905. case SUB:
  906. case MUL:
  907. case AND:
  908. case OR:
  909. case XOR:
  910. case SHL:
  911. case SRA:
  912. case SRL: {
  913. IntInit *LHSi =
  914. dyn_cast_or_null<IntInit>(LHS->convertInitializerTo(IntRecTy::get()));
  915. IntInit *RHSi =
  916. dyn_cast_or_null<IntInit>(RHS->convertInitializerTo(IntRecTy::get()));
  917. if (LHSi && RHSi) {
  918. int64_t LHSv = LHSi->getValue(), RHSv = RHSi->getValue();
  919. int64_t Result;
  920. switch (getOpcode()) {
  921. default: llvm_unreachable("Bad opcode!");
  922. case ADD: Result = LHSv + RHSv; break;
  923. case SUB: Result = LHSv - RHSv; break;
  924. case MUL: Result = LHSv * RHSv; break;
  925. case AND: Result = LHSv & RHSv; break;
  926. case OR: Result = LHSv | RHSv; break;
  927. case XOR: Result = LHSv ^ RHSv; break;
  928. case SHL: Result = (uint64_t)LHSv << (uint64_t)RHSv; break;
  929. case SRA: Result = LHSv >> RHSv; break;
  930. case SRL: Result = (uint64_t)LHSv >> (uint64_t)RHSv; break;
  931. }
  932. return IntInit::get(Result);
  933. }
  934. break;
  935. }
  936. }
  937. return const_cast<BinOpInit *>(this);
  938. }
  939. Init *BinOpInit::resolveReferences(Resolver &R) const {
  940. Init *lhs = LHS->resolveReferences(R);
  941. Init *rhs = RHS->resolveReferences(R);
  942. if (LHS != lhs || RHS != rhs)
  943. return (BinOpInit::get(getOpcode(), lhs, rhs, getType()))
  944. ->Fold(R.getCurrentRecord());
  945. return const_cast<BinOpInit *>(this);
  946. }
  947. std::string BinOpInit::getAsString() const {
  948. std::string Result;
  949. switch (getOpcode()) {
  950. case CONCAT: Result = "!con"; break;
  951. case ADD: Result = "!add"; break;
  952. case SUB: Result = "!sub"; break;
  953. case MUL: Result = "!mul"; break;
  954. case AND: Result = "!and"; break;
  955. case OR: Result = "!or"; break;
  956. case XOR: Result = "!xor"; break;
  957. case SHL: Result = "!shl"; break;
  958. case SRA: Result = "!sra"; break;
  959. case SRL: Result = "!srl"; break;
  960. case EQ: Result = "!eq"; break;
  961. case NE: Result = "!ne"; break;
  962. case LE: Result = "!le"; break;
  963. case LT: Result = "!lt"; break;
  964. case GE: Result = "!ge"; break;
  965. case GT: Result = "!gt"; break;
  966. case LISTCONCAT: Result = "!listconcat"; break;
  967. case LISTSPLAT: Result = "!listsplat"; break;
  968. case STRCONCAT: Result = "!strconcat"; break;
  969. case INTERLEAVE: Result = "!interleave"; break;
  970. case SETDAGOP: Result = "!setdagop"; break;
  971. }
  972. return Result + "(" + LHS->getAsString() + ", " + RHS->getAsString() + ")";
  973. }
  974. static void
  975. ProfileTernOpInit(FoldingSetNodeID &ID, unsigned Opcode, Init *LHS, Init *MHS,
  976. Init *RHS, RecTy *Type) {
  977. ID.AddInteger(Opcode);
  978. ID.AddPointer(LHS);
  979. ID.AddPointer(MHS);
  980. ID.AddPointer(RHS);
  981. ID.AddPointer(Type);
  982. }
  983. TernOpInit *TernOpInit::get(TernaryOp Opc, Init *LHS, Init *MHS, Init *RHS,
  984. RecTy *Type) {
  985. static FoldingSet<TernOpInit> ThePool;
  986. FoldingSetNodeID ID;
  987. ProfileTernOpInit(ID, Opc, LHS, MHS, RHS, Type);
  988. void *IP = nullptr;
  989. if (TernOpInit *I = ThePool.FindNodeOrInsertPos(ID, IP))
  990. return I;
  991. TernOpInit *I = new(Allocator) TernOpInit(Opc, LHS, MHS, RHS, Type);
  992. ThePool.InsertNode(I, IP);
  993. return I;
  994. }
  995. void TernOpInit::Profile(FoldingSetNodeID &ID) const {
  996. ProfileTernOpInit(ID, getOpcode(), getLHS(), getMHS(), getRHS(), getType());
  997. }
  998. static Init *ItemApply(Init *LHS, Init *MHSe, Init *RHS, Record *CurRec) {
  999. MapResolver R(CurRec);
  1000. R.set(LHS, MHSe);
  1001. return RHS->resolveReferences(R);
  1002. }
  1003. static Init *ForeachDagApply(Init *LHS, DagInit *MHSd, Init *RHS,
  1004. Record *CurRec) {
  1005. bool Change = false;
  1006. Init *Val = ItemApply(LHS, MHSd->getOperator(), RHS, CurRec);
  1007. if (Val != MHSd->getOperator())
  1008. Change = true;
  1009. SmallVector<std::pair<Init *, StringInit *>, 8> NewArgs;
  1010. for (unsigned int i = 0; i < MHSd->getNumArgs(); ++i) {
  1011. Init *Arg = MHSd->getArg(i);
  1012. Init *NewArg;
  1013. StringInit *ArgName = MHSd->getArgName(i);
  1014. if (DagInit *Argd = dyn_cast<DagInit>(Arg))
  1015. NewArg = ForeachDagApply(LHS, Argd, RHS, CurRec);
  1016. else
  1017. NewArg = ItemApply(LHS, Arg, RHS, CurRec);
  1018. NewArgs.push_back(std::make_pair(NewArg, ArgName));
  1019. if (Arg != NewArg)
  1020. Change = true;
  1021. }
  1022. if (Change)
  1023. return DagInit::get(Val, nullptr, NewArgs);
  1024. return MHSd;
  1025. }
  1026. // Applies RHS to all elements of MHS, using LHS as a temp variable.
  1027. static Init *ForeachHelper(Init *LHS, Init *MHS, Init *RHS, RecTy *Type,
  1028. Record *CurRec) {
  1029. if (DagInit *MHSd = dyn_cast<DagInit>(MHS))
  1030. return ForeachDagApply(LHS, MHSd, RHS, CurRec);
  1031. if (ListInit *MHSl = dyn_cast<ListInit>(MHS)) {
  1032. SmallVector<Init *, 8> NewList(MHSl->begin(), MHSl->end());
  1033. for (Init *&Item : NewList) {
  1034. Init *NewItem = ItemApply(LHS, Item, RHS, CurRec);
  1035. if (NewItem != Item)
  1036. Item = NewItem;
  1037. }
  1038. return ListInit::get(NewList, cast<ListRecTy>(Type)->getElementType());
  1039. }
  1040. return nullptr;
  1041. }
  1042. // Evaluates RHS for all elements of MHS, using LHS as a temp variable.
  1043. // Creates a new list with the elements that evaluated to true.
  1044. static Init *FilterHelper(Init *LHS, Init *MHS, Init *RHS, RecTy *Type,
  1045. Record *CurRec) {
  1046. if (ListInit *MHSl = dyn_cast<ListInit>(MHS)) {
  1047. SmallVector<Init *, 8> NewList;
  1048. for (Init *Item : MHSl->getValues()) {
  1049. Init *Include = ItemApply(LHS, Item, RHS, CurRec);
  1050. if (!Include)
  1051. return nullptr;
  1052. if (IntInit *IncludeInt = dyn_cast_or_null<IntInit>(
  1053. Include->convertInitializerTo(IntRecTy::get()))) {
  1054. if (IncludeInt->getValue())
  1055. NewList.push_back(Item);
  1056. } else {
  1057. return nullptr;
  1058. }
  1059. }
  1060. return ListInit::get(NewList, cast<ListRecTy>(Type)->getElementType());
  1061. }
  1062. return nullptr;
  1063. }
  1064. Init *TernOpInit::Fold(Record *CurRec) const {
  1065. switch (getOpcode()) {
  1066. case SUBST: {
  1067. DefInit *LHSd = dyn_cast<DefInit>(LHS);
  1068. VarInit *LHSv = dyn_cast<VarInit>(LHS);
  1069. StringInit *LHSs = dyn_cast<StringInit>(LHS);
  1070. DefInit *MHSd = dyn_cast<DefInit>(MHS);
  1071. VarInit *MHSv = dyn_cast<VarInit>(MHS);
  1072. StringInit *MHSs = dyn_cast<StringInit>(MHS);
  1073. DefInit *RHSd = dyn_cast<DefInit>(RHS);
  1074. VarInit *RHSv = dyn_cast<VarInit>(RHS);
  1075. StringInit *RHSs = dyn_cast<StringInit>(RHS);
  1076. if (LHSd && MHSd && RHSd) {
  1077. Record *Val = RHSd->getDef();
  1078. if (LHSd->getAsString() == RHSd->getAsString())
  1079. Val = MHSd->getDef();
  1080. return DefInit::get(Val);
  1081. }
  1082. if (LHSv && MHSv && RHSv) {
  1083. std::string Val = std::string(RHSv->getName());
  1084. if (LHSv->getAsString() == RHSv->getAsString())
  1085. Val = std::string(MHSv->getName());
  1086. return VarInit::get(Val, getType());
  1087. }
  1088. if (LHSs && MHSs && RHSs) {
  1089. std::string Val = std::string(RHSs->getValue());
  1090. std::string::size_type found;
  1091. std::string::size_type idx = 0;
  1092. while (true) {
  1093. found = Val.find(std::string(LHSs->getValue()), idx);
  1094. if (found == std::string::npos)
  1095. break;
  1096. Val.replace(found, LHSs->getValue().size(),
  1097. std::string(MHSs->getValue()));
  1098. idx = found + MHSs->getValue().size();
  1099. }
  1100. return StringInit::get(Val);
  1101. }
  1102. break;
  1103. }
  1104. case FOREACH: {
  1105. if (Init *Result = ForeachHelper(LHS, MHS, RHS, getType(), CurRec))
  1106. return Result;
  1107. break;
  1108. }
  1109. case FILTER: {
  1110. if (Init *Result = FilterHelper(LHS, MHS, RHS, getType(), CurRec))
  1111. return Result;
  1112. break;
  1113. }
  1114. case IF: {
  1115. if (IntInit *LHSi = dyn_cast_or_null<IntInit>(
  1116. LHS->convertInitializerTo(IntRecTy::get()))) {
  1117. if (LHSi->getValue())
  1118. return MHS;
  1119. return RHS;
  1120. }
  1121. break;
  1122. }
  1123. case DAG: {
  1124. ListInit *MHSl = dyn_cast<ListInit>(MHS);
  1125. ListInit *RHSl = dyn_cast<ListInit>(RHS);
  1126. bool MHSok = MHSl || isa<UnsetInit>(MHS);
  1127. bool RHSok = RHSl || isa<UnsetInit>(RHS);
  1128. if (isa<UnsetInit>(MHS) && isa<UnsetInit>(RHS))
  1129. break; // Typically prevented by the parser, but might happen with template args
  1130. if (MHSok && RHSok && (!MHSl || !RHSl || MHSl->size() == RHSl->size())) {
  1131. SmallVector<std::pair<Init *, StringInit *>, 8> Children;
  1132. unsigned Size = MHSl ? MHSl->size() : RHSl->size();
  1133. for (unsigned i = 0; i != Size; ++i) {
  1134. Init *Node = MHSl ? MHSl->getElement(i) : UnsetInit::get();
  1135. Init *Name = RHSl ? RHSl->getElement(i) : UnsetInit::get();
  1136. if (!isa<StringInit>(Name) && !isa<UnsetInit>(Name))
  1137. return const_cast<TernOpInit *>(this);
  1138. Children.emplace_back(Node, dyn_cast<StringInit>(Name));
  1139. }
  1140. return DagInit::get(LHS, nullptr, Children);
  1141. }
  1142. break;
  1143. }
  1144. case SUBSTR: {
  1145. StringInit *LHSs = dyn_cast<StringInit>(LHS);
  1146. IntInit *MHSi = dyn_cast<IntInit>(MHS);
  1147. IntInit *RHSi = dyn_cast<IntInit>(RHS);
  1148. if (LHSs && MHSi && RHSi) {
  1149. int64_t StringSize = LHSs->getValue().size();
  1150. int64_t Start = MHSi->getValue();
  1151. int64_t Length = RHSi->getValue();
  1152. if (Start < 0 || Start > StringSize)
  1153. PrintError(CurRec->getLoc(),
  1154. Twine("!substr start position is out of range 0...") +
  1155. std::to_string(StringSize) + ": " +
  1156. std::to_string(Start));
  1157. if (Length < 0)
  1158. PrintError(CurRec->getLoc(), "!substr length must be nonnegative");
  1159. return StringInit::get(LHSs->getValue().substr(Start, Length),
  1160. LHSs->getFormat());
  1161. }
  1162. break;
  1163. }
  1164. }
  1165. return const_cast<TernOpInit *>(this);
  1166. }
  1167. Init *TernOpInit::resolveReferences(Resolver &R) const {
  1168. Init *lhs = LHS->resolveReferences(R);
  1169. if (getOpcode() == IF && lhs != LHS) {
  1170. if (IntInit *Value = dyn_cast_or_null<IntInit>(
  1171. lhs->convertInitializerTo(IntRecTy::get()))) {
  1172. // Short-circuit
  1173. if (Value->getValue())
  1174. return MHS->resolveReferences(R);
  1175. return RHS->resolveReferences(R);
  1176. }
  1177. }
  1178. Init *mhs = MHS->resolveReferences(R);
  1179. Init *rhs;
  1180. if (getOpcode() == FOREACH || getOpcode() == FILTER) {
  1181. ShadowResolver SR(R);
  1182. SR.addShadow(lhs);
  1183. rhs = RHS->resolveReferences(SR);
  1184. } else {
  1185. rhs = RHS->resolveReferences(R);
  1186. }
  1187. if (LHS != lhs || MHS != mhs || RHS != rhs)
  1188. return (TernOpInit::get(getOpcode(), lhs, mhs, rhs, getType()))
  1189. ->Fold(R.getCurrentRecord());
  1190. return const_cast<TernOpInit *>(this);
  1191. }
  1192. std::string TernOpInit::getAsString() const {
  1193. std::string Result;
  1194. bool UnquotedLHS = false;
  1195. switch (getOpcode()) {
  1196. case DAG: Result = "!dag"; break;
  1197. case FILTER: Result = "!filter"; UnquotedLHS = true; break;
  1198. case FOREACH: Result = "!foreach"; UnquotedLHS = true; break;
  1199. case IF: Result = "!if"; break;
  1200. case SUBST: Result = "!subst"; break;
  1201. case SUBSTR: Result = "!substr"; break;
  1202. }
  1203. return (Result + "(" +
  1204. (UnquotedLHS ? LHS->getAsUnquotedString() : LHS->getAsString()) +
  1205. ", " + MHS->getAsString() + ", " + RHS->getAsString() + ")");
  1206. }
  1207. static void ProfileFoldOpInit(FoldingSetNodeID &ID, Init *A, Init *B,
  1208. Init *Start, Init *List, Init *Expr,
  1209. RecTy *Type) {
  1210. ID.AddPointer(Start);
  1211. ID.AddPointer(List);
  1212. ID.AddPointer(A);
  1213. ID.AddPointer(B);
  1214. ID.AddPointer(Expr);
  1215. ID.AddPointer(Type);
  1216. }
  1217. FoldOpInit *FoldOpInit::get(Init *Start, Init *List, Init *A, Init *B,
  1218. Init *Expr, RecTy *Type) {
  1219. static FoldingSet<FoldOpInit> ThePool;
  1220. FoldingSetNodeID ID;
  1221. ProfileFoldOpInit(ID, Start, List, A, B, Expr, Type);
  1222. void *IP = nullptr;
  1223. if (FoldOpInit *I = ThePool.FindNodeOrInsertPos(ID, IP))
  1224. return I;
  1225. FoldOpInit *I = new (Allocator) FoldOpInit(Start, List, A, B, Expr, Type);
  1226. ThePool.InsertNode(I, IP);
  1227. return I;
  1228. }
  1229. void FoldOpInit::Profile(FoldingSetNodeID &ID) const {
  1230. ProfileFoldOpInit(ID, Start, List, A, B, Expr, getType());
  1231. }
  1232. Init *FoldOpInit::Fold(Record *CurRec) const {
  1233. if (ListInit *LI = dyn_cast<ListInit>(List)) {
  1234. Init *Accum = Start;
  1235. for (Init *Elt : *LI) {
  1236. MapResolver R(CurRec);
  1237. R.set(A, Accum);
  1238. R.set(B, Elt);
  1239. Accum = Expr->resolveReferences(R);
  1240. }
  1241. return Accum;
  1242. }
  1243. return const_cast<FoldOpInit *>(this);
  1244. }
  1245. Init *FoldOpInit::resolveReferences(Resolver &R) const {
  1246. Init *NewStart = Start->resolveReferences(R);
  1247. Init *NewList = List->resolveReferences(R);
  1248. ShadowResolver SR(R);
  1249. SR.addShadow(A);
  1250. SR.addShadow(B);
  1251. Init *NewExpr = Expr->resolveReferences(SR);
  1252. if (Start == NewStart && List == NewList && Expr == NewExpr)
  1253. return const_cast<FoldOpInit *>(this);
  1254. return get(NewStart, NewList, A, B, NewExpr, getType())
  1255. ->Fold(R.getCurrentRecord());
  1256. }
  1257. Init *FoldOpInit::getBit(unsigned Bit) const {
  1258. return VarBitInit::get(const_cast<FoldOpInit *>(this), Bit);
  1259. }
  1260. std::string FoldOpInit::getAsString() const {
  1261. return (Twine("!foldl(") + Start->getAsString() + ", " + List->getAsString() +
  1262. ", " + A->getAsUnquotedString() + ", " + B->getAsUnquotedString() +
  1263. ", " + Expr->getAsString() + ")")
  1264. .str();
  1265. }
  1266. static void ProfileIsAOpInit(FoldingSetNodeID &ID, RecTy *CheckType,
  1267. Init *Expr) {
  1268. ID.AddPointer(CheckType);
  1269. ID.AddPointer(Expr);
  1270. }
  1271. IsAOpInit *IsAOpInit::get(RecTy *CheckType, Init *Expr) {
  1272. static FoldingSet<IsAOpInit> ThePool;
  1273. FoldingSetNodeID ID;
  1274. ProfileIsAOpInit(ID, CheckType, Expr);
  1275. void *IP = nullptr;
  1276. if (IsAOpInit *I = ThePool.FindNodeOrInsertPos(ID, IP))
  1277. return I;
  1278. IsAOpInit *I = new (Allocator) IsAOpInit(CheckType, Expr);
  1279. ThePool.InsertNode(I, IP);
  1280. return I;
  1281. }
  1282. void IsAOpInit::Profile(FoldingSetNodeID &ID) const {
  1283. ProfileIsAOpInit(ID, CheckType, Expr);
  1284. }
  1285. Init *IsAOpInit::Fold() const {
  1286. if (TypedInit *TI = dyn_cast<TypedInit>(Expr)) {
  1287. // Is the expression type known to be (a subclass of) the desired type?
  1288. if (TI->getType()->typeIsConvertibleTo(CheckType))
  1289. return IntInit::get(1);
  1290. if (isa<RecordRecTy>(CheckType)) {
  1291. // If the target type is not a subclass of the expression type, or if
  1292. // the expression has fully resolved to a record, we know that it can't
  1293. // be of the required type.
  1294. if (!CheckType->typeIsConvertibleTo(TI->getType()) || isa<DefInit>(Expr))
  1295. return IntInit::get(0);
  1296. } else {
  1297. // We treat non-record types as not castable.
  1298. return IntInit::get(0);
  1299. }
  1300. }
  1301. return const_cast<IsAOpInit *>(this);
  1302. }
  1303. Init *IsAOpInit::resolveReferences(Resolver &R) const {
  1304. Init *NewExpr = Expr->resolveReferences(R);
  1305. if (Expr != NewExpr)
  1306. return get(CheckType, NewExpr)->Fold();
  1307. return const_cast<IsAOpInit *>(this);
  1308. }
  1309. Init *IsAOpInit::getBit(unsigned Bit) const {
  1310. return VarBitInit::get(const_cast<IsAOpInit *>(this), Bit);
  1311. }
  1312. std::string IsAOpInit::getAsString() const {
  1313. return (Twine("!isa<") + CheckType->getAsString() + ">(" +
  1314. Expr->getAsString() + ")")
  1315. .str();
  1316. }
  1317. RecTy *TypedInit::getFieldType(StringInit *FieldName) const {
  1318. if (RecordRecTy *RecordType = dyn_cast<RecordRecTy>(getType())) {
  1319. for (Record *Rec : RecordType->getClasses()) {
  1320. if (RecordVal *Field = Rec->getValue(FieldName))
  1321. return Field->getType();
  1322. }
  1323. }
  1324. return nullptr;
  1325. }
  1326. Init *
  1327. TypedInit::convertInitializerTo(RecTy *Ty) const {
  1328. if (getType() == Ty || getType()->typeIsA(Ty))
  1329. return const_cast<TypedInit *>(this);
  1330. if (isa<BitRecTy>(getType()) && isa<BitsRecTy>(Ty) &&
  1331. cast<BitsRecTy>(Ty)->getNumBits() == 1)
  1332. return BitsInit::get({const_cast<TypedInit *>(this)});
  1333. return nullptr;
  1334. }
  1335. Init *TypedInit::convertInitializerBitRange(ArrayRef<unsigned> Bits) const {
  1336. BitsRecTy *T = dyn_cast<BitsRecTy>(getType());
  1337. if (!T) return nullptr; // Cannot subscript a non-bits variable.
  1338. unsigned NumBits = T->getNumBits();
  1339. SmallVector<Init *, 16> NewBits;
  1340. NewBits.reserve(Bits.size());
  1341. for (unsigned Bit : Bits) {
  1342. if (Bit >= NumBits)
  1343. return nullptr;
  1344. NewBits.push_back(VarBitInit::get(const_cast<TypedInit *>(this), Bit));
  1345. }
  1346. return BitsInit::get(NewBits);
  1347. }
  1348. Init *TypedInit::getCastTo(RecTy *Ty) const {
  1349. // Handle the common case quickly
  1350. if (getType() == Ty || getType()->typeIsA(Ty))
  1351. return const_cast<TypedInit *>(this);
  1352. if (Init *Converted = convertInitializerTo(Ty)) {
  1353. assert(!isa<TypedInit>(Converted) ||
  1354. cast<TypedInit>(Converted)->getType()->typeIsA(Ty));
  1355. return Converted;
  1356. }
  1357. if (!getType()->typeIsConvertibleTo(Ty))
  1358. return nullptr;
  1359. return UnOpInit::get(UnOpInit::CAST, const_cast<TypedInit *>(this), Ty)
  1360. ->Fold(nullptr);
  1361. }
  1362. Init *TypedInit::convertInitListSlice(ArrayRef<unsigned> Elements) const {
  1363. ListRecTy *T = dyn_cast<ListRecTy>(getType());
  1364. if (!T) return nullptr; // Cannot subscript a non-list variable.
  1365. if (Elements.size() == 1)
  1366. return VarListElementInit::get(const_cast<TypedInit *>(this), Elements[0]);
  1367. SmallVector<Init*, 8> ListInits;
  1368. ListInits.reserve(Elements.size());
  1369. for (unsigned Element : Elements)
  1370. ListInits.push_back(VarListElementInit::get(const_cast<TypedInit *>(this),
  1371. Element));
  1372. return ListInit::get(ListInits, T->getElementType());
  1373. }
  1374. VarInit *VarInit::get(StringRef VN, RecTy *T) {
  1375. Init *Value = StringInit::get(VN);
  1376. return VarInit::get(Value, T);
  1377. }
  1378. VarInit *VarInit::get(Init *VN, RecTy *T) {
  1379. using Key = std::pair<RecTy *, Init *>;
  1380. static DenseMap<Key, VarInit*> ThePool;
  1381. Key TheKey(std::make_pair(T, VN));
  1382. VarInit *&I = ThePool[TheKey];
  1383. if (!I)
  1384. I = new(Allocator) VarInit(VN, T);
  1385. return I;
  1386. }
  1387. StringRef VarInit::getName() const {
  1388. StringInit *NameString = cast<StringInit>(getNameInit());
  1389. return NameString->getValue();
  1390. }
  1391. Init *VarInit::getBit(unsigned Bit) const {
  1392. if (getType() == BitRecTy::get())
  1393. return const_cast<VarInit*>(this);
  1394. return VarBitInit::get(const_cast<VarInit*>(this), Bit);
  1395. }
  1396. Init *VarInit::resolveReferences(Resolver &R) const {
  1397. if (Init *Val = R.resolve(VarName))
  1398. return Val;
  1399. return const_cast<VarInit *>(this);
  1400. }
  1401. VarBitInit *VarBitInit::get(TypedInit *T, unsigned B) {
  1402. using Key = std::pair<TypedInit *, unsigned>;
  1403. static DenseMap<Key, VarBitInit*> ThePool;
  1404. Key TheKey(std::make_pair(T, B));
  1405. VarBitInit *&I = ThePool[TheKey];
  1406. if (!I)
  1407. I = new(Allocator) VarBitInit(T, B);
  1408. return I;
  1409. }
  1410. std::string VarBitInit::getAsString() const {
  1411. return TI->getAsString() + "{" + utostr(Bit) + "}";
  1412. }
  1413. Init *VarBitInit::resolveReferences(Resolver &R) const {
  1414. Init *I = TI->resolveReferences(R);
  1415. if (TI != I)
  1416. return I->getBit(getBitNum());
  1417. return const_cast<VarBitInit*>(this);
  1418. }
  1419. VarListElementInit *VarListElementInit::get(TypedInit *T,
  1420. unsigned E) {
  1421. using Key = std::pair<TypedInit *, unsigned>;
  1422. static DenseMap<Key, VarListElementInit*> ThePool;
  1423. Key TheKey(std::make_pair(T, E));
  1424. VarListElementInit *&I = ThePool[TheKey];
  1425. if (!I) I = new(Allocator) VarListElementInit(T, E);
  1426. return I;
  1427. }
  1428. std::string VarListElementInit::getAsString() const {
  1429. return TI->getAsString() + "[" + utostr(Element) + "]";
  1430. }
  1431. Init *VarListElementInit::resolveReferences(Resolver &R) const {
  1432. Init *NewTI = TI->resolveReferences(R);
  1433. if (ListInit *List = dyn_cast<ListInit>(NewTI)) {
  1434. // Leave out-of-bounds array references as-is. This can happen without
  1435. // being an error, e.g. in the untaken "branch" of an !if expression.
  1436. if (getElementNum() < List->size())
  1437. return List->getElement(getElementNum());
  1438. }
  1439. if (NewTI != TI && isa<TypedInit>(NewTI))
  1440. return VarListElementInit::get(cast<TypedInit>(NewTI), getElementNum());
  1441. return const_cast<VarListElementInit *>(this);
  1442. }
  1443. Init *VarListElementInit::getBit(unsigned Bit) const {
  1444. if (getType() == BitRecTy::get())
  1445. return const_cast<VarListElementInit*>(this);
  1446. return VarBitInit::get(const_cast<VarListElementInit*>(this), Bit);
  1447. }
  1448. DefInit::DefInit(Record *D)
  1449. : TypedInit(IK_DefInit, D->getType()), Def(D) {}
  1450. DefInit *DefInit::get(Record *R) {
  1451. return R->getDefInit();
  1452. }
  1453. Init *DefInit::convertInitializerTo(RecTy *Ty) const {
  1454. if (auto *RRT = dyn_cast<RecordRecTy>(Ty))
  1455. if (getType()->typeIsConvertibleTo(RRT))
  1456. return const_cast<DefInit *>(this);
  1457. return nullptr;
  1458. }
  1459. RecTy *DefInit::getFieldType(StringInit *FieldName) const {
  1460. if (const RecordVal *RV = Def->getValue(FieldName))
  1461. return RV->getType();
  1462. return nullptr;
  1463. }
  1464. std::string DefInit::getAsString() const { return std::string(Def->getName()); }
  1465. static void ProfileVarDefInit(FoldingSetNodeID &ID,
  1466. Record *Class,
  1467. ArrayRef<Init *> Args) {
  1468. ID.AddInteger(Args.size());
  1469. ID.AddPointer(Class);
  1470. for (Init *I : Args)
  1471. ID.AddPointer(I);
  1472. }
  1473. VarDefInit *VarDefInit::get(Record *Class, ArrayRef<Init *> Args) {
  1474. static FoldingSet<VarDefInit> ThePool;
  1475. FoldingSetNodeID ID;
  1476. ProfileVarDefInit(ID, Class, Args);
  1477. void *IP = nullptr;
  1478. if (VarDefInit *I = ThePool.FindNodeOrInsertPos(ID, IP))
  1479. return I;
  1480. void *Mem = Allocator.Allocate(totalSizeToAlloc<Init *>(Args.size()),
  1481. alignof(VarDefInit));
  1482. VarDefInit *I = new(Mem) VarDefInit(Class, Args.size());
  1483. std::uninitialized_copy(Args.begin(), Args.end(),
  1484. I->getTrailingObjects<Init *>());
  1485. ThePool.InsertNode(I, IP);
  1486. return I;
  1487. }
  1488. void VarDefInit::Profile(FoldingSetNodeID &ID) const {
  1489. ProfileVarDefInit(ID, Class, args());
  1490. }
  1491. DefInit *VarDefInit::instantiate() {
  1492. if (!Def) {
  1493. RecordKeeper &Records = Class->getRecords();
  1494. auto NewRecOwner = std::make_unique<Record>(Records.getNewAnonymousName(),
  1495. Class->getLoc(), Records,
  1496. /*IsAnonymous=*/true);
  1497. Record *NewRec = NewRecOwner.get();
  1498. // Copy values from class to instance
  1499. for (const RecordVal &Val : Class->getValues())
  1500. NewRec->addValue(Val);
  1501. // Substitute and resolve template arguments
  1502. ArrayRef<Init *> TArgs = Class->getTemplateArgs();
  1503. MapResolver R(NewRec);
  1504. for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
  1505. if (i < args_size())
  1506. R.set(TArgs[i], getArg(i));
  1507. else
  1508. R.set(TArgs[i], NewRec->getValue(TArgs[i])->getValue());
  1509. NewRec->removeValue(TArgs[i]);
  1510. }
  1511. NewRec->resolveReferences(R);
  1512. // Add superclasses.
  1513. ArrayRef<std::pair<Record *, SMRange>> SCs = Class->getSuperClasses();
  1514. for (const auto &SCPair : SCs)
  1515. NewRec->addSuperClass(SCPair.first, SCPair.second);
  1516. NewRec->addSuperClass(Class,
  1517. SMRange(Class->getLoc().back(),
  1518. Class->getLoc().back()));
  1519. // Resolve internal references and store in record keeper
  1520. NewRec->resolveReferences();
  1521. Records.addDef(std::move(NewRecOwner));
  1522. Def = DefInit::get(NewRec);
  1523. }
  1524. return Def;
  1525. }
  1526. Init *VarDefInit::resolveReferences(Resolver &R) const {
  1527. TrackUnresolvedResolver UR(&R);
  1528. bool Changed = false;
  1529. SmallVector<Init *, 8> NewArgs;
  1530. NewArgs.reserve(args_size());
  1531. for (Init *Arg : args()) {
  1532. Init *NewArg = Arg->resolveReferences(UR);
  1533. NewArgs.push_back(NewArg);
  1534. Changed |= NewArg != Arg;
  1535. }
  1536. if (Changed) {
  1537. auto New = VarDefInit::get(Class, NewArgs);
  1538. if (!UR.foundUnresolved())
  1539. return New->instantiate();
  1540. return New;
  1541. }
  1542. return const_cast<VarDefInit *>(this);
  1543. }
  1544. Init *VarDefInit::Fold() const {
  1545. if (Def)
  1546. return Def;
  1547. TrackUnresolvedResolver R;
  1548. for (Init *Arg : args())
  1549. Arg->resolveReferences(R);
  1550. if (!R.foundUnresolved())
  1551. return const_cast<VarDefInit *>(this)->instantiate();
  1552. return const_cast<VarDefInit *>(this);
  1553. }
  1554. std::string VarDefInit::getAsString() const {
  1555. std::string Result = Class->getNameInitAsString() + "<";
  1556. const char *sep = "";
  1557. for (Init *Arg : args()) {
  1558. Result += sep;
  1559. sep = ", ";
  1560. Result += Arg->getAsString();
  1561. }
  1562. return Result + ">";
  1563. }
  1564. FieldInit *FieldInit::get(Init *R, StringInit *FN) {
  1565. using Key = std::pair<Init *, StringInit *>;
  1566. static DenseMap<Key, FieldInit*> ThePool;
  1567. Key TheKey(std::make_pair(R, FN));
  1568. FieldInit *&I = ThePool[TheKey];
  1569. if (!I) I = new(Allocator) FieldInit(R, FN);
  1570. return I;
  1571. }
  1572. Init *FieldInit::getBit(unsigned Bit) const {
  1573. if (getType() == BitRecTy::get())
  1574. return const_cast<FieldInit*>(this);
  1575. return VarBitInit::get(const_cast<FieldInit*>(this), Bit);
  1576. }
  1577. Init *FieldInit::resolveReferences(Resolver &R) const {
  1578. Init *NewRec = Rec->resolveReferences(R);
  1579. if (NewRec != Rec)
  1580. return FieldInit::get(NewRec, FieldName)->Fold(R.getCurrentRecord());
  1581. return const_cast<FieldInit *>(this);
  1582. }
  1583. Init *FieldInit::Fold(Record *CurRec) const {
  1584. if (DefInit *DI = dyn_cast<DefInit>(Rec)) {
  1585. Record *Def = DI->getDef();
  1586. if (Def == CurRec)
  1587. PrintFatalError(CurRec->getLoc(),
  1588. Twine("Attempting to access field '") +
  1589. FieldName->getAsUnquotedString() + "' of '" +
  1590. Rec->getAsString() + "' is a forbidden self-reference");
  1591. Init *FieldVal = Def->getValue(FieldName)->getValue();
  1592. if (FieldVal->isComplete())
  1593. return FieldVal;
  1594. }
  1595. return const_cast<FieldInit *>(this);
  1596. }
  1597. bool FieldInit::isConcrete() const {
  1598. if (DefInit *DI = dyn_cast<DefInit>(Rec)) {
  1599. Init *FieldVal = DI->getDef()->getValue(FieldName)->getValue();
  1600. return FieldVal->isConcrete();
  1601. }
  1602. return false;
  1603. }
  1604. static void ProfileCondOpInit(FoldingSetNodeID &ID,
  1605. ArrayRef<Init *> CondRange,
  1606. ArrayRef<Init *> ValRange,
  1607. const RecTy *ValType) {
  1608. assert(CondRange.size() == ValRange.size() &&
  1609. "Number of conditions and values must match!");
  1610. ID.AddPointer(ValType);
  1611. ArrayRef<Init *>::iterator Case = CondRange.begin();
  1612. ArrayRef<Init *>::iterator Val = ValRange.begin();
  1613. while (Case != CondRange.end()) {
  1614. ID.AddPointer(*Case++);
  1615. ID.AddPointer(*Val++);
  1616. }
  1617. }
  1618. void CondOpInit::Profile(FoldingSetNodeID &ID) const {
  1619. ProfileCondOpInit(ID,
  1620. makeArrayRef(getTrailingObjects<Init *>(), NumConds),
  1621. makeArrayRef(getTrailingObjects<Init *>() + NumConds, NumConds),
  1622. ValType);
  1623. }
  1624. CondOpInit *
  1625. CondOpInit::get(ArrayRef<Init *> CondRange,
  1626. ArrayRef<Init *> ValRange, RecTy *Ty) {
  1627. assert(CondRange.size() == ValRange.size() &&
  1628. "Number of conditions and values must match!");
  1629. static FoldingSet<CondOpInit> ThePool;
  1630. FoldingSetNodeID ID;
  1631. ProfileCondOpInit(ID, CondRange, ValRange, Ty);
  1632. void *IP = nullptr;
  1633. if (CondOpInit *I = ThePool.FindNodeOrInsertPos(ID, IP))
  1634. return I;
  1635. void *Mem = Allocator.Allocate(totalSizeToAlloc<Init *>(2*CondRange.size()),
  1636. alignof(BitsInit));
  1637. CondOpInit *I = new(Mem) CondOpInit(CondRange.size(), Ty);
  1638. std::uninitialized_copy(CondRange.begin(), CondRange.end(),
  1639. I->getTrailingObjects<Init *>());
  1640. std::uninitialized_copy(ValRange.begin(), ValRange.end(),
  1641. I->getTrailingObjects<Init *>()+CondRange.size());
  1642. ThePool.InsertNode(I, IP);
  1643. return I;
  1644. }
  1645. Init *CondOpInit::resolveReferences(Resolver &R) const {
  1646. SmallVector<Init*, 4> NewConds;
  1647. bool Changed = false;
  1648. for (const Init *Case : getConds()) {
  1649. Init *NewCase = Case->resolveReferences(R);
  1650. NewConds.push_back(NewCase);
  1651. Changed |= NewCase != Case;
  1652. }
  1653. SmallVector<Init*, 4> NewVals;
  1654. for (const Init *Val : getVals()) {
  1655. Init *NewVal = Val->resolveReferences(R);
  1656. NewVals.push_back(NewVal);
  1657. Changed |= NewVal != Val;
  1658. }
  1659. if (Changed)
  1660. return (CondOpInit::get(NewConds, NewVals,
  1661. getValType()))->Fold(R.getCurrentRecord());
  1662. return const_cast<CondOpInit *>(this);
  1663. }
  1664. Init *CondOpInit::Fold(Record *CurRec) const {
  1665. for ( unsigned i = 0; i < NumConds; ++i) {
  1666. Init *Cond = getCond(i);
  1667. Init *Val = getVal(i);
  1668. if (IntInit *CondI = dyn_cast_or_null<IntInit>(
  1669. Cond->convertInitializerTo(IntRecTy::get()))) {
  1670. if (CondI->getValue())
  1671. return Val->convertInitializerTo(getValType());
  1672. } else
  1673. return const_cast<CondOpInit *>(this);
  1674. }
  1675. PrintFatalError(CurRec->getLoc(),
  1676. CurRec->getName() +
  1677. " does not have any true condition in:" +
  1678. this->getAsString());
  1679. return nullptr;
  1680. }
  1681. bool CondOpInit::isConcrete() const {
  1682. for (const Init *Case : getConds())
  1683. if (!Case->isConcrete())
  1684. return false;
  1685. for (const Init *Val : getVals())
  1686. if (!Val->isConcrete())
  1687. return false;
  1688. return true;
  1689. }
  1690. bool CondOpInit::isComplete() const {
  1691. for (const Init *Case : getConds())
  1692. if (!Case->isComplete())
  1693. return false;
  1694. for (const Init *Val : getVals())
  1695. if (!Val->isConcrete())
  1696. return false;
  1697. return true;
  1698. }
  1699. std::string CondOpInit::getAsString() const {
  1700. std::string Result = "!cond(";
  1701. for (unsigned i = 0; i < getNumConds(); i++) {
  1702. Result += getCond(i)->getAsString() + ": ";
  1703. Result += getVal(i)->getAsString();
  1704. if (i != getNumConds()-1)
  1705. Result += ", ";
  1706. }
  1707. return Result + ")";
  1708. }
  1709. Init *CondOpInit::getBit(unsigned Bit) const {
  1710. return VarBitInit::get(const_cast<CondOpInit *>(this), Bit);
  1711. }
  1712. static void ProfileDagInit(FoldingSetNodeID &ID, Init *V, StringInit *VN,
  1713. ArrayRef<Init *> ArgRange,
  1714. ArrayRef<StringInit *> NameRange) {
  1715. ID.AddPointer(V);
  1716. ID.AddPointer(VN);
  1717. ArrayRef<Init *>::iterator Arg = ArgRange.begin();
  1718. ArrayRef<StringInit *>::iterator Name = NameRange.begin();
  1719. while (Arg != ArgRange.end()) {
  1720. assert(Name != NameRange.end() && "Arg name underflow!");
  1721. ID.AddPointer(*Arg++);
  1722. ID.AddPointer(*Name++);
  1723. }
  1724. assert(Name == NameRange.end() && "Arg name overflow!");
  1725. }
  1726. DagInit *
  1727. DagInit::get(Init *V, StringInit *VN, ArrayRef<Init *> ArgRange,
  1728. ArrayRef<StringInit *> NameRange) {
  1729. static FoldingSet<DagInit> ThePool;
  1730. FoldingSetNodeID ID;
  1731. ProfileDagInit(ID, V, VN, ArgRange, NameRange);
  1732. void *IP = nullptr;
  1733. if (DagInit *I = ThePool.FindNodeOrInsertPos(ID, IP))
  1734. return I;
  1735. void *Mem = Allocator.Allocate(totalSizeToAlloc<Init *, StringInit *>(ArgRange.size(), NameRange.size()), alignof(BitsInit));
  1736. DagInit *I = new(Mem) DagInit(V, VN, ArgRange.size(), NameRange.size());
  1737. std::uninitialized_copy(ArgRange.begin(), ArgRange.end(),
  1738. I->getTrailingObjects<Init *>());
  1739. std::uninitialized_copy(NameRange.begin(), NameRange.end(),
  1740. I->getTrailingObjects<StringInit *>());
  1741. ThePool.InsertNode(I, IP);
  1742. return I;
  1743. }
  1744. DagInit *
  1745. DagInit::get(Init *V, StringInit *VN,
  1746. ArrayRef<std::pair<Init*, StringInit*>> args) {
  1747. SmallVector<Init *, 8> Args;
  1748. SmallVector<StringInit *, 8> Names;
  1749. for (const auto &Arg : args) {
  1750. Args.push_back(Arg.first);
  1751. Names.push_back(Arg.second);
  1752. }
  1753. return DagInit::get(V, VN, Args, Names);
  1754. }
  1755. void DagInit::Profile(FoldingSetNodeID &ID) const {
  1756. ProfileDagInit(ID, Val, ValName, makeArrayRef(getTrailingObjects<Init *>(), NumArgs), makeArrayRef(getTrailingObjects<StringInit *>(), NumArgNames));
  1757. }
  1758. Record *DagInit::getOperatorAsDef(ArrayRef<SMLoc> Loc) const {
  1759. if (DefInit *DefI = dyn_cast<DefInit>(Val))
  1760. return DefI->getDef();
  1761. PrintFatalError(Loc, "Expected record as operator");
  1762. return nullptr;
  1763. }
  1764. Init *DagInit::resolveReferences(Resolver &R) const {
  1765. SmallVector<Init*, 8> NewArgs;
  1766. NewArgs.reserve(arg_size());
  1767. bool ArgsChanged = false;
  1768. for (const Init *Arg : getArgs()) {
  1769. Init *NewArg = Arg->resolveReferences(R);
  1770. NewArgs.push_back(NewArg);
  1771. ArgsChanged |= NewArg != Arg;
  1772. }
  1773. Init *Op = Val->resolveReferences(R);
  1774. if (Op != Val || ArgsChanged)
  1775. return DagInit::get(Op, ValName, NewArgs, getArgNames());
  1776. return const_cast<DagInit *>(this);
  1777. }
  1778. bool DagInit::isConcrete() const {
  1779. if (!Val->isConcrete())
  1780. return false;
  1781. for (const Init *Elt : getArgs()) {
  1782. if (!Elt->isConcrete())
  1783. return false;
  1784. }
  1785. return true;
  1786. }
  1787. std::string DagInit::getAsString() const {
  1788. std::string Result = "(" + Val->getAsString();
  1789. if (ValName)
  1790. Result += ":" + ValName->getAsUnquotedString();
  1791. if (!arg_empty()) {
  1792. Result += " " + getArg(0)->getAsString();
  1793. if (getArgName(0)) Result += ":$" + getArgName(0)->getAsUnquotedString();
  1794. for (unsigned i = 1, e = getNumArgs(); i != e; ++i) {
  1795. Result += ", " + getArg(i)->getAsString();
  1796. if (getArgName(i)) Result += ":$" + getArgName(i)->getAsUnquotedString();
  1797. }
  1798. }
  1799. return Result + ")";
  1800. }
  1801. //===----------------------------------------------------------------------===//
  1802. // Other implementations
  1803. //===----------------------------------------------------------------------===//
  1804. RecordVal::RecordVal(Init *N, RecTy *T, FieldKind K)
  1805. : Name(N), TyAndKind(T, K) {
  1806. setValue(UnsetInit::get());
  1807. assert(Value && "Cannot create unset value for current type!");
  1808. }
  1809. // This constructor accepts the same arguments as the above, but also
  1810. // a source location.
  1811. RecordVal::RecordVal(Init *N, SMLoc Loc, RecTy *T, FieldKind K)
  1812. : Name(N), Loc(Loc), TyAndKind(T, K) {
  1813. setValue(UnsetInit::get());
  1814. assert(Value && "Cannot create unset value for current type!");
  1815. }
  1816. StringRef RecordVal::getName() const {
  1817. return cast<StringInit>(getNameInit())->getValue();
  1818. }
  1819. std::string RecordVal::getPrintType() const {
  1820. if (getType() == StringRecTy::get()) {
  1821. if (auto *StrInit = dyn_cast<StringInit>(Value)) {
  1822. if (StrInit->hasCodeFormat())
  1823. return "code";
  1824. else
  1825. return "string";
  1826. } else {
  1827. return "string";
  1828. }
  1829. } else {
  1830. return TyAndKind.getPointer()->getAsString();
  1831. }
  1832. }
  1833. bool RecordVal::setValue(Init *V) {
  1834. if (V) {
  1835. Value = V->getCastTo(getType());
  1836. if (Value) {
  1837. assert(!isa<TypedInit>(Value) ||
  1838. cast<TypedInit>(Value)->getType()->typeIsA(getType()));
  1839. if (BitsRecTy *BTy = dyn_cast<BitsRecTy>(getType())) {
  1840. if (!isa<BitsInit>(Value)) {
  1841. SmallVector<Init *, 64> Bits;
  1842. Bits.reserve(BTy->getNumBits());
  1843. for (unsigned I = 0, E = BTy->getNumBits(); I < E; ++I)
  1844. Bits.push_back(Value->getBit(I));
  1845. Value = BitsInit::get(Bits);
  1846. }
  1847. }
  1848. }
  1849. return Value == nullptr;
  1850. }
  1851. Value = nullptr;
  1852. return false;
  1853. }
  1854. // This version of setValue takes a source location and resets the
  1855. // location in the RecordVal.
  1856. bool RecordVal::setValue(Init *V, SMLoc NewLoc) {
  1857. Loc = NewLoc;
  1858. if (V) {
  1859. Value = V->getCastTo(getType());
  1860. if (Value) {
  1861. assert(!isa<TypedInit>(Value) ||
  1862. cast<TypedInit>(Value)->getType()->typeIsA(getType()));
  1863. if (BitsRecTy *BTy = dyn_cast<BitsRecTy>(getType())) {
  1864. if (!isa<BitsInit>(Value)) {
  1865. SmallVector<Init *, 64> Bits;
  1866. Bits.reserve(BTy->getNumBits());
  1867. for (unsigned I = 0, E = BTy->getNumBits(); I < E; ++I)
  1868. Bits.push_back(Value->getBit(I));
  1869. Value = BitsInit::get(Bits);
  1870. }
  1871. }
  1872. }
  1873. return Value == nullptr;
  1874. }
  1875. Value = nullptr;
  1876. return false;
  1877. }
  1878. #include "llvm/TableGen/Record.h"
  1879. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  1880. LLVM_DUMP_METHOD void RecordVal::dump() const { errs() << *this; }
  1881. #endif
  1882. void RecordVal::print(raw_ostream &OS, bool PrintSem) const {
  1883. if (isNonconcreteOK()) OS << "field ";
  1884. OS << getPrintType() << " " << getNameInitAsString();
  1885. if (getValue())
  1886. OS << " = " << *getValue();
  1887. if (PrintSem) OS << ";\n";
  1888. }
  1889. unsigned Record::LastID = 0;
  1890. void Record::checkName() {
  1891. // Ensure the record name has string type.
  1892. const TypedInit *TypedName = cast<const TypedInit>(Name);
  1893. if (!isa<StringRecTy>(TypedName->getType()))
  1894. PrintFatalError(getLoc(), Twine("Record name '") + Name->getAsString() +
  1895. "' is not a string!");
  1896. }
  1897. RecordRecTy *Record::getType() {
  1898. SmallVector<Record *, 4> DirectSCs;
  1899. getDirectSuperClasses(DirectSCs);
  1900. return RecordRecTy::get(DirectSCs);
  1901. }
  1902. DefInit *Record::getDefInit() {
  1903. if (!CorrespondingDefInit)
  1904. CorrespondingDefInit = new (Allocator) DefInit(this);
  1905. return CorrespondingDefInit;
  1906. }
  1907. void Record::setName(Init *NewName) {
  1908. Name = NewName;
  1909. checkName();
  1910. // DO NOT resolve record values to the name at this point because
  1911. // there might be default values for arguments of this def. Those
  1912. // arguments might not have been resolved yet so we don't want to
  1913. // prematurely assume values for those arguments were not passed to
  1914. // this def.
  1915. //
  1916. // Nonetheless, it may be that some of this Record's values
  1917. // reference the record name. Indeed, the reason for having the
  1918. // record name be an Init is to provide this flexibility. The extra
  1919. // resolve steps after completely instantiating defs takes care of
  1920. // this. See TGParser::ParseDef and TGParser::ParseDefm.
  1921. }
  1922. // NOTE for the next two functions:
  1923. // Superclasses are in post-order, so the final one is a direct
  1924. // superclass. All of its transitive superclases immediately precede it,
  1925. // so we can step through the direct superclasses in reverse order.
  1926. bool Record::hasDirectSuperClass(const Record *Superclass) const {
  1927. ArrayRef<std::pair<Record *, SMRange>> SCs = getSuperClasses();
  1928. for (int I = SCs.size() - 1; I >= 0; --I) {
  1929. const Record *SC = SCs[I].first;
  1930. if (SC == Superclass)
  1931. return true;
  1932. I -= SC->getSuperClasses().size();
  1933. }
  1934. return false;
  1935. }
  1936. void Record::getDirectSuperClasses(SmallVectorImpl<Record *> &Classes) const {
  1937. ArrayRef<std::pair<Record *, SMRange>> SCs = getSuperClasses();
  1938. while (!SCs.empty()) {
  1939. Record *SC = SCs.back().first;
  1940. SCs = SCs.drop_back(1 + SC->getSuperClasses().size());
  1941. Classes.push_back(SC);
  1942. }
  1943. }
  1944. void Record::resolveReferences(Resolver &R, const RecordVal *SkipVal) {
  1945. for (RecordVal &Value : Values) {
  1946. if (SkipVal == &Value) // Skip resolve the same field as the given one
  1947. continue;
  1948. if (Init *V = Value.getValue()) {
  1949. Init *VR = V->resolveReferences(R);
  1950. if (Value.setValue(VR)) {
  1951. std::string Type;
  1952. if (TypedInit *VRT = dyn_cast<TypedInit>(VR))
  1953. Type =
  1954. (Twine("of type '") + VRT->getType()->getAsString() + "' ").str();
  1955. PrintFatalError(getLoc(), Twine("Invalid value ") + Type +
  1956. "is found when setting '" +
  1957. Value.getNameInitAsString() +
  1958. "' of type '" +
  1959. Value.getType()->getAsString() +
  1960. "' after resolving references: " +
  1961. VR->getAsUnquotedString() + "\n");
  1962. }
  1963. }
  1964. }
  1965. Init *OldName = getNameInit();
  1966. Init *NewName = Name->resolveReferences(R);
  1967. if (NewName != OldName) {
  1968. // Re-register with RecordKeeper.
  1969. setName(NewName);
  1970. }
  1971. }
  1972. void Record::resolveReferences() {
  1973. RecordResolver R(*this);
  1974. R.setFinal(true);
  1975. resolveReferences(R);
  1976. }
  1977. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  1978. LLVM_DUMP_METHOD void Record::dump() const { errs() << *this; }
  1979. #endif
  1980. raw_ostream &llvm::operator<<(raw_ostream &OS, const Record &R) {
  1981. OS << R.getNameInitAsString();
  1982. ArrayRef<Init *> TArgs = R.getTemplateArgs();
  1983. if (!TArgs.empty()) {
  1984. OS << "<";
  1985. bool NeedComma = false;
  1986. for (const Init *TA : TArgs) {
  1987. if (NeedComma) OS << ", ";
  1988. NeedComma = true;
  1989. const RecordVal *RV = R.getValue(TA);
  1990. assert(RV && "Template argument record not found??");
  1991. RV->print(OS, false);
  1992. }
  1993. OS << ">";
  1994. }
  1995. OS << " {";
  1996. ArrayRef<std::pair<Record *, SMRange>> SC = R.getSuperClasses();
  1997. if (!SC.empty()) {
  1998. OS << "\t//";
  1999. for (const auto &SuperPair : SC)
  2000. OS << " " << SuperPair.first->getNameInitAsString();
  2001. }
  2002. OS << "\n";
  2003. for (const RecordVal &Val : R.getValues())
  2004. if (Val.isNonconcreteOK() && !R.isTemplateArg(Val.getNameInit()))
  2005. OS << Val;
  2006. for (const RecordVal &Val : R.getValues())
  2007. if (!Val.isNonconcreteOK() && !R.isTemplateArg(Val.getNameInit()))
  2008. OS << Val;
  2009. return OS << "}\n";
  2010. }
  2011. SMLoc Record::getFieldLoc(StringRef FieldName) const {
  2012. const RecordVal *R = getValue(FieldName);
  2013. if (!R)
  2014. PrintFatalError(getLoc(), "Record `" + getName() +
  2015. "' does not have a field named `" + FieldName + "'!\n");
  2016. return R->getLoc();
  2017. }
  2018. Init *Record::getValueInit(StringRef FieldName) const {
  2019. const RecordVal *R = getValue(FieldName);
  2020. if (!R || !R->getValue())
  2021. PrintFatalError(getLoc(), "Record `" + getName() +
  2022. "' does not have a field named `" + FieldName + "'!\n");
  2023. return R->getValue();
  2024. }
  2025. StringRef Record::getValueAsString(StringRef FieldName) const {
  2026. llvm::Optional<StringRef> S = getValueAsOptionalString(FieldName);
  2027. if (!S.hasValue())
  2028. PrintFatalError(getLoc(), "Record `" + getName() +
  2029. "' does not have a field named `" + FieldName + "'!\n");
  2030. return S.getValue();
  2031. }
  2032. llvm::Optional<StringRef>
  2033. Record::getValueAsOptionalString(StringRef FieldName) const {
  2034. const RecordVal *R = getValue(FieldName);
  2035. if (!R || !R->getValue())
  2036. return llvm::Optional<StringRef>();
  2037. if (isa<UnsetInit>(R->getValue()))
  2038. return llvm::Optional<StringRef>();
  2039. if (StringInit *SI = dyn_cast<StringInit>(R->getValue()))
  2040. return SI->getValue();
  2041. PrintFatalError(getLoc(),
  2042. "Record `" + getName() + "', ` field `" + FieldName +
  2043. "' exists but does not have a string initializer!");
  2044. }
  2045. BitsInit *Record::getValueAsBitsInit(StringRef FieldName) const {
  2046. const RecordVal *R = getValue(FieldName);
  2047. if (!R || !R->getValue())
  2048. PrintFatalError(getLoc(), "Record `" + getName() +
  2049. "' does not have a field named `" + FieldName + "'!\n");
  2050. if (BitsInit *BI = dyn_cast<BitsInit>(R->getValue()))
  2051. return BI;
  2052. PrintFatalError(getLoc(), "Record `" + getName() + "', field `" + FieldName +
  2053. "' exists but does not have a bits value");
  2054. }
  2055. ListInit *Record::getValueAsListInit(StringRef FieldName) const {
  2056. const RecordVal *R = getValue(FieldName);
  2057. if (!R || !R->getValue())
  2058. PrintFatalError(getLoc(), "Record `" + getName() +
  2059. "' does not have a field named `" + FieldName + "'!\n");
  2060. if (ListInit *LI = dyn_cast<ListInit>(R->getValue()))
  2061. return LI;
  2062. PrintFatalError(getLoc(), "Record `" + getName() + "', field `" + FieldName +
  2063. "' exists but does not have a list value");
  2064. }
  2065. std::vector<Record*>
  2066. Record::getValueAsListOfDefs(StringRef FieldName) const {
  2067. ListInit *List = getValueAsListInit(FieldName);
  2068. std::vector<Record*> Defs;
  2069. for (Init *I : List->getValues()) {
  2070. if (DefInit *DI = dyn_cast<DefInit>(I))
  2071. Defs.push_back(DI->getDef());
  2072. else
  2073. PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
  2074. FieldName + "' list is not entirely DefInit!");
  2075. }
  2076. return Defs;
  2077. }
  2078. int64_t Record::getValueAsInt(StringRef FieldName) const {
  2079. const RecordVal *R = getValue(FieldName);
  2080. if (!R || !R->getValue())
  2081. PrintFatalError(getLoc(), "Record `" + getName() +
  2082. "' does not have a field named `" + FieldName + "'!\n");
  2083. if (IntInit *II = dyn_cast<IntInit>(R->getValue()))
  2084. return II->getValue();
  2085. PrintFatalError(getLoc(), Twine("Record `") + getName() + "', field `" +
  2086. FieldName +
  2087. "' exists but does not have an int value: " +
  2088. R->getValue()->getAsString());
  2089. }
  2090. std::vector<int64_t>
  2091. Record::getValueAsListOfInts(StringRef FieldName) const {
  2092. ListInit *List = getValueAsListInit(FieldName);
  2093. std::vector<int64_t> Ints;
  2094. for (Init *I : List->getValues()) {
  2095. if (IntInit *II = dyn_cast<IntInit>(I))
  2096. Ints.push_back(II->getValue());
  2097. else
  2098. PrintFatalError(getLoc(),
  2099. Twine("Record `") + getName() + "', field `" + FieldName +
  2100. "' exists but does not have a list of ints value: " +
  2101. I->getAsString());
  2102. }
  2103. return Ints;
  2104. }
  2105. std::vector<StringRef>
  2106. Record::getValueAsListOfStrings(StringRef FieldName) const {
  2107. ListInit *List = getValueAsListInit(FieldName);
  2108. std::vector<StringRef> Strings;
  2109. for (Init *I : List->getValues()) {
  2110. if (StringInit *SI = dyn_cast<StringInit>(I))
  2111. Strings.push_back(SI->getValue());
  2112. else
  2113. PrintFatalError(getLoc(),
  2114. Twine("Record `") + getName() + "', field `" + FieldName +
  2115. "' exists but does not have a list of strings value: " +
  2116. I->getAsString());
  2117. }
  2118. return Strings;
  2119. }
  2120. Record *Record::getValueAsDef(StringRef FieldName) const {
  2121. const RecordVal *R = getValue(FieldName);
  2122. if (!R || !R->getValue())
  2123. PrintFatalError(getLoc(), "Record `" + getName() +
  2124. "' does not have a field named `" + FieldName + "'!\n");
  2125. if (DefInit *DI = dyn_cast<DefInit>(R->getValue()))
  2126. return DI->getDef();
  2127. PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
  2128. FieldName + "' does not have a def initializer!");
  2129. }
  2130. Record *Record::getValueAsOptionalDef(StringRef FieldName) const {
  2131. const RecordVal *R = getValue(FieldName);
  2132. if (!R || !R->getValue())
  2133. PrintFatalError(getLoc(), "Record `" + getName() +
  2134. "' does not have a field named `" + FieldName + "'!\n");
  2135. if (DefInit *DI = dyn_cast<DefInit>(R->getValue()))
  2136. return DI->getDef();
  2137. if (isa<UnsetInit>(R->getValue()))
  2138. return nullptr;
  2139. PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
  2140. FieldName + "' does not have either a def initializer or '?'!");
  2141. }
  2142. bool Record::getValueAsBit(StringRef FieldName) const {
  2143. const RecordVal *R = getValue(FieldName);
  2144. if (!R || !R->getValue())
  2145. PrintFatalError(getLoc(), "Record `" + getName() +
  2146. "' does not have a field named `" + FieldName + "'!\n");
  2147. if (BitInit *BI = dyn_cast<BitInit>(R->getValue()))
  2148. return BI->getValue();
  2149. PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
  2150. FieldName + "' does not have a bit initializer!");
  2151. }
  2152. bool Record::getValueAsBitOrUnset(StringRef FieldName, bool &Unset) const {
  2153. const RecordVal *R = getValue(FieldName);
  2154. if (!R || !R->getValue())
  2155. PrintFatalError(getLoc(), "Record `" + getName() +
  2156. "' does not have a field named `" + FieldName.str() + "'!\n");
  2157. if (isa<UnsetInit>(R->getValue())) {
  2158. Unset = true;
  2159. return false;
  2160. }
  2161. Unset = false;
  2162. if (BitInit *BI = dyn_cast<BitInit>(R->getValue()))
  2163. return BI->getValue();
  2164. PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
  2165. FieldName + "' does not have a bit initializer!");
  2166. }
  2167. DagInit *Record::getValueAsDag(StringRef FieldName) const {
  2168. const RecordVal *R = getValue(FieldName);
  2169. if (!R || !R->getValue())
  2170. PrintFatalError(getLoc(), "Record `" + getName() +
  2171. "' does not have a field named `" + FieldName + "'!\n");
  2172. if (DagInit *DI = dyn_cast<DagInit>(R->getValue()))
  2173. return DI;
  2174. PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
  2175. FieldName + "' does not have a dag initializer!");
  2176. }
  2177. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  2178. LLVM_DUMP_METHOD void RecordKeeper::dump() const { errs() << *this; }
  2179. #endif
  2180. raw_ostream &llvm::operator<<(raw_ostream &OS, const RecordKeeper &RK) {
  2181. OS << "------------- Classes -----------------\n";
  2182. for (const auto &C : RK.getClasses())
  2183. OS << "class " << *C.second;
  2184. OS << "------------- Defs -----------------\n";
  2185. for (const auto &D : RK.getDefs())
  2186. OS << "def " << *D.second;
  2187. return OS;
  2188. }
  2189. /// GetNewAnonymousName - Generate a unique anonymous name that can be used as
  2190. /// an identifier.
  2191. Init *RecordKeeper::getNewAnonymousName() {
  2192. return StringInit::get("anonymous_" + utostr(AnonCounter++));
  2193. }
  2194. // These functions implement the phase timing facility. Starting a timer
  2195. // when one is already running stops the running one.
  2196. void RecordKeeper::startTimer(StringRef Name) {
  2197. if (TimingGroup) {
  2198. if (LastTimer && LastTimer->isRunning()) {
  2199. LastTimer->stopTimer();
  2200. if (BackendTimer) {
  2201. LastTimer->clear();
  2202. BackendTimer = false;
  2203. }
  2204. }
  2205. LastTimer = new Timer("", Name, *TimingGroup);
  2206. LastTimer->startTimer();
  2207. }
  2208. }
  2209. void RecordKeeper::stopTimer() {
  2210. if (TimingGroup) {
  2211. assert(LastTimer && "No phase timer was started");
  2212. LastTimer->stopTimer();
  2213. }
  2214. }
  2215. void RecordKeeper::startBackendTimer(StringRef Name) {
  2216. if (TimingGroup) {
  2217. startTimer(Name);
  2218. BackendTimer = true;
  2219. }
  2220. }
  2221. void RecordKeeper::stopBackendTimer() {
  2222. if (TimingGroup) {
  2223. if (BackendTimer) {
  2224. stopTimer();
  2225. BackendTimer = false;
  2226. }
  2227. }
  2228. }
  2229. // We cache the record vectors for single classes. Many backends request
  2230. // the same vectors multiple times.
  2231. std::vector<Record *> RecordKeeper::getAllDerivedDefinitions(
  2232. StringRef ClassName) const {
  2233. auto Pair = ClassRecordsMap.try_emplace(ClassName);
  2234. if (Pair.second)
  2235. Pair.first->second = getAllDerivedDefinitions(makeArrayRef(ClassName));
  2236. return Pair.first->second;
  2237. }
  2238. std::vector<Record *> RecordKeeper::getAllDerivedDefinitions(
  2239. ArrayRef<StringRef> ClassNames) const {
  2240. SmallVector<Record *, 2> ClassRecs;
  2241. std::vector<Record *> Defs;
  2242. assert(ClassNames.size() > 0 && "At least one class must be passed.");
  2243. for (const auto &ClassName : ClassNames) {
  2244. Record *Class = getClass(ClassName);
  2245. if (!Class)
  2246. PrintFatalError("The class '" + ClassName + "' is not defined\n");
  2247. ClassRecs.push_back(Class);
  2248. }
  2249. for (const auto &OneDef : getDefs()) {
  2250. if (all_of(ClassRecs, [&OneDef](const Record *Class) {
  2251. return OneDef.second->isSubClassOf(Class);
  2252. }))
  2253. Defs.push_back(OneDef.second.get());
  2254. }
  2255. return Defs;
  2256. }
  2257. Init *MapResolver::resolve(Init *VarName) {
  2258. auto It = Map.find(VarName);
  2259. if (It == Map.end())
  2260. return nullptr;
  2261. Init *I = It->second.V;
  2262. if (!It->second.Resolved && Map.size() > 1) {
  2263. // Resolve mutual references among the mapped variables, but prevent
  2264. // infinite recursion.
  2265. Map.erase(It);
  2266. I = I->resolveReferences(*this);
  2267. Map[VarName] = {I, true};
  2268. }
  2269. return I;
  2270. }
  2271. Init *RecordResolver::resolve(Init *VarName) {
  2272. Init *Val = Cache.lookup(VarName);
  2273. if (Val)
  2274. return Val;
  2275. for (Init *S : Stack) {
  2276. if (S == VarName)
  2277. return nullptr; // prevent infinite recursion
  2278. }
  2279. if (RecordVal *RV = getCurrentRecord()->getValue(VarName)) {
  2280. if (!isa<UnsetInit>(RV->getValue())) {
  2281. Val = RV->getValue();
  2282. Stack.push_back(VarName);
  2283. Val = Val->resolveReferences(*this);
  2284. Stack.pop_back();
  2285. }
  2286. }
  2287. Cache[VarName] = Val;
  2288. return Val;
  2289. }
  2290. Init *TrackUnresolvedResolver::resolve(Init *VarName) {
  2291. Init *I = nullptr;
  2292. if (R) {
  2293. I = R->resolve(VarName);
  2294. if (I && !FoundUnresolved) {
  2295. // Do not recurse into the resolved initializer, as that would change
  2296. // the behavior of the resolver we're delegating, but do check to see
  2297. // if there are unresolved variables remaining.
  2298. TrackUnresolvedResolver Sub;
  2299. I->resolveReferences(Sub);
  2300. FoundUnresolved |= Sub.FoundUnresolved;
  2301. }
  2302. }
  2303. if (!I)
  2304. FoundUnresolved = true;
  2305. return I;
  2306. }
  2307. Init *HasReferenceResolver::resolve(Init *VarName)
  2308. {
  2309. if (VarName == VarNameToTrack)
  2310. Found = true;
  2311. return nullptr;
  2312. }