TGParser.cpp 114 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801
  1. //===- TGParser.cpp - Parser for TableGen Files ---------------------------===//
  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 Parser for TableGen.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "TGParser.h"
  13. #include "llvm/ADT/DenseMapInfo.h"
  14. #include "llvm/ADT/None.h"
  15. #include "llvm/ADT/SmallVector.h"
  16. #include "llvm/ADT/StringExtras.h"
  17. #include "llvm/ADT/Twine.h"
  18. #include "llvm/Config/llvm-config.h"
  19. #include "llvm/Support/Casting.h"
  20. #include "llvm/Support/Compiler.h"
  21. #include "llvm/Support/ErrorHandling.h"
  22. #include "llvm/Support/raw_ostream.h"
  23. #include <algorithm>
  24. #include <cassert>
  25. #include <cstdint>
  26. #include <limits>
  27. using namespace llvm;
  28. //===----------------------------------------------------------------------===//
  29. // Support Code for the Semantic Actions.
  30. //===----------------------------------------------------------------------===//
  31. namespace llvm {
  32. struct SubClassReference {
  33. SMRange RefRange;
  34. Record *Rec;
  35. SmallVector<Init*, 4> TemplateArgs;
  36. SubClassReference() : Rec(nullptr) {}
  37. bool isInvalid() const { return Rec == nullptr; }
  38. };
  39. struct SubMultiClassReference {
  40. SMRange RefRange;
  41. MultiClass *MC;
  42. SmallVector<Init*, 4> TemplateArgs;
  43. SubMultiClassReference() : MC(nullptr) {}
  44. bool isInvalid() const { return MC == nullptr; }
  45. void dump() const;
  46. };
  47. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  48. LLVM_DUMP_METHOD void SubMultiClassReference::dump() const {
  49. errs() << "Multiclass:\n";
  50. MC->dump();
  51. errs() << "Template args:\n";
  52. for (Init *TA : TemplateArgs)
  53. TA->dump();
  54. }
  55. #endif
  56. } // end namespace llvm
  57. static bool checkBitsConcrete(Record &R, const RecordVal &RV) {
  58. BitsInit *BV = cast<BitsInit>(RV.getValue());
  59. for (unsigned i = 0, e = BV->getNumBits(); i != e; ++i) {
  60. Init *Bit = BV->getBit(i);
  61. bool IsReference = false;
  62. if (auto VBI = dyn_cast<VarBitInit>(Bit)) {
  63. if (auto VI = dyn_cast<VarInit>(VBI->getBitVar())) {
  64. if (R.getValue(VI->getName()))
  65. IsReference = true;
  66. }
  67. } else if (isa<VarInit>(Bit)) {
  68. IsReference = true;
  69. }
  70. if (!(IsReference || Bit->isConcrete()))
  71. return false;
  72. }
  73. return true;
  74. }
  75. static void checkConcrete(Record &R) {
  76. for (const RecordVal &RV : R.getValues()) {
  77. // HACK: Disable this check for variables declared with 'field'. This is
  78. // done merely because existing targets have legitimate cases of
  79. // non-concrete variables in helper defs. Ideally, we'd introduce a
  80. // 'maybe' or 'optional' modifier instead of this.
  81. if (RV.isNonconcreteOK())
  82. continue;
  83. if (Init *V = RV.getValue()) {
  84. bool Ok = isa<BitsInit>(V) ? checkBitsConcrete(R, RV) : V->isConcrete();
  85. if (!Ok) {
  86. PrintError(R.getLoc(),
  87. Twine("Initializer of '") + RV.getNameInitAsString() +
  88. "' in '" + R.getNameInitAsString() +
  89. "' could not be fully resolved: " +
  90. RV.getValue()->getAsString());
  91. }
  92. }
  93. }
  94. }
  95. /// Return an Init with a qualifier prefix referring
  96. /// to CurRec's name.
  97. static Init *QualifyName(Record &CurRec, MultiClass *CurMultiClass,
  98. Init *Name, StringRef Scoper) {
  99. Init *NewName =
  100. BinOpInit::getStrConcat(CurRec.getNameInit(), StringInit::get(Scoper));
  101. NewName = BinOpInit::getStrConcat(NewName, Name);
  102. if (CurMultiClass && Scoper != "::") {
  103. Init *Prefix = BinOpInit::getStrConcat(CurMultiClass->Rec.getNameInit(),
  104. StringInit::get("::"));
  105. NewName = BinOpInit::getStrConcat(Prefix, NewName);
  106. }
  107. if (BinOpInit *BinOp = dyn_cast<BinOpInit>(NewName))
  108. NewName = BinOp->Fold(&CurRec);
  109. return NewName;
  110. }
  111. /// Return the qualified version of the implicit 'NAME' template argument.
  112. static Init *QualifiedNameOfImplicitName(Record &Rec,
  113. MultiClass *MC = nullptr) {
  114. return QualifyName(Rec, MC, StringInit::get("NAME"), MC ? "::" : ":");
  115. }
  116. static Init *QualifiedNameOfImplicitName(MultiClass *MC) {
  117. return QualifiedNameOfImplicitName(MC->Rec, MC);
  118. }
  119. bool TGParser::AddValue(Record *CurRec, SMLoc Loc, const RecordVal &RV) {
  120. if (!CurRec)
  121. CurRec = &CurMultiClass->Rec;
  122. if (RecordVal *ERV = CurRec->getValue(RV.getNameInit())) {
  123. // The value already exists in the class, treat this as a set.
  124. if (ERV->setValue(RV.getValue()))
  125. return Error(Loc, "New definition of '" + RV.getName() + "' of type '" +
  126. RV.getType()->getAsString() + "' is incompatible with " +
  127. "previous definition of type '" +
  128. ERV->getType()->getAsString() + "'");
  129. } else {
  130. CurRec->addValue(RV);
  131. }
  132. return false;
  133. }
  134. /// SetValue -
  135. /// Return true on error, false on success.
  136. bool TGParser::SetValue(Record *CurRec, SMLoc Loc, Init *ValName,
  137. ArrayRef<unsigned> BitList, Init *V,
  138. bool AllowSelfAssignment) {
  139. if (!V) return false;
  140. if (!CurRec) CurRec = &CurMultiClass->Rec;
  141. RecordVal *RV = CurRec->getValue(ValName);
  142. if (!RV)
  143. return Error(Loc, "Value '" + ValName->getAsUnquotedString() +
  144. "' unknown!");
  145. // Do not allow assignments like 'X = X'. This will just cause infinite loops
  146. // in the resolution machinery.
  147. if (BitList.empty())
  148. if (VarInit *VI = dyn_cast<VarInit>(V))
  149. if (VI->getNameInit() == ValName && !AllowSelfAssignment)
  150. return Error(Loc, "Recursion / self-assignment forbidden");
  151. // If we are assigning to a subset of the bits in the value... then we must be
  152. // assigning to a field of BitsRecTy, which must have a BitsInit
  153. // initializer.
  154. //
  155. if (!BitList.empty()) {
  156. BitsInit *CurVal = dyn_cast<BitsInit>(RV->getValue());
  157. if (!CurVal)
  158. return Error(Loc, "Value '" + ValName->getAsUnquotedString() +
  159. "' is not a bits type");
  160. // Convert the incoming value to a bits type of the appropriate size...
  161. Init *BI = V->getCastTo(BitsRecTy::get(BitList.size()));
  162. if (!BI)
  163. return Error(Loc, "Initializer is not compatible with bit range");
  164. SmallVector<Init *, 16> NewBits(CurVal->getNumBits());
  165. // Loop over bits, assigning values as appropriate.
  166. for (unsigned i = 0, e = BitList.size(); i != e; ++i) {
  167. unsigned Bit = BitList[i];
  168. if (NewBits[Bit])
  169. return Error(Loc, "Cannot set bit #" + Twine(Bit) + " of value '" +
  170. ValName->getAsUnquotedString() + "' more than once");
  171. NewBits[Bit] = BI->getBit(i);
  172. }
  173. for (unsigned i = 0, e = CurVal->getNumBits(); i != e; ++i)
  174. if (!NewBits[i])
  175. NewBits[i] = CurVal->getBit(i);
  176. V = BitsInit::get(NewBits);
  177. }
  178. if (RV->setValue(V, Loc)) {
  179. std::string InitType;
  180. if (BitsInit *BI = dyn_cast<BitsInit>(V))
  181. InitType = (Twine("' of type bit initializer with length ") +
  182. Twine(BI->getNumBits())).str();
  183. else if (TypedInit *TI = dyn_cast<TypedInit>(V))
  184. InitType = (Twine("' of type '") + TI->getType()->getAsString()).str();
  185. return Error(Loc, "Field '" + ValName->getAsUnquotedString() +
  186. "' of type '" + RV->getType()->getAsString() +
  187. "' is incompatible with value '" +
  188. V->getAsString() + InitType + "'");
  189. }
  190. return false;
  191. }
  192. /// AddSubClass - Add SubClass as a subclass to CurRec, resolving its template
  193. /// args as SubClass's template arguments.
  194. bool TGParser::AddSubClass(Record *CurRec, SubClassReference &SubClass) {
  195. Record *SC = SubClass.Rec;
  196. MapResolver R(CurRec);
  197. // Loop over all the subclass record's fields. Add template arguments
  198. // to the resolver map. Add regular fields to the new record.
  199. for (const RecordVal &Field : SC->getValues()) {
  200. if (Field.isTemplateArg()) {
  201. R.set(Field.getNameInit(), Field.getValue());
  202. } else {
  203. if (AddValue(CurRec, SubClass.RefRange.Start, Field))
  204. return true;
  205. }
  206. }
  207. ArrayRef<Init *> TArgs = SC->getTemplateArgs();
  208. assert(SubClass.TemplateArgs.size() <= TArgs.size() &&
  209. "Too many template arguments allowed");
  210. // Loop over the template argument names. If a value was specified,
  211. // reset the map value. If not and there was no default, complain.
  212. for (unsigned I = 0, E = TArgs.size(); I != E; ++I) {
  213. if (I < SubClass.TemplateArgs.size())
  214. R.set(TArgs[I], SubClass.TemplateArgs[I]);
  215. else if (!R.isComplete(TArgs[I]))
  216. return Error(SubClass.RefRange.Start,
  217. "Value not specified for template argument '" +
  218. TArgs[I]->getAsUnquotedString() + "' (#" + Twine(I) +
  219. ") of parent class '" + SC->getNameInitAsString() + "'");
  220. }
  221. // Copy the subclass record's assertions to the new record.
  222. CurRec->appendAssertions(SC);
  223. Init *Name;
  224. if (CurRec->isClass())
  225. Name =
  226. VarInit::get(QualifiedNameOfImplicitName(*CurRec), StringRecTy::get());
  227. else
  228. Name = CurRec->getNameInit();
  229. R.set(QualifiedNameOfImplicitName(*SC), Name);
  230. CurRec->resolveReferences(R);
  231. // Since everything went well, we can now set the "superclass" list for the
  232. // current record.
  233. ArrayRef<std::pair<Record *, SMRange>> SCs = SC->getSuperClasses();
  234. for (const auto &SCPair : SCs) {
  235. if (CurRec->isSubClassOf(SCPair.first))
  236. return Error(SubClass.RefRange.Start,
  237. "Already subclass of '" + SCPair.first->getName() + "'!\n");
  238. CurRec->addSuperClass(SCPair.first, SCPair.second);
  239. }
  240. if (CurRec->isSubClassOf(SC))
  241. return Error(SubClass.RefRange.Start,
  242. "Already subclass of '" + SC->getName() + "'!\n");
  243. CurRec->addSuperClass(SC, SubClass.RefRange);
  244. return false;
  245. }
  246. bool TGParser::AddSubClass(RecordsEntry &Entry, SubClassReference &SubClass) {
  247. if (Entry.Rec)
  248. return AddSubClass(Entry.Rec.get(), SubClass);
  249. if (Entry.Assertion)
  250. return false;
  251. for (auto &E : Entry.Loop->Entries) {
  252. if (AddSubClass(E, SubClass))
  253. return true;
  254. }
  255. return false;
  256. }
  257. /// AddSubMultiClass - Add SubMultiClass as a subclass to
  258. /// CurMC, resolving its template args as SubMultiClass's
  259. /// template arguments.
  260. bool TGParser::AddSubMultiClass(MultiClass *CurMC,
  261. SubMultiClassReference &SubMultiClass) {
  262. MultiClass *SMC = SubMultiClass.MC;
  263. ArrayRef<Init *> SMCTArgs = SMC->Rec.getTemplateArgs();
  264. if (SMCTArgs.size() < SubMultiClass.TemplateArgs.size())
  265. return Error(SubMultiClass.RefRange.Start,
  266. "More template args specified than expected");
  267. // Prepare the mapping of template argument name to value, filling in default
  268. // values if necessary.
  269. SubstStack TemplateArgs;
  270. for (unsigned i = 0, e = SMCTArgs.size(); i != e; ++i) {
  271. if (i < SubMultiClass.TemplateArgs.size()) {
  272. TemplateArgs.emplace_back(SMCTArgs[i], SubMultiClass.TemplateArgs[i]);
  273. } else {
  274. Init *Default = SMC->Rec.getValue(SMCTArgs[i])->getValue();
  275. if (!Default->isComplete()) {
  276. return Error(SubMultiClass.RefRange.Start,
  277. "value not specified for template argument #" + Twine(i) +
  278. " (" + SMCTArgs[i]->getAsUnquotedString() +
  279. ") of multiclass '" + SMC->Rec.getNameInitAsString() +
  280. "'");
  281. }
  282. TemplateArgs.emplace_back(SMCTArgs[i], Default);
  283. }
  284. }
  285. TemplateArgs.emplace_back(
  286. QualifiedNameOfImplicitName(SMC),
  287. VarInit::get(QualifiedNameOfImplicitName(CurMC), StringRecTy::get()));
  288. // Add all of the defs in the subclass into the current multiclass.
  289. return resolve(SMC->Entries, TemplateArgs, false, &CurMC->Entries);
  290. }
  291. /// Add a record, foreach loop, or assertion to the current context.
  292. bool TGParser::addEntry(RecordsEntry E) {
  293. assert((!!E.Rec + !!E.Loop + !!E.Assertion) == 1 &&
  294. "RecordsEntry has invalid number of items");
  295. // If we are parsing a loop, add it to the loop's entries.
  296. if (!Loops.empty()) {
  297. Loops.back()->Entries.push_back(std::move(E));
  298. return false;
  299. }
  300. // If it is a loop, then resolve and perform the loop.
  301. if (E.Loop) {
  302. SubstStack Stack;
  303. return resolve(*E.Loop, Stack, CurMultiClass == nullptr,
  304. CurMultiClass ? &CurMultiClass->Entries : nullptr);
  305. }
  306. // If we are parsing a multiclass, add it to the multiclass's entries.
  307. if (CurMultiClass) {
  308. CurMultiClass->Entries.push_back(std::move(E));
  309. return false;
  310. }
  311. // If it is an assertion, then it's a top-level one, so check it.
  312. if (E.Assertion) {
  313. CheckAssert(E.Assertion->Loc, E.Assertion->Condition, E.Assertion->Message);
  314. return false;
  315. }
  316. // It must be a record, so finish it off.
  317. return addDefOne(std::move(E.Rec));
  318. }
  319. /// Resolve the entries in \p Loop, going over inner loops recursively
  320. /// and making the given subsitutions of (name, value) pairs.
  321. ///
  322. /// The resulting records are stored in \p Dest if non-null. Otherwise, they
  323. /// are added to the global record keeper.
  324. bool TGParser::resolve(const ForeachLoop &Loop, SubstStack &Substs,
  325. bool Final, std::vector<RecordsEntry> *Dest,
  326. SMLoc *Loc) {
  327. MapResolver R;
  328. for (const auto &S : Substs)
  329. R.set(S.first, S.second);
  330. Init *List = Loop.ListValue->resolveReferences(R);
  331. auto LI = dyn_cast<ListInit>(List);
  332. if (!LI) {
  333. if (!Final) {
  334. Dest->emplace_back(std::make_unique<ForeachLoop>(Loop.Loc, Loop.IterVar,
  335. List));
  336. return resolve(Loop.Entries, Substs, Final, &Dest->back().Loop->Entries,
  337. Loc);
  338. }
  339. PrintError(Loop.Loc, Twine("attempting to loop over '") +
  340. List->getAsString() + "', expected a list");
  341. return true;
  342. }
  343. bool Error = false;
  344. for (auto Elt : *LI) {
  345. if (Loop.IterVar)
  346. Substs.emplace_back(Loop.IterVar->getNameInit(), Elt);
  347. Error = resolve(Loop.Entries, Substs, Final, Dest);
  348. if (Loop.IterVar)
  349. Substs.pop_back();
  350. if (Error)
  351. break;
  352. }
  353. return Error;
  354. }
  355. /// Resolve the entries in \p Source, going over loops recursively and
  356. /// making the given substitutions of (name, value) pairs.
  357. ///
  358. /// The resulting records are stored in \p Dest if non-null. Otherwise, they
  359. /// are added to the global record keeper.
  360. bool TGParser::resolve(const std::vector<RecordsEntry> &Source,
  361. SubstStack &Substs, bool Final,
  362. std::vector<RecordsEntry> *Dest, SMLoc *Loc) {
  363. bool Error = false;
  364. for (auto &E : Source) {
  365. if (E.Loop) {
  366. Error = resolve(*E.Loop, Substs, Final, Dest);
  367. } else if (E.Assertion) {
  368. MapResolver R;
  369. for (const auto &S : Substs)
  370. R.set(S.first, S.second);
  371. Init *Condition = E.Assertion->Condition->resolveReferences(R);
  372. Init *Message = E.Assertion->Message->resolveReferences(R);
  373. if (Dest)
  374. Dest->push_back(std::make_unique<Record::AssertionInfo>(
  375. E.Assertion->Loc, Condition, Message));
  376. else
  377. CheckAssert(E.Assertion->Loc, Condition, Message);
  378. } else {
  379. auto Rec = std::make_unique<Record>(*E.Rec);
  380. if (Loc)
  381. Rec->appendLoc(*Loc);
  382. MapResolver R(Rec.get());
  383. for (const auto &S : Substs)
  384. R.set(S.first, S.second);
  385. Rec->resolveReferences(R);
  386. if (Dest)
  387. Dest->push_back(std::move(Rec));
  388. else
  389. Error = addDefOne(std::move(Rec));
  390. }
  391. if (Error)
  392. break;
  393. }
  394. return Error;
  395. }
  396. /// Resolve the record fully and add it to the record keeper.
  397. bool TGParser::addDefOne(std::unique_ptr<Record> Rec) {
  398. Init *NewName = nullptr;
  399. if (Record *Prev = Records.getDef(Rec->getNameInitAsString())) {
  400. if (!Rec->isAnonymous()) {
  401. PrintError(Rec->getLoc(),
  402. "def already exists: " + Rec->getNameInitAsString());
  403. PrintNote(Prev->getLoc(), "location of previous definition");
  404. return true;
  405. }
  406. NewName = Records.getNewAnonymousName();
  407. }
  408. Rec->resolveReferences(NewName);
  409. checkConcrete(*Rec);
  410. if (!isa<StringInit>(Rec->getNameInit())) {
  411. PrintError(Rec->getLoc(), Twine("record name '") +
  412. Rec->getNameInit()->getAsString() +
  413. "' could not be fully resolved");
  414. return true;
  415. }
  416. // Check the assertions.
  417. Rec->checkRecordAssertions();
  418. // If ObjectBody has template arguments, it's an error.
  419. assert(Rec->getTemplateArgs().empty() && "How'd this get template args?");
  420. for (DefsetRecord *Defset : Defsets) {
  421. DefInit *I = Rec->getDefInit();
  422. if (!I->getType()->typeIsA(Defset->EltTy)) {
  423. PrintError(Rec->getLoc(), Twine("adding record of incompatible type '") +
  424. I->getType()->getAsString() +
  425. "' to defset");
  426. PrintNote(Defset->Loc, "location of defset declaration");
  427. return true;
  428. }
  429. Defset->Elements.push_back(I);
  430. }
  431. Records.addDef(std::move(Rec));
  432. return false;
  433. }
  434. //===----------------------------------------------------------------------===//
  435. // Parser Code
  436. //===----------------------------------------------------------------------===//
  437. /// isObjectStart - Return true if this is a valid first token for a statement.
  438. static bool isObjectStart(tgtok::TokKind K) {
  439. return K == tgtok::Assert || K == tgtok::Class || K == tgtok::Def ||
  440. K == tgtok::Defm || K == tgtok::Defset || K == tgtok::Defvar ||
  441. K == tgtok::Foreach || K == tgtok::If || K == tgtok::Let ||
  442. K == tgtok::MultiClass;
  443. }
  444. bool TGParser::consume(tgtok::TokKind K) {
  445. if (Lex.getCode() == K) {
  446. Lex.Lex();
  447. return true;
  448. }
  449. return false;
  450. }
  451. /// ParseObjectName - If a valid object name is specified, return it. If no
  452. /// name is specified, return the unset initializer. Return nullptr on parse
  453. /// error.
  454. /// ObjectName ::= Value [ '#' Value ]*
  455. /// ObjectName ::= /*empty*/
  456. ///
  457. Init *TGParser::ParseObjectName(MultiClass *CurMultiClass) {
  458. switch (Lex.getCode()) {
  459. case tgtok::colon:
  460. case tgtok::semi:
  461. case tgtok::l_brace:
  462. // These are all of the tokens that can begin an object body.
  463. // Some of these can also begin values but we disallow those cases
  464. // because they are unlikely to be useful.
  465. return UnsetInit::get();
  466. default:
  467. break;
  468. }
  469. Record *CurRec = nullptr;
  470. if (CurMultiClass)
  471. CurRec = &CurMultiClass->Rec;
  472. Init *Name = ParseValue(CurRec, StringRecTy::get(), ParseNameMode);
  473. if (!Name)
  474. return nullptr;
  475. if (CurMultiClass) {
  476. Init *NameStr = QualifiedNameOfImplicitName(CurMultiClass);
  477. HasReferenceResolver R(NameStr);
  478. Name->resolveReferences(R);
  479. if (!R.found())
  480. Name = BinOpInit::getStrConcat(VarInit::get(NameStr, StringRecTy::get()),
  481. Name);
  482. }
  483. return Name;
  484. }
  485. /// ParseClassID - Parse and resolve a reference to a class name. This returns
  486. /// null on error.
  487. ///
  488. /// ClassID ::= ID
  489. ///
  490. Record *TGParser::ParseClassID() {
  491. if (Lex.getCode() != tgtok::Id) {
  492. TokError("expected name for ClassID");
  493. return nullptr;
  494. }
  495. Record *Result = Records.getClass(Lex.getCurStrVal());
  496. if (!Result) {
  497. std::string Msg("Couldn't find class '" + Lex.getCurStrVal() + "'");
  498. if (MultiClasses[Lex.getCurStrVal()].get())
  499. TokError(Msg + ". Use 'defm' if you meant to use multiclass '" +
  500. Lex.getCurStrVal() + "'");
  501. else
  502. TokError(Msg);
  503. }
  504. Lex.Lex();
  505. return Result;
  506. }
  507. /// ParseMultiClassID - Parse and resolve a reference to a multiclass name.
  508. /// This returns null on error.
  509. ///
  510. /// MultiClassID ::= ID
  511. ///
  512. MultiClass *TGParser::ParseMultiClassID() {
  513. if (Lex.getCode() != tgtok::Id) {
  514. TokError("expected name for MultiClassID");
  515. return nullptr;
  516. }
  517. MultiClass *Result = MultiClasses[Lex.getCurStrVal()].get();
  518. if (!Result)
  519. TokError("Couldn't find multiclass '" + Lex.getCurStrVal() + "'");
  520. Lex.Lex();
  521. return Result;
  522. }
  523. /// ParseSubClassReference - Parse a reference to a subclass or a
  524. /// multiclass. This returns a SubClassRefTy with a null Record* on error.
  525. ///
  526. /// SubClassRef ::= ClassID
  527. /// SubClassRef ::= ClassID '<' ValueList '>'
  528. ///
  529. SubClassReference TGParser::
  530. ParseSubClassReference(Record *CurRec, bool isDefm) {
  531. SubClassReference Result;
  532. Result.RefRange.Start = Lex.getLoc();
  533. if (isDefm) {
  534. if (MultiClass *MC = ParseMultiClassID())
  535. Result.Rec = &MC->Rec;
  536. } else {
  537. Result.Rec = ParseClassID();
  538. }
  539. if (!Result.Rec) return Result;
  540. // If there is no template arg list, we're done.
  541. if (!consume(tgtok::less)) {
  542. Result.RefRange.End = Lex.getLoc();
  543. return Result;
  544. }
  545. if (ParseTemplateArgValueList(Result.TemplateArgs, CurRec, Result.Rec)) {
  546. Result.Rec = nullptr; // Error parsing value list.
  547. return Result;
  548. }
  549. if (CheckTemplateArgValues(Result.TemplateArgs, Result.RefRange.Start,
  550. Result.Rec)) {
  551. Result.Rec = nullptr; // Error checking value list.
  552. return Result;
  553. }
  554. Result.RefRange.End = Lex.getLoc();
  555. return Result;
  556. }
  557. /// ParseSubMultiClassReference - Parse a reference to a subclass or to a
  558. /// templated submulticlass. This returns a SubMultiClassRefTy with a null
  559. /// Record* on error.
  560. ///
  561. /// SubMultiClassRef ::= MultiClassID
  562. /// SubMultiClassRef ::= MultiClassID '<' ValueList '>'
  563. ///
  564. SubMultiClassReference TGParser::
  565. ParseSubMultiClassReference(MultiClass *CurMC) {
  566. SubMultiClassReference Result;
  567. Result.RefRange.Start = Lex.getLoc();
  568. Result.MC = ParseMultiClassID();
  569. if (!Result.MC) return Result;
  570. // If there is no template arg list, we're done.
  571. if (!consume(tgtok::less)) {
  572. Result.RefRange.End = Lex.getLoc();
  573. return Result;
  574. }
  575. if (ParseTemplateArgValueList(Result.TemplateArgs, &CurMC->Rec,
  576. &Result.MC->Rec)) {
  577. Result.MC = nullptr; // Error parsing value list.
  578. return Result;
  579. }
  580. Result.RefRange.End = Lex.getLoc();
  581. return Result;
  582. }
  583. /// ParseRangePiece - Parse a bit/value range.
  584. /// RangePiece ::= INTVAL
  585. /// RangePiece ::= INTVAL '...' INTVAL
  586. /// RangePiece ::= INTVAL '-' INTVAL
  587. /// RangePiece ::= INTVAL INTVAL
  588. // The last two forms are deprecated.
  589. bool TGParser::ParseRangePiece(SmallVectorImpl<unsigned> &Ranges,
  590. TypedInit *FirstItem) {
  591. Init *CurVal = FirstItem;
  592. if (!CurVal)
  593. CurVal = ParseValue(nullptr);
  594. IntInit *II = dyn_cast_or_null<IntInit>(CurVal);
  595. if (!II)
  596. return TokError("expected integer or bitrange");
  597. int64_t Start = II->getValue();
  598. int64_t End;
  599. if (Start < 0)
  600. return TokError("invalid range, cannot be negative");
  601. switch (Lex.getCode()) {
  602. default:
  603. Ranges.push_back(Start);
  604. return false;
  605. case tgtok::dotdotdot:
  606. case tgtok::minus: {
  607. Lex.Lex(); // eat
  608. Init *I_End = ParseValue(nullptr);
  609. IntInit *II_End = dyn_cast_or_null<IntInit>(I_End);
  610. if (!II_End) {
  611. TokError("expected integer value as end of range");
  612. return true;
  613. }
  614. End = II_End->getValue();
  615. break;
  616. }
  617. case tgtok::IntVal: {
  618. End = -Lex.getCurIntVal();
  619. Lex.Lex();
  620. break;
  621. }
  622. }
  623. if (End < 0)
  624. return TokError("invalid range, cannot be negative");
  625. // Add to the range.
  626. if (Start < End)
  627. for (; Start <= End; ++Start)
  628. Ranges.push_back(Start);
  629. else
  630. for (; Start >= End; --Start)
  631. Ranges.push_back(Start);
  632. return false;
  633. }
  634. /// ParseRangeList - Parse a list of scalars and ranges into scalar values.
  635. ///
  636. /// RangeList ::= RangePiece (',' RangePiece)*
  637. ///
  638. void TGParser::ParseRangeList(SmallVectorImpl<unsigned> &Result) {
  639. // Parse the first piece.
  640. if (ParseRangePiece(Result)) {
  641. Result.clear();
  642. return;
  643. }
  644. while (consume(tgtok::comma))
  645. // Parse the next range piece.
  646. if (ParseRangePiece(Result)) {
  647. Result.clear();
  648. return;
  649. }
  650. }
  651. /// ParseOptionalRangeList - Parse either a range list in <>'s or nothing.
  652. /// OptionalRangeList ::= '<' RangeList '>'
  653. /// OptionalRangeList ::= /*empty*/
  654. bool TGParser::ParseOptionalRangeList(SmallVectorImpl<unsigned> &Ranges) {
  655. SMLoc StartLoc = Lex.getLoc();
  656. if (!consume(tgtok::less))
  657. return false;
  658. // Parse the range list.
  659. ParseRangeList(Ranges);
  660. if (Ranges.empty()) return true;
  661. if (!consume(tgtok::greater)) {
  662. TokError("expected '>' at end of range list");
  663. return Error(StartLoc, "to match this '<'");
  664. }
  665. return false;
  666. }
  667. /// ParseOptionalBitList - Parse either a bit list in {}'s or nothing.
  668. /// OptionalBitList ::= '{' RangeList '}'
  669. /// OptionalBitList ::= /*empty*/
  670. bool TGParser::ParseOptionalBitList(SmallVectorImpl<unsigned> &Ranges) {
  671. SMLoc StartLoc = Lex.getLoc();
  672. if (!consume(tgtok::l_brace))
  673. return false;
  674. // Parse the range list.
  675. ParseRangeList(Ranges);
  676. if (Ranges.empty()) return true;
  677. if (!consume(tgtok::r_brace)) {
  678. TokError("expected '}' at end of bit list");
  679. return Error(StartLoc, "to match this '{'");
  680. }
  681. return false;
  682. }
  683. /// ParseType - Parse and return a tblgen type. This returns null on error.
  684. ///
  685. /// Type ::= STRING // string type
  686. /// Type ::= CODE // code type
  687. /// Type ::= BIT // bit type
  688. /// Type ::= BITS '<' INTVAL '>' // bits<x> type
  689. /// Type ::= INT // int type
  690. /// Type ::= LIST '<' Type '>' // list<x> type
  691. /// Type ::= DAG // dag type
  692. /// Type ::= ClassID // Record Type
  693. ///
  694. RecTy *TGParser::ParseType() {
  695. switch (Lex.getCode()) {
  696. default: TokError("Unknown token when expecting a type"); return nullptr;
  697. case tgtok::String:
  698. case tgtok::Code: Lex.Lex(); return StringRecTy::get();
  699. case tgtok::Bit: Lex.Lex(); return BitRecTy::get();
  700. case tgtok::Int: Lex.Lex(); return IntRecTy::get();
  701. case tgtok::Dag: Lex.Lex(); return DagRecTy::get();
  702. case tgtok::Id:
  703. if (Record *R = ParseClassID()) return RecordRecTy::get(R);
  704. TokError("unknown class name");
  705. return nullptr;
  706. case tgtok::Bits: {
  707. if (Lex.Lex() != tgtok::less) { // Eat 'bits'
  708. TokError("expected '<' after bits type");
  709. return nullptr;
  710. }
  711. if (Lex.Lex() != tgtok::IntVal) { // Eat '<'
  712. TokError("expected integer in bits<n> type");
  713. return nullptr;
  714. }
  715. uint64_t Val = Lex.getCurIntVal();
  716. if (Lex.Lex() != tgtok::greater) { // Eat count.
  717. TokError("expected '>' at end of bits<n> type");
  718. return nullptr;
  719. }
  720. Lex.Lex(); // Eat '>'
  721. return BitsRecTy::get(Val);
  722. }
  723. case tgtok::List: {
  724. if (Lex.Lex() != tgtok::less) { // Eat 'bits'
  725. TokError("expected '<' after list type");
  726. return nullptr;
  727. }
  728. Lex.Lex(); // Eat '<'
  729. RecTy *SubType = ParseType();
  730. if (!SubType) return nullptr;
  731. if (!consume(tgtok::greater)) {
  732. TokError("expected '>' at end of list<ty> type");
  733. return nullptr;
  734. }
  735. return ListRecTy::get(SubType);
  736. }
  737. }
  738. }
  739. /// ParseIDValue
  740. Init *TGParser::ParseIDValue(Record *CurRec, StringInit *Name, SMLoc NameLoc,
  741. IDParseMode Mode) {
  742. if (CurRec) {
  743. if (const RecordVal *RV = CurRec->getValue(Name))
  744. return VarInit::get(Name, RV->getType());
  745. }
  746. if ((CurRec && CurRec->isClass()) || CurMultiClass) {
  747. Init *TemplateArgName;
  748. if (CurMultiClass) {
  749. TemplateArgName =
  750. QualifyName(CurMultiClass->Rec, CurMultiClass, Name, "::");
  751. } else
  752. TemplateArgName = QualifyName(*CurRec, CurMultiClass, Name, ":");
  753. Record *TemplateRec = CurMultiClass ? &CurMultiClass->Rec : CurRec;
  754. if (TemplateRec->isTemplateArg(TemplateArgName)) {
  755. RecordVal *RV = TemplateRec->getValue(TemplateArgName);
  756. assert(RV && "Template arg doesn't exist??");
  757. RV->setUsed(true);
  758. return VarInit::get(TemplateArgName, RV->getType());
  759. } else if (Name->getValue() == "NAME") {
  760. return VarInit::get(TemplateArgName, StringRecTy::get());
  761. }
  762. }
  763. if (CurLocalScope)
  764. if (Init *I = CurLocalScope->getVar(Name->getValue()))
  765. return I;
  766. // If this is in a foreach loop, make sure it's not a loop iterator
  767. for (const auto &L : Loops) {
  768. if (L->IterVar) {
  769. VarInit *IterVar = dyn_cast<VarInit>(L->IterVar);
  770. if (IterVar && IterVar->getNameInit() == Name)
  771. return IterVar;
  772. }
  773. }
  774. if (Mode == ParseNameMode)
  775. return Name;
  776. if (Init *I = Records.getGlobal(Name->getValue()))
  777. return I;
  778. // Allow self-references of concrete defs, but delay the lookup so that we
  779. // get the correct type.
  780. if (CurRec && !CurRec->isClass() && !CurMultiClass &&
  781. CurRec->getNameInit() == Name)
  782. return UnOpInit::get(UnOpInit::CAST, Name, CurRec->getType());
  783. Error(NameLoc, "Variable not defined: '" + Name->getValue() + "'");
  784. return nullptr;
  785. }
  786. /// ParseOperation - Parse an operator. This returns null on error.
  787. ///
  788. /// Operation ::= XOperator ['<' Type '>'] '(' Args ')'
  789. ///
  790. Init *TGParser::ParseOperation(Record *CurRec, RecTy *ItemType) {
  791. switch (Lex.getCode()) {
  792. default:
  793. TokError("unknown bang operator");
  794. return nullptr;
  795. case tgtok::XNOT:
  796. case tgtok::XHead:
  797. case tgtok::XTail:
  798. case tgtok::XSize:
  799. case tgtok::XEmpty:
  800. case tgtok::XCast:
  801. case tgtok::XGetDagOp: { // Value ::= !unop '(' Value ')'
  802. UnOpInit::UnaryOp Code;
  803. RecTy *Type = nullptr;
  804. switch (Lex.getCode()) {
  805. default: llvm_unreachable("Unhandled code!");
  806. case tgtok::XCast:
  807. Lex.Lex(); // eat the operation
  808. Code = UnOpInit::CAST;
  809. Type = ParseOperatorType();
  810. if (!Type) {
  811. TokError("did not get type for unary operator");
  812. return nullptr;
  813. }
  814. break;
  815. case tgtok::XNOT:
  816. Lex.Lex(); // eat the operation
  817. Code = UnOpInit::NOT;
  818. Type = IntRecTy::get();
  819. break;
  820. case tgtok::XHead:
  821. Lex.Lex(); // eat the operation
  822. Code = UnOpInit::HEAD;
  823. break;
  824. case tgtok::XTail:
  825. Lex.Lex(); // eat the operation
  826. Code = UnOpInit::TAIL;
  827. break;
  828. case tgtok::XSize:
  829. Lex.Lex();
  830. Code = UnOpInit::SIZE;
  831. Type = IntRecTy::get();
  832. break;
  833. case tgtok::XEmpty:
  834. Lex.Lex(); // eat the operation
  835. Code = UnOpInit::EMPTY;
  836. Type = IntRecTy::get();
  837. break;
  838. case tgtok::XGetDagOp:
  839. Lex.Lex(); // eat the operation
  840. if (Lex.getCode() == tgtok::less) {
  841. // Parse an optional type suffix, so that you can say
  842. // !getdagop<BaseClass>(someDag) as a shorthand for
  843. // !cast<BaseClass>(!getdagop(someDag)).
  844. Type = ParseOperatorType();
  845. if (!Type) {
  846. TokError("did not get type for unary operator");
  847. return nullptr;
  848. }
  849. if (!isa<RecordRecTy>(Type)) {
  850. TokError("type for !getdagop must be a record type");
  851. // but keep parsing, to consume the operand
  852. }
  853. } else {
  854. Type = RecordRecTy::get({});
  855. }
  856. Code = UnOpInit::GETDAGOP;
  857. break;
  858. }
  859. if (!consume(tgtok::l_paren)) {
  860. TokError("expected '(' after unary operator");
  861. return nullptr;
  862. }
  863. Init *LHS = ParseValue(CurRec);
  864. if (!LHS) return nullptr;
  865. if (Code == UnOpInit::EMPTY || Code == UnOpInit::SIZE) {
  866. ListInit *LHSl = dyn_cast<ListInit>(LHS);
  867. StringInit *LHSs = dyn_cast<StringInit>(LHS);
  868. DagInit *LHSd = dyn_cast<DagInit>(LHS);
  869. TypedInit *LHSt = dyn_cast<TypedInit>(LHS);
  870. if (!LHSl && !LHSs && !LHSd && !LHSt) {
  871. TokError("expected string, list, or dag type argument in unary operator");
  872. return nullptr;
  873. }
  874. if (LHSt) {
  875. ListRecTy *LType = dyn_cast<ListRecTy>(LHSt->getType());
  876. StringRecTy *SType = dyn_cast<StringRecTy>(LHSt->getType());
  877. DagRecTy *DType = dyn_cast<DagRecTy>(LHSt->getType());
  878. if (!LType && !SType && !DType) {
  879. TokError("expected string, list, or dag type argument in unary operator");
  880. return nullptr;
  881. }
  882. }
  883. }
  884. if (Code == UnOpInit::HEAD || Code == UnOpInit::TAIL) {
  885. ListInit *LHSl = dyn_cast<ListInit>(LHS);
  886. TypedInit *LHSt = dyn_cast<TypedInit>(LHS);
  887. if (!LHSl && !LHSt) {
  888. TokError("expected list type argument in unary operator");
  889. return nullptr;
  890. }
  891. if (LHSt) {
  892. ListRecTy *LType = dyn_cast<ListRecTy>(LHSt->getType());
  893. if (!LType) {
  894. TokError("expected list type argument in unary operator");
  895. return nullptr;
  896. }
  897. }
  898. if (LHSl && LHSl->empty()) {
  899. TokError("empty list argument in unary operator");
  900. return nullptr;
  901. }
  902. if (LHSl) {
  903. Init *Item = LHSl->getElement(0);
  904. TypedInit *Itemt = dyn_cast<TypedInit>(Item);
  905. if (!Itemt) {
  906. TokError("untyped list element in unary operator");
  907. return nullptr;
  908. }
  909. Type = (Code == UnOpInit::HEAD) ? Itemt->getType()
  910. : ListRecTy::get(Itemt->getType());
  911. } else {
  912. assert(LHSt && "expected list type argument in unary operator");
  913. ListRecTy *LType = dyn_cast<ListRecTy>(LHSt->getType());
  914. Type = (Code == UnOpInit::HEAD) ? LType->getElementType() : LType;
  915. }
  916. }
  917. if (!consume(tgtok::r_paren)) {
  918. TokError("expected ')' in unary operator");
  919. return nullptr;
  920. }
  921. return (UnOpInit::get(Code, LHS, Type))->Fold(CurRec);
  922. }
  923. case tgtok::XIsA: {
  924. // Value ::= !isa '<' Type '>' '(' Value ')'
  925. Lex.Lex(); // eat the operation
  926. RecTy *Type = ParseOperatorType();
  927. if (!Type)
  928. return nullptr;
  929. if (!consume(tgtok::l_paren)) {
  930. TokError("expected '(' after type of !isa");
  931. return nullptr;
  932. }
  933. Init *LHS = ParseValue(CurRec);
  934. if (!LHS)
  935. return nullptr;
  936. if (!consume(tgtok::r_paren)) {
  937. TokError("expected ')' in !isa");
  938. return nullptr;
  939. }
  940. return (IsAOpInit::get(Type, LHS))->Fold();
  941. }
  942. case tgtok::XConcat:
  943. case tgtok::XADD:
  944. case tgtok::XSUB:
  945. case tgtok::XMUL:
  946. case tgtok::XAND:
  947. case tgtok::XOR:
  948. case tgtok::XXOR:
  949. case tgtok::XSRA:
  950. case tgtok::XSRL:
  951. case tgtok::XSHL:
  952. case tgtok::XEq:
  953. case tgtok::XNe:
  954. case tgtok::XLe:
  955. case tgtok::XLt:
  956. case tgtok::XGe:
  957. case tgtok::XGt:
  958. case tgtok::XListConcat:
  959. case tgtok::XListSplat:
  960. case tgtok::XStrConcat:
  961. case tgtok::XInterleave:
  962. case tgtok::XSetDagOp: { // Value ::= !binop '(' Value ',' Value ')'
  963. tgtok::TokKind OpTok = Lex.getCode();
  964. SMLoc OpLoc = Lex.getLoc();
  965. Lex.Lex(); // eat the operation
  966. BinOpInit::BinaryOp Code;
  967. switch (OpTok) {
  968. default: llvm_unreachable("Unhandled code!");
  969. case tgtok::XConcat: Code = BinOpInit::CONCAT; break;
  970. case tgtok::XADD: Code = BinOpInit::ADD; break;
  971. case tgtok::XSUB: Code = BinOpInit::SUB; break;
  972. case tgtok::XMUL: Code = BinOpInit::MUL; break;
  973. case tgtok::XAND: Code = BinOpInit::AND; break;
  974. case tgtok::XOR: Code = BinOpInit::OR; break;
  975. case tgtok::XXOR: Code = BinOpInit::XOR; break;
  976. case tgtok::XSRA: Code = BinOpInit::SRA; break;
  977. case tgtok::XSRL: Code = BinOpInit::SRL; break;
  978. case tgtok::XSHL: Code = BinOpInit::SHL; break;
  979. case tgtok::XEq: Code = BinOpInit::EQ; break;
  980. case tgtok::XNe: Code = BinOpInit::NE; break;
  981. case tgtok::XLe: Code = BinOpInit::LE; break;
  982. case tgtok::XLt: Code = BinOpInit::LT; break;
  983. case tgtok::XGe: Code = BinOpInit::GE; break;
  984. case tgtok::XGt: Code = BinOpInit::GT; break;
  985. case tgtok::XListConcat: Code = BinOpInit::LISTCONCAT; break;
  986. case tgtok::XListSplat: Code = BinOpInit::LISTSPLAT; break;
  987. case tgtok::XStrConcat: Code = BinOpInit::STRCONCAT; break;
  988. case tgtok::XInterleave: Code = BinOpInit::INTERLEAVE; break;
  989. case tgtok::XSetDagOp: Code = BinOpInit::SETDAGOP; break;
  990. }
  991. RecTy *Type = nullptr;
  992. RecTy *ArgType = nullptr;
  993. switch (OpTok) {
  994. default:
  995. llvm_unreachable("Unhandled code!");
  996. case tgtok::XConcat:
  997. case tgtok::XSetDagOp:
  998. Type = DagRecTy::get();
  999. ArgType = DagRecTy::get();
  1000. break;
  1001. case tgtok::XAND:
  1002. case tgtok::XOR:
  1003. case tgtok::XXOR:
  1004. case tgtok::XSRA:
  1005. case tgtok::XSRL:
  1006. case tgtok::XSHL:
  1007. case tgtok::XADD:
  1008. case tgtok::XSUB:
  1009. case tgtok::XMUL:
  1010. Type = IntRecTy::get();
  1011. ArgType = IntRecTy::get();
  1012. break;
  1013. case tgtok::XEq:
  1014. case tgtok::XNe:
  1015. case tgtok::XLe:
  1016. case tgtok::XLt:
  1017. case tgtok::XGe:
  1018. case tgtok::XGt:
  1019. Type = BitRecTy::get();
  1020. // ArgType for the comparison operators is not yet known.
  1021. break;
  1022. case tgtok::XListConcat:
  1023. // We don't know the list type until we parse the first argument
  1024. ArgType = ItemType;
  1025. break;
  1026. case tgtok::XListSplat:
  1027. // Can't do any typechecking until we parse the first argument.
  1028. break;
  1029. case tgtok::XStrConcat:
  1030. Type = StringRecTy::get();
  1031. ArgType = StringRecTy::get();
  1032. break;
  1033. case tgtok::XInterleave:
  1034. Type = StringRecTy::get();
  1035. // The first argument type is not yet known.
  1036. }
  1037. if (Type && ItemType && !Type->typeIsConvertibleTo(ItemType)) {
  1038. Error(OpLoc, Twine("expected value of type '") +
  1039. ItemType->getAsString() + "', got '" +
  1040. Type->getAsString() + "'");
  1041. return nullptr;
  1042. }
  1043. if (!consume(tgtok::l_paren)) {
  1044. TokError("expected '(' after binary operator");
  1045. return nullptr;
  1046. }
  1047. SmallVector<Init*, 2> InitList;
  1048. // Note that this loop consumes an arbitrary number of arguments.
  1049. // The actual count is checked later.
  1050. for (;;) {
  1051. SMLoc InitLoc = Lex.getLoc();
  1052. InitList.push_back(ParseValue(CurRec, ArgType));
  1053. if (!InitList.back()) return nullptr;
  1054. TypedInit *InitListBack = dyn_cast<TypedInit>(InitList.back());
  1055. if (!InitListBack) {
  1056. Error(OpLoc, Twine("expected value to be a typed value, got '" +
  1057. InitList.back()->getAsString() + "'"));
  1058. return nullptr;
  1059. }
  1060. RecTy *ListType = InitListBack->getType();
  1061. if (!ArgType) {
  1062. // Argument type must be determined from the argument itself.
  1063. ArgType = ListType;
  1064. switch (Code) {
  1065. case BinOpInit::LISTCONCAT:
  1066. if (!isa<ListRecTy>(ArgType)) {
  1067. Error(InitLoc, Twine("expected a list, got value of type '") +
  1068. ArgType->getAsString() + "'");
  1069. return nullptr;
  1070. }
  1071. break;
  1072. case BinOpInit::LISTSPLAT:
  1073. if (ItemType && InitList.size() == 1) {
  1074. if (!isa<ListRecTy>(ItemType)) {
  1075. Error(OpLoc,
  1076. Twine("expected output type to be a list, got type '") +
  1077. ItemType->getAsString() + "'");
  1078. return nullptr;
  1079. }
  1080. if (!ArgType->getListTy()->typeIsConvertibleTo(ItemType)) {
  1081. Error(OpLoc, Twine("expected first arg type to be '") +
  1082. ArgType->getAsString() +
  1083. "', got value of type '" +
  1084. cast<ListRecTy>(ItemType)
  1085. ->getElementType()
  1086. ->getAsString() +
  1087. "'");
  1088. return nullptr;
  1089. }
  1090. }
  1091. if (InitList.size() == 2 && !isa<IntRecTy>(ArgType)) {
  1092. Error(InitLoc, Twine("expected second parameter to be an int, got "
  1093. "value of type '") +
  1094. ArgType->getAsString() + "'");
  1095. return nullptr;
  1096. }
  1097. ArgType = nullptr; // Broken invariant: types not identical.
  1098. break;
  1099. case BinOpInit::EQ:
  1100. case BinOpInit::NE:
  1101. if (!ArgType->typeIsConvertibleTo(IntRecTy::get()) &&
  1102. !ArgType->typeIsConvertibleTo(StringRecTy::get()) &&
  1103. !ArgType->typeIsConvertibleTo(RecordRecTy::get({}))) {
  1104. Error(InitLoc, Twine("expected bit, bits, int, string, or record; "
  1105. "got value of type '") + ArgType->getAsString() +
  1106. "'");
  1107. return nullptr;
  1108. }
  1109. break;
  1110. case BinOpInit::LE:
  1111. case BinOpInit::LT:
  1112. case BinOpInit::GE:
  1113. case BinOpInit::GT:
  1114. if (!ArgType->typeIsConvertibleTo(IntRecTy::get()) &&
  1115. !ArgType->typeIsConvertibleTo(StringRecTy::get())) {
  1116. Error(InitLoc, Twine("expected bit, bits, int, or string; "
  1117. "got value of type '") + ArgType->getAsString() +
  1118. "'");
  1119. return nullptr;
  1120. }
  1121. break;
  1122. case BinOpInit::INTERLEAVE:
  1123. switch (InitList.size()) {
  1124. case 1: // First argument must be a list of strings or integers.
  1125. if (ArgType != StringRecTy::get()->getListTy() &&
  1126. !ArgType->typeIsConvertibleTo(IntRecTy::get()->getListTy())) {
  1127. Error(InitLoc, Twine("expected list of string, int, bits, or bit; "
  1128. "got value of type '") +
  1129. ArgType->getAsString() + "'");
  1130. return nullptr;
  1131. }
  1132. break;
  1133. case 2: // Second argument must be a string.
  1134. if (!isa<StringRecTy>(ArgType)) {
  1135. Error(InitLoc, Twine("expected second argument to be a string, "
  1136. "got value of type '") +
  1137. ArgType->getAsString() + "'");
  1138. return nullptr;
  1139. }
  1140. break;
  1141. default: ;
  1142. }
  1143. ArgType = nullptr; // Broken invariant: types not identical.
  1144. break;
  1145. default: llvm_unreachable("other ops have fixed argument types");
  1146. }
  1147. } else {
  1148. // Desired argument type is a known and in ArgType.
  1149. RecTy *Resolved = resolveTypes(ArgType, ListType);
  1150. if (!Resolved) {
  1151. Error(InitLoc, Twine("expected value of type '") +
  1152. ArgType->getAsString() + "', got '" +
  1153. ListType->getAsString() + "'");
  1154. return nullptr;
  1155. }
  1156. if (Code != BinOpInit::ADD && Code != BinOpInit::SUB &&
  1157. Code != BinOpInit::AND && Code != BinOpInit::OR &&
  1158. Code != BinOpInit::XOR && Code != BinOpInit::SRA &&
  1159. Code != BinOpInit::SRL && Code != BinOpInit::SHL &&
  1160. Code != BinOpInit::MUL)
  1161. ArgType = Resolved;
  1162. }
  1163. // Deal with BinOps whose arguments have different types, by
  1164. // rewriting ArgType in between them.
  1165. switch (Code) {
  1166. case BinOpInit::SETDAGOP:
  1167. // After parsing the first dag argument, switch to expecting
  1168. // a record, with no restriction on its superclasses.
  1169. ArgType = RecordRecTy::get({});
  1170. break;
  1171. default:
  1172. break;
  1173. }
  1174. if (!consume(tgtok::comma))
  1175. break;
  1176. }
  1177. if (!consume(tgtok::r_paren)) {
  1178. TokError("expected ')' in operator");
  1179. return nullptr;
  1180. }
  1181. // listconcat returns a list with type of the argument.
  1182. if (Code == BinOpInit::LISTCONCAT)
  1183. Type = ArgType;
  1184. // listsplat returns a list of type of the *first* argument.
  1185. if (Code == BinOpInit::LISTSPLAT)
  1186. Type = cast<TypedInit>(InitList.front())->getType()->getListTy();
  1187. // We allow multiple operands to associative operators like !strconcat as
  1188. // shorthand for nesting them.
  1189. if (Code == BinOpInit::STRCONCAT || Code == BinOpInit::LISTCONCAT ||
  1190. Code == BinOpInit::CONCAT || Code == BinOpInit::ADD ||
  1191. Code == BinOpInit::AND || Code == BinOpInit::OR ||
  1192. Code == BinOpInit::XOR || Code == BinOpInit::MUL) {
  1193. while (InitList.size() > 2) {
  1194. Init *RHS = InitList.pop_back_val();
  1195. RHS = (BinOpInit::get(Code, InitList.back(), RHS, Type))->Fold(CurRec);
  1196. InitList.back() = RHS;
  1197. }
  1198. }
  1199. if (InitList.size() == 2)
  1200. return (BinOpInit::get(Code, InitList[0], InitList[1], Type))
  1201. ->Fold(CurRec);
  1202. Error(OpLoc, "expected two operands to operator");
  1203. return nullptr;
  1204. }
  1205. case tgtok::XForEach:
  1206. case tgtok::XFilter: {
  1207. return ParseOperationForEachFilter(CurRec, ItemType);
  1208. }
  1209. case tgtok::XDag:
  1210. case tgtok::XIf:
  1211. case tgtok::XSubst: { // Value ::= !ternop '(' Value ',' Value ',' Value ')'
  1212. TernOpInit::TernaryOp Code;
  1213. RecTy *Type = nullptr;
  1214. tgtok::TokKind LexCode = Lex.getCode();
  1215. Lex.Lex(); // eat the operation
  1216. switch (LexCode) {
  1217. default: llvm_unreachable("Unhandled code!");
  1218. case tgtok::XDag:
  1219. Code = TernOpInit::DAG;
  1220. Type = DagRecTy::get();
  1221. ItemType = nullptr;
  1222. break;
  1223. case tgtok::XIf:
  1224. Code = TernOpInit::IF;
  1225. break;
  1226. case tgtok::XSubst:
  1227. Code = TernOpInit::SUBST;
  1228. break;
  1229. }
  1230. if (!consume(tgtok::l_paren)) {
  1231. TokError("expected '(' after ternary operator");
  1232. return nullptr;
  1233. }
  1234. Init *LHS = ParseValue(CurRec);
  1235. if (!LHS) return nullptr;
  1236. if (!consume(tgtok::comma)) {
  1237. TokError("expected ',' in ternary operator");
  1238. return nullptr;
  1239. }
  1240. SMLoc MHSLoc = Lex.getLoc();
  1241. Init *MHS = ParseValue(CurRec, ItemType);
  1242. if (!MHS)
  1243. return nullptr;
  1244. if (!consume(tgtok::comma)) {
  1245. TokError("expected ',' in ternary operator");
  1246. return nullptr;
  1247. }
  1248. SMLoc RHSLoc = Lex.getLoc();
  1249. Init *RHS = ParseValue(CurRec, ItemType);
  1250. if (!RHS)
  1251. return nullptr;
  1252. if (!consume(tgtok::r_paren)) {
  1253. TokError("expected ')' in binary operator");
  1254. return nullptr;
  1255. }
  1256. switch (LexCode) {
  1257. default: llvm_unreachable("Unhandled code!");
  1258. case tgtok::XDag: {
  1259. TypedInit *MHSt = dyn_cast<TypedInit>(MHS);
  1260. if (!MHSt && !isa<UnsetInit>(MHS)) {
  1261. Error(MHSLoc, "could not determine type of the child list in !dag");
  1262. return nullptr;
  1263. }
  1264. if (MHSt && !isa<ListRecTy>(MHSt->getType())) {
  1265. Error(MHSLoc, Twine("expected list of children, got type '") +
  1266. MHSt->getType()->getAsString() + "'");
  1267. return nullptr;
  1268. }
  1269. TypedInit *RHSt = dyn_cast<TypedInit>(RHS);
  1270. if (!RHSt && !isa<UnsetInit>(RHS)) {
  1271. Error(RHSLoc, "could not determine type of the name list in !dag");
  1272. return nullptr;
  1273. }
  1274. if (RHSt && StringRecTy::get()->getListTy() != RHSt->getType()) {
  1275. Error(RHSLoc, Twine("expected list<string>, got type '") +
  1276. RHSt->getType()->getAsString() + "'");
  1277. return nullptr;
  1278. }
  1279. if (!MHSt && !RHSt) {
  1280. Error(MHSLoc,
  1281. "cannot have both unset children and unset names in !dag");
  1282. return nullptr;
  1283. }
  1284. break;
  1285. }
  1286. case tgtok::XIf: {
  1287. RecTy *MHSTy = nullptr;
  1288. RecTy *RHSTy = nullptr;
  1289. if (TypedInit *MHSt = dyn_cast<TypedInit>(MHS))
  1290. MHSTy = MHSt->getType();
  1291. if (BitsInit *MHSbits = dyn_cast<BitsInit>(MHS))
  1292. MHSTy = BitsRecTy::get(MHSbits->getNumBits());
  1293. if (isa<BitInit>(MHS))
  1294. MHSTy = BitRecTy::get();
  1295. if (TypedInit *RHSt = dyn_cast<TypedInit>(RHS))
  1296. RHSTy = RHSt->getType();
  1297. if (BitsInit *RHSbits = dyn_cast<BitsInit>(RHS))
  1298. RHSTy = BitsRecTy::get(RHSbits->getNumBits());
  1299. if (isa<BitInit>(RHS))
  1300. RHSTy = BitRecTy::get();
  1301. // For UnsetInit, it's typed from the other hand.
  1302. if (isa<UnsetInit>(MHS))
  1303. MHSTy = RHSTy;
  1304. if (isa<UnsetInit>(RHS))
  1305. RHSTy = MHSTy;
  1306. if (!MHSTy || !RHSTy) {
  1307. TokError("could not get type for !if");
  1308. return nullptr;
  1309. }
  1310. Type = resolveTypes(MHSTy, RHSTy);
  1311. if (!Type) {
  1312. TokError(Twine("inconsistent types '") + MHSTy->getAsString() +
  1313. "' and '" + RHSTy->getAsString() + "' for !if");
  1314. return nullptr;
  1315. }
  1316. break;
  1317. }
  1318. case tgtok::XSubst: {
  1319. TypedInit *RHSt = dyn_cast<TypedInit>(RHS);
  1320. if (!RHSt) {
  1321. TokError("could not get type for !subst");
  1322. return nullptr;
  1323. }
  1324. Type = RHSt->getType();
  1325. break;
  1326. }
  1327. }
  1328. return (TernOpInit::get(Code, LHS, MHS, RHS, Type))->Fold(CurRec);
  1329. }
  1330. case tgtok::XSubstr:
  1331. return ParseOperationSubstr(CurRec, ItemType);
  1332. case tgtok::XFind:
  1333. return ParseOperationFind(CurRec, ItemType);
  1334. case tgtok::XCond:
  1335. return ParseOperationCond(CurRec, ItemType);
  1336. case tgtok::XFoldl: {
  1337. // Value ::= !foldl '(' Value ',' Value ',' Id ',' Id ',' Expr ')'
  1338. Lex.Lex(); // eat the operation
  1339. if (!consume(tgtok::l_paren)) {
  1340. TokError("expected '(' after !foldl");
  1341. return nullptr;
  1342. }
  1343. Init *StartUntyped = ParseValue(CurRec);
  1344. if (!StartUntyped)
  1345. return nullptr;
  1346. TypedInit *Start = dyn_cast<TypedInit>(StartUntyped);
  1347. if (!Start) {
  1348. TokError(Twine("could not get type of !foldl start: '") +
  1349. StartUntyped->getAsString() + "'");
  1350. return nullptr;
  1351. }
  1352. if (!consume(tgtok::comma)) {
  1353. TokError("expected ',' in !foldl");
  1354. return nullptr;
  1355. }
  1356. Init *ListUntyped = ParseValue(CurRec);
  1357. if (!ListUntyped)
  1358. return nullptr;
  1359. TypedInit *List = dyn_cast<TypedInit>(ListUntyped);
  1360. if (!List) {
  1361. TokError(Twine("could not get type of !foldl list: '") +
  1362. ListUntyped->getAsString() + "'");
  1363. return nullptr;
  1364. }
  1365. ListRecTy *ListType = dyn_cast<ListRecTy>(List->getType());
  1366. if (!ListType) {
  1367. TokError(Twine("!foldl list must be a list, but is of type '") +
  1368. List->getType()->getAsString());
  1369. return nullptr;
  1370. }
  1371. if (Lex.getCode() != tgtok::comma) {
  1372. TokError("expected ',' in !foldl");
  1373. return nullptr;
  1374. }
  1375. if (Lex.Lex() != tgtok::Id) { // eat the ','
  1376. TokError("third argument of !foldl must be an identifier");
  1377. return nullptr;
  1378. }
  1379. Init *A = StringInit::get(Lex.getCurStrVal());
  1380. if (CurRec && CurRec->getValue(A)) {
  1381. TokError((Twine("left !foldl variable '") + A->getAsString() +
  1382. "' already defined")
  1383. .str());
  1384. return nullptr;
  1385. }
  1386. if (Lex.Lex() != tgtok::comma) { // eat the id
  1387. TokError("expected ',' in !foldl");
  1388. return nullptr;
  1389. }
  1390. if (Lex.Lex() != tgtok::Id) { // eat the ','
  1391. TokError("fourth argument of !foldl must be an identifier");
  1392. return nullptr;
  1393. }
  1394. Init *B = StringInit::get(Lex.getCurStrVal());
  1395. if (CurRec && CurRec->getValue(B)) {
  1396. TokError((Twine("right !foldl variable '") + B->getAsString() +
  1397. "' already defined")
  1398. .str());
  1399. return nullptr;
  1400. }
  1401. if (Lex.Lex() != tgtok::comma) { // eat the id
  1402. TokError("expected ',' in !foldl");
  1403. return nullptr;
  1404. }
  1405. Lex.Lex(); // eat the ','
  1406. // We need to create a temporary record to provide a scope for the
  1407. // two variables.
  1408. std::unique_ptr<Record> ParseRecTmp;
  1409. Record *ParseRec = CurRec;
  1410. if (!ParseRec) {
  1411. ParseRecTmp = std::make_unique<Record>(".parse", ArrayRef<SMLoc>{}, Records);
  1412. ParseRec = ParseRecTmp.get();
  1413. }
  1414. ParseRec->addValue(RecordVal(A, Start->getType(), RecordVal::FK_Normal));
  1415. ParseRec->addValue(RecordVal(B, ListType->getElementType(),
  1416. RecordVal::FK_Normal));
  1417. Init *ExprUntyped = ParseValue(ParseRec);
  1418. ParseRec->removeValue(A);
  1419. ParseRec->removeValue(B);
  1420. if (!ExprUntyped)
  1421. return nullptr;
  1422. TypedInit *Expr = dyn_cast<TypedInit>(ExprUntyped);
  1423. if (!Expr) {
  1424. TokError("could not get type of !foldl expression");
  1425. return nullptr;
  1426. }
  1427. if (Expr->getType() != Start->getType()) {
  1428. TokError(Twine("!foldl expression must be of same type as start (") +
  1429. Start->getType()->getAsString() + "), but is of type " +
  1430. Expr->getType()->getAsString());
  1431. return nullptr;
  1432. }
  1433. if (!consume(tgtok::r_paren)) {
  1434. TokError("expected ')' in fold operator");
  1435. return nullptr;
  1436. }
  1437. return FoldOpInit::get(Start, List, A, B, Expr, Start->getType())
  1438. ->Fold(CurRec);
  1439. }
  1440. }
  1441. }
  1442. /// ParseOperatorType - Parse a type for an operator. This returns
  1443. /// null on error.
  1444. ///
  1445. /// OperatorType ::= '<' Type '>'
  1446. ///
  1447. RecTy *TGParser::ParseOperatorType() {
  1448. RecTy *Type = nullptr;
  1449. if (!consume(tgtok::less)) {
  1450. TokError("expected type name for operator");
  1451. return nullptr;
  1452. }
  1453. if (Lex.getCode() == tgtok::Code)
  1454. TokError("the 'code' type is not allowed in bang operators; use 'string'");
  1455. Type = ParseType();
  1456. if (!Type) {
  1457. TokError("expected type name for operator");
  1458. return nullptr;
  1459. }
  1460. if (!consume(tgtok::greater)) {
  1461. TokError("expected type name for operator");
  1462. return nullptr;
  1463. }
  1464. return Type;
  1465. }
  1466. /// Parse the !substr operation. Return null on error.
  1467. ///
  1468. /// Substr ::= !substr(string, start-int [, length-int]) => string
  1469. Init *TGParser::ParseOperationSubstr(Record *CurRec, RecTy *ItemType) {
  1470. TernOpInit::TernaryOp Code = TernOpInit::SUBSTR;
  1471. RecTy *Type = StringRecTy::get();
  1472. Lex.Lex(); // eat the operation
  1473. if (!consume(tgtok::l_paren)) {
  1474. TokError("expected '(' after !substr operator");
  1475. return nullptr;
  1476. }
  1477. Init *LHS = ParseValue(CurRec);
  1478. if (!LHS)
  1479. return nullptr;
  1480. if (!consume(tgtok::comma)) {
  1481. TokError("expected ',' in !substr operator");
  1482. return nullptr;
  1483. }
  1484. SMLoc MHSLoc = Lex.getLoc();
  1485. Init *MHS = ParseValue(CurRec);
  1486. if (!MHS)
  1487. return nullptr;
  1488. SMLoc RHSLoc = Lex.getLoc();
  1489. Init *RHS;
  1490. if (consume(tgtok::comma)) {
  1491. RHSLoc = Lex.getLoc();
  1492. RHS = ParseValue(CurRec);
  1493. if (!RHS)
  1494. return nullptr;
  1495. } else {
  1496. RHS = IntInit::get(std::numeric_limits<int64_t>::max());
  1497. }
  1498. if (!consume(tgtok::r_paren)) {
  1499. TokError("expected ')' in !substr operator");
  1500. return nullptr;
  1501. }
  1502. if (ItemType && !Type->typeIsConvertibleTo(ItemType)) {
  1503. Error(RHSLoc, Twine("expected value of type '") +
  1504. ItemType->getAsString() + "', got '" +
  1505. Type->getAsString() + "'");
  1506. }
  1507. TypedInit *LHSt = dyn_cast<TypedInit>(LHS);
  1508. if (!LHSt && !isa<UnsetInit>(LHS)) {
  1509. TokError("could not determine type of the string in !substr");
  1510. return nullptr;
  1511. }
  1512. if (LHSt && !isa<StringRecTy>(LHSt->getType())) {
  1513. TokError(Twine("expected string, got type '") +
  1514. LHSt->getType()->getAsString() + "'");
  1515. return nullptr;
  1516. }
  1517. TypedInit *MHSt = dyn_cast<TypedInit>(MHS);
  1518. if (!MHSt && !isa<UnsetInit>(MHS)) {
  1519. TokError("could not determine type of the start position in !substr");
  1520. return nullptr;
  1521. }
  1522. if (MHSt && !isa<IntRecTy>(MHSt->getType())) {
  1523. Error(MHSLoc, Twine("expected int, got type '") +
  1524. MHSt->getType()->getAsString() + "'");
  1525. return nullptr;
  1526. }
  1527. if (RHS) {
  1528. TypedInit *RHSt = dyn_cast<TypedInit>(RHS);
  1529. if (!RHSt && !isa<UnsetInit>(RHS)) {
  1530. TokError("could not determine type of the length in !substr");
  1531. return nullptr;
  1532. }
  1533. if (RHSt && !isa<IntRecTy>(RHSt->getType())) {
  1534. TokError(Twine("expected int, got type '") +
  1535. RHSt->getType()->getAsString() + "'");
  1536. return nullptr;
  1537. }
  1538. }
  1539. return (TernOpInit::get(Code, LHS, MHS, RHS, Type))->Fold(CurRec);
  1540. }
  1541. /// Parse the !find operation. Return null on error.
  1542. ///
  1543. /// Substr ::= !find(string, string [, start-int]) => int
  1544. Init *TGParser::ParseOperationFind(Record *CurRec, RecTy *ItemType) {
  1545. TernOpInit::TernaryOp Code = TernOpInit::FIND;
  1546. RecTy *Type = IntRecTy::get();
  1547. Lex.Lex(); // eat the operation
  1548. if (!consume(tgtok::l_paren)) {
  1549. TokError("expected '(' after !find operator");
  1550. return nullptr;
  1551. }
  1552. Init *LHS = ParseValue(CurRec);
  1553. if (!LHS)
  1554. return nullptr;
  1555. if (!consume(tgtok::comma)) {
  1556. TokError("expected ',' in !find operator");
  1557. return nullptr;
  1558. }
  1559. SMLoc MHSLoc = Lex.getLoc();
  1560. Init *MHS = ParseValue(CurRec);
  1561. if (!MHS)
  1562. return nullptr;
  1563. SMLoc RHSLoc = Lex.getLoc();
  1564. Init *RHS;
  1565. if (consume(tgtok::comma)) {
  1566. RHSLoc = Lex.getLoc();
  1567. RHS = ParseValue(CurRec);
  1568. if (!RHS)
  1569. return nullptr;
  1570. } else {
  1571. RHS = IntInit::get(0);
  1572. }
  1573. if (!consume(tgtok::r_paren)) {
  1574. TokError("expected ')' in !find operator");
  1575. return nullptr;
  1576. }
  1577. if (ItemType && !Type->typeIsConvertibleTo(ItemType)) {
  1578. Error(RHSLoc, Twine("expected value of type '") +
  1579. ItemType->getAsString() + "', got '" +
  1580. Type->getAsString() + "'");
  1581. }
  1582. TypedInit *LHSt = dyn_cast<TypedInit>(LHS);
  1583. if (!LHSt && !isa<UnsetInit>(LHS)) {
  1584. TokError("could not determine type of the source string in !find");
  1585. return nullptr;
  1586. }
  1587. if (LHSt && !isa<StringRecTy>(LHSt->getType())) {
  1588. TokError(Twine("expected string, got type '") +
  1589. LHSt->getType()->getAsString() + "'");
  1590. return nullptr;
  1591. }
  1592. TypedInit *MHSt = dyn_cast<TypedInit>(MHS);
  1593. if (!MHSt && !isa<UnsetInit>(MHS)) {
  1594. TokError("could not determine type of the target string in !find");
  1595. return nullptr;
  1596. }
  1597. if (MHSt && !isa<StringRecTy>(MHSt->getType())) {
  1598. Error(MHSLoc, Twine("expected string, got type '") +
  1599. MHSt->getType()->getAsString() + "'");
  1600. return nullptr;
  1601. }
  1602. if (RHS) {
  1603. TypedInit *RHSt = dyn_cast<TypedInit>(RHS);
  1604. if (!RHSt && !isa<UnsetInit>(RHS)) {
  1605. TokError("could not determine type of the start position in !find");
  1606. return nullptr;
  1607. }
  1608. if (RHSt && !isa<IntRecTy>(RHSt->getType())) {
  1609. TokError(Twine("expected int, got type '") +
  1610. RHSt->getType()->getAsString() + "'");
  1611. return nullptr;
  1612. }
  1613. }
  1614. return (TernOpInit::get(Code, LHS, MHS, RHS, Type))->Fold(CurRec);
  1615. }
  1616. /// Parse the !foreach and !filter operations. Return null on error.
  1617. ///
  1618. /// ForEach ::= !foreach(ID, list-or-dag, expr) => list<expr type>
  1619. /// Filter ::= !foreach(ID, list, predicate) ==> list<list type>
  1620. Init *TGParser::ParseOperationForEachFilter(Record *CurRec, RecTy *ItemType) {
  1621. SMLoc OpLoc = Lex.getLoc();
  1622. tgtok::TokKind Operation = Lex.getCode();
  1623. Lex.Lex(); // eat the operation
  1624. if (Lex.getCode() != tgtok::l_paren) {
  1625. TokError("expected '(' after !foreach/!filter");
  1626. return nullptr;
  1627. }
  1628. if (Lex.Lex() != tgtok::Id) { // eat the '('
  1629. TokError("first argument of !foreach/!filter must be an identifier");
  1630. return nullptr;
  1631. }
  1632. Init *LHS = StringInit::get(Lex.getCurStrVal());
  1633. Lex.Lex(); // eat the ID.
  1634. if (CurRec && CurRec->getValue(LHS)) {
  1635. TokError((Twine("iteration variable '") + LHS->getAsString() +
  1636. "' is already defined")
  1637. .str());
  1638. return nullptr;
  1639. }
  1640. if (!consume(tgtok::comma)) {
  1641. TokError("expected ',' in !foreach/!filter");
  1642. return nullptr;
  1643. }
  1644. Init *MHS = ParseValue(CurRec);
  1645. if (!MHS)
  1646. return nullptr;
  1647. if (!consume(tgtok::comma)) {
  1648. TokError("expected ',' in !foreach/!filter");
  1649. return nullptr;
  1650. }
  1651. TypedInit *MHSt = dyn_cast<TypedInit>(MHS);
  1652. if (!MHSt) {
  1653. TokError("could not get type of !foreach/!filter list or dag");
  1654. return nullptr;
  1655. }
  1656. RecTy *InEltType = nullptr;
  1657. RecTy *ExprEltType = nullptr;
  1658. bool IsDAG = false;
  1659. if (ListRecTy *InListTy = dyn_cast<ListRecTy>(MHSt->getType())) {
  1660. InEltType = InListTy->getElementType();
  1661. if (ItemType) {
  1662. if (ListRecTy *OutListTy = dyn_cast<ListRecTy>(ItemType)) {
  1663. ExprEltType = (Operation == tgtok::XForEach)
  1664. ? OutListTy->getElementType()
  1665. : IntRecTy::get();
  1666. } else {
  1667. Error(OpLoc,
  1668. "expected value of type '" +
  1669. Twine(ItemType->getAsString()) +
  1670. "', but got list type");
  1671. return nullptr;
  1672. }
  1673. }
  1674. } else if (DagRecTy *InDagTy = dyn_cast<DagRecTy>(MHSt->getType())) {
  1675. if (Operation == tgtok::XFilter) {
  1676. TokError("!filter must have a list argument");
  1677. return nullptr;
  1678. }
  1679. InEltType = InDagTy;
  1680. if (ItemType && !isa<DagRecTy>(ItemType)) {
  1681. Error(OpLoc,
  1682. "expected value of type '" + Twine(ItemType->getAsString()) +
  1683. "', but got dag type");
  1684. return nullptr;
  1685. }
  1686. IsDAG = true;
  1687. } else {
  1688. if (Operation == tgtok::XForEach)
  1689. TokError("!foreach must have a list or dag argument");
  1690. else
  1691. TokError("!filter must have a list argument");
  1692. return nullptr;
  1693. }
  1694. // We need to create a temporary record to provide a scope for the
  1695. // iteration variable.
  1696. std::unique_ptr<Record> ParseRecTmp;
  1697. Record *ParseRec = CurRec;
  1698. if (!ParseRec) {
  1699. ParseRecTmp =
  1700. std::make_unique<Record>(".parse", ArrayRef<SMLoc>{}, Records);
  1701. ParseRec = ParseRecTmp.get();
  1702. }
  1703. ParseRec->addValue(RecordVal(LHS, InEltType, RecordVal::FK_Normal));
  1704. Init *RHS = ParseValue(ParseRec, ExprEltType);
  1705. ParseRec->removeValue(LHS);
  1706. if (!RHS)
  1707. return nullptr;
  1708. if (!consume(tgtok::r_paren)) {
  1709. TokError("expected ')' in !foreach/!filter");
  1710. return nullptr;
  1711. }
  1712. RecTy *OutType = InEltType;
  1713. if (Operation == tgtok::XForEach && !IsDAG) {
  1714. TypedInit *RHSt = dyn_cast<TypedInit>(RHS);
  1715. if (!RHSt) {
  1716. TokError("could not get type of !foreach result expression");
  1717. return nullptr;
  1718. }
  1719. OutType = RHSt->getType()->getListTy();
  1720. } else if (Operation == tgtok::XFilter) {
  1721. OutType = InEltType->getListTy();
  1722. }
  1723. return (TernOpInit::get((Operation == tgtok::XForEach) ? TernOpInit::FOREACH
  1724. : TernOpInit::FILTER,
  1725. LHS, MHS, RHS, OutType))
  1726. ->Fold(CurRec);
  1727. }
  1728. Init *TGParser::ParseOperationCond(Record *CurRec, RecTy *ItemType) {
  1729. Lex.Lex(); // eat the operation 'cond'
  1730. if (!consume(tgtok::l_paren)) {
  1731. TokError("expected '(' after !cond operator");
  1732. return nullptr;
  1733. }
  1734. // Parse through '[Case: Val,]+'
  1735. SmallVector<Init *, 4> Case;
  1736. SmallVector<Init *, 4> Val;
  1737. while (true) {
  1738. if (consume(tgtok::r_paren))
  1739. break;
  1740. Init *V = ParseValue(CurRec);
  1741. if (!V)
  1742. return nullptr;
  1743. Case.push_back(V);
  1744. if (!consume(tgtok::colon)) {
  1745. TokError("expected ':' following a condition in !cond operator");
  1746. return nullptr;
  1747. }
  1748. V = ParseValue(CurRec, ItemType);
  1749. if (!V)
  1750. return nullptr;
  1751. Val.push_back(V);
  1752. if (consume(tgtok::r_paren))
  1753. break;
  1754. if (!consume(tgtok::comma)) {
  1755. TokError("expected ',' or ')' following a value in !cond operator");
  1756. return nullptr;
  1757. }
  1758. }
  1759. if (Case.size() < 1) {
  1760. TokError("there should be at least 1 'condition : value' in the !cond operator");
  1761. return nullptr;
  1762. }
  1763. // resolve type
  1764. RecTy *Type = nullptr;
  1765. for (Init *V : Val) {
  1766. RecTy *VTy = nullptr;
  1767. if (TypedInit *Vt = dyn_cast<TypedInit>(V))
  1768. VTy = Vt->getType();
  1769. if (BitsInit *Vbits = dyn_cast<BitsInit>(V))
  1770. VTy = BitsRecTy::get(Vbits->getNumBits());
  1771. if (isa<BitInit>(V))
  1772. VTy = BitRecTy::get();
  1773. if (Type == nullptr) {
  1774. if (!isa<UnsetInit>(V))
  1775. Type = VTy;
  1776. } else {
  1777. if (!isa<UnsetInit>(V)) {
  1778. RecTy *RType = resolveTypes(Type, VTy);
  1779. if (!RType) {
  1780. TokError(Twine("inconsistent types '") + Type->getAsString() +
  1781. "' and '" + VTy->getAsString() + "' for !cond");
  1782. return nullptr;
  1783. }
  1784. Type = RType;
  1785. }
  1786. }
  1787. }
  1788. if (!Type) {
  1789. TokError("could not determine type for !cond from its arguments");
  1790. return nullptr;
  1791. }
  1792. return CondOpInit::get(Case, Val, Type)->Fold(CurRec);
  1793. }
  1794. /// ParseSimpleValue - Parse a tblgen value. This returns null on error.
  1795. ///
  1796. /// SimpleValue ::= IDValue
  1797. /// SimpleValue ::= INTVAL
  1798. /// SimpleValue ::= STRVAL+
  1799. /// SimpleValue ::= CODEFRAGMENT
  1800. /// SimpleValue ::= '?'
  1801. /// SimpleValue ::= '{' ValueList '}'
  1802. /// SimpleValue ::= ID '<' ValueListNE '>'
  1803. /// SimpleValue ::= '[' ValueList ']'
  1804. /// SimpleValue ::= '(' IDValue DagArgList ')'
  1805. /// SimpleValue ::= CONCATTOK '(' Value ',' Value ')'
  1806. /// SimpleValue ::= ADDTOK '(' Value ',' Value ')'
  1807. /// SimpleValue ::= SUBTOK '(' Value ',' Value ')'
  1808. /// SimpleValue ::= SHLTOK '(' Value ',' Value ')'
  1809. /// SimpleValue ::= SRATOK '(' Value ',' Value ')'
  1810. /// SimpleValue ::= SRLTOK '(' Value ',' Value ')'
  1811. /// SimpleValue ::= LISTCONCATTOK '(' Value ',' Value ')'
  1812. /// SimpleValue ::= LISTSPLATTOK '(' Value ',' Value ')'
  1813. /// SimpleValue ::= STRCONCATTOK '(' Value ',' Value ')'
  1814. /// SimpleValue ::= COND '(' [Value ':' Value,]+ ')'
  1815. ///
  1816. Init *TGParser::ParseSimpleValue(Record *CurRec, RecTy *ItemType,
  1817. IDParseMode Mode) {
  1818. Init *R = nullptr;
  1819. switch (Lex.getCode()) {
  1820. default: TokError("Unknown or reserved token when parsing a value"); break;
  1821. case tgtok::TrueVal:
  1822. R = IntInit::get(1);
  1823. Lex.Lex();
  1824. break;
  1825. case tgtok::FalseVal:
  1826. R = IntInit::get(0);
  1827. Lex.Lex();
  1828. break;
  1829. case tgtok::IntVal:
  1830. R = IntInit::get(Lex.getCurIntVal());
  1831. Lex.Lex();
  1832. break;
  1833. case tgtok::BinaryIntVal: {
  1834. auto BinaryVal = Lex.getCurBinaryIntVal();
  1835. SmallVector<Init*, 16> Bits(BinaryVal.second);
  1836. for (unsigned i = 0, e = BinaryVal.second; i != e; ++i)
  1837. Bits[i] = BitInit::get(BinaryVal.first & (1LL << i));
  1838. R = BitsInit::get(Bits);
  1839. Lex.Lex();
  1840. break;
  1841. }
  1842. case tgtok::StrVal: {
  1843. std::string Val = Lex.getCurStrVal();
  1844. Lex.Lex();
  1845. // Handle multiple consecutive concatenated strings.
  1846. while (Lex.getCode() == tgtok::StrVal) {
  1847. Val += Lex.getCurStrVal();
  1848. Lex.Lex();
  1849. }
  1850. R = StringInit::get(Val);
  1851. break;
  1852. }
  1853. case tgtok::CodeFragment:
  1854. R = StringInit::get(Lex.getCurStrVal(), StringInit::SF_Code);
  1855. Lex.Lex();
  1856. break;
  1857. case tgtok::question:
  1858. R = UnsetInit::get();
  1859. Lex.Lex();
  1860. break;
  1861. case tgtok::Id: {
  1862. SMLoc NameLoc = Lex.getLoc();
  1863. StringInit *Name = StringInit::get(Lex.getCurStrVal());
  1864. if (Lex.Lex() != tgtok::less) // consume the Id.
  1865. return ParseIDValue(CurRec, Name, NameLoc, Mode); // Value ::= IDValue
  1866. // Value ::= CLASSID '<' ValueListNE '>' (CLASSID has been consumed)
  1867. // This is supposed to synthesize a new anonymous definition, deriving
  1868. // from the class with the template arguments, but no body.
  1869. Record *Class = Records.getClass(Name->getValue());
  1870. if (!Class) {
  1871. Error(NameLoc, "Expected a class name, got '" + Name->getValue() + "'");
  1872. return nullptr;
  1873. }
  1874. SmallVector<Init *, 8> Args;
  1875. Lex.Lex(); // consume the <
  1876. if (ParseTemplateArgValueList(Args, CurRec, Class))
  1877. return nullptr; // Error parsing value list.
  1878. if (CheckTemplateArgValues(Args, NameLoc, Class))
  1879. return nullptr; // Error checking template argument values.
  1880. // Loop through the arguments that were not specified and make sure
  1881. // they have a complete value.
  1882. ArrayRef<Init *> TArgs = Class->getTemplateArgs();
  1883. for (unsigned I = Args.size(), E = TArgs.size(); I < E; ++I) {
  1884. RecordVal *Arg = Class->getValue(TArgs[I]);
  1885. if (!Arg->getValue()->isComplete())
  1886. Error(NameLoc, "Value not specified for template argument '" +
  1887. TArgs[I]->getAsUnquotedString() + "' (#" + Twine(I) +
  1888. ") of parent class '" +
  1889. Class->getNameInitAsString() + "'");
  1890. }
  1891. return VarDefInit::get(Class, Args)->Fold();
  1892. }
  1893. case tgtok::l_brace: { // Value ::= '{' ValueList '}'
  1894. SMLoc BraceLoc = Lex.getLoc();
  1895. Lex.Lex(); // eat the '{'
  1896. SmallVector<Init*, 16> Vals;
  1897. if (Lex.getCode() != tgtok::r_brace) {
  1898. ParseValueList(Vals, CurRec);
  1899. if (Vals.empty()) return nullptr;
  1900. }
  1901. if (!consume(tgtok::r_brace)) {
  1902. TokError("expected '}' at end of bit list value");
  1903. return nullptr;
  1904. }
  1905. SmallVector<Init *, 16> NewBits;
  1906. // As we parse { a, b, ... }, 'a' is the highest bit, but we parse it
  1907. // first. We'll first read everything in to a vector, then we can reverse
  1908. // it to get the bits in the correct order for the BitsInit value.
  1909. for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
  1910. // FIXME: The following two loops would not be duplicated
  1911. // if the API was a little more orthogonal.
  1912. // bits<n> values are allowed to initialize n bits.
  1913. if (BitsInit *BI = dyn_cast<BitsInit>(Vals[i])) {
  1914. for (unsigned i = 0, e = BI->getNumBits(); i != e; ++i)
  1915. NewBits.push_back(BI->getBit((e - i) - 1));
  1916. continue;
  1917. }
  1918. // bits<n> can also come from variable initializers.
  1919. if (VarInit *VI = dyn_cast<VarInit>(Vals[i])) {
  1920. if (BitsRecTy *BitsRec = dyn_cast<BitsRecTy>(VI->getType())) {
  1921. for (unsigned i = 0, e = BitsRec->getNumBits(); i != e; ++i)
  1922. NewBits.push_back(VI->getBit((e - i) - 1));
  1923. continue;
  1924. }
  1925. // Fallthrough to try convert this to a bit.
  1926. }
  1927. // All other values must be convertible to just a single bit.
  1928. Init *Bit = Vals[i]->getCastTo(BitRecTy::get());
  1929. if (!Bit) {
  1930. Error(BraceLoc, "Element #" + Twine(i) + " (" + Vals[i]->getAsString() +
  1931. ") is not convertable to a bit");
  1932. return nullptr;
  1933. }
  1934. NewBits.push_back(Bit);
  1935. }
  1936. std::reverse(NewBits.begin(), NewBits.end());
  1937. return BitsInit::get(NewBits);
  1938. }
  1939. case tgtok::l_square: { // Value ::= '[' ValueList ']'
  1940. Lex.Lex(); // eat the '['
  1941. SmallVector<Init*, 16> Vals;
  1942. RecTy *DeducedEltTy = nullptr;
  1943. ListRecTy *GivenListTy = nullptr;
  1944. if (ItemType) {
  1945. ListRecTy *ListType = dyn_cast<ListRecTy>(ItemType);
  1946. if (!ListType) {
  1947. TokError(Twine("Encountered a list when expecting a ") +
  1948. ItemType->getAsString());
  1949. return nullptr;
  1950. }
  1951. GivenListTy = ListType;
  1952. }
  1953. if (Lex.getCode() != tgtok::r_square) {
  1954. ParseValueList(Vals, CurRec,
  1955. GivenListTy ? GivenListTy->getElementType() : nullptr);
  1956. if (Vals.empty()) return nullptr;
  1957. }
  1958. if (!consume(tgtok::r_square)) {
  1959. TokError("expected ']' at end of list value");
  1960. return nullptr;
  1961. }
  1962. RecTy *GivenEltTy = nullptr;
  1963. if (consume(tgtok::less)) {
  1964. // Optional list element type
  1965. GivenEltTy = ParseType();
  1966. if (!GivenEltTy) {
  1967. // Couldn't parse element type
  1968. return nullptr;
  1969. }
  1970. if (!consume(tgtok::greater)) {
  1971. TokError("expected '>' at end of list element type");
  1972. return nullptr;
  1973. }
  1974. }
  1975. // Check elements
  1976. RecTy *EltTy = nullptr;
  1977. for (Init *V : Vals) {
  1978. TypedInit *TArg = dyn_cast<TypedInit>(V);
  1979. if (TArg) {
  1980. if (EltTy) {
  1981. EltTy = resolveTypes(EltTy, TArg->getType());
  1982. if (!EltTy) {
  1983. TokError("Incompatible types in list elements");
  1984. return nullptr;
  1985. }
  1986. } else {
  1987. EltTy = TArg->getType();
  1988. }
  1989. }
  1990. }
  1991. if (GivenEltTy) {
  1992. if (EltTy) {
  1993. // Verify consistency
  1994. if (!EltTy->typeIsConvertibleTo(GivenEltTy)) {
  1995. TokError("Incompatible types in list elements");
  1996. return nullptr;
  1997. }
  1998. }
  1999. EltTy = GivenEltTy;
  2000. }
  2001. if (!EltTy) {
  2002. if (!ItemType) {
  2003. TokError("No type for list");
  2004. return nullptr;
  2005. }
  2006. DeducedEltTy = GivenListTy->getElementType();
  2007. } else {
  2008. // Make sure the deduced type is compatible with the given type
  2009. if (GivenListTy) {
  2010. if (!EltTy->typeIsConvertibleTo(GivenListTy->getElementType())) {
  2011. TokError(Twine("Element type mismatch for list: element type '") +
  2012. EltTy->getAsString() + "' not convertible to '" +
  2013. GivenListTy->getElementType()->getAsString());
  2014. return nullptr;
  2015. }
  2016. }
  2017. DeducedEltTy = EltTy;
  2018. }
  2019. return ListInit::get(Vals, DeducedEltTy);
  2020. }
  2021. case tgtok::l_paren: { // Value ::= '(' IDValue DagArgList ')'
  2022. Lex.Lex(); // eat the '('
  2023. if (Lex.getCode() != tgtok::Id && Lex.getCode() != tgtok::XCast &&
  2024. Lex.getCode() != tgtok::question && Lex.getCode() != tgtok::XGetDagOp) {
  2025. TokError("expected identifier in dag init");
  2026. return nullptr;
  2027. }
  2028. Init *Operator = ParseValue(CurRec);
  2029. if (!Operator) return nullptr;
  2030. // If the operator name is present, parse it.
  2031. StringInit *OperatorName = nullptr;
  2032. if (consume(tgtok::colon)) {
  2033. if (Lex.getCode() != tgtok::VarName) { // eat the ':'
  2034. TokError("expected variable name in dag operator");
  2035. return nullptr;
  2036. }
  2037. OperatorName = StringInit::get(Lex.getCurStrVal());
  2038. Lex.Lex(); // eat the VarName.
  2039. }
  2040. SmallVector<std::pair<llvm::Init*, StringInit*>, 8> DagArgs;
  2041. if (Lex.getCode() != tgtok::r_paren) {
  2042. ParseDagArgList(DagArgs, CurRec);
  2043. if (DagArgs.empty()) return nullptr;
  2044. }
  2045. if (!consume(tgtok::r_paren)) {
  2046. TokError("expected ')' in dag init");
  2047. return nullptr;
  2048. }
  2049. return DagInit::get(Operator, OperatorName, DagArgs);
  2050. }
  2051. case tgtok::XHead:
  2052. case tgtok::XTail:
  2053. case tgtok::XSize:
  2054. case tgtok::XEmpty:
  2055. case tgtok::XCast:
  2056. case tgtok::XGetDagOp: // Value ::= !unop '(' Value ')'
  2057. case tgtok::XIsA:
  2058. case tgtok::XConcat:
  2059. case tgtok::XDag:
  2060. case tgtok::XADD:
  2061. case tgtok::XSUB:
  2062. case tgtok::XMUL:
  2063. case tgtok::XNOT:
  2064. case tgtok::XAND:
  2065. case tgtok::XOR:
  2066. case tgtok::XXOR:
  2067. case tgtok::XSRA:
  2068. case tgtok::XSRL:
  2069. case tgtok::XSHL:
  2070. case tgtok::XEq:
  2071. case tgtok::XNe:
  2072. case tgtok::XLe:
  2073. case tgtok::XLt:
  2074. case tgtok::XGe:
  2075. case tgtok::XGt:
  2076. case tgtok::XListConcat:
  2077. case tgtok::XListSplat:
  2078. case tgtok::XStrConcat:
  2079. case tgtok::XInterleave:
  2080. case tgtok::XSetDagOp: // Value ::= !binop '(' Value ',' Value ')'
  2081. case tgtok::XIf:
  2082. case tgtok::XCond:
  2083. case tgtok::XFoldl:
  2084. case tgtok::XForEach:
  2085. case tgtok::XFilter:
  2086. case tgtok::XSubst:
  2087. case tgtok::XSubstr:
  2088. case tgtok::XFind: { // Value ::= !ternop '(' Value ',' Value ',' Value ')'
  2089. return ParseOperation(CurRec, ItemType);
  2090. }
  2091. }
  2092. return R;
  2093. }
  2094. /// ParseValue - Parse a TableGen value. This returns null on error.
  2095. ///
  2096. /// Value ::= SimpleValue ValueSuffix*
  2097. /// ValueSuffix ::= '{' BitList '}'
  2098. /// ValueSuffix ::= '[' BitList ']'
  2099. /// ValueSuffix ::= '.' ID
  2100. ///
  2101. Init *TGParser::ParseValue(Record *CurRec, RecTy *ItemType, IDParseMode Mode) {
  2102. Init *Result = ParseSimpleValue(CurRec, ItemType, Mode);
  2103. if (!Result) return nullptr;
  2104. // Parse the suffixes now if present.
  2105. while (true) {
  2106. switch (Lex.getCode()) {
  2107. default: return Result;
  2108. case tgtok::l_brace: {
  2109. if (Mode == ParseNameMode)
  2110. // This is the beginning of the object body.
  2111. return Result;
  2112. SMLoc CurlyLoc = Lex.getLoc();
  2113. Lex.Lex(); // eat the '{'
  2114. SmallVector<unsigned, 16> Ranges;
  2115. ParseRangeList(Ranges);
  2116. if (Ranges.empty()) return nullptr;
  2117. // Reverse the bitlist.
  2118. std::reverse(Ranges.begin(), Ranges.end());
  2119. Result = Result->convertInitializerBitRange(Ranges);
  2120. if (!Result) {
  2121. Error(CurlyLoc, "Invalid bit range for value");
  2122. return nullptr;
  2123. }
  2124. // Eat the '}'.
  2125. if (!consume(tgtok::r_brace)) {
  2126. TokError("expected '}' at end of bit range list");
  2127. return nullptr;
  2128. }
  2129. break;
  2130. }
  2131. case tgtok::l_square: {
  2132. SMLoc SquareLoc = Lex.getLoc();
  2133. Lex.Lex(); // eat the '['
  2134. SmallVector<unsigned, 16> Ranges;
  2135. ParseRangeList(Ranges);
  2136. if (Ranges.empty()) return nullptr;
  2137. Result = Result->convertInitListSlice(Ranges);
  2138. if (!Result) {
  2139. Error(SquareLoc, "Invalid range for list slice");
  2140. return nullptr;
  2141. }
  2142. // Eat the ']'.
  2143. if (!consume(tgtok::r_square)) {
  2144. TokError("expected ']' at end of list slice");
  2145. return nullptr;
  2146. }
  2147. break;
  2148. }
  2149. case tgtok::dot: {
  2150. if (Lex.Lex() != tgtok::Id) { // eat the .
  2151. TokError("expected field identifier after '.'");
  2152. return nullptr;
  2153. }
  2154. StringInit *FieldName = StringInit::get(Lex.getCurStrVal());
  2155. if (!Result->getFieldType(FieldName)) {
  2156. TokError("Cannot access field '" + Lex.getCurStrVal() + "' of value '" +
  2157. Result->getAsString() + "'");
  2158. return nullptr;
  2159. }
  2160. Result = FieldInit::get(Result, FieldName)->Fold(CurRec);
  2161. Lex.Lex(); // eat field name
  2162. break;
  2163. }
  2164. case tgtok::paste:
  2165. SMLoc PasteLoc = Lex.getLoc();
  2166. TypedInit *LHS = dyn_cast<TypedInit>(Result);
  2167. if (!LHS) {
  2168. Error(PasteLoc, "LHS of paste is not typed!");
  2169. return nullptr;
  2170. }
  2171. // Check if it's a 'listA # listB'
  2172. if (isa<ListRecTy>(LHS->getType())) {
  2173. Lex.Lex(); // Eat the '#'.
  2174. assert(Mode == ParseValueMode && "encountered paste of lists in name");
  2175. switch (Lex.getCode()) {
  2176. case tgtok::colon:
  2177. case tgtok::semi:
  2178. case tgtok::l_brace:
  2179. Result = LHS; // trailing paste, ignore.
  2180. break;
  2181. default:
  2182. Init *RHSResult = ParseValue(CurRec, ItemType, ParseValueMode);
  2183. if (!RHSResult)
  2184. return nullptr;
  2185. Result = BinOpInit::getListConcat(LHS, RHSResult);
  2186. break;
  2187. }
  2188. break;
  2189. }
  2190. // Create a !strconcat() operation, first casting each operand to
  2191. // a string if necessary.
  2192. if (LHS->getType() != StringRecTy::get()) {
  2193. auto CastLHS = dyn_cast<TypedInit>(
  2194. UnOpInit::get(UnOpInit::CAST, LHS, StringRecTy::get())
  2195. ->Fold(CurRec));
  2196. if (!CastLHS) {
  2197. Error(PasteLoc,
  2198. Twine("can't cast '") + LHS->getAsString() + "' to string");
  2199. return nullptr;
  2200. }
  2201. LHS = CastLHS;
  2202. }
  2203. TypedInit *RHS = nullptr;
  2204. Lex.Lex(); // Eat the '#'.
  2205. switch (Lex.getCode()) {
  2206. case tgtok::colon:
  2207. case tgtok::semi:
  2208. case tgtok::l_brace:
  2209. // These are all of the tokens that can begin an object body.
  2210. // Some of these can also begin values but we disallow those cases
  2211. // because they are unlikely to be useful.
  2212. // Trailing paste, concat with an empty string.
  2213. RHS = StringInit::get("");
  2214. break;
  2215. default:
  2216. Init *RHSResult = ParseValue(CurRec, nullptr, ParseNameMode);
  2217. if (!RHSResult)
  2218. return nullptr;
  2219. RHS = dyn_cast<TypedInit>(RHSResult);
  2220. if (!RHS) {
  2221. Error(PasteLoc, "RHS of paste is not typed!");
  2222. return nullptr;
  2223. }
  2224. if (RHS->getType() != StringRecTy::get()) {
  2225. auto CastRHS = dyn_cast<TypedInit>(
  2226. UnOpInit::get(UnOpInit::CAST, RHS, StringRecTy::get())
  2227. ->Fold(CurRec));
  2228. if (!CastRHS) {
  2229. Error(PasteLoc,
  2230. Twine("can't cast '") + RHS->getAsString() + "' to string");
  2231. return nullptr;
  2232. }
  2233. RHS = CastRHS;
  2234. }
  2235. break;
  2236. }
  2237. Result = BinOpInit::getStrConcat(LHS, RHS);
  2238. break;
  2239. }
  2240. }
  2241. }
  2242. /// ParseDagArgList - Parse the argument list for a dag literal expression.
  2243. ///
  2244. /// DagArg ::= Value (':' VARNAME)?
  2245. /// DagArg ::= VARNAME
  2246. /// DagArgList ::= DagArg
  2247. /// DagArgList ::= DagArgList ',' DagArg
  2248. void TGParser::ParseDagArgList(
  2249. SmallVectorImpl<std::pair<llvm::Init*, StringInit*>> &Result,
  2250. Record *CurRec) {
  2251. while (true) {
  2252. // DagArg ::= VARNAME
  2253. if (Lex.getCode() == tgtok::VarName) {
  2254. // A missing value is treated like '?'.
  2255. StringInit *VarName = StringInit::get(Lex.getCurStrVal());
  2256. Result.emplace_back(UnsetInit::get(), VarName);
  2257. Lex.Lex();
  2258. } else {
  2259. // DagArg ::= Value (':' VARNAME)?
  2260. Init *Val = ParseValue(CurRec);
  2261. if (!Val) {
  2262. Result.clear();
  2263. return;
  2264. }
  2265. // If the variable name is present, add it.
  2266. StringInit *VarName = nullptr;
  2267. if (Lex.getCode() == tgtok::colon) {
  2268. if (Lex.Lex() != tgtok::VarName) { // eat the ':'
  2269. TokError("expected variable name in dag literal");
  2270. Result.clear();
  2271. return;
  2272. }
  2273. VarName = StringInit::get(Lex.getCurStrVal());
  2274. Lex.Lex(); // eat the VarName.
  2275. }
  2276. Result.push_back(std::make_pair(Val, VarName));
  2277. }
  2278. if (!consume(tgtok::comma))
  2279. break;
  2280. }
  2281. }
  2282. /// ParseValueList - Parse a comma separated list of values, returning them
  2283. /// in a vector. Note that this always expects to be able to parse at least one
  2284. /// value. It returns an empty list if this is not possible.
  2285. ///
  2286. /// ValueList ::= Value (',' Value)
  2287. ///
  2288. void TGParser::ParseValueList(SmallVectorImpl<Init *> &Result, Record *CurRec,
  2289. RecTy *ItemType) {
  2290. Result.push_back(ParseValue(CurRec, ItemType));
  2291. if (!Result.back()) {
  2292. Result.clear();
  2293. return;
  2294. }
  2295. while (consume(tgtok::comma)) {
  2296. // ignore trailing comma for lists
  2297. if (Lex.getCode() == tgtok::r_square)
  2298. return;
  2299. Result.push_back(ParseValue(CurRec, ItemType));
  2300. if (!Result.back()) {
  2301. Result.clear();
  2302. return;
  2303. }
  2304. }
  2305. }
  2306. // ParseTemplateArgValueList - Parse a template argument list with the syntax
  2307. // shown, filling in the Result vector. The open angle has been consumed.
  2308. // An empty argument list is allowed. Return false if okay, true if an
  2309. // error was detected.
  2310. //
  2311. // TemplateArgList ::= '<' [Value {',' Value}*] '>'
  2312. bool TGParser::ParseTemplateArgValueList(SmallVectorImpl<Init *> &Result,
  2313. Record *CurRec, Record *ArgsRec) {
  2314. assert(Result.empty() && "Result vector is not empty");
  2315. ArrayRef<Init *> TArgs = ArgsRec->getTemplateArgs();
  2316. unsigned ArgIndex = 0;
  2317. RecTy *ItemType;
  2318. if (consume(tgtok::greater)) // empty value list
  2319. return false;
  2320. while (true) {
  2321. if (ArgIndex >= TArgs.size()) {
  2322. TokError("Too many template arguments: " + utostr(ArgIndex + 1));
  2323. return true;
  2324. }
  2325. const RecordVal *Arg = ArgsRec->getValue(TArgs[ArgIndex]);
  2326. assert(Arg && "Template argument record not found");
  2327. ItemType = Arg->getType();
  2328. Init *Value = ParseValue(CurRec, ItemType);
  2329. if (!Value)
  2330. return true;
  2331. Result.push_back(Value);
  2332. if (consume(tgtok::greater)) // end of argument list?
  2333. return false;
  2334. if (!consume(tgtok::comma))
  2335. return TokError("Expected comma before next argument");
  2336. ++ArgIndex;
  2337. }
  2338. }
  2339. /// ParseDeclaration - Read a declaration, returning the name of field ID, or an
  2340. /// empty string on error. This can happen in a number of different contexts,
  2341. /// including within a def or in the template args for a class (in which case
  2342. /// CurRec will be non-null) and within the template args for a multiclass (in
  2343. /// which case CurRec will be null, but CurMultiClass will be set). This can
  2344. /// also happen within a def that is within a multiclass, which will set both
  2345. /// CurRec and CurMultiClass.
  2346. ///
  2347. /// Declaration ::= FIELD? Type ID ('=' Value)?
  2348. ///
  2349. Init *TGParser::ParseDeclaration(Record *CurRec,
  2350. bool ParsingTemplateArgs) {
  2351. // Read the field prefix if present.
  2352. bool HasField = consume(tgtok::Field);
  2353. RecTy *Type = ParseType();
  2354. if (!Type) return nullptr;
  2355. if (Lex.getCode() != tgtok::Id) {
  2356. TokError("Expected identifier in declaration");
  2357. return nullptr;
  2358. }
  2359. std::string Str = Lex.getCurStrVal();
  2360. if (Str == "NAME") {
  2361. TokError("'" + Str + "' is a reserved variable name");
  2362. return nullptr;
  2363. }
  2364. SMLoc IdLoc = Lex.getLoc();
  2365. Init *DeclName = StringInit::get(Str);
  2366. Lex.Lex();
  2367. bool BadField;
  2368. if (!ParsingTemplateArgs) { // def, possibly in a multiclass
  2369. BadField = AddValue(CurRec, IdLoc,
  2370. RecordVal(DeclName, IdLoc, Type,
  2371. HasField ? RecordVal::FK_NonconcreteOK
  2372. : RecordVal::FK_Normal));
  2373. } else if (CurRec) { // class template argument
  2374. DeclName = QualifyName(*CurRec, CurMultiClass, DeclName, ":");
  2375. BadField = AddValue(CurRec, IdLoc, RecordVal(DeclName, IdLoc, Type,
  2376. RecordVal::FK_TemplateArg));
  2377. } else { // multiclass template argument
  2378. assert(CurMultiClass && "invalid context for template argument");
  2379. DeclName = QualifyName(CurMultiClass->Rec, CurMultiClass, DeclName, "::");
  2380. BadField = AddValue(CurRec, IdLoc, RecordVal(DeclName, IdLoc, Type,
  2381. RecordVal::FK_TemplateArg));
  2382. }
  2383. if (BadField)
  2384. return nullptr;
  2385. // If a value is present, parse it and set new field's value.
  2386. if (consume(tgtok::equal)) {
  2387. SMLoc ValLoc = Lex.getLoc();
  2388. Init *Val = ParseValue(CurRec, Type);
  2389. if (!Val ||
  2390. SetValue(CurRec, ValLoc, DeclName, None, Val))
  2391. // Return the name, even if an error is thrown. This is so that we can
  2392. // continue to make some progress, even without the value having been
  2393. // initialized.
  2394. return DeclName;
  2395. }
  2396. return DeclName;
  2397. }
  2398. /// ParseForeachDeclaration - Read a foreach declaration, returning
  2399. /// the name of the declared object or a NULL Init on error. Return
  2400. /// the name of the parsed initializer list through ForeachListName.
  2401. ///
  2402. /// ForeachDeclaration ::= ID '=' '{' RangeList '}'
  2403. /// ForeachDeclaration ::= ID '=' RangePiece
  2404. /// ForeachDeclaration ::= ID '=' Value
  2405. ///
  2406. VarInit *TGParser::ParseForeachDeclaration(Init *&ForeachListValue) {
  2407. if (Lex.getCode() != tgtok::Id) {
  2408. TokError("Expected identifier in foreach declaration");
  2409. return nullptr;
  2410. }
  2411. Init *DeclName = StringInit::get(Lex.getCurStrVal());
  2412. Lex.Lex();
  2413. // If a value is present, parse it.
  2414. if (!consume(tgtok::equal)) {
  2415. TokError("Expected '=' in foreach declaration");
  2416. return nullptr;
  2417. }
  2418. RecTy *IterType = nullptr;
  2419. SmallVector<unsigned, 16> Ranges;
  2420. switch (Lex.getCode()) {
  2421. case tgtok::l_brace: { // '{' RangeList '}'
  2422. Lex.Lex(); // eat the '{'
  2423. ParseRangeList(Ranges);
  2424. if (!consume(tgtok::r_brace)) {
  2425. TokError("expected '}' at end of bit range list");
  2426. return nullptr;
  2427. }
  2428. break;
  2429. }
  2430. default: {
  2431. SMLoc ValueLoc = Lex.getLoc();
  2432. Init *I = ParseValue(nullptr);
  2433. if (!I)
  2434. return nullptr;
  2435. TypedInit *TI = dyn_cast<TypedInit>(I);
  2436. if (TI && isa<ListRecTy>(TI->getType())) {
  2437. ForeachListValue = I;
  2438. IterType = cast<ListRecTy>(TI->getType())->getElementType();
  2439. break;
  2440. }
  2441. if (TI) {
  2442. if (ParseRangePiece(Ranges, TI))
  2443. return nullptr;
  2444. break;
  2445. }
  2446. Error(ValueLoc, "expected a list, got '" + I->getAsString() + "'");
  2447. if (CurMultiClass) {
  2448. PrintNote({}, "references to multiclass template arguments cannot be "
  2449. "resolved at this time");
  2450. }
  2451. return nullptr;
  2452. }
  2453. }
  2454. if (!Ranges.empty()) {
  2455. assert(!IterType && "Type already initialized?");
  2456. IterType = IntRecTy::get();
  2457. std::vector<Init *> Values;
  2458. for (unsigned R : Ranges)
  2459. Values.push_back(IntInit::get(R));
  2460. ForeachListValue = ListInit::get(Values, IterType);
  2461. }
  2462. if (!IterType)
  2463. return nullptr;
  2464. return VarInit::get(DeclName, IterType);
  2465. }
  2466. /// ParseTemplateArgList - Read a template argument list, which is a non-empty
  2467. /// sequence of template-declarations in <>'s. If CurRec is non-null, these are
  2468. /// template args for a class. If null, these are the template args for a
  2469. /// multiclass.
  2470. ///
  2471. /// TemplateArgList ::= '<' Declaration (',' Declaration)* '>'
  2472. ///
  2473. bool TGParser::ParseTemplateArgList(Record *CurRec) {
  2474. assert(Lex.getCode() == tgtok::less && "Not a template arg list!");
  2475. Lex.Lex(); // eat the '<'
  2476. Record *TheRecToAddTo = CurRec ? CurRec : &CurMultiClass->Rec;
  2477. // Read the first declaration.
  2478. Init *TemplArg = ParseDeclaration(CurRec, true/*templateargs*/);
  2479. if (!TemplArg)
  2480. return true;
  2481. TheRecToAddTo->addTemplateArg(TemplArg);
  2482. while (consume(tgtok::comma)) {
  2483. // Read the following declarations.
  2484. SMLoc Loc = Lex.getLoc();
  2485. TemplArg = ParseDeclaration(CurRec, true/*templateargs*/);
  2486. if (!TemplArg)
  2487. return true;
  2488. if (TheRecToAddTo->isTemplateArg(TemplArg))
  2489. return Error(Loc, "template argument with the same name has already been "
  2490. "defined");
  2491. TheRecToAddTo->addTemplateArg(TemplArg);
  2492. }
  2493. if (!consume(tgtok::greater))
  2494. return TokError("expected '>' at end of template argument list");
  2495. return false;
  2496. }
  2497. /// ParseBodyItem - Parse a single item within the body of a def or class.
  2498. ///
  2499. /// BodyItem ::= Declaration ';'
  2500. /// BodyItem ::= LET ID OptionalBitList '=' Value ';'
  2501. /// BodyItem ::= Defvar
  2502. /// BodyItem ::= Assert
  2503. ///
  2504. bool TGParser::ParseBodyItem(Record *CurRec) {
  2505. if (Lex.getCode() == tgtok::Assert)
  2506. return ParseAssert(nullptr, CurRec);
  2507. if (Lex.getCode() == tgtok::Defvar)
  2508. return ParseDefvar();
  2509. if (Lex.getCode() != tgtok::Let) {
  2510. if (!ParseDeclaration(CurRec, false))
  2511. return true;
  2512. if (!consume(tgtok::semi))
  2513. return TokError("expected ';' after declaration");
  2514. return false;
  2515. }
  2516. // LET ID OptionalRangeList '=' Value ';'
  2517. if (Lex.Lex() != tgtok::Id)
  2518. return TokError("expected field identifier after let");
  2519. SMLoc IdLoc = Lex.getLoc();
  2520. StringInit *FieldName = StringInit::get(Lex.getCurStrVal());
  2521. Lex.Lex(); // eat the field name.
  2522. SmallVector<unsigned, 16> BitList;
  2523. if (ParseOptionalBitList(BitList))
  2524. return true;
  2525. std::reverse(BitList.begin(), BitList.end());
  2526. if (!consume(tgtok::equal))
  2527. return TokError("expected '=' in let expression");
  2528. RecordVal *Field = CurRec->getValue(FieldName);
  2529. if (!Field)
  2530. return TokError("Value '" + FieldName->getValue() + "' unknown!");
  2531. RecTy *Type = Field->getType();
  2532. if (!BitList.empty() && isa<BitsRecTy>(Type)) {
  2533. // When assigning to a subset of a 'bits' object, expect the RHS to have
  2534. // the type of that subset instead of the type of the whole object.
  2535. Type = BitsRecTy::get(BitList.size());
  2536. }
  2537. Init *Val = ParseValue(CurRec, Type);
  2538. if (!Val) return true;
  2539. if (!consume(tgtok::semi))
  2540. return TokError("expected ';' after let expression");
  2541. return SetValue(CurRec, IdLoc, FieldName, BitList, Val);
  2542. }
  2543. /// ParseBody - Read the body of a class or def. Return true on error, false on
  2544. /// success.
  2545. ///
  2546. /// Body ::= ';'
  2547. /// Body ::= '{' BodyList '}'
  2548. /// BodyList BodyItem*
  2549. ///
  2550. bool TGParser::ParseBody(Record *CurRec) {
  2551. // If this is a null definition, just eat the semi and return.
  2552. if (consume(tgtok::semi))
  2553. return false;
  2554. if (!consume(tgtok::l_brace))
  2555. return TokError("Expected '{' to start body or ';' for declaration only");
  2556. // An object body introduces a new scope for local variables.
  2557. TGLocalVarScope *BodyScope = PushLocalScope();
  2558. while (Lex.getCode() != tgtok::r_brace)
  2559. if (ParseBodyItem(CurRec))
  2560. return true;
  2561. PopLocalScope(BodyScope);
  2562. // Eat the '}'.
  2563. Lex.Lex();
  2564. // If we have a semicolon, print a gentle error.
  2565. SMLoc SemiLoc = Lex.getLoc();
  2566. if (consume(tgtok::semi)) {
  2567. PrintError(SemiLoc, "A class or def body should not end with a semicolon");
  2568. PrintNote("Semicolon ignored; remove to eliminate this error");
  2569. }
  2570. return false;
  2571. }
  2572. /// Apply the current let bindings to \a CurRec.
  2573. /// \returns true on error, false otherwise.
  2574. bool TGParser::ApplyLetStack(Record *CurRec) {
  2575. for (SmallVectorImpl<LetRecord> &LetInfo : LetStack)
  2576. for (LetRecord &LR : LetInfo)
  2577. if (SetValue(CurRec, LR.Loc, LR.Name, LR.Bits, LR.Value))
  2578. return true;
  2579. return false;
  2580. }
  2581. /// Apply the current let bindings to the RecordsEntry.
  2582. bool TGParser::ApplyLetStack(RecordsEntry &Entry) {
  2583. if (Entry.Rec)
  2584. return ApplyLetStack(Entry.Rec.get());
  2585. // Let bindings are not applied to assertions.
  2586. if (Entry.Assertion)
  2587. return false;
  2588. for (auto &E : Entry.Loop->Entries) {
  2589. if (ApplyLetStack(E))
  2590. return true;
  2591. }
  2592. return false;
  2593. }
  2594. /// ParseObjectBody - Parse the body of a def or class. This consists of an
  2595. /// optional ClassList followed by a Body. CurRec is the current def or class
  2596. /// that is being parsed.
  2597. ///
  2598. /// ObjectBody ::= BaseClassList Body
  2599. /// BaseClassList ::= /*empty*/
  2600. /// BaseClassList ::= ':' BaseClassListNE
  2601. /// BaseClassListNE ::= SubClassRef (',' SubClassRef)*
  2602. ///
  2603. bool TGParser::ParseObjectBody(Record *CurRec) {
  2604. // If there is a baseclass list, read it.
  2605. if (consume(tgtok::colon)) {
  2606. // Read all of the subclasses.
  2607. SubClassReference SubClass = ParseSubClassReference(CurRec, false);
  2608. while (true) {
  2609. // Check for error.
  2610. if (!SubClass.Rec) return true;
  2611. // Add it.
  2612. if (AddSubClass(CurRec, SubClass))
  2613. return true;
  2614. if (!consume(tgtok::comma))
  2615. break;
  2616. SubClass = ParseSubClassReference(CurRec, false);
  2617. }
  2618. }
  2619. if (ApplyLetStack(CurRec))
  2620. return true;
  2621. return ParseBody(CurRec);
  2622. }
  2623. /// ParseDef - Parse and return a top level or multiclass record definition.
  2624. /// Return false if okay, true if error.
  2625. ///
  2626. /// DefInst ::= DEF ObjectName ObjectBody
  2627. ///
  2628. bool TGParser::ParseDef(MultiClass *CurMultiClass) {
  2629. SMLoc DefLoc = Lex.getLoc();
  2630. assert(Lex.getCode() == tgtok::Def && "Unknown tok");
  2631. Lex.Lex(); // Eat the 'def' token.
  2632. // Parse ObjectName and make a record for it.
  2633. std::unique_ptr<Record> CurRec;
  2634. Init *Name = ParseObjectName(CurMultiClass);
  2635. if (!Name)
  2636. return true;
  2637. if (isa<UnsetInit>(Name))
  2638. CurRec = std::make_unique<Record>(Records.getNewAnonymousName(), DefLoc, Records,
  2639. /*Anonymous=*/true);
  2640. else
  2641. CurRec = std::make_unique<Record>(Name, DefLoc, Records);
  2642. if (ParseObjectBody(CurRec.get()))
  2643. return true;
  2644. return addEntry(std::move(CurRec));
  2645. }
  2646. /// ParseDefset - Parse a defset statement.
  2647. ///
  2648. /// Defset ::= DEFSET Type Id '=' '{' ObjectList '}'
  2649. ///
  2650. bool TGParser::ParseDefset() {
  2651. assert(Lex.getCode() == tgtok::Defset);
  2652. Lex.Lex(); // Eat the 'defset' token
  2653. DefsetRecord Defset;
  2654. Defset.Loc = Lex.getLoc();
  2655. RecTy *Type = ParseType();
  2656. if (!Type)
  2657. return true;
  2658. if (!isa<ListRecTy>(Type))
  2659. return Error(Defset.Loc, "expected list type");
  2660. Defset.EltTy = cast<ListRecTy>(Type)->getElementType();
  2661. if (Lex.getCode() != tgtok::Id)
  2662. return TokError("expected identifier");
  2663. StringInit *DeclName = StringInit::get(Lex.getCurStrVal());
  2664. if (Records.getGlobal(DeclName->getValue()))
  2665. return TokError("def or global variable of this name already exists");
  2666. if (Lex.Lex() != tgtok::equal) // Eat the identifier
  2667. return TokError("expected '='");
  2668. if (Lex.Lex() != tgtok::l_brace) // Eat the '='
  2669. return TokError("expected '{'");
  2670. SMLoc BraceLoc = Lex.getLoc();
  2671. Lex.Lex(); // Eat the '{'
  2672. Defsets.push_back(&Defset);
  2673. bool Err = ParseObjectList(nullptr);
  2674. Defsets.pop_back();
  2675. if (Err)
  2676. return true;
  2677. if (!consume(tgtok::r_brace)) {
  2678. TokError("expected '}' at end of defset");
  2679. return Error(BraceLoc, "to match this '{'");
  2680. }
  2681. Records.addExtraGlobal(DeclName->getValue(),
  2682. ListInit::get(Defset.Elements, Defset.EltTy));
  2683. return false;
  2684. }
  2685. /// ParseDefvar - Parse a defvar statement.
  2686. ///
  2687. /// Defvar ::= DEFVAR Id '=' Value ';'
  2688. ///
  2689. bool TGParser::ParseDefvar() {
  2690. assert(Lex.getCode() == tgtok::Defvar);
  2691. Lex.Lex(); // Eat the 'defvar' token
  2692. if (Lex.getCode() != tgtok::Id)
  2693. return TokError("expected identifier");
  2694. StringInit *DeclName = StringInit::get(Lex.getCurStrVal());
  2695. if (CurLocalScope) {
  2696. if (CurLocalScope->varAlreadyDefined(DeclName->getValue()))
  2697. return TokError("local variable of this name already exists");
  2698. } else {
  2699. if (Records.getGlobal(DeclName->getValue()))
  2700. return TokError("def or global variable of this name already exists");
  2701. }
  2702. Lex.Lex();
  2703. if (!consume(tgtok::equal))
  2704. return TokError("expected '='");
  2705. Init *Value = ParseValue(nullptr);
  2706. if (!Value)
  2707. return true;
  2708. if (!consume(tgtok::semi))
  2709. return TokError("expected ';'");
  2710. if (CurLocalScope)
  2711. CurLocalScope->addVar(DeclName->getValue(), Value);
  2712. else
  2713. Records.addExtraGlobal(DeclName->getValue(), Value);
  2714. return false;
  2715. }
  2716. /// ParseForeach - Parse a for statement. Return the record corresponding
  2717. /// to it. This returns true on error.
  2718. ///
  2719. /// Foreach ::= FOREACH Declaration IN '{ ObjectList '}'
  2720. /// Foreach ::= FOREACH Declaration IN Object
  2721. ///
  2722. bool TGParser::ParseForeach(MultiClass *CurMultiClass) {
  2723. SMLoc Loc = Lex.getLoc();
  2724. assert(Lex.getCode() == tgtok::Foreach && "Unknown tok");
  2725. Lex.Lex(); // Eat the 'for' token.
  2726. // Make a temporary object to record items associated with the for
  2727. // loop.
  2728. Init *ListValue = nullptr;
  2729. VarInit *IterName = ParseForeachDeclaration(ListValue);
  2730. if (!IterName)
  2731. return TokError("expected declaration in for");
  2732. if (!consume(tgtok::In))
  2733. return TokError("Unknown tok");
  2734. // Create a loop object and remember it.
  2735. Loops.push_back(std::make_unique<ForeachLoop>(Loc, IterName, ListValue));
  2736. // A foreach loop introduces a new scope for local variables.
  2737. TGLocalVarScope *ForeachScope = PushLocalScope();
  2738. if (Lex.getCode() != tgtok::l_brace) {
  2739. // FOREACH Declaration IN Object
  2740. if (ParseObject(CurMultiClass))
  2741. return true;
  2742. } else {
  2743. SMLoc BraceLoc = Lex.getLoc();
  2744. // Otherwise, this is a group foreach.
  2745. Lex.Lex(); // eat the '{'.
  2746. // Parse the object list.
  2747. if (ParseObjectList(CurMultiClass))
  2748. return true;
  2749. if (!consume(tgtok::r_brace)) {
  2750. TokError("expected '}' at end of foreach command");
  2751. return Error(BraceLoc, "to match this '{'");
  2752. }
  2753. }
  2754. PopLocalScope(ForeachScope);
  2755. // Resolve the loop or store it for later resolution.
  2756. std::unique_ptr<ForeachLoop> Loop = std::move(Loops.back());
  2757. Loops.pop_back();
  2758. return addEntry(std::move(Loop));
  2759. }
  2760. /// ParseIf - Parse an if statement.
  2761. ///
  2762. /// If ::= IF Value THEN IfBody
  2763. /// If ::= IF Value THEN IfBody ELSE IfBody
  2764. ///
  2765. bool TGParser::ParseIf(MultiClass *CurMultiClass) {
  2766. SMLoc Loc = Lex.getLoc();
  2767. assert(Lex.getCode() == tgtok::If && "Unknown tok");
  2768. Lex.Lex(); // Eat the 'if' token.
  2769. // Make a temporary object to record items associated with the for
  2770. // loop.
  2771. Init *Condition = ParseValue(nullptr);
  2772. if (!Condition)
  2773. return true;
  2774. if (!consume(tgtok::Then))
  2775. return TokError("Unknown tok");
  2776. // We have to be able to save if statements to execute later, and they have
  2777. // to live on the same stack as foreach loops. The simplest implementation
  2778. // technique is to convert each 'then' or 'else' clause *into* a foreach
  2779. // loop, over a list of length 0 or 1 depending on the condition, and with no
  2780. // iteration variable being assigned.
  2781. ListInit *EmptyList = ListInit::get({}, BitRecTy::get());
  2782. ListInit *SingletonList =
  2783. ListInit::get({BitInit::get(true)}, BitRecTy::get());
  2784. RecTy *BitListTy = ListRecTy::get(BitRecTy::get());
  2785. // The foreach containing the then-clause selects SingletonList if
  2786. // the condition is true.
  2787. Init *ThenClauseList =
  2788. TernOpInit::get(TernOpInit::IF, Condition, SingletonList, EmptyList,
  2789. BitListTy)
  2790. ->Fold(nullptr);
  2791. Loops.push_back(std::make_unique<ForeachLoop>(Loc, nullptr, ThenClauseList));
  2792. if (ParseIfBody(CurMultiClass, "then"))
  2793. return true;
  2794. std::unique_ptr<ForeachLoop> Loop = std::move(Loops.back());
  2795. Loops.pop_back();
  2796. if (addEntry(std::move(Loop)))
  2797. return true;
  2798. // Now look for an optional else clause. The if-else syntax has the usual
  2799. // dangling-else ambiguity, and by greedily matching an else here if we can,
  2800. // we implement the usual resolution of pairing with the innermost unmatched
  2801. // if.
  2802. if (consume(tgtok::ElseKW)) {
  2803. // The foreach containing the else-clause uses the same pair of lists as
  2804. // above, but this time, selects SingletonList if the condition is *false*.
  2805. Init *ElseClauseList =
  2806. TernOpInit::get(TernOpInit::IF, Condition, EmptyList, SingletonList,
  2807. BitListTy)
  2808. ->Fold(nullptr);
  2809. Loops.push_back(
  2810. std::make_unique<ForeachLoop>(Loc, nullptr, ElseClauseList));
  2811. if (ParseIfBody(CurMultiClass, "else"))
  2812. return true;
  2813. Loop = std::move(Loops.back());
  2814. Loops.pop_back();
  2815. if (addEntry(std::move(Loop)))
  2816. return true;
  2817. }
  2818. return false;
  2819. }
  2820. /// ParseIfBody - Parse the then-clause or else-clause of an if statement.
  2821. ///
  2822. /// IfBody ::= Object
  2823. /// IfBody ::= '{' ObjectList '}'
  2824. ///
  2825. bool TGParser::ParseIfBody(MultiClass *CurMultiClass, StringRef Kind) {
  2826. TGLocalVarScope *BodyScope = PushLocalScope();
  2827. if (Lex.getCode() != tgtok::l_brace) {
  2828. // A single object.
  2829. if (ParseObject(CurMultiClass))
  2830. return true;
  2831. } else {
  2832. SMLoc BraceLoc = Lex.getLoc();
  2833. // A braced block.
  2834. Lex.Lex(); // eat the '{'.
  2835. // Parse the object list.
  2836. if (ParseObjectList(CurMultiClass))
  2837. return true;
  2838. if (!consume(tgtok::r_brace)) {
  2839. TokError("expected '}' at end of '" + Kind + "' clause");
  2840. return Error(BraceLoc, "to match this '{'");
  2841. }
  2842. }
  2843. PopLocalScope(BodyScope);
  2844. return false;
  2845. }
  2846. /// ParseAssert - Parse an assert statement.
  2847. ///
  2848. /// Assert ::= ASSERT condition , message ;
  2849. bool TGParser::ParseAssert(MultiClass *CurMultiClass, Record *CurRec) {
  2850. assert(Lex.getCode() == tgtok::Assert && "Unknown tok");
  2851. Lex.Lex(); // Eat the 'assert' token.
  2852. SMLoc ConditionLoc = Lex.getLoc();
  2853. Init *Condition = ParseValue(CurRec);
  2854. if (!Condition)
  2855. return true;
  2856. if (!consume(tgtok::comma)) {
  2857. TokError("expected ',' in assert statement");
  2858. return true;
  2859. }
  2860. Init *Message = ParseValue(CurRec);
  2861. if (!Message)
  2862. return true;
  2863. if (!consume(tgtok::semi))
  2864. return TokError("expected ';'");
  2865. if (CurRec)
  2866. CurRec->addAssertion(ConditionLoc, Condition, Message);
  2867. else
  2868. addEntry(std::make_unique<Record::AssertionInfo>(ConditionLoc, Condition,
  2869. Message));
  2870. return false;
  2871. }
  2872. /// ParseClass - Parse a tblgen class definition.
  2873. ///
  2874. /// ClassInst ::= CLASS ID TemplateArgList? ObjectBody
  2875. ///
  2876. bool TGParser::ParseClass() {
  2877. assert(Lex.getCode() == tgtok::Class && "Unexpected token!");
  2878. Lex.Lex();
  2879. if (Lex.getCode() != tgtok::Id)
  2880. return TokError("expected class name after 'class' keyword");
  2881. Record *CurRec = Records.getClass(Lex.getCurStrVal());
  2882. if (CurRec) {
  2883. // If the body was previously defined, this is an error.
  2884. if (!CurRec->getValues().empty() ||
  2885. !CurRec->getSuperClasses().empty() ||
  2886. !CurRec->getTemplateArgs().empty())
  2887. return TokError("Class '" + CurRec->getNameInitAsString() +
  2888. "' already defined");
  2889. } else {
  2890. // If this is the first reference to this class, create and add it.
  2891. auto NewRec =
  2892. std::make_unique<Record>(Lex.getCurStrVal(), Lex.getLoc(), Records,
  2893. /*Class=*/true);
  2894. CurRec = NewRec.get();
  2895. Records.addClass(std::move(NewRec));
  2896. }
  2897. Lex.Lex(); // eat the name.
  2898. // If there are template args, parse them.
  2899. if (Lex.getCode() == tgtok::less)
  2900. if (ParseTemplateArgList(CurRec))
  2901. return true;
  2902. if (ParseObjectBody(CurRec))
  2903. return true;
  2904. if (!NoWarnOnUnusedTemplateArgs)
  2905. CurRec->checkUnusedTemplateArgs();
  2906. return false;
  2907. }
  2908. /// ParseLetList - Parse a non-empty list of assignment expressions into a list
  2909. /// of LetRecords.
  2910. ///
  2911. /// LetList ::= LetItem (',' LetItem)*
  2912. /// LetItem ::= ID OptionalRangeList '=' Value
  2913. ///
  2914. void TGParser::ParseLetList(SmallVectorImpl<LetRecord> &Result) {
  2915. do {
  2916. if (Lex.getCode() != tgtok::Id) {
  2917. TokError("expected identifier in let definition");
  2918. Result.clear();
  2919. return;
  2920. }
  2921. StringInit *Name = StringInit::get(Lex.getCurStrVal());
  2922. SMLoc NameLoc = Lex.getLoc();
  2923. Lex.Lex(); // Eat the identifier.
  2924. // Check for an optional RangeList.
  2925. SmallVector<unsigned, 16> Bits;
  2926. if (ParseOptionalRangeList(Bits)) {
  2927. Result.clear();
  2928. return;
  2929. }
  2930. std::reverse(Bits.begin(), Bits.end());
  2931. if (!consume(tgtok::equal)) {
  2932. TokError("expected '=' in let expression");
  2933. Result.clear();
  2934. return;
  2935. }
  2936. Init *Val = ParseValue(nullptr);
  2937. if (!Val) {
  2938. Result.clear();
  2939. return;
  2940. }
  2941. // Now that we have everything, add the record.
  2942. Result.emplace_back(Name, Bits, Val, NameLoc);
  2943. } while (consume(tgtok::comma));
  2944. }
  2945. /// ParseTopLevelLet - Parse a 'let' at top level. This can be a couple of
  2946. /// different related productions. This works inside multiclasses too.
  2947. ///
  2948. /// Object ::= LET LetList IN '{' ObjectList '}'
  2949. /// Object ::= LET LetList IN Object
  2950. ///
  2951. bool TGParser::ParseTopLevelLet(MultiClass *CurMultiClass) {
  2952. assert(Lex.getCode() == tgtok::Let && "Unexpected token");
  2953. Lex.Lex();
  2954. // Add this entry to the let stack.
  2955. SmallVector<LetRecord, 8> LetInfo;
  2956. ParseLetList(LetInfo);
  2957. if (LetInfo.empty()) return true;
  2958. LetStack.push_back(std::move(LetInfo));
  2959. if (!consume(tgtok::In))
  2960. return TokError("expected 'in' at end of top-level 'let'");
  2961. TGLocalVarScope *LetScope = PushLocalScope();
  2962. // If this is a scalar let, just handle it now
  2963. if (Lex.getCode() != tgtok::l_brace) {
  2964. // LET LetList IN Object
  2965. if (ParseObject(CurMultiClass))
  2966. return true;
  2967. } else { // Object ::= LETCommand '{' ObjectList '}'
  2968. SMLoc BraceLoc = Lex.getLoc();
  2969. // Otherwise, this is a group let.
  2970. Lex.Lex(); // eat the '{'.
  2971. // Parse the object list.
  2972. if (ParseObjectList(CurMultiClass))
  2973. return true;
  2974. if (!consume(tgtok::r_brace)) {
  2975. TokError("expected '}' at end of top level let command");
  2976. return Error(BraceLoc, "to match this '{'");
  2977. }
  2978. }
  2979. PopLocalScope(LetScope);
  2980. // Outside this let scope, this let block is not active.
  2981. LetStack.pop_back();
  2982. return false;
  2983. }
  2984. /// ParseMultiClass - Parse a multiclass definition.
  2985. ///
  2986. /// MultiClassInst ::= MULTICLASS ID TemplateArgList?
  2987. /// ':' BaseMultiClassList '{' MultiClassObject+ '}'
  2988. /// MultiClassObject ::= Assert
  2989. /// MultiClassObject ::= DefInst
  2990. /// MultiClassObject ::= DefMInst
  2991. /// MultiClassObject ::= Defvar
  2992. /// MultiClassObject ::= Foreach
  2993. /// MultiClassObject ::= If
  2994. /// MultiClassObject ::= LETCommand '{' ObjectList '}'
  2995. /// MultiClassObject ::= LETCommand Object
  2996. ///
  2997. bool TGParser::ParseMultiClass() {
  2998. assert(Lex.getCode() == tgtok::MultiClass && "Unexpected token");
  2999. Lex.Lex(); // Eat the multiclass token.
  3000. if (Lex.getCode() != tgtok::Id)
  3001. return TokError("expected identifier after multiclass for name");
  3002. std::string Name = Lex.getCurStrVal();
  3003. auto Result =
  3004. MultiClasses.insert(std::make_pair(Name,
  3005. std::make_unique<MultiClass>(Name, Lex.getLoc(),Records)));
  3006. if (!Result.second)
  3007. return TokError("multiclass '" + Name + "' already defined");
  3008. CurMultiClass = Result.first->second.get();
  3009. Lex.Lex(); // Eat the identifier.
  3010. // If there are template args, parse them.
  3011. if (Lex.getCode() == tgtok::less)
  3012. if (ParseTemplateArgList(nullptr))
  3013. return true;
  3014. bool inherits = false;
  3015. // If there are submulticlasses, parse them.
  3016. if (consume(tgtok::colon)) {
  3017. inherits = true;
  3018. // Read all of the submulticlasses.
  3019. SubMultiClassReference SubMultiClass =
  3020. ParseSubMultiClassReference(CurMultiClass);
  3021. while (true) {
  3022. // Check for error.
  3023. if (!SubMultiClass.MC) return true;
  3024. // Add it.
  3025. if (AddSubMultiClass(CurMultiClass, SubMultiClass))
  3026. return true;
  3027. if (!consume(tgtok::comma))
  3028. break;
  3029. SubMultiClass = ParseSubMultiClassReference(CurMultiClass);
  3030. }
  3031. }
  3032. if (Lex.getCode() != tgtok::l_brace) {
  3033. if (!inherits)
  3034. return TokError("expected '{' in multiclass definition");
  3035. if (!consume(tgtok::semi))
  3036. return TokError("expected ';' in multiclass definition");
  3037. } else {
  3038. if (Lex.Lex() == tgtok::r_brace) // eat the '{'.
  3039. return TokError("multiclass must contain at least one def");
  3040. // A multiclass body introduces a new scope for local variables.
  3041. TGLocalVarScope *MulticlassScope = PushLocalScope();
  3042. while (Lex.getCode() != tgtok::r_brace) {
  3043. switch (Lex.getCode()) {
  3044. default:
  3045. return TokError("expected 'assert', 'def', 'defm', 'defvar', "
  3046. "'foreach', 'if', or 'let' in multiclass body");
  3047. case tgtok::Assert:
  3048. case tgtok::Def:
  3049. case tgtok::Defm:
  3050. case tgtok::Defvar:
  3051. case tgtok::Foreach:
  3052. case tgtok::If:
  3053. case tgtok::Let:
  3054. if (ParseObject(CurMultiClass))
  3055. return true;
  3056. break;
  3057. }
  3058. }
  3059. Lex.Lex(); // eat the '}'.
  3060. // If we have a semicolon, print a gentle error.
  3061. SMLoc SemiLoc = Lex.getLoc();
  3062. if (consume(tgtok::semi)) {
  3063. PrintError(SemiLoc, "A multiclass body should not end with a semicolon");
  3064. PrintNote("Semicolon ignored; remove to eliminate this error");
  3065. }
  3066. PopLocalScope(MulticlassScope);
  3067. }
  3068. if (!NoWarnOnUnusedTemplateArgs)
  3069. CurMultiClass->Rec.checkUnusedTemplateArgs();
  3070. CurMultiClass = nullptr;
  3071. return false;
  3072. }
  3073. /// ParseDefm - Parse the instantiation of a multiclass.
  3074. ///
  3075. /// DefMInst ::= DEFM ID ':' DefmSubClassRef ';'
  3076. ///
  3077. bool TGParser::ParseDefm(MultiClass *CurMultiClass) {
  3078. assert(Lex.getCode() == tgtok::Defm && "Unexpected token!");
  3079. Lex.Lex(); // eat the defm
  3080. Init *DefmName = ParseObjectName(CurMultiClass);
  3081. if (!DefmName)
  3082. return true;
  3083. if (isa<UnsetInit>(DefmName)) {
  3084. DefmName = Records.getNewAnonymousName();
  3085. if (CurMultiClass)
  3086. DefmName = BinOpInit::getStrConcat(
  3087. VarInit::get(QualifiedNameOfImplicitName(CurMultiClass),
  3088. StringRecTy::get()),
  3089. DefmName);
  3090. }
  3091. if (Lex.getCode() != tgtok::colon)
  3092. return TokError("expected ':' after defm identifier");
  3093. // Keep track of the new generated record definitions.
  3094. std::vector<RecordsEntry> NewEntries;
  3095. // This record also inherits from a regular class (non-multiclass)?
  3096. bool InheritFromClass = false;
  3097. // eat the colon.
  3098. Lex.Lex();
  3099. SMLoc SubClassLoc = Lex.getLoc();
  3100. SubClassReference Ref = ParseSubClassReference(nullptr, true);
  3101. while (true) {
  3102. if (!Ref.Rec) return true;
  3103. // To instantiate a multiclass, we get the multiclass and then loop
  3104. // through its template argument names. Substs contains a substitution
  3105. // value for each argument, either the value specified or the default.
  3106. // Then we can resolve the template arguments.
  3107. MultiClass *MC = MultiClasses[std::string(Ref.Rec->getName())].get();
  3108. assert(MC && "Didn't lookup multiclass correctly?");
  3109. ArrayRef<Init *> TemplateVals = Ref.TemplateArgs;
  3110. ArrayRef<Init *> TArgs = MC->Rec.getTemplateArgs();
  3111. SubstStack Substs;
  3112. for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
  3113. if (i < TemplateVals.size()) {
  3114. Substs.emplace_back(TArgs[i], TemplateVals[i]);
  3115. } else {
  3116. Init *Default = MC->Rec.getValue(TArgs[i])->getValue();
  3117. if (!Default->isComplete())
  3118. return Error(SubClassLoc,
  3119. "value not specified for template argument '" +
  3120. TArgs[i]->getAsUnquotedString() + "' (#" +
  3121. Twine(i) + ") of multiclass '" +
  3122. MC->Rec.getNameInitAsString() + "'");
  3123. Substs.emplace_back(TArgs[i], Default);
  3124. }
  3125. }
  3126. Substs.emplace_back(QualifiedNameOfImplicitName(MC), DefmName);
  3127. if (resolve(MC->Entries, Substs, !CurMultiClass && Loops.empty(),
  3128. &NewEntries, &SubClassLoc))
  3129. return true;
  3130. if (!consume(tgtok::comma))
  3131. break;
  3132. if (Lex.getCode() != tgtok::Id)
  3133. return TokError("expected identifier");
  3134. SubClassLoc = Lex.getLoc();
  3135. // A defm can inherit from regular classes (non-multiclasses) as
  3136. // long as they come in the end of the inheritance list.
  3137. InheritFromClass = (Records.getClass(Lex.getCurStrVal()) != nullptr);
  3138. if (InheritFromClass)
  3139. break;
  3140. Ref = ParseSubClassReference(nullptr, true);
  3141. }
  3142. if (InheritFromClass) {
  3143. // Process all the classes to inherit as if they were part of a
  3144. // regular 'def' and inherit all record values.
  3145. SubClassReference SubClass = ParseSubClassReference(nullptr, false);
  3146. while (true) {
  3147. // Check for error.
  3148. if (!SubClass.Rec) return true;
  3149. // Get the expanded definition prototypes and teach them about
  3150. // the record values the current class to inherit has
  3151. for (auto &E : NewEntries) {
  3152. // Add it.
  3153. if (AddSubClass(E, SubClass))
  3154. return true;
  3155. }
  3156. if (!consume(tgtok::comma))
  3157. break;
  3158. SubClass = ParseSubClassReference(nullptr, false);
  3159. }
  3160. }
  3161. for (auto &E : NewEntries) {
  3162. if (ApplyLetStack(E))
  3163. return true;
  3164. addEntry(std::move(E));
  3165. }
  3166. if (!consume(tgtok::semi))
  3167. return TokError("expected ';' at end of defm");
  3168. return false;
  3169. }
  3170. /// ParseObject
  3171. /// Object ::= ClassInst
  3172. /// Object ::= DefInst
  3173. /// Object ::= MultiClassInst
  3174. /// Object ::= DefMInst
  3175. /// Object ::= LETCommand '{' ObjectList '}'
  3176. /// Object ::= LETCommand Object
  3177. /// Object ::= Defset
  3178. /// Object ::= Defvar
  3179. /// Object ::= Assert
  3180. bool TGParser::ParseObject(MultiClass *MC) {
  3181. switch (Lex.getCode()) {
  3182. default:
  3183. return TokError(
  3184. "Expected assert, class, def, defm, defset, foreach, if, or let");
  3185. case tgtok::Assert: return ParseAssert(MC);
  3186. case tgtok::Def: return ParseDef(MC);
  3187. case tgtok::Defm: return ParseDefm(MC);
  3188. case tgtok::Defvar: return ParseDefvar();
  3189. case tgtok::Foreach: return ParseForeach(MC);
  3190. case tgtok::If: return ParseIf(MC);
  3191. case tgtok::Let: return ParseTopLevelLet(MC);
  3192. case tgtok::Defset:
  3193. if (MC)
  3194. return TokError("defset is not allowed inside multiclass");
  3195. return ParseDefset();
  3196. case tgtok::Class:
  3197. if (MC)
  3198. return TokError("class is not allowed inside multiclass");
  3199. if (!Loops.empty())
  3200. return TokError("class is not allowed inside foreach loop");
  3201. return ParseClass();
  3202. case tgtok::MultiClass:
  3203. if (!Loops.empty())
  3204. return TokError("multiclass is not allowed inside foreach loop");
  3205. return ParseMultiClass();
  3206. }
  3207. }
  3208. /// ParseObjectList
  3209. /// ObjectList :== Object*
  3210. bool TGParser::ParseObjectList(MultiClass *MC) {
  3211. while (isObjectStart(Lex.getCode())) {
  3212. if (ParseObject(MC))
  3213. return true;
  3214. }
  3215. return false;
  3216. }
  3217. bool TGParser::ParseFile() {
  3218. Lex.Lex(); // Prime the lexer.
  3219. if (ParseObjectList()) return true;
  3220. // If we have unread input at the end of the file, report it.
  3221. if (Lex.getCode() == tgtok::Eof)
  3222. return false;
  3223. return TokError("Unexpected token at top level");
  3224. }
  3225. // Check the types of the template argument values for a class
  3226. // inheritance, multiclass invocation, or anonymous class invocation.
  3227. // If necessary, replace an argument with a cast to the required type.
  3228. // The argument count has already been checked.
  3229. bool TGParser::CheckTemplateArgValues(SmallVectorImpl<llvm::Init *> &Values,
  3230. SMLoc Loc, Record *ArgsRec) {
  3231. ArrayRef<Init *> TArgs = ArgsRec->getTemplateArgs();
  3232. for (unsigned I = 0, E = Values.size(); I < E; ++I) {
  3233. RecordVal *Arg = ArgsRec->getValue(TArgs[I]);
  3234. RecTy *ArgType = Arg->getType();
  3235. auto *Value = Values[I];
  3236. if (TypedInit *ArgValue = dyn_cast<TypedInit>(Value)) {
  3237. auto *CastValue = ArgValue->getCastTo(ArgType);
  3238. if (CastValue) {
  3239. assert((!isa<TypedInit>(CastValue) ||
  3240. cast<TypedInit>(CastValue)->getType()->typeIsA(ArgType)) &&
  3241. "result of template arg value cast has wrong type");
  3242. Values[I] = CastValue;
  3243. } else {
  3244. PrintFatalError(Loc,
  3245. "Value specified for template argument '" +
  3246. Arg->getNameInitAsString() + "' (#" + Twine(I) +
  3247. ") is of type " + ArgValue->getType()->getAsString() +
  3248. "; expected type " + ArgType->getAsString() + ": " +
  3249. ArgValue->getAsString());
  3250. }
  3251. }
  3252. }
  3253. return false;
  3254. }
  3255. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  3256. LLVM_DUMP_METHOD void RecordsEntry::dump() const {
  3257. if (Loop)
  3258. Loop->dump();
  3259. if (Rec)
  3260. Rec->dump();
  3261. }
  3262. LLVM_DUMP_METHOD void ForeachLoop::dump() const {
  3263. errs() << "foreach " << IterVar->getAsString() << " = "
  3264. << ListValue->getAsString() << " in {\n";
  3265. for (const auto &E : Entries)
  3266. E.dump();
  3267. errs() << "}\n";
  3268. }
  3269. LLVM_DUMP_METHOD void MultiClass::dump() const {
  3270. errs() << "Record:\n";
  3271. Rec.dump();
  3272. errs() << "Defs:\n";
  3273. for (const auto &E : Entries)
  3274. E.dump();
  3275. }
  3276. #endif