LLParser.cpp 300 KB

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