LLParser.cpp 314 KB

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