LLParser.cpp 333 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999
  1. //===-- LLParser.cpp - Parser Class ---------------------------------------===//
  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. // This file defines the parser class for .ll files.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "llvm/AsmParser/LLParser.h"
  13. #include "llvm/ADT/APSInt.h"
  14. #include "llvm/ADT/DenseMap.h"
  15. #include "llvm/ADT/ScopeExit.h"
  16. #include "llvm/ADT/STLExtras.h"
  17. #include "llvm/ADT/SmallPtrSet.h"
  18. #include "llvm/AsmParser/LLToken.h"
  19. #include "llvm/AsmParser/SlotMapping.h"
  20. #include "llvm/BinaryFormat/Dwarf.h"
  21. #include "llvm/IR/Argument.h"
  22. #include "llvm/IR/AutoUpgrade.h"
  23. #include "llvm/IR/BasicBlock.h"
  24. #include "llvm/IR/CallingConv.h"
  25. #include "llvm/IR/Comdat.h"
  26. #include "llvm/IR/ConstantRange.h"
  27. #include "llvm/IR/Constants.h"
  28. #include "llvm/IR/DebugInfoMetadata.h"
  29. #include "llvm/IR/DerivedTypes.h"
  30. #include "llvm/IR/Function.h"
  31. #include "llvm/IR/GlobalIFunc.h"
  32. #include "llvm/IR/GlobalObject.h"
  33. #include "llvm/IR/InlineAsm.h"
  34. #include "llvm/IR/Instructions.h"
  35. #include "llvm/IR/Intrinsics.h"
  36. #include "llvm/IR/LLVMContext.h"
  37. #include "llvm/IR/Metadata.h"
  38. #include "llvm/IR/Module.h"
  39. #include "llvm/IR/Operator.h"
  40. #include "llvm/IR/Value.h"
  41. #include "llvm/IR/ValueSymbolTable.h"
  42. #include "llvm/Support/Casting.h"
  43. #include "llvm/Support/ErrorHandling.h"
  44. #include "llvm/Support/MathExtras.h"
  45. #include "llvm/Support/ModRef.h"
  46. #include "llvm/Support/SaveAndRestore.h"
  47. #include "llvm/Support/raw_ostream.h"
  48. #include <algorithm>
  49. #include <cassert>
  50. #include <cstring>
  51. #include <optional>
  52. #include <vector>
  53. using namespace llvm;
  54. static std::string getTypeString(Type *T) {
  55. std::string Result;
  56. raw_string_ostream Tmp(Result);
  57. Tmp << *T;
  58. return Tmp.str();
  59. }
  60. /// Run: module ::= toplevelentity*
  61. bool LLParser::Run(bool UpgradeDebugInfo,
  62. DataLayoutCallbackTy DataLayoutCallback) {
  63. // Prime the lexer.
  64. Lex.Lex();
  65. if (Context.shouldDiscardValueNames())
  66. return error(
  67. Lex.getLoc(),
  68. "Can't read textual IR with a Context that discards named Values");
  69. if (M) {
  70. if (parseTargetDefinitions(DataLayoutCallback))
  71. return true;
  72. }
  73. return parseTopLevelEntities() || validateEndOfModule(UpgradeDebugInfo) ||
  74. validateEndOfIndex();
  75. }
  76. bool LLParser::parseStandaloneConstantValue(Constant *&C,
  77. const SlotMapping *Slots) {
  78. restoreParsingState(Slots);
  79. Lex.Lex();
  80. Type *Ty = nullptr;
  81. if (parseType(Ty) || parseConstantValue(Ty, C))
  82. return true;
  83. if (Lex.getKind() != lltok::Eof)
  84. return error(Lex.getLoc(), "expected end of string");
  85. return false;
  86. }
  87. bool LLParser::parseTypeAtBeginning(Type *&Ty, unsigned &Read,
  88. const SlotMapping *Slots) {
  89. restoreParsingState(Slots);
  90. Lex.Lex();
  91. Read = 0;
  92. SMLoc Start = Lex.getLoc();
  93. Ty = nullptr;
  94. if (parseType(Ty))
  95. return true;
  96. SMLoc End = Lex.getLoc();
  97. Read = End.getPointer() - Start.getPointer();
  98. return false;
  99. }
  100. void LLParser::restoreParsingState(const SlotMapping *Slots) {
  101. if (!Slots)
  102. return;
  103. NumberedVals = Slots->GlobalValues;
  104. NumberedMetadata = Slots->MetadataNodes;
  105. for (const auto &I : Slots->NamedTypes)
  106. NamedTypes.insert(
  107. std::make_pair(I.getKey(), std::make_pair(I.second, LocTy())));
  108. for (const auto &I : Slots->Types)
  109. NumberedTypes.insert(
  110. std::make_pair(I.first, std::make_pair(I.second, LocTy())));
  111. }
  112. /// validateEndOfModule - Do final validity and basic correctness checks at the
  113. /// end of the module.
  114. bool LLParser::validateEndOfModule(bool UpgradeDebugInfo) {
  115. if (!M)
  116. return false;
  117. // Handle any function attribute group forward references.
  118. for (const auto &RAG : ForwardRefAttrGroups) {
  119. Value *V = RAG.first;
  120. const std::vector<unsigned> &Attrs = RAG.second;
  121. AttrBuilder B(Context);
  122. for (const auto &Attr : Attrs) {
  123. auto R = NumberedAttrBuilders.find(Attr);
  124. if (R != NumberedAttrBuilders.end())
  125. B.merge(R->second);
  126. }
  127. if (Function *Fn = dyn_cast<Function>(V)) {
  128. AttributeList AS = Fn->getAttributes();
  129. AttrBuilder FnAttrs(M->getContext(), AS.getFnAttrs());
  130. AS = AS.removeFnAttributes(Context);
  131. FnAttrs.merge(B);
  132. // If the alignment was parsed as an attribute, move to the alignment
  133. // field.
  134. if (MaybeAlign A = FnAttrs.getAlignment()) {
  135. Fn->setAlignment(A);
  136. FnAttrs.removeAttribute(Attribute::Alignment);
  137. }
  138. AS = AS.addFnAttributes(Context, FnAttrs);
  139. Fn->setAttributes(AS);
  140. } else if (CallInst *CI = dyn_cast<CallInst>(V)) {
  141. AttributeList AS = CI->getAttributes();
  142. AttrBuilder FnAttrs(M->getContext(), AS.getFnAttrs());
  143. AS = AS.removeFnAttributes(Context);
  144. FnAttrs.merge(B);
  145. AS = AS.addFnAttributes(Context, FnAttrs);
  146. CI->setAttributes(AS);
  147. } else if (InvokeInst *II = dyn_cast<InvokeInst>(V)) {
  148. AttributeList AS = II->getAttributes();
  149. AttrBuilder FnAttrs(M->getContext(), AS.getFnAttrs());
  150. AS = AS.removeFnAttributes(Context);
  151. FnAttrs.merge(B);
  152. AS = AS.addFnAttributes(Context, FnAttrs);
  153. II->setAttributes(AS);
  154. } else if (CallBrInst *CBI = dyn_cast<CallBrInst>(V)) {
  155. AttributeList AS = CBI->getAttributes();
  156. AttrBuilder FnAttrs(M->getContext(), AS.getFnAttrs());
  157. AS = AS.removeFnAttributes(Context);
  158. FnAttrs.merge(B);
  159. AS = AS.addFnAttributes(Context, FnAttrs);
  160. CBI->setAttributes(AS);
  161. } else if (auto *GV = dyn_cast<GlobalVariable>(V)) {
  162. AttrBuilder Attrs(M->getContext(), GV->getAttributes());
  163. Attrs.merge(B);
  164. GV->setAttributes(AttributeSet::get(Context,Attrs));
  165. } else {
  166. llvm_unreachable("invalid object with forward attribute group reference");
  167. }
  168. }
  169. // If there are entries in ForwardRefBlockAddresses at this point, the
  170. // function was never defined.
  171. if (!ForwardRefBlockAddresses.empty())
  172. return error(ForwardRefBlockAddresses.begin()->first.Loc,
  173. "expected function name in blockaddress");
  174. auto ResolveForwardRefDSOLocalEquivalents = [&](const ValID &GVRef,
  175. GlobalValue *FwdRef) {
  176. GlobalValue *GV = nullptr;
  177. if (GVRef.Kind == ValID::t_GlobalName) {
  178. GV = M->getNamedValue(GVRef.StrVal);
  179. } else if (GVRef.UIntVal < NumberedVals.size()) {
  180. GV = dyn_cast<GlobalValue>(NumberedVals[GVRef.UIntVal]);
  181. }
  182. if (!GV)
  183. return error(GVRef.Loc, "unknown function '" + GVRef.StrVal +
  184. "' referenced by dso_local_equivalent");
  185. if (!GV->getValueType()->isFunctionTy())
  186. return error(GVRef.Loc,
  187. "expected a function, alias to function, or ifunc "
  188. "in dso_local_equivalent");
  189. auto *Equiv = DSOLocalEquivalent::get(GV);
  190. FwdRef->replaceAllUsesWith(Equiv);
  191. FwdRef->eraseFromParent();
  192. return false;
  193. };
  194. // If there are entries in ForwardRefDSOLocalEquivalentIDs/Names at this
  195. // point, they are references after the function was defined. Resolve those
  196. // now.
  197. for (auto &Iter : ForwardRefDSOLocalEquivalentIDs) {
  198. if (ResolveForwardRefDSOLocalEquivalents(Iter.first, Iter.second))
  199. return true;
  200. }
  201. for (auto &Iter : ForwardRefDSOLocalEquivalentNames) {
  202. if (ResolveForwardRefDSOLocalEquivalents(Iter.first, Iter.second))
  203. return true;
  204. }
  205. ForwardRefDSOLocalEquivalentIDs.clear();
  206. ForwardRefDSOLocalEquivalentNames.clear();
  207. for (const auto &NT : NumberedTypes)
  208. if (NT.second.second.isValid())
  209. return error(NT.second.second,
  210. "use of undefined type '%" + Twine(NT.first) + "'");
  211. for (StringMap<std::pair<Type*, LocTy> >::iterator I =
  212. NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I)
  213. if (I->second.second.isValid())
  214. return error(I->second.second,
  215. "use of undefined type named '" + I->getKey() + "'");
  216. if (!ForwardRefComdats.empty())
  217. return error(ForwardRefComdats.begin()->second,
  218. "use of undefined comdat '$" +
  219. ForwardRefComdats.begin()->first + "'");
  220. if (!ForwardRefVals.empty())
  221. return error(ForwardRefVals.begin()->second.second,
  222. "use of undefined value '@" + ForwardRefVals.begin()->first +
  223. "'");
  224. if (!ForwardRefValIDs.empty())
  225. return error(ForwardRefValIDs.begin()->second.second,
  226. "use of undefined value '@" +
  227. Twine(ForwardRefValIDs.begin()->first) + "'");
  228. if (!ForwardRefMDNodes.empty())
  229. return error(ForwardRefMDNodes.begin()->second.second,
  230. "use of undefined metadata '!" +
  231. Twine(ForwardRefMDNodes.begin()->first) + "'");
  232. // Resolve metadata cycles.
  233. for (auto &N : NumberedMetadata) {
  234. if (N.second && !N.second->isResolved())
  235. N.second->resolveCycles();
  236. }
  237. for (auto *Inst : InstsWithTBAATag) {
  238. MDNode *MD = Inst->getMetadata(LLVMContext::MD_tbaa);
  239. assert(MD && "UpgradeInstWithTBAATag should have a TBAA tag");
  240. auto *UpgradedMD = UpgradeTBAANode(*MD);
  241. if (MD != UpgradedMD)
  242. Inst->setMetadata(LLVMContext::MD_tbaa, UpgradedMD);
  243. }
  244. // Look for intrinsic functions and CallInst that need to be upgraded. We use
  245. // make_early_inc_range here because we may remove some functions.
  246. for (Function &F : llvm::make_early_inc_range(*M))
  247. UpgradeCallsToIntrinsic(&F);
  248. if (UpgradeDebugInfo)
  249. llvm::UpgradeDebugInfo(*M);
  250. UpgradeModuleFlags(*M);
  251. UpgradeSectionAttributes(*M);
  252. if (!Slots)
  253. return false;
  254. // Initialize the slot mapping.
  255. // Because by this point we've parsed and validated everything, we can "steal"
  256. // the mapping from LLParser as it doesn't need it anymore.
  257. Slots->GlobalValues = std::move(NumberedVals);
  258. Slots->MetadataNodes = std::move(NumberedMetadata);
  259. for (const auto &I : NamedTypes)
  260. Slots->NamedTypes.insert(std::make_pair(I.getKey(), I.second.first));
  261. for (const auto &I : NumberedTypes)
  262. Slots->Types.insert(std::make_pair(I.first, I.second.first));
  263. return false;
  264. }
  265. /// Do final validity and basic correctness checks at the end of the index.
  266. bool LLParser::validateEndOfIndex() {
  267. if (!Index)
  268. return false;
  269. if (!ForwardRefValueInfos.empty())
  270. return error(ForwardRefValueInfos.begin()->second.front().second,
  271. "use of undefined summary '^" +
  272. Twine(ForwardRefValueInfos.begin()->first) + "'");
  273. if (!ForwardRefAliasees.empty())
  274. return error(ForwardRefAliasees.begin()->second.front().second,
  275. "use of undefined summary '^" +
  276. Twine(ForwardRefAliasees.begin()->first) + "'");
  277. if (!ForwardRefTypeIds.empty())
  278. return error(ForwardRefTypeIds.begin()->second.front().second,
  279. "use of undefined type id summary '^" +
  280. Twine(ForwardRefTypeIds.begin()->first) + "'");
  281. return false;
  282. }
  283. //===----------------------------------------------------------------------===//
  284. // Top-Level Entities
  285. //===----------------------------------------------------------------------===//
  286. bool LLParser::parseTargetDefinitions(DataLayoutCallbackTy DataLayoutCallback) {
  287. // Delay parsing of the data layout string until the target triple is known.
  288. // Then, pass both the the target triple and the tentative data layout string
  289. // to DataLayoutCallback, allowing to override the DL string.
  290. // This enables importing modules with invalid DL strings.
  291. std::string TentativeDLStr = M->getDataLayoutStr();
  292. LocTy DLStrLoc;
  293. bool Done = false;
  294. while (!Done) {
  295. switch (Lex.getKind()) {
  296. case lltok::kw_target:
  297. if (parseTargetDefinition(TentativeDLStr, DLStrLoc))
  298. return true;
  299. break;
  300. case lltok::kw_source_filename:
  301. if (parseSourceFileName())
  302. return true;
  303. break;
  304. default:
  305. Done = true;
  306. }
  307. }
  308. // Run the override callback to potentially change the data layout string, and
  309. // parse the data layout string.
  310. if (auto LayoutOverride =
  311. DataLayoutCallback(M->getTargetTriple(), TentativeDLStr)) {
  312. TentativeDLStr = *LayoutOverride;
  313. DLStrLoc = {};
  314. }
  315. Expected<DataLayout> MaybeDL = DataLayout::parse(TentativeDLStr);
  316. if (!MaybeDL)
  317. return error(DLStrLoc, toString(MaybeDL.takeError()));
  318. M->setDataLayout(MaybeDL.get());
  319. return false;
  320. }
  321. bool LLParser::parseTopLevelEntities() {
  322. // If there is no Module, then parse just the summary index entries.
  323. if (!M) {
  324. while (true) {
  325. switch (Lex.getKind()) {
  326. case lltok::Eof:
  327. return false;
  328. case lltok::SummaryID:
  329. if (parseSummaryEntry())
  330. return true;
  331. break;
  332. case lltok::kw_source_filename:
  333. if (parseSourceFileName())
  334. return true;
  335. break;
  336. default:
  337. // Skip everything else
  338. Lex.Lex();
  339. }
  340. }
  341. }
  342. while (true) {
  343. switch (Lex.getKind()) {
  344. default:
  345. return tokError("expected top-level entity");
  346. case lltok::Eof: return false;
  347. case lltok::kw_declare:
  348. if (parseDeclare())
  349. return true;
  350. break;
  351. case lltok::kw_define:
  352. if (parseDefine())
  353. return true;
  354. break;
  355. case lltok::kw_module:
  356. if (parseModuleAsm())
  357. return true;
  358. break;
  359. case lltok::LocalVarID:
  360. if (parseUnnamedType())
  361. return true;
  362. break;
  363. case lltok::LocalVar:
  364. if (parseNamedType())
  365. return true;
  366. break;
  367. case lltok::GlobalID:
  368. if (parseUnnamedGlobal())
  369. return true;
  370. break;
  371. case lltok::GlobalVar:
  372. if (parseNamedGlobal())
  373. return true;
  374. break;
  375. case lltok::ComdatVar: if (parseComdat()) return true; break;
  376. case lltok::exclaim:
  377. if (parseStandaloneMetadata())
  378. return true;
  379. break;
  380. case lltok::SummaryID:
  381. if (parseSummaryEntry())
  382. return true;
  383. break;
  384. case lltok::MetadataVar:
  385. if (parseNamedMetadata())
  386. return true;
  387. break;
  388. case lltok::kw_attributes:
  389. if (parseUnnamedAttrGrp())
  390. return true;
  391. break;
  392. case lltok::kw_uselistorder:
  393. if (parseUseListOrder())
  394. return true;
  395. break;
  396. case lltok::kw_uselistorder_bb:
  397. if (parseUseListOrderBB())
  398. return true;
  399. break;
  400. }
  401. }
  402. }
  403. /// toplevelentity
  404. /// ::= 'module' 'asm' STRINGCONSTANT
  405. bool LLParser::parseModuleAsm() {
  406. assert(Lex.getKind() == lltok::kw_module);
  407. Lex.Lex();
  408. std::string AsmStr;
  409. if (parseToken(lltok::kw_asm, "expected 'module asm'") ||
  410. parseStringConstant(AsmStr))
  411. return true;
  412. M->appendModuleInlineAsm(AsmStr);
  413. return false;
  414. }
  415. /// toplevelentity
  416. /// ::= 'target' 'triple' '=' STRINGCONSTANT
  417. /// ::= 'target' 'datalayout' '=' STRINGCONSTANT
  418. bool LLParser::parseTargetDefinition(std::string &TentativeDLStr,
  419. LocTy &DLStrLoc) {
  420. assert(Lex.getKind() == lltok::kw_target);
  421. std::string Str;
  422. switch (Lex.Lex()) {
  423. default:
  424. return tokError("unknown target property");
  425. case lltok::kw_triple:
  426. Lex.Lex();
  427. if (parseToken(lltok::equal, "expected '=' after target triple") ||
  428. parseStringConstant(Str))
  429. return true;
  430. M->setTargetTriple(Str);
  431. return false;
  432. case lltok::kw_datalayout:
  433. Lex.Lex();
  434. if (parseToken(lltok::equal, "expected '=' after target datalayout"))
  435. return true;
  436. DLStrLoc = Lex.getLoc();
  437. if (parseStringConstant(TentativeDLStr))
  438. return true;
  439. return false;
  440. }
  441. }
  442. /// toplevelentity
  443. /// ::= 'source_filename' '=' STRINGCONSTANT
  444. bool LLParser::parseSourceFileName() {
  445. assert(Lex.getKind() == lltok::kw_source_filename);
  446. Lex.Lex();
  447. if (parseToken(lltok::equal, "expected '=' after source_filename") ||
  448. parseStringConstant(SourceFileName))
  449. return true;
  450. if (M)
  451. M->setSourceFileName(SourceFileName);
  452. return false;
  453. }
  454. /// parseUnnamedType:
  455. /// ::= LocalVarID '=' 'type' type
  456. bool LLParser::parseUnnamedType() {
  457. LocTy TypeLoc = Lex.getLoc();
  458. unsigned TypeID = Lex.getUIntVal();
  459. Lex.Lex(); // eat LocalVarID;
  460. if (parseToken(lltok::equal, "expected '=' after name") ||
  461. parseToken(lltok::kw_type, "expected 'type' after '='"))
  462. return true;
  463. Type *Result = nullptr;
  464. if (parseStructDefinition(TypeLoc, "", NumberedTypes[TypeID], Result))
  465. return true;
  466. if (!isa<StructType>(Result)) {
  467. std::pair<Type*, LocTy> &Entry = NumberedTypes[TypeID];
  468. if (Entry.first)
  469. return error(TypeLoc, "non-struct types may not be recursive");
  470. Entry.first = Result;
  471. Entry.second = SMLoc();
  472. }
  473. return false;
  474. }
  475. /// toplevelentity
  476. /// ::= LocalVar '=' 'type' type
  477. bool LLParser::parseNamedType() {
  478. std::string Name = Lex.getStrVal();
  479. LocTy NameLoc = Lex.getLoc();
  480. Lex.Lex(); // eat LocalVar.
  481. if (parseToken(lltok::equal, "expected '=' after name") ||
  482. parseToken(lltok::kw_type, "expected 'type' after name"))
  483. return true;
  484. Type *Result = nullptr;
  485. if (parseStructDefinition(NameLoc, Name, NamedTypes[Name], Result))
  486. return true;
  487. if (!isa<StructType>(Result)) {
  488. std::pair<Type*, LocTy> &Entry = NamedTypes[Name];
  489. if (Entry.first)
  490. return error(NameLoc, "non-struct types may not be recursive");
  491. Entry.first = Result;
  492. Entry.second = SMLoc();
  493. }
  494. return false;
  495. }
  496. /// toplevelentity
  497. /// ::= 'declare' FunctionHeader
  498. bool LLParser::parseDeclare() {
  499. assert(Lex.getKind() == lltok::kw_declare);
  500. Lex.Lex();
  501. std::vector<std::pair<unsigned, MDNode *>> MDs;
  502. while (Lex.getKind() == lltok::MetadataVar) {
  503. unsigned MDK;
  504. MDNode *N;
  505. if (parseMetadataAttachment(MDK, N))
  506. return true;
  507. MDs.push_back({MDK, N});
  508. }
  509. Function *F;
  510. if (parseFunctionHeader(F, false))
  511. return true;
  512. for (auto &MD : MDs)
  513. F->addMetadata(MD.first, *MD.second);
  514. return false;
  515. }
  516. /// toplevelentity
  517. /// ::= 'define' FunctionHeader (!dbg !56)* '{' ...
  518. bool LLParser::parseDefine() {
  519. assert(Lex.getKind() == lltok::kw_define);
  520. Lex.Lex();
  521. Function *F;
  522. return parseFunctionHeader(F, true) || parseOptionalFunctionMetadata(*F) ||
  523. parseFunctionBody(*F);
  524. }
  525. /// parseGlobalType
  526. /// ::= 'constant'
  527. /// ::= 'global'
  528. bool LLParser::parseGlobalType(bool &IsConstant) {
  529. if (Lex.getKind() == lltok::kw_constant)
  530. IsConstant = true;
  531. else if (Lex.getKind() == lltok::kw_global)
  532. IsConstant = false;
  533. else {
  534. IsConstant = false;
  535. return tokError("expected 'global' or 'constant'");
  536. }
  537. Lex.Lex();
  538. return false;
  539. }
  540. bool LLParser::parseOptionalUnnamedAddr(
  541. GlobalVariable::UnnamedAddr &UnnamedAddr) {
  542. if (EatIfPresent(lltok::kw_unnamed_addr))
  543. UnnamedAddr = GlobalValue::UnnamedAddr::Global;
  544. else if (EatIfPresent(lltok::kw_local_unnamed_addr))
  545. UnnamedAddr = GlobalValue::UnnamedAddr::Local;
  546. else
  547. UnnamedAddr = GlobalValue::UnnamedAddr::None;
  548. return false;
  549. }
  550. /// parseUnnamedGlobal:
  551. /// OptionalVisibility (ALIAS | IFUNC) ...
  552. /// OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
  553. /// OptionalDLLStorageClass
  554. /// ... -> global variable
  555. /// GlobalID '=' OptionalVisibility (ALIAS | IFUNC) ...
  556. /// GlobalID '=' OptionalLinkage OptionalPreemptionSpecifier
  557. /// OptionalVisibility
  558. /// OptionalDLLStorageClass
  559. /// ... -> global variable
  560. bool LLParser::parseUnnamedGlobal() {
  561. unsigned VarID = NumberedVals.size();
  562. std::string Name;
  563. LocTy NameLoc = Lex.getLoc();
  564. // Handle the GlobalID form.
  565. if (Lex.getKind() == lltok::GlobalID) {
  566. if (Lex.getUIntVal() != VarID)
  567. return error(Lex.getLoc(),
  568. "variable expected to be numbered '%" + Twine(VarID) + "'");
  569. Lex.Lex(); // eat GlobalID;
  570. if (parseToken(lltok::equal, "expected '=' after name"))
  571. return true;
  572. }
  573. bool HasLinkage;
  574. unsigned Linkage, Visibility, DLLStorageClass;
  575. bool DSOLocal;
  576. GlobalVariable::ThreadLocalMode TLM;
  577. GlobalVariable::UnnamedAddr UnnamedAddr;
  578. if (parseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
  579. DSOLocal) ||
  580. parseOptionalThreadLocal(TLM) || parseOptionalUnnamedAddr(UnnamedAddr))
  581. return true;
  582. switch (Lex.getKind()) {
  583. default:
  584. return parseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
  585. DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
  586. case lltok::kw_alias:
  587. case lltok::kw_ifunc:
  588. return parseAliasOrIFunc(Name, NameLoc, Linkage, Visibility,
  589. DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
  590. }
  591. }
  592. /// parseNamedGlobal:
  593. /// GlobalVar '=' OptionalVisibility (ALIAS | IFUNC) ...
  594. /// GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
  595. /// OptionalVisibility OptionalDLLStorageClass
  596. /// ... -> global variable
  597. bool LLParser::parseNamedGlobal() {
  598. assert(Lex.getKind() == lltok::GlobalVar);
  599. LocTy NameLoc = Lex.getLoc();
  600. std::string Name = Lex.getStrVal();
  601. Lex.Lex();
  602. bool HasLinkage;
  603. unsigned Linkage, Visibility, DLLStorageClass;
  604. bool DSOLocal;
  605. GlobalVariable::ThreadLocalMode TLM;
  606. GlobalVariable::UnnamedAddr UnnamedAddr;
  607. if (parseToken(lltok::equal, "expected '=' in global variable") ||
  608. parseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
  609. DSOLocal) ||
  610. parseOptionalThreadLocal(TLM) || parseOptionalUnnamedAddr(UnnamedAddr))
  611. return true;
  612. switch (Lex.getKind()) {
  613. default:
  614. return parseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
  615. DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
  616. case lltok::kw_alias:
  617. case lltok::kw_ifunc:
  618. return parseAliasOrIFunc(Name, NameLoc, Linkage, Visibility,
  619. DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
  620. }
  621. }
  622. bool LLParser::parseComdat() {
  623. assert(Lex.getKind() == lltok::ComdatVar);
  624. std::string Name = Lex.getStrVal();
  625. LocTy NameLoc = Lex.getLoc();
  626. Lex.Lex();
  627. if (parseToken(lltok::equal, "expected '=' here"))
  628. return true;
  629. if (parseToken(lltok::kw_comdat, "expected comdat keyword"))
  630. return tokError("expected comdat type");
  631. Comdat::SelectionKind SK;
  632. switch (Lex.getKind()) {
  633. default:
  634. return tokError("unknown selection kind");
  635. case lltok::kw_any:
  636. SK = Comdat::Any;
  637. break;
  638. case lltok::kw_exactmatch:
  639. SK = Comdat::ExactMatch;
  640. break;
  641. case lltok::kw_largest:
  642. SK = Comdat::Largest;
  643. break;
  644. case lltok::kw_nodeduplicate:
  645. SK = Comdat::NoDeduplicate;
  646. break;
  647. case lltok::kw_samesize:
  648. SK = Comdat::SameSize;
  649. break;
  650. }
  651. Lex.Lex();
  652. // See if the comdat was forward referenced, if so, use the comdat.
  653. Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
  654. Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
  655. if (I != ComdatSymTab.end() && !ForwardRefComdats.erase(Name))
  656. return error(NameLoc, "redefinition of comdat '$" + Name + "'");
  657. Comdat *C;
  658. if (I != ComdatSymTab.end())
  659. C = &I->second;
  660. else
  661. C = M->getOrInsertComdat(Name);
  662. C->setSelectionKind(SK);
  663. return false;
  664. }
  665. // MDString:
  666. // ::= '!' STRINGCONSTANT
  667. bool LLParser::parseMDString(MDString *&Result) {
  668. std::string Str;
  669. if (parseStringConstant(Str))
  670. return true;
  671. Result = MDString::get(Context, Str);
  672. return false;
  673. }
  674. // MDNode:
  675. // ::= '!' MDNodeNumber
  676. bool LLParser::parseMDNodeID(MDNode *&Result) {
  677. // !{ ..., !42, ... }
  678. LocTy IDLoc = Lex.getLoc();
  679. unsigned MID = 0;
  680. if (parseUInt32(MID))
  681. return true;
  682. // If not a forward reference, just return it now.
  683. if (NumberedMetadata.count(MID)) {
  684. Result = NumberedMetadata[MID];
  685. return false;
  686. }
  687. // Otherwise, create MDNode forward reference.
  688. auto &FwdRef = ForwardRefMDNodes[MID];
  689. FwdRef = std::make_pair(MDTuple::getTemporary(Context, std::nullopt), IDLoc);
  690. Result = FwdRef.first.get();
  691. NumberedMetadata[MID].reset(Result);
  692. return false;
  693. }
  694. /// parseNamedMetadata:
  695. /// !foo = !{ !1, !2 }
  696. bool LLParser::parseNamedMetadata() {
  697. assert(Lex.getKind() == lltok::MetadataVar);
  698. std::string Name = Lex.getStrVal();
  699. Lex.Lex();
  700. if (parseToken(lltok::equal, "expected '=' here") ||
  701. parseToken(lltok::exclaim, "Expected '!' here") ||
  702. parseToken(lltok::lbrace, "Expected '{' here"))
  703. return true;
  704. NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
  705. if (Lex.getKind() != lltok::rbrace)
  706. do {
  707. MDNode *N = nullptr;
  708. // parse DIExpressions inline as a special case. They are still MDNodes,
  709. // so they can still appear in named metadata. Remove this logic if they
  710. // become plain Metadata.
  711. if (Lex.getKind() == lltok::MetadataVar &&
  712. Lex.getStrVal() == "DIExpression") {
  713. if (parseDIExpression(N, /*IsDistinct=*/false))
  714. return true;
  715. // DIArgLists should only appear inline in a function, as they may
  716. // contain LocalAsMetadata arguments which require a function context.
  717. } else if (Lex.getKind() == lltok::MetadataVar &&
  718. Lex.getStrVal() == "DIArgList") {
  719. return tokError("found DIArgList outside of function");
  720. } else if (parseToken(lltok::exclaim, "Expected '!' here") ||
  721. parseMDNodeID(N)) {
  722. return true;
  723. }
  724. NMD->addOperand(N);
  725. } while (EatIfPresent(lltok::comma));
  726. return parseToken(lltok::rbrace, "expected end of metadata node");
  727. }
  728. /// parseStandaloneMetadata:
  729. /// !42 = !{...}
  730. bool LLParser::parseStandaloneMetadata() {
  731. assert(Lex.getKind() == lltok::exclaim);
  732. Lex.Lex();
  733. unsigned MetadataID = 0;
  734. MDNode *Init;
  735. if (parseUInt32(MetadataID) || parseToken(lltok::equal, "expected '=' here"))
  736. return true;
  737. // Detect common error, from old metadata syntax.
  738. if (Lex.getKind() == lltok::Type)
  739. return tokError("unexpected type in metadata definition");
  740. bool IsDistinct = EatIfPresent(lltok::kw_distinct);
  741. if (Lex.getKind() == lltok::MetadataVar) {
  742. if (parseSpecializedMDNode(Init, IsDistinct))
  743. return true;
  744. } else if (parseToken(lltok::exclaim, "Expected '!' here") ||
  745. parseMDTuple(Init, IsDistinct))
  746. return true;
  747. // See if this was forward referenced, if so, handle it.
  748. auto FI = ForwardRefMDNodes.find(MetadataID);
  749. if (FI != ForwardRefMDNodes.end()) {
  750. auto *ToReplace = FI->second.first.get();
  751. // DIAssignID has its own special forward-reference "replacement" for
  752. // attachments (the temporary attachments are never actually attached).
  753. if (isa<DIAssignID>(Init)) {
  754. for (auto *Inst : TempDIAssignIDAttachments[ToReplace]) {
  755. assert(!Inst->getMetadata(LLVMContext::MD_DIAssignID) &&
  756. "Inst unexpectedly already has DIAssignID attachment");
  757. Inst->setMetadata(LLVMContext::MD_DIAssignID, Init);
  758. }
  759. }
  760. ToReplace->replaceAllUsesWith(Init);
  761. ForwardRefMDNodes.erase(FI);
  762. assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
  763. } else {
  764. if (NumberedMetadata.count(MetadataID))
  765. return tokError("Metadata id is already used");
  766. NumberedMetadata[MetadataID].reset(Init);
  767. }
  768. return false;
  769. }
  770. // Skips a single module summary entry.
  771. bool LLParser::skipModuleSummaryEntry() {
  772. // Each module summary entry consists of a tag for the entry
  773. // type, followed by a colon, then the fields which may be surrounded by
  774. // nested sets of parentheses. The "tag:" looks like a Label. Once parsing
  775. // support is in place we will look for the tokens corresponding to the
  776. // expected tags.
  777. if (Lex.getKind() != lltok::kw_gv && Lex.getKind() != lltok::kw_module &&
  778. Lex.getKind() != lltok::kw_typeid && Lex.getKind() != lltok::kw_flags &&
  779. Lex.getKind() != lltok::kw_blockcount)
  780. return tokError(
  781. "Expected 'gv', 'module', 'typeid', 'flags' or 'blockcount' at the "
  782. "start of summary entry");
  783. if (Lex.getKind() == lltok::kw_flags)
  784. return parseSummaryIndexFlags();
  785. if (Lex.getKind() == lltok::kw_blockcount)
  786. return parseBlockCount();
  787. Lex.Lex();
  788. if (parseToken(lltok::colon, "expected ':' at start of summary entry") ||
  789. parseToken(lltok::lparen, "expected '(' at start of summary entry"))
  790. return true;
  791. // Now walk through the parenthesized entry, until the number of open
  792. // parentheses goes back down to 0 (the first '(' was parsed above).
  793. unsigned NumOpenParen = 1;
  794. do {
  795. switch (Lex.getKind()) {
  796. case lltok::lparen:
  797. NumOpenParen++;
  798. break;
  799. case lltok::rparen:
  800. NumOpenParen--;
  801. break;
  802. case lltok::Eof:
  803. return tokError("found end of file while parsing summary entry");
  804. default:
  805. // Skip everything in between parentheses.
  806. break;
  807. }
  808. Lex.Lex();
  809. } while (NumOpenParen > 0);
  810. return false;
  811. }
  812. /// SummaryEntry
  813. /// ::= SummaryID '=' GVEntry | ModuleEntry | TypeIdEntry
  814. bool LLParser::parseSummaryEntry() {
  815. assert(Lex.getKind() == lltok::SummaryID);
  816. unsigned SummaryID = Lex.getUIntVal();
  817. // For summary entries, colons should be treated as distinct tokens,
  818. // not an indication of the end of a label token.
  819. Lex.setIgnoreColonInIdentifiers(true);
  820. Lex.Lex();
  821. if (parseToken(lltok::equal, "expected '=' here"))
  822. return true;
  823. // If we don't have an index object, skip the summary entry.
  824. if (!Index)
  825. return skipModuleSummaryEntry();
  826. bool result = false;
  827. switch (Lex.getKind()) {
  828. case lltok::kw_gv:
  829. result = parseGVEntry(SummaryID);
  830. break;
  831. case lltok::kw_module:
  832. result = parseModuleEntry(SummaryID);
  833. break;
  834. case lltok::kw_typeid:
  835. result = parseTypeIdEntry(SummaryID);
  836. break;
  837. case lltok::kw_typeidCompatibleVTable:
  838. result = parseTypeIdCompatibleVtableEntry(SummaryID);
  839. break;
  840. case lltok::kw_flags:
  841. result = parseSummaryIndexFlags();
  842. break;
  843. case lltok::kw_blockcount:
  844. result = parseBlockCount();
  845. break;
  846. default:
  847. result = error(Lex.getLoc(), "unexpected summary kind");
  848. break;
  849. }
  850. Lex.setIgnoreColonInIdentifiers(false);
  851. return result;
  852. }
  853. static bool isValidVisibilityForLinkage(unsigned V, unsigned L) {
  854. return !GlobalValue::isLocalLinkage((GlobalValue::LinkageTypes)L) ||
  855. (GlobalValue::VisibilityTypes)V == GlobalValue::DefaultVisibility;
  856. }
  857. static bool isValidDLLStorageClassForLinkage(unsigned S, unsigned L) {
  858. return !GlobalValue::isLocalLinkage((GlobalValue::LinkageTypes)L) ||
  859. (GlobalValue::DLLStorageClassTypes)S == GlobalValue::DefaultStorageClass;
  860. }
  861. // If there was an explicit dso_local, update GV. In the absence of an explicit
  862. // dso_local we keep the default value.
  863. static void maybeSetDSOLocal(bool DSOLocal, GlobalValue &GV) {
  864. if (DSOLocal)
  865. GV.setDSOLocal(true);
  866. }
  867. static std::string typeComparisonErrorMessage(StringRef Message, Type *Ty1,
  868. Type *Ty2) {
  869. std::string ErrString;
  870. raw_string_ostream ErrOS(ErrString);
  871. ErrOS << Message << " (" << *Ty1 << " vs " << *Ty2 << ")";
  872. return ErrOS.str();
  873. }
  874. /// parseAliasOrIFunc:
  875. /// ::= GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
  876. /// OptionalVisibility OptionalDLLStorageClass
  877. /// OptionalThreadLocal OptionalUnnamedAddr
  878. /// 'alias|ifunc' AliaseeOrResolver SymbolAttrs*
  879. ///
  880. /// AliaseeOrResolver
  881. /// ::= TypeAndValue
  882. ///
  883. /// SymbolAttrs
  884. /// ::= ',' 'partition' StringConstant
  885. ///
  886. /// Everything through OptionalUnnamedAddr has already been parsed.
  887. ///
  888. bool LLParser::parseAliasOrIFunc(const std::string &Name, LocTy NameLoc,
  889. unsigned L, unsigned Visibility,
  890. unsigned DLLStorageClass, bool DSOLocal,
  891. GlobalVariable::ThreadLocalMode TLM,
  892. GlobalVariable::UnnamedAddr UnnamedAddr) {
  893. bool IsAlias;
  894. if (Lex.getKind() == lltok::kw_alias)
  895. IsAlias = true;
  896. else if (Lex.getKind() == lltok::kw_ifunc)
  897. IsAlias = false;
  898. else
  899. llvm_unreachable("Not an alias or ifunc!");
  900. Lex.Lex();
  901. GlobalValue::LinkageTypes Linkage = (GlobalValue::LinkageTypes) L;
  902. if(IsAlias && !GlobalAlias::isValidLinkage(Linkage))
  903. return error(NameLoc, "invalid linkage type for alias");
  904. if (!isValidVisibilityForLinkage(Visibility, L))
  905. return error(NameLoc,
  906. "symbol with local linkage must have default visibility");
  907. if (!isValidDLLStorageClassForLinkage(DLLStorageClass, L))
  908. return error(NameLoc,
  909. "symbol with local linkage cannot have a DLL storage class");
  910. Type *Ty;
  911. LocTy ExplicitTypeLoc = Lex.getLoc();
  912. if (parseType(Ty) ||
  913. parseToken(lltok::comma, "expected comma after alias or ifunc's type"))
  914. return true;
  915. Constant *Aliasee;
  916. LocTy AliaseeLoc = Lex.getLoc();
  917. if (Lex.getKind() != lltok::kw_bitcast &&
  918. Lex.getKind() != lltok::kw_getelementptr &&
  919. Lex.getKind() != lltok::kw_addrspacecast &&
  920. Lex.getKind() != lltok::kw_inttoptr) {
  921. if (parseGlobalTypeAndValue(Aliasee))
  922. return true;
  923. } else {
  924. // The bitcast dest type is not present, it is implied by the dest type.
  925. ValID ID;
  926. if (parseValID(ID, /*PFS=*/nullptr))
  927. return true;
  928. if (ID.Kind != ValID::t_Constant)
  929. return error(AliaseeLoc, "invalid aliasee");
  930. Aliasee = ID.ConstantVal;
  931. }
  932. Type *AliaseeType = Aliasee->getType();
  933. auto *PTy = dyn_cast<PointerType>(AliaseeType);
  934. if (!PTy)
  935. return error(AliaseeLoc, "An alias or ifunc must have pointer type");
  936. unsigned AddrSpace = PTy->getAddressSpace();
  937. if (IsAlias) {
  938. if (!PTy->isOpaqueOrPointeeTypeMatches(Ty))
  939. return error(
  940. ExplicitTypeLoc,
  941. typeComparisonErrorMessage(
  942. "explicit pointee type doesn't match operand's pointee type", Ty,
  943. PTy->getNonOpaquePointerElementType()));
  944. } else {
  945. if (!PTy->isOpaque() &&
  946. !PTy->getNonOpaquePointerElementType()->isFunctionTy())
  947. return error(ExplicitTypeLoc,
  948. "explicit pointee type should be a function type");
  949. }
  950. GlobalValue *GVal = nullptr;
  951. // See if the alias was forward referenced, if so, prepare to replace the
  952. // forward reference.
  953. if (!Name.empty()) {
  954. auto I = ForwardRefVals.find(Name);
  955. if (I != ForwardRefVals.end()) {
  956. GVal = I->second.first;
  957. ForwardRefVals.erase(Name);
  958. } else if (M->getNamedValue(Name)) {
  959. return error(NameLoc, "redefinition of global '@" + Name + "'");
  960. }
  961. } else {
  962. auto I = ForwardRefValIDs.find(NumberedVals.size());
  963. if (I != ForwardRefValIDs.end()) {
  964. GVal = I->second.first;
  965. ForwardRefValIDs.erase(I);
  966. }
  967. }
  968. // Okay, create the alias/ifunc but do not insert it into the module yet.
  969. std::unique_ptr<GlobalAlias> GA;
  970. std::unique_ptr<GlobalIFunc> GI;
  971. GlobalValue *GV;
  972. if (IsAlias) {
  973. GA.reset(GlobalAlias::create(Ty, AddrSpace,
  974. (GlobalValue::LinkageTypes)Linkage, Name,
  975. Aliasee, /*Parent*/ nullptr));
  976. GV = GA.get();
  977. } else {
  978. GI.reset(GlobalIFunc::create(Ty, AddrSpace,
  979. (GlobalValue::LinkageTypes)Linkage, Name,
  980. Aliasee, /*Parent*/ nullptr));
  981. GV = GI.get();
  982. }
  983. GV->setThreadLocalMode(TLM);
  984. GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
  985. GV->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
  986. GV->setUnnamedAddr(UnnamedAddr);
  987. maybeSetDSOLocal(DSOLocal, *GV);
  988. // At this point we've parsed everything except for the IndirectSymbolAttrs.
  989. // Now parse them if there are any.
  990. while (Lex.getKind() == lltok::comma) {
  991. Lex.Lex();
  992. if (Lex.getKind() == lltok::kw_partition) {
  993. Lex.Lex();
  994. GV->setPartition(Lex.getStrVal());
  995. if (parseToken(lltok::StringConstant, "expected partition string"))
  996. return true;
  997. } else {
  998. return tokError("unknown alias or ifunc property!");
  999. }
  1000. }
  1001. if (Name.empty())
  1002. NumberedVals.push_back(GV);
  1003. if (GVal) {
  1004. // Verify that types agree.
  1005. if (GVal->getType() != GV->getType())
  1006. return error(
  1007. ExplicitTypeLoc,
  1008. "forward reference and definition of alias have different types");
  1009. // If they agree, just RAUW the old value with the alias and remove the
  1010. // forward ref info.
  1011. GVal->replaceAllUsesWith(GV);
  1012. GVal->eraseFromParent();
  1013. }
  1014. // Insert into the module, we know its name won't collide now.
  1015. if (IsAlias)
  1016. M->getAliasList().push_back(GA.release());
  1017. else
  1018. M->getIFuncList().push_back(GI.release());
  1019. assert(GV->getName() == Name && "Should not be a name conflict!");
  1020. return false;
  1021. }
  1022. static bool isSanitizer(lltok::Kind Kind) {
  1023. switch (Kind) {
  1024. case lltok::kw_no_sanitize_address:
  1025. case lltok::kw_no_sanitize_hwaddress:
  1026. case lltok::kw_sanitize_memtag:
  1027. case lltok::kw_sanitize_address_dyninit:
  1028. return true;
  1029. default:
  1030. return false;
  1031. }
  1032. }
  1033. bool LLParser::parseSanitizer(GlobalVariable *GV) {
  1034. using SanitizerMetadata = GlobalValue::SanitizerMetadata;
  1035. SanitizerMetadata Meta;
  1036. if (GV->hasSanitizerMetadata())
  1037. Meta = GV->getSanitizerMetadata();
  1038. switch (Lex.getKind()) {
  1039. case lltok::kw_no_sanitize_address:
  1040. Meta.NoAddress = true;
  1041. break;
  1042. case lltok::kw_no_sanitize_hwaddress:
  1043. Meta.NoHWAddress = true;
  1044. break;
  1045. case lltok::kw_sanitize_memtag:
  1046. Meta.Memtag = true;
  1047. break;
  1048. case lltok::kw_sanitize_address_dyninit:
  1049. Meta.IsDynInit = true;
  1050. break;
  1051. default:
  1052. return tokError("non-sanitizer token passed to LLParser::parseSanitizer()");
  1053. }
  1054. GV->setSanitizerMetadata(Meta);
  1055. Lex.Lex();
  1056. return false;
  1057. }
  1058. /// parseGlobal
  1059. /// ::= GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
  1060. /// OptionalVisibility OptionalDLLStorageClass
  1061. /// OptionalThreadLocal OptionalUnnamedAddr OptionalAddrSpace
  1062. /// OptionalExternallyInitialized GlobalType Type Const OptionalAttrs
  1063. /// ::= OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
  1064. /// OptionalDLLStorageClass OptionalThreadLocal OptionalUnnamedAddr
  1065. /// OptionalAddrSpace OptionalExternallyInitialized GlobalType Type
  1066. /// Const OptionalAttrs
  1067. ///
  1068. /// Everything up to and including OptionalUnnamedAddr has been parsed
  1069. /// already.
  1070. ///
  1071. bool LLParser::parseGlobal(const std::string &Name, LocTy NameLoc,
  1072. unsigned Linkage, bool HasLinkage,
  1073. unsigned Visibility, unsigned DLLStorageClass,
  1074. bool DSOLocal, GlobalVariable::ThreadLocalMode TLM,
  1075. GlobalVariable::UnnamedAddr UnnamedAddr) {
  1076. if (!isValidVisibilityForLinkage(Visibility, Linkage))
  1077. return error(NameLoc,
  1078. "symbol with local linkage must have default visibility");
  1079. if (!isValidDLLStorageClassForLinkage(DLLStorageClass, Linkage))
  1080. return error(NameLoc,
  1081. "symbol with local linkage cannot have a DLL storage class");
  1082. unsigned AddrSpace;
  1083. bool IsConstant, IsExternallyInitialized;
  1084. LocTy IsExternallyInitializedLoc;
  1085. LocTy TyLoc;
  1086. Type *Ty = nullptr;
  1087. if (parseOptionalAddrSpace(AddrSpace) ||
  1088. parseOptionalToken(lltok::kw_externally_initialized,
  1089. IsExternallyInitialized,
  1090. &IsExternallyInitializedLoc) ||
  1091. parseGlobalType(IsConstant) || parseType(Ty, TyLoc))
  1092. return true;
  1093. // If the linkage is specified and is external, then no initializer is
  1094. // present.
  1095. Constant *Init = nullptr;
  1096. if (!HasLinkage ||
  1097. !GlobalValue::isValidDeclarationLinkage(
  1098. (GlobalValue::LinkageTypes)Linkage)) {
  1099. if (parseGlobalValue(Ty, Init))
  1100. return true;
  1101. }
  1102. if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))
  1103. return error(TyLoc, "invalid type for global variable");
  1104. GlobalValue *GVal = nullptr;
  1105. // See if the global was forward referenced, if so, use the global.
  1106. if (!Name.empty()) {
  1107. auto I = ForwardRefVals.find(Name);
  1108. if (I != ForwardRefVals.end()) {
  1109. GVal = I->second.first;
  1110. ForwardRefVals.erase(I);
  1111. } else if (M->getNamedValue(Name)) {
  1112. return error(NameLoc, "redefinition of global '@" + Name + "'");
  1113. }
  1114. } else {
  1115. auto I = ForwardRefValIDs.find(NumberedVals.size());
  1116. if (I != ForwardRefValIDs.end()) {
  1117. GVal = I->second.first;
  1118. ForwardRefValIDs.erase(I);
  1119. }
  1120. }
  1121. GlobalVariable *GV = new GlobalVariable(
  1122. *M, Ty, false, GlobalValue::ExternalLinkage, nullptr, Name, nullptr,
  1123. GlobalVariable::NotThreadLocal, AddrSpace);
  1124. if (Name.empty())
  1125. NumberedVals.push_back(GV);
  1126. // Set the parsed properties on the global.
  1127. if (Init)
  1128. GV->setInitializer(Init);
  1129. GV->setConstant(IsConstant);
  1130. GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
  1131. maybeSetDSOLocal(DSOLocal, *GV);
  1132. GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
  1133. GV->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
  1134. GV->setExternallyInitialized(IsExternallyInitialized);
  1135. GV->setThreadLocalMode(TLM);
  1136. GV->setUnnamedAddr(UnnamedAddr);
  1137. if (GVal) {
  1138. if (GVal->getType() != Ty->getPointerTo(AddrSpace))
  1139. return error(
  1140. TyLoc,
  1141. "forward reference and definition of global have different types");
  1142. GVal->replaceAllUsesWith(GV);
  1143. GVal->eraseFromParent();
  1144. }
  1145. // parse attributes on the global.
  1146. while (Lex.getKind() == lltok::comma) {
  1147. Lex.Lex();
  1148. if (Lex.getKind() == lltok::kw_section) {
  1149. Lex.Lex();
  1150. GV->setSection(Lex.getStrVal());
  1151. if (parseToken(lltok::StringConstant, "expected global section string"))
  1152. return true;
  1153. } else if (Lex.getKind() == lltok::kw_partition) {
  1154. Lex.Lex();
  1155. GV->setPartition(Lex.getStrVal());
  1156. if (parseToken(lltok::StringConstant, "expected partition string"))
  1157. return true;
  1158. } else if (Lex.getKind() == lltok::kw_align) {
  1159. MaybeAlign Alignment;
  1160. if (parseOptionalAlignment(Alignment))
  1161. return true;
  1162. GV->setAlignment(Alignment);
  1163. } else if (Lex.getKind() == lltok::MetadataVar) {
  1164. if (parseGlobalObjectMetadataAttachment(*GV))
  1165. return true;
  1166. } else if (isSanitizer(Lex.getKind())) {
  1167. if (parseSanitizer(GV))
  1168. return true;
  1169. } else {
  1170. Comdat *C;
  1171. if (parseOptionalComdat(Name, C))
  1172. return true;
  1173. if (C)
  1174. GV->setComdat(C);
  1175. else
  1176. return tokError("unknown global variable property!");
  1177. }
  1178. }
  1179. AttrBuilder Attrs(M->getContext());
  1180. LocTy BuiltinLoc;
  1181. std::vector<unsigned> FwdRefAttrGrps;
  1182. if (parseFnAttributeValuePairs(Attrs, FwdRefAttrGrps, false, BuiltinLoc))
  1183. return true;
  1184. if (Attrs.hasAttributes() || !FwdRefAttrGrps.empty()) {
  1185. GV->setAttributes(AttributeSet::get(Context, Attrs));
  1186. ForwardRefAttrGroups[GV] = FwdRefAttrGrps;
  1187. }
  1188. return false;
  1189. }
  1190. /// parseUnnamedAttrGrp
  1191. /// ::= 'attributes' AttrGrpID '=' '{' AttrValPair+ '}'
  1192. bool LLParser::parseUnnamedAttrGrp() {
  1193. assert(Lex.getKind() == lltok::kw_attributes);
  1194. LocTy AttrGrpLoc = Lex.getLoc();
  1195. Lex.Lex();
  1196. if (Lex.getKind() != lltok::AttrGrpID)
  1197. return tokError("expected attribute group id");
  1198. unsigned VarID = Lex.getUIntVal();
  1199. std::vector<unsigned> unused;
  1200. LocTy BuiltinLoc;
  1201. Lex.Lex();
  1202. if (parseToken(lltok::equal, "expected '=' here") ||
  1203. parseToken(lltok::lbrace, "expected '{' here"))
  1204. return true;
  1205. auto R = NumberedAttrBuilders.find(VarID);
  1206. if (R == NumberedAttrBuilders.end())
  1207. R = NumberedAttrBuilders.emplace(VarID, AttrBuilder(M->getContext())).first;
  1208. if (parseFnAttributeValuePairs(R->second, unused, true, BuiltinLoc) ||
  1209. parseToken(lltok::rbrace, "expected end of attribute group"))
  1210. return true;
  1211. if (!R->second.hasAttributes())
  1212. return error(AttrGrpLoc, "attribute group has no attributes");
  1213. return false;
  1214. }
  1215. static Attribute::AttrKind tokenToAttribute(lltok::Kind Kind) {
  1216. switch (Kind) {
  1217. #define GET_ATTR_NAMES
  1218. #define ATTRIBUTE_ENUM(ENUM_NAME, DISPLAY_NAME) \
  1219. case lltok::kw_##DISPLAY_NAME: \
  1220. return Attribute::ENUM_NAME;
  1221. #include "llvm/IR/Attributes.inc"
  1222. default:
  1223. return Attribute::None;
  1224. }
  1225. }
  1226. bool LLParser::parseEnumAttribute(Attribute::AttrKind Attr, AttrBuilder &B,
  1227. bool InAttrGroup) {
  1228. if (Attribute::isTypeAttrKind(Attr))
  1229. return parseRequiredTypeAttr(B, Lex.getKind(), Attr);
  1230. switch (Attr) {
  1231. case Attribute::Alignment: {
  1232. MaybeAlign Alignment;
  1233. if (InAttrGroup) {
  1234. uint32_t Value = 0;
  1235. Lex.Lex();
  1236. if (parseToken(lltok::equal, "expected '=' here") || parseUInt32(Value))
  1237. return true;
  1238. Alignment = Align(Value);
  1239. } else {
  1240. if (parseOptionalAlignment(Alignment, true))
  1241. return true;
  1242. }
  1243. B.addAlignmentAttr(Alignment);
  1244. return false;
  1245. }
  1246. case Attribute::StackAlignment: {
  1247. unsigned Alignment;
  1248. if (InAttrGroup) {
  1249. Lex.Lex();
  1250. if (parseToken(lltok::equal, "expected '=' here") ||
  1251. parseUInt32(Alignment))
  1252. return true;
  1253. } else {
  1254. if (parseOptionalStackAlignment(Alignment))
  1255. return true;
  1256. }
  1257. B.addStackAlignmentAttr(Alignment);
  1258. return false;
  1259. }
  1260. case Attribute::AllocSize: {
  1261. unsigned ElemSizeArg;
  1262. std::optional<unsigned> NumElemsArg;
  1263. if (parseAllocSizeArguments(ElemSizeArg, NumElemsArg))
  1264. return true;
  1265. B.addAllocSizeAttr(ElemSizeArg, NumElemsArg);
  1266. return false;
  1267. }
  1268. case Attribute::VScaleRange: {
  1269. unsigned MinValue, MaxValue;
  1270. if (parseVScaleRangeArguments(MinValue, MaxValue))
  1271. return true;
  1272. B.addVScaleRangeAttr(MinValue,
  1273. MaxValue > 0 ? MaxValue : std::optional<unsigned>());
  1274. return false;
  1275. }
  1276. case Attribute::Dereferenceable: {
  1277. uint64_t Bytes;
  1278. if (parseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
  1279. return true;
  1280. B.addDereferenceableAttr(Bytes);
  1281. return false;
  1282. }
  1283. case Attribute::DereferenceableOrNull: {
  1284. uint64_t Bytes;
  1285. if (parseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
  1286. return true;
  1287. B.addDereferenceableOrNullAttr(Bytes);
  1288. return false;
  1289. }
  1290. case Attribute::UWTable: {
  1291. UWTableKind Kind;
  1292. if (parseOptionalUWTableKind(Kind))
  1293. return true;
  1294. B.addUWTableAttr(Kind);
  1295. return false;
  1296. }
  1297. case Attribute::AllocKind: {
  1298. AllocFnKind Kind = AllocFnKind::Unknown;
  1299. if (parseAllocKind(Kind))
  1300. return true;
  1301. B.addAllocKindAttr(Kind);
  1302. return false;
  1303. }
  1304. case Attribute::Memory: {
  1305. std::optional<MemoryEffects> ME = parseMemoryAttr();
  1306. if (!ME)
  1307. return true;
  1308. B.addMemoryAttr(*ME);
  1309. return false;
  1310. }
  1311. default:
  1312. B.addAttribute(Attr);
  1313. Lex.Lex();
  1314. return false;
  1315. }
  1316. }
  1317. static bool upgradeMemoryAttr(MemoryEffects &ME, lltok::Kind Kind) {
  1318. switch (Kind) {
  1319. case lltok::kw_readnone:
  1320. ME &= MemoryEffects::none();
  1321. return true;
  1322. case lltok::kw_readonly:
  1323. ME &= MemoryEffects::readOnly();
  1324. return true;
  1325. case lltok::kw_writeonly:
  1326. ME &= MemoryEffects::writeOnly();
  1327. return true;
  1328. case lltok::kw_argmemonly:
  1329. ME &= MemoryEffects::argMemOnly();
  1330. return true;
  1331. case lltok::kw_inaccessiblememonly:
  1332. ME &= MemoryEffects::inaccessibleMemOnly();
  1333. return true;
  1334. case lltok::kw_inaccessiblemem_or_argmemonly:
  1335. ME &= MemoryEffects::inaccessibleOrArgMemOnly();
  1336. return true;
  1337. default:
  1338. return false;
  1339. }
  1340. }
  1341. /// parseFnAttributeValuePairs
  1342. /// ::= <attr> | <attr> '=' <value>
  1343. bool LLParser::parseFnAttributeValuePairs(AttrBuilder &B,
  1344. std::vector<unsigned> &FwdRefAttrGrps,
  1345. bool InAttrGrp, LocTy &BuiltinLoc) {
  1346. bool HaveError = false;
  1347. B.clear();
  1348. MemoryEffects ME = MemoryEffects::unknown();
  1349. while (true) {
  1350. lltok::Kind Token = Lex.getKind();
  1351. if (Token == lltok::rbrace)
  1352. break; // Finished.
  1353. if (Token == lltok::StringConstant) {
  1354. if (parseStringAttribute(B))
  1355. return true;
  1356. continue;
  1357. }
  1358. if (Token == lltok::AttrGrpID) {
  1359. // Allow a function to reference an attribute group:
  1360. //
  1361. // define void @foo() #1 { ... }
  1362. if (InAttrGrp) {
  1363. HaveError |= error(
  1364. Lex.getLoc(),
  1365. "cannot have an attribute group reference in an attribute group");
  1366. } else {
  1367. // Save the reference to the attribute group. We'll fill it in later.
  1368. FwdRefAttrGrps.push_back(Lex.getUIntVal());
  1369. }
  1370. Lex.Lex();
  1371. continue;
  1372. }
  1373. SMLoc Loc = Lex.getLoc();
  1374. if (Token == lltok::kw_builtin)
  1375. BuiltinLoc = Loc;
  1376. if (upgradeMemoryAttr(ME, Token)) {
  1377. Lex.Lex();
  1378. continue;
  1379. }
  1380. Attribute::AttrKind Attr = tokenToAttribute(Token);
  1381. if (Attr == Attribute::None) {
  1382. if (!InAttrGrp)
  1383. break;
  1384. return error(Lex.getLoc(), "unterminated attribute group");
  1385. }
  1386. if (parseEnumAttribute(Attr, B, InAttrGrp))
  1387. return true;
  1388. // As a hack, we allow function alignment to be initially parsed as an
  1389. // attribute on a function declaration/definition or added to an attribute
  1390. // group and later moved to the alignment field.
  1391. if (!Attribute::canUseAsFnAttr(Attr) && Attr != Attribute::Alignment)
  1392. HaveError |= error(Loc, "this attribute does not apply to functions");
  1393. }
  1394. if (ME != MemoryEffects::unknown())
  1395. B.addMemoryAttr(ME);
  1396. return HaveError;
  1397. }
  1398. //===----------------------------------------------------------------------===//
  1399. // GlobalValue Reference/Resolution Routines.
  1400. //===----------------------------------------------------------------------===//
  1401. static inline GlobalValue *createGlobalFwdRef(Module *M, PointerType *PTy) {
  1402. // For opaque pointers, the used global type does not matter. We will later
  1403. // RAUW it with a global/function of the correct type.
  1404. if (PTy->isOpaque())
  1405. return new GlobalVariable(*M, Type::getInt8Ty(M->getContext()), false,
  1406. GlobalValue::ExternalWeakLinkage, nullptr, "",
  1407. nullptr, GlobalVariable::NotThreadLocal,
  1408. PTy->getAddressSpace());
  1409. Type *ElemTy = PTy->getNonOpaquePointerElementType();
  1410. if (auto *FT = dyn_cast<FunctionType>(ElemTy))
  1411. return Function::Create(FT, GlobalValue::ExternalWeakLinkage,
  1412. PTy->getAddressSpace(), "", M);
  1413. else
  1414. return new GlobalVariable(
  1415. *M, ElemTy, false, GlobalValue::ExternalWeakLinkage, nullptr, "",
  1416. nullptr, GlobalVariable::NotThreadLocal, PTy->getAddressSpace());
  1417. }
  1418. Value *LLParser::checkValidVariableType(LocTy Loc, const Twine &Name, Type *Ty,
  1419. Value *Val) {
  1420. Type *ValTy = Val->getType();
  1421. if (ValTy == Ty)
  1422. return Val;
  1423. if (Ty->isLabelTy())
  1424. error(Loc, "'" + Name + "' is not a basic block");
  1425. else
  1426. error(Loc, "'" + Name + "' defined with type '" +
  1427. getTypeString(Val->getType()) + "' but expected '" +
  1428. getTypeString(Ty) + "'");
  1429. return nullptr;
  1430. }
  1431. /// getGlobalVal - Get a value with the specified name or ID, creating a
  1432. /// forward reference record if needed. This can return null if the value
  1433. /// exists but does not have the right type.
  1434. GlobalValue *LLParser::getGlobalVal(const std::string &Name, Type *Ty,
  1435. LocTy Loc) {
  1436. PointerType *PTy = dyn_cast<PointerType>(Ty);
  1437. if (!PTy) {
  1438. error(Loc, "global variable reference must have pointer type");
  1439. return nullptr;
  1440. }
  1441. // Look this name up in the normal function symbol table.
  1442. GlobalValue *Val =
  1443. cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
  1444. // If this is a forward reference for the value, see if we already created a
  1445. // forward ref record.
  1446. if (!Val) {
  1447. auto I = ForwardRefVals.find(Name);
  1448. if (I != ForwardRefVals.end())
  1449. Val = I->second.first;
  1450. }
  1451. // If we have the value in the symbol table or fwd-ref table, return it.
  1452. if (Val)
  1453. return cast_or_null<GlobalValue>(
  1454. checkValidVariableType(Loc, "@" + Name, Ty, Val));
  1455. // Otherwise, create a new forward reference for this value and remember it.
  1456. GlobalValue *FwdVal = createGlobalFwdRef(M, PTy);
  1457. ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
  1458. return FwdVal;
  1459. }
  1460. GlobalValue *LLParser::getGlobalVal(unsigned ID, Type *Ty, LocTy Loc) {
  1461. PointerType *PTy = dyn_cast<PointerType>(Ty);
  1462. if (!PTy) {
  1463. error(Loc, "global variable reference must have pointer type");
  1464. return nullptr;
  1465. }
  1466. GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
  1467. // If this is a forward reference for the value, see if we already created a
  1468. // forward ref record.
  1469. if (!Val) {
  1470. auto I = ForwardRefValIDs.find(ID);
  1471. if (I != ForwardRefValIDs.end())
  1472. Val = I->second.first;
  1473. }
  1474. // If we have the value in the symbol table or fwd-ref table, return it.
  1475. if (Val)
  1476. return cast_or_null<GlobalValue>(
  1477. checkValidVariableType(Loc, "@" + Twine(ID), Ty, Val));
  1478. // Otherwise, create a new forward reference for this value and remember it.
  1479. GlobalValue *FwdVal = createGlobalFwdRef(M, PTy);
  1480. ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
  1481. return FwdVal;
  1482. }
  1483. //===----------------------------------------------------------------------===//
  1484. // Comdat Reference/Resolution Routines.
  1485. //===----------------------------------------------------------------------===//
  1486. Comdat *LLParser::getComdat(const std::string &Name, LocTy Loc) {
  1487. // Look this name up in the comdat symbol table.
  1488. Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
  1489. Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
  1490. if (I != ComdatSymTab.end())
  1491. return &I->second;
  1492. // Otherwise, create a new forward reference for this value and remember it.
  1493. Comdat *C = M->getOrInsertComdat(Name);
  1494. ForwardRefComdats[Name] = Loc;
  1495. return C;
  1496. }
  1497. //===----------------------------------------------------------------------===//
  1498. // Helper Routines.
  1499. //===----------------------------------------------------------------------===//
  1500. /// parseToken - If the current token has the specified kind, eat it and return
  1501. /// success. Otherwise, emit the specified error and return failure.
  1502. bool LLParser::parseToken(lltok::Kind T, const char *ErrMsg) {
  1503. if (Lex.getKind() != T)
  1504. return tokError(ErrMsg);
  1505. Lex.Lex();
  1506. return false;
  1507. }
  1508. /// parseStringConstant
  1509. /// ::= StringConstant
  1510. bool LLParser::parseStringConstant(std::string &Result) {
  1511. if (Lex.getKind() != lltok::StringConstant)
  1512. return tokError("expected string constant");
  1513. Result = Lex.getStrVal();
  1514. Lex.Lex();
  1515. return false;
  1516. }
  1517. /// parseUInt32
  1518. /// ::= uint32
  1519. bool LLParser::parseUInt32(uint32_t &Val) {
  1520. if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
  1521. return tokError("expected integer");
  1522. uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
  1523. if (Val64 != unsigned(Val64))
  1524. return tokError("expected 32-bit integer (too large)");
  1525. Val = Val64;
  1526. Lex.Lex();
  1527. return false;
  1528. }
  1529. /// parseUInt64
  1530. /// ::= uint64
  1531. bool LLParser::parseUInt64(uint64_t &Val) {
  1532. if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
  1533. return tokError("expected integer");
  1534. Val = Lex.getAPSIntVal().getLimitedValue();
  1535. Lex.Lex();
  1536. return false;
  1537. }
  1538. /// parseTLSModel
  1539. /// := 'localdynamic'
  1540. /// := 'initialexec'
  1541. /// := 'localexec'
  1542. bool LLParser::parseTLSModel(GlobalVariable::ThreadLocalMode &TLM) {
  1543. switch (Lex.getKind()) {
  1544. default:
  1545. return tokError("expected localdynamic, initialexec or localexec");
  1546. case lltok::kw_localdynamic:
  1547. TLM = GlobalVariable::LocalDynamicTLSModel;
  1548. break;
  1549. case lltok::kw_initialexec:
  1550. TLM = GlobalVariable::InitialExecTLSModel;
  1551. break;
  1552. case lltok::kw_localexec:
  1553. TLM = GlobalVariable::LocalExecTLSModel;
  1554. break;
  1555. }
  1556. Lex.Lex();
  1557. return false;
  1558. }
  1559. /// parseOptionalThreadLocal
  1560. /// := /*empty*/
  1561. /// := 'thread_local'
  1562. /// := 'thread_local' '(' tlsmodel ')'
  1563. bool LLParser::parseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) {
  1564. TLM = GlobalVariable::NotThreadLocal;
  1565. if (!EatIfPresent(lltok::kw_thread_local))
  1566. return false;
  1567. TLM = GlobalVariable::GeneralDynamicTLSModel;
  1568. if (Lex.getKind() == lltok::lparen) {
  1569. Lex.Lex();
  1570. return parseTLSModel(TLM) ||
  1571. parseToken(lltok::rparen, "expected ')' after thread local model");
  1572. }
  1573. return false;
  1574. }
  1575. /// parseOptionalAddrSpace
  1576. /// := /*empty*/
  1577. /// := 'addrspace' '(' uint32 ')'
  1578. bool LLParser::parseOptionalAddrSpace(unsigned &AddrSpace, unsigned DefaultAS) {
  1579. AddrSpace = DefaultAS;
  1580. if (!EatIfPresent(lltok::kw_addrspace))
  1581. return false;
  1582. auto ParseAddrspaceValue = [&](unsigned &AddrSpace) -> bool {
  1583. if (Lex.getKind() == lltok::StringConstant) {
  1584. auto AddrSpaceStr = Lex.getStrVal();
  1585. if (AddrSpaceStr == "A") {
  1586. AddrSpace = M->getDataLayout().getAllocaAddrSpace();
  1587. } else if (AddrSpaceStr == "G") {
  1588. AddrSpace = M->getDataLayout().getDefaultGlobalsAddressSpace();
  1589. } else if (AddrSpaceStr == "P") {
  1590. AddrSpace = M->getDataLayout().getProgramAddressSpace();
  1591. } else {
  1592. return tokError("invalid symbolic addrspace '" + AddrSpaceStr + "'");
  1593. }
  1594. Lex.Lex();
  1595. return false;
  1596. }
  1597. if (Lex.getKind() != lltok::APSInt)
  1598. return tokError("expected integer or string constant");
  1599. SMLoc Loc = Lex.getLoc();
  1600. if (parseUInt32(AddrSpace))
  1601. return true;
  1602. if (!isUInt<24>(AddrSpace))
  1603. return error(Loc, "invalid address space, must be a 24-bit integer");
  1604. return false;
  1605. };
  1606. return parseToken(lltok::lparen, "expected '(' in address space") ||
  1607. ParseAddrspaceValue(AddrSpace) ||
  1608. parseToken(lltok::rparen, "expected ')' in address space");
  1609. }
  1610. /// parseStringAttribute
  1611. /// := StringConstant
  1612. /// := StringConstant '=' StringConstant
  1613. bool LLParser::parseStringAttribute(AttrBuilder &B) {
  1614. std::string Attr = Lex.getStrVal();
  1615. Lex.Lex();
  1616. std::string Val;
  1617. if (EatIfPresent(lltok::equal) && parseStringConstant(Val))
  1618. return true;
  1619. B.addAttribute(Attr, Val);
  1620. return false;
  1621. }
  1622. /// Parse a potentially empty list of parameter or return attributes.
  1623. bool LLParser::parseOptionalParamOrReturnAttrs(AttrBuilder &B, bool IsParam) {
  1624. bool HaveError = false;
  1625. B.clear();
  1626. while (true) {
  1627. lltok::Kind Token = Lex.getKind();
  1628. if (Token == lltok::StringConstant) {
  1629. if (parseStringAttribute(B))
  1630. return true;
  1631. continue;
  1632. }
  1633. SMLoc Loc = Lex.getLoc();
  1634. Attribute::AttrKind Attr = tokenToAttribute(Token);
  1635. if (Attr == Attribute::None)
  1636. return HaveError;
  1637. if (parseEnumAttribute(Attr, B, /* InAttrGroup */ false))
  1638. return true;
  1639. if (IsParam && !Attribute::canUseAsParamAttr(Attr))
  1640. HaveError |= error(Loc, "this attribute does not apply to parameters");
  1641. if (!IsParam && !Attribute::canUseAsRetAttr(Attr))
  1642. HaveError |= error(Loc, "this attribute does not apply to return values");
  1643. }
  1644. }
  1645. static unsigned parseOptionalLinkageAux(lltok::Kind Kind, bool &HasLinkage) {
  1646. HasLinkage = true;
  1647. switch (Kind) {
  1648. default:
  1649. HasLinkage = false;
  1650. return GlobalValue::ExternalLinkage;
  1651. case lltok::kw_private:
  1652. return GlobalValue::PrivateLinkage;
  1653. case lltok::kw_internal:
  1654. return GlobalValue::InternalLinkage;
  1655. case lltok::kw_weak:
  1656. return GlobalValue::WeakAnyLinkage;
  1657. case lltok::kw_weak_odr:
  1658. return GlobalValue::WeakODRLinkage;
  1659. case lltok::kw_linkonce:
  1660. return GlobalValue::LinkOnceAnyLinkage;
  1661. case lltok::kw_linkonce_odr:
  1662. return GlobalValue::LinkOnceODRLinkage;
  1663. case lltok::kw_available_externally:
  1664. return GlobalValue::AvailableExternallyLinkage;
  1665. case lltok::kw_appending:
  1666. return GlobalValue::AppendingLinkage;
  1667. case lltok::kw_common:
  1668. return GlobalValue::CommonLinkage;
  1669. case lltok::kw_extern_weak:
  1670. return GlobalValue::ExternalWeakLinkage;
  1671. case lltok::kw_external:
  1672. return GlobalValue::ExternalLinkage;
  1673. }
  1674. }
  1675. /// parseOptionalLinkage
  1676. /// ::= /*empty*/
  1677. /// ::= 'private'
  1678. /// ::= 'internal'
  1679. /// ::= 'weak'
  1680. /// ::= 'weak_odr'
  1681. /// ::= 'linkonce'
  1682. /// ::= 'linkonce_odr'
  1683. /// ::= 'available_externally'
  1684. /// ::= 'appending'
  1685. /// ::= 'common'
  1686. /// ::= 'extern_weak'
  1687. /// ::= 'external'
  1688. bool LLParser::parseOptionalLinkage(unsigned &Res, bool &HasLinkage,
  1689. unsigned &Visibility,
  1690. unsigned &DLLStorageClass, bool &DSOLocal) {
  1691. Res = parseOptionalLinkageAux(Lex.getKind(), HasLinkage);
  1692. if (HasLinkage)
  1693. Lex.Lex();
  1694. parseOptionalDSOLocal(DSOLocal);
  1695. parseOptionalVisibility(Visibility);
  1696. parseOptionalDLLStorageClass(DLLStorageClass);
  1697. if (DSOLocal && DLLStorageClass == GlobalValue::DLLImportStorageClass) {
  1698. return error(Lex.getLoc(), "dso_location and DLL-StorageClass mismatch");
  1699. }
  1700. return false;
  1701. }
  1702. void LLParser::parseOptionalDSOLocal(bool &DSOLocal) {
  1703. switch (Lex.getKind()) {
  1704. default:
  1705. DSOLocal = false;
  1706. break;
  1707. case lltok::kw_dso_local:
  1708. DSOLocal = true;
  1709. Lex.Lex();
  1710. break;
  1711. case lltok::kw_dso_preemptable:
  1712. DSOLocal = false;
  1713. Lex.Lex();
  1714. break;
  1715. }
  1716. }
  1717. /// parseOptionalVisibility
  1718. /// ::= /*empty*/
  1719. /// ::= 'default'
  1720. /// ::= 'hidden'
  1721. /// ::= 'protected'
  1722. ///
  1723. void LLParser::parseOptionalVisibility(unsigned &Res) {
  1724. switch (Lex.getKind()) {
  1725. default:
  1726. Res = GlobalValue::DefaultVisibility;
  1727. return;
  1728. case lltok::kw_default:
  1729. Res = GlobalValue::DefaultVisibility;
  1730. break;
  1731. case lltok::kw_hidden:
  1732. Res = GlobalValue::HiddenVisibility;
  1733. break;
  1734. case lltok::kw_protected:
  1735. Res = GlobalValue::ProtectedVisibility;
  1736. break;
  1737. }
  1738. Lex.Lex();
  1739. }
  1740. /// parseOptionalDLLStorageClass
  1741. /// ::= /*empty*/
  1742. /// ::= 'dllimport'
  1743. /// ::= 'dllexport'
  1744. ///
  1745. void LLParser::parseOptionalDLLStorageClass(unsigned &Res) {
  1746. switch (Lex.getKind()) {
  1747. default:
  1748. Res = GlobalValue::DefaultStorageClass;
  1749. return;
  1750. case lltok::kw_dllimport:
  1751. Res = GlobalValue::DLLImportStorageClass;
  1752. break;
  1753. case lltok::kw_dllexport:
  1754. Res = GlobalValue::DLLExportStorageClass;
  1755. break;
  1756. }
  1757. Lex.Lex();
  1758. }
  1759. /// parseOptionalCallingConv
  1760. /// ::= /*empty*/
  1761. /// ::= 'ccc'
  1762. /// ::= 'fastcc'
  1763. /// ::= 'intel_ocl_bicc'
  1764. /// ::= 'coldcc'
  1765. /// ::= 'cfguard_checkcc'
  1766. /// ::= 'x86_stdcallcc'
  1767. /// ::= 'x86_fastcallcc'
  1768. /// ::= 'x86_thiscallcc'
  1769. /// ::= 'x86_vectorcallcc'
  1770. /// ::= 'arm_apcscc'
  1771. /// ::= 'arm_aapcscc'
  1772. /// ::= 'arm_aapcs_vfpcc'
  1773. /// ::= 'aarch64_vector_pcs'
  1774. /// ::= 'aarch64_sve_vector_pcs'
  1775. /// ::= 'aarch64_sme_preservemost_from_x0'
  1776. /// ::= 'aarch64_sme_preservemost_from_x2'
  1777. /// ::= 'msp430_intrcc'
  1778. /// ::= 'avr_intrcc'
  1779. /// ::= 'avr_signalcc'
  1780. /// ::= 'ptx_kernel'
  1781. /// ::= 'ptx_device'
  1782. /// ::= 'spir_func'
  1783. /// ::= 'spir_kernel'
  1784. /// ::= 'x86_64_sysvcc'
  1785. /// ::= 'win64cc'
  1786. /// ::= 'webkit_jscc'
  1787. /// ::= 'anyregcc'
  1788. /// ::= 'preserve_mostcc'
  1789. /// ::= 'preserve_allcc'
  1790. /// ::= 'ghccc'
  1791. /// ::= 'swiftcc'
  1792. /// ::= 'swifttailcc'
  1793. /// ::= 'x86_intrcc'
  1794. /// ::= 'hhvmcc'
  1795. /// ::= 'hhvm_ccc'
  1796. /// ::= 'cxx_fast_tlscc'
  1797. /// ::= 'amdgpu_vs'
  1798. /// ::= 'amdgpu_ls'
  1799. /// ::= 'amdgpu_hs'
  1800. /// ::= 'amdgpu_es'
  1801. /// ::= 'amdgpu_gs'
  1802. /// ::= 'amdgpu_ps'
  1803. /// ::= 'amdgpu_cs'
  1804. /// ::= 'amdgpu_kernel'
  1805. /// ::= 'tailcc'
  1806. /// ::= 'cc' UINT
  1807. ///
  1808. bool LLParser::parseOptionalCallingConv(unsigned &CC) {
  1809. switch (Lex.getKind()) {
  1810. default: CC = CallingConv::C; return false;
  1811. case lltok::kw_ccc: CC = CallingConv::C; break;
  1812. case lltok::kw_fastcc: CC = CallingConv::Fast; break;
  1813. case lltok::kw_coldcc: CC = CallingConv::Cold; break;
  1814. case lltok::kw_cfguard_checkcc: CC = CallingConv::CFGuard_Check; break;
  1815. case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
  1816. case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
  1817. case lltok::kw_x86_regcallcc: CC = CallingConv::X86_RegCall; break;
  1818. case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
  1819. case lltok::kw_x86_vectorcallcc:CC = CallingConv::X86_VectorCall; break;
  1820. case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
  1821. case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
  1822. case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
  1823. case lltok::kw_aarch64_vector_pcs:CC = CallingConv::AArch64_VectorCall; break;
  1824. case lltok::kw_aarch64_sve_vector_pcs:
  1825. CC = CallingConv::AArch64_SVE_VectorCall;
  1826. break;
  1827. case lltok::kw_aarch64_sme_preservemost_from_x0:
  1828. CC = CallingConv::AArch64_SME_ABI_Support_Routines_PreserveMost_From_X0;
  1829. break;
  1830. case lltok::kw_aarch64_sme_preservemost_from_x2:
  1831. CC = CallingConv::AArch64_SME_ABI_Support_Routines_PreserveMost_From_X2;
  1832. break;
  1833. case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
  1834. case lltok::kw_avr_intrcc: CC = CallingConv::AVR_INTR; break;
  1835. case lltok::kw_avr_signalcc: CC = CallingConv::AVR_SIGNAL; break;
  1836. case lltok::kw_ptx_kernel: CC = CallingConv::PTX_Kernel; break;
  1837. case lltok::kw_ptx_device: CC = CallingConv::PTX_Device; break;
  1838. case lltok::kw_spir_kernel: CC = CallingConv::SPIR_KERNEL; break;
  1839. case lltok::kw_spir_func: CC = CallingConv::SPIR_FUNC; break;
  1840. case lltok::kw_intel_ocl_bicc: CC = CallingConv::Intel_OCL_BI; break;
  1841. case lltok::kw_x86_64_sysvcc: CC = CallingConv::X86_64_SysV; break;
  1842. case lltok::kw_win64cc: CC = CallingConv::Win64; break;
  1843. case lltok::kw_webkit_jscc: CC = CallingConv::WebKit_JS; break;
  1844. case lltok::kw_anyregcc: CC = CallingConv::AnyReg; break;
  1845. case lltok::kw_preserve_mostcc:CC = CallingConv::PreserveMost; break;
  1846. case lltok::kw_preserve_allcc: CC = CallingConv::PreserveAll; break;
  1847. case lltok::kw_ghccc: CC = CallingConv::GHC; break;
  1848. case lltok::kw_swiftcc: CC = CallingConv::Swift; break;
  1849. case lltok::kw_swifttailcc: CC = CallingConv::SwiftTail; break;
  1850. case lltok::kw_x86_intrcc: CC = CallingConv::X86_INTR; break;
  1851. case lltok::kw_hhvmcc: CC = CallingConv::HHVM; break;
  1852. case lltok::kw_hhvm_ccc: CC = CallingConv::HHVM_C; break;
  1853. case lltok::kw_cxx_fast_tlscc: CC = CallingConv::CXX_FAST_TLS; break;
  1854. case lltok::kw_amdgpu_vs: CC = CallingConv::AMDGPU_VS; break;
  1855. case lltok::kw_amdgpu_gfx: CC = CallingConv::AMDGPU_Gfx; break;
  1856. case lltok::kw_amdgpu_ls: CC = CallingConv::AMDGPU_LS; break;
  1857. case lltok::kw_amdgpu_hs: CC = CallingConv::AMDGPU_HS; break;
  1858. case lltok::kw_amdgpu_es: CC = CallingConv::AMDGPU_ES; break;
  1859. case lltok::kw_amdgpu_gs: CC = CallingConv::AMDGPU_GS; break;
  1860. case lltok::kw_amdgpu_ps: CC = CallingConv::AMDGPU_PS; break;
  1861. case lltok::kw_amdgpu_cs: CC = CallingConv::AMDGPU_CS; break;
  1862. case lltok::kw_amdgpu_kernel: CC = CallingConv::AMDGPU_KERNEL; break;
  1863. case lltok::kw_tailcc: CC = CallingConv::Tail; break;
  1864. case lltok::kw_cc: {
  1865. Lex.Lex();
  1866. return parseUInt32(CC);
  1867. }
  1868. }
  1869. Lex.Lex();
  1870. return false;
  1871. }
  1872. /// parseMetadataAttachment
  1873. /// ::= !dbg !42
  1874. bool LLParser::parseMetadataAttachment(unsigned &Kind, MDNode *&MD) {
  1875. assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata attachment");
  1876. std::string Name = Lex.getStrVal();
  1877. Kind = M->getMDKindID(Name);
  1878. Lex.Lex();
  1879. return parseMDNode(MD);
  1880. }
  1881. /// parseInstructionMetadata
  1882. /// ::= !dbg !42 (',' !dbg !57)*
  1883. bool LLParser::parseInstructionMetadata(Instruction &Inst) {
  1884. do {
  1885. if (Lex.getKind() != lltok::MetadataVar)
  1886. return tokError("expected metadata after comma");
  1887. unsigned MDK;
  1888. MDNode *N;
  1889. if (parseMetadataAttachment(MDK, N))
  1890. return true;
  1891. if (MDK == LLVMContext::MD_DIAssignID)
  1892. TempDIAssignIDAttachments[N].push_back(&Inst);
  1893. else
  1894. Inst.setMetadata(MDK, N);
  1895. if (MDK == LLVMContext::MD_tbaa)
  1896. InstsWithTBAATag.push_back(&Inst);
  1897. // If this is the end of the list, we're done.
  1898. } while (EatIfPresent(lltok::comma));
  1899. return false;
  1900. }
  1901. /// parseGlobalObjectMetadataAttachment
  1902. /// ::= !dbg !57
  1903. bool LLParser::parseGlobalObjectMetadataAttachment(GlobalObject &GO) {
  1904. unsigned MDK;
  1905. MDNode *N;
  1906. if (parseMetadataAttachment(MDK, N))
  1907. return true;
  1908. GO.addMetadata(MDK, *N);
  1909. return false;
  1910. }
  1911. /// parseOptionalFunctionMetadata
  1912. /// ::= (!dbg !57)*
  1913. bool LLParser::parseOptionalFunctionMetadata(Function &F) {
  1914. while (Lex.getKind() == lltok::MetadataVar)
  1915. if (parseGlobalObjectMetadataAttachment(F))
  1916. return true;
  1917. return false;
  1918. }
  1919. /// parseOptionalAlignment
  1920. /// ::= /* empty */
  1921. /// ::= 'align' 4
  1922. bool LLParser::parseOptionalAlignment(MaybeAlign &Alignment, bool AllowParens) {
  1923. Alignment = std::nullopt;
  1924. if (!EatIfPresent(lltok::kw_align))
  1925. return false;
  1926. LocTy AlignLoc = Lex.getLoc();
  1927. uint64_t Value = 0;
  1928. LocTy ParenLoc = Lex.getLoc();
  1929. bool HaveParens = false;
  1930. if (AllowParens) {
  1931. if (EatIfPresent(lltok::lparen))
  1932. HaveParens = true;
  1933. }
  1934. if (parseUInt64(Value))
  1935. return true;
  1936. if (HaveParens && !EatIfPresent(lltok::rparen))
  1937. return error(ParenLoc, "expected ')'");
  1938. if (!isPowerOf2_64(Value))
  1939. return error(AlignLoc, "alignment is not a power of two");
  1940. if (Value > Value::MaximumAlignment)
  1941. return error(AlignLoc, "huge alignments are not supported yet");
  1942. Alignment = Align(Value);
  1943. return false;
  1944. }
  1945. /// parseOptionalDerefAttrBytes
  1946. /// ::= /* empty */
  1947. /// ::= AttrKind '(' 4 ')'
  1948. ///
  1949. /// where AttrKind is either 'dereferenceable' or 'dereferenceable_or_null'.
  1950. bool LLParser::parseOptionalDerefAttrBytes(lltok::Kind AttrKind,
  1951. uint64_t &Bytes) {
  1952. assert((AttrKind == lltok::kw_dereferenceable ||
  1953. AttrKind == lltok::kw_dereferenceable_or_null) &&
  1954. "contract!");
  1955. Bytes = 0;
  1956. if (!EatIfPresent(AttrKind))
  1957. return false;
  1958. LocTy ParenLoc = Lex.getLoc();
  1959. if (!EatIfPresent(lltok::lparen))
  1960. return error(ParenLoc, "expected '('");
  1961. LocTy DerefLoc = Lex.getLoc();
  1962. if (parseUInt64(Bytes))
  1963. return true;
  1964. ParenLoc = Lex.getLoc();
  1965. if (!EatIfPresent(lltok::rparen))
  1966. return error(ParenLoc, "expected ')'");
  1967. if (!Bytes)
  1968. return error(DerefLoc, "dereferenceable bytes must be non-zero");
  1969. return false;
  1970. }
  1971. bool LLParser::parseOptionalUWTableKind(UWTableKind &Kind) {
  1972. Lex.Lex();
  1973. Kind = UWTableKind::Default;
  1974. if (!EatIfPresent(lltok::lparen))
  1975. return false;
  1976. LocTy KindLoc = Lex.getLoc();
  1977. if (Lex.getKind() == lltok::kw_sync)
  1978. Kind = UWTableKind::Sync;
  1979. else if (Lex.getKind() == lltok::kw_async)
  1980. Kind = UWTableKind::Async;
  1981. else
  1982. return error(KindLoc, "expected unwind table kind");
  1983. Lex.Lex();
  1984. return parseToken(lltok::rparen, "expected ')'");
  1985. }
  1986. bool LLParser::parseAllocKind(AllocFnKind &Kind) {
  1987. Lex.Lex();
  1988. LocTy ParenLoc = Lex.getLoc();
  1989. if (!EatIfPresent(lltok::lparen))
  1990. return error(ParenLoc, "expected '('");
  1991. LocTy KindLoc = Lex.getLoc();
  1992. std::string Arg;
  1993. if (parseStringConstant(Arg))
  1994. return error(KindLoc, "expected allockind value");
  1995. for (StringRef A : llvm::split(Arg, ",")) {
  1996. if (A == "alloc") {
  1997. Kind |= AllocFnKind::Alloc;
  1998. } else if (A == "realloc") {
  1999. Kind |= AllocFnKind::Realloc;
  2000. } else if (A == "free") {
  2001. Kind |= AllocFnKind::Free;
  2002. } else if (A == "uninitialized") {
  2003. Kind |= AllocFnKind::Uninitialized;
  2004. } else if (A == "zeroed") {
  2005. Kind |= AllocFnKind::Zeroed;
  2006. } else if (A == "aligned") {
  2007. Kind |= AllocFnKind::Aligned;
  2008. } else {
  2009. return error(KindLoc, Twine("unknown allockind ") + A);
  2010. }
  2011. }
  2012. ParenLoc = Lex.getLoc();
  2013. if (!EatIfPresent(lltok::rparen))
  2014. return error(ParenLoc, "expected ')'");
  2015. if (Kind == AllocFnKind::Unknown)
  2016. return error(KindLoc, "expected allockind value");
  2017. return false;
  2018. }
  2019. static std::optional<MemoryEffects::Location> keywordToLoc(lltok::Kind Tok) {
  2020. switch (Tok) {
  2021. case lltok::kw_argmem:
  2022. return MemoryEffects::ArgMem;
  2023. case lltok::kw_inaccessiblemem:
  2024. return MemoryEffects::InaccessibleMem;
  2025. default:
  2026. return std::nullopt;
  2027. }
  2028. }
  2029. static std::optional<ModRefInfo> keywordToModRef(lltok::Kind Tok) {
  2030. switch (Tok) {
  2031. case lltok::kw_none:
  2032. return ModRefInfo::NoModRef;
  2033. case lltok::kw_read:
  2034. return ModRefInfo::Ref;
  2035. case lltok::kw_write:
  2036. return ModRefInfo::Mod;
  2037. case lltok::kw_readwrite:
  2038. return ModRefInfo::ModRef;
  2039. default:
  2040. return std::nullopt;
  2041. }
  2042. }
  2043. std::optional<MemoryEffects> LLParser::parseMemoryAttr() {
  2044. MemoryEffects ME = MemoryEffects::none();
  2045. // We use syntax like memory(argmem: read), so the colon should not be
  2046. // interpreted as a label terminator.
  2047. Lex.setIgnoreColonInIdentifiers(true);
  2048. auto _ = make_scope_exit([&] { Lex.setIgnoreColonInIdentifiers(false); });
  2049. Lex.Lex();
  2050. if (!EatIfPresent(lltok::lparen)) {
  2051. tokError("expected '('");
  2052. return std::nullopt;
  2053. }
  2054. bool SeenLoc = false;
  2055. do {
  2056. std::optional<MemoryEffects::Location> Loc = keywordToLoc(Lex.getKind());
  2057. if (Loc) {
  2058. Lex.Lex();
  2059. if (!EatIfPresent(lltok::colon)) {
  2060. tokError("expected ':' after location");
  2061. return std::nullopt;
  2062. }
  2063. }
  2064. std::optional<ModRefInfo> MR = keywordToModRef(Lex.getKind());
  2065. if (!MR) {
  2066. if (!Loc)
  2067. tokError("expected memory location (argmem, inaccessiblemem) "
  2068. "or access kind (none, read, write, readwrite)");
  2069. else
  2070. tokError("expected access kind (none, read, write, readwrite)");
  2071. return std::nullopt;
  2072. }
  2073. Lex.Lex();
  2074. if (Loc) {
  2075. SeenLoc = true;
  2076. ME = ME.getWithModRef(*Loc, *MR);
  2077. } else {
  2078. if (SeenLoc) {
  2079. tokError("default access kind must be specified first");
  2080. return std::nullopt;
  2081. }
  2082. ME = MemoryEffects(*MR);
  2083. }
  2084. if (EatIfPresent(lltok::rparen))
  2085. return ME;
  2086. } while (EatIfPresent(lltok::comma));
  2087. tokError("unterminated memory attribute");
  2088. return std::nullopt;
  2089. }
  2090. /// parseOptionalCommaAlign
  2091. /// ::=
  2092. /// ::= ',' align 4
  2093. ///
  2094. /// This returns with AteExtraComma set to true if it ate an excess comma at the
  2095. /// end.
  2096. bool LLParser::parseOptionalCommaAlign(MaybeAlign &Alignment,
  2097. bool &AteExtraComma) {
  2098. AteExtraComma = false;
  2099. while (EatIfPresent(lltok::comma)) {
  2100. // Metadata at the end is an early exit.
  2101. if (Lex.getKind() == lltok::MetadataVar) {
  2102. AteExtraComma = true;
  2103. return false;
  2104. }
  2105. if (Lex.getKind() != lltok::kw_align)
  2106. return error(Lex.getLoc(), "expected metadata or 'align'");
  2107. if (parseOptionalAlignment(Alignment))
  2108. return true;
  2109. }
  2110. return false;
  2111. }
  2112. /// parseOptionalCommaAddrSpace
  2113. /// ::=
  2114. /// ::= ',' addrspace(1)
  2115. ///
  2116. /// This returns with AteExtraComma set to true if it ate an excess comma at the
  2117. /// end.
  2118. bool LLParser::parseOptionalCommaAddrSpace(unsigned &AddrSpace, LocTy &Loc,
  2119. bool &AteExtraComma) {
  2120. AteExtraComma = false;
  2121. while (EatIfPresent(lltok::comma)) {
  2122. // Metadata at the end is an early exit.
  2123. if (Lex.getKind() == lltok::MetadataVar) {
  2124. AteExtraComma = true;
  2125. return false;
  2126. }
  2127. Loc = Lex.getLoc();
  2128. if (Lex.getKind() != lltok::kw_addrspace)
  2129. return error(Lex.getLoc(), "expected metadata or 'addrspace'");
  2130. if (parseOptionalAddrSpace(AddrSpace))
  2131. return true;
  2132. }
  2133. return false;
  2134. }
  2135. bool LLParser::parseAllocSizeArguments(unsigned &BaseSizeArg,
  2136. std::optional<unsigned> &HowManyArg) {
  2137. Lex.Lex();
  2138. auto StartParen = Lex.getLoc();
  2139. if (!EatIfPresent(lltok::lparen))
  2140. return error(StartParen, "expected '('");
  2141. if (parseUInt32(BaseSizeArg))
  2142. return true;
  2143. if (EatIfPresent(lltok::comma)) {
  2144. auto HowManyAt = Lex.getLoc();
  2145. unsigned HowMany;
  2146. if (parseUInt32(HowMany))
  2147. return true;
  2148. if (HowMany == BaseSizeArg)
  2149. return error(HowManyAt,
  2150. "'allocsize' indices can't refer to the same parameter");
  2151. HowManyArg = HowMany;
  2152. } else
  2153. HowManyArg = std::nullopt;
  2154. auto EndParen = Lex.getLoc();
  2155. if (!EatIfPresent(lltok::rparen))
  2156. return error(EndParen, "expected ')'");
  2157. return false;
  2158. }
  2159. bool LLParser::parseVScaleRangeArguments(unsigned &MinValue,
  2160. unsigned &MaxValue) {
  2161. Lex.Lex();
  2162. auto StartParen = Lex.getLoc();
  2163. if (!EatIfPresent(lltok::lparen))
  2164. return error(StartParen, "expected '('");
  2165. if (parseUInt32(MinValue))
  2166. return true;
  2167. if (EatIfPresent(lltok::comma)) {
  2168. if (parseUInt32(MaxValue))
  2169. return true;
  2170. } else
  2171. MaxValue = MinValue;
  2172. auto EndParen = Lex.getLoc();
  2173. if (!EatIfPresent(lltok::rparen))
  2174. return error(EndParen, "expected ')'");
  2175. return false;
  2176. }
  2177. /// parseScopeAndOrdering
  2178. /// if isAtomic: ::= SyncScope? AtomicOrdering
  2179. /// else: ::=
  2180. ///
  2181. /// This sets Scope and Ordering to the parsed values.
  2182. bool LLParser::parseScopeAndOrdering(bool IsAtomic, SyncScope::ID &SSID,
  2183. AtomicOrdering &Ordering) {
  2184. if (!IsAtomic)
  2185. return false;
  2186. return parseScope(SSID) || parseOrdering(Ordering);
  2187. }
  2188. /// parseScope
  2189. /// ::= syncscope("singlethread" | "<target scope>")?
  2190. ///
  2191. /// This sets synchronization scope ID to the ID of the parsed value.
  2192. bool LLParser::parseScope(SyncScope::ID &SSID) {
  2193. SSID = SyncScope::System;
  2194. if (EatIfPresent(lltok::kw_syncscope)) {
  2195. auto StartParenAt = Lex.getLoc();
  2196. if (!EatIfPresent(lltok::lparen))
  2197. return error(StartParenAt, "Expected '(' in syncscope");
  2198. std::string SSN;
  2199. auto SSNAt = Lex.getLoc();
  2200. if (parseStringConstant(SSN))
  2201. return error(SSNAt, "Expected synchronization scope name");
  2202. auto EndParenAt = Lex.getLoc();
  2203. if (!EatIfPresent(lltok::rparen))
  2204. return error(EndParenAt, "Expected ')' in syncscope");
  2205. SSID = Context.getOrInsertSyncScopeID(SSN);
  2206. }
  2207. return false;
  2208. }
  2209. /// parseOrdering
  2210. /// ::= AtomicOrdering
  2211. ///
  2212. /// This sets Ordering to the parsed value.
  2213. bool LLParser::parseOrdering(AtomicOrdering &Ordering) {
  2214. switch (Lex.getKind()) {
  2215. default:
  2216. return tokError("Expected ordering on atomic instruction");
  2217. case lltok::kw_unordered: Ordering = AtomicOrdering::Unordered; break;
  2218. case lltok::kw_monotonic: Ordering = AtomicOrdering::Monotonic; break;
  2219. // Not specified yet:
  2220. // case lltok::kw_consume: Ordering = AtomicOrdering::Consume; break;
  2221. case lltok::kw_acquire: Ordering = AtomicOrdering::Acquire; break;
  2222. case lltok::kw_release: Ordering = AtomicOrdering::Release; break;
  2223. case lltok::kw_acq_rel: Ordering = AtomicOrdering::AcquireRelease; break;
  2224. case lltok::kw_seq_cst:
  2225. Ordering = AtomicOrdering::SequentiallyConsistent;
  2226. break;
  2227. }
  2228. Lex.Lex();
  2229. return false;
  2230. }
  2231. /// parseOptionalStackAlignment
  2232. /// ::= /* empty */
  2233. /// ::= 'alignstack' '(' 4 ')'
  2234. bool LLParser::parseOptionalStackAlignment(unsigned &Alignment) {
  2235. Alignment = 0;
  2236. if (!EatIfPresent(lltok::kw_alignstack))
  2237. return false;
  2238. LocTy ParenLoc = Lex.getLoc();
  2239. if (!EatIfPresent(lltok::lparen))
  2240. return error(ParenLoc, "expected '('");
  2241. LocTy AlignLoc = Lex.getLoc();
  2242. if (parseUInt32(Alignment))
  2243. return true;
  2244. ParenLoc = Lex.getLoc();
  2245. if (!EatIfPresent(lltok::rparen))
  2246. return error(ParenLoc, "expected ')'");
  2247. if (!isPowerOf2_32(Alignment))
  2248. return error(AlignLoc, "stack alignment is not a power of two");
  2249. return false;
  2250. }
  2251. /// parseIndexList - This parses the index list for an insert/extractvalue
  2252. /// instruction. This sets AteExtraComma in the case where we eat an extra
  2253. /// comma at the end of the line and find that it is followed by metadata.
  2254. /// Clients that don't allow metadata can call the version of this function that
  2255. /// only takes one argument.
  2256. ///
  2257. /// parseIndexList
  2258. /// ::= (',' uint32)+
  2259. ///
  2260. bool LLParser::parseIndexList(SmallVectorImpl<unsigned> &Indices,
  2261. bool &AteExtraComma) {
  2262. AteExtraComma = false;
  2263. if (Lex.getKind() != lltok::comma)
  2264. return tokError("expected ',' as start of index list");
  2265. while (EatIfPresent(lltok::comma)) {
  2266. if (Lex.getKind() == lltok::MetadataVar) {
  2267. if (Indices.empty())
  2268. return tokError("expected index");
  2269. AteExtraComma = true;
  2270. return false;
  2271. }
  2272. unsigned Idx = 0;
  2273. if (parseUInt32(Idx))
  2274. return true;
  2275. Indices.push_back(Idx);
  2276. }
  2277. return false;
  2278. }
  2279. //===----------------------------------------------------------------------===//
  2280. // Type Parsing.
  2281. //===----------------------------------------------------------------------===//
  2282. /// parseType - parse a type.
  2283. bool LLParser::parseType(Type *&Result, const Twine &Msg, bool AllowVoid) {
  2284. SMLoc TypeLoc = Lex.getLoc();
  2285. switch (Lex.getKind()) {
  2286. default:
  2287. return tokError(Msg);
  2288. case lltok::Type:
  2289. // Type ::= 'float' | 'void' (etc)
  2290. Result = Lex.getTyVal();
  2291. Lex.Lex();
  2292. // Handle "ptr" opaque pointer type.
  2293. //
  2294. // Type ::= ptr ('addrspace' '(' uint32 ')')?
  2295. if (Result->isOpaquePointerTy()) {
  2296. unsigned AddrSpace;
  2297. if (parseOptionalAddrSpace(AddrSpace))
  2298. return true;
  2299. Result = PointerType::get(getContext(), AddrSpace);
  2300. // Give a nice error for 'ptr*'.
  2301. if (Lex.getKind() == lltok::star)
  2302. return tokError("ptr* is invalid - use ptr instead");
  2303. // Fall through to parsing the type suffixes only if this 'ptr' is a
  2304. // function return. Otherwise, return success, implicitly rejecting other
  2305. // suffixes.
  2306. if (Lex.getKind() != lltok::lparen)
  2307. return false;
  2308. }
  2309. break;
  2310. case lltok::kw_target: {
  2311. // Type ::= TargetExtType
  2312. if (parseTargetExtType(Result))
  2313. return true;
  2314. break;
  2315. }
  2316. case lltok::lbrace:
  2317. // Type ::= StructType
  2318. if (parseAnonStructType(Result, false))
  2319. return true;
  2320. break;
  2321. case lltok::lsquare:
  2322. // Type ::= '[' ... ']'
  2323. Lex.Lex(); // eat the lsquare.
  2324. if (parseArrayVectorType(Result, false))
  2325. return true;
  2326. break;
  2327. case lltok::less: // Either vector or packed struct.
  2328. // Type ::= '<' ... '>'
  2329. Lex.Lex();
  2330. if (Lex.getKind() == lltok::lbrace) {
  2331. if (parseAnonStructType(Result, true) ||
  2332. parseToken(lltok::greater, "expected '>' at end of packed struct"))
  2333. return true;
  2334. } else if (parseArrayVectorType(Result, true))
  2335. return true;
  2336. break;
  2337. case lltok::LocalVar: {
  2338. // Type ::= %foo
  2339. std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
  2340. // If the type hasn't been defined yet, create a forward definition and
  2341. // remember where that forward def'n was seen (in case it never is defined).
  2342. if (!Entry.first) {
  2343. Entry.first = StructType::create(Context, Lex.getStrVal());
  2344. Entry.second = Lex.getLoc();
  2345. }
  2346. Result = Entry.first;
  2347. Lex.Lex();
  2348. break;
  2349. }
  2350. case lltok::LocalVarID: {
  2351. // Type ::= %4
  2352. std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
  2353. // If the type hasn't been defined yet, create a forward definition and
  2354. // remember where that forward def'n was seen (in case it never is defined).
  2355. if (!Entry.first) {
  2356. Entry.first = StructType::create(Context);
  2357. Entry.second = Lex.getLoc();
  2358. }
  2359. Result = Entry.first;
  2360. Lex.Lex();
  2361. break;
  2362. }
  2363. }
  2364. // parse the type suffixes.
  2365. while (true) {
  2366. switch (Lex.getKind()) {
  2367. // End of type.
  2368. default:
  2369. if (!AllowVoid && Result->isVoidTy())
  2370. return error(TypeLoc, "void type only allowed for function results");
  2371. return false;
  2372. // Type ::= Type '*'
  2373. case lltok::star:
  2374. if (Result->isLabelTy())
  2375. return tokError("basic block pointers are invalid");
  2376. if (Result->isVoidTy())
  2377. return tokError("pointers to void are invalid - use i8* instead");
  2378. if (!PointerType::isValidElementType(Result))
  2379. return tokError("pointer to this type is invalid");
  2380. Result = PointerType::getUnqual(Result);
  2381. Lex.Lex();
  2382. break;
  2383. // Type ::= Type 'addrspace' '(' uint32 ')' '*'
  2384. case lltok::kw_addrspace: {
  2385. if (Result->isLabelTy())
  2386. return tokError("basic block pointers are invalid");
  2387. if (Result->isVoidTy())
  2388. return tokError("pointers to void are invalid; use i8* instead");
  2389. if (!PointerType::isValidElementType(Result))
  2390. return tokError("pointer to this type is invalid");
  2391. unsigned AddrSpace;
  2392. if (parseOptionalAddrSpace(AddrSpace) ||
  2393. parseToken(lltok::star, "expected '*' in address space"))
  2394. return true;
  2395. Result = PointerType::get(Result, AddrSpace);
  2396. break;
  2397. }
  2398. /// Types '(' ArgTypeListI ')' OptFuncAttrs
  2399. case lltok::lparen:
  2400. if (parseFunctionType(Result))
  2401. return true;
  2402. break;
  2403. }
  2404. }
  2405. }
  2406. /// parseParameterList
  2407. /// ::= '(' ')'
  2408. /// ::= '(' Arg (',' Arg)* ')'
  2409. /// Arg
  2410. /// ::= Type OptionalAttributes Value OptionalAttributes
  2411. bool LLParser::parseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
  2412. PerFunctionState &PFS, bool IsMustTailCall,
  2413. bool InVarArgsFunc) {
  2414. if (parseToken(lltok::lparen, "expected '(' in call"))
  2415. return true;
  2416. while (Lex.getKind() != lltok::rparen) {
  2417. // If this isn't the first argument, we need a comma.
  2418. if (!ArgList.empty() &&
  2419. parseToken(lltok::comma, "expected ',' in argument list"))
  2420. return true;
  2421. // parse an ellipsis if this is a musttail call in a variadic function.
  2422. if (Lex.getKind() == lltok::dotdotdot) {
  2423. const char *Msg = "unexpected ellipsis in argument list for ";
  2424. if (!IsMustTailCall)
  2425. return tokError(Twine(Msg) + "non-musttail call");
  2426. if (!InVarArgsFunc)
  2427. return tokError(Twine(Msg) + "musttail call in non-varargs function");
  2428. Lex.Lex(); // Lex the '...', it is purely for readability.
  2429. return parseToken(lltok::rparen, "expected ')' at end of argument list");
  2430. }
  2431. // parse the argument.
  2432. LocTy ArgLoc;
  2433. Type *ArgTy = nullptr;
  2434. Value *V;
  2435. if (parseType(ArgTy, ArgLoc))
  2436. return true;
  2437. AttrBuilder ArgAttrs(M->getContext());
  2438. if (ArgTy->isMetadataTy()) {
  2439. if (parseMetadataAsValue(V, PFS))
  2440. return true;
  2441. } else {
  2442. // Otherwise, handle normal operands.
  2443. if (parseOptionalParamAttrs(ArgAttrs) || parseValue(ArgTy, V, PFS))
  2444. return true;
  2445. }
  2446. ArgList.push_back(ParamInfo(
  2447. ArgLoc, V, AttributeSet::get(V->getContext(), ArgAttrs)));
  2448. }
  2449. if (IsMustTailCall && InVarArgsFunc)
  2450. return tokError("expected '...' at end of argument list for musttail call "
  2451. "in varargs function");
  2452. Lex.Lex(); // Lex the ')'.
  2453. return false;
  2454. }
  2455. /// parseRequiredTypeAttr
  2456. /// ::= attrname(<ty>)
  2457. bool LLParser::parseRequiredTypeAttr(AttrBuilder &B, lltok::Kind AttrToken,
  2458. Attribute::AttrKind AttrKind) {
  2459. Type *Ty = nullptr;
  2460. if (!EatIfPresent(AttrToken))
  2461. return true;
  2462. if (!EatIfPresent(lltok::lparen))
  2463. return error(Lex.getLoc(), "expected '('");
  2464. if (parseType(Ty))
  2465. return true;
  2466. if (!EatIfPresent(lltok::rparen))
  2467. return error(Lex.getLoc(), "expected ')'");
  2468. B.addTypeAttr(AttrKind, Ty);
  2469. return false;
  2470. }
  2471. /// parseOptionalOperandBundles
  2472. /// ::= /*empty*/
  2473. /// ::= '[' OperandBundle [, OperandBundle ]* ']'
  2474. ///
  2475. /// OperandBundle
  2476. /// ::= bundle-tag '(' ')'
  2477. /// ::= bundle-tag '(' Type Value [, Type Value ]* ')'
  2478. ///
  2479. /// bundle-tag ::= String Constant
  2480. bool LLParser::parseOptionalOperandBundles(
  2481. SmallVectorImpl<OperandBundleDef> &BundleList, PerFunctionState &PFS) {
  2482. LocTy BeginLoc = Lex.getLoc();
  2483. if (!EatIfPresent(lltok::lsquare))
  2484. return false;
  2485. while (Lex.getKind() != lltok::rsquare) {
  2486. // If this isn't the first operand bundle, we need a comma.
  2487. if (!BundleList.empty() &&
  2488. parseToken(lltok::comma, "expected ',' in input list"))
  2489. return true;
  2490. std::string Tag;
  2491. if (parseStringConstant(Tag))
  2492. return true;
  2493. if (parseToken(lltok::lparen, "expected '(' in operand bundle"))
  2494. return true;
  2495. std::vector<Value *> Inputs;
  2496. while (Lex.getKind() != lltok::rparen) {
  2497. // If this isn't the first input, we need a comma.
  2498. if (!Inputs.empty() &&
  2499. parseToken(lltok::comma, "expected ',' in input list"))
  2500. return true;
  2501. Type *Ty = nullptr;
  2502. Value *Input = nullptr;
  2503. if (parseType(Ty) || parseValue(Ty, Input, PFS))
  2504. return true;
  2505. Inputs.push_back(Input);
  2506. }
  2507. BundleList.emplace_back(std::move(Tag), std::move(Inputs));
  2508. Lex.Lex(); // Lex the ')'.
  2509. }
  2510. if (BundleList.empty())
  2511. return error(BeginLoc, "operand bundle set must not be empty");
  2512. Lex.Lex(); // Lex the ']'.
  2513. return false;
  2514. }
  2515. /// parseArgumentList - parse the argument list for a function type or function
  2516. /// prototype.
  2517. /// ::= '(' ArgTypeListI ')'
  2518. /// ArgTypeListI
  2519. /// ::= /*empty*/
  2520. /// ::= '...'
  2521. /// ::= ArgTypeList ',' '...'
  2522. /// ::= ArgType (',' ArgType)*
  2523. ///
  2524. bool LLParser::parseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
  2525. bool &IsVarArg) {
  2526. unsigned CurValID = 0;
  2527. IsVarArg = false;
  2528. assert(Lex.getKind() == lltok::lparen);
  2529. Lex.Lex(); // eat the (.
  2530. if (Lex.getKind() == lltok::rparen) {
  2531. // empty
  2532. } else if (Lex.getKind() == lltok::dotdotdot) {
  2533. IsVarArg = true;
  2534. Lex.Lex();
  2535. } else {
  2536. LocTy TypeLoc = Lex.getLoc();
  2537. Type *ArgTy = nullptr;
  2538. AttrBuilder Attrs(M->getContext());
  2539. std::string Name;
  2540. if (parseType(ArgTy) || parseOptionalParamAttrs(Attrs))
  2541. return true;
  2542. if (ArgTy->isVoidTy())
  2543. return error(TypeLoc, "argument can not have void type");
  2544. if (Lex.getKind() == lltok::LocalVar) {
  2545. Name = Lex.getStrVal();
  2546. Lex.Lex();
  2547. } else if (Lex.getKind() == lltok::LocalVarID) {
  2548. if (Lex.getUIntVal() != CurValID)
  2549. return error(TypeLoc, "argument expected to be numbered '%" +
  2550. Twine(CurValID) + "'");
  2551. ++CurValID;
  2552. Lex.Lex();
  2553. }
  2554. if (!FunctionType::isValidArgumentType(ArgTy))
  2555. return error(TypeLoc, "invalid type for function argument");
  2556. ArgList.emplace_back(TypeLoc, ArgTy,
  2557. AttributeSet::get(ArgTy->getContext(), Attrs),
  2558. std::move(Name));
  2559. while (EatIfPresent(lltok::comma)) {
  2560. // Handle ... at end of arg list.
  2561. if (EatIfPresent(lltok::dotdotdot)) {
  2562. IsVarArg = true;
  2563. break;
  2564. }
  2565. // Otherwise must be an argument type.
  2566. TypeLoc = Lex.getLoc();
  2567. if (parseType(ArgTy) || parseOptionalParamAttrs(Attrs))
  2568. return true;
  2569. if (ArgTy->isVoidTy())
  2570. return error(TypeLoc, "argument can not have void type");
  2571. if (Lex.getKind() == lltok::LocalVar) {
  2572. Name = Lex.getStrVal();
  2573. Lex.Lex();
  2574. } else {
  2575. if (Lex.getKind() == lltok::LocalVarID) {
  2576. if (Lex.getUIntVal() != CurValID)
  2577. return error(TypeLoc, "argument expected to be numbered '%" +
  2578. Twine(CurValID) + "'");
  2579. Lex.Lex();
  2580. }
  2581. ++CurValID;
  2582. Name = "";
  2583. }
  2584. if (!ArgTy->isFirstClassType())
  2585. return error(TypeLoc, "invalid type for function argument");
  2586. ArgList.emplace_back(TypeLoc, ArgTy,
  2587. AttributeSet::get(ArgTy->getContext(), Attrs),
  2588. std::move(Name));
  2589. }
  2590. }
  2591. return parseToken(lltok::rparen, "expected ')' at end of argument list");
  2592. }
  2593. /// parseFunctionType
  2594. /// ::= Type ArgumentList OptionalAttrs
  2595. bool LLParser::parseFunctionType(Type *&Result) {
  2596. assert(Lex.getKind() == lltok::lparen);
  2597. if (!FunctionType::isValidReturnType(Result))
  2598. return tokError("invalid function return type");
  2599. SmallVector<ArgInfo, 8> ArgList;
  2600. bool IsVarArg;
  2601. if (parseArgumentList(ArgList, IsVarArg))
  2602. return true;
  2603. // Reject names on the arguments lists.
  2604. for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
  2605. if (!ArgList[i].Name.empty())
  2606. return error(ArgList[i].Loc, "argument name invalid in function type");
  2607. if (ArgList[i].Attrs.hasAttributes())
  2608. return error(ArgList[i].Loc,
  2609. "argument attributes invalid in function type");
  2610. }
  2611. SmallVector<Type*, 16> ArgListTy;
  2612. for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
  2613. ArgListTy.push_back(ArgList[i].Ty);
  2614. Result = FunctionType::get(Result, ArgListTy, IsVarArg);
  2615. return false;
  2616. }
  2617. /// parseAnonStructType - parse an anonymous struct type, which is inlined into
  2618. /// other structs.
  2619. bool LLParser::parseAnonStructType(Type *&Result, bool Packed) {
  2620. SmallVector<Type*, 8> Elts;
  2621. if (parseStructBody(Elts))
  2622. return true;
  2623. Result = StructType::get(Context, Elts, Packed);
  2624. return false;
  2625. }
  2626. /// parseStructDefinition - parse a struct in a 'type' definition.
  2627. bool LLParser::parseStructDefinition(SMLoc TypeLoc, StringRef Name,
  2628. std::pair<Type *, LocTy> &Entry,
  2629. Type *&ResultTy) {
  2630. // If the type was already defined, diagnose the redefinition.
  2631. if (Entry.first && !Entry.second.isValid())
  2632. return error(TypeLoc, "redefinition of type");
  2633. // If we have opaque, just return without filling in the definition for the
  2634. // struct. This counts as a definition as far as the .ll file goes.
  2635. if (EatIfPresent(lltok::kw_opaque)) {
  2636. // This type is being defined, so clear the location to indicate this.
  2637. Entry.second = SMLoc();
  2638. // If this type number has never been uttered, create it.
  2639. if (!Entry.first)
  2640. Entry.first = StructType::create(Context, Name);
  2641. ResultTy = Entry.first;
  2642. return false;
  2643. }
  2644. // If the type starts with '<', then it is either a packed struct or a vector.
  2645. bool isPacked = EatIfPresent(lltok::less);
  2646. // If we don't have a struct, then we have a random type alias, which we
  2647. // accept for compatibility with old files. These types are not allowed to be
  2648. // forward referenced and not allowed to be recursive.
  2649. if (Lex.getKind() != lltok::lbrace) {
  2650. if (Entry.first)
  2651. return error(TypeLoc, "forward references to non-struct type");
  2652. ResultTy = nullptr;
  2653. if (isPacked)
  2654. return parseArrayVectorType(ResultTy, true);
  2655. return parseType(ResultTy);
  2656. }
  2657. // This type is being defined, so clear the location to indicate this.
  2658. Entry.second = SMLoc();
  2659. // If this type number has never been uttered, create it.
  2660. if (!Entry.first)
  2661. Entry.first = StructType::create(Context, Name);
  2662. StructType *STy = cast<StructType>(Entry.first);
  2663. SmallVector<Type*, 8> Body;
  2664. if (parseStructBody(Body) ||
  2665. (isPacked && parseToken(lltok::greater, "expected '>' in packed struct")))
  2666. return true;
  2667. STy->setBody(Body, isPacked);
  2668. ResultTy = STy;
  2669. return false;
  2670. }
  2671. /// parseStructType: Handles packed and unpacked types. </> parsed elsewhere.
  2672. /// StructType
  2673. /// ::= '{' '}'
  2674. /// ::= '{' Type (',' Type)* '}'
  2675. /// ::= '<' '{' '}' '>'
  2676. /// ::= '<' '{' Type (',' Type)* '}' '>'
  2677. bool LLParser::parseStructBody(SmallVectorImpl<Type *> &Body) {
  2678. assert(Lex.getKind() == lltok::lbrace);
  2679. Lex.Lex(); // Consume the '{'
  2680. // Handle the empty struct.
  2681. if (EatIfPresent(lltok::rbrace))
  2682. return false;
  2683. LocTy EltTyLoc = Lex.getLoc();
  2684. Type *Ty = nullptr;
  2685. if (parseType(Ty))
  2686. return true;
  2687. Body.push_back(Ty);
  2688. if (!StructType::isValidElementType(Ty))
  2689. return error(EltTyLoc, "invalid element type for struct");
  2690. while (EatIfPresent(lltok::comma)) {
  2691. EltTyLoc = Lex.getLoc();
  2692. if (parseType(Ty))
  2693. return true;
  2694. if (!StructType::isValidElementType(Ty))
  2695. return error(EltTyLoc, "invalid element type for struct");
  2696. Body.push_back(Ty);
  2697. }
  2698. return parseToken(lltok::rbrace, "expected '}' at end of struct");
  2699. }
  2700. /// parseArrayVectorType - parse an array or vector type, assuming the first
  2701. /// token has already been consumed.
  2702. /// Type
  2703. /// ::= '[' APSINTVAL 'x' Types ']'
  2704. /// ::= '<' APSINTVAL 'x' Types '>'
  2705. /// ::= '<' 'vscale' 'x' APSINTVAL 'x' Types '>'
  2706. bool LLParser::parseArrayVectorType(Type *&Result, bool IsVector) {
  2707. bool Scalable = false;
  2708. if (IsVector && Lex.getKind() == lltok::kw_vscale) {
  2709. Lex.Lex(); // consume the 'vscale'
  2710. if (parseToken(lltok::kw_x, "expected 'x' after vscale"))
  2711. return true;
  2712. Scalable = true;
  2713. }
  2714. if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
  2715. Lex.getAPSIntVal().getBitWidth() > 64)
  2716. return tokError("expected number in address space");
  2717. LocTy SizeLoc = Lex.getLoc();
  2718. uint64_t Size = Lex.getAPSIntVal().getZExtValue();
  2719. Lex.Lex();
  2720. if (parseToken(lltok::kw_x, "expected 'x' after element count"))
  2721. return true;
  2722. LocTy TypeLoc = Lex.getLoc();
  2723. Type *EltTy = nullptr;
  2724. if (parseType(EltTy))
  2725. return true;
  2726. if (parseToken(IsVector ? lltok::greater : lltok::rsquare,
  2727. "expected end of sequential type"))
  2728. return true;
  2729. if (IsVector) {
  2730. if (Size == 0)
  2731. return error(SizeLoc, "zero element vector is illegal");
  2732. if ((unsigned)Size != Size)
  2733. return error(SizeLoc, "size too large for vector");
  2734. if (!VectorType::isValidElementType(EltTy))
  2735. return error(TypeLoc, "invalid vector element type");
  2736. Result = VectorType::get(EltTy, unsigned(Size), Scalable);
  2737. } else {
  2738. if (!ArrayType::isValidElementType(EltTy))
  2739. return error(TypeLoc, "invalid array element type");
  2740. Result = ArrayType::get(EltTy, Size);
  2741. }
  2742. return false;
  2743. }
  2744. /// parseTargetExtType - handle target extension type syntax
  2745. /// TargetExtType
  2746. /// ::= 'target' '(' STRINGCONSTANT TargetExtTypeParams TargetExtIntParams ')'
  2747. ///
  2748. /// TargetExtTypeParams
  2749. /// ::= /*empty*/
  2750. /// ::= ',' Type TargetExtTypeParams
  2751. ///
  2752. /// TargetExtIntParams
  2753. /// ::= /*empty*/
  2754. /// ::= ',' uint32 TargetExtIntParams
  2755. bool LLParser::parseTargetExtType(Type *&Result) {
  2756. Lex.Lex(); // Eat the 'target' keyword.
  2757. // Get the mandatory type name.
  2758. std::string TypeName;
  2759. if (parseToken(lltok::lparen, "expected '(' in target extension type") ||
  2760. parseStringConstant(TypeName))
  2761. return true;
  2762. // Parse all of the integer and type parameters at the same time; the use of
  2763. // SeenInt will allow us to catch cases where type parameters follow integer
  2764. // parameters.
  2765. SmallVector<Type *> TypeParams;
  2766. SmallVector<unsigned> IntParams;
  2767. bool SeenInt = false;
  2768. while (Lex.getKind() == lltok::comma) {
  2769. Lex.Lex(); // Eat the comma.
  2770. if (Lex.getKind() == lltok::APSInt) {
  2771. SeenInt = true;
  2772. unsigned IntVal;
  2773. if (parseUInt32(IntVal))
  2774. return true;
  2775. IntParams.push_back(IntVal);
  2776. } else if (SeenInt) {
  2777. // The only other kind of parameter we support is type parameters, which
  2778. // must precede the integer parameters. This is therefore an error.
  2779. return tokError("expected uint32 param");
  2780. } else {
  2781. Type *TypeParam;
  2782. if (parseType(TypeParam, /*AllowVoid=*/true))
  2783. return true;
  2784. TypeParams.push_back(TypeParam);
  2785. }
  2786. }
  2787. if (parseToken(lltok::rparen, "expected ')' in target extension type"))
  2788. return true;
  2789. Result = TargetExtType::get(Context, TypeName, TypeParams, IntParams);
  2790. return false;
  2791. }
  2792. //===----------------------------------------------------------------------===//
  2793. // Function Semantic Analysis.
  2794. //===----------------------------------------------------------------------===//
  2795. LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
  2796. int functionNumber)
  2797. : P(p), F(f), FunctionNumber(functionNumber) {
  2798. // Insert unnamed arguments into the NumberedVals list.
  2799. for (Argument &A : F.args())
  2800. if (!A.hasName())
  2801. NumberedVals.push_back(&A);
  2802. }
  2803. LLParser::PerFunctionState::~PerFunctionState() {
  2804. // If there were any forward referenced non-basicblock values, delete them.
  2805. for (const auto &P : ForwardRefVals) {
  2806. if (isa<BasicBlock>(P.second.first))
  2807. continue;
  2808. P.second.first->replaceAllUsesWith(
  2809. UndefValue::get(P.second.first->getType()));
  2810. P.second.first->deleteValue();
  2811. }
  2812. for (const auto &P : ForwardRefValIDs) {
  2813. if (isa<BasicBlock>(P.second.first))
  2814. continue;
  2815. P.second.first->replaceAllUsesWith(
  2816. UndefValue::get(P.second.first->getType()));
  2817. P.second.first->deleteValue();
  2818. }
  2819. }
  2820. bool LLParser::PerFunctionState::finishFunction() {
  2821. if (!ForwardRefVals.empty())
  2822. return P.error(ForwardRefVals.begin()->second.second,
  2823. "use of undefined value '%" + ForwardRefVals.begin()->first +
  2824. "'");
  2825. if (!ForwardRefValIDs.empty())
  2826. return P.error(ForwardRefValIDs.begin()->second.second,
  2827. "use of undefined value '%" +
  2828. Twine(ForwardRefValIDs.begin()->first) + "'");
  2829. return false;
  2830. }
  2831. /// getVal - Get a value with the specified name or ID, creating a
  2832. /// forward reference record if needed. This can return null if the value
  2833. /// exists but does not have the right type.
  2834. Value *LLParser::PerFunctionState::getVal(const std::string &Name, Type *Ty,
  2835. LocTy Loc) {
  2836. // Look this name up in the normal function symbol table.
  2837. Value *Val = F.getValueSymbolTable()->lookup(Name);
  2838. // If this is a forward reference for the value, see if we already created a
  2839. // forward ref record.
  2840. if (!Val) {
  2841. auto I = ForwardRefVals.find(Name);
  2842. if (I != ForwardRefVals.end())
  2843. Val = I->second.first;
  2844. }
  2845. // If we have the value in the symbol table or fwd-ref table, return it.
  2846. if (Val)
  2847. return P.checkValidVariableType(Loc, "%" + Name, Ty, Val);
  2848. // Don't make placeholders with invalid type.
  2849. if (!Ty->isFirstClassType()) {
  2850. P.error(Loc, "invalid use of a non-first-class type");
  2851. return nullptr;
  2852. }
  2853. // Otherwise, create a new forward reference for this value and remember it.
  2854. Value *FwdVal;
  2855. if (Ty->isLabelTy()) {
  2856. FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
  2857. } else {
  2858. FwdVal = new Argument(Ty, Name);
  2859. }
  2860. ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
  2861. return FwdVal;
  2862. }
  2863. Value *LLParser::PerFunctionState::getVal(unsigned ID, Type *Ty, LocTy Loc) {
  2864. // Look this name up in the normal function symbol table.
  2865. Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
  2866. // If this is a forward reference for the value, see if we already created a
  2867. // forward ref record.
  2868. if (!Val) {
  2869. auto I = ForwardRefValIDs.find(ID);
  2870. if (I != ForwardRefValIDs.end())
  2871. Val = I->second.first;
  2872. }
  2873. // If we have the value in the symbol table or fwd-ref table, return it.
  2874. if (Val)
  2875. return P.checkValidVariableType(Loc, "%" + Twine(ID), Ty, Val);
  2876. if (!Ty->isFirstClassType()) {
  2877. P.error(Loc, "invalid use of a non-first-class type");
  2878. return nullptr;
  2879. }
  2880. // Otherwise, create a new forward reference for this value and remember it.
  2881. Value *FwdVal;
  2882. if (Ty->isLabelTy()) {
  2883. FwdVal = BasicBlock::Create(F.getContext(), "", &F);
  2884. } else {
  2885. FwdVal = new Argument(Ty);
  2886. }
  2887. ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
  2888. return FwdVal;
  2889. }
  2890. /// setInstName - After an instruction is parsed and inserted into its
  2891. /// basic block, this installs its name.
  2892. bool LLParser::PerFunctionState::setInstName(int NameID,
  2893. const std::string &NameStr,
  2894. LocTy NameLoc, Instruction *Inst) {
  2895. // If this instruction has void type, it cannot have a name or ID specified.
  2896. if (Inst->getType()->isVoidTy()) {
  2897. if (NameID != -1 || !NameStr.empty())
  2898. return P.error(NameLoc, "instructions returning void cannot have a name");
  2899. return false;
  2900. }
  2901. // If this was a numbered instruction, verify that the instruction is the
  2902. // expected value and resolve any forward references.
  2903. if (NameStr.empty()) {
  2904. // If neither a name nor an ID was specified, just use the next ID.
  2905. if (NameID == -1)
  2906. NameID = NumberedVals.size();
  2907. if (unsigned(NameID) != NumberedVals.size())
  2908. return P.error(NameLoc, "instruction expected to be numbered '%" +
  2909. Twine(NumberedVals.size()) + "'");
  2910. auto FI = ForwardRefValIDs.find(NameID);
  2911. if (FI != ForwardRefValIDs.end()) {
  2912. Value *Sentinel = FI->second.first;
  2913. if (Sentinel->getType() != Inst->getType())
  2914. return P.error(NameLoc, "instruction forward referenced with type '" +
  2915. getTypeString(FI->second.first->getType()) +
  2916. "'");
  2917. Sentinel->replaceAllUsesWith(Inst);
  2918. Sentinel->deleteValue();
  2919. ForwardRefValIDs.erase(FI);
  2920. }
  2921. NumberedVals.push_back(Inst);
  2922. return false;
  2923. }
  2924. // Otherwise, the instruction had a name. Resolve forward refs and set it.
  2925. auto FI = ForwardRefVals.find(NameStr);
  2926. if (FI != ForwardRefVals.end()) {
  2927. Value *Sentinel = FI->second.first;
  2928. if (Sentinel->getType() != Inst->getType())
  2929. return P.error(NameLoc, "instruction forward referenced with type '" +
  2930. getTypeString(FI->second.first->getType()) +
  2931. "'");
  2932. Sentinel->replaceAllUsesWith(Inst);
  2933. Sentinel->deleteValue();
  2934. ForwardRefVals.erase(FI);
  2935. }
  2936. // Set the name on the instruction.
  2937. Inst->setName(NameStr);
  2938. if (Inst->getName() != NameStr)
  2939. return P.error(NameLoc, "multiple definition of local value named '" +
  2940. NameStr + "'");
  2941. return false;
  2942. }
  2943. /// getBB - Get a basic block with the specified name or ID, creating a
  2944. /// forward reference record if needed.
  2945. BasicBlock *LLParser::PerFunctionState::getBB(const std::string &Name,
  2946. LocTy Loc) {
  2947. return dyn_cast_or_null<BasicBlock>(
  2948. getVal(Name, Type::getLabelTy(F.getContext()), Loc));
  2949. }
  2950. BasicBlock *LLParser::PerFunctionState::getBB(unsigned ID, LocTy Loc) {
  2951. return dyn_cast_or_null<BasicBlock>(
  2952. getVal(ID, Type::getLabelTy(F.getContext()), Loc));
  2953. }
  2954. /// defineBB - Define the specified basic block, which is either named or
  2955. /// unnamed. If there is an error, this returns null otherwise it returns
  2956. /// the block being defined.
  2957. BasicBlock *LLParser::PerFunctionState::defineBB(const std::string &Name,
  2958. int NameID, LocTy Loc) {
  2959. BasicBlock *BB;
  2960. if (Name.empty()) {
  2961. if (NameID != -1 && unsigned(NameID) != NumberedVals.size()) {
  2962. P.error(Loc, "label expected to be numbered '" +
  2963. Twine(NumberedVals.size()) + "'");
  2964. return nullptr;
  2965. }
  2966. BB = getBB(NumberedVals.size(), Loc);
  2967. if (!BB) {
  2968. P.error(Loc, "unable to create block numbered '" +
  2969. Twine(NumberedVals.size()) + "'");
  2970. return nullptr;
  2971. }
  2972. } else {
  2973. BB = getBB(Name, Loc);
  2974. if (!BB) {
  2975. P.error(Loc, "unable to create block named '" + Name + "'");
  2976. return nullptr;
  2977. }
  2978. }
  2979. // Move the block to the end of the function. Forward ref'd blocks are
  2980. // inserted wherever they happen to be referenced.
  2981. F.splice(F.end(), &F, BB->getIterator());
  2982. // Remove the block from forward ref sets.
  2983. if (Name.empty()) {
  2984. ForwardRefValIDs.erase(NumberedVals.size());
  2985. NumberedVals.push_back(BB);
  2986. } else {
  2987. // BB forward references are already in the function symbol table.
  2988. ForwardRefVals.erase(Name);
  2989. }
  2990. return BB;
  2991. }
  2992. //===----------------------------------------------------------------------===//
  2993. // Constants.
  2994. //===----------------------------------------------------------------------===//
  2995. /// parseValID - parse an abstract value that doesn't necessarily have a
  2996. /// type implied. For example, if we parse "4" we don't know what integer type
  2997. /// it has. The value will later be combined with its type and checked for
  2998. /// basic correctness. PFS is used to convert function-local operands of
  2999. /// metadata (since metadata operands are not just parsed here but also
  3000. /// converted to values). PFS can be null when we are not parsing metadata
  3001. /// values inside a function.
  3002. bool LLParser::parseValID(ValID &ID, PerFunctionState *PFS, Type *ExpectedTy) {
  3003. ID.Loc = Lex.getLoc();
  3004. switch (Lex.getKind()) {
  3005. default:
  3006. return tokError("expected value token");
  3007. case lltok::GlobalID: // @42
  3008. ID.UIntVal = Lex.getUIntVal();
  3009. ID.Kind = ValID::t_GlobalID;
  3010. break;
  3011. case lltok::GlobalVar: // @foo
  3012. ID.StrVal = Lex.getStrVal();
  3013. ID.Kind = ValID::t_GlobalName;
  3014. break;
  3015. case lltok::LocalVarID: // %42
  3016. ID.UIntVal = Lex.getUIntVal();
  3017. ID.Kind = ValID::t_LocalID;
  3018. break;
  3019. case lltok::LocalVar: // %foo
  3020. ID.StrVal = Lex.getStrVal();
  3021. ID.Kind = ValID::t_LocalName;
  3022. break;
  3023. case lltok::APSInt:
  3024. ID.APSIntVal = Lex.getAPSIntVal();
  3025. ID.Kind = ValID::t_APSInt;
  3026. break;
  3027. case lltok::APFloat:
  3028. ID.APFloatVal = Lex.getAPFloatVal();
  3029. ID.Kind = ValID::t_APFloat;
  3030. break;
  3031. case lltok::kw_true:
  3032. ID.ConstantVal = ConstantInt::getTrue(Context);
  3033. ID.Kind = ValID::t_Constant;
  3034. break;
  3035. case lltok::kw_false:
  3036. ID.ConstantVal = ConstantInt::getFalse(Context);
  3037. ID.Kind = ValID::t_Constant;
  3038. break;
  3039. case lltok::kw_null: ID.Kind = ValID::t_Null; break;
  3040. case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
  3041. case lltok::kw_poison: ID.Kind = ValID::t_Poison; break;
  3042. case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
  3043. case lltok::kw_none: ID.Kind = ValID::t_None; break;
  3044. case lltok::lbrace: {
  3045. // ValID ::= '{' ConstVector '}'
  3046. Lex.Lex();
  3047. SmallVector<Constant*, 16> Elts;
  3048. if (parseGlobalValueVector(Elts) ||
  3049. parseToken(lltok::rbrace, "expected end of struct constant"))
  3050. return true;
  3051. ID.ConstantStructElts = std::make_unique<Constant *[]>(Elts.size());
  3052. ID.UIntVal = Elts.size();
  3053. memcpy(ID.ConstantStructElts.get(), Elts.data(),
  3054. Elts.size() * sizeof(Elts[0]));
  3055. ID.Kind = ValID::t_ConstantStruct;
  3056. return false;
  3057. }
  3058. case lltok::less: {
  3059. // ValID ::= '<' ConstVector '>' --> Vector.
  3060. // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
  3061. Lex.Lex();
  3062. bool isPackedStruct = EatIfPresent(lltok::lbrace);
  3063. SmallVector<Constant*, 16> Elts;
  3064. LocTy FirstEltLoc = Lex.getLoc();
  3065. if (parseGlobalValueVector(Elts) ||
  3066. (isPackedStruct &&
  3067. parseToken(lltok::rbrace, "expected end of packed struct")) ||
  3068. parseToken(lltok::greater, "expected end of constant"))
  3069. return true;
  3070. if (isPackedStruct) {
  3071. ID.ConstantStructElts = std::make_unique<Constant *[]>(Elts.size());
  3072. memcpy(ID.ConstantStructElts.get(), Elts.data(),
  3073. Elts.size() * sizeof(Elts[0]));
  3074. ID.UIntVal = Elts.size();
  3075. ID.Kind = ValID::t_PackedConstantStruct;
  3076. return false;
  3077. }
  3078. if (Elts.empty())
  3079. return error(ID.Loc, "constant vector must not be empty");
  3080. if (!Elts[0]->getType()->isIntegerTy() &&
  3081. !Elts[0]->getType()->isFloatingPointTy() &&
  3082. !Elts[0]->getType()->isPointerTy())
  3083. return error(
  3084. FirstEltLoc,
  3085. "vector elements must have integer, pointer or floating point type");
  3086. // Verify that all the vector elements have the same type.
  3087. for (unsigned i = 1, e = Elts.size(); i != e; ++i)
  3088. if (Elts[i]->getType() != Elts[0]->getType())
  3089. return error(FirstEltLoc, "vector element #" + Twine(i) +
  3090. " is not of type '" +
  3091. getTypeString(Elts[0]->getType()));
  3092. ID.ConstantVal = ConstantVector::get(Elts);
  3093. ID.Kind = ValID::t_Constant;
  3094. return false;
  3095. }
  3096. case lltok::lsquare: { // Array Constant
  3097. Lex.Lex();
  3098. SmallVector<Constant*, 16> Elts;
  3099. LocTy FirstEltLoc = Lex.getLoc();
  3100. if (parseGlobalValueVector(Elts) ||
  3101. parseToken(lltok::rsquare, "expected end of array constant"))
  3102. return true;
  3103. // Handle empty element.
  3104. if (Elts.empty()) {
  3105. // Use undef instead of an array because it's inconvenient to determine
  3106. // the element type at this point, there being no elements to examine.
  3107. ID.Kind = ValID::t_EmptyArray;
  3108. return false;
  3109. }
  3110. if (!Elts[0]->getType()->isFirstClassType())
  3111. return error(FirstEltLoc, "invalid array element type: " +
  3112. getTypeString(Elts[0]->getType()));
  3113. ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
  3114. // Verify all elements are correct type!
  3115. for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
  3116. if (Elts[i]->getType() != Elts[0]->getType())
  3117. return error(FirstEltLoc, "array element #" + Twine(i) +
  3118. " is not of type '" +
  3119. getTypeString(Elts[0]->getType()));
  3120. }
  3121. ID.ConstantVal = ConstantArray::get(ATy, Elts);
  3122. ID.Kind = ValID::t_Constant;
  3123. return false;
  3124. }
  3125. case lltok::kw_c: // c "foo"
  3126. Lex.Lex();
  3127. ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(),
  3128. false);
  3129. if (parseToken(lltok::StringConstant, "expected string"))
  3130. return true;
  3131. ID.Kind = ValID::t_Constant;
  3132. return false;
  3133. case lltok::kw_asm: {
  3134. // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ','
  3135. // STRINGCONSTANT
  3136. bool HasSideEffect, AlignStack, AsmDialect, CanThrow;
  3137. Lex.Lex();
  3138. if (parseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
  3139. parseOptionalToken(lltok::kw_alignstack, AlignStack) ||
  3140. parseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
  3141. parseOptionalToken(lltok::kw_unwind, CanThrow) ||
  3142. parseStringConstant(ID.StrVal) ||
  3143. parseToken(lltok::comma, "expected comma in inline asm expression") ||
  3144. parseToken(lltok::StringConstant, "expected constraint string"))
  3145. return true;
  3146. ID.StrVal2 = Lex.getStrVal();
  3147. ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack) << 1) |
  3148. (unsigned(AsmDialect) << 2) | (unsigned(CanThrow) << 3);
  3149. ID.Kind = ValID::t_InlineAsm;
  3150. return false;
  3151. }
  3152. case lltok::kw_blockaddress: {
  3153. // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
  3154. Lex.Lex();
  3155. ValID Fn, Label;
  3156. if (parseToken(lltok::lparen, "expected '(' in block address expression") ||
  3157. parseValID(Fn, PFS) ||
  3158. parseToken(lltok::comma,
  3159. "expected comma in block address expression") ||
  3160. parseValID(Label, PFS) ||
  3161. parseToken(lltok::rparen, "expected ')' in block address expression"))
  3162. return true;
  3163. if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
  3164. return error(Fn.Loc, "expected function name in blockaddress");
  3165. if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
  3166. return error(Label.Loc, "expected basic block name in blockaddress");
  3167. // Try to find the function (but skip it if it's forward-referenced).
  3168. GlobalValue *GV = nullptr;
  3169. if (Fn.Kind == ValID::t_GlobalID) {
  3170. if (Fn.UIntVal < NumberedVals.size())
  3171. GV = NumberedVals[Fn.UIntVal];
  3172. } else if (!ForwardRefVals.count(Fn.StrVal)) {
  3173. GV = M->getNamedValue(Fn.StrVal);
  3174. }
  3175. Function *F = nullptr;
  3176. if (GV) {
  3177. // Confirm that it's actually a function with a definition.
  3178. if (!isa<Function>(GV))
  3179. return error(Fn.Loc, "expected function name in blockaddress");
  3180. F = cast<Function>(GV);
  3181. if (F->isDeclaration())
  3182. return error(Fn.Loc, "cannot take blockaddress inside a declaration");
  3183. }
  3184. if (!F) {
  3185. // Make a global variable as a placeholder for this reference.
  3186. GlobalValue *&FwdRef =
  3187. ForwardRefBlockAddresses.insert(std::make_pair(
  3188. std::move(Fn),
  3189. std::map<ValID, GlobalValue *>()))
  3190. .first->second.insert(std::make_pair(std::move(Label), nullptr))
  3191. .first->second;
  3192. if (!FwdRef) {
  3193. unsigned FwdDeclAS;
  3194. if (ExpectedTy) {
  3195. // If we know the type that the blockaddress is being assigned to,
  3196. // we can use the address space of that type.
  3197. if (!ExpectedTy->isPointerTy())
  3198. return error(ID.Loc,
  3199. "type of blockaddress must be a pointer and not '" +
  3200. getTypeString(ExpectedTy) + "'");
  3201. FwdDeclAS = ExpectedTy->getPointerAddressSpace();
  3202. } else if (PFS) {
  3203. // Otherwise, we default the address space of the current function.
  3204. FwdDeclAS = PFS->getFunction().getAddressSpace();
  3205. } else {
  3206. llvm_unreachable("Unknown address space for blockaddress");
  3207. }
  3208. FwdRef = new GlobalVariable(
  3209. *M, Type::getInt8Ty(Context), false, GlobalValue::InternalLinkage,
  3210. nullptr, "", nullptr, GlobalValue::NotThreadLocal, FwdDeclAS);
  3211. }
  3212. ID.ConstantVal = FwdRef;
  3213. ID.Kind = ValID::t_Constant;
  3214. return false;
  3215. }
  3216. // We found the function; now find the basic block. Don't use PFS, since we
  3217. // might be inside a constant expression.
  3218. BasicBlock *BB;
  3219. if (BlockAddressPFS && F == &BlockAddressPFS->getFunction()) {
  3220. if (Label.Kind == ValID::t_LocalID)
  3221. BB = BlockAddressPFS->getBB(Label.UIntVal, Label.Loc);
  3222. else
  3223. BB = BlockAddressPFS->getBB(Label.StrVal, Label.Loc);
  3224. if (!BB)
  3225. return error(Label.Loc, "referenced value is not a basic block");
  3226. } else {
  3227. if (Label.Kind == ValID::t_LocalID)
  3228. return error(Label.Loc, "cannot take address of numeric label after "
  3229. "the function is defined");
  3230. BB = dyn_cast_or_null<BasicBlock>(
  3231. F->getValueSymbolTable()->lookup(Label.StrVal));
  3232. if (!BB)
  3233. return error(Label.Loc, "referenced value is not a basic block");
  3234. }
  3235. ID.ConstantVal = BlockAddress::get(F, BB);
  3236. ID.Kind = ValID::t_Constant;
  3237. return false;
  3238. }
  3239. case lltok::kw_dso_local_equivalent: {
  3240. // ValID ::= 'dso_local_equivalent' @foo
  3241. Lex.Lex();
  3242. ValID Fn;
  3243. if (parseValID(Fn, PFS))
  3244. return true;
  3245. if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
  3246. return error(Fn.Loc,
  3247. "expected global value name in dso_local_equivalent");
  3248. // Try to find the function (but skip it if it's forward-referenced).
  3249. GlobalValue *GV = nullptr;
  3250. if (Fn.Kind == ValID::t_GlobalID) {
  3251. if (Fn.UIntVal < NumberedVals.size())
  3252. GV = NumberedVals[Fn.UIntVal];
  3253. } else if (!ForwardRefVals.count(Fn.StrVal)) {
  3254. GV = M->getNamedValue(Fn.StrVal);
  3255. }
  3256. if (!GV) {
  3257. // Make a placeholder global variable as a placeholder for this reference.
  3258. auto &FwdRefMap = (Fn.Kind == ValID::t_GlobalID)
  3259. ? ForwardRefDSOLocalEquivalentIDs
  3260. : ForwardRefDSOLocalEquivalentNames;
  3261. GlobalValue *&FwdRef = FwdRefMap.try_emplace(Fn, nullptr).first->second;
  3262. if (!FwdRef) {
  3263. FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context), false,
  3264. GlobalValue::InternalLinkage, nullptr, "",
  3265. nullptr, GlobalValue::NotThreadLocal);
  3266. }
  3267. ID.ConstantVal = FwdRef;
  3268. ID.Kind = ValID::t_Constant;
  3269. return false;
  3270. }
  3271. if (!GV->getValueType()->isFunctionTy())
  3272. return error(Fn.Loc, "expected a function, alias to function, or ifunc "
  3273. "in dso_local_equivalent");
  3274. ID.ConstantVal = DSOLocalEquivalent::get(GV);
  3275. ID.Kind = ValID::t_Constant;
  3276. return false;
  3277. }
  3278. case lltok::kw_no_cfi: {
  3279. // ValID ::= 'no_cfi' @foo
  3280. Lex.Lex();
  3281. if (parseValID(ID, PFS))
  3282. return true;
  3283. if (ID.Kind != ValID::t_GlobalID && ID.Kind != ValID::t_GlobalName)
  3284. return error(ID.Loc, "expected global value name in no_cfi");
  3285. ID.NoCFI = true;
  3286. return false;
  3287. }
  3288. case lltok::kw_trunc:
  3289. case lltok::kw_zext:
  3290. case lltok::kw_sext:
  3291. case lltok::kw_fptrunc:
  3292. case lltok::kw_fpext:
  3293. case lltok::kw_bitcast:
  3294. case lltok::kw_addrspacecast:
  3295. case lltok::kw_uitofp:
  3296. case lltok::kw_sitofp:
  3297. case lltok::kw_fptoui:
  3298. case lltok::kw_fptosi:
  3299. case lltok::kw_inttoptr:
  3300. case lltok::kw_ptrtoint: {
  3301. unsigned Opc = Lex.getUIntVal();
  3302. Type *DestTy = nullptr;
  3303. Constant *SrcVal;
  3304. Lex.Lex();
  3305. if (parseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
  3306. parseGlobalTypeAndValue(SrcVal) ||
  3307. parseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
  3308. parseType(DestTy) ||
  3309. parseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
  3310. return true;
  3311. if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
  3312. return error(ID.Loc, "invalid cast opcode for cast from '" +
  3313. getTypeString(SrcVal->getType()) + "' to '" +
  3314. getTypeString(DestTy) + "'");
  3315. ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
  3316. SrcVal, DestTy);
  3317. ID.Kind = ValID::t_Constant;
  3318. return false;
  3319. }
  3320. case lltok::kw_extractvalue:
  3321. return error(ID.Loc, "extractvalue constexprs are no longer supported");
  3322. case lltok::kw_insertvalue:
  3323. return error(ID.Loc, "insertvalue constexprs are no longer supported");
  3324. case lltok::kw_udiv:
  3325. return error(ID.Loc, "udiv constexprs are no longer supported");
  3326. case lltok::kw_sdiv:
  3327. return error(ID.Loc, "sdiv constexprs are no longer supported");
  3328. case lltok::kw_urem:
  3329. return error(ID.Loc, "urem constexprs are no longer supported");
  3330. case lltok::kw_srem:
  3331. return error(ID.Loc, "srem constexprs are no longer supported");
  3332. case lltok::kw_fadd:
  3333. return error(ID.Loc, "fadd constexprs are no longer supported");
  3334. case lltok::kw_fsub:
  3335. return error(ID.Loc, "fsub constexprs are no longer supported");
  3336. case lltok::kw_fmul:
  3337. return error(ID.Loc, "fmul constexprs are no longer supported");
  3338. case lltok::kw_fdiv:
  3339. return error(ID.Loc, "fdiv constexprs are no longer supported");
  3340. case lltok::kw_frem:
  3341. return error(ID.Loc, "frem constexprs are no longer supported");
  3342. case lltok::kw_fneg:
  3343. return error(ID.Loc, "fneg constexprs are no longer supported");
  3344. case lltok::kw_icmp:
  3345. case lltok::kw_fcmp: {
  3346. unsigned PredVal, Opc = Lex.getUIntVal();
  3347. Constant *Val0, *Val1;
  3348. Lex.Lex();
  3349. if (parseCmpPredicate(PredVal, Opc) ||
  3350. parseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
  3351. parseGlobalTypeAndValue(Val0) ||
  3352. parseToken(lltok::comma, "expected comma in compare constantexpr") ||
  3353. parseGlobalTypeAndValue(Val1) ||
  3354. parseToken(lltok::rparen, "expected ')' in compare constantexpr"))
  3355. return true;
  3356. if (Val0->getType() != Val1->getType())
  3357. return error(ID.Loc, "compare operands must have the same type");
  3358. CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
  3359. if (Opc == Instruction::FCmp) {
  3360. if (!Val0->getType()->isFPOrFPVectorTy())
  3361. return error(ID.Loc, "fcmp requires floating point operands");
  3362. ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
  3363. } else {
  3364. assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
  3365. if (!Val0->getType()->isIntOrIntVectorTy() &&
  3366. !Val0->getType()->isPtrOrPtrVectorTy())
  3367. return error(ID.Loc, "icmp requires pointer or integer operands");
  3368. ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
  3369. }
  3370. ID.Kind = ValID::t_Constant;
  3371. return false;
  3372. }
  3373. // Binary Operators.
  3374. case lltok::kw_add:
  3375. case lltok::kw_sub:
  3376. case lltok::kw_mul:
  3377. case lltok::kw_shl:
  3378. case lltok::kw_lshr:
  3379. case lltok::kw_ashr: {
  3380. bool NUW = false;
  3381. bool NSW = false;
  3382. bool Exact = false;
  3383. unsigned Opc = Lex.getUIntVal();
  3384. Constant *Val0, *Val1;
  3385. Lex.Lex();
  3386. if (Opc == Instruction::Add || Opc == Instruction::Sub ||
  3387. Opc == Instruction::Mul || Opc == Instruction::Shl) {
  3388. if (EatIfPresent(lltok::kw_nuw))
  3389. NUW = true;
  3390. if (EatIfPresent(lltok::kw_nsw)) {
  3391. NSW = true;
  3392. if (EatIfPresent(lltok::kw_nuw))
  3393. NUW = true;
  3394. }
  3395. } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
  3396. Opc == Instruction::LShr || Opc == Instruction::AShr) {
  3397. if (EatIfPresent(lltok::kw_exact))
  3398. Exact = true;
  3399. }
  3400. if (parseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
  3401. parseGlobalTypeAndValue(Val0) ||
  3402. parseToken(lltok::comma, "expected comma in binary constantexpr") ||
  3403. parseGlobalTypeAndValue(Val1) ||
  3404. parseToken(lltok::rparen, "expected ')' in binary constantexpr"))
  3405. return true;
  3406. if (Val0->getType() != Val1->getType())
  3407. return error(ID.Loc, "operands of constexpr must have same type");
  3408. // Check that the type is valid for the operator.
  3409. switch (Opc) {
  3410. case Instruction::Add:
  3411. case Instruction::Sub:
  3412. case Instruction::Mul:
  3413. case Instruction::UDiv:
  3414. case Instruction::SDiv:
  3415. case Instruction::URem:
  3416. case Instruction::SRem:
  3417. case Instruction::Shl:
  3418. case Instruction::AShr:
  3419. case Instruction::LShr:
  3420. if (!Val0->getType()->isIntOrIntVectorTy())
  3421. return error(ID.Loc, "constexpr requires integer operands");
  3422. break;
  3423. case Instruction::FAdd:
  3424. case Instruction::FSub:
  3425. case Instruction::FMul:
  3426. case Instruction::FDiv:
  3427. case Instruction::FRem:
  3428. if (!Val0->getType()->isFPOrFPVectorTy())
  3429. return error(ID.Loc, "constexpr requires fp operands");
  3430. break;
  3431. default: llvm_unreachable("Unknown binary operator!");
  3432. }
  3433. unsigned Flags = 0;
  3434. if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
  3435. if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
  3436. if (Exact) Flags |= PossiblyExactOperator::IsExact;
  3437. Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
  3438. ID.ConstantVal = C;
  3439. ID.Kind = ValID::t_Constant;
  3440. return false;
  3441. }
  3442. // Logical Operations
  3443. case lltok::kw_and:
  3444. case lltok::kw_or:
  3445. case lltok::kw_xor: {
  3446. unsigned Opc = Lex.getUIntVal();
  3447. Constant *Val0, *Val1;
  3448. Lex.Lex();
  3449. if (parseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
  3450. parseGlobalTypeAndValue(Val0) ||
  3451. parseToken(lltok::comma, "expected comma in logical constantexpr") ||
  3452. parseGlobalTypeAndValue(Val1) ||
  3453. parseToken(lltok::rparen, "expected ')' in logical constantexpr"))
  3454. return true;
  3455. if (Val0->getType() != Val1->getType())
  3456. return error(ID.Loc, "operands of constexpr must have same type");
  3457. if (!Val0->getType()->isIntOrIntVectorTy())
  3458. return error(ID.Loc,
  3459. "constexpr requires integer or integer vector operands");
  3460. ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
  3461. ID.Kind = ValID::t_Constant;
  3462. return false;
  3463. }
  3464. case lltok::kw_getelementptr:
  3465. case lltok::kw_shufflevector:
  3466. case lltok::kw_insertelement:
  3467. case lltok::kw_extractelement:
  3468. case lltok::kw_select: {
  3469. unsigned Opc = Lex.getUIntVal();
  3470. SmallVector<Constant*, 16> Elts;
  3471. bool InBounds = false;
  3472. Type *Ty;
  3473. Lex.Lex();
  3474. if (Opc == Instruction::GetElementPtr)
  3475. InBounds = EatIfPresent(lltok::kw_inbounds);
  3476. if (parseToken(lltok::lparen, "expected '(' in constantexpr"))
  3477. return true;
  3478. LocTy ExplicitTypeLoc = Lex.getLoc();
  3479. if (Opc == Instruction::GetElementPtr) {
  3480. if (parseType(Ty) ||
  3481. parseToken(lltok::comma, "expected comma after getelementptr's type"))
  3482. return true;
  3483. }
  3484. std::optional<unsigned> InRangeOp;
  3485. if (parseGlobalValueVector(
  3486. Elts, Opc == Instruction::GetElementPtr ? &InRangeOp : nullptr) ||
  3487. parseToken(lltok::rparen, "expected ')' in constantexpr"))
  3488. return true;
  3489. if (Opc == Instruction::GetElementPtr) {
  3490. if (Elts.size() == 0 ||
  3491. !Elts[0]->getType()->isPtrOrPtrVectorTy())
  3492. return error(ID.Loc, "base of getelementptr must be a pointer");
  3493. Type *BaseType = Elts[0]->getType();
  3494. auto *BasePointerType = cast<PointerType>(BaseType->getScalarType());
  3495. if (!BasePointerType->isOpaqueOrPointeeTypeMatches(Ty)) {
  3496. return error(
  3497. ExplicitTypeLoc,
  3498. typeComparisonErrorMessage(
  3499. "explicit pointee type doesn't match operand's pointee type",
  3500. Ty, BasePointerType->getNonOpaquePointerElementType()));
  3501. }
  3502. unsigned GEPWidth =
  3503. BaseType->isVectorTy()
  3504. ? cast<FixedVectorType>(BaseType)->getNumElements()
  3505. : 0;
  3506. ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
  3507. for (Constant *Val : Indices) {
  3508. Type *ValTy = Val->getType();
  3509. if (!ValTy->isIntOrIntVectorTy())
  3510. return error(ID.Loc, "getelementptr index must be an integer");
  3511. if (auto *ValVTy = dyn_cast<VectorType>(ValTy)) {
  3512. unsigned ValNumEl = cast<FixedVectorType>(ValVTy)->getNumElements();
  3513. if (GEPWidth && (ValNumEl != GEPWidth))
  3514. return error(
  3515. ID.Loc,
  3516. "getelementptr vector index has a wrong number of elements");
  3517. // GEPWidth may have been unknown because the base is a scalar,
  3518. // but it is known now.
  3519. GEPWidth = ValNumEl;
  3520. }
  3521. }
  3522. SmallPtrSet<Type*, 4> Visited;
  3523. if (!Indices.empty() && !Ty->isSized(&Visited))
  3524. return error(ID.Loc, "base element of getelementptr must be sized");
  3525. if (!GetElementPtrInst::getIndexedType(Ty, Indices))
  3526. return error(ID.Loc, "invalid getelementptr indices");
  3527. if (InRangeOp) {
  3528. if (*InRangeOp == 0)
  3529. return error(ID.Loc,
  3530. "inrange keyword may not appear on pointer operand");
  3531. --*InRangeOp;
  3532. }
  3533. ID.ConstantVal = ConstantExpr::getGetElementPtr(Ty, Elts[0], Indices,
  3534. InBounds, InRangeOp);
  3535. } else if (Opc == Instruction::Select) {
  3536. if (Elts.size() != 3)
  3537. return error(ID.Loc, "expected three operands to select");
  3538. if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
  3539. Elts[2]))
  3540. return error(ID.Loc, Reason);
  3541. ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
  3542. } else if (Opc == Instruction::ShuffleVector) {
  3543. if (Elts.size() != 3)
  3544. return error(ID.Loc, "expected three operands to shufflevector");
  3545. if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
  3546. return error(ID.Loc, "invalid operands to shufflevector");
  3547. SmallVector<int, 16> Mask;
  3548. ShuffleVectorInst::getShuffleMask(cast<Constant>(Elts[2]), Mask);
  3549. ID.ConstantVal = ConstantExpr::getShuffleVector(Elts[0], Elts[1], Mask);
  3550. } else if (Opc == Instruction::ExtractElement) {
  3551. if (Elts.size() != 2)
  3552. return error(ID.Loc, "expected two operands to extractelement");
  3553. if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
  3554. return error(ID.Loc, "invalid extractelement operands");
  3555. ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
  3556. } else {
  3557. assert(Opc == Instruction::InsertElement && "Unknown opcode");
  3558. if (Elts.size() != 3)
  3559. return error(ID.Loc, "expected three operands to insertelement");
  3560. if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
  3561. return error(ID.Loc, "invalid insertelement operands");
  3562. ID.ConstantVal =
  3563. ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
  3564. }
  3565. ID.Kind = ValID::t_Constant;
  3566. return false;
  3567. }
  3568. }
  3569. Lex.Lex();
  3570. return false;
  3571. }
  3572. /// parseGlobalValue - parse a global value with the specified type.
  3573. bool LLParser::parseGlobalValue(Type *Ty, Constant *&C) {
  3574. C = nullptr;
  3575. ValID ID;
  3576. Value *V = nullptr;
  3577. bool Parsed = parseValID(ID, /*PFS=*/nullptr, Ty) ||
  3578. convertValIDToValue(Ty, ID, V, nullptr);
  3579. if (V && !(C = dyn_cast<Constant>(V)))
  3580. return error(ID.Loc, "global values must be constants");
  3581. return Parsed;
  3582. }
  3583. bool LLParser::parseGlobalTypeAndValue(Constant *&V) {
  3584. Type *Ty = nullptr;
  3585. return parseType(Ty) || parseGlobalValue(Ty, V);
  3586. }
  3587. bool LLParser::parseOptionalComdat(StringRef GlobalName, Comdat *&C) {
  3588. C = nullptr;
  3589. LocTy KwLoc = Lex.getLoc();
  3590. if (!EatIfPresent(lltok::kw_comdat))
  3591. return false;
  3592. if (EatIfPresent(lltok::lparen)) {
  3593. if (Lex.getKind() != lltok::ComdatVar)
  3594. return tokError("expected comdat variable");
  3595. C = getComdat(Lex.getStrVal(), Lex.getLoc());
  3596. Lex.Lex();
  3597. if (parseToken(lltok::rparen, "expected ')' after comdat var"))
  3598. return true;
  3599. } else {
  3600. if (GlobalName.empty())
  3601. return tokError("comdat cannot be unnamed");
  3602. C = getComdat(std::string(GlobalName), KwLoc);
  3603. }
  3604. return false;
  3605. }
  3606. /// parseGlobalValueVector
  3607. /// ::= /*empty*/
  3608. /// ::= [inrange] TypeAndValue (',' [inrange] TypeAndValue)*
  3609. bool LLParser::parseGlobalValueVector(SmallVectorImpl<Constant *> &Elts,
  3610. std::optional<unsigned> *InRangeOp) {
  3611. // Empty list.
  3612. if (Lex.getKind() == lltok::rbrace ||
  3613. Lex.getKind() == lltok::rsquare ||
  3614. Lex.getKind() == lltok::greater ||
  3615. Lex.getKind() == lltok::rparen)
  3616. return false;
  3617. do {
  3618. if (InRangeOp && !*InRangeOp && EatIfPresent(lltok::kw_inrange))
  3619. *InRangeOp = Elts.size();
  3620. Constant *C;
  3621. if (parseGlobalTypeAndValue(C))
  3622. return true;
  3623. Elts.push_back(C);
  3624. } while (EatIfPresent(lltok::comma));
  3625. return false;
  3626. }
  3627. bool LLParser::parseMDTuple(MDNode *&MD, bool IsDistinct) {
  3628. SmallVector<Metadata *, 16> Elts;
  3629. if (parseMDNodeVector(Elts))
  3630. return true;
  3631. MD = (IsDistinct ? MDTuple::getDistinct : MDTuple::get)(Context, Elts);
  3632. return false;
  3633. }
  3634. /// MDNode:
  3635. /// ::= !{ ... }
  3636. /// ::= !7
  3637. /// ::= !DILocation(...)
  3638. bool LLParser::parseMDNode(MDNode *&N) {
  3639. if (Lex.getKind() == lltok::MetadataVar)
  3640. return parseSpecializedMDNode(N);
  3641. return parseToken(lltok::exclaim, "expected '!' here") || parseMDNodeTail(N);
  3642. }
  3643. bool LLParser::parseMDNodeTail(MDNode *&N) {
  3644. // !{ ... }
  3645. if (Lex.getKind() == lltok::lbrace)
  3646. return parseMDTuple(N);
  3647. // !42
  3648. return parseMDNodeID(N);
  3649. }
  3650. namespace {
  3651. /// Structure to represent an optional metadata field.
  3652. template <class FieldTy> struct MDFieldImpl {
  3653. typedef MDFieldImpl ImplTy;
  3654. FieldTy Val;
  3655. bool Seen;
  3656. void assign(FieldTy Val) {
  3657. Seen = true;
  3658. this->Val = std::move(Val);
  3659. }
  3660. explicit MDFieldImpl(FieldTy Default)
  3661. : Val(std::move(Default)), Seen(false) {}
  3662. };
  3663. /// Structure to represent an optional metadata field that
  3664. /// can be of either type (A or B) and encapsulates the
  3665. /// MD<typeofA>Field and MD<typeofB>Field structs, so not
  3666. /// to reimplement the specifics for representing each Field.
  3667. template <class FieldTypeA, class FieldTypeB> struct MDEitherFieldImpl {
  3668. typedef MDEitherFieldImpl<FieldTypeA, FieldTypeB> ImplTy;
  3669. FieldTypeA A;
  3670. FieldTypeB B;
  3671. bool Seen;
  3672. enum {
  3673. IsInvalid = 0,
  3674. IsTypeA = 1,
  3675. IsTypeB = 2
  3676. } WhatIs;
  3677. void assign(FieldTypeA A) {
  3678. Seen = true;
  3679. this->A = std::move(A);
  3680. WhatIs = IsTypeA;
  3681. }
  3682. void assign(FieldTypeB B) {
  3683. Seen = true;
  3684. this->B = std::move(B);
  3685. WhatIs = IsTypeB;
  3686. }
  3687. explicit MDEitherFieldImpl(FieldTypeA DefaultA, FieldTypeB DefaultB)
  3688. : A(std::move(DefaultA)), B(std::move(DefaultB)), Seen(false),
  3689. WhatIs(IsInvalid) {}
  3690. };
  3691. struct MDUnsignedField : public MDFieldImpl<uint64_t> {
  3692. uint64_t Max;
  3693. MDUnsignedField(uint64_t Default = 0, uint64_t Max = UINT64_MAX)
  3694. : ImplTy(Default), Max(Max) {}
  3695. };
  3696. struct LineField : public MDUnsignedField {
  3697. LineField() : MDUnsignedField(0, UINT32_MAX) {}
  3698. };
  3699. struct ColumnField : public MDUnsignedField {
  3700. ColumnField() : MDUnsignedField(0, UINT16_MAX) {}
  3701. };
  3702. struct DwarfTagField : public MDUnsignedField {
  3703. DwarfTagField() : MDUnsignedField(0, dwarf::DW_TAG_hi_user) {}
  3704. DwarfTagField(dwarf::Tag DefaultTag)
  3705. : MDUnsignedField(DefaultTag, dwarf::DW_TAG_hi_user) {}
  3706. };
  3707. struct DwarfMacinfoTypeField : public MDUnsignedField {
  3708. DwarfMacinfoTypeField() : MDUnsignedField(0, dwarf::DW_MACINFO_vendor_ext) {}
  3709. DwarfMacinfoTypeField(dwarf::MacinfoRecordType DefaultType)
  3710. : MDUnsignedField(DefaultType, dwarf::DW_MACINFO_vendor_ext) {}
  3711. };
  3712. struct DwarfAttEncodingField : public MDUnsignedField {
  3713. DwarfAttEncodingField() : MDUnsignedField(0, dwarf::DW_ATE_hi_user) {}
  3714. };
  3715. struct DwarfVirtualityField : public MDUnsignedField {
  3716. DwarfVirtualityField() : MDUnsignedField(0, dwarf::DW_VIRTUALITY_max) {}
  3717. };
  3718. struct DwarfLangField : public MDUnsignedField {
  3719. DwarfLangField() : MDUnsignedField(0, dwarf::DW_LANG_hi_user) {}
  3720. };
  3721. struct DwarfCCField : public MDUnsignedField {
  3722. DwarfCCField() : MDUnsignedField(0, dwarf::DW_CC_hi_user) {}
  3723. };
  3724. struct EmissionKindField : public MDUnsignedField {
  3725. EmissionKindField() : MDUnsignedField(0, DICompileUnit::LastEmissionKind) {}
  3726. };
  3727. struct NameTableKindField : public MDUnsignedField {
  3728. NameTableKindField()
  3729. : MDUnsignedField(
  3730. 0, (unsigned)
  3731. DICompileUnit::DebugNameTableKind::LastDebugNameTableKind) {}
  3732. };
  3733. struct DIFlagField : public MDFieldImpl<DINode::DIFlags> {
  3734. DIFlagField() : MDFieldImpl(DINode::FlagZero) {}
  3735. };
  3736. struct DISPFlagField : public MDFieldImpl<DISubprogram::DISPFlags> {
  3737. DISPFlagField() : MDFieldImpl(DISubprogram::SPFlagZero) {}
  3738. };
  3739. struct MDAPSIntField : public MDFieldImpl<APSInt> {
  3740. MDAPSIntField() : ImplTy(APSInt()) {}
  3741. };
  3742. struct MDSignedField : public MDFieldImpl<int64_t> {
  3743. int64_t Min = INT64_MIN;
  3744. int64_t Max = INT64_MAX;
  3745. MDSignedField(int64_t Default = 0)
  3746. : ImplTy(Default) {}
  3747. MDSignedField(int64_t Default, int64_t Min, int64_t Max)
  3748. : ImplTy(Default), Min(Min), Max(Max) {}
  3749. };
  3750. struct MDBoolField : public MDFieldImpl<bool> {
  3751. MDBoolField(bool Default = false) : ImplTy(Default) {}
  3752. };
  3753. struct MDField : public MDFieldImpl<Metadata *> {
  3754. bool AllowNull;
  3755. MDField(bool AllowNull = true) : ImplTy(nullptr), AllowNull(AllowNull) {}
  3756. };
  3757. struct MDStringField : public MDFieldImpl<MDString *> {
  3758. bool AllowEmpty;
  3759. MDStringField(bool AllowEmpty = true)
  3760. : ImplTy(nullptr), AllowEmpty(AllowEmpty) {}
  3761. };
  3762. struct MDFieldList : public MDFieldImpl<SmallVector<Metadata *, 4>> {
  3763. MDFieldList() : ImplTy(SmallVector<Metadata *, 4>()) {}
  3764. };
  3765. struct ChecksumKindField : public MDFieldImpl<DIFile::ChecksumKind> {
  3766. ChecksumKindField(DIFile::ChecksumKind CSKind) : ImplTy(CSKind) {}
  3767. };
  3768. struct MDSignedOrMDField : MDEitherFieldImpl<MDSignedField, MDField> {
  3769. MDSignedOrMDField(int64_t Default = 0, bool AllowNull = true)
  3770. : ImplTy(MDSignedField(Default), MDField(AllowNull)) {}
  3771. MDSignedOrMDField(int64_t Default, int64_t Min, int64_t Max,
  3772. bool AllowNull = true)
  3773. : ImplTy(MDSignedField(Default, Min, Max), MDField(AllowNull)) {}
  3774. bool isMDSignedField() const { return WhatIs == IsTypeA; }
  3775. bool isMDField() const { return WhatIs == IsTypeB; }
  3776. int64_t getMDSignedValue() const {
  3777. assert(isMDSignedField() && "Wrong field type");
  3778. return A.Val;
  3779. }
  3780. Metadata *getMDFieldValue() const {
  3781. assert(isMDField() && "Wrong field type");
  3782. return B.Val;
  3783. }
  3784. };
  3785. } // end anonymous namespace
  3786. namespace llvm {
  3787. template <>
  3788. bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDAPSIntField &Result) {
  3789. if (Lex.getKind() != lltok::APSInt)
  3790. return tokError("expected integer");
  3791. Result.assign(Lex.getAPSIntVal());
  3792. Lex.Lex();
  3793. return false;
  3794. }
  3795. template <>
  3796. bool LLParser::parseMDField(LocTy Loc, StringRef Name,
  3797. MDUnsignedField &Result) {
  3798. if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
  3799. return tokError("expected unsigned integer");
  3800. auto &U = Lex.getAPSIntVal();
  3801. if (U.ugt(Result.Max))
  3802. return tokError("value for '" + Name + "' too large, limit is " +
  3803. Twine(Result.Max));
  3804. Result.assign(U.getZExtValue());
  3805. assert(Result.Val <= Result.Max && "Expected value in range");
  3806. Lex.Lex();
  3807. return false;
  3808. }
  3809. template <>
  3810. bool LLParser::parseMDField(LocTy Loc, StringRef Name, LineField &Result) {
  3811. return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
  3812. }
  3813. template <>
  3814. bool LLParser::parseMDField(LocTy Loc, StringRef Name, ColumnField &Result) {
  3815. return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
  3816. }
  3817. template <>
  3818. bool LLParser::parseMDField(LocTy Loc, StringRef Name, DwarfTagField &Result) {
  3819. if (Lex.getKind() == lltok::APSInt)
  3820. return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
  3821. if (Lex.getKind() != lltok::DwarfTag)
  3822. return tokError("expected DWARF tag");
  3823. unsigned Tag = dwarf::getTag(Lex.getStrVal());
  3824. if (Tag == dwarf::DW_TAG_invalid)
  3825. return tokError("invalid DWARF tag" + Twine(" '") + Lex.getStrVal() + "'");
  3826. assert(Tag <= Result.Max && "Expected valid DWARF tag");
  3827. Result.assign(Tag);
  3828. Lex.Lex();
  3829. return false;
  3830. }
  3831. template <>
  3832. bool LLParser::parseMDField(LocTy Loc, StringRef Name,
  3833. DwarfMacinfoTypeField &Result) {
  3834. if (Lex.getKind() == lltok::APSInt)
  3835. return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
  3836. if (Lex.getKind() != lltok::DwarfMacinfo)
  3837. return tokError("expected DWARF macinfo type");
  3838. unsigned Macinfo = dwarf::getMacinfo(Lex.getStrVal());
  3839. if (Macinfo == dwarf::DW_MACINFO_invalid)
  3840. return tokError("invalid DWARF macinfo type" + Twine(" '") +
  3841. Lex.getStrVal() + "'");
  3842. assert(Macinfo <= Result.Max && "Expected valid DWARF macinfo type");
  3843. Result.assign(Macinfo);
  3844. Lex.Lex();
  3845. return false;
  3846. }
  3847. template <>
  3848. bool LLParser::parseMDField(LocTy Loc, StringRef Name,
  3849. DwarfVirtualityField &Result) {
  3850. if (Lex.getKind() == lltok::APSInt)
  3851. return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
  3852. if (Lex.getKind() != lltok::DwarfVirtuality)
  3853. return tokError("expected DWARF virtuality code");
  3854. unsigned Virtuality = dwarf::getVirtuality(Lex.getStrVal());
  3855. if (Virtuality == dwarf::DW_VIRTUALITY_invalid)
  3856. return tokError("invalid DWARF virtuality code" + Twine(" '") +
  3857. Lex.getStrVal() + "'");
  3858. assert(Virtuality <= Result.Max && "Expected valid DWARF virtuality code");
  3859. Result.assign(Virtuality);
  3860. Lex.Lex();
  3861. return false;
  3862. }
  3863. template <>
  3864. bool LLParser::parseMDField(LocTy Loc, StringRef Name, DwarfLangField &Result) {
  3865. if (Lex.getKind() == lltok::APSInt)
  3866. return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
  3867. if (Lex.getKind() != lltok::DwarfLang)
  3868. return tokError("expected DWARF language");
  3869. unsigned Lang = dwarf::getLanguage(Lex.getStrVal());
  3870. if (!Lang)
  3871. return tokError("invalid DWARF language" + Twine(" '") + Lex.getStrVal() +
  3872. "'");
  3873. assert(Lang <= Result.Max && "Expected valid DWARF language");
  3874. Result.assign(Lang);
  3875. Lex.Lex();
  3876. return false;
  3877. }
  3878. template <>
  3879. bool LLParser::parseMDField(LocTy Loc, StringRef Name, DwarfCCField &Result) {
  3880. if (Lex.getKind() == lltok::APSInt)
  3881. return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
  3882. if (Lex.getKind() != lltok::DwarfCC)
  3883. return tokError("expected DWARF calling convention");
  3884. unsigned CC = dwarf::getCallingConvention(Lex.getStrVal());
  3885. if (!CC)
  3886. return tokError("invalid DWARF calling convention" + Twine(" '") +
  3887. Lex.getStrVal() + "'");
  3888. assert(CC <= Result.Max && "Expected valid DWARF calling convention");
  3889. Result.assign(CC);
  3890. Lex.Lex();
  3891. return false;
  3892. }
  3893. template <>
  3894. bool LLParser::parseMDField(LocTy Loc, StringRef Name,
  3895. EmissionKindField &Result) {
  3896. if (Lex.getKind() == lltok::APSInt)
  3897. return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
  3898. if (Lex.getKind() != lltok::EmissionKind)
  3899. return tokError("expected emission kind");
  3900. auto Kind = DICompileUnit::getEmissionKind(Lex.getStrVal());
  3901. if (!Kind)
  3902. return tokError("invalid emission kind" + Twine(" '") + Lex.getStrVal() +
  3903. "'");
  3904. assert(*Kind <= Result.Max && "Expected valid emission kind");
  3905. Result.assign(*Kind);
  3906. Lex.Lex();
  3907. return false;
  3908. }
  3909. template <>
  3910. bool LLParser::parseMDField(LocTy Loc, StringRef Name,
  3911. NameTableKindField &Result) {
  3912. if (Lex.getKind() == lltok::APSInt)
  3913. return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
  3914. if (Lex.getKind() != lltok::NameTableKind)
  3915. return tokError("expected nameTable kind");
  3916. auto Kind = DICompileUnit::getNameTableKind(Lex.getStrVal());
  3917. if (!Kind)
  3918. return tokError("invalid nameTable kind" + Twine(" '") + Lex.getStrVal() +
  3919. "'");
  3920. assert(((unsigned)*Kind) <= Result.Max && "Expected valid nameTable kind");
  3921. Result.assign((unsigned)*Kind);
  3922. Lex.Lex();
  3923. return false;
  3924. }
  3925. template <>
  3926. bool LLParser::parseMDField(LocTy Loc, StringRef Name,
  3927. DwarfAttEncodingField &Result) {
  3928. if (Lex.getKind() == lltok::APSInt)
  3929. return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
  3930. if (Lex.getKind() != lltok::DwarfAttEncoding)
  3931. return tokError("expected DWARF type attribute encoding");
  3932. unsigned Encoding = dwarf::getAttributeEncoding(Lex.getStrVal());
  3933. if (!Encoding)
  3934. return tokError("invalid DWARF type attribute encoding" + Twine(" '") +
  3935. Lex.getStrVal() + "'");
  3936. assert(Encoding <= Result.Max && "Expected valid DWARF language");
  3937. Result.assign(Encoding);
  3938. Lex.Lex();
  3939. return false;
  3940. }
  3941. /// DIFlagField
  3942. /// ::= uint32
  3943. /// ::= DIFlagVector
  3944. /// ::= DIFlagVector '|' DIFlagFwdDecl '|' uint32 '|' DIFlagPublic
  3945. template <>
  3946. bool LLParser::parseMDField(LocTy Loc, StringRef Name, DIFlagField &Result) {
  3947. // parser for a single flag.
  3948. auto parseFlag = [&](DINode::DIFlags &Val) {
  3949. if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned()) {
  3950. uint32_t TempVal = static_cast<uint32_t>(Val);
  3951. bool Res = parseUInt32(TempVal);
  3952. Val = static_cast<DINode::DIFlags>(TempVal);
  3953. return Res;
  3954. }
  3955. if (Lex.getKind() != lltok::DIFlag)
  3956. return tokError("expected debug info flag");
  3957. Val = DINode::getFlag(Lex.getStrVal());
  3958. if (!Val)
  3959. return tokError(Twine("invalid debug info flag '") + Lex.getStrVal() +
  3960. "'");
  3961. Lex.Lex();
  3962. return false;
  3963. };
  3964. // parse the flags and combine them together.
  3965. DINode::DIFlags Combined = DINode::FlagZero;
  3966. do {
  3967. DINode::DIFlags Val;
  3968. if (parseFlag(Val))
  3969. return true;
  3970. Combined |= Val;
  3971. } while (EatIfPresent(lltok::bar));
  3972. Result.assign(Combined);
  3973. return false;
  3974. }
  3975. /// DISPFlagField
  3976. /// ::= uint32
  3977. /// ::= DISPFlagVector
  3978. /// ::= DISPFlagVector '|' DISPFlag* '|' uint32
  3979. template <>
  3980. bool LLParser::parseMDField(LocTy Loc, StringRef Name, DISPFlagField &Result) {
  3981. // parser for a single flag.
  3982. auto parseFlag = [&](DISubprogram::DISPFlags &Val) {
  3983. if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned()) {
  3984. uint32_t TempVal = static_cast<uint32_t>(Val);
  3985. bool Res = parseUInt32(TempVal);
  3986. Val = static_cast<DISubprogram::DISPFlags>(TempVal);
  3987. return Res;
  3988. }
  3989. if (Lex.getKind() != lltok::DISPFlag)
  3990. return tokError("expected debug info flag");
  3991. Val = DISubprogram::getFlag(Lex.getStrVal());
  3992. if (!Val)
  3993. return tokError(Twine("invalid subprogram debug info flag '") +
  3994. Lex.getStrVal() + "'");
  3995. Lex.Lex();
  3996. return false;
  3997. };
  3998. // parse the flags and combine them together.
  3999. DISubprogram::DISPFlags Combined = DISubprogram::SPFlagZero;
  4000. do {
  4001. DISubprogram::DISPFlags Val;
  4002. if (parseFlag(Val))
  4003. return true;
  4004. Combined |= Val;
  4005. } while (EatIfPresent(lltok::bar));
  4006. Result.assign(Combined);
  4007. return false;
  4008. }
  4009. template <>
  4010. bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDSignedField &Result) {
  4011. if (Lex.getKind() != lltok::APSInt)
  4012. return tokError("expected signed integer");
  4013. auto &S = Lex.getAPSIntVal();
  4014. if (S < Result.Min)
  4015. return tokError("value for '" + Name + "' too small, limit is " +
  4016. Twine(Result.Min));
  4017. if (S > Result.Max)
  4018. return tokError("value for '" + Name + "' too large, limit is " +
  4019. Twine(Result.Max));
  4020. Result.assign(S.getExtValue());
  4021. assert(Result.Val >= Result.Min && "Expected value in range");
  4022. assert(Result.Val <= Result.Max && "Expected value in range");
  4023. Lex.Lex();
  4024. return false;
  4025. }
  4026. template <>
  4027. bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDBoolField &Result) {
  4028. switch (Lex.getKind()) {
  4029. default:
  4030. return tokError("expected 'true' or 'false'");
  4031. case lltok::kw_true:
  4032. Result.assign(true);
  4033. break;
  4034. case lltok::kw_false:
  4035. Result.assign(false);
  4036. break;
  4037. }
  4038. Lex.Lex();
  4039. return false;
  4040. }
  4041. template <>
  4042. bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDField &Result) {
  4043. if (Lex.getKind() == lltok::kw_null) {
  4044. if (!Result.AllowNull)
  4045. return tokError("'" + Name + "' cannot be null");
  4046. Lex.Lex();
  4047. Result.assign(nullptr);
  4048. return false;
  4049. }
  4050. Metadata *MD;
  4051. if (parseMetadata(MD, nullptr))
  4052. return true;
  4053. Result.assign(MD);
  4054. return false;
  4055. }
  4056. template <>
  4057. bool LLParser::parseMDField(LocTy Loc, StringRef Name,
  4058. MDSignedOrMDField &Result) {
  4059. // Try to parse a signed int.
  4060. if (Lex.getKind() == lltok::APSInt) {
  4061. MDSignedField Res = Result.A;
  4062. if (!parseMDField(Loc, Name, Res)) {
  4063. Result.assign(Res);
  4064. return false;
  4065. }
  4066. return true;
  4067. }
  4068. // Otherwise, try to parse as an MDField.
  4069. MDField Res = Result.B;
  4070. if (!parseMDField(Loc, Name, Res)) {
  4071. Result.assign(Res);
  4072. return false;
  4073. }
  4074. return true;
  4075. }
  4076. template <>
  4077. bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDStringField &Result) {
  4078. LocTy ValueLoc = Lex.getLoc();
  4079. std::string S;
  4080. if (parseStringConstant(S))
  4081. return true;
  4082. if (!Result.AllowEmpty && S.empty())
  4083. return error(ValueLoc, "'" + Name + "' cannot be empty");
  4084. Result.assign(S.empty() ? nullptr : MDString::get(Context, S));
  4085. return false;
  4086. }
  4087. template <>
  4088. bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDFieldList &Result) {
  4089. SmallVector<Metadata *, 4> MDs;
  4090. if (parseMDNodeVector(MDs))
  4091. return true;
  4092. Result.assign(std::move(MDs));
  4093. return false;
  4094. }
  4095. template <>
  4096. bool LLParser::parseMDField(LocTy Loc, StringRef Name,
  4097. ChecksumKindField &Result) {
  4098. std::optional<DIFile::ChecksumKind> CSKind =
  4099. DIFile::getChecksumKind(Lex.getStrVal());
  4100. if (Lex.getKind() != lltok::ChecksumKind || !CSKind)
  4101. return tokError("invalid checksum kind" + Twine(" '") + Lex.getStrVal() +
  4102. "'");
  4103. Result.assign(*CSKind);
  4104. Lex.Lex();
  4105. return false;
  4106. }
  4107. } // end namespace llvm
  4108. template <class ParserTy>
  4109. bool LLParser::parseMDFieldsImplBody(ParserTy ParseField) {
  4110. do {
  4111. if (Lex.getKind() != lltok::LabelStr)
  4112. return tokError("expected field label here");
  4113. if (ParseField())
  4114. return true;
  4115. } while (EatIfPresent(lltok::comma));
  4116. return false;
  4117. }
  4118. template <class ParserTy>
  4119. bool LLParser::parseMDFieldsImpl(ParserTy ParseField, LocTy &ClosingLoc) {
  4120. assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
  4121. Lex.Lex();
  4122. if (parseToken(lltok::lparen, "expected '(' here"))
  4123. return true;
  4124. if (Lex.getKind() != lltok::rparen)
  4125. if (parseMDFieldsImplBody(ParseField))
  4126. return true;
  4127. ClosingLoc = Lex.getLoc();
  4128. return parseToken(lltok::rparen, "expected ')' here");
  4129. }
  4130. template <class FieldTy>
  4131. bool LLParser::parseMDField(StringRef Name, FieldTy &Result) {
  4132. if (Result.Seen)
  4133. return tokError("field '" + Name + "' cannot be specified more than once");
  4134. LocTy Loc = Lex.getLoc();
  4135. Lex.Lex();
  4136. return parseMDField(Loc, Name, Result);
  4137. }
  4138. bool LLParser::parseSpecializedMDNode(MDNode *&N, bool IsDistinct) {
  4139. assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
  4140. #define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
  4141. if (Lex.getStrVal() == #CLASS) \
  4142. return parse##CLASS(N, IsDistinct);
  4143. #include "llvm/IR/Metadata.def"
  4144. return tokError("expected metadata type");
  4145. }
  4146. #define DECLARE_FIELD(NAME, TYPE, INIT) TYPE NAME INIT
  4147. #define NOP_FIELD(NAME, TYPE, INIT)
  4148. #define REQUIRE_FIELD(NAME, TYPE, INIT) \
  4149. if (!NAME.Seen) \
  4150. return error(ClosingLoc, "missing required field '" #NAME "'");
  4151. #define PARSE_MD_FIELD(NAME, TYPE, DEFAULT) \
  4152. if (Lex.getStrVal() == #NAME) \
  4153. return parseMDField(#NAME, NAME);
  4154. #define PARSE_MD_FIELDS() \
  4155. VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) \
  4156. do { \
  4157. LocTy ClosingLoc; \
  4158. if (parseMDFieldsImpl( \
  4159. [&]() -> bool { \
  4160. VISIT_MD_FIELDS(PARSE_MD_FIELD, PARSE_MD_FIELD) \
  4161. return tokError(Twine("invalid field '") + Lex.getStrVal() + \
  4162. "'"); \
  4163. }, \
  4164. ClosingLoc)) \
  4165. return true; \
  4166. VISIT_MD_FIELDS(NOP_FIELD, REQUIRE_FIELD) \
  4167. } while (false)
  4168. #define GET_OR_DISTINCT(CLASS, ARGS) \
  4169. (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
  4170. /// parseDILocationFields:
  4171. /// ::= !DILocation(line: 43, column: 8, scope: !5, inlinedAt: !6,
  4172. /// isImplicitCode: true)
  4173. bool LLParser::parseDILocation(MDNode *&Result, bool IsDistinct) {
  4174. #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
  4175. OPTIONAL(line, LineField, ); \
  4176. OPTIONAL(column, ColumnField, ); \
  4177. REQUIRED(scope, MDField, (/* AllowNull */ false)); \
  4178. OPTIONAL(inlinedAt, MDField, ); \
  4179. OPTIONAL(isImplicitCode, MDBoolField, (false));
  4180. PARSE_MD_FIELDS();
  4181. #undef VISIT_MD_FIELDS
  4182. Result =
  4183. GET_OR_DISTINCT(DILocation, (Context, line.Val, column.Val, scope.Val,
  4184. inlinedAt.Val, isImplicitCode.Val));
  4185. return false;
  4186. }
  4187. /// parseDIAssignID:
  4188. /// ::= distinct !DIAssignID()
  4189. bool LLParser::parseDIAssignID(MDNode *&Result, bool IsDistinct) {
  4190. if (!IsDistinct)
  4191. return Lex.Error("missing 'distinct', required for !DIAssignID()");
  4192. Lex.Lex();
  4193. // Now eat the parens.
  4194. if (parseToken(lltok::lparen, "expected '(' here"))
  4195. return true;
  4196. if (parseToken(lltok::rparen, "expected ')' here"))
  4197. return true;
  4198. Result = DIAssignID::getDistinct(Context);
  4199. return false;
  4200. }
  4201. /// parseGenericDINode:
  4202. /// ::= !GenericDINode(tag: 15, header: "...", operands: {...})
  4203. bool LLParser::parseGenericDINode(MDNode *&Result, bool IsDistinct) {
  4204. #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
  4205. REQUIRED(tag, DwarfTagField, ); \
  4206. OPTIONAL(header, MDStringField, ); \
  4207. OPTIONAL(operands, MDFieldList, );
  4208. PARSE_MD_FIELDS();
  4209. #undef VISIT_MD_FIELDS
  4210. Result = GET_OR_DISTINCT(GenericDINode,
  4211. (Context, tag.Val, header.Val, operands.Val));
  4212. return false;
  4213. }
  4214. /// parseDISubrange:
  4215. /// ::= !DISubrange(count: 30, lowerBound: 2)
  4216. /// ::= !DISubrange(count: !node, lowerBound: 2)
  4217. /// ::= !DISubrange(lowerBound: !node1, upperBound: !node2, stride: !node3)
  4218. bool LLParser::parseDISubrange(MDNode *&Result, bool IsDistinct) {
  4219. #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
  4220. OPTIONAL(count, MDSignedOrMDField, (-1, -1, INT64_MAX, false)); \
  4221. OPTIONAL(lowerBound, MDSignedOrMDField, ); \
  4222. OPTIONAL(upperBound, MDSignedOrMDField, ); \
  4223. OPTIONAL(stride, MDSignedOrMDField, );
  4224. PARSE_MD_FIELDS();
  4225. #undef VISIT_MD_FIELDS
  4226. Metadata *Count = nullptr;
  4227. Metadata *LowerBound = nullptr;
  4228. Metadata *UpperBound = nullptr;
  4229. Metadata *Stride = nullptr;
  4230. auto convToMetadata = [&](MDSignedOrMDField Bound) -> Metadata * {
  4231. if (Bound.isMDSignedField())
  4232. return ConstantAsMetadata::get(ConstantInt::getSigned(
  4233. Type::getInt64Ty(Context), Bound.getMDSignedValue()));
  4234. if (Bound.isMDField())
  4235. return Bound.getMDFieldValue();
  4236. return nullptr;
  4237. };
  4238. Count = convToMetadata(count);
  4239. LowerBound = convToMetadata(lowerBound);
  4240. UpperBound = convToMetadata(upperBound);
  4241. Stride = convToMetadata(stride);
  4242. Result = GET_OR_DISTINCT(DISubrange,
  4243. (Context, Count, LowerBound, UpperBound, Stride));
  4244. return false;
  4245. }
  4246. /// parseDIGenericSubrange:
  4247. /// ::= !DIGenericSubrange(lowerBound: !node1, upperBound: !node2, stride:
  4248. /// !node3)
  4249. bool LLParser::parseDIGenericSubrange(MDNode *&Result, bool IsDistinct) {
  4250. #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
  4251. OPTIONAL(count, MDSignedOrMDField, ); \
  4252. OPTIONAL(lowerBound, MDSignedOrMDField, ); \
  4253. OPTIONAL(upperBound, MDSignedOrMDField, ); \
  4254. OPTIONAL(stride, MDSignedOrMDField, );
  4255. PARSE_MD_FIELDS();
  4256. #undef VISIT_MD_FIELDS
  4257. auto ConvToMetadata = [&](MDSignedOrMDField Bound) -> Metadata * {
  4258. if (Bound.isMDSignedField())
  4259. return DIExpression::get(
  4260. Context, {dwarf::DW_OP_consts,
  4261. static_cast<uint64_t>(Bound.getMDSignedValue())});
  4262. if (Bound.isMDField())
  4263. return Bound.getMDFieldValue();
  4264. return nullptr;
  4265. };
  4266. Metadata *Count = ConvToMetadata(count);
  4267. Metadata *LowerBound = ConvToMetadata(lowerBound);
  4268. Metadata *UpperBound = ConvToMetadata(upperBound);
  4269. Metadata *Stride = ConvToMetadata(stride);
  4270. Result = GET_OR_DISTINCT(DIGenericSubrange,
  4271. (Context, Count, LowerBound, UpperBound, Stride));
  4272. return false;
  4273. }
  4274. /// parseDIEnumerator:
  4275. /// ::= !DIEnumerator(value: 30, isUnsigned: true, name: "SomeKind")
  4276. bool LLParser::parseDIEnumerator(MDNode *&Result, bool IsDistinct) {
  4277. #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
  4278. REQUIRED(name, MDStringField, ); \
  4279. REQUIRED(value, MDAPSIntField, ); \
  4280. OPTIONAL(isUnsigned, MDBoolField, (false));
  4281. PARSE_MD_FIELDS();
  4282. #undef VISIT_MD_FIELDS
  4283. if (isUnsigned.Val && value.Val.isNegative())
  4284. return tokError("unsigned enumerator with negative value");
  4285. APSInt Value(value.Val);
  4286. // Add a leading zero so that unsigned values with the msb set are not
  4287. // mistaken for negative values when used for signed enumerators.
  4288. if (!isUnsigned.Val && value.Val.isUnsigned() && value.Val.isSignBitSet())
  4289. Value = Value.zext(Value.getBitWidth() + 1);
  4290. Result =
  4291. GET_OR_DISTINCT(DIEnumerator, (Context, Value, isUnsigned.Val, name.Val));
  4292. return false;
  4293. }
  4294. /// parseDIBasicType:
  4295. /// ::= !DIBasicType(tag: DW_TAG_base_type, name: "int", size: 32, align: 32,
  4296. /// encoding: DW_ATE_encoding, flags: 0)
  4297. bool LLParser::parseDIBasicType(MDNode *&Result, bool IsDistinct) {
  4298. #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
  4299. OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type)); \
  4300. OPTIONAL(name, MDStringField, ); \
  4301. OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
  4302. OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
  4303. OPTIONAL(encoding, DwarfAttEncodingField, ); \
  4304. OPTIONAL(flags, DIFlagField, );
  4305. PARSE_MD_FIELDS();
  4306. #undef VISIT_MD_FIELDS
  4307. Result = GET_OR_DISTINCT(DIBasicType, (Context, tag.Val, name.Val, size.Val,
  4308. align.Val, encoding.Val, flags.Val));
  4309. return false;
  4310. }
  4311. /// parseDIStringType:
  4312. /// ::= !DIStringType(name: "character(4)", size: 32, align: 32)
  4313. bool LLParser::parseDIStringType(MDNode *&Result, bool IsDistinct) {
  4314. #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
  4315. OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_string_type)); \
  4316. OPTIONAL(name, MDStringField, ); \
  4317. OPTIONAL(stringLength, MDField, ); \
  4318. OPTIONAL(stringLengthExpression, MDField, ); \
  4319. OPTIONAL(stringLocationExpression, MDField, ); \
  4320. OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
  4321. OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
  4322. OPTIONAL(encoding, DwarfAttEncodingField, );
  4323. PARSE_MD_FIELDS();
  4324. #undef VISIT_MD_FIELDS
  4325. Result = GET_OR_DISTINCT(
  4326. DIStringType,
  4327. (Context, tag.Val, name.Val, stringLength.Val, stringLengthExpression.Val,
  4328. stringLocationExpression.Val, size.Val, align.Val, encoding.Val));
  4329. return false;
  4330. }
  4331. /// parseDIDerivedType:
  4332. /// ::= !DIDerivedType(tag: DW_TAG_pointer_type, name: "int", file: !0,
  4333. /// line: 7, scope: !1, baseType: !2, size: 32,
  4334. /// align: 32, offset: 0, flags: 0, extraData: !3,
  4335. /// dwarfAddressSpace: 3)
  4336. bool LLParser::parseDIDerivedType(MDNode *&Result, bool IsDistinct) {
  4337. #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
  4338. REQUIRED(tag, DwarfTagField, ); \
  4339. OPTIONAL(name, MDStringField, ); \
  4340. OPTIONAL(file, MDField, ); \
  4341. OPTIONAL(line, LineField, ); \
  4342. OPTIONAL(scope, MDField, ); \
  4343. REQUIRED(baseType, MDField, ); \
  4344. OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
  4345. OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
  4346. OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
  4347. OPTIONAL(flags, DIFlagField, ); \
  4348. OPTIONAL(extraData, MDField, ); \
  4349. OPTIONAL(dwarfAddressSpace, MDUnsignedField, (UINT32_MAX, UINT32_MAX)); \
  4350. OPTIONAL(annotations, MDField, );
  4351. PARSE_MD_FIELDS();
  4352. #undef VISIT_MD_FIELDS
  4353. std::optional<unsigned> DWARFAddressSpace;
  4354. if (dwarfAddressSpace.Val != UINT32_MAX)
  4355. DWARFAddressSpace = dwarfAddressSpace.Val;
  4356. Result = GET_OR_DISTINCT(DIDerivedType,
  4357. (Context, tag.Val, name.Val, file.Val, line.Val,
  4358. scope.Val, baseType.Val, size.Val, align.Val,
  4359. offset.Val, DWARFAddressSpace, flags.Val,
  4360. extraData.Val, annotations.Val));
  4361. return false;
  4362. }
  4363. bool LLParser::parseDICompositeType(MDNode *&Result, bool IsDistinct) {
  4364. #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
  4365. REQUIRED(tag, DwarfTagField, ); \
  4366. OPTIONAL(name, MDStringField, ); \
  4367. OPTIONAL(file, MDField, ); \
  4368. OPTIONAL(line, LineField, ); \
  4369. OPTIONAL(scope, MDField, ); \
  4370. OPTIONAL(baseType, MDField, ); \
  4371. OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
  4372. OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
  4373. OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
  4374. OPTIONAL(flags, DIFlagField, ); \
  4375. OPTIONAL(elements, MDField, ); \
  4376. OPTIONAL(runtimeLang, DwarfLangField, ); \
  4377. OPTIONAL(vtableHolder, MDField, ); \
  4378. OPTIONAL(templateParams, MDField, ); \
  4379. OPTIONAL(identifier, MDStringField, ); \
  4380. OPTIONAL(discriminator, MDField, ); \
  4381. OPTIONAL(dataLocation, MDField, ); \
  4382. OPTIONAL(associated, MDField, ); \
  4383. OPTIONAL(allocated, MDField, ); \
  4384. OPTIONAL(rank, MDSignedOrMDField, ); \
  4385. OPTIONAL(annotations, MDField, );
  4386. PARSE_MD_FIELDS();
  4387. #undef VISIT_MD_FIELDS
  4388. Metadata *Rank = nullptr;
  4389. if (rank.isMDSignedField())
  4390. Rank = ConstantAsMetadata::get(ConstantInt::getSigned(
  4391. Type::getInt64Ty(Context), rank.getMDSignedValue()));
  4392. else if (rank.isMDField())
  4393. Rank = rank.getMDFieldValue();
  4394. // If this has an identifier try to build an ODR type.
  4395. if (identifier.Val)
  4396. if (auto *CT = DICompositeType::buildODRType(
  4397. Context, *identifier.Val, tag.Val, name.Val, file.Val, line.Val,
  4398. scope.Val, baseType.Val, size.Val, align.Val, offset.Val, flags.Val,
  4399. elements.Val, runtimeLang.Val, vtableHolder.Val, templateParams.Val,
  4400. discriminator.Val, dataLocation.Val, associated.Val, allocated.Val,
  4401. Rank, annotations.Val)) {
  4402. Result = CT;
  4403. return false;
  4404. }
  4405. // Create a new node, and save it in the context if it belongs in the type
  4406. // map.
  4407. Result = GET_OR_DISTINCT(
  4408. DICompositeType,
  4409. (Context, tag.Val, name.Val, file.Val, line.Val, scope.Val, baseType.Val,
  4410. size.Val, align.Val, offset.Val, flags.Val, elements.Val,
  4411. runtimeLang.Val, vtableHolder.Val, templateParams.Val, identifier.Val,
  4412. discriminator.Val, dataLocation.Val, associated.Val, allocated.Val, Rank,
  4413. annotations.Val));
  4414. return false;
  4415. }
  4416. bool LLParser::parseDISubroutineType(MDNode *&Result, bool IsDistinct) {
  4417. #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
  4418. OPTIONAL(flags, DIFlagField, ); \
  4419. OPTIONAL(cc, DwarfCCField, ); \
  4420. REQUIRED(types, MDField, );
  4421. PARSE_MD_FIELDS();
  4422. #undef VISIT_MD_FIELDS
  4423. Result = GET_OR_DISTINCT(DISubroutineType,
  4424. (Context, flags.Val, cc.Val, types.Val));
  4425. return false;
  4426. }
  4427. /// parseDIFileType:
  4428. /// ::= !DIFileType(filename: "path/to/file", directory: "/path/to/dir",
  4429. /// checksumkind: CSK_MD5,
  4430. /// checksum: "000102030405060708090a0b0c0d0e0f",
  4431. /// source: "source file contents")
  4432. bool LLParser::parseDIFile(MDNode *&Result, bool IsDistinct) {
  4433. // The default constructed value for checksumkind is required, but will never
  4434. // be used, as the parser checks if the field was actually Seen before using
  4435. // the Val.
  4436. #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
  4437. REQUIRED(filename, MDStringField, ); \
  4438. REQUIRED(directory, MDStringField, ); \
  4439. OPTIONAL(checksumkind, ChecksumKindField, (DIFile::CSK_MD5)); \
  4440. OPTIONAL(checksum, MDStringField, ); \
  4441. OPTIONAL(source, MDStringField, );
  4442. PARSE_MD_FIELDS();
  4443. #undef VISIT_MD_FIELDS
  4444. std::optional<DIFile::ChecksumInfo<MDString *>> OptChecksum;
  4445. if (checksumkind.Seen && checksum.Seen)
  4446. OptChecksum.emplace(checksumkind.Val, checksum.Val);
  4447. else if (checksumkind.Seen || checksum.Seen)
  4448. return Lex.Error("'checksumkind' and 'checksum' must be provided together");
  4449. MDString *Source = nullptr;
  4450. if (source.Seen)
  4451. Source = source.Val;
  4452. Result = GET_OR_DISTINCT(
  4453. DIFile, (Context, filename.Val, directory.Val, OptChecksum, Source));
  4454. return false;
  4455. }
  4456. /// parseDICompileUnit:
  4457. /// ::= !DICompileUnit(language: DW_LANG_C99, file: !0, producer: "clang",
  4458. /// isOptimized: true, flags: "-O2", runtimeVersion: 1,
  4459. /// splitDebugFilename: "abc.debug",
  4460. /// emissionKind: FullDebug, enums: !1, retainedTypes: !2,
  4461. /// globals: !4, imports: !5, macros: !6, dwoId: 0x0abcd,
  4462. /// sysroot: "/", sdk: "MacOSX.sdk")
  4463. bool LLParser::parseDICompileUnit(MDNode *&Result, bool IsDistinct) {
  4464. if (!IsDistinct)
  4465. return Lex.Error("missing 'distinct', required for !DICompileUnit");
  4466. #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
  4467. REQUIRED(language, DwarfLangField, ); \
  4468. REQUIRED(file, MDField, (/* AllowNull */ false)); \
  4469. OPTIONAL(producer, MDStringField, ); \
  4470. OPTIONAL(isOptimized, MDBoolField, ); \
  4471. OPTIONAL(flags, MDStringField, ); \
  4472. OPTIONAL(runtimeVersion, MDUnsignedField, (0, UINT32_MAX)); \
  4473. OPTIONAL(splitDebugFilename, MDStringField, ); \
  4474. OPTIONAL(emissionKind, EmissionKindField, ); \
  4475. OPTIONAL(enums, MDField, ); \
  4476. OPTIONAL(retainedTypes, MDField, ); \
  4477. OPTIONAL(globals, MDField, ); \
  4478. OPTIONAL(imports, MDField, ); \
  4479. OPTIONAL(macros, MDField, ); \
  4480. OPTIONAL(dwoId, MDUnsignedField, ); \
  4481. OPTIONAL(splitDebugInlining, MDBoolField, = true); \
  4482. OPTIONAL(debugInfoForProfiling, MDBoolField, = false); \
  4483. OPTIONAL(nameTableKind, NameTableKindField, ); \
  4484. OPTIONAL(rangesBaseAddress, MDBoolField, = false); \
  4485. OPTIONAL(sysroot, MDStringField, ); \
  4486. OPTIONAL(sdk, MDStringField, );
  4487. PARSE_MD_FIELDS();
  4488. #undef VISIT_MD_FIELDS
  4489. Result = DICompileUnit::getDistinct(
  4490. Context, language.Val, file.Val, producer.Val, isOptimized.Val, flags.Val,
  4491. runtimeVersion.Val, splitDebugFilename.Val, emissionKind.Val, enums.Val,
  4492. retainedTypes.Val, globals.Val, imports.Val, macros.Val, dwoId.Val,
  4493. splitDebugInlining.Val, debugInfoForProfiling.Val, nameTableKind.Val,
  4494. rangesBaseAddress.Val, sysroot.Val, sdk.Val);
  4495. return false;
  4496. }
  4497. /// parseDISubprogram:
  4498. /// ::= !DISubprogram(scope: !0, name: "foo", linkageName: "_Zfoo",
  4499. /// file: !1, line: 7, type: !2, isLocal: false,
  4500. /// isDefinition: true, scopeLine: 8, containingType: !3,
  4501. /// virtuality: DW_VIRTUALTIY_pure_virtual,
  4502. /// virtualIndex: 10, thisAdjustment: 4, flags: 11,
  4503. /// spFlags: 10, isOptimized: false, templateParams: !4,
  4504. /// declaration: !5, retainedNodes: !6, thrownTypes: !7,
  4505. /// annotations: !8)
  4506. bool LLParser::parseDISubprogram(MDNode *&Result, bool IsDistinct) {
  4507. auto Loc = Lex.getLoc();
  4508. #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
  4509. OPTIONAL(scope, MDField, ); \
  4510. OPTIONAL(name, MDStringField, ); \
  4511. OPTIONAL(linkageName, MDStringField, ); \
  4512. OPTIONAL(file, MDField, ); \
  4513. OPTIONAL(line, LineField, ); \
  4514. OPTIONAL(type, MDField, ); \
  4515. OPTIONAL(isLocal, MDBoolField, ); \
  4516. OPTIONAL(isDefinition, MDBoolField, (true)); \
  4517. OPTIONAL(scopeLine, LineField, ); \
  4518. OPTIONAL(containingType, MDField, ); \
  4519. OPTIONAL(virtuality, DwarfVirtualityField, ); \
  4520. OPTIONAL(virtualIndex, MDUnsignedField, (0, UINT32_MAX)); \
  4521. OPTIONAL(thisAdjustment, MDSignedField, (0, INT32_MIN, INT32_MAX)); \
  4522. OPTIONAL(flags, DIFlagField, ); \
  4523. OPTIONAL(spFlags, DISPFlagField, ); \
  4524. OPTIONAL(isOptimized, MDBoolField, ); \
  4525. OPTIONAL(unit, MDField, ); \
  4526. OPTIONAL(templateParams, MDField, ); \
  4527. OPTIONAL(declaration, MDField, ); \
  4528. OPTIONAL(retainedNodes, MDField, ); \
  4529. OPTIONAL(thrownTypes, MDField, ); \
  4530. OPTIONAL(annotations, MDField, ); \
  4531. OPTIONAL(targetFuncName, MDStringField, );
  4532. PARSE_MD_FIELDS();
  4533. #undef VISIT_MD_FIELDS
  4534. // An explicit spFlags field takes precedence over individual fields in
  4535. // older IR versions.
  4536. DISubprogram::DISPFlags SPFlags =
  4537. spFlags.Seen ? spFlags.Val
  4538. : DISubprogram::toSPFlags(isLocal.Val, isDefinition.Val,
  4539. isOptimized.Val, virtuality.Val);
  4540. if ((SPFlags & DISubprogram::SPFlagDefinition) && !IsDistinct)
  4541. return Lex.Error(
  4542. Loc,
  4543. "missing 'distinct', required for !DISubprogram that is a Definition");
  4544. Result = GET_OR_DISTINCT(
  4545. DISubprogram,
  4546. (Context, scope.Val, name.Val, linkageName.Val, file.Val, line.Val,
  4547. type.Val, scopeLine.Val, containingType.Val, virtualIndex.Val,
  4548. thisAdjustment.Val, flags.Val, SPFlags, unit.Val, templateParams.Val,
  4549. declaration.Val, retainedNodes.Val, thrownTypes.Val, annotations.Val,
  4550. targetFuncName.Val));
  4551. return false;
  4552. }
  4553. /// parseDILexicalBlock:
  4554. /// ::= !DILexicalBlock(scope: !0, file: !2, line: 7, column: 9)
  4555. bool LLParser::parseDILexicalBlock(MDNode *&Result, bool IsDistinct) {
  4556. #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
  4557. REQUIRED(scope, MDField, (/* AllowNull */ false)); \
  4558. OPTIONAL(file, MDField, ); \
  4559. OPTIONAL(line, LineField, ); \
  4560. OPTIONAL(column, ColumnField, );
  4561. PARSE_MD_FIELDS();
  4562. #undef VISIT_MD_FIELDS
  4563. Result = GET_OR_DISTINCT(
  4564. DILexicalBlock, (Context, scope.Val, file.Val, line.Val, column.Val));
  4565. return false;
  4566. }
  4567. /// parseDILexicalBlockFile:
  4568. /// ::= !DILexicalBlockFile(scope: !0, file: !2, discriminator: 9)
  4569. bool LLParser::parseDILexicalBlockFile(MDNode *&Result, bool IsDistinct) {
  4570. #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
  4571. REQUIRED(scope, MDField, (/* AllowNull */ false)); \
  4572. OPTIONAL(file, MDField, ); \
  4573. REQUIRED(discriminator, MDUnsignedField, (0, UINT32_MAX));
  4574. PARSE_MD_FIELDS();
  4575. #undef VISIT_MD_FIELDS
  4576. Result = GET_OR_DISTINCT(DILexicalBlockFile,
  4577. (Context, scope.Val, file.Val, discriminator.Val));
  4578. return false;
  4579. }
  4580. /// parseDICommonBlock:
  4581. /// ::= !DICommonBlock(scope: !0, file: !2, name: "COMMON name", line: 9)
  4582. bool LLParser::parseDICommonBlock(MDNode *&Result, bool IsDistinct) {
  4583. #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
  4584. REQUIRED(scope, MDField, ); \
  4585. OPTIONAL(declaration, MDField, ); \
  4586. OPTIONAL(name, MDStringField, ); \
  4587. OPTIONAL(file, MDField, ); \
  4588. OPTIONAL(line, LineField, );
  4589. PARSE_MD_FIELDS();
  4590. #undef VISIT_MD_FIELDS
  4591. Result = GET_OR_DISTINCT(DICommonBlock,
  4592. (Context, scope.Val, declaration.Val, name.Val,
  4593. file.Val, line.Val));
  4594. return false;
  4595. }
  4596. /// parseDINamespace:
  4597. /// ::= !DINamespace(scope: !0, file: !2, name: "SomeNamespace", line: 9)
  4598. bool LLParser::parseDINamespace(MDNode *&Result, bool IsDistinct) {
  4599. #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
  4600. REQUIRED(scope, MDField, ); \
  4601. OPTIONAL(name, MDStringField, ); \
  4602. OPTIONAL(exportSymbols, MDBoolField, );
  4603. PARSE_MD_FIELDS();
  4604. #undef VISIT_MD_FIELDS
  4605. Result = GET_OR_DISTINCT(DINamespace,
  4606. (Context, scope.Val, name.Val, exportSymbols.Val));
  4607. return false;
  4608. }
  4609. /// parseDIMacro:
  4610. /// ::= !DIMacro(macinfo: type, line: 9, name: "SomeMacro", value:
  4611. /// "SomeValue")
  4612. bool LLParser::parseDIMacro(MDNode *&Result, bool IsDistinct) {
  4613. #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
  4614. REQUIRED(type, DwarfMacinfoTypeField, ); \
  4615. OPTIONAL(line, LineField, ); \
  4616. REQUIRED(name, MDStringField, ); \
  4617. OPTIONAL(value, MDStringField, );
  4618. PARSE_MD_FIELDS();
  4619. #undef VISIT_MD_FIELDS
  4620. Result = GET_OR_DISTINCT(DIMacro,
  4621. (Context, type.Val, line.Val, name.Val, value.Val));
  4622. return false;
  4623. }
  4624. /// parseDIMacroFile:
  4625. /// ::= !DIMacroFile(line: 9, file: !2, nodes: !3)
  4626. bool LLParser::parseDIMacroFile(MDNode *&Result, bool IsDistinct) {
  4627. #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
  4628. OPTIONAL(type, DwarfMacinfoTypeField, (dwarf::DW_MACINFO_start_file)); \
  4629. OPTIONAL(line, LineField, ); \
  4630. REQUIRED(file, MDField, ); \
  4631. OPTIONAL(nodes, MDField, );
  4632. PARSE_MD_FIELDS();
  4633. #undef VISIT_MD_FIELDS
  4634. Result = GET_OR_DISTINCT(DIMacroFile,
  4635. (Context, type.Val, line.Val, file.Val, nodes.Val));
  4636. return false;
  4637. }
  4638. /// parseDIModule:
  4639. /// ::= !DIModule(scope: !0, name: "SomeModule", configMacros:
  4640. /// "-DNDEBUG", includePath: "/usr/include", apinotes: "module.apinotes",
  4641. /// file: !1, line: 4, isDecl: false)
  4642. bool LLParser::parseDIModule(MDNode *&Result, bool IsDistinct) {
  4643. #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
  4644. REQUIRED(scope, MDField, ); \
  4645. REQUIRED(name, MDStringField, ); \
  4646. OPTIONAL(configMacros, MDStringField, ); \
  4647. OPTIONAL(includePath, MDStringField, ); \
  4648. OPTIONAL(apinotes, MDStringField, ); \
  4649. OPTIONAL(file, MDField, ); \
  4650. OPTIONAL(line, LineField, ); \
  4651. OPTIONAL(isDecl, MDBoolField, );
  4652. PARSE_MD_FIELDS();
  4653. #undef VISIT_MD_FIELDS
  4654. Result = GET_OR_DISTINCT(DIModule, (Context, file.Val, scope.Val, name.Val,
  4655. configMacros.Val, includePath.Val,
  4656. apinotes.Val, line.Val, isDecl.Val));
  4657. return false;
  4658. }
  4659. /// parseDITemplateTypeParameter:
  4660. /// ::= !DITemplateTypeParameter(name: "Ty", type: !1, defaulted: false)
  4661. bool LLParser::parseDITemplateTypeParameter(MDNode *&Result, bool IsDistinct) {
  4662. #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
  4663. OPTIONAL(name, MDStringField, ); \
  4664. REQUIRED(type, MDField, ); \
  4665. OPTIONAL(defaulted, MDBoolField, );
  4666. PARSE_MD_FIELDS();
  4667. #undef VISIT_MD_FIELDS
  4668. Result = GET_OR_DISTINCT(DITemplateTypeParameter,
  4669. (Context, name.Val, type.Val, defaulted.Val));
  4670. return false;
  4671. }
  4672. /// parseDITemplateValueParameter:
  4673. /// ::= !DITemplateValueParameter(tag: DW_TAG_template_value_parameter,
  4674. /// name: "V", type: !1, defaulted: false,
  4675. /// value: i32 7)
  4676. bool LLParser::parseDITemplateValueParameter(MDNode *&Result, bool IsDistinct) {
  4677. #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
  4678. OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_template_value_parameter)); \
  4679. OPTIONAL(name, MDStringField, ); \
  4680. OPTIONAL(type, MDField, ); \
  4681. OPTIONAL(defaulted, MDBoolField, ); \
  4682. REQUIRED(value, MDField, );
  4683. PARSE_MD_FIELDS();
  4684. #undef VISIT_MD_FIELDS
  4685. Result = GET_OR_DISTINCT(
  4686. DITemplateValueParameter,
  4687. (Context, tag.Val, name.Val, type.Val, defaulted.Val, value.Val));
  4688. return false;
  4689. }
  4690. /// parseDIGlobalVariable:
  4691. /// ::= !DIGlobalVariable(scope: !0, name: "foo", linkageName: "foo",
  4692. /// file: !1, line: 7, type: !2, isLocal: false,
  4693. /// isDefinition: true, templateParams: !3,
  4694. /// declaration: !4, align: 8)
  4695. bool LLParser::parseDIGlobalVariable(MDNode *&Result, bool IsDistinct) {
  4696. #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
  4697. OPTIONAL(name, MDStringField, (/* AllowEmpty */ false)); \
  4698. OPTIONAL(scope, MDField, ); \
  4699. OPTIONAL(linkageName, MDStringField, ); \
  4700. OPTIONAL(file, MDField, ); \
  4701. OPTIONAL(line, LineField, ); \
  4702. OPTIONAL(type, MDField, ); \
  4703. OPTIONAL(isLocal, MDBoolField, ); \
  4704. OPTIONAL(isDefinition, MDBoolField, (true)); \
  4705. OPTIONAL(templateParams, MDField, ); \
  4706. OPTIONAL(declaration, MDField, ); \
  4707. OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
  4708. OPTIONAL(annotations, MDField, );
  4709. PARSE_MD_FIELDS();
  4710. #undef VISIT_MD_FIELDS
  4711. Result =
  4712. GET_OR_DISTINCT(DIGlobalVariable,
  4713. (Context, scope.Val, name.Val, linkageName.Val, file.Val,
  4714. line.Val, type.Val, isLocal.Val, isDefinition.Val,
  4715. declaration.Val, templateParams.Val, align.Val,
  4716. annotations.Val));
  4717. return false;
  4718. }
  4719. /// parseDILocalVariable:
  4720. /// ::= !DILocalVariable(arg: 7, scope: !0, name: "foo",
  4721. /// file: !1, line: 7, type: !2, arg: 2, flags: 7,
  4722. /// align: 8)
  4723. /// ::= !DILocalVariable(scope: !0, name: "foo",
  4724. /// file: !1, line: 7, type: !2, arg: 2, flags: 7,
  4725. /// align: 8)
  4726. bool LLParser::parseDILocalVariable(MDNode *&Result, bool IsDistinct) {
  4727. #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
  4728. REQUIRED(scope, MDField, (/* AllowNull */ false)); \
  4729. OPTIONAL(name, MDStringField, ); \
  4730. OPTIONAL(arg, MDUnsignedField, (0, UINT16_MAX)); \
  4731. OPTIONAL(file, MDField, ); \
  4732. OPTIONAL(line, LineField, ); \
  4733. OPTIONAL(type, MDField, ); \
  4734. OPTIONAL(flags, DIFlagField, ); \
  4735. OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
  4736. OPTIONAL(annotations, MDField, );
  4737. PARSE_MD_FIELDS();
  4738. #undef VISIT_MD_FIELDS
  4739. Result = GET_OR_DISTINCT(DILocalVariable,
  4740. (Context, scope.Val, name.Val, file.Val, line.Val,
  4741. type.Val, arg.Val, flags.Val, align.Val,
  4742. annotations.Val));
  4743. return false;
  4744. }
  4745. /// parseDILabel:
  4746. /// ::= !DILabel(scope: !0, name: "foo", file: !1, line: 7)
  4747. bool LLParser::parseDILabel(MDNode *&Result, bool IsDistinct) {
  4748. #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
  4749. REQUIRED(scope, MDField, (/* AllowNull */ false)); \
  4750. REQUIRED(name, MDStringField, ); \
  4751. REQUIRED(file, MDField, ); \
  4752. REQUIRED(line, LineField, );
  4753. PARSE_MD_FIELDS();
  4754. #undef VISIT_MD_FIELDS
  4755. Result = GET_OR_DISTINCT(DILabel,
  4756. (Context, scope.Val, name.Val, file.Val, line.Val));
  4757. return false;
  4758. }
  4759. /// parseDIExpression:
  4760. /// ::= !DIExpression(0, 7, -1)
  4761. bool LLParser::parseDIExpression(MDNode *&Result, bool IsDistinct) {
  4762. assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
  4763. Lex.Lex();
  4764. if (parseToken(lltok::lparen, "expected '(' here"))
  4765. return true;
  4766. SmallVector<uint64_t, 8> Elements;
  4767. if (Lex.getKind() != lltok::rparen)
  4768. do {
  4769. if (Lex.getKind() == lltok::DwarfOp) {
  4770. if (unsigned Op = dwarf::getOperationEncoding(Lex.getStrVal())) {
  4771. Lex.Lex();
  4772. Elements.push_back(Op);
  4773. continue;
  4774. }
  4775. return tokError(Twine("invalid DWARF op '") + Lex.getStrVal() + "'");
  4776. }
  4777. if (Lex.getKind() == lltok::DwarfAttEncoding) {
  4778. if (unsigned Op = dwarf::getAttributeEncoding(Lex.getStrVal())) {
  4779. Lex.Lex();
  4780. Elements.push_back(Op);
  4781. continue;
  4782. }
  4783. return tokError(Twine("invalid DWARF attribute encoding '") +
  4784. Lex.getStrVal() + "'");
  4785. }
  4786. if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
  4787. return tokError("expected unsigned integer");
  4788. auto &U = Lex.getAPSIntVal();
  4789. if (U.ugt(UINT64_MAX))
  4790. return tokError("element too large, limit is " + Twine(UINT64_MAX));
  4791. Elements.push_back(U.getZExtValue());
  4792. Lex.Lex();
  4793. } while (EatIfPresent(lltok::comma));
  4794. if (parseToken(lltok::rparen, "expected ')' here"))
  4795. return true;
  4796. Result = GET_OR_DISTINCT(DIExpression, (Context, Elements));
  4797. return false;
  4798. }
  4799. bool LLParser::parseDIArgList(MDNode *&Result, bool IsDistinct) {
  4800. return parseDIArgList(Result, IsDistinct, nullptr);
  4801. }
  4802. /// ParseDIArgList:
  4803. /// ::= !DIArgList(i32 7, i64 %0)
  4804. bool LLParser::parseDIArgList(MDNode *&Result, bool IsDistinct,
  4805. PerFunctionState *PFS) {
  4806. assert(PFS && "Expected valid function state");
  4807. assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
  4808. Lex.Lex();
  4809. if (parseToken(lltok::lparen, "expected '(' here"))
  4810. return true;
  4811. SmallVector<ValueAsMetadata *, 4> Args;
  4812. if (Lex.getKind() != lltok::rparen)
  4813. do {
  4814. Metadata *MD;
  4815. if (parseValueAsMetadata(MD, "expected value-as-metadata operand", PFS))
  4816. return true;
  4817. Args.push_back(dyn_cast<ValueAsMetadata>(MD));
  4818. } while (EatIfPresent(lltok::comma));
  4819. if (parseToken(lltok::rparen, "expected ')' here"))
  4820. return true;
  4821. Result = GET_OR_DISTINCT(DIArgList, (Context, Args));
  4822. return false;
  4823. }
  4824. /// parseDIGlobalVariableExpression:
  4825. /// ::= !DIGlobalVariableExpression(var: !0, expr: !1)
  4826. bool LLParser::parseDIGlobalVariableExpression(MDNode *&Result,
  4827. bool IsDistinct) {
  4828. #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
  4829. REQUIRED(var, MDField, ); \
  4830. REQUIRED(expr, MDField, );
  4831. PARSE_MD_FIELDS();
  4832. #undef VISIT_MD_FIELDS
  4833. Result =
  4834. GET_OR_DISTINCT(DIGlobalVariableExpression, (Context, var.Val, expr.Val));
  4835. return false;
  4836. }
  4837. /// parseDIObjCProperty:
  4838. /// ::= !DIObjCProperty(name: "foo", file: !1, line: 7, setter: "setFoo",
  4839. /// getter: "getFoo", attributes: 7, type: !2)
  4840. bool LLParser::parseDIObjCProperty(MDNode *&Result, bool IsDistinct) {
  4841. #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
  4842. OPTIONAL(name, MDStringField, ); \
  4843. OPTIONAL(file, MDField, ); \
  4844. OPTIONAL(line, LineField, ); \
  4845. OPTIONAL(setter, MDStringField, ); \
  4846. OPTIONAL(getter, MDStringField, ); \
  4847. OPTIONAL(attributes, MDUnsignedField, (0, UINT32_MAX)); \
  4848. OPTIONAL(type, MDField, );
  4849. PARSE_MD_FIELDS();
  4850. #undef VISIT_MD_FIELDS
  4851. Result = GET_OR_DISTINCT(DIObjCProperty,
  4852. (Context, name.Val, file.Val, line.Val, setter.Val,
  4853. getter.Val, attributes.Val, type.Val));
  4854. return false;
  4855. }
  4856. /// parseDIImportedEntity:
  4857. /// ::= !DIImportedEntity(tag: DW_TAG_imported_module, scope: !0, entity: !1,
  4858. /// line: 7, name: "foo", elements: !2)
  4859. bool LLParser::parseDIImportedEntity(MDNode *&Result, bool IsDistinct) {
  4860. #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
  4861. REQUIRED(tag, DwarfTagField, ); \
  4862. REQUIRED(scope, MDField, ); \
  4863. OPTIONAL(entity, MDField, ); \
  4864. OPTIONAL(file, MDField, ); \
  4865. OPTIONAL(line, LineField, ); \
  4866. OPTIONAL(name, MDStringField, ); \
  4867. OPTIONAL(elements, MDField, );
  4868. PARSE_MD_FIELDS();
  4869. #undef VISIT_MD_FIELDS
  4870. Result = GET_OR_DISTINCT(DIImportedEntity,
  4871. (Context, tag.Val, scope.Val, entity.Val, file.Val,
  4872. line.Val, name.Val, elements.Val));
  4873. return false;
  4874. }
  4875. #undef PARSE_MD_FIELD
  4876. #undef NOP_FIELD
  4877. #undef REQUIRE_FIELD
  4878. #undef DECLARE_FIELD
  4879. /// parseMetadataAsValue
  4880. /// ::= metadata i32 %local
  4881. /// ::= metadata i32 @global
  4882. /// ::= metadata i32 7
  4883. /// ::= metadata !0
  4884. /// ::= metadata !{...}
  4885. /// ::= metadata !"string"
  4886. bool LLParser::parseMetadataAsValue(Value *&V, PerFunctionState &PFS) {
  4887. // Note: the type 'metadata' has already been parsed.
  4888. Metadata *MD;
  4889. if (parseMetadata(MD, &PFS))
  4890. return true;
  4891. V = MetadataAsValue::get(Context, MD);
  4892. return false;
  4893. }
  4894. /// parseValueAsMetadata
  4895. /// ::= i32 %local
  4896. /// ::= i32 @global
  4897. /// ::= i32 7
  4898. bool LLParser::parseValueAsMetadata(Metadata *&MD, const Twine &TypeMsg,
  4899. PerFunctionState *PFS) {
  4900. Type *Ty;
  4901. LocTy Loc;
  4902. if (parseType(Ty, TypeMsg, Loc))
  4903. return true;
  4904. if (Ty->isMetadataTy())
  4905. return error(Loc, "invalid metadata-value-metadata roundtrip");
  4906. Value *V;
  4907. if (parseValue(Ty, V, PFS))
  4908. return true;
  4909. MD = ValueAsMetadata::get(V);
  4910. return false;
  4911. }
  4912. /// parseMetadata
  4913. /// ::= i32 %local
  4914. /// ::= i32 @global
  4915. /// ::= i32 7
  4916. /// ::= !42
  4917. /// ::= !{...}
  4918. /// ::= !"string"
  4919. /// ::= !DILocation(...)
  4920. bool LLParser::parseMetadata(Metadata *&MD, PerFunctionState *PFS) {
  4921. if (Lex.getKind() == lltok::MetadataVar) {
  4922. MDNode *N;
  4923. // DIArgLists are a special case, as they are a list of ValueAsMetadata and
  4924. // so parsing this requires a Function State.
  4925. if (Lex.getStrVal() == "DIArgList") {
  4926. if (parseDIArgList(N, false, PFS))
  4927. return true;
  4928. } else if (parseSpecializedMDNode(N)) {
  4929. return true;
  4930. }
  4931. MD = N;
  4932. return false;
  4933. }
  4934. // ValueAsMetadata:
  4935. // <type> <value>
  4936. if (Lex.getKind() != lltok::exclaim)
  4937. return parseValueAsMetadata(MD, "expected metadata operand", PFS);
  4938. // '!'.
  4939. assert(Lex.getKind() == lltok::exclaim && "Expected '!' here");
  4940. Lex.Lex();
  4941. // MDString:
  4942. // ::= '!' STRINGCONSTANT
  4943. if (Lex.getKind() == lltok::StringConstant) {
  4944. MDString *S;
  4945. if (parseMDString(S))
  4946. return true;
  4947. MD = S;
  4948. return false;
  4949. }
  4950. // MDNode:
  4951. // !{ ... }
  4952. // !7
  4953. MDNode *N;
  4954. if (parseMDNodeTail(N))
  4955. return true;
  4956. MD = N;
  4957. return false;
  4958. }
  4959. //===----------------------------------------------------------------------===//
  4960. // Function Parsing.
  4961. //===----------------------------------------------------------------------===//
  4962. bool LLParser::convertValIDToValue(Type *Ty, ValID &ID, Value *&V,
  4963. PerFunctionState *PFS) {
  4964. if (Ty->isFunctionTy())
  4965. return error(ID.Loc, "functions are not values, refer to them as pointers");
  4966. switch (ID.Kind) {
  4967. case ValID::t_LocalID:
  4968. if (!PFS)
  4969. return error(ID.Loc, "invalid use of function-local name");
  4970. V = PFS->getVal(ID.UIntVal, Ty, ID.Loc);
  4971. return V == nullptr;
  4972. case ValID::t_LocalName:
  4973. if (!PFS)
  4974. return error(ID.Loc, "invalid use of function-local name");
  4975. V = PFS->getVal(ID.StrVal, Ty, ID.Loc);
  4976. return V == nullptr;
  4977. case ValID::t_InlineAsm: {
  4978. if (!ID.FTy)
  4979. return error(ID.Loc, "invalid type for inline asm constraint string");
  4980. if (Error Err = InlineAsm::verify(ID.FTy, ID.StrVal2))
  4981. return error(ID.Loc, toString(std::move(Err)));
  4982. V = InlineAsm::get(
  4983. ID.FTy, ID.StrVal, ID.StrVal2, ID.UIntVal & 1, (ID.UIntVal >> 1) & 1,
  4984. InlineAsm::AsmDialect((ID.UIntVal >> 2) & 1), (ID.UIntVal >> 3) & 1);
  4985. return false;
  4986. }
  4987. case ValID::t_GlobalName:
  4988. V = getGlobalVal(ID.StrVal, Ty, ID.Loc);
  4989. if (V && ID.NoCFI)
  4990. V = NoCFIValue::get(cast<GlobalValue>(V));
  4991. return V == nullptr;
  4992. case ValID::t_GlobalID:
  4993. V = getGlobalVal(ID.UIntVal, Ty, ID.Loc);
  4994. if (V && ID.NoCFI)
  4995. V = NoCFIValue::get(cast<GlobalValue>(V));
  4996. return V == nullptr;
  4997. case ValID::t_APSInt:
  4998. if (!Ty->isIntegerTy())
  4999. return error(ID.Loc, "integer constant must have integer type");
  5000. ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
  5001. V = ConstantInt::get(Context, ID.APSIntVal);
  5002. return false;
  5003. case ValID::t_APFloat:
  5004. if (!Ty->isFloatingPointTy() ||
  5005. !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
  5006. return error(ID.Loc, "floating point constant invalid for type");
  5007. // The lexer has no type info, so builds all half, bfloat, float, and double
  5008. // FP constants as double. Fix this here. Long double does not need this.
  5009. if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble()) {
  5010. // Check for signaling before potentially converting and losing that info.
  5011. bool IsSNAN = ID.APFloatVal.isSignaling();
  5012. bool Ignored;
  5013. if (Ty->isHalfTy())
  5014. ID.APFloatVal.convert(APFloat::IEEEhalf(), APFloat::rmNearestTiesToEven,
  5015. &Ignored);
  5016. else if (Ty->isBFloatTy())
  5017. ID.APFloatVal.convert(APFloat::BFloat(), APFloat::rmNearestTiesToEven,
  5018. &Ignored);
  5019. else if (Ty->isFloatTy())
  5020. ID.APFloatVal.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven,
  5021. &Ignored);
  5022. if (IsSNAN) {
  5023. // The convert call above may quiet an SNaN, so manufacture another
  5024. // SNaN. The bitcast works because the payload (significand) parameter
  5025. // is truncated to fit.
  5026. APInt Payload = ID.APFloatVal.bitcastToAPInt();
  5027. ID.APFloatVal = APFloat::getSNaN(ID.APFloatVal.getSemantics(),
  5028. ID.APFloatVal.isNegative(), &Payload);
  5029. }
  5030. }
  5031. V = ConstantFP::get(Context, ID.APFloatVal);
  5032. if (V->getType() != Ty)
  5033. return error(ID.Loc, "floating point constant does not have type '" +
  5034. getTypeString(Ty) + "'");
  5035. return false;
  5036. case ValID::t_Null:
  5037. if (!Ty->isPointerTy())
  5038. return error(ID.Loc, "null must be a pointer type");
  5039. V = ConstantPointerNull::get(cast<PointerType>(Ty));
  5040. return false;
  5041. case ValID::t_Undef:
  5042. // FIXME: LabelTy should not be a first-class type.
  5043. if (!Ty->isFirstClassType() || Ty->isLabelTy())
  5044. return error(ID.Loc, "invalid type for undef constant");
  5045. V = UndefValue::get(Ty);
  5046. return false;
  5047. case ValID::t_EmptyArray:
  5048. if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
  5049. return error(ID.Loc, "invalid empty array initializer");
  5050. V = UndefValue::get(Ty);
  5051. return false;
  5052. case ValID::t_Zero:
  5053. // FIXME: LabelTy should not be a first-class type.
  5054. if (!Ty->isFirstClassType() || Ty->isLabelTy())
  5055. return error(ID.Loc, "invalid type for null constant");
  5056. if (auto *TETy = dyn_cast<TargetExtType>(Ty))
  5057. if (!TETy->hasProperty(TargetExtType::HasZeroInit))
  5058. return error(ID.Loc, "invalid type for null constant");
  5059. V = Constant::getNullValue(Ty);
  5060. return false;
  5061. case ValID::t_None:
  5062. if (!Ty->isTokenTy())
  5063. return error(ID.Loc, "invalid type for none constant");
  5064. V = Constant::getNullValue(Ty);
  5065. return false;
  5066. case ValID::t_Poison:
  5067. // FIXME: LabelTy should not be a first-class type.
  5068. if (!Ty->isFirstClassType() || Ty->isLabelTy())
  5069. return error(ID.Loc, "invalid type for poison constant");
  5070. V = PoisonValue::get(Ty);
  5071. return false;
  5072. case ValID::t_Constant:
  5073. if (ID.ConstantVal->getType() != Ty)
  5074. return error(ID.Loc, "constant expression type mismatch: got type '" +
  5075. getTypeString(ID.ConstantVal->getType()) +
  5076. "' but expected '" + getTypeString(Ty) + "'");
  5077. V = ID.ConstantVal;
  5078. return false;
  5079. case ValID::t_ConstantStruct:
  5080. case ValID::t_PackedConstantStruct:
  5081. if (StructType *ST = dyn_cast<StructType>(Ty)) {
  5082. if (ST->getNumElements() != ID.UIntVal)
  5083. return error(ID.Loc,
  5084. "initializer with struct type has wrong # elements");
  5085. if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
  5086. return error(ID.Loc, "packed'ness of initializer and type don't match");
  5087. // Verify that the elements are compatible with the structtype.
  5088. for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
  5089. if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
  5090. return error(
  5091. ID.Loc,
  5092. "element " + Twine(i) +
  5093. " of struct initializer doesn't match struct element type");
  5094. V = ConstantStruct::get(
  5095. ST, ArrayRef(ID.ConstantStructElts.get(), ID.UIntVal));
  5096. } else
  5097. return error(ID.Loc, "constant expression type mismatch");
  5098. return false;
  5099. }
  5100. llvm_unreachable("Invalid ValID");
  5101. }
  5102. bool LLParser::parseConstantValue(Type *Ty, Constant *&C) {
  5103. C = nullptr;
  5104. ValID ID;
  5105. auto Loc = Lex.getLoc();
  5106. if (parseValID(ID, /*PFS=*/nullptr))
  5107. return true;
  5108. switch (ID.Kind) {
  5109. case ValID::t_APSInt:
  5110. case ValID::t_APFloat:
  5111. case ValID::t_Undef:
  5112. case ValID::t_Constant:
  5113. case ValID::t_ConstantStruct:
  5114. case ValID::t_PackedConstantStruct: {
  5115. Value *V;
  5116. if (convertValIDToValue(Ty, ID, V, /*PFS=*/nullptr))
  5117. return true;
  5118. assert(isa<Constant>(V) && "Expected a constant value");
  5119. C = cast<Constant>(V);
  5120. return false;
  5121. }
  5122. case ValID::t_Null:
  5123. C = Constant::getNullValue(Ty);
  5124. return false;
  5125. default:
  5126. return error(Loc, "expected a constant value");
  5127. }
  5128. }
  5129. bool LLParser::parseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
  5130. V = nullptr;
  5131. ValID ID;
  5132. return parseValID(ID, PFS, Ty) ||
  5133. convertValIDToValue(Ty, ID, V, PFS);
  5134. }
  5135. bool LLParser::parseTypeAndValue(Value *&V, PerFunctionState *PFS) {
  5136. Type *Ty = nullptr;
  5137. return parseType(Ty) || parseValue(Ty, V, PFS);
  5138. }
  5139. bool LLParser::parseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
  5140. PerFunctionState &PFS) {
  5141. Value *V;
  5142. Loc = Lex.getLoc();
  5143. if (parseTypeAndValue(V, PFS))
  5144. return true;
  5145. if (!isa<BasicBlock>(V))
  5146. return error(Loc, "expected a basic block");
  5147. BB = cast<BasicBlock>(V);
  5148. return false;
  5149. }
  5150. /// FunctionHeader
  5151. /// ::= OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
  5152. /// OptionalCallingConv OptRetAttrs OptUnnamedAddr Type GlobalName
  5153. /// '(' ArgList ')' OptAddrSpace OptFuncAttrs OptSection OptionalAlign
  5154. /// OptGC OptionalPrefix OptionalPrologue OptPersonalityFn
  5155. bool LLParser::parseFunctionHeader(Function *&Fn, bool IsDefine) {
  5156. // parse the linkage.
  5157. LocTy LinkageLoc = Lex.getLoc();
  5158. unsigned Linkage;
  5159. unsigned Visibility;
  5160. unsigned DLLStorageClass;
  5161. bool DSOLocal;
  5162. AttrBuilder RetAttrs(M->getContext());
  5163. unsigned CC;
  5164. bool HasLinkage;
  5165. Type *RetType = nullptr;
  5166. LocTy RetTypeLoc = Lex.getLoc();
  5167. if (parseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
  5168. DSOLocal) ||
  5169. parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
  5170. parseType(RetType, RetTypeLoc, true /*void allowed*/))
  5171. return true;
  5172. // Verify that the linkage is ok.
  5173. switch ((GlobalValue::LinkageTypes)Linkage) {
  5174. case GlobalValue::ExternalLinkage:
  5175. break; // always ok.
  5176. case GlobalValue::ExternalWeakLinkage:
  5177. if (IsDefine)
  5178. return error(LinkageLoc, "invalid linkage for function definition");
  5179. break;
  5180. case GlobalValue::PrivateLinkage:
  5181. case GlobalValue::InternalLinkage:
  5182. case GlobalValue::AvailableExternallyLinkage:
  5183. case GlobalValue::LinkOnceAnyLinkage:
  5184. case GlobalValue::LinkOnceODRLinkage:
  5185. case GlobalValue::WeakAnyLinkage:
  5186. case GlobalValue::WeakODRLinkage:
  5187. if (!IsDefine)
  5188. return error(LinkageLoc, "invalid linkage for function declaration");
  5189. break;
  5190. case GlobalValue::AppendingLinkage:
  5191. case GlobalValue::CommonLinkage:
  5192. return error(LinkageLoc, "invalid function linkage type");
  5193. }
  5194. if (!isValidVisibilityForLinkage(Visibility, Linkage))
  5195. return error(LinkageLoc,
  5196. "symbol with local linkage must have default visibility");
  5197. if (!isValidDLLStorageClassForLinkage(DLLStorageClass, Linkage))
  5198. return error(LinkageLoc,
  5199. "symbol with local linkage cannot have a DLL storage class");
  5200. if (!FunctionType::isValidReturnType(RetType))
  5201. return error(RetTypeLoc, "invalid function return type");
  5202. LocTy NameLoc = Lex.getLoc();
  5203. std::string FunctionName;
  5204. if (Lex.getKind() == lltok::GlobalVar) {
  5205. FunctionName = Lex.getStrVal();
  5206. } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
  5207. unsigned NameID = Lex.getUIntVal();
  5208. if (NameID != NumberedVals.size())
  5209. return tokError("function expected to be numbered '%" +
  5210. Twine(NumberedVals.size()) + "'");
  5211. } else {
  5212. return tokError("expected function name");
  5213. }
  5214. Lex.Lex();
  5215. if (Lex.getKind() != lltok::lparen)
  5216. return tokError("expected '(' in function argument list");
  5217. SmallVector<ArgInfo, 8> ArgList;
  5218. bool IsVarArg;
  5219. AttrBuilder FuncAttrs(M->getContext());
  5220. std::vector<unsigned> FwdRefAttrGrps;
  5221. LocTy BuiltinLoc;
  5222. std::string Section;
  5223. std::string Partition;
  5224. MaybeAlign Alignment;
  5225. std::string GC;
  5226. GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None;
  5227. unsigned AddrSpace = 0;
  5228. Constant *Prefix = nullptr;
  5229. Constant *Prologue = nullptr;
  5230. Constant *PersonalityFn = nullptr;
  5231. Comdat *C;
  5232. if (parseArgumentList(ArgList, IsVarArg) ||
  5233. parseOptionalUnnamedAddr(UnnamedAddr) ||
  5234. parseOptionalProgramAddrSpace(AddrSpace) ||
  5235. parseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false,
  5236. BuiltinLoc) ||
  5237. (EatIfPresent(lltok::kw_section) && parseStringConstant(Section)) ||
  5238. (EatIfPresent(lltok::kw_partition) && parseStringConstant(Partition)) ||
  5239. parseOptionalComdat(FunctionName, C) ||
  5240. parseOptionalAlignment(Alignment) ||
  5241. (EatIfPresent(lltok::kw_gc) && parseStringConstant(GC)) ||
  5242. (EatIfPresent(lltok::kw_prefix) && parseGlobalTypeAndValue(Prefix)) ||
  5243. (EatIfPresent(lltok::kw_prologue) && parseGlobalTypeAndValue(Prologue)) ||
  5244. (EatIfPresent(lltok::kw_personality) &&
  5245. parseGlobalTypeAndValue(PersonalityFn)))
  5246. return true;
  5247. if (FuncAttrs.contains(Attribute::Builtin))
  5248. return error(BuiltinLoc, "'builtin' attribute not valid on function");
  5249. // If the alignment was parsed as an attribute, move to the alignment field.
  5250. if (MaybeAlign A = FuncAttrs.getAlignment()) {
  5251. Alignment = A;
  5252. FuncAttrs.removeAttribute(Attribute::Alignment);
  5253. }
  5254. // Okay, if we got here, the function is syntactically valid. Convert types
  5255. // and do semantic checks.
  5256. std::vector<Type*> ParamTypeList;
  5257. SmallVector<AttributeSet, 8> Attrs;
  5258. for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
  5259. ParamTypeList.push_back(ArgList[i].Ty);
  5260. Attrs.push_back(ArgList[i].Attrs);
  5261. }
  5262. AttributeList PAL =
  5263. AttributeList::get(Context, AttributeSet::get(Context, FuncAttrs),
  5264. AttributeSet::get(Context, RetAttrs), Attrs);
  5265. if (PAL.hasParamAttr(0, Attribute::StructRet) && !RetType->isVoidTy())
  5266. return error(RetTypeLoc, "functions with 'sret' argument must return void");
  5267. FunctionType *FT = FunctionType::get(RetType, ParamTypeList, IsVarArg);
  5268. PointerType *PFT = PointerType::get(FT, AddrSpace);
  5269. Fn = nullptr;
  5270. GlobalValue *FwdFn = nullptr;
  5271. if (!FunctionName.empty()) {
  5272. // If this was a definition of a forward reference, remove the definition
  5273. // from the forward reference table and fill in the forward ref.
  5274. auto FRVI = ForwardRefVals.find(FunctionName);
  5275. if (FRVI != ForwardRefVals.end()) {
  5276. FwdFn = FRVI->second.first;
  5277. if (!FwdFn->getType()->isOpaque() &&
  5278. !FwdFn->getType()->getNonOpaquePointerElementType()->isFunctionTy())
  5279. return error(FRVI->second.second, "invalid forward reference to "
  5280. "function as global value!");
  5281. if (FwdFn->getType() != PFT)
  5282. return error(FRVI->second.second,
  5283. "invalid forward reference to "
  5284. "function '" +
  5285. FunctionName +
  5286. "' with wrong type: "
  5287. "expected '" +
  5288. getTypeString(PFT) + "' but was '" +
  5289. getTypeString(FwdFn->getType()) + "'");
  5290. ForwardRefVals.erase(FRVI);
  5291. } else if ((Fn = M->getFunction(FunctionName))) {
  5292. // Reject redefinitions.
  5293. return error(NameLoc,
  5294. "invalid redefinition of function '" + FunctionName + "'");
  5295. } else if (M->getNamedValue(FunctionName)) {
  5296. return error(NameLoc, "redefinition of function '@" + FunctionName + "'");
  5297. }
  5298. } else {
  5299. // If this is a definition of a forward referenced function, make sure the
  5300. // types agree.
  5301. auto I = ForwardRefValIDs.find(NumberedVals.size());
  5302. if (I != ForwardRefValIDs.end()) {
  5303. FwdFn = I->second.first;
  5304. if (FwdFn->getType() != PFT)
  5305. return error(NameLoc, "type of definition and forward reference of '@" +
  5306. Twine(NumberedVals.size()) +
  5307. "' disagree: "
  5308. "expected '" +
  5309. getTypeString(PFT) + "' but was '" +
  5310. getTypeString(FwdFn->getType()) + "'");
  5311. ForwardRefValIDs.erase(I);
  5312. }
  5313. }
  5314. Fn = Function::Create(FT, GlobalValue::ExternalLinkage, AddrSpace,
  5315. FunctionName, M);
  5316. assert(Fn->getAddressSpace() == AddrSpace && "Created function in wrong AS");
  5317. if (FunctionName.empty())
  5318. NumberedVals.push_back(Fn);
  5319. Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
  5320. maybeSetDSOLocal(DSOLocal, *Fn);
  5321. Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
  5322. Fn->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
  5323. Fn->setCallingConv(CC);
  5324. Fn->setAttributes(PAL);
  5325. Fn->setUnnamedAddr(UnnamedAddr);
  5326. Fn->setAlignment(MaybeAlign(Alignment));
  5327. Fn->setSection(Section);
  5328. Fn->setPartition(Partition);
  5329. Fn->setComdat(C);
  5330. Fn->setPersonalityFn(PersonalityFn);
  5331. if (!GC.empty()) Fn->setGC(GC);
  5332. Fn->setPrefixData(Prefix);
  5333. Fn->setPrologueData(Prologue);
  5334. ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
  5335. // Add all of the arguments we parsed to the function.
  5336. Function::arg_iterator ArgIt = Fn->arg_begin();
  5337. for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
  5338. // If the argument has a name, insert it into the argument symbol table.
  5339. if (ArgList[i].Name.empty()) continue;
  5340. // Set the name, if it conflicted, it will be auto-renamed.
  5341. ArgIt->setName(ArgList[i].Name);
  5342. if (ArgIt->getName() != ArgList[i].Name)
  5343. return error(ArgList[i].Loc,
  5344. "redefinition of argument '%" + ArgList[i].Name + "'");
  5345. }
  5346. if (FwdFn) {
  5347. FwdFn->replaceAllUsesWith(Fn);
  5348. FwdFn->eraseFromParent();
  5349. }
  5350. if (IsDefine)
  5351. return false;
  5352. // Check the declaration has no block address forward references.
  5353. ValID ID;
  5354. if (FunctionName.empty()) {
  5355. ID.Kind = ValID::t_GlobalID;
  5356. ID.UIntVal = NumberedVals.size() - 1;
  5357. } else {
  5358. ID.Kind = ValID::t_GlobalName;
  5359. ID.StrVal = FunctionName;
  5360. }
  5361. auto Blocks = ForwardRefBlockAddresses.find(ID);
  5362. if (Blocks != ForwardRefBlockAddresses.end())
  5363. return error(Blocks->first.Loc,
  5364. "cannot take blockaddress inside a declaration");
  5365. return false;
  5366. }
  5367. bool LLParser::PerFunctionState::resolveForwardRefBlockAddresses() {
  5368. ValID ID;
  5369. if (FunctionNumber == -1) {
  5370. ID.Kind = ValID::t_GlobalName;
  5371. ID.StrVal = std::string(F.getName());
  5372. } else {
  5373. ID.Kind = ValID::t_GlobalID;
  5374. ID.UIntVal = FunctionNumber;
  5375. }
  5376. auto Blocks = P.ForwardRefBlockAddresses.find(ID);
  5377. if (Blocks == P.ForwardRefBlockAddresses.end())
  5378. return false;
  5379. for (const auto &I : Blocks->second) {
  5380. const ValID &BBID = I.first;
  5381. GlobalValue *GV = I.second;
  5382. assert((BBID.Kind == ValID::t_LocalID || BBID.Kind == ValID::t_LocalName) &&
  5383. "Expected local id or name");
  5384. BasicBlock *BB;
  5385. if (BBID.Kind == ValID::t_LocalName)
  5386. BB = getBB(BBID.StrVal, BBID.Loc);
  5387. else
  5388. BB = getBB(BBID.UIntVal, BBID.Loc);
  5389. if (!BB)
  5390. return P.error(BBID.Loc, "referenced value is not a basic block");
  5391. Value *ResolvedVal = BlockAddress::get(&F, BB);
  5392. ResolvedVal = P.checkValidVariableType(BBID.Loc, BBID.StrVal, GV->getType(),
  5393. ResolvedVal);
  5394. if (!ResolvedVal)
  5395. return true;
  5396. GV->replaceAllUsesWith(ResolvedVal);
  5397. GV->eraseFromParent();
  5398. }
  5399. P.ForwardRefBlockAddresses.erase(Blocks);
  5400. return false;
  5401. }
  5402. /// parseFunctionBody
  5403. /// ::= '{' BasicBlock+ UseListOrderDirective* '}'
  5404. bool LLParser::parseFunctionBody(Function &Fn) {
  5405. if (Lex.getKind() != lltok::lbrace)
  5406. return tokError("expected '{' in function body");
  5407. Lex.Lex(); // eat the {.
  5408. int FunctionNumber = -1;
  5409. if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
  5410. PerFunctionState PFS(*this, Fn, FunctionNumber);
  5411. // Resolve block addresses and allow basic blocks to be forward-declared
  5412. // within this function.
  5413. if (PFS.resolveForwardRefBlockAddresses())
  5414. return true;
  5415. SaveAndRestore ScopeExit(BlockAddressPFS, &PFS);
  5416. // We need at least one basic block.
  5417. if (Lex.getKind() == lltok::rbrace || Lex.getKind() == lltok::kw_uselistorder)
  5418. return tokError("function body requires at least one basic block");
  5419. while (Lex.getKind() != lltok::rbrace &&
  5420. Lex.getKind() != lltok::kw_uselistorder)
  5421. if (parseBasicBlock(PFS))
  5422. return true;
  5423. while (Lex.getKind() != lltok::rbrace)
  5424. if (parseUseListOrder(&PFS))
  5425. return true;
  5426. // Eat the }.
  5427. Lex.Lex();
  5428. // Verify function is ok.
  5429. return PFS.finishFunction();
  5430. }
  5431. /// parseBasicBlock
  5432. /// ::= (LabelStr|LabelID)? Instruction*
  5433. bool LLParser::parseBasicBlock(PerFunctionState &PFS) {
  5434. // If this basic block starts out with a name, remember it.
  5435. std::string Name;
  5436. int NameID = -1;
  5437. LocTy NameLoc = Lex.getLoc();
  5438. if (Lex.getKind() == lltok::LabelStr) {
  5439. Name = Lex.getStrVal();
  5440. Lex.Lex();
  5441. } else if (Lex.getKind() == lltok::LabelID) {
  5442. NameID = Lex.getUIntVal();
  5443. Lex.Lex();
  5444. }
  5445. BasicBlock *BB = PFS.defineBB(Name, NameID, NameLoc);
  5446. if (!BB)
  5447. return true;
  5448. std::string NameStr;
  5449. // parse the instructions in this block until we get a terminator.
  5450. Instruction *Inst;
  5451. do {
  5452. // This instruction may have three possibilities for a name: a) none
  5453. // specified, b) name specified "%foo =", c) number specified: "%4 =".
  5454. LocTy NameLoc = Lex.getLoc();
  5455. int NameID = -1;
  5456. NameStr = "";
  5457. if (Lex.getKind() == lltok::LocalVarID) {
  5458. NameID = Lex.getUIntVal();
  5459. Lex.Lex();
  5460. if (parseToken(lltok::equal, "expected '=' after instruction id"))
  5461. return true;
  5462. } else if (Lex.getKind() == lltok::LocalVar) {
  5463. NameStr = Lex.getStrVal();
  5464. Lex.Lex();
  5465. if (parseToken(lltok::equal, "expected '=' after instruction name"))
  5466. return true;
  5467. }
  5468. switch (parseInstruction(Inst, BB, PFS)) {
  5469. default:
  5470. llvm_unreachable("Unknown parseInstruction result!");
  5471. case InstError: return true;
  5472. case InstNormal:
  5473. Inst->insertInto(BB, BB->end());
  5474. // With a normal result, we check to see if the instruction is followed by
  5475. // a comma and metadata.
  5476. if (EatIfPresent(lltok::comma))
  5477. if (parseInstructionMetadata(*Inst))
  5478. return true;
  5479. break;
  5480. case InstExtraComma:
  5481. Inst->insertInto(BB, BB->end());
  5482. // If the instruction parser ate an extra comma at the end of it, it
  5483. // *must* be followed by metadata.
  5484. if (parseInstructionMetadata(*Inst))
  5485. return true;
  5486. break;
  5487. }
  5488. // Set the name on the instruction.
  5489. if (PFS.setInstName(NameID, NameStr, NameLoc, Inst))
  5490. return true;
  5491. } while (!Inst->isTerminator());
  5492. return false;
  5493. }
  5494. //===----------------------------------------------------------------------===//
  5495. // Instruction Parsing.
  5496. //===----------------------------------------------------------------------===//
  5497. /// parseInstruction - parse one of the many different instructions.
  5498. ///
  5499. int LLParser::parseInstruction(Instruction *&Inst, BasicBlock *BB,
  5500. PerFunctionState &PFS) {
  5501. lltok::Kind Token = Lex.getKind();
  5502. if (Token == lltok::Eof)
  5503. return tokError("found end of file when expecting more instructions");
  5504. LocTy Loc = Lex.getLoc();
  5505. unsigned KeywordVal = Lex.getUIntVal();
  5506. Lex.Lex(); // Eat the keyword.
  5507. switch (Token) {
  5508. default:
  5509. return error(Loc, "expected instruction opcode");
  5510. // Terminator Instructions.
  5511. case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
  5512. case lltok::kw_ret:
  5513. return parseRet(Inst, BB, PFS);
  5514. case lltok::kw_br:
  5515. return parseBr(Inst, PFS);
  5516. case lltok::kw_switch:
  5517. return parseSwitch(Inst, PFS);
  5518. case lltok::kw_indirectbr:
  5519. return parseIndirectBr(Inst, PFS);
  5520. case lltok::kw_invoke:
  5521. return parseInvoke(Inst, PFS);
  5522. case lltok::kw_resume:
  5523. return parseResume(Inst, PFS);
  5524. case lltok::kw_cleanupret:
  5525. return parseCleanupRet(Inst, PFS);
  5526. case lltok::kw_catchret:
  5527. return parseCatchRet(Inst, PFS);
  5528. case lltok::kw_catchswitch:
  5529. return parseCatchSwitch(Inst, PFS);
  5530. case lltok::kw_catchpad:
  5531. return parseCatchPad(Inst, PFS);
  5532. case lltok::kw_cleanuppad:
  5533. return parseCleanupPad(Inst, PFS);
  5534. case lltok::kw_callbr:
  5535. return parseCallBr(Inst, PFS);
  5536. // Unary Operators.
  5537. case lltok::kw_fneg: {
  5538. FastMathFlags FMF = EatFastMathFlagsIfPresent();
  5539. int Res = parseUnaryOp(Inst, PFS, KeywordVal, /*IsFP*/ true);
  5540. if (Res != 0)
  5541. return Res;
  5542. if (FMF.any())
  5543. Inst->setFastMathFlags(FMF);
  5544. return false;
  5545. }
  5546. // Binary Operators.
  5547. case lltok::kw_add:
  5548. case lltok::kw_sub:
  5549. case lltok::kw_mul:
  5550. case lltok::kw_shl: {
  5551. bool NUW = EatIfPresent(lltok::kw_nuw);
  5552. bool NSW = EatIfPresent(lltok::kw_nsw);
  5553. if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
  5554. if (parseArithmetic(Inst, PFS, KeywordVal, /*IsFP*/ false))
  5555. return true;
  5556. if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
  5557. if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
  5558. return false;
  5559. }
  5560. case lltok::kw_fadd:
  5561. case lltok::kw_fsub:
  5562. case lltok::kw_fmul:
  5563. case lltok::kw_fdiv:
  5564. case lltok::kw_frem: {
  5565. FastMathFlags FMF = EatFastMathFlagsIfPresent();
  5566. int Res = parseArithmetic(Inst, PFS, KeywordVal, /*IsFP*/ true);
  5567. if (Res != 0)
  5568. return Res;
  5569. if (FMF.any())
  5570. Inst->setFastMathFlags(FMF);
  5571. return 0;
  5572. }
  5573. case lltok::kw_sdiv:
  5574. case lltok::kw_udiv:
  5575. case lltok::kw_lshr:
  5576. case lltok::kw_ashr: {
  5577. bool Exact = EatIfPresent(lltok::kw_exact);
  5578. if (parseArithmetic(Inst, PFS, KeywordVal, /*IsFP*/ false))
  5579. return true;
  5580. if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
  5581. return false;
  5582. }
  5583. case lltok::kw_urem:
  5584. case lltok::kw_srem:
  5585. return parseArithmetic(Inst, PFS, KeywordVal,
  5586. /*IsFP*/ false);
  5587. case lltok::kw_and:
  5588. case lltok::kw_or:
  5589. case lltok::kw_xor:
  5590. return parseLogical(Inst, PFS, KeywordVal);
  5591. case lltok::kw_icmp:
  5592. return parseCompare(Inst, PFS, KeywordVal);
  5593. case lltok::kw_fcmp: {
  5594. FastMathFlags FMF = EatFastMathFlagsIfPresent();
  5595. int Res = parseCompare(Inst, PFS, KeywordVal);
  5596. if (Res != 0)
  5597. return Res;
  5598. if (FMF.any())
  5599. Inst->setFastMathFlags(FMF);
  5600. return 0;
  5601. }
  5602. // Casts.
  5603. case lltok::kw_trunc:
  5604. case lltok::kw_zext:
  5605. case lltok::kw_sext:
  5606. case lltok::kw_fptrunc:
  5607. case lltok::kw_fpext:
  5608. case lltok::kw_bitcast:
  5609. case lltok::kw_addrspacecast:
  5610. case lltok::kw_uitofp:
  5611. case lltok::kw_sitofp:
  5612. case lltok::kw_fptoui:
  5613. case lltok::kw_fptosi:
  5614. case lltok::kw_inttoptr:
  5615. case lltok::kw_ptrtoint:
  5616. return parseCast(Inst, PFS, KeywordVal);
  5617. // Other.
  5618. case lltok::kw_select: {
  5619. FastMathFlags FMF = EatFastMathFlagsIfPresent();
  5620. int Res = parseSelect(Inst, PFS);
  5621. if (Res != 0)
  5622. return Res;
  5623. if (FMF.any()) {
  5624. if (!isa<FPMathOperator>(Inst))
  5625. return error(Loc, "fast-math-flags specified for select without "
  5626. "floating-point scalar or vector return type");
  5627. Inst->setFastMathFlags(FMF);
  5628. }
  5629. return 0;
  5630. }
  5631. case lltok::kw_va_arg:
  5632. return parseVAArg(Inst, PFS);
  5633. case lltok::kw_extractelement:
  5634. return parseExtractElement(Inst, PFS);
  5635. case lltok::kw_insertelement:
  5636. return parseInsertElement(Inst, PFS);
  5637. case lltok::kw_shufflevector:
  5638. return parseShuffleVector(Inst, PFS);
  5639. case lltok::kw_phi: {
  5640. FastMathFlags FMF = EatFastMathFlagsIfPresent();
  5641. int Res = parsePHI(Inst, PFS);
  5642. if (Res != 0)
  5643. return Res;
  5644. if (FMF.any()) {
  5645. if (!isa<FPMathOperator>(Inst))
  5646. return error(Loc, "fast-math-flags specified for phi without "
  5647. "floating-point scalar or vector return type");
  5648. Inst->setFastMathFlags(FMF);
  5649. }
  5650. return 0;
  5651. }
  5652. case lltok::kw_landingpad:
  5653. return parseLandingPad(Inst, PFS);
  5654. case lltok::kw_freeze:
  5655. return parseFreeze(Inst, PFS);
  5656. // Call.
  5657. case lltok::kw_call:
  5658. return parseCall(Inst, PFS, CallInst::TCK_None);
  5659. case lltok::kw_tail:
  5660. return parseCall(Inst, PFS, CallInst::TCK_Tail);
  5661. case lltok::kw_musttail:
  5662. return parseCall(Inst, PFS, CallInst::TCK_MustTail);
  5663. case lltok::kw_notail:
  5664. return parseCall(Inst, PFS, CallInst::TCK_NoTail);
  5665. // Memory.
  5666. case lltok::kw_alloca:
  5667. return parseAlloc(Inst, PFS);
  5668. case lltok::kw_load:
  5669. return parseLoad(Inst, PFS);
  5670. case lltok::kw_store:
  5671. return parseStore(Inst, PFS);
  5672. case lltok::kw_cmpxchg:
  5673. return parseCmpXchg(Inst, PFS);
  5674. case lltok::kw_atomicrmw:
  5675. return parseAtomicRMW(Inst, PFS);
  5676. case lltok::kw_fence:
  5677. return parseFence(Inst, PFS);
  5678. case lltok::kw_getelementptr:
  5679. return parseGetElementPtr(Inst, PFS);
  5680. case lltok::kw_extractvalue:
  5681. return parseExtractValue(Inst, PFS);
  5682. case lltok::kw_insertvalue:
  5683. return parseInsertValue(Inst, PFS);
  5684. }
  5685. }
  5686. /// parseCmpPredicate - parse an integer or fp predicate, based on Kind.
  5687. bool LLParser::parseCmpPredicate(unsigned &P, unsigned Opc) {
  5688. if (Opc == Instruction::FCmp) {
  5689. switch (Lex.getKind()) {
  5690. default:
  5691. return tokError("expected fcmp predicate (e.g. 'oeq')");
  5692. case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
  5693. case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
  5694. case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
  5695. case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
  5696. case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
  5697. case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
  5698. case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
  5699. case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
  5700. case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
  5701. case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
  5702. case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
  5703. case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
  5704. case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
  5705. case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
  5706. case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
  5707. case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
  5708. }
  5709. } else {
  5710. switch (Lex.getKind()) {
  5711. default:
  5712. return tokError("expected icmp predicate (e.g. 'eq')");
  5713. case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
  5714. case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
  5715. case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
  5716. case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
  5717. case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
  5718. case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
  5719. case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
  5720. case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
  5721. case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
  5722. case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
  5723. }
  5724. }
  5725. Lex.Lex();
  5726. return false;
  5727. }
  5728. //===----------------------------------------------------------------------===//
  5729. // Terminator Instructions.
  5730. //===----------------------------------------------------------------------===//
  5731. /// parseRet - parse a return instruction.
  5732. /// ::= 'ret' void (',' !dbg, !1)*
  5733. /// ::= 'ret' TypeAndValue (',' !dbg, !1)*
  5734. bool LLParser::parseRet(Instruction *&Inst, BasicBlock *BB,
  5735. PerFunctionState &PFS) {
  5736. SMLoc TypeLoc = Lex.getLoc();
  5737. Type *Ty = nullptr;
  5738. if (parseType(Ty, true /*void allowed*/))
  5739. return true;
  5740. Type *ResType = PFS.getFunction().getReturnType();
  5741. if (Ty->isVoidTy()) {
  5742. if (!ResType->isVoidTy())
  5743. return error(TypeLoc, "value doesn't match function result type '" +
  5744. getTypeString(ResType) + "'");
  5745. Inst = ReturnInst::Create(Context);
  5746. return false;
  5747. }
  5748. Value *RV;
  5749. if (parseValue(Ty, RV, PFS))
  5750. return true;
  5751. if (ResType != RV->getType())
  5752. return error(TypeLoc, "value doesn't match function result type '" +
  5753. getTypeString(ResType) + "'");
  5754. Inst = ReturnInst::Create(Context, RV);
  5755. return false;
  5756. }
  5757. /// parseBr
  5758. /// ::= 'br' TypeAndValue
  5759. /// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
  5760. bool LLParser::parseBr(Instruction *&Inst, PerFunctionState &PFS) {
  5761. LocTy Loc, Loc2;
  5762. Value *Op0;
  5763. BasicBlock *Op1, *Op2;
  5764. if (parseTypeAndValue(Op0, Loc, PFS))
  5765. return true;
  5766. if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
  5767. Inst = BranchInst::Create(BB);
  5768. return false;
  5769. }
  5770. if (Op0->getType() != Type::getInt1Ty(Context))
  5771. return error(Loc, "branch condition must have 'i1' type");
  5772. if (parseToken(lltok::comma, "expected ',' after branch condition") ||
  5773. parseTypeAndBasicBlock(Op1, Loc, PFS) ||
  5774. parseToken(lltok::comma, "expected ',' after true destination") ||
  5775. parseTypeAndBasicBlock(Op2, Loc2, PFS))
  5776. return true;
  5777. Inst = BranchInst::Create(Op1, Op2, Op0);
  5778. return false;
  5779. }
  5780. /// parseSwitch
  5781. /// Instruction
  5782. /// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
  5783. /// JumpTable
  5784. /// ::= (TypeAndValue ',' TypeAndValue)*
  5785. bool LLParser::parseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
  5786. LocTy CondLoc, BBLoc;
  5787. Value *Cond;
  5788. BasicBlock *DefaultBB;
  5789. if (parseTypeAndValue(Cond, CondLoc, PFS) ||
  5790. parseToken(lltok::comma, "expected ',' after switch condition") ||
  5791. parseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
  5792. parseToken(lltok::lsquare, "expected '[' with switch table"))
  5793. return true;
  5794. if (!Cond->getType()->isIntegerTy())
  5795. return error(CondLoc, "switch condition must have integer type");
  5796. // parse the jump table pairs.
  5797. SmallPtrSet<Value*, 32> SeenCases;
  5798. SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
  5799. while (Lex.getKind() != lltok::rsquare) {
  5800. Value *Constant;
  5801. BasicBlock *DestBB;
  5802. if (parseTypeAndValue(Constant, CondLoc, PFS) ||
  5803. parseToken(lltok::comma, "expected ',' after case value") ||
  5804. parseTypeAndBasicBlock(DestBB, PFS))
  5805. return true;
  5806. if (!SeenCases.insert(Constant).second)
  5807. return error(CondLoc, "duplicate case value in switch");
  5808. if (!isa<ConstantInt>(Constant))
  5809. return error(CondLoc, "case value is not a constant integer");
  5810. Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
  5811. }
  5812. Lex.Lex(); // Eat the ']'.
  5813. SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
  5814. for (unsigned i = 0, e = Table.size(); i != e; ++i)
  5815. SI->addCase(Table[i].first, Table[i].second);
  5816. Inst = SI;
  5817. return false;
  5818. }
  5819. /// parseIndirectBr
  5820. /// Instruction
  5821. /// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
  5822. bool LLParser::parseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
  5823. LocTy AddrLoc;
  5824. Value *Address;
  5825. if (parseTypeAndValue(Address, AddrLoc, PFS) ||
  5826. parseToken(lltok::comma, "expected ',' after indirectbr address") ||
  5827. parseToken(lltok::lsquare, "expected '[' with indirectbr"))
  5828. return true;
  5829. if (!Address->getType()->isPointerTy())
  5830. return error(AddrLoc, "indirectbr address must have pointer type");
  5831. // parse the destination list.
  5832. SmallVector<BasicBlock*, 16> DestList;
  5833. if (Lex.getKind() != lltok::rsquare) {
  5834. BasicBlock *DestBB;
  5835. if (parseTypeAndBasicBlock(DestBB, PFS))
  5836. return true;
  5837. DestList.push_back(DestBB);
  5838. while (EatIfPresent(lltok::comma)) {
  5839. if (parseTypeAndBasicBlock(DestBB, PFS))
  5840. return true;
  5841. DestList.push_back(DestBB);
  5842. }
  5843. }
  5844. if (parseToken(lltok::rsquare, "expected ']' at end of block list"))
  5845. return true;
  5846. IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
  5847. for (unsigned i = 0, e = DestList.size(); i != e; ++i)
  5848. IBI->addDestination(DestList[i]);
  5849. Inst = IBI;
  5850. return false;
  5851. }
  5852. // If RetType is a non-function pointer type, then this is the short syntax
  5853. // for the call, which means that RetType is just the return type. Infer the
  5854. // rest of the function argument types from the arguments that are present.
  5855. bool LLParser::resolveFunctionType(Type *RetType,
  5856. const SmallVector<ParamInfo, 16> &ArgList,
  5857. FunctionType *&FuncTy) {
  5858. FuncTy = dyn_cast<FunctionType>(RetType);
  5859. if (!FuncTy) {
  5860. // Pull out the types of all of the arguments...
  5861. std::vector<Type*> ParamTypes;
  5862. for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
  5863. ParamTypes.push_back(ArgList[i].V->getType());
  5864. if (!FunctionType::isValidReturnType(RetType))
  5865. return true;
  5866. FuncTy = FunctionType::get(RetType, ParamTypes, false);
  5867. }
  5868. return false;
  5869. }
  5870. /// parseInvoke
  5871. /// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
  5872. /// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
  5873. bool LLParser::parseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
  5874. LocTy CallLoc = Lex.getLoc();
  5875. AttrBuilder RetAttrs(M->getContext()), FnAttrs(M->getContext());
  5876. std::vector<unsigned> FwdRefAttrGrps;
  5877. LocTy NoBuiltinLoc;
  5878. unsigned CC;
  5879. unsigned InvokeAddrSpace;
  5880. Type *RetType = nullptr;
  5881. LocTy RetTypeLoc;
  5882. ValID CalleeID;
  5883. SmallVector<ParamInfo, 16> ArgList;
  5884. SmallVector<OperandBundleDef, 2> BundleList;
  5885. BasicBlock *NormalBB, *UnwindBB;
  5886. if (parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
  5887. parseOptionalProgramAddrSpace(InvokeAddrSpace) ||
  5888. parseType(RetType, RetTypeLoc, true /*void allowed*/) ||
  5889. parseValID(CalleeID, &PFS) || parseParameterList(ArgList, PFS) ||
  5890. parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
  5891. NoBuiltinLoc) ||
  5892. parseOptionalOperandBundles(BundleList, PFS) ||
  5893. parseToken(lltok::kw_to, "expected 'to' in invoke") ||
  5894. parseTypeAndBasicBlock(NormalBB, PFS) ||
  5895. parseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
  5896. parseTypeAndBasicBlock(UnwindBB, PFS))
  5897. return true;
  5898. // If RetType is a non-function pointer type, then this is the short syntax
  5899. // for the call, which means that RetType is just the return type. Infer the
  5900. // rest of the function argument types from the arguments that are present.
  5901. FunctionType *Ty;
  5902. if (resolveFunctionType(RetType, ArgList, Ty))
  5903. return error(RetTypeLoc, "Invalid result type for LLVM function");
  5904. CalleeID.FTy = Ty;
  5905. // Look up the callee.
  5906. Value *Callee;
  5907. if (convertValIDToValue(PointerType::get(Ty, InvokeAddrSpace), CalleeID,
  5908. Callee, &PFS))
  5909. return true;
  5910. // Set up the Attribute for the function.
  5911. SmallVector<Value *, 8> Args;
  5912. SmallVector<AttributeSet, 8> ArgAttrs;
  5913. // Loop through FunctionType's arguments and ensure they are specified
  5914. // correctly. Also, gather any parameter attributes.
  5915. FunctionType::param_iterator I = Ty->param_begin();
  5916. FunctionType::param_iterator E = Ty->param_end();
  5917. for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
  5918. Type *ExpectedTy = nullptr;
  5919. if (I != E) {
  5920. ExpectedTy = *I++;
  5921. } else if (!Ty->isVarArg()) {
  5922. return error(ArgList[i].Loc, "too many arguments specified");
  5923. }
  5924. if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
  5925. return error(ArgList[i].Loc, "argument is not of expected type '" +
  5926. getTypeString(ExpectedTy) + "'");
  5927. Args.push_back(ArgList[i].V);
  5928. ArgAttrs.push_back(ArgList[i].Attrs);
  5929. }
  5930. if (I != E)
  5931. return error(CallLoc, "not enough parameters specified for call");
  5932. // Finish off the Attribute and check them
  5933. AttributeList PAL =
  5934. AttributeList::get(Context, AttributeSet::get(Context, FnAttrs),
  5935. AttributeSet::get(Context, RetAttrs), ArgAttrs);
  5936. InvokeInst *II =
  5937. InvokeInst::Create(Ty, Callee, NormalBB, UnwindBB, Args, BundleList);
  5938. II->setCallingConv(CC);
  5939. II->setAttributes(PAL);
  5940. ForwardRefAttrGroups[II] = FwdRefAttrGrps;
  5941. Inst = II;
  5942. return false;
  5943. }
  5944. /// parseResume
  5945. /// ::= 'resume' TypeAndValue
  5946. bool LLParser::parseResume(Instruction *&Inst, PerFunctionState &PFS) {
  5947. Value *Exn; LocTy ExnLoc;
  5948. if (parseTypeAndValue(Exn, ExnLoc, PFS))
  5949. return true;
  5950. ResumeInst *RI = ResumeInst::Create(Exn);
  5951. Inst = RI;
  5952. return false;
  5953. }
  5954. bool LLParser::parseExceptionArgs(SmallVectorImpl<Value *> &Args,
  5955. PerFunctionState &PFS) {
  5956. if (parseToken(lltok::lsquare, "expected '[' in catchpad/cleanuppad"))
  5957. return true;
  5958. while (Lex.getKind() != lltok::rsquare) {
  5959. // If this isn't the first argument, we need a comma.
  5960. if (!Args.empty() &&
  5961. parseToken(lltok::comma, "expected ',' in argument list"))
  5962. return true;
  5963. // parse the argument.
  5964. LocTy ArgLoc;
  5965. Type *ArgTy = nullptr;
  5966. if (parseType(ArgTy, ArgLoc))
  5967. return true;
  5968. Value *V;
  5969. if (ArgTy->isMetadataTy()) {
  5970. if (parseMetadataAsValue(V, PFS))
  5971. return true;
  5972. } else {
  5973. if (parseValue(ArgTy, V, PFS))
  5974. return true;
  5975. }
  5976. Args.push_back(V);
  5977. }
  5978. Lex.Lex(); // Lex the ']'.
  5979. return false;
  5980. }
  5981. /// parseCleanupRet
  5982. /// ::= 'cleanupret' from Value unwind ('to' 'caller' | TypeAndValue)
  5983. bool LLParser::parseCleanupRet(Instruction *&Inst, PerFunctionState &PFS) {
  5984. Value *CleanupPad = nullptr;
  5985. if (parseToken(lltok::kw_from, "expected 'from' after cleanupret"))
  5986. return true;
  5987. if (parseValue(Type::getTokenTy(Context), CleanupPad, PFS))
  5988. return true;
  5989. if (parseToken(lltok::kw_unwind, "expected 'unwind' in cleanupret"))
  5990. return true;
  5991. BasicBlock *UnwindBB = nullptr;
  5992. if (Lex.getKind() == lltok::kw_to) {
  5993. Lex.Lex();
  5994. if (parseToken(lltok::kw_caller, "expected 'caller' in cleanupret"))
  5995. return true;
  5996. } else {
  5997. if (parseTypeAndBasicBlock(UnwindBB, PFS)) {
  5998. return true;
  5999. }
  6000. }
  6001. Inst = CleanupReturnInst::Create(CleanupPad, UnwindBB);
  6002. return false;
  6003. }
  6004. /// parseCatchRet
  6005. /// ::= 'catchret' from Parent Value 'to' TypeAndValue
  6006. bool LLParser::parseCatchRet(Instruction *&Inst, PerFunctionState &PFS) {
  6007. Value *CatchPad = nullptr;
  6008. if (parseToken(lltok::kw_from, "expected 'from' after catchret"))
  6009. return true;
  6010. if (parseValue(Type::getTokenTy(Context), CatchPad, PFS))
  6011. return true;
  6012. BasicBlock *BB;
  6013. if (parseToken(lltok::kw_to, "expected 'to' in catchret") ||
  6014. parseTypeAndBasicBlock(BB, PFS))
  6015. return true;
  6016. Inst = CatchReturnInst::Create(CatchPad, BB);
  6017. return false;
  6018. }
  6019. /// parseCatchSwitch
  6020. /// ::= 'catchswitch' within Parent
  6021. bool LLParser::parseCatchSwitch(Instruction *&Inst, PerFunctionState &PFS) {
  6022. Value *ParentPad;
  6023. if (parseToken(lltok::kw_within, "expected 'within' after catchswitch"))
  6024. return true;
  6025. if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar &&
  6026. Lex.getKind() != lltok::LocalVarID)
  6027. return tokError("expected scope value for catchswitch");
  6028. if (parseValue(Type::getTokenTy(Context), ParentPad, PFS))
  6029. return true;
  6030. if (parseToken(lltok::lsquare, "expected '[' with catchswitch labels"))
  6031. return true;
  6032. SmallVector<BasicBlock *, 32> Table;
  6033. do {
  6034. BasicBlock *DestBB;
  6035. if (parseTypeAndBasicBlock(DestBB, PFS))
  6036. return true;
  6037. Table.push_back(DestBB);
  6038. } while (EatIfPresent(lltok::comma));
  6039. if (parseToken(lltok::rsquare, "expected ']' after catchswitch labels"))
  6040. return true;
  6041. if (parseToken(lltok::kw_unwind, "expected 'unwind' after catchswitch scope"))
  6042. return true;
  6043. BasicBlock *UnwindBB = nullptr;
  6044. if (EatIfPresent(lltok::kw_to)) {
  6045. if (parseToken(lltok::kw_caller, "expected 'caller' in catchswitch"))
  6046. return true;
  6047. } else {
  6048. if (parseTypeAndBasicBlock(UnwindBB, PFS))
  6049. return true;
  6050. }
  6051. auto *CatchSwitch =
  6052. CatchSwitchInst::Create(ParentPad, UnwindBB, Table.size());
  6053. for (BasicBlock *DestBB : Table)
  6054. CatchSwitch->addHandler(DestBB);
  6055. Inst = CatchSwitch;
  6056. return false;
  6057. }
  6058. /// parseCatchPad
  6059. /// ::= 'catchpad' ParamList 'to' TypeAndValue 'unwind' TypeAndValue
  6060. bool LLParser::parseCatchPad(Instruction *&Inst, PerFunctionState &PFS) {
  6061. Value *CatchSwitch = nullptr;
  6062. if (parseToken(lltok::kw_within, "expected 'within' after catchpad"))
  6063. return true;
  6064. if (Lex.getKind() != lltok::LocalVar && Lex.getKind() != lltok::LocalVarID)
  6065. return tokError("expected scope value for catchpad");
  6066. if (parseValue(Type::getTokenTy(Context), CatchSwitch, PFS))
  6067. return true;
  6068. SmallVector<Value *, 8> Args;
  6069. if (parseExceptionArgs(Args, PFS))
  6070. return true;
  6071. Inst = CatchPadInst::Create(CatchSwitch, Args);
  6072. return false;
  6073. }
  6074. /// parseCleanupPad
  6075. /// ::= 'cleanuppad' within Parent ParamList
  6076. bool LLParser::parseCleanupPad(Instruction *&Inst, PerFunctionState &PFS) {
  6077. Value *ParentPad = nullptr;
  6078. if (parseToken(lltok::kw_within, "expected 'within' after cleanuppad"))
  6079. return true;
  6080. if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar &&
  6081. Lex.getKind() != lltok::LocalVarID)
  6082. return tokError("expected scope value for cleanuppad");
  6083. if (parseValue(Type::getTokenTy(Context), ParentPad, PFS))
  6084. return true;
  6085. SmallVector<Value *, 8> Args;
  6086. if (parseExceptionArgs(Args, PFS))
  6087. return true;
  6088. Inst = CleanupPadInst::Create(ParentPad, Args);
  6089. return false;
  6090. }
  6091. //===----------------------------------------------------------------------===//
  6092. // Unary Operators.
  6093. //===----------------------------------------------------------------------===//
  6094. /// parseUnaryOp
  6095. /// ::= UnaryOp TypeAndValue ',' Value
  6096. ///
  6097. /// If IsFP is false, then any integer operand is allowed, if it is true, any fp
  6098. /// operand is allowed.
  6099. bool LLParser::parseUnaryOp(Instruction *&Inst, PerFunctionState &PFS,
  6100. unsigned Opc, bool IsFP) {
  6101. LocTy Loc; Value *LHS;
  6102. if (parseTypeAndValue(LHS, Loc, PFS))
  6103. return true;
  6104. bool Valid = IsFP ? LHS->getType()->isFPOrFPVectorTy()
  6105. : LHS->getType()->isIntOrIntVectorTy();
  6106. if (!Valid)
  6107. return error(Loc, "invalid operand type for instruction");
  6108. Inst = UnaryOperator::Create((Instruction::UnaryOps)Opc, LHS);
  6109. return false;
  6110. }
  6111. /// parseCallBr
  6112. /// ::= 'callbr' OptionalCallingConv OptionalAttrs Type Value ParamList
  6113. /// OptionalAttrs OptionalOperandBundles 'to' TypeAndValue
  6114. /// '[' LabelList ']'
  6115. bool LLParser::parseCallBr(Instruction *&Inst, PerFunctionState &PFS) {
  6116. LocTy CallLoc = Lex.getLoc();
  6117. AttrBuilder RetAttrs(M->getContext()), FnAttrs(M->getContext());
  6118. std::vector<unsigned> FwdRefAttrGrps;
  6119. LocTy NoBuiltinLoc;
  6120. unsigned CC;
  6121. Type *RetType = nullptr;
  6122. LocTy RetTypeLoc;
  6123. ValID CalleeID;
  6124. SmallVector<ParamInfo, 16> ArgList;
  6125. SmallVector<OperandBundleDef, 2> BundleList;
  6126. BasicBlock *DefaultDest;
  6127. if (parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
  6128. parseType(RetType, RetTypeLoc, true /*void allowed*/) ||
  6129. parseValID(CalleeID, &PFS) || parseParameterList(ArgList, PFS) ||
  6130. parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
  6131. NoBuiltinLoc) ||
  6132. parseOptionalOperandBundles(BundleList, PFS) ||
  6133. parseToken(lltok::kw_to, "expected 'to' in callbr") ||
  6134. parseTypeAndBasicBlock(DefaultDest, PFS) ||
  6135. parseToken(lltok::lsquare, "expected '[' in callbr"))
  6136. return true;
  6137. // parse the destination list.
  6138. SmallVector<BasicBlock *, 16> IndirectDests;
  6139. if (Lex.getKind() != lltok::rsquare) {
  6140. BasicBlock *DestBB;
  6141. if (parseTypeAndBasicBlock(DestBB, PFS))
  6142. return true;
  6143. IndirectDests.push_back(DestBB);
  6144. while (EatIfPresent(lltok::comma)) {
  6145. if (parseTypeAndBasicBlock(DestBB, PFS))
  6146. return true;
  6147. IndirectDests.push_back(DestBB);
  6148. }
  6149. }
  6150. if (parseToken(lltok::rsquare, "expected ']' at end of block list"))
  6151. return true;
  6152. // If RetType is a non-function pointer type, then this is the short syntax
  6153. // for the call, which means that RetType is just the return type. Infer the
  6154. // rest of the function argument types from the arguments that are present.
  6155. FunctionType *Ty;
  6156. if (resolveFunctionType(RetType, ArgList, Ty))
  6157. return error(RetTypeLoc, "Invalid result type for LLVM function");
  6158. CalleeID.FTy = Ty;
  6159. // Look up the callee.
  6160. Value *Callee;
  6161. if (convertValIDToValue(PointerType::getUnqual(Ty), CalleeID, Callee, &PFS))
  6162. return true;
  6163. // Set up the Attribute for the function.
  6164. SmallVector<Value *, 8> Args;
  6165. SmallVector<AttributeSet, 8> ArgAttrs;
  6166. // Loop through FunctionType's arguments and ensure they are specified
  6167. // correctly. Also, gather any parameter attributes.
  6168. FunctionType::param_iterator I = Ty->param_begin();
  6169. FunctionType::param_iterator E = Ty->param_end();
  6170. for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
  6171. Type *ExpectedTy = nullptr;
  6172. if (I != E) {
  6173. ExpectedTy = *I++;
  6174. } else if (!Ty->isVarArg()) {
  6175. return error(ArgList[i].Loc, "too many arguments specified");
  6176. }
  6177. if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
  6178. return error(ArgList[i].Loc, "argument is not of expected type '" +
  6179. getTypeString(ExpectedTy) + "'");
  6180. Args.push_back(ArgList[i].V);
  6181. ArgAttrs.push_back(ArgList[i].Attrs);
  6182. }
  6183. if (I != E)
  6184. return error(CallLoc, "not enough parameters specified for call");
  6185. // Finish off the Attribute and check them
  6186. AttributeList PAL =
  6187. AttributeList::get(Context, AttributeSet::get(Context, FnAttrs),
  6188. AttributeSet::get(Context, RetAttrs), ArgAttrs);
  6189. CallBrInst *CBI =
  6190. CallBrInst::Create(Ty, Callee, DefaultDest, IndirectDests, Args,
  6191. BundleList);
  6192. CBI->setCallingConv(CC);
  6193. CBI->setAttributes(PAL);
  6194. ForwardRefAttrGroups[CBI] = FwdRefAttrGrps;
  6195. Inst = CBI;
  6196. return false;
  6197. }
  6198. //===----------------------------------------------------------------------===//
  6199. // Binary Operators.
  6200. //===----------------------------------------------------------------------===//
  6201. /// parseArithmetic
  6202. /// ::= ArithmeticOps TypeAndValue ',' Value
  6203. ///
  6204. /// If IsFP is false, then any integer operand is allowed, if it is true, any fp
  6205. /// operand is allowed.
  6206. bool LLParser::parseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
  6207. unsigned Opc, bool IsFP) {
  6208. LocTy Loc; Value *LHS, *RHS;
  6209. if (parseTypeAndValue(LHS, Loc, PFS) ||
  6210. parseToken(lltok::comma, "expected ',' in arithmetic operation") ||
  6211. parseValue(LHS->getType(), RHS, PFS))
  6212. return true;
  6213. bool Valid = IsFP ? LHS->getType()->isFPOrFPVectorTy()
  6214. : LHS->getType()->isIntOrIntVectorTy();
  6215. if (!Valid)
  6216. return error(Loc, "invalid operand type for instruction");
  6217. Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
  6218. return false;
  6219. }
  6220. /// parseLogical
  6221. /// ::= ArithmeticOps TypeAndValue ',' Value {
  6222. bool LLParser::parseLogical(Instruction *&Inst, PerFunctionState &PFS,
  6223. unsigned Opc) {
  6224. LocTy Loc; Value *LHS, *RHS;
  6225. if (parseTypeAndValue(LHS, Loc, PFS) ||
  6226. parseToken(lltok::comma, "expected ',' in logical operation") ||
  6227. parseValue(LHS->getType(), RHS, PFS))
  6228. return true;
  6229. if (!LHS->getType()->isIntOrIntVectorTy())
  6230. return error(Loc,
  6231. "instruction requires integer or integer vector operands");
  6232. Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
  6233. return false;
  6234. }
  6235. /// parseCompare
  6236. /// ::= 'icmp' IPredicates TypeAndValue ',' Value
  6237. /// ::= 'fcmp' FPredicates TypeAndValue ',' Value
  6238. bool LLParser::parseCompare(Instruction *&Inst, PerFunctionState &PFS,
  6239. unsigned Opc) {
  6240. // parse the integer/fp comparison predicate.
  6241. LocTy Loc;
  6242. unsigned Pred;
  6243. Value *LHS, *RHS;
  6244. if (parseCmpPredicate(Pred, Opc) || parseTypeAndValue(LHS, Loc, PFS) ||
  6245. parseToken(lltok::comma, "expected ',' after compare value") ||
  6246. parseValue(LHS->getType(), RHS, PFS))
  6247. return true;
  6248. if (Opc == Instruction::FCmp) {
  6249. if (!LHS->getType()->isFPOrFPVectorTy())
  6250. return error(Loc, "fcmp requires floating point operands");
  6251. Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
  6252. } else {
  6253. assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
  6254. if (!LHS->getType()->isIntOrIntVectorTy() &&
  6255. !LHS->getType()->isPtrOrPtrVectorTy())
  6256. return error(Loc, "icmp requires integer operands");
  6257. Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
  6258. }
  6259. return false;
  6260. }
  6261. //===----------------------------------------------------------------------===//
  6262. // Other Instructions.
  6263. //===----------------------------------------------------------------------===//
  6264. /// parseCast
  6265. /// ::= CastOpc TypeAndValue 'to' Type
  6266. bool LLParser::parseCast(Instruction *&Inst, PerFunctionState &PFS,
  6267. unsigned Opc) {
  6268. LocTy Loc;
  6269. Value *Op;
  6270. Type *DestTy = nullptr;
  6271. if (parseTypeAndValue(Op, Loc, PFS) ||
  6272. parseToken(lltok::kw_to, "expected 'to' after cast value") ||
  6273. parseType(DestTy))
  6274. return true;
  6275. if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
  6276. CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
  6277. return error(Loc, "invalid cast opcode for cast from '" +
  6278. getTypeString(Op->getType()) + "' to '" +
  6279. getTypeString(DestTy) + "'");
  6280. }
  6281. Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
  6282. return false;
  6283. }
  6284. /// parseSelect
  6285. /// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
  6286. bool LLParser::parseSelect(Instruction *&Inst, PerFunctionState &PFS) {
  6287. LocTy Loc;
  6288. Value *Op0, *Op1, *Op2;
  6289. if (parseTypeAndValue(Op0, Loc, PFS) ||
  6290. parseToken(lltok::comma, "expected ',' after select condition") ||
  6291. parseTypeAndValue(Op1, PFS) ||
  6292. parseToken(lltok::comma, "expected ',' after select value") ||
  6293. parseTypeAndValue(Op2, PFS))
  6294. return true;
  6295. if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
  6296. return error(Loc, Reason);
  6297. Inst = SelectInst::Create(Op0, Op1, Op2);
  6298. return false;
  6299. }
  6300. /// parseVAArg
  6301. /// ::= 'va_arg' TypeAndValue ',' Type
  6302. bool LLParser::parseVAArg(Instruction *&Inst, PerFunctionState &PFS) {
  6303. Value *Op;
  6304. Type *EltTy = nullptr;
  6305. LocTy TypeLoc;
  6306. if (parseTypeAndValue(Op, PFS) ||
  6307. parseToken(lltok::comma, "expected ',' after vaarg operand") ||
  6308. parseType(EltTy, TypeLoc))
  6309. return true;
  6310. if (!EltTy->isFirstClassType())
  6311. return error(TypeLoc, "va_arg requires operand with first class type");
  6312. Inst = new VAArgInst(Op, EltTy);
  6313. return false;
  6314. }
  6315. /// parseExtractElement
  6316. /// ::= 'extractelement' TypeAndValue ',' TypeAndValue
  6317. bool LLParser::parseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
  6318. LocTy Loc;
  6319. Value *Op0, *Op1;
  6320. if (parseTypeAndValue(Op0, Loc, PFS) ||
  6321. parseToken(lltok::comma, "expected ',' after extract value") ||
  6322. parseTypeAndValue(Op1, PFS))
  6323. return true;
  6324. if (!ExtractElementInst::isValidOperands(Op0, Op1))
  6325. return error(Loc, "invalid extractelement operands");
  6326. Inst = ExtractElementInst::Create(Op0, Op1);
  6327. return false;
  6328. }
  6329. /// parseInsertElement
  6330. /// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
  6331. bool LLParser::parseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
  6332. LocTy Loc;
  6333. Value *Op0, *Op1, *Op2;
  6334. if (parseTypeAndValue(Op0, Loc, PFS) ||
  6335. parseToken(lltok::comma, "expected ',' after insertelement value") ||
  6336. parseTypeAndValue(Op1, PFS) ||
  6337. parseToken(lltok::comma, "expected ',' after insertelement value") ||
  6338. parseTypeAndValue(Op2, PFS))
  6339. return true;
  6340. if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
  6341. return error(Loc, "invalid insertelement operands");
  6342. Inst = InsertElementInst::Create(Op0, Op1, Op2);
  6343. return false;
  6344. }
  6345. /// parseShuffleVector
  6346. /// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
  6347. bool LLParser::parseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
  6348. LocTy Loc;
  6349. Value *Op0, *Op1, *Op2;
  6350. if (parseTypeAndValue(Op0, Loc, PFS) ||
  6351. parseToken(lltok::comma, "expected ',' after shuffle mask") ||
  6352. parseTypeAndValue(Op1, PFS) ||
  6353. parseToken(lltok::comma, "expected ',' after shuffle value") ||
  6354. parseTypeAndValue(Op2, PFS))
  6355. return true;
  6356. if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
  6357. return error(Loc, "invalid shufflevector operands");
  6358. Inst = new ShuffleVectorInst(Op0, Op1, Op2);
  6359. return false;
  6360. }
  6361. /// parsePHI
  6362. /// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
  6363. int LLParser::parsePHI(Instruction *&Inst, PerFunctionState &PFS) {
  6364. Type *Ty = nullptr; LocTy TypeLoc;
  6365. Value *Op0, *Op1;
  6366. if (parseType(Ty, TypeLoc))
  6367. return true;
  6368. if (!Ty->isFirstClassType())
  6369. return error(TypeLoc, "phi node must have first class type");
  6370. bool First = true;
  6371. bool AteExtraComma = false;
  6372. SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
  6373. while (true) {
  6374. if (First) {
  6375. if (Lex.getKind() != lltok::lsquare)
  6376. break;
  6377. First = false;
  6378. } else if (!EatIfPresent(lltok::comma))
  6379. break;
  6380. if (Lex.getKind() == lltok::MetadataVar) {
  6381. AteExtraComma = true;
  6382. break;
  6383. }
  6384. if (parseToken(lltok::lsquare, "expected '[' in phi value list") ||
  6385. parseValue(Ty, Op0, PFS) ||
  6386. parseToken(lltok::comma, "expected ',' after insertelement value") ||
  6387. parseValue(Type::getLabelTy(Context), Op1, PFS) ||
  6388. parseToken(lltok::rsquare, "expected ']' in phi value list"))
  6389. return true;
  6390. PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
  6391. }
  6392. PHINode *PN = PHINode::Create(Ty, PHIVals.size());
  6393. for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
  6394. PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
  6395. Inst = PN;
  6396. return AteExtraComma ? InstExtraComma : InstNormal;
  6397. }
  6398. /// parseLandingPad
  6399. /// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
  6400. /// Clause
  6401. /// ::= 'catch' TypeAndValue
  6402. /// ::= 'filter'
  6403. /// ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
  6404. bool LLParser::parseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
  6405. Type *Ty = nullptr; LocTy TyLoc;
  6406. if (parseType(Ty, TyLoc))
  6407. return true;
  6408. std::unique_ptr<LandingPadInst> LP(LandingPadInst::Create(Ty, 0));
  6409. LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
  6410. while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
  6411. LandingPadInst::ClauseType CT;
  6412. if (EatIfPresent(lltok::kw_catch))
  6413. CT = LandingPadInst::Catch;
  6414. else if (EatIfPresent(lltok::kw_filter))
  6415. CT = LandingPadInst::Filter;
  6416. else
  6417. return tokError("expected 'catch' or 'filter' clause type");
  6418. Value *V;
  6419. LocTy VLoc;
  6420. if (parseTypeAndValue(V, VLoc, PFS))
  6421. return true;
  6422. // A 'catch' type expects a non-array constant. A filter clause expects an
  6423. // array constant.
  6424. if (CT == LandingPadInst::Catch) {
  6425. if (isa<ArrayType>(V->getType()))
  6426. error(VLoc, "'catch' clause has an invalid type");
  6427. } else {
  6428. if (!isa<ArrayType>(V->getType()))
  6429. error(VLoc, "'filter' clause has an invalid type");
  6430. }
  6431. Constant *CV = dyn_cast<Constant>(V);
  6432. if (!CV)
  6433. return error(VLoc, "clause argument must be a constant");
  6434. LP->addClause(CV);
  6435. }
  6436. Inst = LP.release();
  6437. return false;
  6438. }
  6439. /// parseFreeze
  6440. /// ::= 'freeze' Type Value
  6441. bool LLParser::parseFreeze(Instruction *&Inst, PerFunctionState &PFS) {
  6442. LocTy Loc;
  6443. Value *Op;
  6444. if (parseTypeAndValue(Op, Loc, PFS))
  6445. return true;
  6446. Inst = new FreezeInst(Op);
  6447. return false;
  6448. }
  6449. /// parseCall
  6450. /// ::= 'call' OptionalFastMathFlags OptionalCallingConv
  6451. /// OptionalAttrs Type Value ParameterList OptionalAttrs
  6452. /// ::= 'tail' 'call' OptionalFastMathFlags OptionalCallingConv
  6453. /// OptionalAttrs Type Value ParameterList OptionalAttrs
  6454. /// ::= 'musttail' 'call' OptionalFastMathFlags OptionalCallingConv
  6455. /// OptionalAttrs Type Value ParameterList OptionalAttrs
  6456. /// ::= 'notail' 'call' OptionalFastMathFlags OptionalCallingConv
  6457. /// OptionalAttrs Type Value ParameterList OptionalAttrs
  6458. bool LLParser::parseCall(Instruction *&Inst, PerFunctionState &PFS,
  6459. CallInst::TailCallKind TCK) {
  6460. AttrBuilder RetAttrs(M->getContext()), FnAttrs(M->getContext());
  6461. std::vector<unsigned> FwdRefAttrGrps;
  6462. LocTy BuiltinLoc;
  6463. unsigned CallAddrSpace;
  6464. unsigned CC;
  6465. Type *RetType = nullptr;
  6466. LocTy RetTypeLoc;
  6467. ValID CalleeID;
  6468. SmallVector<ParamInfo, 16> ArgList;
  6469. SmallVector<OperandBundleDef, 2> BundleList;
  6470. LocTy CallLoc = Lex.getLoc();
  6471. if (TCK != CallInst::TCK_None &&
  6472. parseToken(lltok::kw_call,
  6473. "expected 'tail call', 'musttail call', or 'notail call'"))
  6474. return true;
  6475. FastMathFlags FMF = EatFastMathFlagsIfPresent();
  6476. if (parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
  6477. parseOptionalProgramAddrSpace(CallAddrSpace) ||
  6478. parseType(RetType, RetTypeLoc, true /*void allowed*/) ||
  6479. parseValID(CalleeID, &PFS) ||
  6480. parseParameterList(ArgList, PFS, TCK == CallInst::TCK_MustTail,
  6481. PFS.getFunction().isVarArg()) ||
  6482. parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false, BuiltinLoc) ||
  6483. parseOptionalOperandBundles(BundleList, PFS))
  6484. return true;
  6485. // If RetType is a non-function pointer type, then this is the short syntax
  6486. // for the call, which means that RetType is just the return type. Infer the
  6487. // rest of the function argument types from the arguments that are present.
  6488. FunctionType *Ty;
  6489. if (resolveFunctionType(RetType, ArgList, Ty))
  6490. return error(RetTypeLoc, "Invalid result type for LLVM function");
  6491. CalleeID.FTy = Ty;
  6492. // Look up the callee.
  6493. Value *Callee;
  6494. if (convertValIDToValue(PointerType::get(Ty, CallAddrSpace), CalleeID, Callee,
  6495. &PFS))
  6496. return true;
  6497. // Set up the Attribute for the function.
  6498. SmallVector<AttributeSet, 8> Attrs;
  6499. SmallVector<Value*, 8> Args;
  6500. // Loop through FunctionType's arguments and ensure they are specified
  6501. // correctly. Also, gather any parameter attributes.
  6502. FunctionType::param_iterator I = Ty->param_begin();
  6503. FunctionType::param_iterator E = Ty->param_end();
  6504. for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
  6505. Type *ExpectedTy = nullptr;
  6506. if (I != E) {
  6507. ExpectedTy = *I++;
  6508. } else if (!Ty->isVarArg()) {
  6509. return error(ArgList[i].Loc, "too many arguments specified");
  6510. }
  6511. if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
  6512. return error(ArgList[i].Loc, "argument is not of expected type '" +
  6513. getTypeString(ExpectedTy) + "'");
  6514. Args.push_back(ArgList[i].V);
  6515. Attrs.push_back(ArgList[i].Attrs);
  6516. }
  6517. if (I != E)
  6518. return error(CallLoc, "not enough parameters specified for call");
  6519. // Finish off the Attribute and check them
  6520. AttributeList PAL =
  6521. AttributeList::get(Context, AttributeSet::get(Context, FnAttrs),
  6522. AttributeSet::get(Context, RetAttrs), Attrs);
  6523. CallInst *CI = CallInst::Create(Ty, Callee, Args, BundleList);
  6524. CI->setTailCallKind(TCK);
  6525. CI->setCallingConv(CC);
  6526. if (FMF.any()) {
  6527. if (!isa<FPMathOperator>(CI)) {
  6528. CI->deleteValue();
  6529. return error(CallLoc, "fast-math-flags specified for call without "
  6530. "floating-point scalar or vector return type");
  6531. }
  6532. CI->setFastMathFlags(FMF);
  6533. }
  6534. CI->setAttributes(PAL);
  6535. ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
  6536. Inst = CI;
  6537. return false;
  6538. }
  6539. //===----------------------------------------------------------------------===//
  6540. // Memory Instructions.
  6541. //===----------------------------------------------------------------------===//
  6542. /// parseAlloc
  6543. /// ::= 'alloca' 'inalloca'? 'swifterror'? Type (',' TypeAndValue)?
  6544. /// (',' 'align' i32)? (',', 'addrspace(n))?
  6545. int LLParser::parseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
  6546. Value *Size = nullptr;
  6547. LocTy SizeLoc, TyLoc, ASLoc;
  6548. MaybeAlign Alignment;
  6549. unsigned AddrSpace = 0;
  6550. Type *Ty = nullptr;
  6551. bool IsInAlloca = EatIfPresent(lltok::kw_inalloca);
  6552. bool IsSwiftError = EatIfPresent(lltok::kw_swifterror);
  6553. if (parseType(Ty, TyLoc))
  6554. return true;
  6555. if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))
  6556. return error(TyLoc, "invalid type for alloca");
  6557. bool AteExtraComma = false;
  6558. if (EatIfPresent(lltok::comma)) {
  6559. if (Lex.getKind() == lltok::kw_align) {
  6560. if (parseOptionalAlignment(Alignment))
  6561. return true;
  6562. if (parseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma))
  6563. return true;
  6564. } else if (Lex.getKind() == lltok::kw_addrspace) {
  6565. ASLoc = Lex.getLoc();
  6566. if (parseOptionalAddrSpace(AddrSpace))
  6567. return true;
  6568. } else if (Lex.getKind() == lltok::MetadataVar) {
  6569. AteExtraComma = true;
  6570. } else {
  6571. if (parseTypeAndValue(Size, SizeLoc, PFS))
  6572. return true;
  6573. if (EatIfPresent(lltok::comma)) {
  6574. if (Lex.getKind() == lltok::kw_align) {
  6575. if (parseOptionalAlignment(Alignment))
  6576. return true;
  6577. if (parseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma))
  6578. return true;
  6579. } else if (Lex.getKind() == lltok::kw_addrspace) {
  6580. ASLoc = Lex.getLoc();
  6581. if (parseOptionalAddrSpace(AddrSpace))
  6582. return true;
  6583. } else if (Lex.getKind() == lltok::MetadataVar) {
  6584. AteExtraComma = true;
  6585. }
  6586. }
  6587. }
  6588. }
  6589. if (Size && !Size->getType()->isIntegerTy())
  6590. return error(SizeLoc, "element count must have integer type");
  6591. SmallPtrSet<Type *, 4> Visited;
  6592. if (!Alignment && !Ty->isSized(&Visited))
  6593. return error(TyLoc, "Cannot allocate unsized type");
  6594. if (!Alignment)
  6595. Alignment = M->getDataLayout().getPrefTypeAlign(Ty);
  6596. AllocaInst *AI = new AllocaInst(Ty, AddrSpace, Size, *Alignment);
  6597. AI->setUsedWithInAlloca(IsInAlloca);
  6598. AI->setSwiftError(IsSwiftError);
  6599. Inst = AI;
  6600. return AteExtraComma ? InstExtraComma : InstNormal;
  6601. }
  6602. /// parseLoad
  6603. /// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
  6604. /// ::= 'load' 'atomic' 'volatile'? TypeAndValue
  6605. /// 'singlethread'? AtomicOrdering (',' 'align' i32)?
  6606. int LLParser::parseLoad(Instruction *&Inst, PerFunctionState &PFS) {
  6607. Value *Val; LocTy Loc;
  6608. MaybeAlign Alignment;
  6609. bool AteExtraComma = false;
  6610. bool isAtomic = false;
  6611. AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
  6612. SyncScope::ID SSID = SyncScope::System;
  6613. if (Lex.getKind() == lltok::kw_atomic) {
  6614. isAtomic = true;
  6615. Lex.Lex();
  6616. }
  6617. bool isVolatile = false;
  6618. if (Lex.getKind() == lltok::kw_volatile) {
  6619. isVolatile = true;
  6620. Lex.Lex();
  6621. }
  6622. Type *Ty;
  6623. LocTy ExplicitTypeLoc = Lex.getLoc();
  6624. if (parseType(Ty) ||
  6625. parseToken(lltok::comma, "expected comma after load's type") ||
  6626. parseTypeAndValue(Val, Loc, PFS) ||
  6627. parseScopeAndOrdering(isAtomic, SSID, Ordering) ||
  6628. parseOptionalCommaAlign(Alignment, AteExtraComma))
  6629. return true;
  6630. if (!Val->getType()->isPointerTy() || !Ty->isFirstClassType())
  6631. return error(Loc, "load operand must be a pointer to a first class type");
  6632. if (isAtomic && !Alignment)
  6633. return error(Loc, "atomic load must have explicit non-zero alignment");
  6634. if (Ordering == AtomicOrdering::Release ||
  6635. Ordering == AtomicOrdering::AcquireRelease)
  6636. return error(Loc, "atomic load cannot use Release ordering");
  6637. if (!cast<PointerType>(Val->getType())->isOpaqueOrPointeeTypeMatches(Ty)) {
  6638. return error(
  6639. ExplicitTypeLoc,
  6640. typeComparisonErrorMessage(
  6641. "explicit pointee type doesn't match operand's pointee type", Ty,
  6642. Val->getType()->getNonOpaquePointerElementType()));
  6643. }
  6644. SmallPtrSet<Type *, 4> Visited;
  6645. if (!Alignment && !Ty->isSized(&Visited))
  6646. return error(ExplicitTypeLoc, "loading unsized types is not allowed");
  6647. if (!Alignment)
  6648. Alignment = M->getDataLayout().getABITypeAlign(Ty);
  6649. Inst = new LoadInst(Ty, Val, "", isVolatile, *Alignment, Ordering, SSID);
  6650. return AteExtraComma ? InstExtraComma : InstNormal;
  6651. }
  6652. /// parseStore
  6653. /// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
  6654. /// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
  6655. /// 'singlethread'? AtomicOrdering (',' 'align' i32)?
  6656. int LLParser::parseStore(Instruction *&Inst, PerFunctionState &PFS) {
  6657. Value *Val, *Ptr; LocTy Loc, PtrLoc;
  6658. MaybeAlign Alignment;
  6659. bool AteExtraComma = false;
  6660. bool isAtomic = false;
  6661. AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
  6662. SyncScope::ID SSID = SyncScope::System;
  6663. if (Lex.getKind() == lltok::kw_atomic) {
  6664. isAtomic = true;
  6665. Lex.Lex();
  6666. }
  6667. bool isVolatile = false;
  6668. if (Lex.getKind() == lltok::kw_volatile) {
  6669. isVolatile = true;
  6670. Lex.Lex();
  6671. }
  6672. if (parseTypeAndValue(Val, Loc, PFS) ||
  6673. parseToken(lltok::comma, "expected ',' after store operand") ||
  6674. parseTypeAndValue(Ptr, PtrLoc, PFS) ||
  6675. parseScopeAndOrdering(isAtomic, SSID, Ordering) ||
  6676. parseOptionalCommaAlign(Alignment, AteExtraComma))
  6677. return true;
  6678. if (!Ptr->getType()->isPointerTy())
  6679. return error(PtrLoc, "store operand must be a pointer");
  6680. if (!Val->getType()->isFirstClassType())
  6681. return error(Loc, "store operand must be a first class value");
  6682. if (!cast<PointerType>(Ptr->getType())
  6683. ->isOpaqueOrPointeeTypeMatches(Val->getType()))
  6684. return error(Loc, "stored value and pointer type do not match");
  6685. if (isAtomic && !Alignment)
  6686. return error(Loc, "atomic store must have explicit non-zero alignment");
  6687. if (Ordering == AtomicOrdering::Acquire ||
  6688. Ordering == AtomicOrdering::AcquireRelease)
  6689. return error(Loc, "atomic store cannot use Acquire ordering");
  6690. SmallPtrSet<Type *, 4> Visited;
  6691. if (!Alignment && !Val->getType()->isSized(&Visited))
  6692. return error(Loc, "storing unsized types is not allowed");
  6693. if (!Alignment)
  6694. Alignment = M->getDataLayout().getABITypeAlign(Val->getType());
  6695. Inst = new StoreInst(Val, Ptr, isVolatile, *Alignment, Ordering, SSID);
  6696. return AteExtraComma ? InstExtraComma : InstNormal;
  6697. }
  6698. /// parseCmpXchg
  6699. /// ::= 'cmpxchg' 'weak'? 'volatile'? TypeAndValue ',' TypeAndValue ','
  6700. /// TypeAndValue 'singlethread'? AtomicOrdering AtomicOrdering ','
  6701. /// 'Align'?
  6702. int LLParser::parseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
  6703. Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
  6704. bool AteExtraComma = false;
  6705. AtomicOrdering SuccessOrdering = AtomicOrdering::NotAtomic;
  6706. AtomicOrdering FailureOrdering = AtomicOrdering::NotAtomic;
  6707. SyncScope::ID SSID = SyncScope::System;
  6708. bool isVolatile = false;
  6709. bool isWeak = false;
  6710. MaybeAlign Alignment;
  6711. if (EatIfPresent(lltok::kw_weak))
  6712. isWeak = true;
  6713. if (EatIfPresent(lltok::kw_volatile))
  6714. isVolatile = true;
  6715. if (parseTypeAndValue(Ptr, PtrLoc, PFS) ||
  6716. parseToken(lltok::comma, "expected ',' after cmpxchg address") ||
  6717. parseTypeAndValue(Cmp, CmpLoc, PFS) ||
  6718. parseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
  6719. parseTypeAndValue(New, NewLoc, PFS) ||
  6720. parseScopeAndOrdering(true /*Always atomic*/, SSID, SuccessOrdering) ||
  6721. parseOrdering(FailureOrdering) ||
  6722. parseOptionalCommaAlign(Alignment, AteExtraComma))
  6723. return true;
  6724. if (!AtomicCmpXchgInst::isValidSuccessOrdering(SuccessOrdering))
  6725. return tokError("invalid cmpxchg success ordering");
  6726. if (!AtomicCmpXchgInst::isValidFailureOrdering(FailureOrdering))
  6727. return tokError("invalid cmpxchg failure ordering");
  6728. if (!Ptr->getType()->isPointerTy())
  6729. return error(PtrLoc, "cmpxchg operand must be a pointer");
  6730. if (!cast<PointerType>(Ptr->getType())
  6731. ->isOpaqueOrPointeeTypeMatches(Cmp->getType()))
  6732. return error(CmpLoc, "compare value and pointer type do not match");
  6733. if (!cast<PointerType>(Ptr->getType())
  6734. ->isOpaqueOrPointeeTypeMatches(New->getType()))
  6735. return error(NewLoc, "new value and pointer type do not match");
  6736. if (Cmp->getType() != New->getType())
  6737. return error(NewLoc, "compare value and new value type do not match");
  6738. if (!New->getType()->isFirstClassType())
  6739. return error(NewLoc, "cmpxchg operand must be a first class value");
  6740. const Align DefaultAlignment(
  6741. PFS.getFunction().getParent()->getDataLayout().getTypeStoreSize(
  6742. Cmp->getType()));
  6743. AtomicCmpXchgInst *CXI =
  6744. new AtomicCmpXchgInst(Ptr, Cmp, New, Alignment.value_or(DefaultAlignment),
  6745. SuccessOrdering, FailureOrdering, SSID);
  6746. CXI->setVolatile(isVolatile);
  6747. CXI->setWeak(isWeak);
  6748. Inst = CXI;
  6749. return AteExtraComma ? InstExtraComma : InstNormal;
  6750. }
  6751. /// parseAtomicRMW
  6752. /// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
  6753. /// 'singlethread'? AtomicOrdering
  6754. int LLParser::parseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
  6755. Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
  6756. bool AteExtraComma = false;
  6757. AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
  6758. SyncScope::ID SSID = SyncScope::System;
  6759. bool isVolatile = false;
  6760. bool IsFP = false;
  6761. AtomicRMWInst::BinOp Operation;
  6762. MaybeAlign Alignment;
  6763. if (EatIfPresent(lltok::kw_volatile))
  6764. isVolatile = true;
  6765. switch (Lex.getKind()) {
  6766. default:
  6767. return tokError("expected binary operation in atomicrmw");
  6768. case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break;
  6769. case lltok::kw_add: Operation = AtomicRMWInst::Add; break;
  6770. case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break;
  6771. case lltok::kw_and: Operation = AtomicRMWInst::And; break;
  6772. case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break;
  6773. case lltok::kw_or: Operation = AtomicRMWInst::Or; break;
  6774. case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break;
  6775. case lltok::kw_max: Operation = AtomicRMWInst::Max; break;
  6776. case lltok::kw_min: Operation = AtomicRMWInst::Min; break;
  6777. case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break;
  6778. case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break;
  6779. case lltok::kw_uinc_wrap:
  6780. Operation = AtomicRMWInst::UIncWrap;
  6781. break;
  6782. case lltok::kw_udec_wrap:
  6783. Operation = AtomicRMWInst::UDecWrap;
  6784. break;
  6785. case lltok::kw_fadd:
  6786. Operation = AtomicRMWInst::FAdd;
  6787. IsFP = true;
  6788. break;
  6789. case lltok::kw_fsub:
  6790. Operation = AtomicRMWInst::FSub;
  6791. IsFP = true;
  6792. break;
  6793. case lltok::kw_fmax:
  6794. Operation = AtomicRMWInst::FMax;
  6795. IsFP = true;
  6796. break;
  6797. case lltok::kw_fmin:
  6798. Operation = AtomicRMWInst::FMin;
  6799. IsFP = true;
  6800. break;
  6801. }
  6802. Lex.Lex(); // Eat the operation.
  6803. if (parseTypeAndValue(Ptr, PtrLoc, PFS) ||
  6804. parseToken(lltok::comma, "expected ',' after atomicrmw address") ||
  6805. parseTypeAndValue(Val, ValLoc, PFS) ||
  6806. parseScopeAndOrdering(true /*Always atomic*/, SSID, Ordering) ||
  6807. parseOptionalCommaAlign(Alignment, AteExtraComma))
  6808. return true;
  6809. if (Ordering == AtomicOrdering::Unordered)
  6810. return tokError("atomicrmw cannot be unordered");
  6811. if (!Ptr->getType()->isPointerTy())
  6812. return error(PtrLoc, "atomicrmw operand must be a pointer");
  6813. if (!cast<PointerType>(Ptr->getType())
  6814. ->isOpaqueOrPointeeTypeMatches(Val->getType()))
  6815. return error(ValLoc, "atomicrmw value and pointer type do not match");
  6816. if (Operation == AtomicRMWInst::Xchg) {
  6817. if (!Val->getType()->isIntegerTy() &&
  6818. !Val->getType()->isFloatingPointTy() &&
  6819. !Val->getType()->isPointerTy()) {
  6820. return error(
  6821. ValLoc,
  6822. "atomicrmw " + AtomicRMWInst::getOperationName(Operation) +
  6823. " operand must be an integer, floating point, or pointer type");
  6824. }
  6825. } else if (IsFP) {
  6826. if (!Val->getType()->isFloatingPointTy()) {
  6827. return error(ValLoc, "atomicrmw " +
  6828. AtomicRMWInst::getOperationName(Operation) +
  6829. " operand must be a floating point type");
  6830. }
  6831. } else {
  6832. if (!Val->getType()->isIntegerTy()) {
  6833. return error(ValLoc, "atomicrmw " +
  6834. AtomicRMWInst::getOperationName(Operation) +
  6835. " operand must be an integer");
  6836. }
  6837. }
  6838. unsigned Size =
  6839. PFS.getFunction().getParent()->getDataLayout().getTypeStoreSizeInBits(
  6840. Val->getType());
  6841. if (Size < 8 || (Size & (Size - 1)))
  6842. return error(ValLoc, "atomicrmw operand must be power-of-two byte-sized"
  6843. " integer");
  6844. const Align DefaultAlignment(
  6845. PFS.getFunction().getParent()->getDataLayout().getTypeStoreSize(
  6846. Val->getType()));
  6847. AtomicRMWInst *RMWI =
  6848. new AtomicRMWInst(Operation, Ptr, Val,
  6849. Alignment.value_or(DefaultAlignment), Ordering, SSID);
  6850. RMWI->setVolatile(isVolatile);
  6851. Inst = RMWI;
  6852. return AteExtraComma ? InstExtraComma : InstNormal;
  6853. }
  6854. /// parseFence
  6855. /// ::= 'fence' 'singlethread'? AtomicOrdering
  6856. int LLParser::parseFence(Instruction *&Inst, PerFunctionState &PFS) {
  6857. AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
  6858. SyncScope::ID SSID = SyncScope::System;
  6859. if (parseScopeAndOrdering(true /*Always atomic*/, SSID, Ordering))
  6860. return true;
  6861. if (Ordering == AtomicOrdering::Unordered)
  6862. return tokError("fence cannot be unordered");
  6863. if (Ordering == AtomicOrdering::Monotonic)
  6864. return tokError("fence cannot be monotonic");
  6865. Inst = new FenceInst(Context, Ordering, SSID);
  6866. return InstNormal;
  6867. }
  6868. /// parseGetElementPtr
  6869. /// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
  6870. int LLParser::parseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
  6871. Value *Ptr = nullptr;
  6872. Value *Val = nullptr;
  6873. LocTy Loc, EltLoc;
  6874. bool InBounds = EatIfPresent(lltok::kw_inbounds);
  6875. Type *Ty = nullptr;
  6876. LocTy ExplicitTypeLoc = Lex.getLoc();
  6877. if (parseType(Ty) ||
  6878. parseToken(lltok::comma, "expected comma after getelementptr's type") ||
  6879. parseTypeAndValue(Ptr, Loc, PFS))
  6880. return true;
  6881. Type *BaseType = Ptr->getType();
  6882. PointerType *BasePointerType = dyn_cast<PointerType>(BaseType->getScalarType());
  6883. if (!BasePointerType)
  6884. return error(Loc, "base of getelementptr must be a pointer");
  6885. if (!BasePointerType->isOpaqueOrPointeeTypeMatches(Ty)) {
  6886. return error(
  6887. ExplicitTypeLoc,
  6888. typeComparisonErrorMessage(
  6889. "explicit pointee type doesn't match operand's pointee type", Ty,
  6890. BasePointerType->getNonOpaquePointerElementType()));
  6891. }
  6892. SmallVector<Value*, 16> Indices;
  6893. bool AteExtraComma = false;
  6894. // GEP returns a vector of pointers if at least one of parameters is a vector.
  6895. // All vector parameters should have the same vector width.
  6896. ElementCount GEPWidth = BaseType->isVectorTy()
  6897. ? cast<VectorType>(BaseType)->getElementCount()
  6898. : ElementCount::getFixed(0);
  6899. while (EatIfPresent(lltok::comma)) {
  6900. if (Lex.getKind() == lltok::MetadataVar) {
  6901. AteExtraComma = true;
  6902. break;
  6903. }
  6904. if (parseTypeAndValue(Val, EltLoc, PFS))
  6905. return true;
  6906. if (!Val->getType()->isIntOrIntVectorTy())
  6907. return error(EltLoc, "getelementptr index must be an integer");
  6908. if (auto *ValVTy = dyn_cast<VectorType>(Val->getType())) {
  6909. ElementCount ValNumEl = ValVTy->getElementCount();
  6910. if (GEPWidth != ElementCount::getFixed(0) && GEPWidth != ValNumEl)
  6911. return error(
  6912. EltLoc,
  6913. "getelementptr vector index has a wrong number of elements");
  6914. GEPWidth = ValNumEl;
  6915. }
  6916. Indices.push_back(Val);
  6917. }
  6918. SmallPtrSet<Type*, 4> Visited;
  6919. if (!Indices.empty() && !Ty->isSized(&Visited))
  6920. return error(Loc, "base element of getelementptr must be sized");
  6921. if (!GetElementPtrInst::getIndexedType(Ty, Indices))
  6922. return error(Loc, "invalid getelementptr indices");
  6923. Inst = GetElementPtrInst::Create(Ty, Ptr, Indices);
  6924. if (InBounds)
  6925. cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
  6926. return AteExtraComma ? InstExtraComma : InstNormal;
  6927. }
  6928. /// parseExtractValue
  6929. /// ::= 'extractvalue' TypeAndValue (',' uint32)+
  6930. int LLParser::parseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
  6931. Value *Val; LocTy Loc;
  6932. SmallVector<unsigned, 4> Indices;
  6933. bool AteExtraComma;
  6934. if (parseTypeAndValue(Val, Loc, PFS) ||
  6935. parseIndexList(Indices, AteExtraComma))
  6936. return true;
  6937. if (!Val->getType()->isAggregateType())
  6938. return error(Loc, "extractvalue operand must be aggregate type");
  6939. if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
  6940. return error(Loc, "invalid indices for extractvalue");
  6941. Inst = ExtractValueInst::Create(Val, Indices);
  6942. return AteExtraComma ? InstExtraComma : InstNormal;
  6943. }
  6944. /// parseInsertValue
  6945. /// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
  6946. int LLParser::parseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
  6947. Value *Val0, *Val1; LocTy Loc0, Loc1;
  6948. SmallVector<unsigned, 4> Indices;
  6949. bool AteExtraComma;
  6950. if (parseTypeAndValue(Val0, Loc0, PFS) ||
  6951. parseToken(lltok::comma, "expected comma after insertvalue operand") ||
  6952. parseTypeAndValue(Val1, Loc1, PFS) ||
  6953. parseIndexList(Indices, AteExtraComma))
  6954. return true;
  6955. if (!Val0->getType()->isAggregateType())
  6956. return error(Loc0, "insertvalue operand must be aggregate type");
  6957. Type *IndexedType = ExtractValueInst::getIndexedType(Val0->getType(), Indices);
  6958. if (!IndexedType)
  6959. return error(Loc0, "invalid indices for insertvalue");
  6960. if (IndexedType != Val1->getType())
  6961. return error(Loc1, "insertvalue operand and field disagree in type: '" +
  6962. getTypeString(Val1->getType()) + "' instead of '" +
  6963. getTypeString(IndexedType) + "'");
  6964. Inst = InsertValueInst::Create(Val0, Val1, Indices);
  6965. return AteExtraComma ? InstExtraComma : InstNormal;
  6966. }
  6967. //===----------------------------------------------------------------------===//
  6968. // Embedded metadata.
  6969. //===----------------------------------------------------------------------===//
  6970. /// parseMDNodeVector
  6971. /// ::= { Element (',' Element)* }
  6972. /// Element
  6973. /// ::= 'null' | TypeAndValue
  6974. bool LLParser::parseMDNodeVector(SmallVectorImpl<Metadata *> &Elts) {
  6975. if (parseToken(lltok::lbrace, "expected '{' here"))
  6976. return true;
  6977. // Check for an empty list.
  6978. if (EatIfPresent(lltok::rbrace))
  6979. return false;
  6980. do {
  6981. // Null is a special case since it is typeless.
  6982. if (EatIfPresent(lltok::kw_null)) {
  6983. Elts.push_back(nullptr);
  6984. continue;
  6985. }
  6986. Metadata *MD;
  6987. if (parseMetadata(MD, nullptr))
  6988. return true;
  6989. Elts.push_back(MD);
  6990. } while (EatIfPresent(lltok::comma));
  6991. return parseToken(lltok::rbrace, "expected end of metadata node");
  6992. }
  6993. //===----------------------------------------------------------------------===//
  6994. // Use-list order directives.
  6995. //===----------------------------------------------------------------------===//
  6996. bool LLParser::sortUseListOrder(Value *V, ArrayRef<unsigned> Indexes,
  6997. SMLoc Loc) {
  6998. if (V->use_empty())
  6999. return error(Loc, "value has no uses");
  7000. unsigned NumUses = 0;
  7001. SmallDenseMap<const Use *, unsigned, 16> Order;
  7002. for (const Use &U : V->uses()) {
  7003. if (++NumUses > Indexes.size())
  7004. break;
  7005. Order[&U] = Indexes[NumUses - 1];
  7006. }
  7007. if (NumUses < 2)
  7008. return error(Loc, "value only has one use");
  7009. if (Order.size() != Indexes.size() || NumUses > Indexes.size())
  7010. return error(Loc,
  7011. "wrong number of indexes, expected " + Twine(V->getNumUses()));
  7012. V->sortUseList([&](const Use &L, const Use &R) {
  7013. return Order.lookup(&L) < Order.lookup(&R);
  7014. });
  7015. return false;
  7016. }
  7017. /// parseUseListOrderIndexes
  7018. /// ::= '{' uint32 (',' uint32)+ '}'
  7019. bool LLParser::parseUseListOrderIndexes(SmallVectorImpl<unsigned> &Indexes) {
  7020. SMLoc Loc = Lex.getLoc();
  7021. if (parseToken(lltok::lbrace, "expected '{' here"))
  7022. return true;
  7023. if (Lex.getKind() == lltok::rbrace)
  7024. return Lex.Error("expected non-empty list of uselistorder indexes");
  7025. // Use Offset, Max, and IsOrdered to check consistency of indexes. The
  7026. // indexes should be distinct numbers in the range [0, size-1], and should
  7027. // not be in order.
  7028. unsigned Offset = 0;
  7029. unsigned Max = 0;
  7030. bool IsOrdered = true;
  7031. assert(Indexes.empty() && "Expected empty order vector");
  7032. do {
  7033. unsigned Index;
  7034. if (parseUInt32(Index))
  7035. return true;
  7036. // Update consistency checks.
  7037. Offset += Index - Indexes.size();
  7038. Max = std::max(Max, Index);
  7039. IsOrdered &= Index == Indexes.size();
  7040. Indexes.push_back(Index);
  7041. } while (EatIfPresent(lltok::comma));
  7042. if (parseToken(lltok::rbrace, "expected '}' here"))
  7043. return true;
  7044. if (Indexes.size() < 2)
  7045. return error(Loc, "expected >= 2 uselistorder indexes");
  7046. if (Offset != 0 || Max >= Indexes.size())
  7047. return error(Loc,
  7048. "expected distinct uselistorder indexes in range [0, size)");
  7049. if (IsOrdered)
  7050. return error(Loc, "expected uselistorder indexes to change the order");
  7051. return false;
  7052. }
  7053. /// parseUseListOrder
  7054. /// ::= 'uselistorder' Type Value ',' UseListOrderIndexes
  7055. bool LLParser::parseUseListOrder(PerFunctionState *PFS) {
  7056. SMLoc Loc = Lex.getLoc();
  7057. if (parseToken(lltok::kw_uselistorder, "expected uselistorder directive"))
  7058. return true;
  7059. Value *V;
  7060. SmallVector<unsigned, 16> Indexes;
  7061. if (parseTypeAndValue(V, PFS) ||
  7062. parseToken(lltok::comma, "expected comma in uselistorder directive") ||
  7063. parseUseListOrderIndexes(Indexes))
  7064. return true;
  7065. return sortUseListOrder(V, Indexes, Loc);
  7066. }
  7067. /// parseUseListOrderBB
  7068. /// ::= 'uselistorder_bb' @foo ',' %bar ',' UseListOrderIndexes
  7069. bool LLParser::parseUseListOrderBB() {
  7070. assert(Lex.getKind() == lltok::kw_uselistorder_bb);
  7071. SMLoc Loc = Lex.getLoc();
  7072. Lex.Lex();
  7073. ValID Fn, Label;
  7074. SmallVector<unsigned, 16> Indexes;
  7075. if (parseValID(Fn, /*PFS=*/nullptr) ||
  7076. parseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
  7077. parseValID(Label, /*PFS=*/nullptr) ||
  7078. parseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
  7079. parseUseListOrderIndexes(Indexes))
  7080. return true;
  7081. // Check the function.
  7082. GlobalValue *GV;
  7083. if (Fn.Kind == ValID::t_GlobalName)
  7084. GV = M->getNamedValue(Fn.StrVal);
  7085. else if (Fn.Kind == ValID::t_GlobalID)
  7086. GV = Fn.UIntVal < NumberedVals.size() ? NumberedVals[Fn.UIntVal] : nullptr;
  7087. else
  7088. return error(Fn.Loc, "expected function name in uselistorder_bb");
  7089. if (!GV)
  7090. return error(Fn.Loc,
  7091. "invalid function forward reference in uselistorder_bb");
  7092. auto *F = dyn_cast<Function>(GV);
  7093. if (!F)
  7094. return error(Fn.Loc, "expected function name in uselistorder_bb");
  7095. if (F->isDeclaration())
  7096. return error(Fn.Loc, "invalid declaration in uselistorder_bb");
  7097. // Check the basic block.
  7098. if (Label.Kind == ValID::t_LocalID)
  7099. return error(Label.Loc, "invalid numeric label in uselistorder_bb");
  7100. if (Label.Kind != ValID::t_LocalName)
  7101. return error(Label.Loc, "expected basic block name in uselistorder_bb");
  7102. Value *V = F->getValueSymbolTable()->lookup(Label.StrVal);
  7103. if (!V)
  7104. return error(Label.Loc, "invalid basic block in uselistorder_bb");
  7105. if (!isa<BasicBlock>(V))
  7106. return error(Label.Loc, "expected basic block in uselistorder_bb");
  7107. return sortUseListOrder(V, Indexes, Loc);
  7108. }
  7109. /// ModuleEntry
  7110. /// ::= 'module' ':' '(' 'path' ':' STRINGCONSTANT ',' 'hash' ':' Hash ')'
  7111. /// Hash ::= '(' UInt32 ',' UInt32 ',' UInt32 ',' UInt32 ',' UInt32 ')'
  7112. bool LLParser::parseModuleEntry(unsigned ID) {
  7113. assert(Lex.getKind() == lltok::kw_module);
  7114. Lex.Lex();
  7115. std::string Path;
  7116. if (parseToken(lltok::colon, "expected ':' here") ||
  7117. parseToken(lltok::lparen, "expected '(' here") ||
  7118. parseToken(lltok::kw_path, "expected 'path' here") ||
  7119. parseToken(lltok::colon, "expected ':' here") ||
  7120. parseStringConstant(Path) ||
  7121. parseToken(lltok::comma, "expected ',' here") ||
  7122. parseToken(lltok::kw_hash, "expected 'hash' here") ||
  7123. parseToken(lltok::colon, "expected ':' here") ||
  7124. parseToken(lltok::lparen, "expected '(' here"))
  7125. return true;
  7126. ModuleHash Hash;
  7127. if (parseUInt32(Hash[0]) || parseToken(lltok::comma, "expected ',' here") ||
  7128. parseUInt32(Hash[1]) || parseToken(lltok::comma, "expected ',' here") ||
  7129. parseUInt32(Hash[2]) || parseToken(lltok::comma, "expected ',' here") ||
  7130. parseUInt32(Hash[3]) || parseToken(lltok::comma, "expected ',' here") ||
  7131. parseUInt32(Hash[4]))
  7132. return true;
  7133. if (parseToken(lltok::rparen, "expected ')' here") ||
  7134. parseToken(lltok::rparen, "expected ')' here"))
  7135. return true;
  7136. auto ModuleEntry = Index->addModule(Path, ID, Hash);
  7137. ModuleIdMap[ID] = ModuleEntry->first();
  7138. return false;
  7139. }
  7140. /// TypeIdEntry
  7141. /// ::= 'typeid' ':' '(' 'name' ':' STRINGCONSTANT ',' TypeIdSummary ')'
  7142. bool LLParser::parseTypeIdEntry(unsigned ID) {
  7143. assert(Lex.getKind() == lltok::kw_typeid);
  7144. Lex.Lex();
  7145. std::string Name;
  7146. if (parseToken(lltok::colon, "expected ':' here") ||
  7147. parseToken(lltok::lparen, "expected '(' here") ||
  7148. parseToken(lltok::kw_name, "expected 'name' here") ||
  7149. parseToken(lltok::colon, "expected ':' here") ||
  7150. parseStringConstant(Name))
  7151. return true;
  7152. TypeIdSummary &TIS = Index->getOrInsertTypeIdSummary(Name);
  7153. if (parseToken(lltok::comma, "expected ',' here") ||
  7154. parseTypeIdSummary(TIS) || parseToken(lltok::rparen, "expected ')' here"))
  7155. return true;
  7156. // Check if this ID was forward referenced, and if so, update the
  7157. // corresponding GUIDs.
  7158. auto FwdRefTIDs = ForwardRefTypeIds.find(ID);
  7159. if (FwdRefTIDs != ForwardRefTypeIds.end()) {
  7160. for (auto TIDRef : FwdRefTIDs->second) {
  7161. assert(!*TIDRef.first &&
  7162. "Forward referenced type id GUID expected to be 0");
  7163. *TIDRef.first = GlobalValue::getGUID(Name);
  7164. }
  7165. ForwardRefTypeIds.erase(FwdRefTIDs);
  7166. }
  7167. return false;
  7168. }
  7169. /// TypeIdSummary
  7170. /// ::= 'summary' ':' '(' TypeTestResolution [',' OptionalWpdResolutions]? ')'
  7171. bool LLParser::parseTypeIdSummary(TypeIdSummary &TIS) {
  7172. if (parseToken(lltok::kw_summary, "expected 'summary' here") ||
  7173. parseToken(lltok::colon, "expected ':' here") ||
  7174. parseToken(lltok::lparen, "expected '(' here") ||
  7175. parseTypeTestResolution(TIS.TTRes))
  7176. return true;
  7177. if (EatIfPresent(lltok::comma)) {
  7178. // Expect optional wpdResolutions field
  7179. if (parseOptionalWpdResolutions(TIS.WPDRes))
  7180. return true;
  7181. }
  7182. if (parseToken(lltok::rparen, "expected ')' here"))
  7183. return true;
  7184. return false;
  7185. }
  7186. static ValueInfo EmptyVI =
  7187. ValueInfo(false, (GlobalValueSummaryMapTy::value_type *)-8);
  7188. /// TypeIdCompatibleVtableEntry
  7189. /// ::= 'typeidCompatibleVTable' ':' '(' 'name' ':' STRINGCONSTANT ','
  7190. /// TypeIdCompatibleVtableInfo
  7191. /// ')'
  7192. bool LLParser::parseTypeIdCompatibleVtableEntry(unsigned ID) {
  7193. assert(Lex.getKind() == lltok::kw_typeidCompatibleVTable);
  7194. Lex.Lex();
  7195. std::string Name;
  7196. if (parseToken(lltok::colon, "expected ':' here") ||
  7197. parseToken(lltok::lparen, "expected '(' here") ||
  7198. parseToken(lltok::kw_name, "expected 'name' here") ||
  7199. parseToken(lltok::colon, "expected ':' here") ||
  7200. parseStringConstant(Name))
  7201. return true;
  7202. TypeIdCompatibleVtableInfo &TI =
  7203. Index->getOrInsertTypeIdCompatibleVtableSummary(Name);
  7204. if (parseToken(lltok::comma, "expected ',' here") ||
  7205. parseToken(lltok::kw_summary, "expected 'summary' here") ||
  7206. parseToken(lltok::colon, "expected ':' here") ||
  7207. parseToken(lltok::lparen, "expected '(' here"))
  7208. return true;
  7209. IdToIndexMapType IdToIndexMap;
  7210. // parse each call edge
  7211. do {
  7212. uint64_t Offset;
  7213. if (parseToken(lltok::lparen, "expected '(' here") ||
  7214. parseToken(lltok::kw_offset, "expected 'offset' here") ||
  7215. parseToken(lltok::colon, "expected ':' here") || parseUInt64(Offset) ||
  7216. parseToken(lltok::comma, "expected ',' here"))
  7217. return true;
  7218. LocTy Loc = Lex.getLoc();
  7219. unsigned GVId;
  7220. ValueInfo VI;
  7221. if (parseGVReference(VI, GVId))
  7222. return true;
  7223. // Keep track of the TypeIdCompatibleVtableInfo array index needing a
  7224. // forward reference. We will save the location of the ValueInfo needing an
  7225. // update, but can only do so once the std::vector is finalized.
  7226. if (VI == EmptyVI)
  7227. IdToIndexMap[GVId].push_back(std::make_pair(TI.size(), Loc));
  7228. TI.push_back({Offset, VI});
  7229. if (parseToken(lltok::rparen, "expected ')' in call"))
  7230. return true;
  7231. } while (EatIfPresent(lltok::comma));
  7232. // Now that the TI vector is finalized, it is safe to save the locations
  7233. // of any forward GV references that need updating later.
  7234. for (auto I : IdToIndexMap) {
  7235. auto &Infos = ForwardRefValueInfos[I.first];
  7236. for (auto P : I.second) {
  7237. assert(TI[P.first].VTableVI == EmptyVI &&
  7238. "Forward referenced ValueInfo expected to be empty");
  7239. Infos.emplace_back(&TI[P.first].VTableVI, P.second);
  7240. }
  7241. }
  7242. if (parseToken(lltok::rparen, "expected ')' here") ||
  7243. parseToken(lltok::rparen, "expected ')' here"))
  7244. return true;
  7245. // Check if this ID was forward referenced, and if so, update the
  7246. // corresponding GUIDs.
  7247. auto FwdRefTIDs = ForwardRefTypeIds.find(ID);
  7248. if (FwdRefTIDs != ForwardRefTypeIds.end()) {
  7249. for (auto TIDRef : FwdRefTIDs->second) {
  7250. assert(!*TIDRef.first &&
  7251. "Forward referenced type id GUID expected to be 0");
  7252. *TIDRef.first = GlobalValue::getGUID(Name);
  7253. }
  7254. ForwardRefTypeIds.erase(FwdRefTIDs);
  7255. }
  7256. return false;
  7257. }
  7258. /// TypeTestResolution
  7259. /// ::= 'typeTestRes' ':' '(' 'kind' ':'
  7260. /// ( 'unsat' | 'byteArray' | 'inline' | 'single' | 'allOnes' ) ','
  7261. /// 'sizeM1BitWidth' ':' SizeM1BitWidth [',' 'alignLog2' ':' UInt64]?
  7262. /// [',' 'sizeM1' ':' UInt64]? [',' 'bitMask' ':' UInt8]?
  7263. /// [',' 'inlinesBits' ':' UInt64]? ')'
  7264. bool LLParser::parseTypeTestResolution(TypeTestResolution &TTRes) {
  7265. if (parseToken(lltok::kw_typeTestRes, "expected 'typeTestRes' here") ||
  7266. parseToken(lltok::colon, "expected ':' here") ||
  7267. parseToken(lltok::lparen, "expected '(' here") ||
  7268. parseToken(lltok::kw_kind, "expected 'kind' here") ||
  7269. parseToken(lltok::colon, "expected ':' here"))
  7270. return true;
  7271. switch (Lex.getKind()) {
  7272. case lltok::kw_unknown:
  7273. TTRes.TheKind = TypeTestResolution::Unknown;
  7274. break;
  7275. case lltok::kw_unsat:
  7276. TTRes.TheKind = TypeTestResolution::Unsat;
  7277. break;
  7278. case lltok::kw_byteArray:
  7279. TTRes.TheKind = TypeTestResolution::ByteArray;
  7280. break;
  7281. case lltok::kw_inline:
  7282. TTRes.TheKind = TypeTestResolution::Inline;
  7283. break;
  7284. case lltok::kw_single:
  7285. TTRes.TheKind = TypeTestResolution::Single;
  7286. break;
  7287. case lltok::kw_allOnes:
  7288. TTRes.TheKind = TypeTestResolution::AllOnes;
  7289. break;
  7290. default:
  7291. return error(Lex.getLoc(), "unexpected TypeTestResolution kind");
  7292. }
  7293. Lex.Lex();
  7294. if (parseToken(lltok::comma, "expected ',' here") ||
  7295. parseToken(lltok::kw_sizeM1BitWidth, "expected 'sizeM1BitWidth' here") ||
  7296. parseToken(lltok::colon, "expected ':' here") ||
  7297. parseUInt32(TTRes.SizeM1BitWidth))
  7298. return true;
  7299. // parse optional fields
  7300. while (EatIfPresent(lltok::comma)) {
  7301. switch (Lex.getKind()) {
  7302. case lltok::kw_alignLog2:
  7303. Lex.Lex();
  7304. if (parseToken(lltok::colon, "expected ':'") ||
  7305. parseUInt64(TTRes.AlignLog2))
  7306. return true;
  7307. break;
  7308. case lltok::kw_sizeM1:
  7309. Lex.Lex();
  7310. if (parseToken(lltok::colon, "expected ':'") || parseUInt64(TTRes.SizeM1))
  7311. return true;
  7312. break;
  7313. case lltok::kw_bitMask: {
  7314. unsigned Val;
  7315. Lex.Lex();
  7316. if (parseToken(lltok::colon, "expected ':'") || parseUInt32(Val))
  7317. return true;
  7318. assert(Val <= 0xff);
  7319. TTRes.BitMask = (uint8_t)Val;
  7320. break;
  7321. }
  7322. case lltok::kw_inlineBits:
  7323. Lex.Lex();
  7324. if (parseToken(lltok::colon, "expected ':'") ||
  7325. parseUInt64(TTRes.InlineBits))
  7326. return true;
  7327. break;
  7328. default:
  7329. return error(Lex.getLoc(), "expected optional TypeTestResolution field");
  7330. }
  7331. }
  7332. if (parseToken(lltok::rparen, "expected ')' here"))
  7333. return true;
  7334. return false;
  7335. }
  7336. /// OptionalWpdResolutions
  7337. /// ::= 'wpsResolutions' ':' '(' WpdResolution [',' WpdResolution]* ')'
  7338. /// WpdResolution ::= '(' 'offset' ':' UInt64 ',' WpdRes ')'
  7339. bool LLParser::parseOptionalWpdResolutions(
  7340. std::map<uint64_t, WholeProgramDevirtResolution> &WPDResMap) {
  7341. if (parseToken(lltok::kw_wpdResolutions, "expected 'wpdResolutions' here") ||
  7342. parseToken(lltok::colon, "expected ':' here") ||
  7343. parseToken(lltok::lparen, "expected '(' here"))
  7344. return true;
  7345. do {
  7346. uint64_t Offset;
  7347. WholeProgramDevirtResolution WPDRes;
  7348. if (parseToken(lltok::lparen, "expected '(' here") ||
  7349. parseToken(lltok::kw_offset, "expected 'offset' here") ||
  7350. parseToken(lltok::colon, "expected ':' here") || parseUInt64(Offset) ||
  7351. parseToken(lltok::comma, "expected ',' here") || parseWpdRes(WPDRes) ||
  7352. parseToken(lltok::rparen, "expected ')' here"))
  7353. return true;
  7354. WPDResMap[Offset] = WPDRes;
  7355. } while (EatIfPresent(lltok::comma));
  7356. if (parseToken(lltok::rparen, "expected ')' here"))
  7357. return true;
  7358. return false;
  7359. }
  7360. /// WpdRes
  7361. /// ::= 'wpdRes' ':' '(' 'kind' ':' 'indir'
  7362. /// [',' OptionalResByArg]? ')'
  7363. /// ::= 'wpdRes' ':' '(' 'kind' ':' 'singleImpl'
  7364. /// ',' 'singleImplName' ':' STRINGCONSTANT ','
  7365. /// [',' OptionalResByArg]? ')'
  7366. /// ::= 'wpdRes' ':' '(' 'kind' ':' 'branchFunnel'
  7367. /// [',' OptionalResByArg]? ')'
  7368. bool LLParser::parseWpdRes(WholeProgramDevirtResolution &WPDRes) {
  7369. if (parseToken(lltok::kw_wpdRes, "expected 'wpdRes' here") ||
  7370. parseToken(lltok::colon, "expected ':' here") ||
  7371. parseToken(lltok::lparen, "expected '(' here") ||
  7372. parseToken(lltok::kw_kind, "expected 'kind' here") ||
  7373. parseToken(lltok::colon, "expected ':' here"))
  7374. return true;
  7375. switch (Lex.getKind()) {
  7376. case lltok::kw_indir:
  7377. WPDRes.TheKind = WholeProgramDevirtResolution::Indir;
  7378. break;
  7379. case lltok::kw_singleImpl:
  7380. WPDRes.TheKind = WholeProgramDevirtResolution::SingleImpl;
  7381. break;
  7382. case lltok::kw_branchFunnel:
  7383. WPDRes.TheKind = WholeProgramDevirtResolution::BranchFunnel;
  7384. break;
  7385. default:
  7386. return error(Lex.getLoc(), "unexpected WholeProgramDevirtResolution kind");
  7387. }
  7388. Lex.Lex();
  7389. // parse optional fields
  7390. while (EatIfPresent(lltok::comma)) {
  7391. switch (Lex.getKind()) {
  7392. case lltok::kw_singleImplName:
  7393. Lex.Lex();
  7394. if (parseToken(lltok::colon, "expected ':' here") ||
  7395. parseStringConstant(WPDRes.SingleImplName))
  7396. return true;
  7397. break;
  7398. case lltok::kw_resByArg:
  7399. if (parseOptionalResByArg(WPDRes.ResByArg))
  7400. return true;
  7401. break;
  7402. default:
  7403. return error(Lex.getLoc(),
  7404. "expected optional WholeProgramDevirtResolution field");
  7405. }
  7406. }
  7407. if (parseToken(lltok::rparen, "expected ')' here"))
  7408. return true;
  7409. return false;
  7410. }
  7411. /// OptionalResByArg
  7412. /// ::= 'wpdRes' ':' '(' ResByArg[, ResByArg]* ')'
  7413. /// ResByArg ::= Args ',' 'byArg' ':' '(' 'kind' ':'
  7414. /// ( 'indir' | 'uniformRetVal' | 'UniqueRetVal' |
  7415. /// 'virtualConstProp' )
  7416. /// [',' 'info' ':' UInt64]? [',' 'byte' ':' UInt32]?
  7417. /// [',' 'bit' ':' UInt32]? ')'
  7418. bool LLParser::parseOptionalResByArg(
  7419. std::map<std::vector<uint64_t>, WholeProgramDevirtResolution::ByArg>
  7420. &ResByArg) {
  7421. if (parseToken(lltok::kw_resByArg, "expected 'resByArg' here") ||
  7422. parseToken(lltok::colon, "expected ':' here") ||
  7423. parseToken(lltok::lparen, "expected '(' here"))
  7424. return true;
  7425. do {
  7426. std::vector<uint64_t> Args;
  7427. if (parseArgs(Args) || parseToken(lltok::comma, "expected ',' here") ||
  7428. parseToken(lltok::kw_byArg, "expected 'byArg here") ||
  7429. parseToken(lltok::colon, "expected ':' here") ||
  7430. parseToken(lltok::lparen, "expected '(' here") ||
  7431. parseToken(lltok::kw_kind, "expected 'kind' here") ||
  7432. parseToken(lltok::colon, "expected ':' here"))
  7433. return true;
  7434. WholeProgramDevirtResolution::ByArg ByArg;
  7435. switch (Lex.getKind()) {
  7436. case lltok::kw_indir:
  7437. ByArg.TheKind = WholeProgramDevirtResolution::ByArg::Indir;
  7438. break;
  7439. case lltok::kw_uniformRetVal:
  7440. ByArg.TheKind = WholeProgramDevirtResolution::ByArg::UniformRetVal;
  7441. break;
  7442. case lltok::kw_uniqueRetVal:
  7443. ByArg.TheKind = WholeProgramDevirtResolution::ByArg::UniqueRetVal;
  7444. break;
  7445. case lltok::kw_virtualConstProp:
  7446. ByArg.TheKind = WholeProgramDevirtResolution::ByArg::VirtualConstProp;
  7447. break;
  7448. default:
  7449. return error(Lex.getLoc(),
  7450. "unexpected WholeProgramDevirtResolution::ByArg kind");
  7451. }
  7452. Lex.Lex();
  7453. // parse optional fields
  7454. while (EatIfPresent(lltok::comma)) {
  7455. switch (Lex.getKind()) {
  7456. case lltok::kw_info:
  7457. Lex.Lex();
  7458. if (parseToken(lltok::colon, "expected ':' here") ||
  7459. parseUInt64(ByArg.Info))
  7460. return true;
  7461. break;
  7462. case lltok::kw_byte:
  7463. Lex.Lex();
  7464. if (parseToken(lltok::colon, "expected ':' here") ||
  7465. parseUInt32(ByArg.Byte))
  7466. return true;
  7467. break;
  7468. case lltok::kw_bit:
  7469. Lex.Lex();
  7470. if (parseToken(lltok::colon, "expected ':' here") ||
  7471. parseUInt32(ByArg.Bit))
  7472. return true;
  7473. break;
  7474. default:
  7475. return error(Lex.getLoc(),
  7476. "expected optional whole program devirt field");
  7477. }
  7478. }
  7479. if (parseToken(lltok::rparen, "expected ')' here"))
  7480. return true;
  7481. ResByArg[Args] = ByArg;
  7482. } while (EatIfPresent(lltok::comma));
  7483. if (parseToken(lltok::rparen, "expected ')' here"))
  7484. return true;
  7485. return false;
  7486. }
  7487. /// OptionalResByArg
  7488. /// ::= 'args' ':' '(' UInt64[, UInt64]* ')'
  7489. bool LLParser::parseArgs(std::vector<uint64_t> &Args) {
  7490. if (parseToken(lltok::kw_args, "expected 'args' here") ||
  7491. parseToken(lltok::colon, "expected ':' here") ||
  7492. parseToken(lltok::lparen, "expected '(' here"))
  7493. return true;
  7494. do {
  7495. uint64_t Val;
  7496. if (parseUInt64(Val))
  7497. return true;
  7498. Args.push_back(Val);
  7499. } while (EatIfPresent(lltok::comma));
  7500. if (parseToken(lltok::rparen, "expected ')' here"))
  7501. return true;
  7502. return false;
  7503. }
  7504. static const auto FwdVIRef = (GlobalValueSummaryMapTy::value_type *)-8;
  7505. static void resolveFwdRef(ValueInfo *Fwd, ValueInfo &Resolved) {
  7506. bool ReadOnly = Fwd->isReadOnly();
  7507. bool WriteOnly = Fwd->isWriteOnly();
  7508. assert(!(ReadOnly && WriteOnly));
  7509. *Fwd = Resolved;
  7510. if (ReadOnly)
  7511. Fwd->setReadOnly();
  7512. if (WriteOnly)
  7513. Fwd->setWriteOnly();
  7514. }
  7515. /// Stores the given Name/GUID and associated summary into the Index.
  7516. /// Also updates any forward references to the associated entry ID.
  7517. void LLParser::addGlobalValueToIndex(
  7518. std::string Name, GlobalValue::GUID GUID, GlobalValue::LinkageTypes Linkage,
  7519. unsigned ID, std::unique_ptr<GlobalValueSummary> Summary) {
  7520. // First create the ValueInfo utilizing the Name or GUID.
  7521. ValueInfo VI;
  7522. if (GUID != 0) {
  7523. assert(Name.empty());
  7524. VI = Index->getOrInsertValueInfo(GUID);
  7525. } else {
  7526. assert(!Name.empty());
  7527. if (M) {
  7528. auto *GV = M->getNamedValue(Name);
  7529. assert(GV);
  7530. VI = Index->getOrInsertValueInfo(GV);
  7531. } else {
  7532. assert(
  7533. (!GlobalValue::isLocalLinkage(Linkage) || !SourceFileName.empty()) &&
  7534. "Need a source_filename to compute GUID for local");
  7535. GUID = GlobalValue::getGUID(
  7536. GlobalValue::getGlobalIdentifier(Name, Linkage, SourceFileName));
  7537. VI = Index->getOrInsertValueInfo(GUID, Index->saveString(Name));
  7538. }
  7539. }
  7540. // Resolve forward references from calls/refs
  7541. auto FwdRefVIs = ForwardRefValueInfos.find(ID);
  7542. if (FwdRefVIs != ForwardRefValueInfos.end()) {
  7543. for (auto VIRef : FwdRefVIs->second) {
  7544. assert(VIRef.first->getRef() == FwdVIRef &&
  7545. "Forward referenced ValueInfo expected to be empty");
  7546. resolveFwdRef(VIRef.first, VI);
  7547. }
  7548. ForwardRefValueInfos.erase(FwdRefVIs);
  7549. }
  7550. // Resolve forward references from aliases
  7551. auto FwdRefAliasees = ForwardRefAliasees.find(ID);
  7552. if (FwdRefAliasees != ForwardRefAliasees.end()) {
  7553. for (auto AliaseeRef : FwdRefAliasees->second) {
  7554. assert(!AliaseeRef.first->hasAliasee() &&
  7555. "Forward referencing alias already has aliasee");
  7556. assert(Summary && "Aliasee must be a definition");
  7557. AliaseeRef.first->setAliasee(VI, Summary.get());
  7558. }
  7559. ForwardRefAliasees.erase(FwdRefAliasees);
  7560. }
  7561. // Add the summary if one was provided.
  7562. if (Summary)
  7563. Index->addGlobalValueSummary(VI, std::move(Summary));
  7564. // Save the associated ValueInfo for use in later references by ID.
  7565. if (ID == NumberedValueInfos.size())
  7566. NumberedValueInfos.push_back(VI);
  7567. else {
  7568. // Handle non-continuous numbers (to make test simplification easier).
  7569. if (ID > NumberedValueInfos.size())
  7570. NumberedValueInfos.resize(ID + 1);
  7571. NumberedValueInfos[ID] = VI;
  7572. }
  7573. }
  7574. /// parseSummaryIndexFlags
  7575. /// ::= 'flags' ':' UInt64
  7576. bool LLParser::parseSummaryIndexFlags() {
  7577. assert(Lex.getKind() == lltok::kw_flags);
  7578. Lex.Lex();
  7579. if (parseToken(lltok::colon, "expected ':' here"))
  7580. return true;
  7581. uint64_t Flags;
  7582. if (parseUInt64(Flags))
  7583. return true;
  7584. if (Index)
  7585. Index->setFlags(Flags);
  7586. return false;
  7587. }
  7588. /// parseBlockCount
  7589. /// ::= 'blockcount' ':' UInt64
  7590. bool LLParser::parseBlockCount() {
  7591. assert(Lex.getKind() == lltok::kw_blockcount);
  7592. Lex.Lex();
  7593. if (parseToken(lltok::colon, "expected ':' here"))
  7594. return true;
  7595. uint64_t BlockCount;
  7596. if (parseUInt64(BlockCount))
  7597. return true;
  7598. if (Index)
  7599. Index->setBlockCount(BlockCount);
  7600. return false;
  7601. }
  7602. /// parseGVEntry
  7603. /// ::= 'gv' ':' '(' ('name' ':' STRINGCONSTANT | 'guid' ':' UInt64)
  7604. /// [',' 'summaries' ':' Summary[',' Summary]* ]? ')'
  7605. /// Summary ::= '(' (FunctionSummary | VariableSummary | AliasSummary) ')'
  7606. bool LLParser::parseGVEntry(unsigned ID) {
  7607. assert(Lex.getKind() == lltok::kw_gv);
  7608. Lex.Lex();
  7609. if (parseToken(lltok::colon, "expected ':' here") ||
  7610. parseToken(lltok::lparen, "expected '(' here"))
  7611. return true;
  7612. std::string Name;
  7613. GlobalValue::GUID GUID = 0;
  7614. switch (Lex.getKind()) {
  7615. case lltok::kw_name:
  7616. Lex.Lex();
  7617. if (parseToken(lltok::colon, "expected ':' here") ||
  7618. parseStringConstant(Name))
  7619. return true;
  7620. // Can't create GUID/ValueInfo until we have the linkage.
  7621. break;
  7622. case lltok::kw_guid:
  7623. Lex.Lex();
  7624. if (parseToken(lltok::colon, "expected ':' here") || parseUInt64(GUID))
  7625. return true;
  7626. break;
  7627. default:
  7628. return error(Lex.getLoc(), "expected name or guid tag");
  7629. }
  7630. if (!EatIfPresent(lltok::comma)) {
  7631. // No summaries. Wrap up.
  7632. if (parseToken(lltok::rparen, "expected ')' here"))
  7633. return true;
  7634. // This was created for a call to an external or indirect target.
  7635. // A GUID with no summary came from a VALUE_GUID record, dummy GUID
  7636. // created for indirect calls with VP. A Name with no GUID came from
  7637. // an external definition. We pass ExternalLinkage since that is only
  7638. // used when the GUID must be computed from Name, and in that case
  7639. // the symbol must have external linkage.
  7640. addGlobalValueToIndex(Name, GUID, GlobalValue::ExternalLinkage, ID,
  7641. nullptr);
  7642. return false;
  7643. }
  7644. // Have a list of summaries
  7645. if (parseToken(lltok::kw_summaries, "expected 'summaries' here") ||
  7646. parseToken(lltok::colon, "expected ':' here") ||
  7647. parseToken(lltok::lparen, "expected '(' here"))
  7648. return true;
  7649. do {
  7650. switch (Lex.getKind()) {
  7651. case lltok::kw_function:
  7652. if (parseFunctionSummary(Name, GUID, ID))
  7653. return true;
  7654. break;
  7655. case lltok::kw_variable:
  7656. if (parseVariableSummary(Name, GUID, ID))
  7657. return true;
  7658. break;
  7659. case lltok::kw_alias:
  7660. if (parseAliasSummary(Name, GUID, ID))
  7661. return true;
  7662. break;
  7663. default:
  7664. return error(Lex.getLoc(), "expected summary type");
  7665. }
  7666. } while (EatIfPresent(lltok::comma));
  7667. if (parseToken(lltok::rparen, "expected ')' here") ||
  7668. parseToken(lltok::rparen, "expected ')' here"))
  7669. return true;
  7670. return false;
  7671. }
  7672. /// FunctionSummary
  7673. /// ::= 'function' ':' '(' 'module' ':' ModuleReference ',' GVFlags
  7674. /// ',' 'insts' ':' UInt32 [',' OptionalFFlags]? [',' OptionalCalls]?
  7675. /// [',' OptionalTypeIdInfo]? [',' OptionalParamAccesses]?
  7676. /// [',' OptionalRefs]? ')'
  7677. bool LLParser::parseFunctionSummary(std::string Name, GlobalValue::GUID GUID,
  7678. unsigned ID) {
  7679. assert(Lex.getKind() == lltok::kw_function);
  7680. Lex.Lex();
  7681. StringRef ModulePath;
  7682. GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(
  7683. GlobalValue::ExternalLinkage, GlobalValue::DefaultVisibility,
  7684. /*NotEligibleToImport=*/false,
  7685. /*Live=*/false, /*IsLocal=*/false, /*CanAutoHide=*/false);
  7686. unsigned InstCount;
  7687. std::vector<FunctionSummary::EdgeTy> Calls;
  7688. FunctionSummary::TypeIdInfo TypeIdInfo;
  7689. std::vector<FunctionSummary::ParamAccess> ParamAccesses;
  7690. std::vector<ValueInfo> Refs;
  7691. std::vector<CallsiteInfo> Callsites;
  7692. std::vector<AllocInfo> Allocs;
  7693. // Default is all-zeros (conservative values).
  7694. FunctionSummary::FFlags FFlags = {};
  7695. if (parseToken(lltok::colon, "expected ':' here") ||
  7696. parseToken(lltok::lparen, "expected '(' here") ||
  7697. parseModuleReference(ModulePath) ||
  7698. parseToken(lltok::comma, "expected ',' here") || parseGVFlags(GVFlags) ||
  7699. parseToken(lltok::comma, "expected ',' here") ||
  7700. parseToken(lltok::kw_insts, "expected 'insts' here") ||
  7701. parseToken(lltok::colon, "expected ':' here") || parseUInt32(InstCount))
  7702. return true;
  7703. // parse optional fields
  7704. while (EatIfPresent(lltok::comma)) {
  7705. switch (Lex.getKind()) {
  7706. case lltok::kw_funcFlags:
  7707. if (parseOptionalFFlags(FFlags))
  7708. return true;
  7709. break;
  7710. case lltok::kw_calls:
  7711. if (parseOptionalCalls(Calls))
  7712. return true;
  7713. break;
  7714. case lltok::kw_typeIdInfo:
  7715. if (parseOptionalTypeIdInfo(TypeIdInfo))
  7716. return true;
  7717. break;
  7718. case lltok::kw_refs:
  7719. if (parseOptionalRefs(Refs))
  7720. return true;
  7721. break;
  7722. case lltok::kw_params:
  7723. if (parseOptionalParamAccesses(ParamAccesses))
  7724. return true;
  7725. break;
  7726. case lltok::kw_allocs:
  7727. if (parseOptionalAllocs(Allocs))
  7728. return true;
  7729. break;
  7730. case lltok::kw_callsites:
  7731. if (parseOptionalCallsites(Callsites))
  7732. return true;
  7733. break;
  7734. default:
  7735. return error(Lex.getLoc(), "expected optional function summary field");
  7736. }
  7737. }
  7738. if (parseToken(lltok::rparen, "expected ')' here"))
  7739. return true;
  7740. auto FS = std::make_unique<FunctionSummary>(
  7741. GVFlags, InstCount, FFlags, /*EntryCount=*/0, std::move(Refs),
  7742. std::move(Calls), std::move(TypeIdInfo.TypeTests),
  7743. std::move(TypeIdInfo.TypeTestAssumeVCalls),
  7744. std::move(TypeIdInfo.TypeCheckedLoadVCalls),
  7745. std::move(TypeIdInfo.TypeTestAssumeConstVCalls),
  7746. std::move(TypeIdInfo.TypeCheckedLoadConstVCalls),
  7747. std::move(ParamAccesses), std::move(Callsites), std::move(Allocs));
  7748. FS->setModulePath(ModulePath);
  7749. addGlobalValueToIndex(Name, GUID, (GlobalValue::LinkageTypes)GVFlags.Linkage,
  7750. ID, std::move(FS));
  7751. return false;
  7752. }
  7753. /// VariableSummary
  7754. /// ::= 'variable' ':' '(' 'module' ':' ModuleReference ',' GVFlags
  7755. /// [',' OptionalRefs]? ')'
  7756. bool LLParser::parseVariableSummary(std::string Name, GlobalValue::GUID GUID,
  7757. unsigned ID) {
  7758. assert(Lex.getKind() == lltok::kw_variable);
  7759. Lex.Lex();
  7760. StringRef ModulePath;
  7761. GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(
  7762. GlobalValue::ExternalLinkage, GlobalValue::DefaultVisibility,
  7763. /*NotEligibleToImport=*/false,
  7764. /*Live=*/false, /*IsLocal=*/false, /*CanAutoHide=*/false);
  7765. GlobalVarSummary::GVarFlags GVarFlags(/*ReadOnly*/ false,
  7766. /* WriteOnly */ false,
  7767. /* Constant */ false,
  7768. GlobalObject::VCallVisibilityPublic);
  7769. std::vector<ValueInfo> Refs;
  7770. VTableFuncList VTableFuncs;
  7771. if (parseToken(lltok::colon, "expected ':' here") ||
  7772. parseToken(lltok::lparen, "expected '(' here") ||
  7773. parseModuleReference(ModulePath) ||
  7774. parseToken(lltok::comma, "expected ',' here") || parseGVFlags(GVFlags) ||
  7775. parseToken(lltok::comma, "expected ',' here") ||
  7776. parseGVarFlags(GVarFlags))
  7777. return true;
  7778. // parse optional fields
  7779. while (EatIfPresent(lltok::comma)) {
  7780. switch (Lex.getKind()) {
  7781. case lltok::kw_vTableFuncs:
  7782. if (parseOptionalVTableFuncs(VTableFuncs))
  7783. return true;
  7784. break;
  7785. case lltok::kw_refs:
  7786. if (parseOptionalRefs(Refs))
  7787. return true;
  7788. break;
  7789. default:
  7790. return error(Lex.getLoc(), "expected optional variable summary field");
  7791. }
  7792. }
  7793. if (parseToken(lltok::rparen, "expected ')' here"))
  7794. return true;
  7795. auto GS =
  7796. std::make_unique<GlobalVarSummary>(GVFlags, GVarFlags, std::move(Refs));
  7797. GS->setModulePath(ModulePath);
  7798. GS->setVTableFuncs(std::move(VTableFuncs));
  7799. addGlobalValueToIndex(Name, GUID, (GlobalValue::LinkageTypes)GVFlags.Linkage,
  7800. ID, std::move(GS));
  7801. return false;
  7802. }
  7803. /// AliasSummary
  7804. /// ::= 'alias' ':' '(' 'module' ':' ModuleReference ',' GVFlags ','
  7805. /// 'aliasee' ':' GVReference ')'
  7806. bool LLParser::parseAliasSummary(std::string Name, GlobalValue::GUID GUID,
  7807. unsigned ID) {
  7808. assert(Lex.getKind() == lltok::kw_alias);
  7809. LocTy Loc = Lex.getLoc();
  7810. Lex.Lex();
  7811. StringRef ModulePath;
  7812. GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(
  7813. GlobalValue::ExternalLinkage, GlobalValue::DefaultVisibility,
  7814. /*NotEligibleToImport=*/false,
  7815. /*Live=*/false, /*IsLocal=*/false, /*CanAutoHide=*/false);
  7816. if (parseToken(lltok::colon, "expected ':' here") ||
  7817. parseToken(lltok::lparen, "expected '(' here") ||
  7818. parseModuleReference(ModulePath) ||
  7819. parseToken(lltok::comma, "expected ',' here") || parseGVFlags(GVFlags) ||
  7820. parseToken(lltok::comma, "expected ',' here") ||
  7821. parseToken(lltok::kw_aliasee, "expected 'aliasee' here") ||
  7822. parseToken(lltok::colon, "expected ':' here"))
  7823. return true;
  7824. ValueInfo AliaseeVI;
  7825. unsigned GVId;
  7826. if (parseGVReference(AliaseeVI, GVId))
  7827. return true;
  7828. if (parseToken(lltok::rparen, "expected ')' here"))
  7829. return true;
  7830. auto AS = std::make_unique<AliasSummary>(GVFlags);
  7831. AS->setModulePath(ModulePath);
  7832. // Record forward reference if the aliasee is not parsed yet.
  7833. if (AliaseeVI.getRef() == FwdVIRef) {
  7834. ForwardRefAliasees[GVId].emplace_back(AS.get(), Loc);
  7835. } else {
  7836. auto Summary = Index->findSummaryInModule(AliaseeVI, ModulePath);
  7837. assert(Summary && "Aliasee must be a definition");
  7838. AS->setAliasee(AliaseeVI, Summary);
  7839. }
  7840. addGlobalValueToIndex(Name, GUID, (GlobalValue::LinkageTypes)GVFlags.Linkage,
  7841. ID, std::move(AS));
  7842. return false;
  7843. }
  7844. /// Flag
  7845. /// ::= [0|1]
  7846. bool LLParser::parseFlag(unsigned &Val) {
  7847. if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
  7848. return tokError("expected integer");
  7849. Val = (unsigned)Lex.getAPSIntVal().getBoolValue();
  7850. Lex.Lex();
  7851. return false;
  7852. }
  7853. /// OptionalFFlags
  7854. /// := 'funcFlags' ':' '(' ['readNone' ':' Flag]?
  7855. /// [',' 'readOnly' ':' Flag]? [',' 'noRecurse' ':' Flag]?
  7856. /// [',' 'returnDoesNotAlias' ':' Flag]? ')'
  7857. /// [',' 'noInline' ':' Flag]? ')'
  7858. /// [',' 'alwaysInline' ':' Flag]? ')'
  7859. /// [',' 'noUnwind' ':' Flag]? ')'
  7860. /// [',' 'mayThrow' ':' Flag]? ')'
  7861. /// [',' 'hasUnknownCall' ':' Flag]? ')'
  7862. /// [',' 'mustBeUnreachable' ':' Flag]? ')'
  7863. bool LLParser::parseOptionalFFlags(FunctionSummary::FFlags &FFlags) {
  7864. assert(Lex.getKind() == lltok::kw_funcFlags);
  7865. Lex.Lex();
  7866. if (parseToken(lltok::colon, "expected ':' in funcFlags") ||
  7867. parseToken(lltok::lparen, "expected '(' in funcFlags"))
  7868. return true;
  7869. do {
  7870. unsigned Val = 0;
  7871. switch (Lex.getKind()) {
  7872. case lltok::kw_readNone:
  7873. Lex.Lex();
  7874. if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
  7875. return true;
  7876. FFlags.ReadNone = Val;
  7877. break;
  7878. case lltok::kw_readOnly:
  7879. Lex.Lex();
  7880. if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
  7881. return true;
  7882. FFlags.ReadOnly = Val;
  7883. break;
  7884. case lltok::kw_noRecurse:
  7885. Lex.Lex();
  7886. if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
  7887. return true;
  7888. FFlags.NoRecurse = Val;
  7889. break;
  7890. case lltok::kw_returnDoesNotAlias:
  7891. Lex.Lex();
  7892. if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
  7893. return true;
  7894. FFlags.ReturnDoesNotAlias = Val;
  7895. break;
  7896. case lltok::kw_noInline:
  7897. Lex.Lex();
  7898. if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
  7899. return true;
  7900. FFlags.NoInline = Val;
  7901. break;
  7902. case lltok::kw_alwaysInline:
  7903. Lex.Lex();
  7904. if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
  7905. return true;
  7906. FFlags.AlwaysInline = Val;
  7907. break;
  7908. case lltok::kw_noUnwind:
  7909. Lex.Lex();
  7910. if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
  7911. return true;
  7912. FFlags.NoUnwind = Val;
  7913. break;
  7914. case lltok::kw_mayThrow:
  7915. Lex.Lex();
  7916. if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
  7917. return true;
  7918. FFlags.MayThrow = Val;
  7919. break;
  7920. case lltok::kw_hasUnknownCall:
  7921. Lex.Lex();
  7922. if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
  7923. return true;
  7924. FFlags.HasUnknownCall = Val;
  7925. break;
  7926. case lltok::kw_mustBeUnreachable:
  7927. Lex.Lex();
  7928. if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
  7929. return true;
  7930. FFlags.MustBeUnreachable = Val;
  7931. break;
  7932. default:
  7933. return error(Lex.getLoc(), "expected function flag type");
  7934. }
  7935. } while (EatIfPresent(lltok::comma));
  7936. if (parseToken(lltok::rparen, "expected ')' in funcFlags"))
  7937. return true;
  7938. return false;
  7939. }
  7940. /// OptionalCalls
  7941. /// := 'calls' ':' '(' Call [',' Call]* ')'
  7942. /// Call ::= '(' 'callee' ':' GVReference
  7943. /// [( ',' 'hotness' ':' Hotness | ',' 'relbf' ':' UInt32 )]? ')'
  7944. bool LLParser::parseOptionalCalls(std::vector<FunctionSummary::EdgeTy> &Calls) {
  7945. assert(Lex.getKind() == lltok::kw_calls);
  7946. Lex.Lex();
  7947. if (parseToken(lltok::colon, "expected ':' in calls") ||
  7948. parseToken(lltok::lparen, "expected '(' in calls"))
  7949. return true;
  7950. IdToIndexMapType IdToIndexMap;
  7951. // parse each call edge
  7952. do {
  7953. ValueInfo VI;
  7954. if (parseToken(lltok::lparen, "expected '(' in call") ||
  7955. parseToken(lltok::kw_callee, "expected 'callee' in call") ||
  7956. parseToken(lltok::colon, "expected ':'"))
  7957. return true;
  7958. LocTy Loc = Lex.getLoc();
  7959. unsigned GVId;
  7960. if (parseGVReference(VI, GVId))
  7961. return true;
  7962. CalleeInfo::HotnessType Hotness = CalleeInfo::HotnessType::Unknown;
  7963. unsigned RelBF = 0;
  7964. if (EatIfPresent(lltok::comma)) {
  7965. // Expect either hotness or relbf
  7966. if (EatIfPresent(lltok::kw_hotness)) {
  7967. if (parseToken(lltok::colon, "expected ':'") || parseHotness(Hotness))
  7968. return true;
  7969. } else {
  7970. if (parseToken(lltok::kw_relbf, "expected relbf") ||
  7971. parseToken(lltok::colon, "expected ':'") || parseUInt32(RelBF))
  7972. return true;
  7973. }
  7974. }
  7975. // Keep track of the Call array index needing a forward reference.
  7976. // We will save the location of the ValueInfo needing an update, but
  7977. // can only do so once the std::vector is finalized.
  7978. if (VI.getRef() == FwdVIRef)
  7979. IdToIndexMap[GVId].push_back(std::make_pair(Calls.size(), Loc));
  7980. Calls.push_back(FunctionSummary::EdgeTy{VI, CalleeInfo(Hotness, RelBF)});
  7981. if (parseToken(lltok::rparen, "expected ')' in call"))
  7982. return true;
  7983. } while (EatIfPresent(lltok::comma));
  7984. // Now that the Calls vector is finalized, it is safe to save the locations
  7985. // of any forward GV references that need updating later.
  7986. for (auto I : IdToIndexMap) {
  7987. auto &Infos = ForwardRefValueInfos[I.first];
  7988. for (auto P : I.second) {
  7989. assert(Calls[P.first].first.getRef() == FwdVIRef &&
  7990. "Forward referenced ValueInfo expected to be empty");
  7991. Infos.emplace_back(&Calls[P.first].first, P.second);
  7992. }
  7993. }
  7994. if (parseToken(lltok::rparen, "expected ')' in calls"))
  7995. return true;
  7996. return false;
  7997. }
  7998. /// Hotness
  7999. /// := ('unknown'|'cold'|'none'|'hot'|'critical')
  8000. bool LLParser::parseHotness(CalleeInfo::HotnessType &Hotness) {
  8001. switch (Lex.getKind()) {
  8002. case lltok::kw_unknown:
  8003. Hotness = CalleeInfo::HotnessType::Unknown;
  8004. break;
  8005. case lltok::kw_cold:
  8006. Hotness = CalleeInfo::HotnessType::Cold;
  8007. break;
  8008. case lltok::kw_none:
  8009. Hotness = CalleeInfo::HotnessType::None;
  8010. break;
  8011. case lltok::kw_hot:
  8012. Hotness = CalleeInfo::HotnessType::Hot;
  8013. break;
  8014. case lltok::kw_critical:
  8015. Hotness = CalleeInfo::HotnessType::Critical;
  8016. break;
  8017. default:
  8018. return error(Lex.getLoc(), "invalid call edge hotness");
  8019. }
  8020. Lex.Lex();
  8021. return false;
  8022. }
  8023. /// OptionalVTableFuncs
  8024. /// := 'vTableFuncs' ':' '(' VTableFunc [',' VTableFunc]* ')'
  8025. /// VTableFunc ::= '(' 'virtFunc' ':' GVReference ',' 'offset' ':' UInt64 ')'
  8026. bool LLParser::parseOptionalVTableFuncs(VTableFuncList &VTableFuncs) {
  8027. assert(Lex.getKind() == lltok::kw_vTableFuncs);
  8028. Lex.Lex();
  8029. if (parseToken(lltok::colon, "expected ':' in vTableFuncs") ||
  8030. parseToken(lltok::lparen, "expected '(' in vTableFuncs"))
  8031. return true;
  8032. IdToIndexMapType IdToIndexMap;
  8033. // parse each virtual function pair
  8034. do {
  8035. ValueInfo VI;
  8036. if (parseToken(lltok::lparen, "expected '(' in vTableFunc") ||
  8037. parseToken(lltok::kw_virtFunc, "expected 'callee' in vTableFunc") ||
  8038. parseToken(lltok::colon, "expected ':'"))
  8039. return true;
  8040. LocTy Loc = Lex.getLoc();
  8041. unsigned GVId;
  8042. if (parseGVReference(VI, GVId))
  8043. return true;
  8044. uint64_t Offset;
  8045. if (parseToken(lltok::comma, "expected comma") ||
  8046. parseToken(lltok::kw_offset, "expected offset") ||
  8047. parseToken(lltok::colon, "expected ':'") || parseUInt64(Offset))
  8048. return true;
  8049. // Keep track of the VTableFuncs array index needing a forward reference.
  8050. // We will save the location of the ValueInfo needing an update, but
  8051. // can only do so once the std::vector is finalized.
  8052. if (VI == EmptyVI)
  8053. IdToIndexMap[GVId].push_back(std::make_pair(VTableFuncs.size(), Loc));
  8054. VTableFuncs.push_back({VI, Offset});
  8055. if (parseToken(lltok::rparen, "expected ')' in vTableFunc"))
  8056. return true;
  8057. } while (EatIfPresent(lltok::comma));
  8058. // Now that the VTableFuncs vector is finalized, it is safe to save the
  8059. // locations of any forward GV references that need updating later.
  8060. for (auto I : IdToIndexMap) {
  8061. auto &Infos = ForwardRefValueInfos[I.first];
  8062. for (auto P : I.second) {
  8063. assert(VTableFuncs[P.first].FuncVI == EmptyVI &&
  8064. "Forward referenced ValueInfo expected to be empty");
  8065. Infos.emplace_back(&VTableFuncs[P.first].FuncVI, P.second);
  8066. }
  8067. }
  8068. if (parseToken(lltok::rparen, "expected ')' in vTableFuncs"))
  8069. return true;
  8070. return false;
  8071. }
  8072. /// ParamNo := 'param' ':' UInt64
  8073. bool LLParser::parseParamNo(uint64_t &ParamNo) {
  8074. if (parseToken(lltok::kw_param, "expected 'param' here") ||
  8075. parseToken(lltok::colon, "expected ':' here") || parseUInt64(ParamNo))
  8076. return true;
  8077. return false;
  8078. }
  8079. /// ParamAccessOffset := 'offset' ':' '[' APSINTVAL ',' APSINTVAL ']'
  8080. bool LLParser::parseParamAccessOffset(ConstantRange &Range) {
  8081. APSInt Lower;
  8082. APSInt Upper;
  8083. auto ParseAPSInt = [&](APSInt &Val) {
  8084. if (Lex.getKind() != lltok::APSInt)
  8085. return tokError("expected integer");
  8086. Val = Lex.getAPSIntVal();
  8087. Val = Val.extOrTrunc(FunctionSummary::ParamAccess::RangeWidth);
  8088. Val.setIsSigned(true);
  8089. Lex.Lex();
  8090. return false;
  8091. };
  8092. if (parseToken(lltok::kw_offset, "expected 'offset' here") ||
  8093. parseToken(lltok::colon, "expected ':' here") ||
  8094. parseToken(lltok::lsquare, "expected '[' here") || ParseAPSInt(Lower) ||
  8095. parseToken(lltok::comma, "expected ',' here") || ParseAPSInt(Upper) ||
  8096. parseToken(lltok::rsquare, "expected ']' here"))
  8097. return true;
  8098. ++Upper;
  8099. Range =
  8100. (Lower == Upper && !Lower.isMaxValue())
  8101. ? ConstantRange::getEmpty(FunctionSummary::ParamAccess::RangeWidth)
  8102. : ConstantRange(Lower, Upper);
  8103. return false;
  8104. }
  8105. /// ParamAccessCall
  8106. /// := '(' 'callee' ':' GVReference ',' ParamNo ',' ParamAccessOffset ')'
  8107. bool LLParser::parseParamAccessCall(FunctionSummary::ParamAccess::Call &Call,
  8108. IdLocListType &IdLocList) {
  8109. if (parseToken(lltok::lparen, "expected '(' here") ||
  8110. parseToken(lltok::kw_callee, "expected 'callee' here") ||
  8111. parseToken(lltok::colon, "expected ':' here"))
  8112. return true;
  8113. unsigned GVId;
  8114. ValueInfo VI;
  8115. LocTy Loc = Lex.getLoc();
  8116. if (parseGVReference(VI, GVId))
  8117. return true;
  8118. Call.Callee = VI;
  8119. IdLocList.emplace_back(GVId, Loc);
  8120. if (parseToken(lltok::comma, "expected ',' here") ||
  8121. parseParamNo(Call.ParamNo) ||
  8122. parseToken(lltok::comma, "expected ',' here") ||
  8123. parseParamAccessOffset(Call.Offsets))
  8124. return true;
  8125. if (parseToken(lltok::rparen, "expected ')' here"))
  8126. return true;
  8127. return false;
  8128. }
  8129. /// ParamAccess
  8130. /// := '(' ParamNo ',' ParamAccessOffset [',' OptionalParamAccessCalls]? ')'
  8131. /// OptionalParamAccessCalls := '(' Call [',' Call]* ')'
  8132. bool LLParser::parseParamAccess(FunctionSummary::ParamAccess &Param,
  8133. IdLocListType &IdLocList) {
  8134. if (parseToken(lltok::lparen, "expected '(' here") ||
  8135. parseParamNo(Param.ParamNo) ||
  8136. parseToken(lltok::comma, "expected ',' here") ||
  8137. parseParamAccessOffset(Param.Use))
  8138. return true;
  8139. if (EatIfPresent(lltok::comma)) {
  8140. if (parseToken(lltok::kw_calls, "expected 'calls' here") ||
  8141. parseToken(lltok::colon, "expected ':' here") ||
  8142. parseToken(lltok::lparen, "expected '(' here"))
  8143. return true;
  8144. do {
  8145. FunctionSummary::ParamAccess::Call Call;
  8146. if (parseParamAccessCall(Call, IdLocList))
  8147. return true;
  8148. Param.Calls.push_back(Call);
  8149. } while (EatIfPresent(lltok::comma));
  8150. if (parseToken(lltok::rparen, "expected ')' here"))
  8151. return true;
  8152. }
  8153. if (parseToken(lltok::rparen, "expected ')' here"))
  8154. return true;
  8155. return false;
  8156. }
  8157. /// OptionalParamAccesses
  8158. /// := 'params' ':' '(' ParamAccess [',' ParamAccess]* ')'
  8159. bool LLParser::parseOptionalParamAccesses(
  8160. std::vector<FunctionSummary::ParamAccess> &Params) {
  8161. assert(Lex.getKind() == lltok::kw_params);
  8162. Lex.Lex();
  8163. if (parseToken(lltok::colon, "expected ':' here") ||
  8164. parseToken(lltok::lparen, "expected '(' here"))
  8165. return true;
  8166. IdLocListType VContexts;
  8167. size_t CallsNum = 0;
  8168. do {
  8169. FunctionSummary::ParamAccess ParamAccess;
  8170. if (parseParamAccess(ParamAccess, VContexts))
  8171. return true;
  8172. CallsNum += ParamAccess.Calls.size();
  8173. assert(VContexts.size() == CallsNum);
  8174. (void)CallsNum;
  8175. Params.emplace_back(std::move(ParamAccess));
  8176. } while (EatIfPresent(lltok::comma));
  8177. if (parseToken(lltok::rparen, "expected ')' here"))
  8178. return true;
  8179. // Now that the Params is finalized, it is safe to save the locations
  8180. // of any forward GV references that need updating later.
  8181. IdLocListType::const_iterator ItContext = VContexts.begin();
  8182. for (auto &PA : Params) {
  8183. for (auto &C : PA.Calls) {
  8184. if (C.Callee.getRef() == FwdVIRef)
  8185. ForwardRefValueInfos[ItContext->first].emplace_back(&C.Callee,
  8186. ItContext->second);
  8187. ++ItContext;
  8188. }
  8189. }
  8190. assert(ItContext == VContexts.end());
  8191. return false;
  8192. }
  8193. /// OptionalRefs
  8194. /// := 'refs' ':' '(' GVReference [',' GVReference]* ')'
  8195. bool LLParser::parseOptionalRefs(std::vector<ValueInfo> &Refs) {
  8196. assert(Lex.getKind() == lltok::kw_refs);
  8197. Lex.Lex();
  8198. if (parseToken(lltok::colon, "expected ':' in refs") ||
  8199. parseToken(lltok::lparen, "expected '(' in refs"))
  8200. return true;
  8201. struct ValueContext {
  8202. ValueInfo VI;
  8203. unsigned GVId;
  8204. LocTy Loc;
  8205. };
  8206. std::vector<ValueContext> VContexts;
  8207. // parse each ref edge
  8208. do {
  8209. ValueContext VC;
  8210. VC.Loc = Lex.getLoc();
  8211. if (parseGVReference(VC.VI, VC.GVId))
  8212. return true;
  8213. VContexts.push_back(VC);
  8214. } while (EatIfPresent(lltok::comma));
  8215. // Sort value contexts so that ones with writeonly
  8216. // and readonly ValueInfo are at the end of VContexts vector.
  8217. // See FunctionSummary::specialRefCounts()
  8218. llvm::sort(VContexts, [](const ValueContext &VC1, const ValueContext &VC2) {
  8219. return VC1.VI.getAccessSpecifier() < VC2.VI.getAccessSpecifier();
  8220. });
  8221. IdToIndexMapType IdToIndexMap;
  8222. for (auto &VC : VContexts) {
  8223. // Keep track of the Refs array index needing a forward reference.
  8224. // We will save the location of the ValueInfo needing an update, but
  8225. // can only do so once the std::vector is finalized.
  8226. if (VC.VI.getRef() == FwdVIRef)
  8227. IdToIndexMap[VC.GVId].push_back(std::make_pair(Refs.size(), VC.Loc));
  8228. Refs.push_back(VC.VI);
  8229. }
  8230. // Now that the Refs vector is finalized, it is safe to save the locations
  8231. // of any forward GV references that need updating later.
  8232. for (auto I : IdToIndexMap) {
  8233. auto &Infos = ForwardRefValueInfos[I.first];
  8234. for (auto P : I.second) {
  8235. assert(Refs[P.first].getRef() == FwdVIRef &&
  8236. "Forward referenced ValueInfo expected to be empty");
  8237. Infos.emplace_back(&Refs[P.first], P.second);
  8238. }
  8239. }
  8240. if (parseToken(lltok::rparen, "expected ')' in refs"))
  8241. return true;
  8242. return false;
  8243. }
  8244. /// OptionalTypeIdInfo
  8245. /// := 'typeidinfo' ':' '(' [',' TypeTests]? [',' TypeTestAssumeVCalls]?
  8246. /// [',' TypeCheckedLoadVCalls]? [',' TypeTestAssumeConstVCalls]?
  8247. /// [',' TypeCheckedLoadConstVCalls]? ')'
  8248. bool LLParser::parseOptionalTypeIdInfo(
  8249. FunctionSummary::TypeIdInfo &TypeIdInfo) {
  8250. assert(Lex.getKind() == lltok::kw_typeIdInfo);
  8251. Lex.Lex();
  8252. if (parseToken(lltok::colon, "expected ':' here") ||
  8253. parseToken(lltok::lparen, "expected '(' in typeIdInfo"))
  8254. return true;
  8255. do {
  8256. switch (Lex.getKind()) {
  8257. case lltok::kw_typeTests:
  8258. if (parseTypeTests(TypeIdInfo.TypeTests))
  8259. return true;
  8260. break;
  8261. case lltok::kw_typeTestAssumeVCalls:
  8262. if (parseVFuncIdList(lltok::kw_typeTestAssumeVCalls,
  8263. TypeIdInfo.TypeTestAssumeVCalls))
  8264. return true;
  8265. break;
  8266. case lltok::kw_typeCheckedLoadVCalls:
  8267. if (parseVFuncIdList(lltok::kw_typeCheckedLoadVCalls,
  8268. TypeIdInfo.TypeCheckedLoadVCalls))
  8269. return true;
  8270. break;
  8271. case lltok::kw_typeTestAssumeConstVCalls:
  8272. if (parseConstVCallList(lltok::kw_typeTestAssumeConstVCalls,
  8273. TypeIdInfo.TypeTestAssumeConstVCalls))
  8274. return true;
  8275. break;
  8276. case lltok::kw_typeCheckedLoadConstVCalls:
  8277. if (parseConstVCallList(lltok::kw_typeCheckedLoadConstVCalls,
  8278. TypeIdInfo.TypeCheckedLoadConstVCalls))
  8279. return true;
  8280. break;
  8281. default:
  8282. return error(Lex.getLoc(), "invalid typeIdInfo list type");
  8283. }
  8284. } while (EatIfPresent(lltok::comma));
  8285. if (parseToken(lltok::rparen, "expected ')' in typeIdInfo"))
  8286. return true;
  8287. return false;
  8288. }
  8289. /// TypeTests
  8290. /// ::= 'typeTests' ':' '(' (SummaryID | UInt64)
  8291. /// [',' (SummaryID | UInt64)]* ')'
  8292. bool LLParser::parseTypeTests(std::vector<GlobalValue::GUID> &TypeTests) {
  8293. assert(Lex.getKind() == lltok::kw_typeTests);
  8294. Lex.Lex();
  8295. if (parseToken(lltok::colon, "expected ':' here") ||
  8296. parseToken(lltok::lparen, "expected '(' in typeIdInfo"))
  8297. return true;
  8298. IdToIndexMapType IdToIndexMap;
  8299. do {
  8300. GlobalValue::GUID GUID = 0;
  8301. if (Lex.getKind() == lltok::SummaryID) {
  8302. unsigned ID = Lex.getUIntVal();
  8303. LocTy Loc = Lex.getLoc();
  8304. // Keep track of the TypeTests array index needing a forward reference.
  8305. // We will save the location of the GUID needing an update, but
  8306. // can only do so once the std::vector is finalized.
  8307. IdToIndexMap[ID].push_back(std::make_pair(TypeTests.size(), Loc));
  8308. Lex.Lex();
  8309. } else if (parseUInt64(GUID))
  8310. return true;
  8311. TypeTests.push_back(GUID);
  8312. } while (EatIfPresent(lltok::comma));
  8313. // Now that the TypeTests vector is finalized, it is safe to save the
  8314. // locations of any forward GV references that need updating later.
  8315. for (auto I : IdToIndexMap) {
  8316. auto &Ids = ForwardRefTypeIds[I.first];
  8317. for (auto P : I.second) {
  8318. assert(TypeTests[P.first] == 0 &&
  8319. "Forward referenced type id GUID expected to be 0");
  8320. Ids.emplace_back(&TypeTests[P.first], P.second);
  8321. }
  8322. }
  8323. if (parseToken(lltok::rparen, "expected ')' in typeIdInfo"))
  8324. return true;
  8325. return false;
  8326. }
  8327. /// VFuncIdList
  8328. /// ::= Kind ':' '(' VFuncId [',' VFuncId]* ')'
  8329. bool LLParser::parseVFuncIdList(
  8330. lltok::Kind Kind, std::vector<FunctionSummary::VFuncId> &VFuncIdList) {
  8331. assert(Lex.getKind() == Kind);
  8332. Lex.Lex();
  8333. if (parseToken(lltok::colon, "expected ':' here") ||
  8334. parseToken(lltok::lparen, "expected '(' here"))
  8335. return true;
  8336. IdToIndexMapType IdToIndexMap;
  8337. do {
  8338. FunctionSummary::VFuncId VFuncId;
  8339. if (parseVFuncId(VFuncId, IdToIndexMap, VFuncIdList.size()))
  8340. return true;
  8341. VFuncIdList.push_back(VFuncId);
  8342. } while (EatIfPresent(lltok::comma));
  8343. if (parseToken(lltok::rparen, "expected ')' here"))
  8344. return true;
  8345. // Now that the VFuncIdList vector is finalized, it is safe to save the
  8346. // locations of any forward GV references that need updating later.
  8347. for (auto I : IdToIndexMap) {
  8348. auto &Ids = ForwardRefTypeIds[I.first];
  8349. for (auto P : I.second) {
  8350. assert(VFuncIdList[P.first].GUID == 0 &&
  8351. "Forward referenced type id GUID expected to be 0");
  8352. Ids.emplace_back(&VFuncIdList[P.first].GUID, P.second);
  8353. }
  8354. }
  8355. return false;
  8356. }
  8357. /// ConstVCallList
  8358. /// ::= Kind ':' '(' ConstVCall [',' ConstVCall]* ')'
  8359. bool LLParser::parseConstVCallList(
  8360. lltok::Kind Kind,
  8361. std::vector<FunctionSummary::ConstVCall> &ConstVCallList) {
  8362. assert(Lex.getKind() == Kind);
  8363. Lex.Lex();
  8364. if (parseToken(lltok::colon, "expected ':' here") ||
  8365. parseToken(lltok::lparen, "expected '(' here"))
  8366. return true;
  8367. IdToIndexMapType IdToIndexMap;
  8368. do {
  8369. FunctionSummary::ConstVCall ConstVCall;
  8370. if (parseConstVCall(ConstVCall, IdToIndexMap, ConstVCallList.size()))
  8371. return true;
  8372. ConstVCallList.push_back(ConstVCall);
  8373. } while (EatIfPresent(lltok::comma));
  8374. if (parseToken(lltok::rparen, "expected ')' here"))
  8375. return true;
  8376. // Now that the ConstVCallList vector is finalized, it is safe to save the
  8377. // locations of any forward GV references that need updating later.
  8378. for (auto I : IdToIndexMap) {
  8379. auto &Ids = ForwardRefTypeIds[I.first];
  8380. for (auto P : I.second) {
  8381. assert(ConstVCallList[P.first].VFunc.GUID == 0 &&
  8382. "Forward referenced type id GUID expected to be 0");
  8383. Ids.emplace_back(&ConstVCallList[P.first].VFunc.GUID, P.second);
  8384. }
  8385. }
  8386. return false;
  8387. }
  8388. /// ConstVCall
  8389. /// ::= '(' VFuncId ',' Args ')'
  8390. bool LLParser::parseConstVCall(FunctionSummary::ConstVCall &ConstVCall,
  8391. IdToIndexMapType &IdToIndexMap, unsigned Index) {
  8392. if (parseToken(lltok::lparen, "expected '(' here") ||
  8393. parseVFuncId(ConstVCall.VFunc, IdToIndexMap, Index))
  8394. return true;
  8395. if (EatIfPresent(lltok::comma))
  8396. if (parseArgs(ConstVCall.Args))
  8397. return true;
  8398. if (parseToken(lltok::rparen, "expected ')' here"))
  8399. return true;
  8400. return false;
  8401. }
  8402. /// VFuncId
  8403. /// ::= 'vFuncId' ':' '(' (SummaryID | 'guid' ':' UInt64) ','
  8404. /// 'offset' ':' UInt64 ')'
  8405. bool LLParser::parseVFuncId(FunctionSummary::VFuncId &VFuncId,
  8406. IdToIndexMapType &IdToIndexMap, unsigned Index) {
  8407. assert(Lex.getKind() == lltok::kw_vFuncId);
  8408. Lex.Lex();
  8409. if (parseToken(lltok::colon, "expected ':' here") ||
  8410. parseToken(lltok::lparen, "expected '(' here"))
  8411. return true;
  8412. if (Lex.getKind() == lltok::SummaryID) {
  8413. VFuncId.GUID = 0;
  8414. unsigned ID = Lex.getUIntVal();
  8415. LocTy Loc = Lex.getLoc();
  8416. // Keep track of the array index needing a forward reference.
  8417. // We will save the location of the GUID needing an update, but
  8418. // can only do so once the caller's std::vector is finalized.
  8419. IdToIndexMap[ID].push_back(std::make_pair(Index, Loc));
  8420. Lex.Lex();
  8421. } else if (parseToken(lltok::kw_guid, "expected 'guid' here") ||
  8422. parseToken(lltok::colon, "expected ':' here") ||
  8423. parseUInt64(VFuncId.GUID))
  8424. return true;
  8425. if (parseToken(lltok::comma, "expected ',' here") ||
  8426. parseToken(lltok::kw_offset, "expected 'offset' here") ||
  8427. parseToken(lltok::colon, "expected ':' here") ||
  8428. parseUInt64(VFuncId.Offset) ||
  8429. parseToken(lltok::rparen, "expected ')' here"))
  8430. return true;
  8431. return false;
  8432. }
  8433. /// GVFlags
  8434. /// ::= 'flags' ':' '(' 'linkage' ':' OptionalLinkageAux ','
  8435. /// 'visibility' ':' Flag 'notEligibleToImport' ':' Flag ','
  8436. /// 'live' ':' Flag ',' 'dsoLocal' ':' Flag ','
  8437. /// 'canAutoHide' ':' Flag ',' ')'
  8438. bool LLParser::parseGVFlags(GlobalValueSummary::GVFlags &GVFlags) {
  8439. assert(Lex.getKind() == lltok::kw_flags);
  8440. Lex.Lex();
  8441. if (parseToken(lltok::colon, "expected ':' here") ||
  8442. parseToken(lltok::lparen, "expected '(' here"))
  8443. return true;
  8444. do {
  8445. unsigned Flag = 0;
  8446. switch (Lex.getKind()) {
  8447. case lltok::kw_linkage:
  8448. Lex.Lex();
  8449. if (parseToken(lltok::colon, "expected ':'"))
  8450. return true;
  8451. bool HasLinkage;
  8452. GVFlags.Linkage = parseOptionalLinkageAux(Lex.getKind(), HasLinkage);
  8453. assert(HasLinkage && "Linkage not optional in summary entry");
  8454. Lex.Lex();
  8455. break;
  8456. case lltok::kw_visibility:
  8457. Lex.Lex();
  8458. if (parseToken(lltok::colon, "expected ':'"))
  8459. return true;
  8460. parseOptionalVisibility(Flag);
  8461. GVFlags.Visibility = Flag;
  8462. break;
  8463. case lltok::kw_notEligibleToImport:
  8464. Lex.Lex();
  8465. if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag))
  8466. return true;
  8467. GVFlags.NotEligibleToImport = Flag;
  8468. break;
  8469. case lltok::kw_live:
  8470. Lex.Lex();
  8471. if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag))
  8472. return true;
  8473. GVFlags.Live = Flag;
  8474. break;
  8475. case lltok::kw_dsoLocal:
  8476. Lex.Lex();
  8477. if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag))
  8478. return true;
  8479. GVFlags.DSOLocal = Flag;
  8480. break;
  8481. case lltok::kw_canAutoHide:
  8482. Lex.Lex();
  8483. if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag))
  8484. return true;
  8485. GVFlags.CanAutoHide = Flag;
  8486. break;
  8487. default:
  8488. return error(Lex.getLoc(), "expected gv flag type");
  8489. }
  8490. } while (EatIfPresent(lltok::comma));
  8491. if (parseToken(lltok::rparen, "expected ')' here"))
  8492. return true;
  8493. return false;
  8494. }
  8495. /// GVarFlags
  8496. /// ::= 'varFlags' ':' '(' 'readonly' ':' Flag
  8497. /// ',' 'writeonly' ':' Flag
  8498. /// ',' 'constant' ':' Flag ')'
  8499. bool LLParser::parseGVarFlags(GlobalVarSummary::GVarFlags &GVarFlags) {
  8500. assert(Lex.getKind() == lltok::kw_varFlags);
  8501. Lex.Lex();
  8502. if (parseToken(lltok::colon, "expected ':' here") ||
  8503. parseToken(lltok::lparen, "expected '(' here"))
  8504. return true;
  8505. auto ParseRest = [this](unsigned int &Val) {
  8506. Lex.Lex();
  8507. if (parseToken(lltok::colon, "expected ':'"))
  8508. return true;
  8509. return parseFlag(Val);
  8510. };
  8511. do {
  8512. unsigned Flag = 0;
  8513. switch (Lex.getKind()) {
  8514. case lltok::kw_readonly:
  8515. if (ParseRest(Flag))
  8516. return true;
  8517. GVarFlags.MaybeReadOnly = Flag;
  8518. break;
  8519. case lltok::kw_writeonly:
  8520. if (ParseRest(Flag))
  8521. return true;
  8522. GVarFlags.MaybeWriteOnly = Flag;
  8523. break;
  8524. case lltok::kw_constant:
  8525. if (ParseRest(Flag))
  8526. return true;
  8527. GVarFlags.Constant = Flag;
  8528. break;
  8529. case lltok::kw_vcall_visibility:
  8530. if (ParseRest(Flag))
  8531. return true;
  8532. GVarFlags.VCallVisibility = Flag;
  8533. break;
  8534. default:
  8535. return error(Lex.getLoc(), "expected gvar flag type");
  8536. }
  8537. } while (EatIfPresent(lltok::comma));
  8538. return parseToken(lltok::rparen, "expected ')' here");
  8539. }
  8540. /// ModuleReference
  8541. /// ::= 'module' ':' UInt
  8542. bool LLParser::parseModuleReference(StringRef &ModulePath) {
  8543. // parse module id.
  8544. if (parseToken(lltok::kw_module, "expected 'module' here") ||
  8545. parseToken(lltok::colon, "expected ':' here") ||
  8546. parseToken(lltok::SummaryID, "expected module ID"))
  8547. return true;
  8548. unsigned ModuleID = Lex.getUIntVal();
  8549. auto I = ModuleIdMap.find(ModuleID);
  8550. // We should have already parsed all module IDs
  8551. assert(I != ModuleIdMap.end());
  8552. ModulePath = I->second;
  8553. return false;
  8554. }
  8555. /// GVReference
  8556. /// ::= SummaryID
  8557. bool LLParser::parseGVReference(ValueInfo &VI, unsigned &GVId) {
  8558. bool WriteOnly = false, ReadOnly = EatIfPresent(lltok::kw_readonly);
  8559. if (!ReadOnly)
  8560. WriteOnly = EatIfPresent(lltok::kw_writeonly);
  8561. if (parseToken(lltok::SummaryID, "expected GV ID"))
  8562. return true;
  8563. GVId = Lex.getUIntVal();
  8564. // Check if we already have a VI for this GV
  8565. if (GVId < NumberedValueInfos.size()) {
  8566. assert(NumberedValueInfos[GVId].getRef() != FwdVIRef);
  8567. VI = NumberedValueInfos[GVId];
  8568. } else
  8569. // We will create a forward reference to the stored location.
  8570. VI = ValueInfo(false, FwdVIRef);
  8571. if (ReadOnly)
  8572. VI.setReadOnly();
  8573. if (WriteOnly)
  8574. VI.setWriteOnly();
  8575. return false;
  8576. }
  8577. /// OptionalAllocs
  8578. /// := 'allocs' ':' '(' Alloc [',' Alloc]* ')'
  8579. /// Alloc ::= '(' 'versions' ':' '(' Version [',' Version]* ')'
  8580. /// ',' MemProfs ')'
  8581. /// Version ::= UInt32
  8582. bool LLParser::parseOptionalAllocs(std::vector<AllocInfo> &Allocs) {
  8583. assert(Lex.getKind() == lltok::kw_allocs);
  8584. Lex.Lex();
  8585. if (parseToken(lltok::colon, "expected ':' in allocs") ||
  8586. parseToken(lltok::lparen, "expected '(' in allocs"))
  8587. return true;
  8588. // parse each alloc
  8589. do {
  8590. if (parseToken(lltok::lparen, "expected '(' in alloc") ||
  8591. parseToken(lltok::kw_versions, "expected 'versions' in alloc") ||
  8592. parseToken(lltok::colon, "expected ':'") ||
  8593. parseToken(lltok::lparen, "expected '(' in versions"))
  8594. return true;
  8595. SmallVector<uint8_t> Versions;
  8596. do {
  8597. uint8_t V = 0;
  8598. if (parseAllocType(V))
  8599. return true;
  8600. Versions.push_back(V);
  8601. } while (EatIfPresent(lltok::comma));
  8602. if (parseToken(lltok::rparen, "expected ')' in versions") ||
  8603. parseToken(lltok::comma, "expected ',' in alloc"))
  8604. return true;
  8605. std::vector<MIBInfo> MIBs;
  8606. if (parseMemProfs(MIBs))
  8607. return true;
  8608. Allocs.push_back({Versions, MIBs});
  8609. if (parseToken(lltok::rparen, "expected ')' in alloc"))
  8610. return true;
  8611. } while (EatIfPresent(lltok::comma));
  8612. if (parseToken(lltok::rparen, "expected ')' in allocs"))
  8613. return true;
  8614. return false;
  8615. }
  8616. /// MemProfs
  8617. /// := 'memProf' ':' '(' MemProf [',' MemProf]* ')'
  8618. /// MemProf ::= '(' 'type' ':' AllocType
  8619. /// ',' 'stackIds' ':' '(' StackId [',' StackId]* ')' ')'
  8620. /// StackId ::= UInt64
  8621. bool LLParser::parseMemProfs(std::vector<MIBInfo> &MIBs) {
  8622. assert(Lex.getKind() == lltok::kw_memProf);
  8623. Lex.Lex();
  8624. if (parseToken(lltok::colon, "expected ':' in memprof") ||
  8625. parseToken(lltok::lparen, "expected '(' in memprof"))
  8626. return true;
  8627. // parse each MIB
  8628. do {
  8629. if (parseToken(lltok::lparen, "expected '(' in memprof") ||
  8630. parseToken(lltok::kw_type, "expected 'type' in memprof") ||
  8631. parseToken(lltok::colon, "expected ':'"))
  8632. return true;
  8633. uint8_t AllocType;
  8634. if (parseAllocType(AllocType))
  8635. return true;
  8636. if (parseToken(lltok::comma, "expected ',' in memprof") ||
  8637. parseToken(lltok::kw_stackIds, "expected 'stackIds' in memprof") ||
  8638. parseToken(lltok::colon, "expected ':'") ||
  8639. parseToken(lltok::lparen, "expected '(' in stackIds"))
  8640. return true;
  8641. SmallVector<unsigned> StackIdIndices;
  8642. do {
  8643. uint64_t StackId = 0;
  8644. if (parseUInt64(StackId))
  8645. return true;
  8646. StackIdIndices.push_back(Index->addOrGetStackIdIndex(StackId));
  8647. } while (EatIfPresent(lltok::comma));
  8648. if (parseToken(lltok::rparen, "expected ')' in stackIds"))
  8649. return true;
  8650. MIBs.push_back({(AllocationType)AllocType, StackIdIndices});
  8651. if (parseToken(lltok::rparen, "expected ')' in memprof"))
  8652. return true;
  8653. } while (EatIfPresent(lltok::comma));
  8654. if (parseToken(lltok::rparen, "expected ')' in memprof"))
  8655. return true;
  8656. return false;
  8657. }
  8658. /// AllocType
  8659. /// := ('none'|'notcold'|'cold'|'notcoldandcold')
  8660. bool LLParser::parseAllocType(uint8_t &AllocType) {
  8661. switch (Lex.getKind()) {
  8662. case lltok::kw_none:
  8663. AllocType = (uint8_t)AllocationType::None;
  8664. break;
  8665. case lltok::kw_notcold:
  8666. AllocType = (uint8_t)AllocationType::NotCold;
  8667. break;
  8668. case lltok::kw_cold:
  8669. AllocType = (uint8_t)AllocationType::Cold;
  8670. break;
  8671. case lltok::kw_notcoldandcold:
  8672. AllocType =
  8673. (uint8_t)AllocationType::NotCold | (uint8_t)AllocationType::Cold;
  8674. break;
  8675. default:
  8676. return error(Lex.getLoc(), "invalid alloc type");
  8677. }
  8678. Lex.Lex();
  8679. return false;
  8680. }
  8681. /// OptionalCallsites
  8682. /// := 'callsites' ':' '(' Callsite [',' Callsite]* ')'
  8683. /// Callsite ::= '(' 'callee' ':' GVReference
  8684. /// ',' 'clones' ':' '(' Version [',' Version]* ')'
  8685. /// ',' 'stackIds' ':' '(' StackId [',' StackId]* ')' ')'
  8686. /// Version ::= UInt32
  8687. /// StackId ::= UInt64
  8688. bool LLParser::parseOptionalCallsites(std::vector<CallsiteInfo> &Callsites) {
  8689. assert(Lex.getKind() == lltok::kw_callsites);
  8690. Lex.Lex();
  8691. if (parseToken(lltok::colon, "expected ':' in callsites") ||
  8692. parseToken(lltok::lparen, "expected '(' in callsites"))
  8693. return true;
  8694. IdToIndexMapType IdToIndexMap;
  8695. // parse each callsite
  8696. do {
  8697. if (parseToken(lltok::lparen, "expected '(' in callsite") ||
  8698. parseToken(lltok::kw_callee, "expected 'callee' in callsite") ||
  8699. parseToken(lltok::colon, "expected ':'"))
  8700. return true;
  8701. ValueInfo VI;
  8702. unsigned GVId = 0;
  8703. LocTy Loc = Lex.getLoc();
  8704. if (!EatIfPresent(lltok::kw_null)) {
  8705. if (parseGVReference(VI, GVId))
  8706. return true;
  8707. }
  8708. if (parseToken(lltok::comma, "expected ',' in callsite") ||
  8709. parseToken(lltok::kw_clones, "expected 'clones' in callsite") ||
  8710. parseToken(lltok::colon, "expected ':'") ||
  8711. parseToken(lltok::lparen, "expected '(' in clones"))
  8712. return true;
  8713. SmallVector<unsigned> Clones;
  8714. do {
  8715. unsigned V = 0;
  8716. if (parseUInt32(V))
  8717. return true;
  8718. Clones.push_back(V);
  8719. } while (EatIfPresent(lltok::comma));
  8720. if (parseToken(lltok::rparen, "expected ')' in clones") ||
  8721. parseToken(lltok::comma, "expected ',' in callsite") ||
  8722. parseToken(lltok::kw_stackIds, "expected 'stackIds' in callsite") ||
  8723. parseToken(lltok::colon, "expected ':'") ||
  8724. parseToken(lltok::lparen, "expected '(' in stackIds"))
  8725. return true;
  8726. SmallVector<unsigned> StackIdIndices;
  8727. do {
  8728. uint64_t StackId = 0;
  8729. if (parseUInt64(StackId))
  8730. return true;
  8731. StackIdIndices.push_back(Index->addOrGetStackIdIndex(StackId));
  8732. } while (EatIfPresent(lltok::comma));
  8733. if (parseToken(lltok::rparen, "expected ')' in stackIds"))
  8734. return true;
  8735. // Keep track of the Callsites array index needing a forward reference.
  8736. // We will save the location of the ValueInfo needing an update, but
  8737. // can only do so once the SmallVector is finalized.
  8738. if (VI.getRef() == FwdVIRef)
  8739. IdToIndexMap[GVId].push_back(std::make_pair(Callsites.size(), Loc));
  8740. Callsites.push_back({VI, Clones, StackIdIndices});
  8741. if (parseToken(lltok::rparen, "expected ')' in callsite"))
  8742. return true;
  8743. } while (EatIfPresent(lltok::comma));
  8744. // Now that the Callsites vector is finalized, it is safe to save the
  8745. // locations of any forward GV references that need updating later.
  8746. for (auto I : IdToIndexMap) {
  8747. auto &Infos = ForwardRefValueInfos[I.first];
  8748. for (auto P : I.second) {
  8749. assert(Callsites[P.first].Callee.getRef() == FwdVIRef &&
  8750. "Forward referenced ValueInfo expected to be empty");
  8751. Infos.emplace_back(&Callsites[P.first].Callee, P.second);
  8752. }
  8753. }
  8754. if (parseToken(lltok::rparen, "expected ')' in callsites"))
  8755. return true;
  8756. return false;
  8757. }