TGParser.cpp 119 KB

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