SelectionDAGBuilder.cpp 454 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601
  1. //===- SelectionDAGBuilder.cpp - Selection-DAG building -------------------===//
  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 implements routines for translating from LLVM IR into SelectionDAG IR.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "SelectionDAGBuilder.h"
  13. #include "SDNodeDbgValue.h"
  14. #include "llvm/ADT/APFloat.h"
  15. #include "llvm/ADT/APInt.h"
  16. #include "llvm/ADT/BitVector.h"
  17. #include "llvm/ADT/STLExtras.h"
  18. #include "llvm/ADT/SmallPtrSet.h"
  19. #include "llvm/ADT/SmallSet.h"
  20. #include "llvm/ADT/StringRef.h"
  21. #include "llvm/ADT/Triple.h"
  22. #include "llvm/ADT/Twine.h"
  23. #include "llvm/Analysis/AliasAnalysis.h"
  24. #include "llvm/Analysis/BranchProbabilityInfo.h"
  25. #include "llvm/Analysis/ConstantFolding.h"
  26. #include "llvm/Analysis/EHPersonalities.h"
  27. #include "llvm/Analysis/Loads.h"
  28. #include "llvm/Analysis/MemoryLocation.h"
  29. #include "llvm/Analysis/TargetLibraryInfo.h"
  30. #include "llvm/Analysis/ValueTracking.h"
  31. #include "llvm/CodeGen/Analysis.h"
  32. #include "llvm/CodeGen/AssignmentTrackingAnalysis.h"
  33. #include "llvm/CodeGen/CodeGenCommonISel.h"
  34. #include "llvm/CodeGen/FunctionLoweringInfo.h"
  35. #include "llvm/CodeGen/GCMetadata.h"
  36. #include "llvm/CodeGen/MachineBasicBlock.h"
  37. #include "llvm/CodeGen/MachineFrameInfo.h"
  38. #include "llvm/CodeGen/MachineFunction.h"
  39. #include "llvm/CodeGen/MachineInstrBuilder.h"
  40. #include "llvm/CodeGen/MachineInstrBundleIterator.h"
  41. #include "llvm/CodeGen/MachineMemOperand.h"
  42. #include "llvm/CodeGen/MachineModuleInfo.h"
  43. #include "llvm/CodeGen/MachineOperand.h"
  44. #include "llvm/CodeGen/MachineRegisterInfo.h"
  45. #include "llvm/CodeGen/RuntimeLibcalls.h"
  46. #include "llvm/CodeGen/SelectionDAG.h"
  47. #include "llvm/CodeGen/SelectionDAGTargetInfo.h"
  48. #include "llvm/CodeGen/StackMaps.h"
  49. #include "llvm/CodeGen/SwiftErrorValueTracking.h"
  50. #include "llvm/CodeGen/TargetFrameLowering.h"
  51. #include "llvm/CodeGen/TargetInstrInfo.h"
  52. #include "llvm/CodeGen/TargetOpcodes.h"
  53. #include "llvm/CodeGen/TargetRegisterInfo.h"
  54. #include "llvm/CodeGen/TargetSubtargetInfo.h"
  55. #include "llvm/CodeGen/WinEHFuncInfo.h"
  56. #include "llvm/IR/Argument.h"
  57. #include "llvm/IR/Attributes.h"
  58. #include "llvm/IR/BasicBlock.h"
  59. #include "llvm/IR/CFG.h"
  60. #include "llvm/IR/CallingConv.h"
  61. #include "llvm/IR/Constant.h"
  62. #include "llvm/IR/ConstantRange.h"
  63. #include "llvm/IR/Constants.h"
  64. #include "llvm/IR/DataLayout.h"
  65. #include "llvm/IR/DebugInfo.h"
  66. #include "llvm/IR/DebugInfoMetadata.h"
  67. #include "llvm/IR/DerivedTypes.h"
  68. #include "llvm/IR/DiagnosticInfo.h"
  69. #include "llvm/IR/Function.h"
  70. #include "llvm/IR/GetElementPtrTypeIterator.h"
  71. #include "llvm/IR/InlineAsm.h"
  72. #include "llvm/IR/InstrTypes.h"
  73. #include "llvm/IR/Instructions.h"
  74. #include "llvm/IR/IntrinsicInst.h"
  75. #include "llvm/IR/Intrinsics.h"
  76. #include "llvm/IR/IntrinsicsAArch64.h"
  77. #include "llvm/IR/IntrinsicsWebAssembly.h"
  78. #include "llvm/IR/LLVMContext.h"
  79. #include "llvm/IR/Metadata.h"
  80. #include "llvm/IR/Module.h"
  81. #include "llvm/IR/Operator.h"
  82. #include "llvm/IR/PatternMatch.h"
  83. #include "llvm/IR/Statepoint.h"
  84. #include "llvm/IR/Type.h"
  85. #include "llvm/IR/User.h"
  86. #include "llvm/IR/Value.h"
  87. #include "llvm/MC/MCContext.h"
  88. #include "llvm/Support/AtomicOrdering.h"
  89. #include "llvm/Support/Casting.h"
  90. #include "llvm/Support/CommandLine.h"
  91. #include "llvm/Support/Compiler.h"
  92. #include "llvm/Support/Debug.h"
  93. #include "llvm/Support/MathExtras.h"
  94. #include "llvm/Support/raw_ostream.h"
  95. #include "llvm/Target/TargetIntrinsicInfo.h"
  96. #include "llvm/Target/TargetMachine.h"
  97. #include "llvm/Target/TargetOptions.h"
  98. #include "llvm/Transforms/Utils/Local.h"
  99. #include <cstddef>
  100. #include <iterator>
  101. #include <limits>
  102. #include <optional>
  103. #include <tuple>
  104. using namespace llvm;
  105. using namespace PatternMatch;
  106. using namespace SwitchCG;
  107. #define DEBUG_TYPE "isel"
  108. /// LimitFloatPrecision - Generate low-precision inline sequences for
  109. /// some float libcalls (6, 8 or 12 bits).
  110. static unsigned LimitFloatPrecision;
  111. static cl::opt<bool>
  112. InsertAssertAlign("insert-assert-align", cl::init(true),
  113. cl::desc("Insert the experimental `assertalign` node."),
  114. cl::ReallyHidden);
  115. static cl::opt<unsigned, true>
  116. LimitFPPrecision("limit-float-precision",
  117. cl::desc("Generate low-precision inline sequences "
  118. "for some float libcalls"),
  119. cl::location(LimitFloatPrecision), cl::Hidden,
  120. cl::init(0));
  121. static cl::opt<unsigned> SwitchPeelThreshold(
  122. "switch-peel-threshold", cl::Hidden, cl::init(66),
  123. cl::desc("Set the case probability threshold for peeling the case from a "
  124. "switch statement. A value greater than 100 will void this "
  125. "optimization"));
  126. // Limit the width of DAG chains. This is important in general to prevent
  127. // DAG-based analysis from blowing up. For example, alias analysis and
  128. // load clustering may not complete in reasonable time. It is difficult to
  129. // recognize and avoid this situation within each individual analysis, and
  130. // future analyses are likely to have the same behavior. Limiting DAG width is
  131. // the safe approach and will be especially important with global DAGs.
  132. //
  133. // MaxParallelChains default is arbitrarily high to avoid affecting
  134. // optimization, but could be lowered to improve compile time. Any ld-ld-st-st
  135. // sequence over this should have been converted to llvm.memcpy by the
  136. // frontend. It is easy to induce this behavior with .ll code such as:
  137. // %buffer = alloca [4096 x i8]
  138. // %data = load [4096 x i8]* %argPtr
  139. // store [4096 x i8] %data, [4096 x i8]* %buffer
  140. static const unsigned MaxParallelChains = 64;
  141. static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
  142. const SDValue *Parts, unsigned NumParts,
  143. MVT PartVT, EVT ValueVT, const Value *V,
  144. std::optional<CallingConv::ID> CC);
  145. /// getCopyFromParts - Create a value that contains the specified legal parts
  146. /// combined into the value they represent. If the parts combine to a type
  147. /// larger than ValueVT then AssertOp can be used to specify whether the extra
  148. /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
  149. /// (ISD::AssertSext).
  150. static SDValue
  151. getCopyFromParts(SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts,
  152. unsigned NumParts, MVT PartVT, EVT ValueVT, const Value *V,
  153. std::optional<CallingConv::ID> CC = std::nullopt,
  154. std::optional<ISD::NodeType> AssertOp = std::nullopt) {
  155. // Let the target assemble the parts if it wants to
  156. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  157. if (SDValue Val = TLI.joinRegisterPartsIntoValue(DAG, DL, Parts, NumParts,
  158. PartVT, ValueVT, CC))
  159. return Val;
  160. if (ValueVT.isVector())
  161. return getCopyFromPartsVector(DAG, DL, Parts, NumParts, PartVT, ValueVT, V,
  162. CC);
  163. assert(NumParts > 0 && "No parts to assemble!");
  164. SDValue Val = Parts[0];
  165. if (NumParts > 1) {
  166. // Assemble the value from multiple parts.
  167. if (ValueVT.isInteger()) {
  168. unsigned PartBits = PartVT.getSizeInBits();
  169. unsigned ValueBits = ValueVT.getSizeInBits();
  170. // Assemble the power of 2 part.
  171. unsigned RoundParts = llvm::bit_floor(NumParts);
  172. unsigned RoundBits = PartBits * RoundParts;
  173. EVT RoundVT = RoundBits == ValueBits ?
  174. ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits);
  175. SDValue Lo, Hi;
  176. EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2);
  177. if (RoundParts > 2) {
  178. Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2,
  179. PartVT, HalfVT, V);
  180. Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2,
  181. RoundParts / 2, PartVT, HalfVT, V);
  182. } else {
  183. Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]);
  184. Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]);
  185. }
  186. if (DAG.getDataLayout().isBigEndian())
  187. std::swap(Lo, Hi);
  188. Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi);
  189. if (RoundParts < NumParts) {
  190. // Assemble the trailing non-power-of-2 part.
  191. unsigned OddParts = NumParts - RoundParts;
  192. EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits);
  193. Hi = getCopyFromParts(DAG, DL, Parts + RoundParts, OddParts, PartVT,
  194. OddVT, V, CC);
  195. // Combine the round and odd parts.
  196. Lo = Val;
  197. if (DAG.getDataLayout().isBigEndian())
  198. std::swap(Lo, Hi);
  199. EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
  200. Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi);
  201. Hi = DAG.getNode(ISD::SHL, DL, TotalVT, Hi,
  202. DAG.getConstant(Lo.getValueSizeInBits(), DL,
  203. TLI.getShiftAmountTy(
  204. TotalVT, DAG.getDataLayout())));
  205. Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo);
  206. Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi);
  207. }
  208. } else if (PartVT.isFloatingPoint()) {
  209. // FP split into multiple FP parts (for ppcf128)
  210. assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 &&
  211. "Unexpected split");
  212. SDValue Lo, Hi;
  213. Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]);
  214. Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]);
  215. if (TLI.hasBigEndianPartOrdering(ValueVT, DAG.getDataLayout()))
  216. std::swap(Lo, Hi);
  217. Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi);
  218. } else {
  219. // FP split into integer parts (soft fp)
  220. assert(ValueVT.isFloatingPoint() && PartVT.isInteger() &&
  221. !PartVT.isVector() && "Unexpected split");
  222. EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
  223. Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V, CC);
  224. }
  225. }
  226. // There is now one part, held in Val. Correct it to match ValueVT.
  227. // PartEVT is the type of the register class that holds the value.
  228. // ValueVT is the type of the inline asm operation.
  229. EVT PartEVT = Val.getValueType();
  230. if (PartEVT == ValueVT)
  231. return Val;
  232. if (PartEVT.isInteger() && ValueVT.isFloatingPoint() &&
  233. ValueVT.bitsLT(PartEVT)) {
  234. // For an FP value in an integer part, we need to truncate to the right
  235. // width first.
  236. PartEVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
  237. Val = DAG.getNode(ISD::TRUNCATE, DL, PartEVT, Val);
  238. }
  239. // Handle types that have the same size.
  240. if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits())
  241. return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
  242. // Handle types with different sizes.
  243. if (PartEVT.isInteger() && ValueVT.isInteger()) {
  244. if (ValueVT.bitsLT(PartEVT)) {
  245. // For a truncate, see if we have any information to
  246. // indicate whether the truncated bits will always be
  247. // zero or sign-extension.
  248. if (AssertOp)
  249. Val = DAG.getNode(*AssertOp, DL, PartEVT, Val,
  250. DAG.getValueType(ValueVT));
  251. return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
  252. }
  253. return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val);
  254. }
  255. if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
  256. // FP_ROUND's are always exact here.
  257. if (ValueVT.bitsLT(Val.getValueType()))
  258. return DAG.getNode(
  259. ISD::FP_ROUND, DL, ValueVT, Val,
  260. DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout())));
  261. return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val);
  262. }
  263. // Handle MMX to a narrower integer type by bitcasting MMX to integer and
  264. // then truncating.
  265. if (PartEVT == MVT::x86mmx && ValueVT.isInteger() &&
  266. ValueVT.bitsLT(PartEVT)) {
  267. Val = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Val);
  268. return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
  269. }
  270. report_fatal_error("Unknown mismatch in getCopyFromParts!");
  271. }
  272. static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V,
  273. const Twine &ErrMsg) {
  274. const Instruction *I = dyn_cast_or_null<Instruction>(V);
  275. if (!V)
  276. return Ctx.emitError(ErrMsg);
  277. const char *AsmError = ", possible invalid constraint for vector type";
  278. if (const CallInst *CI = dyn_cast<CallInst>(I))
  279. if (CI->isInlineAsm())
  280. return Ctx.emitError(I, ErrMsg + AsmError);
  281. return Ctx.emitError(I, ErrMsg);
  282. }
  283. /// getCopyFromPartsVector - Create a value that contains the specified legal
  284. /// parts combined into the value they represent. If the parts combine to a
  285. /// type larger than ValueVT then AssertOp can be used to specify whether the
  286. /// extra bits are known to be zero (ISD::AssertZext) or sign extended from
  287. /// ValueVT (ISD::AssertSext).
  288. static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
  289. const SDValue *Parts, unsigned NumParts,
  290. MVT PartVT, EVT ValueVT, const Value *V,
  291. std::optional<CallingConv::ID> CallConv) {
  292. assert(ValueVT.isVector() && "Not a vector value");
  293. assert(NumParts > 0 && "No parts to assemble!");
  294. const bool IsABIRegCopy = CallConv.has_value();
  295. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  296. SDValue Val = Parts[0];
  297. // Handle a multi-element vector.
  298. if (NumParts > 1) {
  299. EVT IntermediateVT;
  300. MVT RegisterVT;
  301. unsigned NumIntermediates;
  302. unsigned NumRegs;
  303. if (IsABIRegCopy) {
  304. NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
  305. *DAG.getContext(), *CallConv, ValueVT, IntermediateVT,
  306. NumIntermediates, RegisterVT);
  307. } else {
  308. NumRegs =
  309. TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
  310. NumIntermediates, RegisterVT);
  311. }
  312. assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
  313. NumParts = NumRegs; // Silence a compiler warning.
  314. assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
  315. assert(RegisterVT.getSizeInBits() ==
  316. Parts[0].getSimpleValueType().getSizeInBits() &&
  317. "Part type sizes don't match!");
  318. // Assemble the parts into intermediate operands.
  319. SmallVector<SDValue, 8> Ops(NumIntermediates);
  320. if (NumIntermediates == NumParts) {
  321. // If the register was not expanded, truncate or copy the value,
  322. // as appropriate.
  323. for (unsigned i = 0; i != NumParts; ++i)
  324. Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1,
  325. PartVT, IntermediateVT, V, CallConv);
  326. } else if (NumParts > 0) {
  327. // If the intermediate type was expanded, build the intermediate
  328. // operands from the parts.
  329. assert(NumParts % NumIntermediates == 0 &&
  330. "Must expand into a divisible number of parts!");
  331. unsigned Factor = NumParts / NumIntermediates;
  332. for (unsigned i = 0; i != NumIntermediates; ++i)
  333. Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor,
  334. PartVT, IntermediateVT, V, CallConv);
  335. }
  336. // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the
  337. // intermediate operands.
  338. EVT BuiltVectorTy =
  339. IntermediateVT.isVector()
  340. ? EVT::getVectorVT(
  341. *DAG.getContext(), IntermediateVT.getScalarType(),
  342. IntermediateVT.getVectorElementCount() * NumParts)
  343. : EVT::getVectorVT(*DAG.getContext(),
  344. IntermediateVT.getScalarType(),
  345. NumIntermediates);
  346. Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS
  347. : ISD::BUILD_VECTOR,
  348. DL, BuiltVectorTy, Ops);
  349. }
  350. // There is now one part, held in Val. Correct it to match ValueVT.
  351. EVT PartEVT = Val.getValueType();
  352. if (PartEVT == ValueVT)
  353. return Val;
  354. if (PartEVT.isVector()) {
  355. // Vector/Vector bitcast.
  356. if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits())
  357. return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
  358. // If the parts vector has more elements than the value vector, then we
  359. // have a vector widening case (e.g. <2 x float> -> <4 x float>).
  360. // Extract the elements we want.
  361. if (PartEVT.getVectorElementCount() != ValueVT.getVectorElementCount()) {
  362. assert((PartEVT.getVectorElementCount().getKnownMinValue() >
  363. ValueVT.getVectorElementCount().getKnownMinValue()) &&
  364. (PartEVT.getVectorElementCount().isScalable() ==
  365. ValueVT.getVectorElementCount().isScalable()) &&
  366. "Cannot narrow, it would be a lossy transformation");
  367. PartEVT =
  368. EVT::getVectorVT(*DAG.getContext(), PartEVT.getVectorElementType(),
  369. ValueVT.getVectorElementCount());
  370. Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, PartEVT, Val,
  371. DAG.getVectorIdxConstant(0, DL));
  372. if (PartEVT == ValueVT)
  373. return Val;
  374. if (PartEVT.isInteger() && ValueVT.isFloatingPoint())
  375. return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
  376. }
  377. // Promoted vector extract
  378. return DAG.getAnyExtOrTrunc(Val, DL, ValueVT);
  379. }
  380. // Trivial bitcast if the types are the same size and the destination
  381. // vector type is legal.
  382. if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() &&
  383. TLI.isTypeLegal(ValueVT))
  384. return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
  385. if (ValueVT.getVectorNumElements() != 1) {
  386. // Certain ABIs require that vectors are passed as integers. For vectors
  387. // are the same size, this is an obvious bitcast.
  388. if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) {
  389. return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
  390. } else if (ValueVT.bitsLT(PartEVT)) {
  391. const uint64_t ValueSize = ValueVT.getFixedSizeInBits();
  392. EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize);
  393. // Drop the extra bits.
  394. Val = DAG.getNode(ISD::TRUNCATE, DL, IntermediateType, Val);
  395. return DAG.getBitcast(ValueVT, Val);
  396. }
  397. diagnosePossiblyInvalidConstraint(
  398. *DAG.getContext(), V, "non-trivial scalar-to-vector conversion");
  399. return DAG.getUNDEF(ValueVT);
  400. }
  401. // Handle cases such as i8 -> <1 x i1>
  402. EVT ValueSVT = ValueVT.getVectorElementType();
  403. if (ValueVT.getVectorNumElements() == 1 && ValueSVT != PartEVT) {
  404. unsigned ValueSize = ValueSVT.getSizeInBits();
  405. if (ValueSize == PartEVT.getSizeInBits()) {
  406. Val = DAG.getNode(ISD::BITCAST, DL, ValueSVT, Val);
  407. } else if (ValueSVT.isFloatingPoint() && PartEVT.isInteger()) {
  408. // It's possible a scalar floating point type gets softened to integer and
  409. // then promoted to a larger integer. If PartEVT is the larger integer
  410. // we need to truncate it and then bitcast to the FP type.
  411. assert(ValueSVT.bitsLT(PartEVT) && "Unexpected types");
  412. EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize);
  413. Val = DAG.getNode(ISD::TRUNCATE, DL, IntermediateType, Val);
  414. Val = DAG.getBitcast(ValueSVT, Val);
  415. } else {
  416. Val = ValueVT.isFloatingPoint()
  417. ? DAG.getFPExtendOrRound(Val, DL, ValueSVT)
  418. : DAG.getAnyExtOrTrunc(Val, DL, ValueSVT);
  419. }
  420. }
  421. return DAG.getBuildVector(ValueVT, DL, Val);
  422. }
  423. static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl,
  424. SDValue Val, SDValue *Parts, unsigned NumParts,
  425. MVT PartVT, const Value *V,
  426. std::optional<CallingConv::ID> CallConv);
  427. /// getCopyToParts - Create a series of nodes that contain the specified value
  428. /// split into legal parts. If the parts contain more bits than Val, then, for
  429. /// integers, ExtendKind can be used to specify how to generate the extra bits.
  430. static void
  431. getCopyToParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts,
  432. unsigned NumParts, MVT PartVT, const Value *V,
  433. std::optional<CallingConv::ID> CallConv = std::nullopt,
  434. ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
  435. // Let the target split the parts if it wants to
  436. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  437. if (TLI.splitValueIntoRegisterParts(DAG, DL, Val, Parts, NumParts, PartVT,
  438. CallConv))
  439. return;
  440. EVT ValueVT = Val.getValueType();
  441. // Handle the vector case separately.
  442. if (ValueVT.isVector())
  443. return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V,
  444. CallConv);
  445. unsigned PartBits = PartVT.getSizeInBits();
  446. unsigned OrigNumParts = NumParts;
  447. assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) &&
  448. "Copying to an illegal type!");
  449. if (NumParts == 0)
  450. return;
  451. assert(!ValueVT.isVector() && "Vector case handled elsewhere");
  452. EVT PartEVT = PartVT;
  453. if (PartEVT == ValueVT) {
  454. assert(NumParts == 1 && "No-op copy with multiple parts!");
  455. Parts[0] = Val;
  456. return;
  457. }
  458. if (NumParts * PartBits > ValueVT.getSizeInBits()) {
  459. // If the parts cover more bits than the value has, promote the value.
  460. if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
  461. assert(NumParts == 1 && "Do not know what to promote to!");
  462. Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val);
  463. } else {
  464. if (ValueVT.isFloatingPoint()) {
  465. // FP values need to be bitcast, then extended if they are being put
  466. // into a larger container.
  467. ValueVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
  468. Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
  469. }
  470. assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
  471. ValueVT.isInteger() &&
  472. "Unknown mismatch!");
  473. ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
  474. Val = DAG.getNode(ExtendKind, DL, ValueVT, Val);
  475. if (PartVT == MVT::x86mmx)
  476. Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
  477. }
  478. } else if (PartBits == ValueVT.getSizeInBits()) {
  479. // Different types of the same size.
  480. assert(NumParts == 1 && PartEVT != ValueVT);
  481. Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
  482. } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
  483. // If the parts cover less bits than value has, truncate the value.
  484. assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
  485. ValueVT.isInteger() &&
  486. "Unknown mismatch!");
  487. ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
  488. Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
  489. if (PartVT == MVT::x86mmx)
  490. Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
  491. }
  492. // The value may have changed - recompute ValueVT.
  493. ValueVT = Val.getValueType();
  494. assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
  495. "Failed to tile the value with PartVT!");
  496. if (NumParts == 1) {
  497. if (PartEVT != ValueVT) {
  498. diagnosePossiblyInvalidConstraint(*DAG.getContext(), V,
  499. "scalar-to-vector conversion failed");
  500. Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
  501. }
  502. Parts[0] = Val;
  503. return;
  504. }
  505. // Expand the value into multiple parts.
  506. if (NumParts & (NumParts - 1)) {
  507. // The number of parts is not a power of 2. Split off and copy the tail.
  508. assert(PartVT.isInteger() && ValueVT.isInteger() &&
  509. "Do not know what to expand to!");
  510. unsigned RoundParts = llvm::bit_floor(NumParts);
  511. unsigned RoundBits = RoundParts * PartBits;
  512. unsigned OddParts = NumParts - RoundParts;
  513. SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val,
  514. DAG.getShiftAmountConstant(RoundBits, ValueVT, DL));
  515. getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V,
  516. CallConv);
  517. if (DAG.getDataLayout().isBigEndian())
  518. // The odd parts were reversed by getCopyToParts - unreverse them.
  519. std::reverse(Parts + RoundParts, Parts + NumParts);
  520. NumParts = RoundParts;
  521. ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
  522. Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
  523. }
  524. // The number of parts is a power of 2. Repeatedly bisect the value using
  525. // EXTRACT_ELEMENT.
  526. Parts[0] = DAG.getNode(ISD::BITCAST, DL,
  527. EVT::getIntegerVT(*DAG.getContext(),
  528. ValueVT.getSizeInBits()),
  529. Val);
  530. for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
  531. for (unsigned i = 0; i < NumParts; i += StepSize) {
  532. unsigned ThisBits = StepSize * PartBits / 2;
  533. EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits);
  534. SDValue &Part0 = Parts[i];
  535. SDValue &Part1 = Parts[i+StepSize/2];
  536. Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
  537. ThisVT, Part0, DAG.getIntPtrConstant(1, DL));
  538. Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
  539. ThisVT, Part0, DAG.getIntPtrConstant(0, DL));
  540. if (ThisBits == PartBits && ThisVT != PartVT) {
  541. Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0);
  542. Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1);
  543. }
  544. }
  545. }
  546. if (DAG.getDataLayout().isBigEndian())
  547. std::reverse(Parts, Parts + OrigNumParts);
  548. }
  549. static SDValue widenVectorToPartType(SelectionDAG &DAG, SDValue Val,
  550. const SDLoc &DL, EVT PartVT) {
  551. if (!PartVT.isVector())
  552. return SDValue();
  553. EVT ValueVT = Val.getValueType();
  554. ElementCount PartNumElts = PartVT.getVectorElementCount();
  555. ElementCount ValueNumElts = ValueVT.getVectorElementCount();
  556. // We only support widening vectors with equivalent element types and
  557. // fixed/scalable properties. If a target needs to widen a fixed-length type
  558. // to a scalable one, it should be possible to use INSERT_SUBVECTOR below.
  559. if (ElementCount::isKnownLE(PartNumElts, ValueNumElts) ||
  560. PartNumElts.isScalable() != ValueNumElts.isScalable() ||
  561. PartVT.getVectorElementType() != ValueVT.getVectorElementType())
  562. return SDValue();
  563. // Widening a scalable vector to another scalable vector is done by inserting
  564. // the vector into a larger undef one.
  565. if (PartNumElts.isScalable())
  566. return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT),
  567. Val, DAG.getVectorIdxConstant(0, DL));
  568. EVT ElementVT = PartVT.getVectorElementType();
  569. // Vector widening case, e.g. <2 x float> -> <4 x float>. Shuffle in
  570. // undef elements.
  571. SmallVector<SDValue, 16> Ops;
  572. DAG.ExtractVectorElements(Val, Ops);
  573. SDValue EltUndef = DAG.getUNDEF(ElementVT);
  574. Ops.append((PartNumElts - ValueNumElts).getFixedValue(), EltUndef);
  575. // FIXME: Use CONCAT for 2x -> 4x.
  576. return DAG.getBuildVector(PartVT, DL, Ops);
  577. }
  578. /// getCopyToPartsVector - Create a series of nodes that contain the specified
  579. /// value split into legal parts.
  580. static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL,
  581. SDValue Val, SDValue *Parts, unsigned NumParts,
  582. MVT PartVT, const Value *V,
  583. std::optional<CallingConv::ID> CallConv) {
  584. EVT ValueVT = Val.getValueType();
  585. assert(ValueVT.isVector() && "Not a vector");
  586. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  587. const bool IsABIRegCopy = CallConv.has_value();
  588. if (NumParts == 1) {
  589. EVT PartEVT = PartVT;
  590. if (PartEVT == ValueVT) {
  591. // Nothing to do.
  592. } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) {
  593. // Bitconvert vector->vector case.
  594. Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
  595. } else if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, PartVT)) {
  596. Val = Widened;
  597. } else if (PartVT.isVector() &&
  598. PartEVT.getVectorElementType().bitsGE(
  599. ValueVT.getVectorElementType()) &&
  600. PartEVT.getVectorElementCount() ==
  601. ValueVT.getVectorElementCount()) {
  602. // Promoted vector extract
  603. Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
  604. } else if (PartEVT.isVector() &&
  605. PartEVT.getVectorElementType() !=
  606. ValueVT.getVectorElementType() &&
  607. TLI.getTypeAction(*DAG.getContext(), ValueVT) ==
  608. TargetLowering::TypeWidenVector) {
  609. // Combination of widening and promotion.
  610. EVT WidenVT =
  611. EVT::getVectorVT(*DAG.getContext(), ValueVT.getVectorElementType(),
  612. PartVT.getVectorElementCount());
  613. SDValue Widened = widenVectorToPartType(DAG, Val, DL, WidenVT);
  614. Val = DAG.getAnyExtOrTrunc(Widened, DL, PartVT);
  615. } else {
  616. // Don't extract an integer from a float vector. This can happen if the
  617. // FP type gets softened to integer and then promoted. The promotion
  618. // prevents it from being picked up by the earlier bitcast case.
  619. if (ValueVT.getVectorElementCount().isScalar() &&
  620. (!ValueVT.isFloatingPoint() || !PartVT.isInteger())) {
  621. Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val,
  622. DAG.getVectorIdxConstant(0, DL));
  623. } else {
  624. uint64_t ValueSize = ValueVT.getFixedSizeInBits();
  625. assert(PartVT.getFixedSizeInBits() > ValueSize &&
  626. "lossy conversion of vector to scalar type");
  627. EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize);
  628. Val = DAG.getBitcast(IntermediateType, Val);
  629. Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
  630. }
  631. }
  632. assert(Val.getValueType() == PartVT && "Unexpected vector part value type");
  633. Parts[0] = Val;
  634. return;
  635. }
  636. // Handle a multi-element vector.
  637. EVT IntermediateVT;
  638. MVT RegisterVT;
  639. unsigned NumIntermediates;
  640. unsigned NumRegs;
  641. if (IsABIRegCopy) {
  642. NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
  643. *DAG.getContext(), *CallConv, ValueVT, IntermediateVT, NumIntermediates,
  644. RegisterVT);
  645. } else {
  646. NumRegs =
  647. TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
  648. NumIntermediates, RegisterVT);
  649. }
  650. assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
  651. NumParts = NumRegs; // Silence a compiler warning.
  652. assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
  653. assert(IntermediateVT.isScalableVector() == ValueVT.isScalableVector() &&
  654. "Mixing scalable and fixed vectors when copying in parts");
  655. std::optional<ElementCount> DestEltCnt;
  656. if (IntermediateVT.isVector())
  657. DestEltCnt = IntermediateVT.getVectorElementCount() * NumIntermediates;
  658. else
  659. DestEltCnt = ElementCount::getFixed(NumIntermediates);
  660. EVT BuiltVectorTy = EVT::getVectorVT(
  661. *DAG.getContext(), IntermediateVT.getScalarType(), *DestEltCnt);
  662. if (ValueVT == BuiltVectorTy) {
  663. // Nothing to do.
  664. } else if (ValueVT.getSizeInBits() == BuiltVectorTy.getSizeInBits()) {
  665. // Bitconvert vector->vector case.
  666. Val = DAG.getNode(ISD::BITCAST, DL, BuiltVectorTy, Val);
  667. } else {
  668. if (BuiltVectorTy.getVectorElementType().bitsGT(
  669. ValueVT.getVectorElementType())) {
  670. // Integer promotion.
  671. ValueVT = EVT::getVectorVT(*DAG.getContext(),
  672. BuiltVectorTy.getVectorElementType(),
  673. ValueVT.getVectorElementCount());
  674. Val = DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val);
  675. }
  676. if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, BuiltVectorTy)) {
  677. Val = Widened;
  678. }
  679. }
  680. assert(Val.getValueType() == BuiltVectorTy && "Unexpected vector value type");
  681. // Split the vector into intermediate operands.
  682. SmallVector<SDValue, 8> Ops(NumIntermediates);
  683. for (unsigned i = 0; i != NumIntermediates; ++i) {
  684. if (IntermediateVT.isVector()) {
  685. // This does something sensible for scalable vectors - see the
  686. // definition of EXTRACT_SUBVECTOR for further details.
  687. unsigned IntermediateNumElts = IntermediateVT.getVectorMinNumElements();
  688. Ops[i] =
  689. DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val,
  690. DAG.getVectorIdxConstant(i * IntermediateNumElts, DL));
  691. } else {
  692. Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val,
  693. DAG.getVectorIdxConstant(i, DL));
  694. }
  695. }
  696. // Split the intermediate operands into legal parts.
  697. if (NumParts == NumIntermediates) {
  698. // If the register was not expanded, promote or copy the value,
  699. // as appropriate.
  700. for (unsigned i = 0; i != NumParts; ++i)
  701. getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V, CallConv);
  702. } else if (NumParts > 0) {
  703. // If the intermediate type was expanded, split each the value into
  704. // legal parts.
  705. assert(NumIntermediates != 0 && "division by zero");
  706. assert(NumParts % NumIntermediates == 0 &&
  707. "Must expand into a divisible number of parts!");
  708. unsigned Factor = NumParts / NumIntermediates;
  709. for (unsigned i = 0; i != NumIntermediates; ++i)
  710. getCopyToParts(DAG, DL, Ops[i], &Parts[i * Factor], Factor, PartVT, V,
  711. CallConv);
  712. }
  713. }
  714. RegsForValue::RegsForValue(const SmallVector<unsigned, 4> &regs, MVT regvt,
  715. EVT valuevt, std::optional<CallingConv::ID> CC)
  716. : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs),
  717. RegCount(1, regs.size()), CallConv(CC) {}
  718. RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI,
  719. const DataLayout &DL, unsigned Reg, Type *Ty,
  720. std::optional<CallingConv::ID> CC) {
  721. ComputeValueVTs(TLI, DL, Ty, ValueVTs);
  722. CallConv = CC;
  723. for (EVT ValueVT : ValueVTs) {
  724. unsigned NumRegs =
  725. isABIMangled()
  726. ? TLI.getNumRegistersForCallingConv(Context, *CC, ValueVT)
  727. : TLI.getNumRegisters(Context, ValueVT);
  728. MVT RegisterVT =
  729. isABIMangled()
  730. ? TLI.getRegisterTypeForCallingConv(Context, *CC, ValueVT)
  731. : TLI.getRegisterType(Context, ValueVT);
  732. for (unsigned i = 0; i != NumRegs; ++i)
  733. Regs.push_back(Reg + i);
  734. RegVTs.push_back(RegisterVT);
  735. RegCount.push_back(NumRegs);
  736. Reg += NumRegs;
  737. }
  738. }
  739. SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
  740. FunctionLoweringInfo &FuncInfo,
  741. const SDLoc &dl, SDValue &Chain,
  742. SDValue *Flag, const Value *V) const {
  743. // A Value with type {} or [0 x %t] needs no registers.
  744. if (ValueVTs.empty())
  745. return SDValue();
  746. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  747. // Assemble the legal parts into the final values.
  748. SmallVector<SDValue, 4> Values(ValueVTs.size());
  749. SmallVector<SDValue, 8> Parts;
  750. for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
  751. // Copy the legal parts from the registers.
  752. EVT ValueVT = ValueVTs[Value];
  753. unsigned NumRegs = RegCount[Value];
  754. MVT RegisterVT = isABIMangled()
  755. ? TLI.getRegisterTypeForCallingConv(
  756. *DAG.getContext(), *CallConv, RegVTs[Value])
  757. : RegVTs[Value];
  758. Parts.resize(NumRegs);
  759. for (unsigned i = 0; i != NumRegs; ++i) {
  760. SDValue P;
  761. if (!Flag) {
  762. P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT);
  763. } else {
  764. P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag);
  765. *Flag = P.getValue(2);
  766. }
  767. Chain = P.getValue(1);
  768. Parts[i] = P;
  769. // If the source register was virtual and if we know something about it,
  770. // add an assert node.
  771. if (!Register::isVirtualRegister(Regs[Part + i]) ||
  772. !RegisterVT.isInteger())
  773. continue;
  774. const FunctionLoweringInfo::LiveOutInfo *LOI =
  775. FuncInfo.GetLiveOutRegInfo(Regs[Part+i]);
  776. if (!LOI)
  777. continue;
  778. unsigned RegSize = RegisterVT.getScalarSizeInBits();
  779. unsigned NumSignBits = LOI->NumSignBits;
  780. unsigned NumZeroBits = LOI->Known.countMinLeadingZeros();
  781. if (NumZeroBits == RegSize) {
  782. // The current value is a zero.
  783. // Explicitly express that as it would be easier for
  784. // optimizations to kick in.
  785. Parts[i] = DAG.getConstant(0, dl, RegisterVT);
  786. continue;
  787. }
  788. // FIXME: We capture more information than the dag can represent. For
  789. // now, just use the tightest assertzext/assertsext possible.
  790. bool isSExt;
  791. EVT FromVT(MVT::Other);
  792. if (NumZeroBits) {
  793. FromVT = EVT::getIntegerVT(*DAG.getContext(), RegSize - NumZeroBits);
  794. isSExt = false;
  795. } else if (NumSignBits > 1) {
  796. FromVT =
  797. EVT::getIntegerVT(*DAG.getContext(), RegSize - NumSignBits + 1);
  798. isSExt = true;
  799. } else {
  800. continue;
  801. }
  802. // Add an assertion node.
  803. assert(FromVT != MVT::Other);
  804. Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl,
  805. RegisterVT, P, DAG.getValueType(FromVT));
  806. }
  807. Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(), NumRegs,
  808. RegisterVT, ValueVT, V, CallConv);
  809. Part += NumRegs;
  810. Parts.clear();
  811. }
  812. return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values);
  813. }
  814. void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG,
  815. const SDLoc &dl, SDValue &Chain, SDValue *Flag,
  816. const Value *V,
  817. ISD::NodeType PreferredExtendType) const {
  818. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  819. ISD::NodeType ExtendKind = PreferredExtendType;
  820. // Get the list of the values's legal parts.
  821. unsigned NumRegs = Regs.size();
  822. SmallVector<SDValue, 8> Parts(NumRegs);
  823. for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
  824. unsigned NumParts = RegCount[Value];
  825. MVT RegisterVT = isABIMangled()
  826. ? TLI.getRegisterTypeForCallingConv(
  827. *DAG.getContext(), *CallConv, RegVTs[Value])
  828. : RegVTs[Value];
  829. if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT))
  830. ExtendKind = ISD::ZERO_EXTEND;
  831. getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value), &Parts[Part],
  832. NumParts, RegisterVT, V, CallConv, ExtendKind);
  833. Part += NumParts;
  834. }
  835. // Copy the parts into the registers.
  836. SmallVector<SDValue, 8> Chains(NumRegs);
  837. for (unsigned i = 0; i != NumRegs; ++i) {
  838. SDValue Part;
  839. if (!Flag) {
  840. Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]);
  841. } else {
  842. Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag);
  843. *Flag = Part.getValue(1);
  844. }
  845. Chains[i] = Part.getValue(0);
  846. }
  847. if (NumRegs == 1 || Flag)
  848. // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
  849. // flagged to it. That is the CopyToReg nodes and the user are considered
  850. // a single scheduling unit. If we create a TokenFactor and return it as
  851. // chain, then the TokenFactor is both a predecessor (operand) of the
  852. // user as well as a successor (the TF operands are flagged to the user).
  853. // c1, f1 = CopyToReg
  854. // c2, f2 = CopyToReg
  855. // c3 = TokenFactor c1, c2
  856. // ...
  857. // = op c3, ..., f2
  858. Chain = Chains[NumRegs-1];
  859. else
  860. Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
  861. }
  862. void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching,
  863. unsigned MatchingIdx, const SDLoc &dl,
  864. SelectionDAG &DAG,
  865. std::vector<SDValue> &Ops) const {
  866. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  867. unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size());
  868. if (HasMatching)
  869. Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx);
  870. else if (!Regs.empty() && Register::isVirtualRegister(Regs.front())) {
  871. // Put the register class of the virtual registers in the flag word. That
  872. // way, later passes can recompute register class constraints for inline
  873. // assembly as well as normal instructions.
  874. // Don't do this for tied operands that can use the regclass information
  875. // from the def.
  876. const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
  877. const TargetRegisterClass *RC = MRI.getRegClass(Regs.front());
  878. Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID());
  879. }
  880. SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32);
  881. Ops.push_back(Res);
  882. if (Code == InlineAsm::Kind_Clobber) {
  883. // Clobbers should always have a 1:1 mapping with registers, and may
  884. // reference registers that have illegal (e.g. vector) types. Hence, we
  885. // shouldn't try to apply any sort of splitting logic to them.
  886. assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() &&
  887. "No 1:1 mapping from clobbers to regs?");
  888. Register SP = TLI.getStackPointerRegisterToSaveRestore();
  889. (void)SP;
  890. for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) {
  891. Ops.push_back(DAG.getRegister(Regs[I], RegVTs[I]));
  892. assert(
  893. (Regs[I] != SP ||
  894. DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment()) &&
  895. "If we clobbered the stack pointer, MFI should know about it.");
  896. }
  897. return;
  898. }
  899. for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
  900. MVT RegisterVT = RegVTs[Value];
  901. unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value],
  902. RegisterVT);
  903. for (unsigned i = 0; i != NumRegs; ++i) {
  904. assert(Reg < Regs.size() && "Mismatch in # registers expected");
  905. unsigned TheReg = Regs[Reg++];
  906. Ops.push_back(DAG.getRegister(TheReg, RegisterVT));
  907. }
  908. }
  909. }
  910. SmallVector<std::pair<unsigned, TypeSize>, 4>
  911. RegsForValue::getRegsAndSizes() const {
  912. SmallVector<std::pair<unsigned, TypeSize>, 4> OutVec;
  913. unsigned I = 0;
  914. for (auto CountAndVT : zip_first(RegCount, RegVTs)) {
  915. unsigned RegCount = std::get<0>(CountAndVT);
  916. MVT RegisterVT = std::get<1>(CountAndVT);
  917. TypeSize RegisterSize = RegisterVT.getSizeInBits();
  918. for (unsigned E = I + RegCount; I != E; ++I)
  919. OutVec.push_back(std::make_pair(Regs[I], RegisterSize));
  920. }
  921. return OutVec;
  922. }
  923. void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis *aa,
  924. AssumptionCache *ac,
  925. const TargetLibraryInfo *li) {
  926. AA = aa;
  927. AC = ac;
  928. GFI = gfi;
  929. LibInfo = li;
  930. Context = DAG.getContext();
  931. LPadToCallSiteMap.clear();
  932. SL->init(DAG.getTargetLoweringInfo(), TM, DAG.getDataLayout());
  933. }
  934. void SelectionDAGBuilder::clear() {
  935. NodeMap.clear();
  936. UnusedArgNodeMap.clear();
  937. PendingLoads.clear();
  938. PendingExports.clear();
  939. PendingConstrainedFP.clear();
  940. PendingConstrainedFPStrict.clear();
  941. CurInst = nullptr;
  942. HasTailCall = false;
  943. SDNodeOrder = LowestSDNodeOrder;
  944. StatepointLowering.clear();
  945. }
  946. void SelectionDAGBuilder::clearDanglingDebugInfo() {
  947. DanglingDebugInfoMap.clear();
  948. }
  949. // Update DAG root to include dependencies on Pending chains.
  950. SDValue SelectionDAGBuilder::updateRoot(SmallVectorImpl<SDValue> &Pending) {
  951. SDValue Root = DAG.getRoot();
  952. if (Pending.empty())
  953. return Root;
  954. // Add current root to PendingChains, unless we already indirectly
  955. // depend on it.
  956. if (Root.getOpcode() != ISD::EntryToken) {
  957. unsigned i = 0, e = Pending.size();
  958. for (; i != e; ++i) {
  959. assert(Pending[i].getNode()->getNumOperands() > 1);
  960. if (Pending[i].getNode()->getOperand(0) == Root)
  961. break; // Don't add the root if we already indirectly depend on it.
  962. }
  963. if (i == e)
  964. Pending.push_back(Root);
  965. }
  966. if (Pending.size() == 1)
  967. Root = Pending[0];
  968. else
  969. Root = DAG.getTokenFactor(getCurSDLoc(), Pending);
  970. DAG.setRoot(Root);
  971. Pending.clear();
  972. return Root;
  973. }
  974. SDValue SelectionDAGBuilder::getMemoryRoot() {
  975. return updateRoot(PendingLoads);
  976. }
  977. SDValue SelectionDAGBuilder::getRoot() {
  978. // Chain up all pending constrained intrinsics together with all
  979. // pending loads, by simply appending them to PendingLoads and
  980. // then calling getMemoryRoot().
  981. PendingLoads.reserve(PendingLoads.size() +
  982. PendingConstrainedFP.size() +
  983. PendingConstrainedFPStrict.size());
  984. PendingLoads.append(PendingConstrainedFP.begin(),
  985. PendingConstrainedFP.end());
  986. PendingLoads.append(PendingConstrainedFPStrict.begin(),
  987. PendingConstrainedFPStrict.end());
  988. PendingConstrainedFP.clear();
  989. PendingConstrainedFPStrict.clear();
  990. return getMemoryRoot();
  991. }
  992. SDValue SelectionDAGBuilder::getControlRoot() {
  993. // We need to emit pending fpexcept.strict constrained intrinsics,
  994. // so append them to the PendingExports list.
  995. PendingExports.append(PendingConstrainedFPStrict.begin(),
  996. PendingConstrainedFPStrict.end());
  997. PendingConstrainedFPStrict.clear();
  998. return updateRoot(PendingExports);
  999. }
  1000. void SelectionDAGBuilder::visit(const Instruction &I) {
  1001. // Set up outgoing PHI node register values before emitting the terminator.
  1002. if (I.isTerminator()) {
  1003. HandlePHINodesInSuccessorBlocks(I.getParent());
  1004. }
  1005. // Add SDDbgValue nodes for any var locs here. Do so before updating
  1006. // SDNodeOrder, as this mapping is {Inst -> Locs BEFORE Inst}.
  1007. if (FunctionVarLocs const *FnVarLocs = DAG.getFunctionVarLocs()) {
  1008. // Add SDDbgValue nodes for any var locs here. Do so before updating
  1009. // SDNodeOrder, as this mapping is {Inst -> Locs BEFORE Inst}.
  1010. for (auto It = FnVarLocs->locs_begin(&I), End = FnVarLocs->locs_end(&I);
  1011. It != End; ++It) {
  1012. auto *Var = FnVarLocs->getDILocalVariable(It->VariableID);
  1013. dropDanglingDebugInfo(Var, It->Expr);
  1014. if (!handleDebugValue(It->V, Var, It->Expr, It->DL, SDNodeOrder,
  1015. /*IsVariadic=*/false))
  1016. addDanglingDebugInfo(It, SDNodeOrder);
  1017. }
  1018. }
  1019. // Increase the SDNodeOrder if dealing with a non-debug instruction.
  1020. if (!isa<DbgInfoIntrinsic>(I))
  1021. ++SDNodeOrder;
  1022. CurInst = &I;
  1023. // Set inserted listener only if required.
  1024. bool NodeInserted = false;
  1025. std::unique_ptr<SelectionDAG::DAGNodeInsertedListener> InsertedListener;
  1026. MDNode *PCSectionsMD = I.getMetadata(LLVMContext::MD_pcsections);
  1027. if (PCSectionsMD) {
  1028. InsertedListener = std::make_unique<SelectionDAG::DAGNodeInsertedListener>(
  1029. DAG, [&](SDNode *) { NodeInserted = true; });
  1030. }
  1031. visit(I.getOpcode(), I);
  1032. if (!I.isTerminator() && !HasTailCall &&
  1033. !isa<GCStatepointInst>(I)) // statepoints handle their exports internally
  1034. CopyToExportRegsIfNeeded(&I);
  1035. // Handle metadata.
  1036. if (PCSectionsMD) {
  1037. auto It = NodeMap.find(&I);
  1038. if (It != NodeMap.end()) {
  1039. DAG.addPCSections(It->second.getNode(), PCSectionsMD);
  1040. } else if (NodeInserted) {
  1041. // This should not happen; if it does, don't let it go unnoticed so we can
  1042. // fix it. Relevant visit*() function is probably missing a setValue().
  1043. errs() << "warning: loosing !pcsections metadata ["
  1044. << I.getModule()->getName() << "]\n";
  1045. LLVM_DEBUG(I.dump());
  1046. assert(false);
  1047. }
  1048. }
  1049. CurInst = nullptr;
  1050. }
  1051. void SelectionDAGBuilder::visitPHI(const PHINode &) {
  1052. llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!");
  1053. }
  1054. void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) {
  1055. // Note: this doesn't use InstVisitor, because it has to work with
  1056. // ConstantExpr's in addition to instructions.
  1057. switch (Opcode) {
  1058. default: llvm_unreachable("Unknown instruction type encountered!");
  1059. // Build the switch statement using the Instruction.def file.
  1060. #define HANDLE_INST(NUM, OPCODE, CLASS) \
  1061. case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break;
  1062. #include "llvm/IR/Instruction.def"
  1063. }
  1064. }
  1065. void SelectionDAGBuilder::addDanglingDebugInfo(const VarLocInfo *VarLoc,
  1066. unsigned Order) {
  1067. DanglingDebugInfoMap[VarLoc->V].emplace_back(VarLoc, Order);
  1068. }
  1069. void SelectionDAGBuilder::addDanglingDebugInfo(const DbgValueInst *DI,
  1070. unsigned Order) {
  1071. // We treat variadic dbg_values differently at this stage.
  1072. if (DI->hasArgList()) {
  1073. // For variadic dbg_values we will now insert an undef.
  1074. // FIXME: We can potentially recover these!
  1075. SmallVector<SDDbgOperand, 2> Locs;
  1076. for (const Value *V : DI->getValues()) {
  1077. auto Undef = UndefValue::get(V->getType());
  1078. Locs.push_back(SDDbgOperand::fromConst(Undef));
  1079. }
  1080. SDDbgValue *SDV = DAG.getDbgValueList(
  1081. DI->getVariable(), DI->getExpression(), Locs, {},
  1082. /*IsIndirect=*/false, DI->getDebugLoc(), Order, /*IsVariadic=*/true);
  1083. DAG.AddDbgValue(SDV, /*isParameter=*/false);
  1084. } else {
  1085. // TODO: Dangling debug info will eventually either be resolved or produce
  1086. // an Undef DBG_VALUE. However in the resolution case, a gap may appear
  1087. // between the original dbg.value location and its resolved DBG_VALUE,
  1088. // which we should ideally fill with an extra Undef DBG_VALUE.
  1089. assert(DI->getNumVariableLocationOps() == 1 &&
  1090. "DbgValueInst without an ArgList should have a single location "
  1091. "operand.");
  1092. DanglingDebugInfoMap[DI->getValue(0)].emplace_back(DI, Order);
  1093. }
  1094. }
  1095. void SelectionDAGBuilder::dropDanglingDebugInfo(const DILocalVariable *Variable,
  1096. const DIExpression *Expr) {
  1097. auto isMatchingDbgValue = [&](DanglingDebugInfo &DDI) {
  1098. DIVariable *DanglingVariable = DDI.getVariable(DAG.getFunctionVarLocs());
  1099. DIExpression *DanglingExpr = DDI.getExpression();
  1100. if (DanglingVariable == Variable && Expr->fragmentsOverlap(DanglingExpr)) {
  1101. LLVM_DEBUG(dbgs() << "Dropping dangling debug info for " << printDDI(DDI)
  1102. << "\n");
  1103. return true;
  1104. }
  1105. return false;
  1106. };
  1107. for (auto &DDIMI : DanglingDebugInfoMap) {
  1108. DanglingDebugInfoVector &DDIV = DDIMI.second;
  1109. // If debug info is to be dropped, run it through final checks to see
  1110. // whether it can be salvaged.
  1111. for (auto &DDI : DDIV)
  1112. if (isMatchingDbgValue(DDI))
  1113. salvageUnresolvedDbgValue(DDI);
  1114. erase_if(DDIV, isMatchingDbgValue);
  1115. }
  1116. }
  1117. // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V,
  1118. // generate the debug data structures now that we've seen its definition.
  1119. void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V,
  1120. SDValue Val) {
  1121. auto DanglingDbgInfoIt = DanglingDebugInfoMap.find(V);
  1122. if (DanglingDbgInfoIt == DanglingDebugInfoMap.end())
  1123. return;
  1124. DanglingDebugInfoVector &DDIV = DanglingDbgInfoIt->second;
  1125. for (auto &DDI : DDIV) {
  1126. DebugLoc DL = DDI.getDebugLoc();
  1127. unsigned ValSDNodeOrder = Val.getNode()->getIROrder();
  1128. unsigned DbgSDNodeOrder = DDI.getSDNodeOrder();
  1129. DILocalVariable *Variable = DDI.getVariable(DAG.getFunctionVarLocs());
  1130. DIExpression *Expr = DDI.getExpression();
  1131. assert(Variable->isValidLocationForIntrinsic(DL) &&
  1132. "Expected inlined-at fields to agree");
  1133. SDDbgValue *SDV;
  1134. if (Val.getNode()) {
  1135. // FIXME: I doubt that it is correct to resolve a dangling DbgValue as a
  1136. // FuncArgumentDbgValue (it would be hoisted to the function entry, and if
  1137. // we couldn't resolve it directly when examining the DbgValue intrinsic
  1138. // in the first place we should not be more successful here). Unless we
  1139. // have some test case that prove this to be correct we should avoid
  1140. // calling EmitFuncArgumentDbgValue here.
  1141. if (!EmitFuncArgumentDbgValue(V, Variable, Expr, DL,
  1142. FuncArgumentDbgValueKind::Value, Val)) {
  1143. LLVM_DEBUG(dbgs() << "Resolve dangling debug info for " << printDDI(DDI)
  1144. << "\n");
  1145. LLVM_DEBUG(dbgs() << " By mapping to:\n "; Val.dump());
  1146. // Increase the SDNodeOrder for the DbgValue here to make sure it is
  1147. // inserted after the definition of Val when emitting the instructions
  1148. // after ISel. An alternative could be to teach
  1149. // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly.
  1150. LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs()
  1151. << "changing SDNodeOrder from " << DbgSDNodeOrder << " to "
  1152. << ValSDNodeOrder << "\n");
  1153. SDV = getDbgValue(Val, Variable, Expr, DL,
  1154. std::max(DbgSDNodeOrder, ValSDNodeOrder));
  1155. DAG.AddDbgValue(SDV, false);
  1156. } else
  1157. LLVM_DEBUG(dbgs() << "Resolved dangling debug info for "
  1158. << printDDI(DDI) << " in EmitFuncArgumentDbgValue\n");
  1159. } else {
  1160. LLVM_DEBUG(dbgs() << "Dropping debug info for " << printDDI(DDI) << "\n");
  1161. auto Undef = UndefValue::get(V->getType());
  1162. auto SDV =
  1163. DAG.getConstantDbgValue(Variable, Expr, Undef, DL, DbgSDNodeOrder);
  1164. DAG.AddDbgValue(SDV, false);
  1165. }
  1166. }
  1167. DDIV.clear();
  1168. }
  1169. void SelectionDAGBuilder::salvageUnresolvedDbgValue(DanglingDebugInfo &DDI) {
  1170. // TODO: For the variadic implementation, instead of only checking the fail
  1171. // state of `handleDebugValue`, we need know specifically which values were
  1172. // invalid, so that we attempt to salvage only those values when processing
  1173. // a DIArgList.
  1174. Value *V = DDI.getVariableLocationOp(0);
  1175. Value *OrigV = V;
  1176. DILocalVariable *Var = DDI.getVariable(DAG.getFunctionVarLocs());
  1177. DIExpression *Expr = DDI.getExpression();
  1178. DebugLoc DL = DDI.getDebugLoc();
  1179. unsigned SDOrder = DDI.getSDNodeOrder();
  1180. // Currently we consider only dbg.value intrinsics -- we tell the salvager
  1181. // that DW_OP_stack_value is desired.
  1182. bool StackValue = true;
  1183. // Can this Value can be encoded without any further work?
  1184. if (handleDebugValue(V, Var, Expr, DL, SDOrder, /*IsVariadic=*/false))
  1185. return;
  1186. // Attempt to salvage back through as many instructions as possible. Bail if
  1187. // a non-instruction is seen, such as a constant expression or global
  1188. // variable. FIXME: Further work could recover those too.
  1189. while (isa<Instruction>(V)) {
  1190. Instruction &VAsInst = *cast<Instruction>(V);
  1191. // Temporary "0", awaiting real implementation.
  1192. SmallVector<uint64_t, 16> Ops;
  1193. SmallVector<Value *, 4> AdditionalValues;
  1194. V = salvageDebugInfoImpl(VAsInst, Expr->getNumLocationOperands(), Ops,
  1195. AdditionalValues);
  1196. // If we cannot salvage any further, and haven't yet found a suitable debug
  1197. // expression, bail out.
  1198. if (!V)
  1199. break;
  1200. // TODO: If AdditionalValues isn't empty, then the salvage can only be
  1201. // represented with a DBG_VALUE_LIST, so we give up. When we have support
  1202. // here for variadic dbg_values, remove that condition.
  1203. if (!AdditionalValues.empty())
  1204. break;
  1205. // New value and expr now represent this debuginfo.
  1206. Expr = DIExpression::appendOpsToArg(Expr, Ops, 0, StackValue);
  1207. // Some kind of simplification occurred: check whether the operand of the
  1208. // salvaged debug expression can be encoded in this DAG.
  1209. if (handleDebugValue(V, Var, Expr, DL, SDOrder, /*IsVariadic=*/false)) {
  1210. LLVM_DEBUG(
  1211. dbgs() << "Salvaged debug location info for:\n " << *Var << "\n"
  1212. << *OrigV << "\nBy stripping back to:\n " << *V << "\n");
  1213. return;
  1214. }
  1215. }
  1216. // This was the final opportunity to salvage this debug information, and it
  1217. // couldn't be done. Place an undef DBG_VALUE at this location to terminate
  1218. // any earlier variable location.
  1219. assert(OrigV && "V shouldn't be null");
  1220. auto *Undef = UndefValue::get(OrigV->getType());
  1221. auto *SDV = DAG.getConstantDbgValue(Var, Expr, Undef, DL, SDNodeOrder);
  1222. DAG.AddDbgValue(SDV, false);
  1223. LLVM_DEBUG(dbgs() << "Dropping debug value info for:\n " << printDDI(DDI)
  1224. << "\n");
  1225. }
  1226. bool SelectionDAGBuilder::handleDebugValue(ArrayRef<const Value *> Values,
  1227. DILocalVariable *Var,
  1228. DIExpression *Expr, DebugLoc DbgLoc,
  1229. unsigned Order, bool IsVariadic) {
  1230. if (Values.empty())
  1231. return true;
  1232. SmallVector<SDDbgOperand> LocationOps;
  1233. SmallVector<SDNode *> Dependencies;
  1234. for (const Value *V : Values) {
  1235. // Constant value.
  1236. if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V) ||
  1237. isa<ConstantPointerNull>(V)) {
  1238. LocationOps.emplace_back(SDDbgOperand::fromConst(V));
  1239. continue;
  1240. }
  1241. // Look through IntToPtr constants.
  1242. if (auto *CE = dyn_cast<ConstantExpr>(V))
  1243. if (CE->getOpcode() == Instruction::IntToPtr) {
  1244. LocationOps.emplace_back(SDDbgOperand::fromConst(CE->getOperand(0)));
  1245. continue;
  1246. }
  1247. // If the Value is a frame index, we can create a FrameIndex debug value
  1248. // without relying on the DAG at all.
  1249. if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
  1250. auto SI = FuncInfo.StaticAllocaMap.find(AI);
  1251. if (SI != FuncInfo.StaticAllocaMap.end()) {
  1252. LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(SI->second));
  1253. continue;
  1254. }
  1255. }
  1256. // Do not use getValue() in here; we don't want to generate code at
  1257. // this point if it hasn't been done yet.
  1258. SDValue N = NodeMap[V];
  1259. if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map.
  1260. N = UnusedArgNodeMap[V];
  1261. if (N.getNode()) {
  1262. // Only emit func arg dbg value for non-variadic dbg.values for now.
  1263. if (!IsVariadic &&
  1264. EmitFuncArgumentDbgValue(V, Var, Expr, DbgLoc,
  1265. FuncArgumentDbgValueKind::Value, N))
  1266. return true;
  1267. if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) {
  1268. // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can
  1269. // describe stack slot locations.
  1270. //
  1271. // Consider "int x = 0; int *px = &x;". There are two kinds of
  1272. // interesting debug values here after optimization:
  1273. //
  1274. // dbg.value(i32* %px, !"int *px", !DIExpression()), and
  1275. // dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref))
  1276. //
  1277. // Both describe the direct values of their associated variables.
  1278. Dependencies.push_back(N.getNode());
  1279. LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(FISDN->getIndex()));
  1280. continue;
  1281. }
  1282. LocationOps.emplace_back(
  1283. SDDbgOperand::fromNode(N.getNode(), N.getResNo()));
  1284. continue;
  1285. }
  1286. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  1287. // Special rules apply for the first dbg.values of parameter variables in a
  1288. // function. Identify them by the fact they reference Argument Values, that
  1289. // they're parameters, and they are parameters of the current function. We
  1290. // need to let them dangle until they get an SDNode.
  1291. bool IsParamOfFunc =
  1292. isa<Argument>(V) && Var->isParameter() && !DbgLoc.getInlinedAt();
  1293. if (IsParamOfFunc)
  1294. return false;
  1295. // The value is not used in this block yet (or it would have an SDNode).
  1296. // We still want the value to appear for the user if possible -- if it has
  1297. // an associated VReg, we can refer to that instead.
  1298. auto VMI = FuncInfo.ValueMap.find(V);
  1299. if (VMI != FuncInfo.ValueMap.end()) {
  1300. unsigned Reg = VMI->second;
  1301. // If this is a PHI node, it may be split up into several MI PHI nodes
  1302. // (in FunctionLoweringInfo::set).
  1303. RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg,
  1304. V->getType(), std::nullopt);
  1305. if (RFV.occupiesMultipleRegs()) {
  1306. // FIXME: We could potentially support variadic dbg_values here.
  1307. if (IsVariadic)
  1308. return false;
  1309. unsigned Offset = 0;
  1310. unsigned BitsToDescribe = 0;
  1311. if (auto VarSize = Var->getSizeInBits())
  1312. BitsToDescribe = *VarSize;
  1313. if (auto Fragment = Expr->getFragmentInfo())
  1314. BitsToDescribe = Fragment->SizeInBits;
  1315. for (const auto &RegAndSize : RFV.getRegsAndSizes()) {
  1316. // Bail out if all bits are described already.
  1317. if (Offset >= BitsToDescribe)
  1318. break;
  1319. // TODO: handle scalable vectors.
  1320. unsigned RegisterSize = RegAndSize.second;
  1321. unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe)
  1322. ? BitsToDescribe - Offset
  1323. : RegisterSize;
  1324. auto FragmentExpr = DIExpression::createFragmentExpression(
  1325. Expr, Offset, FragmentSize);
  1326. if (!FragmentExpr)
  1327. continue;
  1328. SDDbgValue *SDV = DAG.getVRegDbgValue(
  1329. Var, *FragmentExpr, RegAndSize.first, false, DbgLoc, SDNodeOrder);
  1330. DAG.AddDbgValue(SDV, false);
  1331. Offset += RegisterSize;
  1332. }
  1333. return true;
  1334. }
  1335. // We can use simple vreg locations for variadic dbg_values as well.
  1336. LocationOps.emplace_back(SDDbgOperand::fromVReg(Reg));
  1337. continue;
  1338. }
  1339. // We failed to create a SDDbgOperand for V.
  1340. return false;
  1341. }
  1342. // We have created a SDDbgOperand for each Value in Values.
  1343. // Should use Order instead of SDNodeOrder?
  1344. assert(!LocationOps.empty());
  1345. SDDbgValue *SDV = DAG.getDbgValueList(Var, Expr, LocationOps, Dependencies,
  1346. /*IsIndirect=*/false, DbgLoc,
  1347. SDNodeOrder, IsVariadic);
  1348. DAG.AddDbgValue(SDV, /*isParameter=*/false);
  1349. return true;
  1350. }
  1351. void SelectionDAGBuilder::resolveOrClearDbgInfo() {
  1352. // Try to fixup any remaining dangling debug info -- and drop it if we can't.
  1353. for (auto &Pair : DanglingDebugInfoMap)
  1354. for (auto &DDI : Pair.second)
  1355. salvageUnresolvedDbgValue(DDI);
  1356. clearDanglingDebugInfo();
  1357. }
  1358. /// getCopyFromRegs - If there was virtual register allocated for the value V
  1359. /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise.
  1360. SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) {
  1361. DenseMap<const Value *, Register>::iterator It = FuncInfo.ValueMap.find(V);
  1362. SDValue Result;
  1363. if (It != FuncInfo.ValueMap.end()) {
  1364. Register InReg = It->second;
  1365. RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(),
  1366. DAG.getDataLayout(), InReg, Ty,
  1367. std::nullopt); // This is not an ABI copy.
  1368. SDValue Chain = DAG.getEntryNode();
  1369. Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr,
  1370. V);
  1371. resolveDanglingDebugInfo(V, Result);
  1372. }
  1373. return Result;
  1374. }
  1375. /// getValue - Return an SDValue for the given Value.
  1376. SDValue SelectionDAGBuilder::getValue(const Value *V) {
  1377. // If we already have an SDValue for this value, use it. It's important
  1378. // to do this first, so that we don't create a CopyFromReg if we already
  1379. // have a regular SDValue.
  1380. SDValue &N = NodeMap[V];
  1381. if (N.getNode()) return N;
  1382. // If there's a virtual register allocated and initialized for this
  1383. // value, use it.
  1384. if (SDValue copyFromReg = getCopyFromRegs(V, V->getType()))
  1385. return copyFromReg;
  1386. // Otherwise create a new SDValue and remember it.
  1387. SDValue Val = getValueImpl(V);
  1388. NodeMap[V] = Val;
  1389. resolveDanglingDebugInfo(V, Val);
  1390. return Val;
  1391. }
  1392. /// getNonRegisterValue - Return an SDValue for the given Value, but
  1393. /// don't look in FuncInfo.ValueMap for a virtual register.
  1394. SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) {
  1395. // If we already have an SDValue for this value, use it.
  1396. SDValue &N = NodeMap[V];
  1397. if (N.getNode()) {
  1398. if (isa<ConstantSDNode>(N) || isa<ConstantFPSDNode>(N)) {
  1399. // Remove the debug location from the node as the node is about to be used
  1400. // in a location which may differ from the original debug location. This
  1401. // is relevant to Constant and ConstantFP nodes because they can appear
  1402. // as constant expressions inside PHI nodes.
  1403. N->setDebugLoc(DebugLoc());
  1404. }
  1405. return N;
  1406. }
  1407. // Otherwise create a new SDValue and remember it.
  1408. SDValue Val = getValueImpl(V);
  1409. NodeMap[V] = Val;
  1410. resolveDanglingDebugInfo(V, Val);
  1411. return Val;
  1412. }
  1413. /// getValueImpl - Helper function for getValue and getNonRegisterValue.
  1414. /// Create an SDValue for the given value.
  1415. SDValue SelectionDAGBuilder::getValueImpl(const Value *V) {
  1416. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  1417. if (const Constant *C = dyn_cast<Constant>(V)) {
  1418. EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true);
  1419. if (const ConstantInt *CI = dyn_cast<ConstantInt>(C))
  1420. return DAG.getConstant(*CI, getCurSDLoc(), VT);
  1421. if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
  1422. return DAG.getGlobalAddress(GV, getCurSDLoc(), VT);
  1423. if (isa<ConstantPointerNull>(C)) {
  1424. unsigned AS = V->getType()->getPointerAddressSpace();
  1425. return DAG.getConstant(0, getCurSDLoc(),
  1426. TLI.getPointerTy(DAG.getDataLayout(), AS));
  1427. }
  1428. if (match(C, m_VScale(DAG.getDataLayout())))
  1429. return DAG.getVScale(getCurSDLoc(), VT, APInt(VT.getSizeInBits(), 1));
  1430. if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
  1431. return DAG.getConstantFP(*CFP, getCurSDLoc(), VT);
  1432. if (isa<UndefValue>(C) && !V->getType()->isAggregateType())
  1433. return DAG.getUNDEF(VT);
  1434. if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
  1435. visit(CE->getOpcode(), *CE);
  1436. SDValue N1 = NodeMap[V];
  1437. assert(N1.getNode() && "visit didn't populate the NodeMap!");
  1438. return N1;
  1439. }
  1440. if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
  1441. SmallVector<SDValue, 4> Constants;
  1442. for (const Use &U : C->operands()) {
  1443. SDNode *Val = getValue(U).getNode();
  1444. // If the operand is an empty aggregate, there are no values.
  1445. if (!Val) continue;
  1446. // Add each leaf value from the operand to the Constants list
  1447. // to form a flattened list of all the values.
  1448. for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
  1449. Constants.push_back(SDValue(Val, i));
  1450. }
  1451. return DAG.getMergeValues(Constants, getCurSDLoc());
  1452. }
  1453. if (const ConstantDataSequential *CDS =
  1454. dyn_cast<ConstantDataSequential>(C)) {
  1455. SmallVector<SDValue, 4> Ops;
  1456. for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
  1457. SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode();
  1458. // Add each leaf value from the operand to the Constants list
  1459. // to form a flattened list of all the values.
  1460. for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
  1461. Ops.push_back(SDValue(Val, i));
  1462. }
  1463. if (isa<ArrayType>(CDS->getType()))
  1464. return DAG.getMergeValues(Ops, getCurSDLoc());
  1465. return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
  1466. }
  1467. if (C->getType()->isStructTy() || C->getType()->isArrayTy()) {
  1468. assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
  1469. "Unknown struct or array constant!");
  1470. SmallVector<EVT, 4> ValueVTs;
  1471. ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs);
  1472. unsigned NumElts = ValueVTs.size();
  1473. if (NumElts == 0)
  1474. return SDValue(); // empty struct
  1475. SmallVector<SDValue, 4> Constants(NumElts);
  1476. for (unsigned i = 0; i != NumElts; ++i) {
  1477. EVT EltVT = ValueVTs[i];
  1478. if (isa<UndefValue>(C))
  1479. Constants[i] = DAG.getUNDEF(EltVT);
  1480. else if (EltVT.isFloatingPoint())
  1481. Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
  1482. else
  1483. Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT);
  1484. }
  1485. return DAG.getMergeValues(Constants, getCurSDLoc());
  1486. }
  1487. if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
  1488. return DAG.getBlockAddress(BA, VT);
  1489. if (const auto *Equiv = dyn_cast<DSOLocalEquivalent>(C))
  1490. return getValue(Equiv->getGlobalValue());
  1491. if (const auto *NC = dyn_cast<NoCFIValue>(C))
  1492. return getValue(NC->getGlobalValue());
  1493. VectorType *VecTy = cast<VectorType>(V->getType());
  1494. // Now that we know the number and type of the elements, get that number of
  1495. // elements into the Ops array based on what kind of constant it is.
  1496. if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) {
  1497. SmallVector<SDValue, 16> Ops;
  1498. unsigned NumElements = cast<FixedVectorType>(VecTy)->getNumElements();
  1499. for (unsigned i = 0; i != NumElements; ++i)
  1500. Ops.push_back(getValue(CV->getOperand(i)));
  1501. return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
  1502. }
  1503. if (isa<ConstantAggregateZero>(C)) {
  1504. EVT EltVT =
  1505. TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType());
  1506. SDValue Op;
  1507. if (EltVT.isFloatingPoint())
  1508. Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
  1509. else
  1510. Op = DAG.getConstant(0, getCurSDLoc(), EltVT);
  1511. return NodeMap[V] = DAG.getSplat(VT, getCurSDLoc(), Op);
  1512. }
  1513. llvm_unreachable("Unknown vector constant");
  1514. }
  1515. // If this is a static alloca, generate it as the frameindex instead of
  1516. // computation.
  1517. if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
  1518. DenseMap<const AllocaInst*, int>::iterator SI =
  1519. FuncInfo.StaticAllocaMap.find(AI);
  1520. if (SI != FuncInfo.StaticAllocaMap.end())
  1521. return DAG.getFrameIndex(
  1522. SI->second, TLI.getValueType(DAG.getDataLayout(), AI->getType()));
  1523. }
  1524. // If this is an instruction which fast-isel has deferred, select it now.
  1525. if (const Instruction *Inst = dyn_cast<Instruction>(V)) {
  1526. Register InReg = FuncInfo.InitializeRegForValue(Inst);
  1527. RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg,
  1528. Inst->getType(), std::nullopt);
  1529. SDValue Chain = DAG.getEntryNode();
  1530. return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V);
  1531. }
  1532. if (const MetadataAsValue *MD = dyn_cast<MetadataAsValue>(V))
  1533. return DAG.getMDNode(cast<MDNode>(MD->getMetadata()));
  1534. if (const auto *BB = dyn_cast<BasicBlock>(V))
  1535. return DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
  1536. llvm_unreachable("Can't get register for value!");
  1537. }
  1538. void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) {
  1539. auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
  1540. bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX;
  1541. bool IsCoreCLR = Pers == EHPersonality::CoreCLR;
  1542. bool IsSEH = isAsynchronousEHPersonality(Pers);
  1543. MachineBasicBlock *CatchPadMBB = FuncInfo.MBB;
  1544. if (!IsSEH)
  1545. CatchPadMBB->setIsEHScopeEntry();
  1546. // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues.
  1547. if (IsMSVCCXX || IsCoreCLR)
  1548. CatchPadMBB->setIsEHFuncletEntry();
  1549. }
  1550. void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) {
  1551. // Update machine-CFG edge.
  1552. MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()];
  1553. FuncInfo.MBB->addSuccessor(TargetMBB);
  1554. TargetMBB->setIsEHCatchretTarget(true);
  1555. DAG.getMachineFunction().setHasEHCatchret(true);
  1556. auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
  1557. bool IsSEH = isAsynchronousEHPersonality(Pers);
  1558. if (IsSEH) {
  1559. // If this is not a fall-through branch or optimizations are switched off,
  1560. // emit the branch.
  1561. if (TargetMBB != NextBlock(FuncInfo.MBB) ||
  1562. TM.getOptLevel() == CodeGenOpt::None)
  1563. DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
  1564. getControlRoot(), DAG.getBasicBlock(TargetMBB)));
  1565. return;
  1566. }
  1567. // Figure out the funclet membership for the catchret's successor.
  1568. // This will be used by the FuncletLayout pass to determine how to order the
  1569. // BB's.
  1570. // A 'catchret' returns to the outer scope's color.
  1571. Value *ParentPad = I.getCatchSwitchParentPad();
  1572. const BasicBlock *SuccessorColor;
  1573. if (isa<ConstantTokenNone>(ParentPad))
  1574. SuccessorColor = &FuncInfo.Fn->getEntryBlock();
  1575. else
  1576. SuccessorColor = cast<Instruction>(ParentPad)->getParent();
  1577. assert(SuccessorColor && "No parent funclet for catchret!");
  1578. MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor];
  1579. assert(SuccessorColorMBB && "No MBB for SuccessorColor!");
  1580. // Create the terminator node.
  1581. SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other,
  1582. getControlRoot(), DAG.getBasicBlock(TargetMBB),
  1583. DAG.getBasicBlock(SuccessorColorMBB));
  1584. DAG.setRoot(Ret);
  1585. }
  1586. void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) {
  1587. // Don't emit any special code for the cleanuppad instruction. It just marks
  1588. // the start of an EH scope/funclet.
  1589. FuncInfo.MBB->setIsEHScopeEntry();
  1590. auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
  1591. if (Pers != EHPersonality::Wasm_CXX) {
  1592. FuncInfo.MBB->setIsEHFuncletEntry();
  1593. FuncInfo.MBB->setIsCleanupFuncletEntry();
  1594. }
  1595. }
  1596. // In wasm EH, even though a catchpad may not catch an exception if a tag does
  1597. // not match, it is OK to add only the first unwind destination catchpad to the
  1598. // successors, because there will be at least one invoke instruction within the
  1599. // catch scope that points to the next unwind destination, if one exists, so
  1600. // CFGSort cannot mess up with BB sorting order.
  1601. // (All catchpads with 'catch (type)' clauses have a 'llvm.rethrow' intrinsic
  1602. // call within them, and catchpads only consisting of 'catch (...)' have a
  1603. // '__cxa_end_catch' call within them, both of which generate invokes in case
  1604. // the next unwind destination exists, i.e., the next unwind destination is not
  1605. // the caller.)
  1606. //
  1607. // Having at most one EH pad successor is also simpler and helps later
  1608. // transformations.
  1609. //
  1610. // For example,
  1611. // current:
  1612. // invoke void @foo to ... unwind label %catch.dispatch
  1613. // catch.dispatch:
  1614. // %0 = catchswitch within ... [label %catch.start] unwind label %next
  1615. // catch.start:
  1616. // ...
  1617. // ... in this BB or some other child BB dominated by this BB there will be an
  1618. // invoke that points to 'next' BB as an unwind destination
  1619. //
  1620. // next: ; We don't need to add this to 'current' BB's successor
  1621. // ...
  1622. static void findWasmUnwindDestinations(
  1623. FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
  1624. BranchProbability Prob,
  1625. SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
  1626. &UnwindDests) {
  1627. while (EHPadBB) {
  1628. const Instruction *Pad = EHPadBB->getFirstNonPHI();
  1629. if (isa<CleanupPadInst>(Pad)) {
  1630. // Stop on cleanup pads.
  1631. UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
  1632. UnwindDests.back().first->setIsEHScopeEntry();
  1633. break;
  1634. } else if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
  1635. // Add the catchpad handlers to the possible destinations. We don't
  1636. // continue to the unwind destination of the catchswitch for wasm.
  1637. for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
  1638. UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
  1639. UnwindDests.back().first->setIsEHScopeEntry();
  1640. }
  1641. break;
  1642. } else {
  1643. continue;
  1644. }
  1645. }
  1646. }
  1647. /// When an invoke or a cleanupret unwinds to the next EH pad, there are
  1648. /// many places it could ultimately go. In the IR, we have a single unwind
  1649. /// destination, but in the machine CFG, we enumerate all the possible blocks.
  1650. /// This function skips over imaginary basic blocks that hold catchswitch
  1651. /// instructions, and finds all the "real" machine
  1652. /// basic block destinations. As those destinations may not be successors of
  1653. /// EHPadBB, here we also calculate the edge probability to those destinations.
  1654. /// The passed-in Prob is the edge probability to EHPadBB.
  1655. static void findUnwindDestinations(
  1656. FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
  1657. BranchProbability Prob,
  1658. SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
  1659. &UnwindDests) {
  1660. EHPersonality Personality =
  1661. classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
  1662. bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX;
  1663. bool IsCoreCLR = Personality == EHPersonality::CoreCLR;
  1664. bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX;
  1665. bool IsSEH = isAsynchronousEHPersonality(Personality);
  1666. if (IsWasmCXX) {
  1667. findWasmUnwindDestinations(FuncInfo, EHPadBB, Prob, UnwindDests);
  1668. assert(UnwindDests.size() <= 1 &&
  1669. "There should be at most one unwind destination for wasm");
  1670. return;
  1671. }
  1672. while (EHPadBB) {
  1673. const Instruction *Pad = EHPadBB->getFirstNonPHI();
  1674. BasicBlock *NewEHPadBB = nullptr;
  1675. if (isa<LandingPadInst>(Pad)) {
  1676. // Stop on landingpads. They are not funclets.
  1677. UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
  1678. break;
  1679. } else if (isa<CleanupPadInst>(Pad)) {
  1680. // Stop on cleanup pads. Cleanups are always funclet entries for all known
  1681. // personalities.
  1682. UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
  1683. UnwindDests.back().first->setIsEHScopeEntry();
  1684. UnwindDests.back().first->setIsEHFuncletEntry();
  1685. break;
  1686. } else if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
  1687. // Add the catchpad handlers to the possible destinations.
  1688. for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
  1689. UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
  1690. // For MSVC++ and the CLR, catchblocks are funclets and need prologues.
  1691. if (IsMSVCCXX || IsCoreCLR)
  1692. UnwindDests.back().first->setIsEHFuncletEntry();
  1693. if (!IsSEH)
  1694. UnwindDests.back().first->setIsEHScopeEntry();
  1695. }
  1696. NewEHPadBB = CatchSwitch->getUnwindDest();
  1697. } else {
  1698. continue;
  1699. }
  1700. BranchProbabilityInfo *BPI = FuncInfo.BPI;
  1701. if (BPI && NewEHPadBB)
  1702. Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB);
  1703. EHPadBB = NewEHPadBB;
  1704. }
  1705. }
  1706. void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) {
  1707. // Update successor info.
  1708. SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
  1709. auto UnwindDest = I.getUnwindDest();
  1710. BranchProbabilityInfo *BPI = FuncInfo.BPI;
  1711. BranchProbability UnwindDestProb =
  1712. (BPI && UnwindDest)
  1713. ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest)
  1714. : BranchProbability::getZero();
  1715. findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests);
  1716. for (auto &UnwindDest : UnwindDests) {
  1717. UnwindDest.first->setIsEHPad();
  1718. addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second);
  1719. }
  1720. FuncInfo.MBB->normalizeSuccProbs();
  1721. // Create the terminator node.
  1722. SDValue Ret =
  1723. DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot());
  1724. DAG.setRoot(Ret);
  1725. }
  1726. void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) {
  1727. report_fatal_error("visitCatchSwitch not yet implemented!");
  1728. }
  1729. void SelectionDAGBuilder::visitRet(const ReturnInst &I) {
  1730. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  1731. auto &DL = DAG.getDataLayout();
  1732. SDValue Chain = getControlRoot();
  1733. SmallVector<ISD::OutputArg, 8> Outs;
  1734. SmallVector<SDValue, 8> OutVals;
  1735. // Calls to @llvm.experimental.deoptimize don't generate a return value, so
  1736. // lower
  1737. //
  1738. // %val = call <ty> @llvm.experimental.deoptimize()
  1739. // ret <ty> %val
  1740. //
  1741. // differently.
  1742. if (I.getParent()->getTerminatingDeoptimizeCall()) {
  1743. LowerDeoptimizingReturn();
  1744. return;
  1745. }
  1746. if (!FuncInfo.CanLowerReturn) {
  1747. unsigned DemoteReg = FuncInfo.DemoteRegister;
  1748. const Function *F = I.getParent()->getParent();
  1749. // Emit a store of the return value through the virtual register.
  1750. // Leave Outs empty so that LowerReturn won't try to load return
  1751. // registers the usual way.
  1752. SmallVector<EVT, 1> PtrValueVTs;
  1753. ComputeValueVTs(TLI, DL,
  1754. F->getReturnType()->getPointerTo(
  1755. DAG.getDataLayout().getAllocaAddrSpace()),
  1756. PtrValueVTs);
  1757. SDValue RetPtr =
  1758. DAG.getCopyFromReg(Chain, getCurSDLoc(), DemoteReg, PtrValueVTs[0]);
  1759. SDValue RetOp = getValue(I.getOperand(0));
  1760. SmallVector<EVT, 4> ValueVTs, MemVTs;
  1761. SmallVector<uint64_t, 4> Offsets;
  1762. ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &MemVTs,
  1763. &Offsets);
  1764. unsigned NumValues = ValueVTs.size();
  1765. SmallVector<SDValue, 4> Chains(NumValues);
  1766. Align BaseAlign = DL.getPrefTypeAlign(I.getOperand(0)->getType());
  1767. for (unsigned i = 0; i != NumValues; ++i) {
  1768. // An aggregate return value cannot wrap around the address space, so
  1769. // offsets to its parts don't wrap either.
  1770. SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr,
  1771. TypeSize::Fixed(Offsets[i]));
  1772. SDValue Val = RetOp.getValue(RetOp.getResNo() + i);
  1773. if (MemVTs[i] != ValueVTs[i])
  1774. Val = DAG.getPtrExtOrTrunc(Val, getCurSDLoc(), MemVTs[i]);
  1775. Chains[i] = DAG.getStore(
  1776. Chain, getCurSDLoc(), Val,
  1777. // FIXME: better loc info would be nice.
  1778. Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction()),
  1779. commonAlignment(BaseAlign, Offsets[i]));
  1780. }
  1781. Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
  1782. MVT::Other, Chains);
  1783. } else if (I.getNumOperands() != 0) {
  1784. SmallVector<EVT, 4> ValueVTs;
  1785. ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs);
  1786. unsigned NumValues = ValueVTs.size();
  1787. if (NumValues) {
  1788. SDValue RetOp = getValue(I.getOperand(0));
  1789. const Function *F = I.getParent()->getParent();
  1790. bool NeedsRegBlock = TLI.functionArgumentNeedsConsecutiveRegisters(
  1791. I.getOperand(0)->getType(), F->getCallingConv(),
  1792. /*IsVarArg*/ false, DL);
  1793. ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
  1794. if (F->getAttributes().hasRetAttr(Attribute::SExt))
  1795. ExtendKind = ISD::SIGN_EXTEND;
  1796. else if (F->getAttributes().hasRetAttr(Attribute::ZExt))
  1797. ExtendKind = ISD::ZERO_EXTEND;
  1798. LLVMContext &Context = F->getContext();
  1799. bool RetInReg = F->getAttributes().hasRetAttr(Attribute::InReg);
  1800. for (unsigned j = 0; j != NumValues; ++j) {
  1801. EVT VT = ValueVTs[j];
  1802. if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger())
  1803. VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind);
  1804. CallingConv::ID CC = F->getCallingConv();
  1805. unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT);
  1806. MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT);
  1807. SmallVector<SDValue, 4> Parts(NumParts);
  1808. getCopyToParts(DAG, getCurSDLoc(),
  1809. SDValue(RetOp.getNode(), RetOp.getResNo() + j),
  1810. &Parts[0], NumParts, PartVT, &I, CC, ExtendKind);
  1811. // 'inreg' on function refers to return value
  1812. ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
  1813. if (RetInReg)
  1814. Flags.setInReg();
  1815. if (I.getOperand(0)->getType()->isPointerTy()) {
  1816. Flags.setPointer();
  1817. Flags.setPointerAddrSpace(
  1818. cast<PointerType>(I.getOperand(0)->getType())->getAddressSpace());
  1819. }
  1820. if (NeedsRegBlock) {
  1821. Flags.setInConsecutiveRegs();
  1822. if (j == NumValues - 1)
  1823. Flags.setInConsecutiveRegsLast();
  1824. }
  1825. // Propagate extension type if any
  1826. if (ExtendKind == ISD::SIGN_EXTEND)
  1827. Flags.setSExt();
  1828. else if (ExtendKind == ISD::ZERO_EXTEND)
  1829. Flags.setZExt();
  1830. for (unsigned i = 0; i < NumParts; ++i) {
  1831. Outs.push_back(ISD::OutputArg(Flags,
  1832. Parts[i].getValueType().getSimpleVT(),
  1833. VT, /*isfixed=*/true, 0, 0));
  1834. OutVals.push_back(Parts[i]);
  1835. }
  1836. }
  1837. }
  1838. }
  1839. // Push in swifterror virtual register as the last element of Outs. This makes
  1840. // sure swifterror virtual register will be returned in the swifterror
  1841. // physical register.
  1842. const Function *F = I.getParent()->getParent();
  1843. if (TLI.supportSwiftError() &&
  1844. F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) {
  1845. assert(SwiftError.getFunctionArg() && "Need a swift error argument");
  1846. ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
  1847. Flags.setSwiftError();
  1848. Outs.push_back(ISD::OutputArg(
  1849. Flags, /*vt=*/TLI.getPointerTy(DL), /*argvt=*/EVT(TLI.getPointerTy(DL)),
  1850. /*isfixed=*/true, /*origidx=*/1, /*partOffs=*/0));
  1851. // Create SDNode for the swifterror virtual register.
  1852. OutVals.push_back(
  1853. DAG.getRegister(SwiftError.getOrCreateVRegUseAt(
  1854. &I, FuncInfo.MBB, SwiftError.getFunctionArg()),
  1855. EVT(TLI.getPointerTy(DL))));
  1856. }
  1857. bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg();
  1858. CallingConv::ID CallConv =
  1859. DAG.getMachineFunction().getFunction().getCallingConv();
  1860. Chain = DAG.getTargetLoweringInfo().LowerReturn(
  1861. Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG);
  1862. // Verify that the target's LowerReturn behaved as expected.
  1863. assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
  1864. "LowerReturn didn't return a valid chain!");
  1865. // Update the DAG with the new chain value resulting from return lowering.
  1866. DAG.setRoot(Chain);
  1867. }
  1868. /// CopyToExportRegsIfNeeded - If the given value has virtual registers
  1869. /// created for it, emit nodes to copy the value into the virtual
  1870. /// registers.
  1871. void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) {
  1872. // Skip empty types
  1873. if (V->getType()->isEmptyTy())
  1874. return;
  1875. DenseMap<const Value *, Register>::iterator VMI = FuncInfo.ValueMap.find(V);
  1876. if (VMI != FuncInfo.ValueMap.end()) {
  1877. assert(!V->use_empty() && "Unused value assigned virtual registers!");
  1878. CopyValueToVirtualRegister(V, VMI->second);
  1879. }
  1880. }
  1881. /// ExportFromCurrentBlock - If this condition isn't known to be exported from
  1882. /// the current basic block, add it to ValueMap now so that we'll get a
  1883. /// CopyTo/FromReg.
  1884. void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) {
  1885. // No need to export constants.
  1886. if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
  1887. // Already exported?
  1888. if (FuncInfo.isExportedInst(V)) return;
  1889. Register Reg = FuncInfo.InitializeRegForValue(V);
  1890. CopyValueToVirtualRegister(V, Reg);
  1891. }
  1892. bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V,
  1893. const BasicBlock *FromBB) {
  1894. // The operands of the setcc have to be in this block. We don't know
  1895. // how to export them from some other block.
  1896. if (const Instruction *VI = dyn_cast<Instruction>(V)) {
  1897. // Can export from current BB.
  1898. if (VI->getParent() == FromBB)
  1899. return true;
  1900. // Is already exported, noop.
  1901. return FuncInfo.isExportedInst(V);
  1902. }
  1903. // If this is an argument, we can export it if the BB is the entry block or
  1904. // if it is already exported.
  1905. if (isa<Argument>(V)) {
  1906. if (FromBB->isEntryBlock())
  1907. return true;
  1908. // Otherwise, can only export this if it is already exported.
  1909. return FuncInfo.isExportedInst(V);
  1910. }
  1911. // Otherwise, constants can always be exported.
  1912. return true;
  1913. }
  1914. /// Return branch probability calculated by BranchProbabilityInfo for IR blocks.
  1915. BranchProbability
  1916. SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src,
  1917. const MachineBasicBlock *Dst) const {
  1918. BranchProbabilityInfo *BPI = FuncInfo.BPI;
  1919. const BasicBlock *SrcBB = Src->getBasicBlock();
  1920. const BasicBlock *DstBB = Dst->getBasicBlock();
  1921. if (!BPI) {
  1922. // If BPI is not available, set the default probability as 1 / N, where N is
  1923. // the number of successors.
  1924. auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1);
  1925. return BranchProbability(1, SuccSize);
  1926. }
  1927. return BPI->getEdgeProbability(SrcBB, DstBB);
  1928. }
  1929. void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src,
  1930. MachineBasicBlock *Dst,
  1931. BranchProbability Prob) {
  1932. if (!FuncInfo.BPI)
  1933. Src->addSuccessorWithoutProb(Dst);
  1934. else {
  1935. if (Prob.isUnknown())
  1936. Prob = getEdgeProbability(Src, Dst);
  1937. Src->addSuccessor(Dst, Prob);
  1938. }
  1939. }
  1940. static bool InBlock(const Value *V, const BasicBlock *BB) {
  1941. if (const Instruction *I = dyn_cast<Instruction>(V))
  1942. return I->getParent() == BB;
  1943. return true;
  1944. }
  1945. /// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
  1946. /// This function emits a branch and is used at the leaves of an OR or an
  1947. /// AND operator tree.
  1948. void
  1949. SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond,
  1950. MachineBasicBlock *TBB,
  1951. MachineBasicBlock *FBB,
  1952. MachineBasicBlock *CurBB,
  1953. MachineBasicBlock *SwitchBB,
  1954. BranchProbability TProb,
  1955. BranchProbability FProb,
  1956. bool InvertCond) {
  1957. const BasicBlock *BB = CurBB->getBasicBlock();
  1958. // If the leaf of the tree is a comparison, merge the condition into
  1959. // the caseblock.
  1960. if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
  1961. // The operands of the cmp have to be in this block. We don't know
  1962. // how to export them from some other block. If this is the first block
  1963. // of the sequence, no exporting is needed.
  1964. if (CurBB == SwitchBB ||
  1965. (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
  1966. isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
  1967. ISD::CondCode Condition;
  1968. if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
  1969. ICmpInst::Predicate Pred =
  1970. InvertCond ? IC->getInversePredicate() : IC->getPredicate();
  1971. Condition = getICmpCondCode(Pred);
  1972. } else {
  1973. const FCmpInst *FC = cast<FCmpInst>(Cond);
  1974. FCmpInst::Predicate Pred =
  1975. InvertCond ? FC->getInversePredicate() : FC->getPredicate();
  1976. Condition = getFCmpCondCode(Pred);
  1977. if (TM.Options.NoNaNsFPMath)
  1978. Condition = getFCmpCodeWithoutNaN(Condition);
  1979. }
  1980. CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr,
  1981. TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
  1982. SL->SwitchCases.push_back(CB);
  1983. return;
  1984. }
  1985. }
  1986. // Create a CaseBlock record representing this branch.
  1987. ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ;
  1988. CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()),
  1989. nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
  1990. SL->SwitchCases.push_back(CB);
  1991. }
  1992. void SelectionDAGBuilder::FindMergedConditions(const Value *Cond,
  1993. MachineBasicBlock *TBB,
  1994. MachineBasicBlock *FBB,
  1995. MachineBasicBlock *CurBB,
  1996. MachineBasicBlock *SwitchBB,
  1997. Instruction::BinaryOps Opc,
  1998. BranchProbability TProb,
  1999. BranchProbability FProb,
  2000. bool InvertCond) {
  2001. // Skip over not part of the tree and remember to invert op and operands at
  2002. // next level.
  2003. Value *NotCond;
  2004. if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) &&
  2005. InBlock(NotCond, CurBB->getBasicBlock())) {
  2006. FindMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb,
  2007. !InvertCond);
  2008. return;
  2009. }
  2010. const Instruction *BOp = dyn_cast<Instruction>(Cond);
  2011. const Value *BOpOp0, *BOpOp1;
  2012. // Compute the effective opcode for Cond, taking into account whether it needs
  2013. // to be inverted, e.g.
  2014. // and (not (or A, B)), C
  2015. // gets lowered as
  2016. // and (and (not A, not B), C)
  2017. Instruction::BinaryOps BOpc = (Instruction::BinaryOps)0;
  2018. if (BOp) {
  2019. BOpc = match(BOp, m_LogicalAnd(m_Value(BOpOp0), m_Value(BOpOp1)))
  2020. ? Instruction::And
  2021. : (match(BOp, m_LogicalOr(m_Value(BOpOp0), m_Value(BOpOp1)))
  2022. ? Instruction::Or
  2023. : (Instruction::BinaryOps)0);
  2024. if (InvertCond) {
  2025. if (BOpc == Instruction::And)
  2026. BOpc = Instruction::Or;
  2027. else if (BOpc == Instruction::Or)
  2028. BOpc = Instruction::And;
  2029. }
  2030. }
  2031. // If this node is not part of the or/and tree, emit it as a branch.
  2032. // Note that all nodes in the tree should have same opcode.
  2033. bool BOpIsInOrAndTree = BOpc && BOpc == Opc && BOp->hasOneUse();
  2034. if (!BOpIsInOrAndTree || BOp->getParent() != CurBB->getBasicBlock() ||
  2035. !InBlock(BOpOp0, CurBB->getBasicBlock()) ||
  2036. !InBlock(BOpOp1, CurBB->getBasicBlock())) {
  2037. EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB,
  2038. TProb, FProb, InvertCond);
  2039. return;
  2040. }
  2041. // Create TmpBB after CurBB.
  2042. MachineFunction::iterator BBI(CurBB);
  2043. MachineFunction &MF = DAG.getMachineFunction();
  2044. MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
  2045. CurBB->getParent()->insert(++BBI, TmpBB);
  2046. if (Opc == Instruction::Or) {
  2047. // Codegen X | Y as:
  2048. // BB1:
  2049. // jmp_if_X TBB
  2050. // jmp TmpBB
  2051. // TmpBB:
  2052. // jmp_if_Y TBB
  2053. // jmp FBB
  2054. //
  2055. // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
  2056. // The requirement is that
  2057. // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
  2058. // = TrueProb for original BB.
  2059. // Assuming the original probabilities are A and B, one choice is to set
  2060. // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to
  2061. // A/(1+B) and 2B/(1+B). This choice assumes that
  2062. // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
  2063. // Another choice is to assume TrueProb for BB1 equals to TrueProb for
  2064. // TmpBB, but the math is more complicated.
  2065. auto NewTrueProb = TProb / 2;
  2066. auto NewFalseProb = TProb / 2 + FProb;
  2067. // Emit the LHS condition.
  2068. FindMergedConditions(BOpOp0, TBB, TmpBB, CurBB, SwitchBB, Opc, NewTrueProb,
  2069. NewFalseProb, InvertCond);
  2070. // Normalize A/2 and B to get A/(1+B) and 2B/(1+B).
  2071. SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb};
  2072. BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
  2073. // Emit the RHS condition into TmpBB.
  2074. FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0],
  2075. Probs[1], InvertCond);
  2076. } else {
  2077. assert(Opc == Instruction::And && "Unknown merge op!");
  2078. // Codegen X & Y as:
  2079. // BB1:
  2080. // jmp_if_X TmpBB
  2081. // jmp FBB
  2082. // TmpBB:
  2083. // jmp_if_Y TBB
  2084. // jmp FBB
  2085. //
  2086. // This requires creation of TmpBB after CurBB.
  2087. // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
  2088. // The requirement is that
  2089. // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
  2090. // = FalseProb for original BB.
  2091. // Assuming the original probabilities are A and B, one choice is to set
  2092. // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to
  2093. // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 ==
  2094. // TrueProb for BB1 * FalseProb for TmpBB.
  2095. auto NewTrueProb = TProb + FProb / 2;
  2096. auto NewFalseProb = FProb / 2;
  2097. // Emit the LHS condition.
  2098. FindMergedConditions(BOpOp0, TmpBB, FBB, CurBB, SwitchBB, Opc, NewTrueProb,
  2099. NewFalseProb, InvertCond);
  2100. // Normalize A and B/2 to get 2A/(1+A) and B/(1+A).
  2101. SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2};
  2102. BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
  2103. // Emit the RHS condition into TmpBB.
  2104. FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0],
  2105. Probs[1], InvertCond);
  2106. }
  2107. }
  2108. /// If the set of cases should be emitted as a series of branches, return true.
  2109. /// If we should emit this as a bunch of and/or'd together conditions, return
  2110. /// false.
  2111. bool
  2112. SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) {
  2113. if (Cases.size() != 2) return true;
  2114. // If this is two comparisons of the same values or'd or and'd together, they
  2115. // will get folded into a single comparison, so don't emit two blocks.
  2116. if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
  2117. Cases[0].CmpRHS == Cases[1].CmpRHS) ||
  2118. (Cases[0].CmpRHS == Cases[1].CmpLHS &&
  2119. Cases[0].CmpLHS == Cases[1].CmpRHS)) {
  2120. return false;
  2121. }
  2122. // Handle: (X != null) | (Y != null) --> (X|Y) != 0
  2123. // Handle: (X == null) & (Y == null) --> (X|Y) == 0
  2124. if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
  2125. Cases[0].CC == Cases[1].CC &&
  2126. isa<Constant>(Cases[0].CmpRHS) &&
  2127. cast<Constant>(Cases[0].CmpRHS)->isNullValue()) {
  2128. if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB)
  2129. return false;
  2130. if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB)
  2131. return false;
  2132. }
  2133. return true;
  2134. }
  2135. void SelectionDAGBuilder::visitBr(const BranchInst &I) {
  2136. MachineBasicBlock *BrMBB = FuncInfo.MBB;
  2137. // Update machine-CFG edges.
  2138. MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
  2139. if (I.isUnconditional()) {
  2140. // Update machine-CFG edges.
  2141. BrMBB->addSuccessor(Succ0MBB);
  2142. // If this is not a fall-through branch or optimizations are switched off,
  2143. // emit the branch.
  2144. if (Succ0MBB != NextBlock(BrMBB) || TM.getOptLevel() == CodeGenOpt::None)
  2145. DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
  2146. MVT::Other, getControlRoot(),
  2147. DAG.getBasicBlock(Succ0MBB)));
  2148. return;
  2149. }
  2150. // If this condition is one of the special cases we handle, do special stuff
  2151. // now.
  2152. const Value *CondVal = I.getCondition();
  2153. MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
  2154. // If this is a series of conditions that are or'd or and'd together, emit
  2155. // this as a sequence of branches instead of setcc's with and/or operations.
  2156. // As long as jumps are not expensive (exceptions for multi-use logic ops,
  2157. // unpredictable branches, and vector extracts because those jumps are likely
  2158. // expensive for any target), this should improve performance.
  2159. // For example, instead of something like:
  2160. // cmp A, B
  2161. // C = seteq
  2162. // cmp D, E
  2163. // F = setle
  2164. // or C, F
  2165. // jnz foo
  2166. // Emit:
  2167. // cmp A, B
  2168. // je foo
  2169. // cmp D, E
  2170. // jle foo
  2171. const Instruction *BOp = dyn_cast<Instruction>(CondVal);
  2172. if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp &&
  2173. BOp->hasOneUse() && !I.hasMetadata(LLVMContext::MD_unpredictable)) {
  2174. Value *Vec;
  2175. const Value *BOp0, *BOp1;
  2176. Instruction::BinaryOps Opcode = (Instruction::BinaryOps)0;
  2177. if (match(BOp, m_LogicalAnd(m_Value(BOp0), m_Value(BOp1))))
  2178. Opcode = Instruction::And;
  2179. else if (match(BOp, m_LogicalOr(m_Value(BOp0), m_Value(BOp1))))
  2180. Opcode = Instruction::Or;
  2181. if (Opcode && !(match(BOp0, m_ExtractElt(m_Value(Vec), m_Value())) &&
  2182. match(BOp1, m_ExtractElt(m_Specific(Vec), m_Value())))) {
  2183. FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB, Opcode,
  2184. getEdgeProbability(BrMBB, Succ0MBB),
  2185. getEdgeProbability(BrMBB, Succ1MBB),
  2186. /*InvertCond=*/false);
  2187. // If the compares in later blocks need to use values not currently
  2188. // exported from this block, export them now. This block should always
  2189. // be the first entry.
  2190. assert(SL->SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!");
  2191. // Allow some cases to be rejected.
  2192. if (ShouldEmitAsBranches(SL->SwitchCases)) {
  2193. for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) {
  2194. ExportFromCurrentBlock(SL->SwitchCases[i].CmpLHS);
  2195. ExportFromCurrentBlock(SL->SwitchCases[i].CmpRHS);
  2196. }
  2197. // Emit the branch for this block.
  2198. visitSwitchCase(SL->SwitchCases[0], BrMBB);
  2199. SL->SwitchCases.erase(SL->SwitchCases.begin());
  2200. return;
  2201. }
  2202. // Okay, we decided not to do this, remove any inserted MBB's and clear
  2203. // SwitchCases.
  2204. for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i)
  2205. FuncInfo.MF->erase(SL->SwitchCases[i].ThisBB);
  2206. SL->SwitchCases.clear();
  2207. }
  2208. }
  2209. // Create a CaseBlock record representing this branch.
  2210. CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
  2211. nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc());
  2212. // Use visitSwitchCase to actually insert the fast branch sequence for this
  2213. // cond branch.
  2214. visitSwitchCase(CB, BrMBB);
  2215. }
  2216. /// visitSwitchCase - Emits the necessary code to represent a single node in
  2217. /// the binary search tree resulting from lowering a switch instruction.
  2218. void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB,
  2219. MachineBasicBlock *SwitchBB) {
  2220. SDValue Cond;
  2221. SDValue CondLHS = getValue(CB.CmpLHS);
  2222. SDLoc dl = CB.DL;
  2223. if (CB.CC == ISD::SETTRUE) {
  2224. // Branch or fall through to TrueBB.
  2225. addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
  2226. SwitchBB->normalizeSuccProbs();
  2227. if (CB.TrueBB != NextBlock(SwitchBB)) {
  2228. DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, getControlRoot(),
  2229. DAG.getBasicBlock(CB.TrueBB)));
  2230. }
  2231. return;
  2232. }
  2233. auto &TLI = DAG.getTargetLoweringInfo();
  2234. EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), CB.CmpLHS->getType());
  2235. // Build the setcc now.
  2236. if (!CB.CmpMHS) {
  2237. // Fold "(X == true)" to X and "(X == false)" to !X to
  2238. // handle common cases produced by branch lowering.
  2239. if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
  2240. CB.CC == ISD::SETEQ)
  2241. Cond = CondLHS;
  2242. else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
  2243. CB.CC == ISD::SETEQ) {
  2244. SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType());
  2245. Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
  2246. } else {
  2247. SDValue CondRHS = getValue(CB.CmpRHS);
  2248. // If a pointer's DAG type is larger than its memory type then the DAG
  2249. // values are zero-extended. This breaks signed comparisons so truncate
  2250. // back to the underlying type before doing the compare.
  2251. if (CondLHS.getValueType() != MemVT) {
  2252. CondLHS = DAG.getPtrExtOrTrunc(CondLHS, getCurSDLoc(), MemVT);
  2253. CondRHS = DAG.getPtrExtOrTrunc(CondRHS, getCurSDLoc(), MemVT);
  2254. }
  2255. Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, CondRHS, CB.CC);
  2256. }
  2257. } else {
  2258. assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
  2259. const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
  2260. const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
  2261. SDValue CmpOp = getValue(CB.CmpMHS);
  2262. EVT VT = CmpOp.getValueType();
  2263. if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
  2264. Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT),
  2265. ISD::SETLE);
  2266. } else {
  2267. SDValue SUB = DAG.getNode(ISD::SUB, dl,
  2268. VT, CmpOp, DAG.getConstant(Low, dl, VT));
  2269. Cond = DAG.getSetCC(dl, MVT::i1, SUB,
  2270. DAG.getConstant(High-Low, dl, VT), ISD::SETULE);
  2271. }
  2272. }
  2273. // Update successor info
  2274. addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
  2275. // TrueBB and FalseBB are always different unless the incoming IR is
  2276. // degenerate. This only happens when running llc on weird IR.
  2277. if (CB.TrueBB != CB.FalseBB)
  2278. addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb);
  2279. SwitchBB->normalizeSuccProbs();
  2280. // If the lhs block is the next block, invert the condition so that we can
  2281. // fall through to the lhs instead of the rhs block.
  2282. if (CB.TrueBB == NextBlock(SwitchBB)) {
  2283. std::swap(CB.TrueBB, CB.FalseBB);
  2284. SDValue True = DAG.getConstant(1, dl, Cond.getValueType());
  2285. Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
  2286. }
  2287. SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
  2288. MVT::Other, getControlRoot(), Cond,
  2289. DAG.getBasicBlock(CB.TrueBB));
  2290. setValue(CurInst, BrCond);
  2291. // Insert the false branch. Do this even if it's a fall through branch,
  2292. // this makes it easier to do DAG optimizations which require inverting
  2293. // the branch condition.
  2294. BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
  2295. DAG.getBasicBlock(CB.FalseBB));
  2296. DAG.setRoot(BrCond);
  2297. }
  2298. /// visitJumpTable - Emit JumpTable node in the current MBB
  2299. void SelectionDAGBuilder::visitJumpTable(SwitchCG::JumpTable &JT) {
  2300. // Emit the code for the jump table
  2301. assert(JT.Reg != -1U && "Should lower JT Header first!");
  2302. EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
  2303. SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(),
  2304. JT.Reg, PTy);
  2305. SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
  2306. SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(),
  2307. MVT::Other, Index.getValue(1),
  2308. Table, Index);
  2309. DAG.setRoot(BrJumpTable);
  2310. }
  2311. /// visitJumpTableHeader - This function emits necessary code to produce index
  2312. /// in the JumpTable from switch case.
  2313. void SelectionDAGBuilder::visitJumpTableHeader(SwitchCG::JumpTable &JT,
  2314. JumpTableHeader &JTH,
  2315. MachineBasicBlock *SwitchBB) {
  2316. SDLoc dl = getCurSDLoc();
  2317. // Subtract the lowest switch case value from the value being switched on.
  2318. SDValue SwitchOp = getValue(JTH.SValue);
  2319. EVT VT = SwitchOp.getValueType();
  2320. SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp,
  2321. DAG.getConstant(JTH.First, dl, VT));
  2322. // The SDNode we just created, which holds the value being switched on minus
  2323. // the smallest case value, needs to be copied to a virtual register so it
  2324. // can be used as an index into the jump table in a subsequent basic block.
  2325. // This value may be smaller or larger than the target's pointer type, and
  2326. // therefore require extension or truncating.
  2327. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2328. SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout()));
  2329. unsigned JumpTableReg =
  2330. FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout()));
  2331. SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl,
  2332. JumpTableReg, SwitchOp);
  2333. JT.Reg = JumpTableReg;
  2334. if (!JTH.FallthroughUnreachable) {
  2335. // Emit the range check for the jump table, and branch to the default block
  2336. // for the switch statement if the value being switched on exceeds the
  2337. // largest case in the switch.
  2338. SDValue CMP = DAG.getSetCC(
  2339. dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
  2340. Sub.getValueType()),
  2341. Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT);
  2342. SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
  2343. MVT::Other, CopyTo, CMP,
  2344. DAG.getBasicBlock(JT.Default));
  2345. // Avoid emitting unnecessary branches to the next block.
  2346. if (JT.MBB != NextBlock(SwitchBB))
  2347. BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
  2348. DAG.getBasicBlock(JT.MBB));
  2349. DAG.setRoot(BrCond);
  2350. } else {
  2351. // Avoid emitting unnecessary branches to the next block.
  2352. if (JT.MBB != NextBlock(SwitchBB))
  2353. DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, CopyTo,
  2354. DAG.getBasicBlock(JT.MBB)));
  2355. else
  2356. DAG.setRoot(CopyTo);
  2357. }
  2358. }
  2359. /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global
  2360. /// variable if there exists one.
  2361. static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL,
  2362. SDValue &Chain) {
  2363. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2364. EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
  2365. EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout());
  2366. MachineFunction &MF = DAG.getMachineFunction();
  2367. Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent());
  2368. MachineSDNode *Node =
  2369. DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain);
  2370. if (Global) {
  2371. MachinePointerInfo MPInfo(Global);
  2372. auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant |
  2373. MachineMemOperand::MODereferenceable;
  2374. MachineMemOperand *MemRef = MF.getMachineMemOperand(
  2375. MPInfo, Flags, PtrTy.getSizeInBits() / 8, DAG.getEVTAlign(PtrTy));
  2376. DAG.setNodeMemRefs(Node, {MemRef});
  2377. }
  2378. if (PtrTy != PtrMemTy)
  2379. return DAG.getPtrExtOrTrunc(SDValue(Node, 0), DL, PtrMemTy);
  2380. return SDValue(Node, 0);
  2381. }
  2382. /// Codegen a new tail for a stack protector check ParentMBB which has had its
  2383. /// tail spliced into a stack protector check success bb.
  2384. ///
  2385. /// For a high level explanation of how this fits into the stack protector
  2386. /// generation see the comment on the declaration of class
  2387. /// StackProtectorDescriptor.
  2388. void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD,
  2389. MachineBasicBlock *ParentBB) {
  2390. // First create the loads to the guard/stack slot for the comparison.
  2391. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2392. EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
  2393. EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout());
  2394. MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo();
  2395. int FI = MFI.getStackProtectorIndex();
  2396. SDValue Guard;
  2397. SDLoc dl = getCurSDLoc();
  2398. SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy);
  2399. const Module &M = *ParentBB->getParent()->getFunction().getParent();
  2400. Align Align =
  2401. DAG.getDataLayout().getPrefTypeAlign(Type::getInt8PtrTy(M.getContext()));
  2402. // Generate code to load the content of the guard slot.
  2403. SDValue GuardVal = DAG.getLoad(
  2404. PtrMemTy, dl, DAG.getEntryNode(), StackSlotPtr,
  2405. MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align,
  2406. MachineMemOperand::MOVolatile);
  2407. if (TLI.useStackGuardXorFP())
  2408. GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl);
  2409. // Retrieve guard check function, nullptr if instrumentation is inlined.
  2410. if (const Function *GuardCheckFn = TLI.getSSPStackGuardCheck(M)) {
  2411. // The target provides a guard check function to validate the guard value.
  2412. // Generate a call to that function with the content of the guard slot as
  2413. // argument.
  2414. FunctionType *FnTy = GuardCheckFn->getFunctionType();
  2415. assert(FnTy->getNumParams() == 1 && "Invalid function signature");
  2416. TargetLowering::ArgListTy Args;
  2417. TargetLowering::ArgListEntry Entry;
  2418. Entry.Node = GuardVal;
  2419. Entry.Ty = FnTy->getParamType(0);
  2420. if (GuardCheckFn->hasParamAttribute(0, Attribute::AttrKind::InReg))
  2421. Entry.IsInReg = true;
  2422. Args.push_back(Entry);
  2423. TargetLowering::CallLoweringInfo CLI(DAG);
  2424. CLI.setDebugLoc(getCurSDLoc())
  2425. .setChain(DAG.getEntryNode())
  2426. .setCallee(GuardCheckFn->getCallingConv(), FnTy->getReturnType(),
  2427. getValue(GuardCheckFn), std::move(Args));
  2428. std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
  2429. DAG.setRoot(Result.second);
  2430. return;
  2431. }
  2432. // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD.
  2433. // Otherwise, emit a volatile load to retrieve the stack guard value.
  2434. SDValue Chain = DAG.getEntryNode();
  2435. if (TLI.useLoadStackGuardNode()) {
  2436. Guard = getLoadStackGuard(DAG, dl, Chain);
  2437. } else {
  2438. const Value *IRGuard = TLI.getSDagStackGuard(M);
  2439. SDValue GuardPtr = getValue(IRGuard);
  2440. Guard = DAG.getLoad(PtrMemTy, dl, Chain, GuardPtr,
  2441. MachinePointerInfo(IRGuard, 0), Align,
  2442. MachineMemOperand::MOVolatile);
  2443. }
  2444. // Perform the comparison via a getsetcc.
  2445. SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(),
  2446. *DAG.getContext(),
  2447. Guard.getValueType()),
  2448. Guard, GuardVal, ISD::SETNE);
  2449. // If the guard/stackslot do not equal, branch to failure MBB.
  2450. SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
  2451. MVT::Other, GuardVal.getOperand(0),
  2452. Cmp, DAG.getBasicBlock(SPD.getFailureMBB()));
  2453. // Otherwise branch to success MBB.
  2454. SDValue Br = DAG.getNode(ISD::BR, dl,
  2455. MVT::Other, BrCond,
  2456. DAG.getBasicBlock(SPD.getSuccessMBB()));
  2457. DAG.setRoot(Br);
  2458. }
  2459. /// Codegen the failure basic block for a stack protector check.
  2460. ///
  2461. /// A failure stack protector machine basic block consists simply of a call to
  2462. /// __stack_chk_fail().
  2463. ///
  2464. /// For a high level explanation of how this fits into the stack protector
  2465. /// generation see the comment on the declaration of class
  2466. /// StackProtectorDescriptor.
  2467. void
  2468. SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) {
  2469. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2470. TargetLowering::MakeLibCallOptions CallOptions;
  2471. CallOptions.setDiscardResult(true);
  2472. SDValue Chain =
  2473. TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid,
  2474. std::nullopt, CallOptions, getCurSDLoc())
  2475. .second;
  2476. // On PS4/PS5, the "return address" must still be within the calling
  2477. // function, even if it's at the very end, so emit an explicit TRAP here.
  2478. // Passing 'true' for doesNotReturn above won't generate the trap for us.
  2479. if (TM.getTargetTriple().isPS())
  2480. Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain);
  2481. // WebAssembly needs an unreachable instruction after a non-returning call,
  2482. // because the function return type can be different from __stack_chk_fail's
  2483. // return type (void).
  2484. if (TM.getTargetTriple().isWasm())
  2485. Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain);
  2486. DAG.setRoot(Chain);
  2487. }
  2488. /// visitBitTestHeader - This function emits necessary code to produce value
  2489. /// suitable for "bit tests"
  2490. void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B,
  2491. MachineBasicBlock *SwitchBB) {
  2492. SDLoc dl = getCurSDLoc();
  2493. // Subtract the minimum value.
  2494. SDValue SwitchOp = getValue(B.SValue);
  2495. EVT VT = SwitchOp.getValueType();
  2496. SDValue RangeSub =
  2497. DAG.getNode(ISD::SUB, dl, VT, SwitchOp, DAG.getConstant(B.First, dl, VT));
  2498. // Determine the type of the test operands.
  2499. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2500. bool UsePtrType = false;
  2501. if (!TLI.isTypeLegal(VT)) {
  2502. UsePtrType = true;
  2503. } else {
  2504. for (unsigned i = 0, e = B.Cases.size(); i != e; ++i)
  2505. if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) {
  2506. // Switch table case range are encoded into series of masks.
  2507. // Just use pointer type, it's guaranteed to fit.
  2508. UsePtrType = true;
  2509. break;
  2510. }
  2511. }
  2512. SDValue Sub = RangeSub;
  2513. if (UsePtrType) {
  2514. VT = TLI.getPointerTy(DAG.getDataLayout());
  2515. Sub = DAG.getZExtOrTrunc(Sub, dl, VT);
  2516. }
  2517. B.RegVT = VT.getSimpleVT();
  2518. B.Reg = FuncInfo.CreateReg(B.RegVT);
  2519. SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub);
  2520. MachineBasicBlock* MBB = B.Cases[0].ThisBB;
  2521. if (!B.FallthroughUnreachable)
  2522. addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb);
  2523. addSuccessorWithProb(SwitchBB, MBB, B.Prob);
  2524. SwitchBB->normalizeSuccProbs();
  2525. SDValue Root = CopyTo;
  2526. if (!B.FallthroughUnreachable) {
  2527. // Conditional branch to the default block.
  2528. SDValue RangeCmp = DAG.getSetCC(dl,
  2529. TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
  2530. RangeSub.getValueType()),
  2531. RangeSub, DAG.getConstant(B.Range, dl, RangeSub.getValueType()),
  2532. ISD::SETUGT);
  2533. Root = DAG.getNode(ISD::BRCOND, dl, MVT::Other, Root, RangeCmp,
  2534. DAG.getBasicBlock(B.Default));
  2535. }
  2536. // Avoid emitting unnecessary branches to the next block.
  2537. if (MBB != NextBlock(SwitchBB))
  2538. Root = DAG.getNode(ISD::BR, dl, MVT::Other, Root, DAG.getBasicBlock(MBB));
  2539. DAG.setRoot(Root);
  2540. }
  2541. /// visitBitTestCase - this function produces one "bit test"
  2542. void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB,
  2543. MachineBasicBlock* NextMBB,
  2544. BranchProbability BranchProbToNext,
  2545. unsigned Reg,
  2546. BitTestCase &B,
  2547. MachineBasicBlock *SwitchBB) {
  2548. SDLoc dl = getCurSDLoc();
  2549. MVT VT = BB.RegVT;
  2550. SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT);
  2551. SDValue Cmp;
  2552. unsigned PopCount = llvm::popcount(B.Mask);
  2553. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2554. if (PopCount == 1) {
  2555. // Testing for a single bit; just compare the shift count with what it
  2556. // would need to be to shift a 1 bit in that position.
  2557. Cmp = DAG.getSetCC(
  2558. dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
  2559. ShiftOp, DAG.getConstant(countTrailingZeros(B.Mask), dl, VT),
  2560. ISD::SETEQ);
  2561. } else if (PopCount == BB.Range) {
  2562. // There is only one zero bit in the range, test for it directly.
  2563. Cmp = DAG.getSetCC(
  2564. dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
  2565. ShiftOp, DAG.getConstant(countTrailingOnes(B.Mask), dl, VT),
  2566. ISD::SETNE);
  2567. } else {
  2568. // Make desired shift
  2569. SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT,
  2570. DAG.getConstant(1, dl, VT), ShiftOp);
  2571. // Emit bit tests and jumps
  2572. SDValue AndOp = DAG.getNode(ISD::AND, dl,
  2573. VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT));
  2574. Cmp = DAG.getSetCC(
  2575. dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
  2576. AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE);
  2577. }
  2578. // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb.
  2579. addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb);
  2580. // The branch probability from SwitchBB to NextMBB is BranchProbToNext.
  2581. addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext);
  2582. // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is
  2583. // one as they are relative probabilities (and thus work more like weights),
  2584. // and hence we need to normalize them to let the sum of them become one.
  2585. SwitchBB->normalizeSuccProbs();
  2586. SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl,
  2587. MVT::Other, getControlRoot(),
  2588. Cmp, DAG.getBasicBlock(B.TargetBB));
  2589. // Avoid emitting unnecessary branches to the next block.
  2590. if (NextMBB != NextBlock(SwitchBB))
  2591. BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd,
  2592. DAG.getBasicBlock(NextMBB));
  2593. DAG.setRoot(BrAnd);
  2594. }
  2595. void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) {
  2596. MachineBasicBlock *InvokeMBB = FuncInfo.MBB;
  2597. // Retrieve successors. Look through artificial IR level blocks like
  2598. // catchswitch for successors.
  2599. MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
  2600. const BasicBlock *EHPadBB = I.getSuccessor(1);
  2601. // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
  2602. // have to do anything here to lower funclet bundles.
  2603. assert(!I.hasOperandBundlesOtherThan(
  2604. {LLVMContext::OB_deopt, LLVMContext::OB_gc_transition,
  2605. LLVMContext::OB_gc_live, LLVMContext::OB_funclet,
  2606. LLVMContext::OB_cfguardtarget,
  2607. LLVMContext::OB_clang_arc_attachedcall}) &&
  2608. "Cannot lower invokes with arbitrary operand bundles yet!");
  2609. const Value *Callee(I.getCalledOperand());
  2610. const Function *Fn = dyn_cast<Function>(Callee);
  2611. if (isa<InlineAsm>(Callee))
  2612. visitInlineAsm(I, EHPadBB);
  2613. else if (Fn && Fn->isIntrinsic()) {
  2614. switch (Fn->getIntrinsicID()) {
  2615. default:
  2616. llvm_unreachable("Cannot invoke this intrinsic");
  2617. case Intrinsic::donothing:
  2618. // Ignore invokes to @llvm.donothing: jump directly to the next BB.
  2619. case Intrinsic::seh_try_begin:
  2620. case Intrinsic::seh_scope_begin:
  2621. case Intrinsic::seh_try_end:
  2622. case Intrinsic::seh_scope_end:
  2623. break;
  2624. case Intrinsic::experimental_patchpoint_void:
  2625. case Intrinsic::experimental_patchpoint_i64:
  2626. visitPatchpoint(I, EHPadBB);
  2627. break;
  2628. case Intrinsic::experimental_gc_statepoint:
  2629. LowerStatepoint(cast<GCStatepointInst>(I), EHPadBB);
  2630. break;
  2631. case Intrinsic::wasm_rethrow: {
  2632. // This is usually done in visitTargetIntrinsic, but this intrinsic is
  2633. // special because it can be invoked, so we manually lower it to a DAG
  2634. // node here.
  2635. SmallVector<SDValue, 8> Ops;
  2636. Ops.push_back(getRoot()); // inchain
  2637. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2638. Ops.push_back(
  2639. DAG.getTargetConstant(Intrinsic::wasm_rethrow, getCurSDLoc(),
  2640. TLI.getPointerTy(DAG.getDataLayout())));
  2641. SDVTList VTs = DAG.getVTList(ArrayRef<EVT>({MVT::Other})); // outchain
  2642. DAG.setRoot(DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops));
  2643. break;
  2644. }
  2645. }
  2646. } else if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) {
  2647. // Currently we do not lower any intrinsic calls with deopt operand bundles.
  2648. // Eventually we will support lowering the @llvm.experimental.deoptimize
  2649. // intrinsic, and right now there are no plans to support other intrinsics
  2650. // with deopt state.
  2651. LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB);
  2652. } else {
  2653. LowerCallTo(I, getValue(Callee), false, false, EHPadBB);
  2654. }
  2655. // If the value of the invoke is used outside of its defining block, make it
  2656. // available as a virtual register.
  2657. // We already took care of the exported value for the statepoint instruction
  2658. // during call to the LowerStatepoint.
  2659. if (!isa<GCStatepointInst>(I)) {
  2660. CopyToExportRegsIfNeeded(&I);
  2661. }
  2662. SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
  2663. BranchProbabilityInfo *BPI = FuncInfo.BPI;
  2664. BranchProbability EHPadBBProb =
  2665. BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB)
  2666. : BranchProbability::getZero();
  2667. findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests);
  2668. // Update successor info.
  2669. addSuccessorWithProb(InvokeMBB, Return);
  2670. for (auto &UnwindDest : UnwindDests) {
  2671. UnwindDest.first->setIsEHPad();
  2672. addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second);
  2673. }
  2674. InvokeMBB->normalizeSuccProbs();
  2675. // Drop into normal successor.
  2676. DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, getControlRoot(),
  2677. DAG.getBasicBlock(Return)));
  2678. }
  2679. void SelectionDAGBuilder::visitCallBr(const CallBrInst &I) {
  2680. MachineBasicBlock *CallBrMBB = FuncInfo.MBB;
  2681. // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
  2682. // have to do anything here to lower funclet bundles.
  2683. assert(!I.hasOperandBundlesOtherThan(
  2684. {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) &&
  2685. "Cannot lower callbrs with arbitrary operand bundles yet!");
  2686. assert(I.isInlineAsm() && "Only know how to handle inlineasm callbr");
  2687. visitInlineAsm(I);
  2688. CopyToExportRegsIfNeeded(&I);
  2689. // Retrieve successors.
  2690. SmallPtrSet<BasicBlock *, 8> Dests;
  2691. Dests.insert(I.getDefaultDest());
  2692. MachineBasicBlock *Return = FuncInfo.MBBMap[I.getDefaultDest()];
  2693. // Update successor info.
  2694. addSuccessorWithProb(CallBrMBB, Return, BranchProbability::getOne());
  2695. for (unsigned i = 0, e = I.getNumIndirectDests(); i < e; ++i) {
  2696. BasicBlock *Dest = I.getIndirectDest(i);
  2697. MachineBasicBlock *Target = FuncInfo.MBBMap[Dest];
  2698. Target->setIsInlineAsmBrIndirectTarget();
  2699. Target->setMachineBlockAddressTaken();
  2700. Target->setLabelMustBeEmitted();
  2701. // Don't add duplicate machine successors.
  2702. if (Dests.insert(Dest).second)
  2703. addSuccessorWithProb(CallBrMBB, Target, BranchProbability::getZero());
  2704. }
  2705. CallBrMBB->normalizeSuccProbs();
  2706. // Drop into default successor.
  2707. DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
  2708. MVT::Other, getControlRoot(),
  2709. DAG.getBasicBlock(Return)));
  2710. }
  2711. void SelectionDAGBuilder::visitResume(const ResumeInst &RI) {
  2712. llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!");
  2713. }
  2714. void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) {
  2715. assert(FuncInfo.MBB->isEHPad() &&
  2716. "Call to landingpad not in landing pad!");
  2717. // If there aren't registers to copy the values into (e.g., during SjLj
  2718. // exceptions), then don't bother to create these DAG nodes.
  2719. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2720. const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn();
  2721. if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 &&
  2722. TLI.getExceptionSelectorRegister(PersonalityFn) == 0)
  2723. return;
  2724. // If landingpad's return type is token type, we don't create DAG nodes
  2725. // for its exception pointer and selector value. The extraction of exception
  2726. // pointer or selector value from token type landingpads is not currently
  2727. // supported.
  2728. if (LP.getType()->isTokenTy())
  2729. return;
  2730. SmallVector<EVT, 2> ValueVTs;
  2731. SDLoc dl = getCurSDLoc();
  2732. ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs);
  2733. assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported");
  2734. // Get the two live-in registers as SDValues. The physregs have already been
  2735. // copied into virtual registers.
  2736. SDValue Ops[2];
  2737. if (FuncInfo.ExceptionPointerVirtReg) {
  2738. Ops[0] = DAG.getZExtOrTrunc(
  2739. DAG.getCopyFromReg(DAG.getEntryNode(), dl,
  2740. FuncInfo.ExceptionPointerVirtReg,
  2741. TLI.getPointerTy(DAG.getDataLayout())),
  2742. dl, ValueVTs[0]);
  2743. } else {
  2744. Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout()));
  2745. }
  2746. Ops[1] = DAG.getZExtOrTrunc(
  2747. DAG.getCopyFromReg(DAG.getEntryNode(), dl,
  2748. FuncInfo.ExceptionSelectorVirtReg,
  2749. TLI.getPointerTy(DAG.getDataLayout())),
  2750. dl, ValueVTs[1]);
  2751. // Merge into one.
  2752. SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl,
  2753. DAG.getVTList(ValueVTs), Ops);
  2754. setValue(&LP, Res);
  2755. }
  2756. void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First,
  2757. MachineBasicBlock *Last) {
  2758. // Update JTCases.
  2759. for (JumpTableBlock &JTB : SL->JTCases)
  2760. if (JTB.first.HeaderBB == First)
  2761. JTB.first.HeaderBB = Last;
  2762. // Update BitTestCases.
  2763. for (BitTestBlock &BTB : SL->BitTestCases)
  2764. if (BTB.Parent == First)
  2765. BTB.Parent = Last;
  2766. }
  2767. void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) {
  2768. MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB;
  2769. // Update machine-CFG edges with unique successors.
  2770. SmallSet<BasicBlock*, 32> Done;
  2771. for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) {
  2772. BasicBlock *BB = I.getSuccessor(i);
  2773. bool Inserted = Done.insert(BB).second;
  2774. if (!Inserted)
  2775. continue;
  2776. MachineBasicBlock *Succ = FuncInfo.MBBMap[BB];
  2777. addSuccessorWithProb(IndirectBrMBB, Succ);
  2778. }
  2779. IndirectBrMBB->normalizeSuccProbs();
  2780. DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(),
  2781. MVT::Other, getControlRoot(),
  2782. getValue(I.getAddress())));
  2783. }
  2784. void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) {
  2785. if (!DAG.getTarget().Options.TrapUnreachable)
  2786. return;
  2787. // We may be able to ignore unreachable behind a noreturn call.
  2788. if (DAG.getTarget().Options.NoTrapAfterNoreturn) {
  2789. const BasicBlock &BB = *I.getParent();
  2790. if (&I != &BB.front()) {
  2791. BasicBlock::const_iterator PredI =
  2792. std::prev(BasicBlock::const_iterator(&I));
  2793. if (const CallInst *Call = dyn_cast<CallInst>(&*PredI)) {
  2794. if (Call->doesNotReturn())
  2795. return;
  2796. }
  2797. }
  2798. }
  2799. DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot()));
  2800. }
  2801. void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) {
  2802. SDNodeFlags Flags;
  2803. if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
  2804. Flags.copyFMF(*FPOp);
  2805. SDValue Op = getValue(I.getOperand(0));
  2806. SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(),
  2807. Op, Flags);
  2808. setValue(&I, UnNodeValue);
  2809. }
  2810. void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) {
  2811. SDNodeFlags Flags;
  2812. if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) {
  2813. Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap());
  2814. Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap());
  2815. }
  2816. if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I))
  2817. Flags.setExact(ExactOp->isExact());
  2818. if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
  2819. Flags.copyFMF(*FPOp);
  2820. SDValue Op1 = getValue(I.getOperand(0));
  2821. SDValue Op2 = getValue(I.getOperand(1));
  2822. SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(),
  2823. Op1, Op2, Flags);
  2824. setValue(&I, BinNodeValue);
  2825. }
  2826. void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) {
  2827. SDValue Op1 = getValue(I.getOperand(0));
  2828. SDValue Op2 = getValue(I.getOperand(1));
  2829. EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy(
  2830. Op1.getValueType(), DAG.getDataLayout());
  2831. // Coerce the shift amount to the right type if we can. This exposes the
  2832. // truncate or zext to optimization early.
  2833. if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) {
  2834. assert(ShiftTy.getSizeInBits() >= Log2_32_Ceil(Op1.getValueSizeInBits()) &&
  2835. "Unexpected shift type");
  2836. Op2 = DAG.getZExtOrTrunc(Op2, getCurSDLoc(), ShiftTy);
  2837. }
  2838. bool nuw = false;
  2839. bool nsw = false;
  2840. bool exact = false;
  2841. if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) {
  2842. if (const OverflowingBinaryOperator *OFBinOp =
  2843. dyn_cast<const OverflowingBinaryOperator>(&I)) {
  2844. nuw = OFBinOp->hasNoUnsignedWrap();
  2845. nsw = OFBinOp->hasNoSignedWrap();
  2846. }
  2847. if (const PossiblyExactOperator *ExactOp =
  2848. dyn_cast<const PossiblyExactOperator>(&I))
  2849. exact = ExactOp->isExact();
  2850. }
  2851. SDNodeFlags Flags;
  2852. Flags.setExact(exact);
  2853. Flags.setNoSignedWrap(nsw);
  2854. Flags.setNoUnsignedWrap(nuw);
  2855. SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2,
  2856. Flags);
  2857. setValue(&I, Res);
  2858. }
  2859. void SelectionDAGBuilder::visitSDiv(const User &I) {
  2860. SDValue Op1 = getValue(I.getOperand(0));
  2861. SDValue Op2 = getValue(I.getOperand(1));
  2862. SDNodeFlags Flags;
  2863. Flags.setExact(isa<PossiblyExactOperator>(&I) &&
  2864. cast<PossiblyExactOperator>(&I)->isExact());
  2865. setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1,
  2866. Op2, Flags));
  2867. }
  2868. void SelectionDAGBuilder::visitICmp(const User &I) {
  2869. ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
  2870. if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I))
  2871. predicate = IC->getPredicate();
  2872. else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
  2873. predicate = ICmpInst::Predicate(IC->getPredicate());
  2874. SDValue Op1 = getValue(I.getOperand(0));
  2875. SDValue Op2 = getValue(I.getOperand(1));
  2876. ISD::CondCode Opcode = getICmpCondCode(predicate);
  2877. auto &TLI = DAG.getTargetLoweringInfo();
  2878. EVT MemVT =
  2879. TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
  2880. // If a pointer's DAG type is larger than its memory type then the DAG values
  2881. // are zero-extended. This breaks signed comparisons so truncate back to the
  2882. // underlying type before doing the compare.
  2883. if (Op1.getValueType() != MemVT) {
  2884. Op1 = DAG.getPtrExtOrTrunc(Op1, getCurSDLoc(), MemVT);
  2885. Op2 = DAG.getPtrExtOrTrunc(Op2, getCurSDLoc(), MemVT);
  2886. }
  2887. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  2888. I.getType());
  2889. setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode));
  2890. }
  2891. void SelectionDAGBuilder::visitFCmp(const User &I) {
  2892. FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
  2893. if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I))
  2894. predicate = FC->getPredicate();
  2895. else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
  2896. predicate = FCmpInst::Predicate(FC->getPredicate());
  2897. SDValue Op1 = getValue(I.getOperand(0));
  2898. SDValue Op2 = getValue(I.getOperand(1));
  2899. ISD::CondCode Condition = getFCmpCondCode(predicate);
  2900. auto *FPMO = cast<FPMathOperator>(&I);
  2901. if (FPMO->hasNoNaNs() || TM.Options.NoNaNsFPMath)
  2902. Condition = getFCmpCodeWithoutNaN(Condition);
  2903. SDNodeFlags Flags;
  2904. Flags.copyFMF(*FPMO);
  2905. SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
  2906. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  2907. I.getType());
  2908. setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition));
  2909. }
  2910. // Check if the condition of the select has one use or two users that are both
  2911. // selects with the same condition.
  2912. static bool hasOnlySelectUsers(const Value *Cond) {
  2913. return llvm::all_of(Cond->users(), [](const Value *V) {
  2914. return isa<SelectInst>(V);
  2915. });
  2916. }
  2917. void SelectionDAGBuilder::visitSelect(const User &I) {
  2918. SmallVector<EVT, 4> ValueVTs;
  2919. ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
  2920. ValueVTs);
  2921. unsigned NumValues = ValueVTs.size();
  2922. if (NumValues == 0) return;
  2923. SmallVector<SDValue, 4> Values(NumValues);
  2924. SDValue Cond = getValue(I.getOperand(0));
  2925. SDValue LHSVal = getValue(I.getOperand(1));
  2926. SDValue RHSVal = getValue(I.getOperand(2));
  2927. SmallVector<SDValue, 1> BaseOps(1, Cond);
  2928. ISD::NodeType OpCode =
  2929. Cond.getValueType().isVector() ? ISD::VSELECT : ISD::SELECT;
  2930. bool IsUnaryAbs = false;
  2931. bool Negate = false;
  2932. SDNodeFlags Flags;
  2933. if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
  2934. Flags.copyFMF(*FPOp);
  2935. // Min/max matching is only viable if all output VTs are the same.
  2936. if (all_equal(ValueVTs)) {
  2937. EVT VT = ValueVTs[0];
  2938. LLVMContext &Ctx = *DAG.getContext();
  2939. auto &TLI = DAG.getTargetLoweringInfo();
  2940. // We care about the legality of the operation after it has been type
  2941. // legalized.
  2942. while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal)
  2943. VT = TLI.getTypeToTransformTo(Ctx, VT);
  2944. // If the vselect is legal, assume we want to leave this as a vector setcc +
  2945. // vselect. Otherwise, if this is going to be scalarized, we want to see if
  2946. // min/max is legal on the scalar type.
  2947. bool UseScalarMinMax = VT.isVector() &&
  2948. !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT);
  2949. Value *LHS, *RHS;
  2950. auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS);
  2951. ISD::NodeType Opc = ISD::DELETED_NODE;
  2952. switch (SPR.Flavor) {
  2953. case SPF_UMAX: Opc = ISD::UMAX; break;
  2954. case SPF_UMIN: Opc = ISD::UMIN; break;
  2955. case SPF_SMAX: Opc = ISD::SMAX; break;
  2956. case SPF_SMIN: Opc = ISD::SMIN; break;
  2957. case SPF_FMINNUM:
  2958. switch (SPR.NaNBehavior) {
  2959. case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
  2960. case SPNB_RETURNS_NAN: Opc = ISD::FMINIMUM; break;
  2961. case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break;
  2962. case SPNB_RETURNS_ANY: {
  2963. if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT))
  2964. Opc = ISD::FMINNUM;
  2965. else if (TLI.isOperationLegalOrCustom(ISD::FMINIMUM, VT))
  2966. Opc = ISD::FMINIMUM;
  2967. else if (UseScalarMinMax)
  2968. Opc = TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType()) ?
  2969. ISD::FMINNUM : ISD::FMINIMUM;
  2970. break;
  2971. }
  2972. }
  2973. break;
  2974. case SPF_FMAXNUM:
  2975. switch (SPR.NaNBehavior) {
  2976. case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
  2977. case SPNB_RETURNS_NAN: Opc = ISD::FMAXIMUM; break;
  2978. case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break;
  2979. case SPNB_RETURNS_ANY:
  2980. if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT))
  2981. Opc = ISD::FMAXNUM;
  2982. else if (TLI.isOperationLegalOrCustom(ISD::FMAXIMUM, VT))
  2983. Opc = ISD::FMAXIMUM;
  2984. else if (UseScalarMinMax)
  2985. Opc = TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType()) ?
  2986. ISD::FMAXNUM : ISD::FMAXIMUM;
  2987. break;
  2988. }
  2989. break;
  2990. case SPF_NABS:
  2991. Negate = true;
  2992. [[fallthrough]];
  2993. case SPF_ABS:
  2994. IsUnaryAbs = true;
  2995. Opc = ISD::ABS;
  2996. break;
  2997. default: break;
  2998. }
  2999. if (!IsUnaryAbs && Opc != ISD::DELETED_NODE &&
  3000. (TLI.isOperationLegalOrCustom(Opc, VT) ||
  3001. (UseScalarMinMax &&
  3002. TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) &&
  3003. // If the underlying comparison instruction is used by any other
  3004. // instruction, the consumed instructions won't be destroyed, so it is
  3005. // not profitable to convert to a min/max.
  3006. hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) {
  3007. OpCode = Opc;
  3008. LHSVal = getValue(LHS);
  3009. RHSVal = getValue(RHS);
  3010. BaseOps.clear();
  3011. }
  3012. if (IsUnaryAbs) {
  3013. OpCode = Opc;
  3014. LHSVal = getValue(LHS);
  3015. BaseOps.clear();
  3016. }
  3017. }
  3018. if (IsUnaryAbs) {
  3019. for (unsigned i = 0; i != NumValues; ++i) {
  3020. SDLoc dl = getCurSDLoc();
  3021. EVT VT = LHSVal.getNode()->getValueType(LHSVal.getResNo() + i);
  3022. Values[i] =
  3023. DAG.getNode(OpCode, dl, VT, LHSVal.getValue(LHSVal.getResNo() + i));
  3024. if (Negate)
  3025. Values[i] = DAG.getNegative(Values[i], dl, VT);
  3026. }
  3027. } else {
  3028. for (unsigned i = 0; i != NumValues; ++i) {
  3029. SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end());
  3030. Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i));
  3031. Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i));
  3032. Values[i] = DAG.getNode(
  3033. OpCode, getCurSDLoc(),
  3034. LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), Ops, Flags);
  3035. }
  3036. }
  3037. setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
  3038. DAG.getVTList(ValueVTs), Values));
  3039. }
  3040. void SelectionDAGBuilder::visitTrunc(const User &I) {
  3041. // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
  3042. SDValue N = getValue(I.getOperand(0));
  3043. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  3044. I.getType());
  3045. setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N));
  3046. }
  3047. void SelectionDAGBuilder::visitZExt(const User &I) {
  3048. // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
  3049. // ZExt also can't be a cast to bool for same reason. So, nothing much to do
  3050. SDValue N = getValue(I.getOperand(0));
  3051. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  3052. I.getType());
  3053. setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N));
  3054. }
  3055. void SelectionDAGBuilder::visitSExt(const User &I) {
  3056. // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
  3057. // SExt also can't be a cast to bool for same reason. So, nothing much to do
  3058. SDValue N = getValue(I.getOperand(0));
  3059. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  3060. I.getType());
  3061. setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
  3062. }
  3063. void SelectionDAGBuilder::visitFPTrunc(const User &I) {
  3064. // FPTrunc is never a no-op cast, no need to check
  3065. SDValue N = getValue(I.getOperand(0));
  3066. SDLoc dl = getCurSDLoc();
  3067. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3068. EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  3069. setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N,
  3070. DAG.getTargetConstant(
  3071. 0, dl, TLI.getPointerTy(DAG.getDataLayout()))));
  3072. }
  3073. void SelectionDAGBuilder::visitFPExt(const User &I) {
  3074. // FPExt is never a no-op cast, no need to check
  3075. SDValue N = getValue(I.getOperand(0));
  3076. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  3077. I.getType());
  3078. setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N));
  3079. }
  3080. void SelectionDAGBuilder::visitFPToUI(const User &I) {
  3081. // FPToUI is never a no-op cast, no need to check
  3082. SDValue N = getValue(I.getOperand(0));
  3083. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  3084. I.getType());
  3085. setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N));
  3086. }
  3087. void SelectionDAGBuilder::visitFPToSI(const User &I) {
  3088. // FPToSI is never a no-op cast, no need to check
  3089. SDValue N = getValue(I.getOperand(0));
  3090. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  3091. I.getType());
  3092. setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N));
  3093. }
  3094. void SelectionDAGBuilder::visitUIToFP(const User &I) {
  3095. // UIToFP is never a no-op cast, no need to check
  3096. SDValue N = getValue(I.getOperand(0));
  3097. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  3098. I.getType());
  3099. setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N));
  3100. }
  3101. void SelectionDAGBuilder::visitSIToFP(const User &I) {
  3102. // SIToFP is never a no-op cast, no need to check
  3103. SDValue N = getValue(I.getOperand(0));
  3104. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  3105. I.getType());
  3106. setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N));
  3107. }
  3108. void SelectionDAGBuilder::visitPtrToInt(const User &I) {
  3109. // What to do depends on the size of the integer and the size of the pointer.
  3110. // We can either truncate, zero extend, or no-op, accordingly.
  3111. SDValue N = getValue(I.getOperand(0));
  3112. auto &TLI = DAG.getTargetLoweringInfo();
  3113. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  3114. I.getType());
  3115. EVT PtrMemVT =
  3116. TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
  3117. N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
  3118. N = DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT);
  3119. setValue(&I, N);
  3120. }
  3121. void SelectionDAGBuilder::visitIntToPtr(const User &I) {
  3122. // What to do depends on the size of the integer and the size of the pointer.
  3123. // We can either truncate, zero extend, or no-op, accordingly.
  3124. SDValue N = getValue(I.getOperand(0));
  3125. auto &TLI = DAG.getTargetLoweringInfo();
  3126. EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  3127. EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
  3128. N = DAG.getZExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
  3129. N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), DestVT);
  3130. setValue(&I, N);
  3131. }
  3132. void SelectionDAGBuilder::visitBitCast(const User &I) {
  3133. SDValue N = getValue(I.getOperand(0));
  3134. SDLoc dl = getCurSDLoc();
  3135. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  3136. I.getType());
  3137. // BitCast assures us that source and destination are the same size so this is
  3138. // either a BITCAST or a no-op.
  3139. if (DestVT != N.getValueType())
  3140. setValue(&I, DAG.getNode(ISD::BITCAST, dl,
  3141. DestVT, N)); // convert types.
  3142. // Check if the original LLVM IR Operand was a ConstantInt, because getValue()
  3143. // might fold any kind of constant expression to an integer constant and that
  3144. // is not what we are looking for. Only recognize a bitcast of a genuine
  3145. // constant integer as an opaque constant.
  3146. else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0)))
  3147. setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false,
  3148. /*isOpaque*/true));
  3149. else
  3150. setValue(&I, N); // noop cast.
  3151. }
  3152. void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) {
  3153. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3154. const Value *SV = I.getOperand(0);
  3155. SDValue N = getValue(SV);
  3156. EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  3157. unsigned SrcAS = SV->getType()->getPointerAddressSpace();
  3158. unsigned DestAS = I.getType()->getPointerAddressSpace();
  3159. if (!TM.isNoopAddrSpaceCast(SrcAS, DestAS))
  3160. N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS);
  3161. setValue(&I, N);
  3162. }
  3163. void SelectionDAGBuilder::visitInsertElement(const User &I) {
  3164. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3165. SDValue InVec = getValue(I.getOperand(0));
  3166. SDValue InVal = getValue(I.getOperand(1));
  3167. SDValue InIdx = DAG.getZExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(),
  3168. TLI.getVectorIdxTy(DAG.getDataLayout()));
  3169. setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(),
  3170. TLI.getValueType(DAG.getDataLayout(), I.getType()),
  3171. InVec, InVal, InIdx));
  3172. }
  3173. void SelectionDAGBuilder::visitExtractElement(const User &I) {
  3174. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3175. SDValue InVec = getValue(I.getOperand(0));
  3176. SDValue InIdx = DAG.getZExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(),
  3177. TLI.getVectorIdxTy(DAG.getDataLayout()));
  3178. setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(),
  3179. TLI.getValueType(DAG.getDataLayout(), I.getType()),
  3180. InVec, InIdx));
  3181. }
  3182. void SelectionDAGBuilder::visitShuffleVector(const User &I) {
  3183. SDValue Src1 = getValue(I.getOperand(0));
  3184. SDValue Src2 = getValue(I.getOperand(1));
  3185. ArrayRef<int> Mask;
  3186. if (auto *SVI = dyn_cast<ShuffleVectorInst>(&I))
  3187. Mask = SVI->getShuffleMask();
  3188. else
  3189. Mask = cast<ConstantExpr>(I).getShuffleMask();
  3190. SDLoc DL = getCurSDLoc();
  3191. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3192. EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  3193. EVT SrcVT = Src1.getValueType();
  3194. if (all_of(Mask, [](int Elem) { return Elem == 0; }) &&
  3195. VT.isScalableVector()) {
  3196. // Canonical splat form of first element of first input vector.
  3197. SDValue FirstElt =
  3198. DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, SrcVT.getScalarType(), Src1,
  3199. DAG.getVectorIdxConstant(0, DL));
  3200. setValue(&I, DAG.getNode(ISD::SPLAT_VECTOR, DL, VT, FirstElt));
  3201. return;
  3202. }
  3203. // For now, we only handle splats for scalable vectors.
  3204. // The DAGCombiner will perform a BUILD_VECTOR -> SPLAT_VECTOR transformation
  3205. // for targets that support a SPLAT_VECTOR for non-scalable vector types.
  3206. assert(!VT.isScalableVector() && "Unsupported scalable vector shuffle");
  3207. unsigned SrcNumElts = SrcVT.getVectorNumElements();
  3208. unsigned MaskNumElts = Mask.size();
  3209. if (SrcNumElts == MaskNumElts) {
  3210. setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask));
  3211. return;
  3212. }
  3213. // Normalize the shuffle vector since mask and vector length don't match.
  3214. if (SrcNumElts < MaskNumElts) {
  3215. // Mask is longer than the source vectors. We can use concatenate vector to
  3216. // make the mask and vectors lengths match.
  3217. if (MaskNumElts % SrcNumElts == 0) {
  3218. // Mask length is a multiple of the source vector length.
  3219. // Check if the shuffle is some kind of concatenation of the input
  3220. // vectors.
  3221. unsigned NumConcat = MaskNumElts / SrcNumElts;
  3222. bool IsConcat = true;
  3223. SmallVector<int, 8> ConcatSrcs(NumConcat, -1);
  3224. for (unsigned i = 0; i != MaskNumElts; ++i) {
  3225. int Idx = Mask[i];
  3226. if (Idx < 0)
  3227. continue;
  3228. // Ensure the indices in each SrcVT sized piece are sequential and that
  3229. // the same source is used for the whole piece.
  3230. if ((Idx % SrcNumElts != (i % SrcNumElts)) ||
  3231. (ConcatSrcs[i / SrcNumElts] >= 0 &&
  3232. ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) {
  3233. IsConcat = false;
  3234. break;
  3235. }
  3236. // Remember which source this index came from.
  3237. ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts;
  3238. }
  3239. // The shuffle is concatenating multiple vectors together. Just emit
  3240. // a CONCAT_VECTORS operation.
  3241. if (IsConcat) {
  3242. SmallVector<SDValue, 8> ConcatOps;
  3243. for (auto Src : ConcatSrcs) {
  3244. if (Src < 0)
  3245. ConcatOps.push_back(DAG.getUNDEF(SrcVT));
  3246. else if (Src == 0)
  3247. ConcatOps.push_back(Src1);
  3248. else
  3249. ConcatOps.push_back(Src2);
  3250. }
  3251. setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps));
  3252. return;
  3253. }
  3254. }
  3255. unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts);
  3256. unsigned NumConcat = PaddedMaskNumElts / SrcNumElts;
  3257. EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
  3258. PaddedMaskNumElts);
  3259. // Pad both vectors with undefs to make them the same length as the mask.
  3260. SDValue UndefVal = DAG.getUNDEF(SrcVT);
  3261. SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
  3262. SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
  3263. MOps1[0] = Src1;
  3264. MOps2[0] = Src2;
  3265. Src1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1);
  3266. Src2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2);
  3267. // Readjust mask for new input vector length.
  3268. SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1);
  3269. for (unsigned i = 0; i != MaskNumElts; ++i) {
  3270. int Idx = Mask[i];
  3271. if (Idx >= (int)SrcNumElts)
  3272. Idx -= SrcNumElts - PaddedMaskNumElts;
  3273. MappedOps[i] = Idx;
  3274. }
  3275. SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps);
  3276. // If the concatenated vector was padded, extract a subvector with the
  3277. // correct number of elements.
  3278. if (MaskNumElts != PaddedMaskNumElts)
  3279. Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Result,
  3280. DAG.getVectorIdxConstant(0, DL));
  3281. setValue(&I, Result);
  3282. return;
  3283. }
  3284. if (SrcNumElts > MaskNumElts) {
  3285. // Analyze the access pattern of the vector to see if we can extract
  3286. // two subvectors and do the shuffle.
  3287. int StartIdx[2] = { -1, -1 }; // StartIdx to extract from
  3288. bool CanExtract = true;
  3289. for (int Idx : Mask) {
  3290. unsigned Input = 0;
  3291. if (Idx < 0)
  3292. continue;
  3293. if (Idx >= (int)SrcNumElts) {
  3294. Input = 1;
  3295. Idx -= SrcNumElts;
  3296. }
  3297. // If all the indices come from the same MaskNumElts sized portion of
  3298. // the sources we can use extract. Also make sure the extract wouldn't
  3299. // extract past the end of the source.
  3300. int NewStartIdx = alignDown(Idx, MaskNumElts);
  3301. if (NewStartIdx + MaskNumElts > SrcNumElts ||
  3302. (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx))
  3303. CanExtract = false;
  3304. // Make sure we always update StartIdx as we use it to track if all
  3305. // elements are undef.
  3306. StartIdx[Input] = NewStartIdx;
  3307. }
  3308. if (StartIdx[0] < 0 && StartIdx[1] < 0) {
  3309. setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
  3310. return;
  3311. }
  3312. if (CanExtract) {
  3313. // Extract appropriate subvector and generate a vector shuffle
  3314. for (unsigned Input = 0; Input < 2; ++Input) {
  3315. SDValue &Src = Input == 0 ? Src1 : Src2;
  3316. if (StartIdx[Input] < 0)
  3317. Src = DAG.getUNDEF(VT);
  3318. else {
  3319. Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Src,
  3320. DAG.getVectorIdxConstant(StartIdx[Input], DL));
  3321. }
  3322. }
  3323. // Calculate new mask.
  3324. SmallVector<int, 8> MappedOps(Mask);
  3325. for (int &Idx : MappedOps) {
  3326. if (Idx >= (int)SrcNumElts)
  3327. Idx -= SrcNumElts + StartIdx[1] - MaskNumElts;
  3328. else if (Idx >= 0)
  3329. Idx -= StartIdx[0];
  3330. }
  3331. setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps));
  3332. return;
  3333. }
  3334. }
  3335. // We can't use either concat vectors or extract subvectors so fall back to
  3336. // replacing the shuffle with extract and build vector.
  3337. // to insert and build vector.
  3338. EVT EltVT = VT.getVectorElementType();
  3339. SmallVector<SDValue,8> Ops;
  3340. for (int Idx : Mask) {
  3341. SDValue Res;
  3342. if (Idx < 0) {
  3343. Res = DAG.getUNDEF(EltVT);
  3344. } else {
  3345. SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2;
  3346. if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts;
  3347. Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Src,
  3348. DAG.getVectorIdxConstant(Idx, DL));
  3349. }
  3350. Ops.push_back(Res);
  3351. }
  3352. setValue(&I, DAG.getBuildVector(VT, DL, Ops));
  3353. }
  3354. void SelectionDAGBuilder::visitInsertValue(const InsertValueInst &I) {
  3355. ArrayRef<unsigned> Indices = I.getIndices();
  3356. const Value *Op0 = I.getOperand(0);
  3357. const Value *Op1 = I.getOperand(1);
  3358. Type *AggTy = I.getType();
  3359. Type *ValTy = Op1->getType();
  3360. bool IntoUndef = isa<UndefValue>(Op0);
  3361. bool FromUndef = isa<UndefValue>(Op1);
  3362. unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
  3363. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3364. SmallVector<EVT, 4> AggValueVTs;
  3365. ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs);
  3366. SmallVector<EVT, 4> ValValueVTs;
  3367. ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
  3368. unsigned NumAggValues = AggValueVTs.size();
  3369. unsigned NumValValues = ValValueVTs.size();
  3370. SmallVector<SDValue, 4> Values(NumAggValues);
  3371. // Ignore an insertvalue that produces an empty object
  3372. if (!NumAggValues) {
  3373. setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
  3374. return;
  3375. }
  3376. SDValue Agg = getValue(Op0);
  3377. unsigned i = 0;
  3378. // Copy the beginning value(s) from the original aggregate.
  3379. for (; i != LinearIndex; ++i)
  3380. Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
  3381. SDValue(Agg.getNode(), Agg.getResNo() + i);
  3382. // Copy values from the inserted value(s).
  3383. if (NumValValues) {
  3384. SDValue Val = getValue(Op1);
  3385. for (; i != LinearIndex + NumValValues; ++i)
  3386. Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
  3387. SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
  3388. }
  3389. // Copy remaining value(s) from the original aggregate.
  3390. for (; i != NumAggValues; ++i)
  3391. Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
  3392. SDValue(Agg.getNode(), Agg.getResNo() + i);
  3393. setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
  3394. DAG.getVTList(AggValueVTs), Values));
  3395. }
  3396. void SelectionDAGBuilder::visitExtractValue(const ExtractValueInst &I) {
  3397. ArrayRef<unsigned> Indices = I.getIndices();
  3398. const Value *Op0 = I.getOperand(0);
  3399. Type *AggTy = Op0->getType();
  3400. Type *ValTy = I.getType();
  3401. bool OutOfUndef = isa<UndefValue>(Op0);
  3402. unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
  3403. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3404. SmallVector<EVT, 4> ValValueVTs;
  3405. ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
  3406. unsigned NumValValues = ValValueVTs.size();
  3407. // Ignore a extractvalue that produces an empty object
  3408. if (!NumValValues) {
  3409. setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
  3410. return;
  3411. }
  3412. SmallVector<SDValue, 4> Values(NumValValues);
  3413. SDValue Agg = getValue(Op0);
  3414. // Copy out the selected value(s).
  3415. for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
  3416. Values[i - LinearIndex] =
  3417. OutOfUndef ?
  3418. DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
  3419. SDValue(Agg.getNode(), Agg.getResNo() + i);
  3420. setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
  3421. DAG.getVTList(ValValueVTs), Values));
  3422. }
  3423. void SelectionDAGBuilder::visitGetElementPtr(const User &I) {
  3424. Value *Op0 = I.getOperand(0);
  3425. // Note that the pointer operand may be a vector of pointers. Take the scalar
  3426. // element which holds a pointer.
  3427. unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace();
  3428. SDValue N = getValue(Op0);
  3429. SDLoc dl = getCurSDLoc();
  3430. auto &TLI = DAG.getTargetLoweringInfo();
  3431. // Normalize Vector GEP - all scalar operands should be converted to the
  3432. // splat vector.
  3433. bool IsVectorGEP = I.getType()->isVectorTy();
  3434. ElementCount VectorElementCount =
  3435. IsVectorGEP ? cast<VectorType>(I.getType())->getElementCount()
  3436. : ElementCount::getFixed(0);
  3437. if (IsVectorGEP && !N.getValueType().isVector()) {
  3438. LLVMContext &Context = *DAG.getContext();
  3439. EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorElementCount);
  3440. N = DAG.getSplat(VT, dl, N);
  3441. }
  3442. for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I);
  3443. GTI != E; ++GTI) {
  3444. const Value *Idx = GTI.getOperand();
  3445. if (StructType *StTy = GTI.getStructTypeOrNull()) {
  3446. unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
  3447. if (Field) {
  3448. // N = N + Offset
  3449. uint64_t Offset =
  3450. DAG.getDataLayout().getStructLayout(StTy)->getElementOffset(Field);
  3451. // In an inbounds GEP with an offset that is nonnegative even when
  3452. // interpreted as signed, assume there is no unsigned overflow.
  3453. SDNodeFlags Flags;
  3454. if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds())
  3455. Flags.setNoUnsignedWrap(true);
  3456. N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N,
  3457. DAG.getConstant(Offset, dl, N.getValueType()), Flags);
  3458. }
  3459. } else {
  3460. // IdxSize is the width of the arithmetic according to IR semantics.
  3461. // In SelectionDAG, we may prefer to do arithmetic in a wider bitwidth
  3462. // (and fix up the result later).
  3463. unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS);
  3464. MVT IdxTy = MVT::getIntegerVT(IdxSize);
  3465. TypeSize ElementSize =
  3466. DAG.getDataLayout().getTypeAllocSize(GTI.getIndexedType());
  3467. // We intentionally mask away the high bits here; ElementSize may not
  3468. // fit in IdxTy.
  3469. APInt ElementMul(IdxSize, ElementSize.getKnownMinValue());
  3470. bool ElementScalable = ElementSize.isScalable();
  3471. // If this is a scalar constant or a splat vector of constants,
  3472. // handle it quickly.
  3473. const auto *C = dyn_cast<Constant>(Idx);
  3474. if (C && isa<VectorType>(C->getType()))
  3475. C = C->getSplatValue();
  3476. const auto *CI = dyn_cast_or_null<ConstantInt>(C);
  3477. if (CI && CI->isZero())
  3478. continue;
  3479. if (CI && !ElementScalable) {
  3480. APInt Offs = ElementMul * CI->getValue().sextOrTrunc(IdxSize);
  3481. LLVMContext &Context = *DAG.getContext();
  3482. SDValue OffsVal;
  3483. if (IsVectorGEP)
  3484. OffsVal = DAG.getConstant(
  3485. Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorElementCount));
  3486. else
  3487. OffsVal = DAG.getConstant(Offs, dl, IdxTy);
  3488. // In an inbounds GEP with an offset that is nonnegative even when
  3489. // interpreted as signed, assume there is no unsigned overflow.
  3490. SDNodeFlags Flags;
  3491. if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds())
  3492. Flags.setNoUnsignedWrap(true);
  3493. OffsVal = DAG.getSExtOrTrunc(OffsVal, dl, N.getValueType());
  3494. N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags);
  3495. continue;
  3496. }
  3497. // N = N + Idx * ElementMul;
  3498. SDValue IdxN = getValue(Idx);
  3499. if (!IdxN.getValueType().isVector() && IsVectorGEP) {
  3500. EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(),
  3501. VectorElementCount);
  3502. IdxN = DAG.getSplat(VT, dl, IdxN);
  3503. }
  3504. // If the index is smaller or larger than intptr_t, truncate or extend
  3505. // it.
  3506. IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType());
  3507. if (ElementScalable) {
  3508. EVT VScaleTy = N.getValueType().getScalarType();
  3509. SDValue VScale = DAG.getNode(
  3510. ISD::VSCALE, dl, VScaleTy,
  3511. DAG.getConstant(ElementMul.getZExtValue(), dl, VScaleTy));
  3512. if (IsVectorGEP)
  3513. VScale = DAG.getSplatVector(N.getValueType(), dl, VScale);
  3514. IdxN = DAG.getNode(ISD::MUL, dl, N.getValueType(), IdxN, VScale);
  3515. } else {
  3516. // If this is a multiply by a power of two, turn it into a shl
  3517. // immediately. This is a very common case.
  3518. if (ElementMul != 1) {
  3519. if (ElementMul.isPowerOf2()) {
  3520. unsigned Amt = ElementMul.logBase2();
  3521. IdxN = DAG.getNode(ISD::SHL, dl,
  3522. N.getValueType(), IdxN,
  3523. DAG.getConstant(Amt, dl, IdxN.getValueType()));
  3524. } else {
  3525. SDValue Scale = DAG.getConstant(ElementMul.getZExtValue(), dl,
  3526. IdxN.getValueType());
  3527. IdxN = DAG.getNode(ISD::MUL, dl,
  3528. N.getValueType(), IdxN, Scale);
  3529. }
  3530. }
  3531. }
  3532. N = DAG.getNode(ISD::ADD, dl,
  3533. N.getValueType(), N, IdxN);
  3534. }
  3535. }
  3536. MVT PtrTy = TLI.getPointerTy(DAG.getDataLayout(), AS);
  3537. MVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout(), AS);
  3538. if (IsVectorGEP) {
  3539. PtrTy = MVT::getVectorVT(PtrTy, VectorElementCount);
  3540. PtrMemTy = MVT::getVectorVT(PtrMemTy, VectorElementCount);
  3541. }
  3542. if (PtrMemTy != PtrTy && !cast<GEPOperator>(I).isInBounds())
  3543. N = DAG.getPtrExtendInReg(N, dl, PtrMemTy);
  3544. setValue(&I, N);
  3545. }
  3546. void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) {
  3547. // If this is a fixed sized alloca in the entry block of the function,
  3548. // allocate it statically on the stack.
  3549. if (FuncInfo.StaticAllocaMap.count(&I))
  3550. return; // getValue will auto-populate this.
  3551. SDLoc dl = getCurSDLoc();
  3552. Type *Ty = I.getAllocatedType();
  3553. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3554. auto &DL = DAG.getDataLayout();
  3555. TypeSize TySize = DL.getTypeAllocSize(Ty);
  3556. MaybeAlign Alignment = std::max(DL.getPrefTypeAlign(Ty), I.getAlign());
  3557. SDValue AllocSize = getValue(I.getArraySize());
  3558. EVT IntPtr = TLI.getPointerTy(DAG.getDataLayout(), I.getAddressSpace());
  3559. if (AllocSize.getValueType() != IntPtr)
  3560. AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr);
  3561. if (TySize.isScalable())
  3562. AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr, AllocSize,
  3563. DAG.getVScale(dl, IntPtr,
  3564. APInt(IntPtr.getScalarSizeInBits(),
  3565. TySize.getKnownMinValue())));
  3566. else
  3567. AllocSize =
  3568. DAG.getNode(ISD::MUL, dl, IntPtr, AllocSize,
  3569. DAG.getConstant(TySize.getFixedValue(), dl, IntPtr));
  3570. // Handle alignment. If the requested alignment is less than or equal to
  3571. // the stack alignment, ignore it. If the size is greater than or equal to
  3572. // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
  3573. Align StackAlign = DAG.getSubtarget().getFrameLowering()->getStackAlign();
  3574. if (*Alignment <= StackAlign)
  3575. Alignment = std::nullopt;
  3576. const uint64_t StackAlignMask = StackAlign.value() - 1U;
  3577. // Round the size of the allocation up to the stack alignment size
  3578. // by add SA-1 to the size. This doesn't overflow because we're computing
  3579. // an address inside an alloca.
  3580. SDNodeFlags Flags;
  3581. Flags.setNoUnsignedWrap(true);
  3582. AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize,
  3583. DAG.getConstant(StackAlignMask, dl, IntPtr), Flags);
  3584. // Mask out the low bits for alignment purposes.
  3585. AllocSize = DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize,
  3586. DAG.getConstant(~StackAlignMask, dl, IntPtr));
  3587. SDValue Ops[] = {
  3588. getRoot(), AllocSize,
  3589. DAG.getConstant(Alignment ? Alignment->value() : 0, dl, IntPtr)};
  3590. SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
  3591. SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops);
  3592. setValue(&I, DSA);
  3593. DAG.setRoot(DSA.getValue(1));
  3594. assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects());
  3595. }
  3596. void SelectionDAGBuilder::visitLoad(const LoadInst &I) {
  3597. if (I.isAtomic())
  3598. return visitAtomicLoad(I);
  3599. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3600. const Value *SV = I.getOperand(0);
  3601. if (TLI.supportSwiftError()) {
  3602. // Swifterror values can come from either a function parameter with
  3603. // swifterror attribute or an alloca with swifterror attribute.
  3604. if (const Argument *Arg = dyn_cast<Argument>(SV)) {
  3605. if (Arg->hasSwiftErrorAttr())
  3606. return visitLoadFromSwiftError(I);
  3607. }
  3608. if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) {
  3609. if (Alloca->isSwiftError())
  3610. return visitLoadFromSwiftError(I);
  3611. }
  3612. }
  3613. SDValue Ptr = getValue(SV);
  3614. Type *Ty = I.getType();
  3615. SmallVector<EVT, 4> ValueVTs, MemVTs;
  3616. SmallVector<uint64_t, 4> Offsets;
  3617. ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &MemVTs, &Offsets);
  3618. unsigned NumValues = ValueVTs.size();
  3619. if (NumValues == 0)
  3620. return;
  3621. Align Alignment = I.getAlign();
  3622. AAMDNodes AAInfo = I.getAAMetadata();
  3623. const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
  3624. bool isVolatile = I.isVolatile();
  3625. MachineMemOperand::Flags MMOFlags =
  3626. TLI.getLoadMemOperandFlags(I, DAG.getDataLayout(), AC, LibInfo);
  3627. SDValue Root;
  3628. bool ConstantMemory = false;
  3629. if (isVolatile)
  3630. // Serialize volatile loads with other side effects.
  3631. Root = getRoot();
  3632. else if (NumValues > MaxParallelChains)
  3633. Root = getMemoryRoot();
  3634. else if (AA &&
  3635. AA->pointsToConstantMemory(MemoryLocation(
  3636. SV,
  3637. LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
  3638. AAInfo))) {
  3639. // Do not serialize (non-volatile) loads of constant memory with anything.
  3640. Root = DAG.getEntryNode();
  3641. ConstantMemory = true;
  3642. MMOFlags |= MachineMemOperand::MOInvariant;
  3643. } else {
  3644. // Do not serialize non-volatile loads against each other.
  3645. Root = DAG.getRoot();
  3646. }
  3647. SDLoc dl = getCurSDLoc();
  3648. if (isVolatile)
  3649. Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG);
  3650. // An aggregate load cannot wrap around the address space, so offsets to its
  3651. // parts don't wrap either.
  3652. SDNodeFlags Flags;
  3653. Flags.setNoUnsignedWrap(true);
  3654. SmallVector<SDValue, 4> Values(NumValues);
  3655. SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
  3656. EVT PtrVT = Ptr.getValueType();
  3657. unsigned ChainI = 0;
  3658. for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
  3659. // Serializing loads here may result in excessive register pressure, and
  3660. // TokenFactor places arbitrary choke points on the scheduler. SD scheduling
  3661. // could recover a bit by hoisting nodes upward in the chain by recognizing
  3662. // they are side-effect free or do not alias. The optimizer should really
  3663. // avoid this case by converting large object/array copies to llvm.memcpy
  3664. // (MaxParallelChains should always remain as failsafe).
  3665. if (ChainI == MaxParallelChains) {
  3666. assert(PendingLoads.empty() && "PendingLoads must be serialized first");
  3667. SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
  3668. ArrayRef(Chains.data(), ChainI));
  3669. Root = Chain;
  3670. ChainI = 0;
  3671. }
  3672. SDValue A = DAG.getNode(ISD::ADD, dl,
  3673. PtrVT, Ptr,
  3674. DAG.getConstant(Offsets[i], dl, PtrVT),
  3675. Flags);
  3676. SDValue L = DAG.getLoad(MemVTs[i], dl, Root, A,
  3677. MachinePointerInfo(SV, Offsets[i]), Alignment,
  3678. MMOFlags, AAInfo, Ranges);
  3679. Chains[ChainI] = L.getValue(1);
  3680. if (MemVTs[i] != ValueVTs[i])
  3681. L = DAG.getZExtOrTrunc(L, dl, ValueVTs[i]);
  3682. Values[i] = L;
  3683. }
  3684. if (!ConstantMemory) {
  3685. SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
  3686. ArrayRef(Chains.data(), ChainI));
  3687. if (isVolatile)
  3688. DAG.setRoot(Chain);
  3689. else
  3690. PendingLoads.push_back(Chain);
  3691. }
  3692. setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl,
  3693. DAG.getVTList(ValueVTs), Values));
  3694. }
  3695. void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) {
  3696. assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
  3697. "call visitStoreToSwiftError when backend supports swifterror");
  3698. SmallVector<EVT, 4> ValueVTs;
  3699. SmallVector<uint64_t, 4> Offsets;
  3700. const Value *SrcV = I.getOperand(0);
  3701. ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
  3702. SrcV->getType(), ValueVTs, &Offsets);
  3703. assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
  3704. "expect a single EVT for swifterror");
  3705. SDValue Src = getValue(SrcV);
  3706. // Create a virtual register, then update the virtual register.
  3707. Register VReg =
  3708. SwiftError.getOrCreateVRegDefAt(&I, FuncInfo.MBB, I.getPointerOperand());
  3709. // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue
  3710. // Chain can be getRoot or getControlRoot.
  3711. SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg,
  3712. SDValue(Src.getNode(), Src.getResNo()));
  3713. DAG.setRoot(CopyNode);
  3714. }
  3715. void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) {
  3716. assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
  3717. "call visitLoadFromSwiftError when backend supports swifterror");
  3718. assert(!I.isVolatile() &&
  3719. !I.hasMetadata(LLVMContext::MD_nontemporal) &&
  3720. !I.hasMetadata(LLVMContext::MD_invariant_load) &&
  3721. "Support volatile, non temporal, invariant for load_from_swift_error");
  3722. const Value *SV = I.getOperand(0);
  3723. Type *Ty = I.getType();
  3724. assert(
  3725. (!AA ||
  3726. !AA->pointsToConstantMemory(MemoryLocation(
  3727. SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
  3728. I.getAAMetadata()))) &&
  3729. "load_from_swift_error should not be constant memory");
  3730. SmallVector<EVT, 4> ValueVTs;
  3731. SmallVector<uint64_t, 4> Offsets;
  3732. ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty,
  3733. ValueVTs, &Offsets);
  3734. assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
  3735. "expect a single EVT for swifterror");
  3736. // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT
  3737. SDValue L = DAG.getCopyFromReg(
  3738. getRoot(), getCurSDLoc(),
  3739. SwiftError.getOrCreateVRegUseAt(&I, FuncInfo.MBB, SV), ValueVTs[0]);
  3740. setValue(&I, L);
  3741. }
  3742. void SelectionDAGBuilder::visitStore(const StoreInst &I) {
  3743. if (I.isAtomic())
  3744. return visitAtomicStore(I);
  3745. const Value *SrcV = I.getOperand(0);
  3746. const Value *PtrV = I.getOperand(1);
  3747. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3748. if (TLI.supportSwiftError()) {
  3749. // Swifterror values can come from either a function parameter with
  3750. // swifterror attribute or an alloca with swifterror attribute.
  3751. if (const Argument *Arg = dyn_cast<Argument>(PtrV)) {
  3752. if (Arg->hasSwiftErrorAttr())
  3753. return visitStoreToSwiftError(I);
  3754. }
  3755. if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) {
  3756. if (Alloca->isSwiftError())
  3757. return visitStoreToSwiftError(I);
  3758. }
  3759. }
  3760. SmallVector<EVT, 4> ValueVTs, MemVTs;
  3761. SmallVector<uint64_t, 4> Offsets;
  3762. ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
  3763. SrcV->getType(), ValueVTs, &MemVTs, &Offsets);
  3764. unsigned NumValues = ValueVTs.size();
  3765. if (NumValues == 0)
  3766. return;
  3767. // Get the lowered operands. Note that we do this after
  3768. // checking if NumResults is zero, because with zero results
  3769. // the operands won't have values in the map.
  3770. SDValue Src = getValue(SrcV);
  3771. SDValue Ptr = getValue(PtrV);
  3772. SDValue Root = I.isVolatile() ? getRoot() : getMemoryRoot();
  3773. SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
  3774. SDLoc dl = getCurSDLoc();
  3775. Align Alignment = I.getAlign();
  3776. AAMDNodes AAInfo = I.getAAMetadata();
  3777. auto MMOFlags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout());
  3778. // An aggregate load cannot wrap around the address space, so offsets to its
  3779. // parts don't wrap either.
  3780. SDNodeFlags Flags;
  3781. Flags.setNoUnsignedWrap(true);
  3782. unsigned ChainI = 0;
  3783. for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
  3784. // See visitLoad comments.
  3785. if (ChainI == MaxParallelChains) {
  3786. SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
  3787. ArrayRef(Chains.data(), ChainI));
  3788. Root = Chain;
  3789. ChainI = 0;
  3790. }
  3791. SDValue Add =
  3792. DAG.getMemBasePlusOffset(Ptr, TypeSize::Fixed(Offsets[i]), dl, Flags);
  3793. SDValue Val = SDValue(Src.getNode(), Src.getResNo() + i);
  3794. if (MemVTs[i] != ValueVTs[i])
  3795. Val = DAG.getPtrExtOrTrunc(Val, dl, MemVTs[i]);
  3796. SDValue St =
  3797. DAG.getStore(Root, dl, Val, Add, MachinePointerInfo(PtrV, Offsets[i]),
  3798. Alignment, MMOFlags, AAInfo);
  3799. Chains[ChainI] = St;
  3800. }
  3801. SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
  3802. ArrayRef(Chains.data(), ChainI));
  3803. setValue(&I, StoreNode);
  3804. DAG.setRoot(StoreNode);
  3805. }
  3806. void SelectionDAGBuilder::visitMaskedStore(const CallInst &I,
  3807. bool IsCompressing) {
  3808. SDLoc sdl = getCurSDLoc();
  3809. auto getMaskedStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
  3810. MaybeAlign &Alignment) {
  3811. // llvm.masked.store.*(Src0, Ptr, alignment, Mask)
  3812. Src0 = I.getArgOperand(0);
  3813. Ptr = I.getArgOperand(1);
  3814. Alignment = cast<ConstantInt>(I.getArgOperand(2))->getMaybeAlignValue();
  3815. Mask = I.getArgOperand(3);
  3816. };
  3817. auto getCompressingStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
  3818. MaybeAlign &Alignment) {
  3819. // llvm.masked.compressstore.*(Src0, Ptr, Mask)
  3820. Src0 = I.getArgOperand(0);
  3821. Ptr = I.getArgOperand(1);
  3822. Mask = I.getArgOperand(2);
  3823. Alignment = std::nullopt;
  3824. };
  3825. Value *PtrOperand, *MaskOperand, *Src0Operand;
  3826. MaybeAlign Alignment;
  3827. if (IsCompressing)
  3828. getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
  3829. else
  3830. getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
  3831. SDValue Ptr = getValue(PtrOperand);
  3832. SDValue Src0 = getValue(Src0Operand);
  3833. SDValue Mask = getValue(MaskOperand);
  3834. SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
  3835. EVT VT = Src0.getValueType();
  3836. if (!Alignment)
  3837. Alignment = DAG.getEVTAlign(VT);
  3838. MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
  3839. MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore,
  3840. MemoryLocation::UnknownSize, *Alignment, I.getAAMetadata());
  3841. SDValue StoreNode =
  3842. DAG.getMaskedStore(getMemoryRoot(), sdl, Src0, Ptr, Offset, Mask, VT, MMO,
  3843. ISD::UNINDEXED, false /* Truncating */, IsCompressing);
  3844. DAG.setRoot(StoreNode);
  3845. setValue(&I, StoreNode);
  3846. }
  3847. // Get a uniform base for the Gather/Scatter intrinsic.
  3848. // The first argument of the Gather/Scatter intrinsic is a vector of pointers.
  3849. // We try to represent it as a base pointer + vector of indices.
  3850. // Usually, the vector of pointers comes from a 'getelementptr' instruction.
  3851. // The first operand of the GEP may be a single pointer or a vector of pointers
  3852. // Example:
  3853. // %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind
  3854. // or
  3855. // %gep.ptr = getelementptr i32, i32* %ptr, <8 x i32> %ind
  3856. // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, ..
  3857. //
  3858. // When the first GEP operand is a single pointer - it is the uniform base we
  3859. // are looking for. If first operand of the GEP is a splat vector - we
  3860. // extract the splat value and use it as a uniform base.
  3861. // In all other cases the function returns 'false'.
  3862. static bool getUniformBase(const Value *Ptr, SDValue &Base, SDValue &Index,
  3863. ISD::MemIndexType &IndexType, SDValue &Scale,
  3864. SelectionDAGBuilder *SDB, const BasicBlock *CurBB,
  3865. uint64_t ElemSize) {
  3866. SelectionDAG& DAG = SDB->DAG;
  3867. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3868. const DataLayout &DL = DAG.getDataLayout();
  3869. assert(Ptr->getType()->isVectorTy() && "Unexpected pointer type");
  3870. // Handle splat constant pointer.
  3871. if (auto *C = dyn_cast<Constant>(Ptr)) {
  3872. C = C->getSplatValue();
  3873. if (!C)
  3874. return false;
  3875. Base = SDB->getValue(C);
  3876. ElementCount NumElts = cast<VectorType>(Ptr->getType())->getElementCount();
  3877. EVT VT = EVT::getVectorVT(*DAG.getContext(), TLI.getPointerTy(DL), NumElts);
  3878. Index = DAG.getConstant(0, SDB->getCurSDLoc(), VT);
  3879. IndexType = ISD::SIGNED_SCALED;
  3880. Scale = DAG.getTargetConstant(1, SDB->getCurSDLoc(), TLI.getPointerTy(DL));
  3881. return true;
  3882. }
  3883. const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr);
  3884. if (!GEP || GEP->getParent() != CurBB)
  3885. return false;
  3886. if (GEP->getNumOperands() != 2)
  3887. return false;
  3888. const Value *BasePtr = GEP->getPointerOperand();
  3889. const Value *IndexVal = GEP->getOperand(GEP->getNumOperands() - 1);
  3890. // Make sure the base is scalar and the index is a vector.
  3891. if (BasePtr->getType()->isVectorTy() || !IndexVal->getType()->isVectorTy())
  3892. return false;
  3893. uint64_t ScaleVal = DL.getTypeAllocSize(GEP->getResultElementType());
  3894. // Target may not support the required addressing mode.
  3895. if (ScaleVal != 1 &&
  3896. !TLI.isLegalScaleForGatherScatter(ScaleVal, ElemSize))
  3897. return false;
  3898. Base = SDB->getValue(BasePtr);
  3899. Index = SDB->getValue(IndexVal);
  3900. IndexType = ISD::SIGNED_SCALED;
  3901. Scale =
  3902. DAG.getTargetConstant(ScaleVal, SDB->getCurSDLoc(), TLI.getPointerTy(DL));
  3903. return true;
  3904. }
  3905. void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) {
  3906. SDLoc sdl = getCurSDLoc();
  3907. // llvm.masked.scatter.*(Src0, Ptrs, alignment, Mask)
  3908. const Value *Ptr = I.getArgOperand(1);
  3909. SDValue Src0 = getValue(I.getArgOperand(0));
  3910. SDValue Mask = getValue(I.getArgOperand(3));
  3911. EVT VT = Src0.getValueType();
  3912. Align Alignment = cast<ConstantInt>(I.getArgOperand(2))
  3913. ->getMaybeAlignValue()
  3914. .value_or(DAG.getEVTAlign(VT.getScalarType()));
  3915. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3916. SDValue Base;
  3917. SDValue Index;
  3918. ISD::MemIndexType IndexType;
  3919. SDValue Scale;
  3920. bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this,
  3921. I.getParent(), VT.getScalarStoreSize());
  3922. unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace();
  3923. MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
  3924. MachinePointerInfo(AS), MachineMemOperand::MOStore,
  3925. // TODO: Make MachineMemOperands aware of scalable
  3926. // vectors.
  3927. MemoryLocation::UnknownSize, Alignment, I.getAAMetadata());
  3928. if (!UniformBase) {
  3929. Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
  3930. Index = getValue(Ptr);
  3931. IndexType = ISD::SIGNED_SCALED;
  3932. Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
  3933. }
  3934. EVT IdxVT = Index.getValueType();
  3935. EVT EltTy = IdxVT.getVectorElementType();
  3936. if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
  3937. EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
  3938. Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index);
  3939. }
  3940. SDValue Ops[] = { getMemoryRoot(), Src0, Mask, Base, Index, Scale };
  3941. SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl,
  3942. Ops, MMO, IndexType, false);
  3943. DAG.setRoot(Scatter);
  3944. setValue(&I, Scatter);
  3945. }
  3946. void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) {
  3947. SDLoc sdl = getCurSDLoc();
  3948. auto getMaskedLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
  3949. MaybeAlign &Alignment) {
  3950. // @llvm.masked.load.*(Ptr, alignment, Mask, Src0)
  3951. Ptr = I.getArgOperand(0);
  3952. Alignment = cast<ConstantInt>(I.getArgOperand(1))->getMaybeAlignValue();
  3953. Mask = I.getArgOperand(2);
  3954. Src0 = I.getArgOperand(3);
  3955. };
  3956. auto getExpandingLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
  3957. MaybeAlign &Alignment) {
  3958. // @llvm.masked.expandload.*(Ptr, Mask, Src0)
  3959. Ptr = I.getArgOperand(0);
  3960. Alignment = std::nullopt;
  3961. Mask = I.getArgOperand(1);
  3962. Src0 = I.getArgOperand(2);
  3963. };
  3964. Value *PtrOperand, *MaskOperand, *Src0Operand;
  3965. MaybeAlign Alignment;
  3966. if (IsExpanding)
  3967. getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
  3968. else
  3969. getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
  3970. SDValue Ptr = getValue(PtrOperand);
  3971. SDValue Src0 = getValue(Src0Operand);
  3972. SDValue Mask = getValue(MaskOperand);
  3973. SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
  3974. EVT VT = Src0.getValueType();
  3975. if (!Alignment)
  3976. Alignment = DAG.getEVTAlign(VT);
  3977. AAMDNodes AAInfo = I.getAAMetadata();
  3978. const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
  3979. // Do not serialize masked loads of constant memory with anything.
  3980. MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo);
  3981. bool AddToChain = !AA || !AA->pointsToConstantMemory(ML);
  3982. SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
  3983. MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
  3984. MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad,
  3985. MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges);
  3986. SDValue Load =
  3987. DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Offset, Mask, Src0, VT, MMO,
  3988. ISD::UNINDEXED, ISD::NON_EXTLOAD, IsExpanding);
  3989. if (AddToChain)
  3990. PendingLoads.push_back(Load.getValue(1));
  3991. setValue(&I, Load);
  3992. }
  3993. void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) {
  3994. SDLoc sdl = getCurSDLoc();
  3995. // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0)
  3996. const Value *Ptr = I.getArgOperand(0);
  3997. SDValue Src0 = getValue(I.getArgOperand(3));
  3998. SDValue Mask = getValue(I.getArgOperand(2));
  3999. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  4000. EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  4001. Align Alignment = cast<ConstantInt>(I.getArgOperand(1))
  4002. ->getMaybeAlignValue()
  4003. .value_or(DAG.getEVTAlign(VT.getScalarType()));
  4004. const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
  4005. SDValue Root = DAG.getRoot();
  4006. SDValue Base;
  4007. SDValue Index;
  4008. ISD::MemIndexType IndexType;
  4009. SDValue Scale;
  4010. bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this,
  4011. I.getParent(), VT.getScalarStoreSize());
  4012. unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace();
  4013. MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
  4014. MachinePointerInfo(AS), MachineMemOperand::MOLoad,
  4015. // TODO: Make MachineMemOperands aware of scalable
  4016. // vectors.
  4017. MemoryLocation::UnknownSize, Alignment, I.getAAMetadata(), Ranges);
  4018. if (!UniformBase) {
  4019. Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
  4020. Index = getValue(Ptr);
  4021. IndexType = ISD::SIGNED_SCALED;
  4022. Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
  4023. }
  4024. EVT IdxVT = Index.getValueType();
  4025. EVT EltTy = IdxVT.getVectorElementType();
  4026. if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
  4027. EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
  4028. Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index);
  4029. }
  4030. SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale };
  4031. SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl,
  4032. Ops, MMO, IndexType, ISD::NON_EXTLOAD);
  4033. PendingLoads.push_back(Gather.getValue(1));
  4034. setValue(&I, Gather);
  4035. }
  4036. void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) {
  4037. SDLoc dl = getCurSDLoc();
  4038. AtomicOrdering SuccessOrdering = I.getSuccessOrdering();
  4039. AtomicOrdering FailureOrdering = I.getFailureOrdering();
  4040. SyncScope::ID SSID = I.getSyncScopeID();
  4041. SDValue InChain = getRoot();
  4042. MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType();
  4043. SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other);
  4044. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  4045. auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout());
  4046. MachineFunction &MF = DAG.getMachineFunction();
  4047. MachineMemOperand *MMO = MF.getMachineMemOperand(
  4048. MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
  4049. DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, SuccessOrdering,
  4050. FailureOrdering);
  4051. SDValue L = DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS,
  4052. dl, MemVT, VTs, InChain,
  4053. getValue(I.getPointerOperand()),
  4054. getValue(I.getCompareOperand()),
  4055. getValue(I.getNewValOperand()), MMO);
  4056. SDValue OutChain = L.getValue(2);
  4057. setValue(&I, L);
  4058. DAG.setRoot(OutChain);
  4059. }
  4060. void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) {
  4061. SDLoc dl = getCurSDLoc();
  4062. ISD::NodeType NT;
  4063. switch (I.getOperation()) {
  4064. default: llvm_unreachable("Unknown atomicrmw operation");
  4065. case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break;
  4066. case AtomicRMWInst::Add: NT = ISD::ATOMIC_LOAD_ADD; break;
  4067. case AtomicRMWInst::Sub: NT = ISD::ATOMIC_LOAD_SUB; break;
  4068. case AtomicRMWInst::And: NT = ISD::ATOMIC_LOAD_AND; break;
  4069. case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break;
  4070. case AtomicRMWInst::Or: NT = ISD::ATOMIC_LOAD_OR; break;
  4071. case AtomicRMWInst::Xor: NT = ISD::ATOMIC_LOAD_XOR; break;
  4072. case AtomicRMWInst::Max: NT = ISD::ATOMIC_LOAD_MAX; break;
  4073. case AtomicRMWInst::Min: NT = ISD::ATOMIC_LOAD_MIN; break;
  4074. case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break;
  4075. case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break;
  4076. case AtomicRMWInst::FAdd: NT = ISD::ATOMIC_LOAD_FADD; break;
  4077. case AtomicRMWInst::FSub: NT = ISD::ATOMIC_LOAD_FSUB; break;
  4078. case AtomicRMWInst::FMax: NT = ISD::ATOMIC_LOAD_FMAX; break;
  4079. case AtomicRMWInst::FMin: NT = ISD::ATOMIC_LOAD_FMIN; break;
  4080. case AtomicRMWInst::UIncWrap:
  4081. NT = ISD::ATOMIC_LOAD_UINC_WRAP;
  4082. break;
  4083. case AtomicRMWInst::UDecWrap:
  4084. NT = ISD::ATOMIC_LOAD_UDEC_WRAP;
  4085. break;
  4086. }
  4087. AtomicOrdering Ordering = I.getOrdering();
  4088. SyncScope::ID SSID = I.getSyncScopeID();
  4089. SDValue InChain = getRoot();
  4090. auto MemVT = getValue(I.getValOperand()).getSimpleValueType();
  4091. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  4092. auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout());
  4093. MachineFunction &MF = DAG.getMachineFunction();
  4094. MachineMemOperand *MMO = MF.getMachineMemOperand(
  4095. MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
  4096. DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, Ordering);
  4097. SDValue L =
  4098. DAG.getAtomic(NT, dl, MemVT, InChain,
  4099. getValue(I.getPointerOperand()), getValue(I.getValOperand()),
  4100. MMO);
  4101. SDValue OutChain = L.getValue(1);
  4102. setValue(&I, L);
  4103. DAG.setRoot(OutChain);
  4104. }
  4105. void SelectionDAGBuilder::visitFence(const FenceInst &I) {
  4106. SDLoc dl = getCurSDLoc();
  4107. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  4108. SDValue Ops[3];
  4109. Ops[0] = getRoot();
  4110. Ops[1] = DAG.getTargetConstant((unsigned)I.getOrdering(), dl,
  4111. TLI.getFenceOperandTy(DAG.getDataLayout()));
  4112. Ops[2] = DAG.getTargetConstant(I.getSyncScopeID(), dl,
  4113. TLI.getFenceOperandTy(DAG.getDataLayout()));
  4114. SDValue N = DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops);
  4115. setValue(&I, N);
  4116. DAG.setRoot(N);
  4117. }
  4118. void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) {
  4119. SDLoc dl = getCurSDLoc();
  4120. AtomicOrdering Order = I.getOrdering();
  4121. SyncScope::ID SSID = I.getSyncScopeID();
  4122. SDValue InChain = getRoot();
  4123. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  4124. EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  4125. EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
  4126. if (!TLI.supportsUnalignedAtomics() &&
  4127. I.getAlign().value() < MemVT.getSizeInBits() / 8)
  4128. report_fatal_error("Cannot generate unaligned atomic load");
  4129. auto Flags = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout(), AC, LibInfo);
  4130. MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
  4131. MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
  4132. I.getAlign(), AAMDNodes(), nullptr, SSID, Order);
  4133. InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG);
  4134. SDValue Ptr = getValue(I.getPointerOperand());
  4135. if (TLI.lowerAtomicLoadAsLoadSDNode(I)) {
  4136. // TODO: Once this is better exercised by tests, it should be merged with
  4137. // the normal path for loads to prevent future divergence.
  4138. SDValue L = DAG.getLoad(MemVT, dl, InChain, Ptr, MMO);
  4139. if (MemVT != VT)
  4140. L = DAG.getPtrExtOrTrunc(L, dl, VT);
  4141. setValue(&I, L);
  4142. SDValue OutChain = L.getValue(1);
  4143. if (!I.isUnordered())
  4144. DAG.setRoot(OutChain);
  4145. else
  4146. PendingLoads.push_back(OutChain);
  4147. return;
  4148. }
  4149. SDValue L = DAG.getAtomic(ISD::ATOMIC_LOAD, dl, MemVT, MemVT, InChain,
  4150. Ptr, MMO);
  4151. SDValue OutChain = L.getValue(1);
  4152. if (MemVT != VT)
  4153. L = DAG.getPtrExtOrTrunc(L, dl, VT);
  4154. setValue(&I, L);
  4155. DAG.setRoot(OutChain);
  4156. }
  4157. void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) {
  4158. SDLoc dl = getCurSDLoc();
  4159. AtomicOrdering Ordering = I.getOrdering();
  4160. SyncScope::ID SSID = I.getSyncScopeID();
  4161. SDValue InChain = getRoot();
  4162. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  4163. EVT MemVT =
  4164. TLI.getMemValueType(DAG.getDataLayout(), I.getValueOperand()->getType());
  4165. if (!TLI.supportsUnalignedAtomics() &&
  4166. I.getAlign().value() < MemVT.getSizeInBits() / 8)
  4167. report_fatal_error("Cannot generate unaligned atomic store");
  4168. auto Flags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout());
  4169. MachineFunction &MF = DAG.getMachineFunction();
  4170. MachineMemOperand *MMO = MF.getMachineMemOperand(
  4171. MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
  4172. I.getAlign(), AAMDNodes(), nullptr, SSID, Ordering);
  4173. SDValue Val = getValue(I.getValueOperand());
  4174. if (Val.getValueType() != MemVT)
  4175. Val = DAG.getPtrExtOrTrunc(Val, dl, MemVT);
  4176. SDValue Ptr = getValue(I.getPointerOperand());
  4177. if (TLI.lowerAtomicStoreAsStoreSDNode(I)) {
  4178. // TODO: Once this is better exercised by tests, it should be merged with
  4179. // the normal path for stores to prevent future divergence.
  4180. SDValue S = DAG.getStore(InChain, dl, Val, Ptr, MMO);
  4181. setValue(&I, S);
  4182. DAG.setRoot(S);
  4183. return;
  4184. }
  4185. SDValue OutChain = DAG.getAtomic(ISD::ATOMIC_STORE, dl, MemVT, InChain,
  4186. Ptr, Val, MMO);
  4187. setValue(&I, OutChain);
  4188. DAG.setRoot(OutChain);
  4189. }
  4190. /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
  4191. /// node.
  4192. void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I,
  4193. unsigned Intrinsic) {
  4194. // Ignore the callsite's attributes. A specific call site may be marked with
  4195. // readnone, but the lowering code will expect the chain based on the
  4196. // definition.
  4197. const Function *F = I.getCalledFunction();
  4198. bool HasChain = !F->doesNotAccessMemory();
  4199. bool OnlyLoad = HasChain && F->onlyReadsMemory();
  4200. // Build the operand list.
  4201. SmallVector<SDValue, 8> Ops;
  4202. if (HasChain) { // If this intrinsic has side-effects, chainify it.
  4203. if (OnlyLoad) {
  4204. // We don't need to serialize loads against other loads.
  4205. Ops.push_back(DAG.getRoot());
  4206. } else {
  4207. Ops.push_back(getRoot());
  4208. }
  4209. }
  4210. // Info is set by getTgtMemIntrinsic
  4211. TargetLowering::IntrinsicInfo Info;
  4212. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  4213. bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I,
  4214. DAG.getMachineFunction(),
  4215. Intrinsic);
  4216. // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
  4217. if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID ||
  4218. Info.opc == ISD::INTRINSIC_W_CHAIN)
  4219. Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(),
  4220. TLI.getPointerTy(DAG.getDataLayout())));
  4221. // Add all operands of the call to the operand list.
  4222. for (unsigned i = 0, e = I.arg_size(); i != e; ++i) {
  4223. const Value *Arg = I.getArgOperand(i);
  4224. if (!I.paramHasAttr(i, Attribute::ImmArg)) {
  4225. Ops.push_back(getValue(Arg));
  4226. continue;
  4227. }
  4228. // Use TargetConstant instead of a regular constant for immarg.
  4229. EVT VT = TLI.getValueType(DAG.getDataLayout(), Arg->getType(), true);
  4230. if (const ConstantInt *CI = dyn_cast<ConstantInt>(Arg)) {
  4231. assert(CI->getBitWidth() <= 64 &&
  4232. "large intrinsic immediates not handled");
  4233. Ops.push_back(DAG.getTargetConstant(*CI, SDLoc(), VT));
  4234. } else {
  4235. Ops.push_back(
  4236. DAG.getTargetConstantFP(*cast<ConstantFP>(Arg), SDLoc(), VT));
  4237. }
  4238. }
  4239. SmallVector<EVT, 4> ValueVTs;
  4240. ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs);
  4241. if (HasChain)
  4242. ValueVTs.push_back(MVT::Other);
  4243. SDVTList VTs = DAG.getVTList(ValueVTs);
  4244. // Propagate fast-math-flags from IR to node(s).
  4245. SDNodeFlags Flags;
  4246. if (auto *FPMO = dyn_cast<FPMathOperator>(&I))
  4247. Flags.copyFMF(*FPMO);
  4248. SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
  4249. // Create the node.
  4250. SDValue Result;
  4251. // In some cases, custom collection of operands from CallInst I may be needed.
  4252. TLI.CollectTargetIntrinsicOperands(I, Ops, DAG);
  4253. if (IsTgtIntrinsic) {
  4254. // This is target intrinsic that touches memory
  4255. //
  4256. // TODO: We currently just fallback to address space 0 if getTgtMemIntrinsic
  4257. // didn't yield anything useful.
  4258. MachinePointerInfo MPI;
  4259. if (Info.ptrVal)
  4260. MPI = MachinePointerInfo(Info.ptrVal, Info.offset);
  4261. else if (Info.fallbackAddressSpace)
  4262. MPI = MachinePointerInfo(*Info.fallbackAddressSpace);
  4263. Result = DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(), VTs, Ops,
  4264. Info.memVT, MPI, Info.align, Info.flags,
  4265. Info.size, I.getAAMetadata());
  4266. } else if (!HasChain) {
  4267. Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops);
  4268. } else if (!I.getType()->isVoidTy()) {
  4269. Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops);
  4270. } else {
  4271. Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops);
  4272. }
  4273. if (HasChain) {
  4274. SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
  4275. if (OnlyLoad)
  4276. PendingLoads.push_back(Chain);
  4277. else
  4278. DAG.setRoot(Chain);
  4279. }
  4280. if (!I.getType()->isVoidTy()) {
  4281. if (!isa<VectorType>(I.getType()))
  4282. Result = lowerRangeToAssertZExt(DAG, I, Result);
  4283. MaybeAlign Alignment = I.getRetAlign();
  4284. if (!Alignment)
  4285. Alignment = F->getAttributes().getRetAlignment();
  4286. // Insert `assertalign` node if there's an alignment.
  4287. if (InsertAssertAlign && Alignment) {
  4288. Result =
  4289. DAG.getAssertAlign(getCurSDLoc(), Result, Alignment.valueOrOne());
  4290. }
  4291. setValue(&I, Result);
  4292. }
  4293. }
  4294. /// GetSignificand - Get the significand and build it into a floating-point
  4295. /// number with exponent of 1:
  4296. ///
  4297. /// Op = (Op & 0x007fffff) | 0x3f800000;
  4298. ///
  4299. /// where Op is the hexadecimal representation of floating point value.
  4300. static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) {
  4301. SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
  4302. DAG.getConstant(0x007fffff, dl, MVT::i32));
  4303. SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
  4304. DAG.getConstant(0x3f800000, dl, MVT::i32));
  4305. return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2);
  4306. }
  4307. /// GetExponent - Get the exponent:
  4308. ///
  4309. /// (float)(int)(((Op & 0x7f800000) >> 23) - 127);
  4310. ///
  4311. /// where Op is the hexadecimal representation of floating point value.
  4312. static SDValue GetExponent(SelectionDAG &DAG, SDValue Op,
  4313. const TargetLowering &TLI, const SDLoc &dl) {
  4314. SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
  4315. DAG.getConstant(0x7f800000, dl, MVT::i32));
  4316. SDValue t1 = DAG.getNode(
  4317. ISD::SRL, dl, MVT::i32, t0,
  4318. DAG.getConstant(23, dl,
  4319. TLI.getShiftAmountTy(MVT::i32, DAG.getDataLayout())));
  4320. SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
  4321. DAG.getConstant(127, dl, MVT::i32));
  4322. return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
  4323. }
  4324. /// getF32Constant - Get 32-bit floating point constant.
  4325. static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt,
  4326. const SDLoc &dl) {
  4327. return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl,
  4328. MVT::f32);
  4329. }
  4330. static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl,
  4331. SelectionDAG &DAG) {
  4332. // TODO: What fast-math-flags should be set on the floating-point nodes?
  4333. // IntegerPartOfX = ((int32_t)(t0);
  4334. SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
  4335. // FractionalPartOfX = t0 - (float)IntegerPartOfX;
  4336. SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
  4337. SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
  4338. // IntegerPartOfX <<= 23;
  4339. IntegerPartOfX =
  4340. DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
  4341. DAG.getConstant(23, dl,
  4342. DAG.getTargetLoweringInfo().getShiftAmountTy(
  4343. MVT::i32, DAG.getDataLayout())));
  4344. SDValue TwoToFractionalPartOfX;
  4345. if (LimitFloatPrecision <= 6) {
  4346. // For floating-point precision of 6:
  4347. //
  4348. // TwoToFractionalPartOfX =
  4349. // 0.997535578f +
  4350. // (0.735607626f + 0.252464424f * x) * x;
  4351. //
  4352. // error 0.0144103317, which is 6 bits
  4353. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  4354. getF32Constant(DAG, 0x3e814304, dl));
  4355. SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
  4356. getF32Constant(DAG, 0x3f3c50c8, dl));
  4357. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  4358. TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  4359. getF32Constant(DAG, 0x3f7f5e7e, dl));
  4360. } else if (LimitFloatPrecision <= 12) {
  4361. // For floating-point precision of 12:
  4362. //
  4363. // TwoToFractionalPartOfX =
  4364. // 0.999892986f +
  4365. // (0.696457318f +
  4366. // (0.224338339f + 0.792043434e-1f * x) * x) * x;
  4367. //
  4368. // error 0.000107046256, which is 13 to 14 bits
  4369. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  4370. getF32Constant(DAG, 0x3da235e3, dl));
  4371. SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
  4372. getF32Constant(DAG, 0x3e65b8f3, dl));
  4373. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  4374. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  4375. getF32Constant(DAG, 0x3f324b07, dl));
  4376. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  4377. TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
  4378. getF32Constant(DAG, 0x3f7ff8fd, dl));
  4379. } else { // LimitFloatPrecision <= 18
  4380. // For floating-point precision of 18:
  4381. //
  4382. // TwoToFractionalPartOfX =
  4383. // 0.999999982f +
  4384. // (0.693148872f +
  4385. // (0.240227044f +
  4386. // (0.554906021e-1f +
  4387. // (0.961591928e-2f +
  4388. // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
  4389. // error 2.47208000*10^(-7), which is better than 18 bits
  4390. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  4391. getF32Constant(DAG, 0x3924b03e, dl));
  4392. SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
  4393. getF32Constant(DAG, 0x3ab24b87, dl));
  4394. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  4395. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  4396. getF32Constant(DAG, 0x3c1d8c17, dl));
  4397. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  4398. SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
  4399. getF32Constant(DAG, 0x3d634a1d, dl));
  4400. SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
  4401. SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
  4402. getF32Constant(DAG, 0x3e75fe14, dl));
  4403. SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
  4404. SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
  4405. getF32Constant(DAG, 0x3f317234, dl));
  4406. SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
  4407. TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
  4408. getF32Constant(DAG, 0x3f800000, dl));
  4409. }
  4410. // Add the exponent into the result in integer domain.
  4411. SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX);
  4412. return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
  4413. DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX));
  4414. }
  4415. /// expandExp - Lower an exp intrinsic. Handles the special sequences for
  4416. /// limited-precision mode.
  4417. static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
  4418. const TargetLowering &TLI, SDNodeFlags Flags) {
  4419. if (Op.getValueType() == MVT::f32 &&
  4420. LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
  4421. // Put the exponent in the right bit position for later addition to the
  4422. // final result:
  4423. //
  4424. // t0 = Op * log2(e)
  4425. // TODO: What fast-math-flags should be set here?
  4426. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
  4427. DAG.getConstantFP(numbers::log2ef, dl, MVT::f32));
  4428. return getLimitedPrecisionExp2(t0, dl, DAG);
  4429. }
  4430. // No special expansion.
  4431. return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op, Flags);
  4432. }
  4433. /// expandLog - Lower a log intrinsic. Handles the special sequences for
  4434. /// limited-precision mode.
  4435. static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
  4436. const TargetLowering &TLI, SDNodeFlags Flags) {
  4437. // TODO: What fast-math-flags should be set on the floating-point nodes?
  4438. if (Op.getValueType() == MVT::f32 &&
  4439. LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
  4440. SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
  4441. // Scale the exponent by log(2).
  4442. SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
  4443. SDValue LogOfExponent =
  4444. DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
  4445. DAG.getConstantFP(numbers::ln2f, dl, MVT::f32));
  4446. // Get the significand and build it into a floating-point number with
  4447. // exponent of 1.
  4448. SDValue X = GetSignificand(DAG, Op1, dl);
  4449. SDValue LogOfMantissa;
  4450. if (LimitFloatPrecision <= 6) {
  4451. // For floating-point precision of 6:
  4452. //
  4453. // LogofMantissa =
  4454. // -1.1609546f +
  4455. // (1.4034025f - 0.23903021f * x) * x;
  4456. //
  4457. // error 0.0034276066, which is better than 8 bits
  4458. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  4459. getF32Constant(DAG, 0xbe74c456, dl));
  4460. SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
  4461. getF32Constant(DAG, 0x3fb3a2b1, dl));
  4462. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  4463. LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
  4464. getF32Constant(DAG, 0x3f949a29, dl));
  4465. } else if (LimitFloatPrecision <= 12) {
  4466. // For floating-point precision of 12:
  4467. //
  4468. // LogOfMantissa =
  4469. // -1.7417939f +
  4470. // (2.8212026f +
  4471. // (-1.4699568f +
  4472. // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
  4473. //
  4474. // error 0.000061011436, which is 14 bits
  4475. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  4476. getF32Constant(DAG, 0xbd67b6d6, dl));
  4477. SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
  4478. getF32Constant(DAG, 0x3ee4f4b8, dl));
  4479. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  4480. SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
  4481. getF32Constant(DAG, 0x3fbc278b, dl));
  4482. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  4483. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  4484. getF32Constant(DAG, 0x40348e95, dl));
  4485. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  4486. LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
  4487. getF32Constant(DAG, 0x3fdef31a, dl));
  4488. } else { // LimitFloatPrecision <= 18
  4489. // For floating-point precision of 18:
  4490. //
  4491. // LogOfMantissa =
  4492. // -2.1072184f +
  4493. // (4.2372794f +
  4494. // (-3.7029485f +
  4495. // (2.2781945f +
  4496. // (-0.87823314f +
  4497. // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
  4498. //
  4499. // error 0.0000023660568, which is better than 18 bits
  4500. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  4501. getF32Constant(DAG, 0xbc91e5ac, dl));
  4502. SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
  4503. getF32Constant(DAG, 0x3e4350aa, dl));
  4504. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  4505. SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
  4506. getF32Constant(DAG, 0x3f60d3e3, dl));
  4507. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  4508. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  4509. getF32Constant(DAG, 0x4011cdf0, dl));
  4510. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  4511. SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
  4512. getF32Constant(DAG, 0x406cfd1c, dl));
  4513. SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
  4514. SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
  4515. getF32Constant(DAG, 0x408797cb, dl));
  4516. SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
  4517. LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
  4518. getF32Constant(DAG, 0x4006dcab, dl));
  4519. }
  4520. return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa);
  4521. }
  4522. // No special expansion.
  4523. return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op, Flags);
  4524. }
  4525. /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for
  4526. /// limited-precision mode.
  4527. static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
  4528. const TargetLowering &TLI, SDNodeFlags Flags) {
  4529. // TODO: What fast-math-flags should be set on the floating-point nodes?
  4530. if (Op.getValueType() == MVT::f32 &&
  4531. LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
  4532. SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
  4533. // Get the exponent.
  4534. SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
  4535. // Get the significand and build it into a floating-point number with
  4536. // exponent of 1.
  4537. SDValue X = GetSignificand(DAG, Op1, dl);
  4538. // Different possible minimax approximations of significand in
  4539. // floating-point for various degrees of accuracy over [1,2].
  4540. SDValue Log2ofMantissa;
  4541. if (LimitFloatPrecision <= 6) {
  4542. // For floating-point precision of 6:
  4543. //
  4544. // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
  4545. //
  4546. // error 0.0049451742, which is more than 7 bits
  4547. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  4548. getF32Constant(DAG, 0xbeb08fe0, dl));
  4549. SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
  4550. getF32Constant(DAG, 0x40019463, dl));
  4551. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  4552. Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
  4553. getF32Constant(DAG, 0x3fd6633d, dl));
  4554. } else if (LimitFloatPrecision <= 12) {
  4555. // For floating-point precision of 12:
  4556. //
  4557. // Log2ofMantissa =
  4558. // -2.51285454f +
  4559. // (4.07009056f +
  4560. // (-2.12067489f +
  4561. // (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
  4562. //
  4563. // error 0.0000876136000, which is better than 13 bits
  4564. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  4565. getF32Constant(DAG, 0xbda7262e, dl));
  4566. SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
  4567. getF32Constant(DAG, 0x3f25280b, dl));
  4568. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  4569. SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
  4570. getF32Constant(DAG, 0x4007b923, dl));
  4571. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  4572. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  4573. getF32Constant(DAG, 0x40823e2f, dl));
  4574. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  4575. Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
  4576. getF32Constant(DAG, 0x4020d29c, dl));
  4577. } else { // LimitFloatPrecision <= 18
  4578. // For floating-point precision of 18:
  4579. //
  4580. // Log2ofMantissa =
  4581. // -3.0400495f +
  4582. // (6.1129976f +
  4583. // (-5.3420409f +
  4584. // (3.2865683f +
  4585. // (-1.2669343f +
  4586. // (0.27515199f -
  4587. // 0.25691327e-1f * x) * x) * x) * x) * x) * x;
  4588. //
  4589. // error 0.0000018516, which is better than 18 bits
  4590. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  4591. getF32Constant(DAG, 0xbcd2769e, dl));
  4592. SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
  4593. getF32Constant(DAG, 0x3e8ce0b9, dl));
  4594. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  4595. SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
  4596. getF32Constant(DAG, 0x3fa22ae7, dl));
  4597. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  4598. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  4599. getF32Constant(DAG, 0x40525723, dl));
  4600. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  4601. SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
  4602. getF32Constant(DAG, 0x40aaf200, dl));
  4603. SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
  4604. SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
  4605. getF32Constant(DAG, 0x40c39dad, dl));
  4606. SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
  4607. Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
  4608. getF32Constant(DAG, 0x4042902c, dl));
  4609. }
  4610. return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa);
  4611. }
  4612. // No special expansion.
  4613. return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op, Flags);
  4614. }
  4615. /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for
  4616. /// limited-precision mode.
  4617. static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
  4618. const TargetLowering &TLI, SDNodeFlags Flags) {
  4619. // TODO: What fast-math-flags should be set on the floating-point nodes?
  4620. if (Op.getValueType() == MVT::f32 &&
  4621. LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
  4622. SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
  4623. // Scale the exponent by log10(2) [0.30102999f].
  4624. SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
  4625. SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
  4626. getF32Constant(DAG, 0x3e9a209a, dl));
  4627. // Get the significand and build it into a floating-point number with
  4628. // exponent of 1.
  4629. SDValue X = GetSignificand(DAG, Op1, dl);
  4630. SDValue Log10ofMantissa;
  4631. if (LimitFloatPrecision <= 6) {
  4632. // For floating-point precision of 6:
  4633. //
  4634. // Log10ofMantissa =
  4635. // -0.50419619f +
  4636. // (0.60948995f - 0.10380950f * x) * x;
  4637. //
  4638. // error 0.0014886165, which is 6 bits
  4639. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  4640. getF32Constant(DAG, 0xbdd49a13, dl));
  4641. SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
  4642. getF32Constant(DAG, 0x3f1c0789, dl));
  4643. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  4644. Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
  4645. getF32Constant(DAG, 0x3f011300, dl));
  4646. } else if (LimitFloatPrecision <= 12) {
  4647. // For floating-point precision of 12:
  4648. //
  4649. // Log10ofMantissa =
  4650. // -0.64831180f +
  4651. // (0.91751397f +
  4652. // (-0.31664806f + 0.47637168e-1f * x) * x) * x;
  4653. //
  4654. // error 0.00019228036, which is better than 12 bits
  4655. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  4656. getF32Constant(DAG, 0x3d431f31, dl));
  4657. SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
  4658. getF32Constant(DAG, 0x3ea21fb2, dl));
  4659. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  4660. SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
  4661. getF32Constant(DAG, 0x3f6ae232, dl));
  4662. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  4663. Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
  4664. getF32Constant(DAG, 0x3f25f7c3, dl));
  4665. } else { // LimitFloatPrecision <= 18
  4666. // For floating-point precision of 18:
  4667. //
  4668. // Log10ofMantissa =
  4669. // -0.84299375f +
  4670. // (1.5327582f +
  4671. // (-1.0688956f +
  4672. // (0.49102474f +
  4673. // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
  4674. //
  4675. // error 0.0000037995730, which is better than 18 bits
  4676. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  4677. getF32Constant(DAG, 0x3c5d51ce, dl));
  4678. SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
  4679. getF32Constant(DAG, 0x3e00685a, dl));
  4680. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  4681. SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
  4682. getF32Constant(DAG, 0x3efb6798, dl));
  4683. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  4684. SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
  4685. getF32Constant(DAG, 0x3f88d192, dl));
  4686. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  4687. SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
  4688. getF32Constant(DAG, 0x3fc4316c, dl));
  4689. SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
  4690. Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
  4691. getF32Constant(DAG, 0x3f57ce70, dl));
  4692. }
  4693. return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa);
  4694. }
  4695. // No special expansion.
  4696. return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op, Flags);
  4697. }
  4698. /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for
  4699. /// limited-precision mode.
  4700. static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
  4701. const TargetLowering &TLI, SDNodeFlags Flags) {
  4702. if (Op.getValueType() == MVT::f32 &&
  4703. LimitFloatPrecision > 0 && LimitFloatPrecision <= 18)
  4704. return getLimitedPrecisionExp2(Op, dl, DAG);
  4705. // No special expansion.
  4706. return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op, Flags);
  4707. }
  4708. /// visitPow - Lower a pow intrinsic. Handles the special sequences for
  4709. /// limited-precision mode with x == 10.0f.
  4710. static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS,
  4711. SelectionDAG &DAG, const TargetLowering &TLI,
  4712. SDNodeFlags Flags) {
  4713. bool IsExp10 = false;
  4714. if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 &&
  4715. LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
  4716. if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) {
  4717. APFloat Ten(10.0f);
  4718. IsExp10 = LHSC->isExactlyValue(Ten);
  4719. }
  4720. }
  4721. // TODO: What fast-math-flags should be set on the FMUL node?
  4722. if (IsExp10) {
  4723. // Put the exponent in the right bit position for later addition to the
  4724. // final result:
  4725. //
  4726. // #define LOG2OF10 3.3219281f
  4727. // t0 = Op * LOG2OF10;
  4728. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS,
  4729. getF32Constant(DAG, 0x40549a78, dl));
  4730. return getLimitedPrecisionExp2(t0, dl, DAG);
  4731. }
  4732. // No special expansion.
  4733. return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS, Flags);
  4734. }
  4735. /// ExpandPowI - Expand a llvm.powi intrinsic.
  4736. static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS,
  4737. SelectionDAG &DAG) {
  4738. // If RHS is a constant, we can expand this out to a multiplication tree if
  4739. // it's beneficial on the target, otherwise we end up lowering to a call to
  4740. // __powidf2 (for example).
  4741. if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
  4742. unsigned Val = RHSC->getSExtValue();
  4743. // powi(x, 0) -> 1.0
  4744. if (Val == 0)
  4745. return DAG.getConstantFP(1.0, DL, LHS.getValueType());
  4746. if (DAG.getTargetLoweringInfo().isBeneficialToExpandPowI(
  4747. Val, DAG.shouldOptForSize())) {
  4748. // Get the exponent as a positive value.
  4749. if ((int)Val < 0)
  4750. Val = -Val;
  4751. // We use the simple binary decomposition method to generate the multiply
  4752. // sequence. There are more optimal ways to do this (for example,
  4753. // powi(x,15) generates one more multiply than it should), but this has
  4754. // the benefit of being both really simple and much better than a libcall.
  4755. SDValue Res; // Logically starts equal to 1.0
  4756. SDValue CurSquare = LHS;
  4757. // TODO: Intrinsics should have fast-math-flags that propagate to these
  4758. // nodes.
  4759. while (Val) {
  4760. if (Val & 1) {
  4761. if (Res.getNode())
  4762. Res =
  4763. DAG.getNode(ISD::FMUL, DL, Res.getValueType(), Res, CurSquare);
  4764. else
  4765. Res = CurSquare; // 1.0*CurSquare.
  4766. }
  4767. CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(),
  4768. CurSquare, CurSquare);
  4769. Val >>= 1;
  4770. }
  4771. // If the original was negative, invert the result, producing 1/(x*x*x).
  4772. if (RHSC->getSExtValue() < 0)
  4773. Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(),
  4774. DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res);
  4775. return Res;
  4776. }
  4777. }
  4778. // Otherwise, expand to a libcall.
  4779. return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS);
  4780. }
  4781. static SDValue expandDivFix(unsigned Opcode, const SDLoc &DL,
  4782. SDValue LHS, SDValue RHS, SDValue Scale,
  4783. SelectionDAG &DAG, const TargetLowering &TLI) {
  4784. EVT VT = LHS.getValueType();
  4785. bool Signed = Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT;
  4786. bool Saturating = Opcode == ISD::SDIVFIXSAT || Opcode == ISD::UDIVFIXSAT;
  4787. LLVMContext &Ctx = *DAG.getContext();
  4788. // If the type is legal but the operation isn't, this node might survive all
  4789. // the way to operation legalization. If we end up there and we do not have
  4790. // the ability to widen the type (if VT*2 is not legal), we cannot expand the
  4791. // node.
  4792. // Coax the legalizer into expanding the node during type legalization instead
  4793. // by bumping the size by one bit. This will force it to Promote, enabling the
  4794. // early expansion and avoiding the need to expand later.
  4795. // We don't have to do this if Scale is 0; that can always be expanded, unless
  4796. // it's a saturating signed operation. Those can experience true integer
  4797. // division overflow, a case which we must avoid.
  4798. // FIXME: We wouldn't have to do this (or any of the early
  4799. // expansion/promotion) if it was possible to expand a libcall of an
  4800. // illegal type during operation legalization. But it's not, so things
  4801. // get a bit hacky.
  4802. unsigned ScaleInt = cast<ConstantSDNode>(Scale)->getZExtValue();
  4803. if ((ScaleInt > 0 || (Saturating && Signed)) &&
  4804. (TLI.isTypeLegal(VT) ||
  4805. (VT.isVector() && TLI.isTypeLegal(VT.getVectorElementType())))) {
  4806. TargetLowering::LegalizeAction Action = TLI.getFixedPointOperationAction(
  4807. Opcode, VT, ScaleInt);
  4808. if (Action != TargetLowering::Legal && Action != TargetLowering::Custom) {
  4809. EVT PromVT;
  4810. if (VT.isScalarInteger())
  4811. PromVT = EVT::getIntegerVT(Ctx, VT.getSizeInBits() + 1);
  4812. else if (VT.isVector()) {
  4813. PromVT = VT.getVectorElementType();
  4814. PromVT = EVT::getIntegerVT(Ctx, PromVT.getSizeInBits() + 1);
  4815. PromVT = EVT::getVectorVT(Ctx, PromVT, VT.getVectorElementCount());
  4816. } else
  4817. llvm_unreachable("Wrong VT for DIVFIX?");
  4818. if (Signed) {
  4819. LHS = DAG.getSExtOrTrunc(LHS, DL, PromVT);
  4820. RHS = DAG.getSExtOrTrunc(RHS, DL, PromVT);
  4821. } else {
  4822. LHS = DAG.getZExtOrTrunc(LHS, DL, PromVT);
  4823. RHS = DAG.getZExtOrTrunc(RHS, DL, PromVT);
  4824. }
  4825. EVT ShiftTy = TLI.getShiftAmountTy(PromVT, DAG.getDataLayout());
  4826. // For saturating operations, we need to shift up the LHS to get the
  4827. // proper saturation width, and then shift down again afterwards.
  4828. if (Saturating)
  4829. LHS = DAG.getNode(ISD::SHL, DL, PromVT, LHS,
  4830. DAG.getConstant(1, DL, ShiftTy));
  4831. SDValue Res = DAG.getNode(Opcode, DL, PromVT, LHS, RHS, Scale);
  4832. if (Saturating)
  4833. Res = DAG.getNode(Signed ? ISD::SRA : ISD::SRL, DL, PromVT, Res,
  4834. DAG.getConstant(1, DL, ShiftTy));
  4835. return DAG.getZExtOrTrunc(Res, DL, VT);
  4836. }
  4837. }
  4838. return DAG.getNode(Opcode, DL, VT, LHS, RHS, Scale);
  4839. }
  4840. // getUnderlyingArgRegs - Find underlying registers used for a truncated,
  4841. // bitcasted, or split argument. Returns a list of <Register, size in bits>
  4842. static void
  4843. getUnderlyingArgRegs(SmallVectorImpl<std::pair<unsigned, TypeSize>> &Regs,
  4844. const SDValue &N) {
  4845. switch (N.getOpcode()) {
  4846. case ISD::CopyFromReg: {
  4847. SDValue Op = N.getOperand(1);
  4848. Regs.emplace_back(cast<RegisterSDNode>(Op)->getReg(),
  4849. Op.getValueType().getSizeInBits());
  4850. return;
  4851. }
  4852. case ISD::BITCAST:
  4853. case ISD::AssertZext:
  4854. case ISD::AssertSext:
  4855. case ISD::TRUNCATE:
  4856. getUnderlyingArgRegs(Regs, N.getOperand(0));
  4857. return;
  4858. case ISD::BUILD_PAIR:
  4859. case ISD::BUILD_VECTOR:
  4860. case ISD::CONCAT_VECTORS:
  4861. for (SDValue Op : N->op_values())
  4862. getUnderlyingArgRegs(Regs, Op);
  4863. return;
  4864. default:
  4865. return;
  4866. }
  4867. }
  4868. /// If the DbgValueInst is a dbg_value of a function argument, create the
  4869. /// corresponding DBG_VALUE machine instruction for it now. At the end of
  4870. /// instruction selection, they will be inserted to the entry BB.
  4871. /// We don't currently support this for variadic dbg_values, as they shouldn't
  4872. /// appear for function arguments or in the prologue.
  4873. bool SelectionDAGBuilder::EmitFuncArgumentDbgValue(
  4874. const Value *V, DILocalVariable *Variable, DIExpression *Expr,
  4875. DILocation *DL, FuncArgumentDbgValueKind Kind, const SDValue &N) {
  4876. const Argument *Arg = dyn_cast<Argument>(V);
  4877. if (!Arg)
  4878. return false;
  4879. MachineFunction &MF = DAG.getMachineFunction();
  4880. const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
  4881. // Helper to create DBG_INSTR_REFs or DBG_VALUEs, depending on what kind
  4882. // we've been asked to pursue.
  4883. auto MakeVRegDbgValue = [&](Register Reg, DIExpression *FragExpr,
  4884. bool Indirect) {
  4885. if (Reg.isVirtual() && MF.useDebugInstrRef()) {
  4886. // For VRegs, in instruction referencing mode, create a DBG_INSTR_REF
  4887. // pointing at the VReg, which will be patched up later.
  4888. auto &Inst = TII->get(TargetOpcode::DBG_INSTR_REF);
  4889. SmallVector<MachineOperand, 1> MOs({MachineOperand::CreateReg(
  4890. /* Reg */ Reg, /* isDef */ false, /* isImp */ false,
  4891. /* isKill */ false, /* isDead */ false,
  4892. /* isUndef */ false, /* isEarlyClobber */ false,
  4893. /* SubReg */ 0, /* isDebug */ true)});
  4894. auto *NewDIExpr = FragExpr;
  4895. // We don't have an "Indirect" field in DBG_INSTR_REF, fold that into
  4896. // the DIExpression.
  4897. if (Indirect)
  4898. NewDIExpr = DIExpression::prepend(FragExpr, DIExpression::DerefBefore);
  4899. SmallVector<uint64_t, 2> Ops({dwarf::DW_OP_LLVM_arg, 0});
  4900. NewDIExpr = DIExpression::prependOpcodes(NewDIExpr, Ops);
  4901. return BuildMI(MF, DL, Inst, false, MOs, Variable, NewDIExpr);
  4902. } else {
  4903. // Create a completely standard DBG_VALUE.
  4904. auto &Inst = TII->get(TargetOpcode::DBG_VALUE);
  4905. return BuildMI(MF, DL, Inst, Indirect, Reg, Variable, FragExpr);
  4906. }
  4907. };
  4908. if (Kind == FuncArgumentDbgValueKind::Value) {
  4909. // ArgDbgValues are hoisted to the beginning of the entry block. So we
  4910. // should only emit as ArgDbgValue if the dbg.value intrinsic is found in
  4911. // the entry block.
  4912. bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front();
  4913. if (!IsInEntryBlock)
  4914. return false;
  4915. // ArgDbgValues are hoisted to the beginning of the entry block. So we
  4916. // should only emit as ArgDbgValue if the dbg.value intrinsic describes a
  4917. // variable that also is a param.
  4918. //
  4919. // Although, if we are at the top of the entry block already, we can still
  4920. // emit using ArgDbgValue. This might catch some situations when the
  4921. // dbg.value refers to an argument that isn't used in the entry block, so
  4922. // any CopyToReg node would be optimized out and the only way to express
  4923. // this DBG_VALUE is by using the physical reg (or FI) as done in this
  4924. // method. ArgDbgValues are hoisted to the beginning of the entry block. So
  4925. // we should only emit as ArgDbgValue if the Variable is an argument to the
  4926. // current function, and the dbg.value intrinsic is found in the entry
  4927. // block.
  4928. bool VariableIsFunctionInputArg = Variable->isParameter() &&
  4929. !DL->getInlinedAt();
  4930. bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder;
  4931. if (!IsInPrologue && !VariableIsFunctionInputArg)
  4932. return false;
  4933. // Here we assume that a function argument on IR level only can be used to
  4934. // describe one input parameter on source level. If we for example have
  4935. // source code like this
  4936. //
  4937. // struct A { long x, y; };
  4938. // void foo(struct A a, long b) {
  4939. // ...
  4940. // b = a.x;
  4941. // ...
  4942. // }
  4943. //
  4944. // and IR like this
  4945. //
  4946. // define void @foo(i32 %a1, i32 %a2, i32 %b) {
  4947. // entry:
  4948. // call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment
  4949. // call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment
  4950. // call void @llvm.dbg.value(metadata i32 %b, "b",
  4951. // ...
  4952. // call void @llvm.dbg.value(metadata i32 %a1, "b"
  4953. // ...
  4954. //
  4955. // then the last dbg.value is describing a parameter "b" using a value that
  4956. // is an argument. But since we already has used %a1 to describe a parameter
  4957. // we should not handle that last dbg.value here (that would result in an
  4958. // incorrect hoisting of the DBG_VALUE to the function entry).
  4959. // Notice that we allow one dbg.value per IR level argument, to accommodate
  4960. // for the situation with fragments above.
  4961. if (VariableIsFunctionInputArg) {
  4962. unsigned ArgNo = Arg->getArgNo();
  4963. if (ArgNo >= FuncInfo.DescribedArgs.size())
  4964. FuncInfo.DescribedArgs.resize(ArgNo + 1, false);
  4965. else if (!IsInPrologue && FuncInfo.DescribedArgs.test(ArgNo))
  4966. return false;
  4967. FuncInfo.DescribedArgs.set(ArgNo);
  4968. }
  4969. }
  4970. bool IsIndirect = false;
  4971. std::optional<MachineOperand> Op;
  4972. // Some arguments' frame index is recorded during argument lowering.
  4973. int FI = FuncInfo.getArgumentFrameIndex(Arg);
  4974. if (FI != std::numeric_limits<int>::max())
  4975. Op = MachineOperand::CreateFI(FI);
  4976. SmallVector<std::pair<unsigned, TypeSize>, 8> ArgRegsAndSizes;
  4977. if (!Op && N.getNode()) {
  4978. getUnderlyingArgRegs(ArgRegsAndSizes, N);
  4979. Register Reg;
  4980. if (ArgRegsAndSizes.size() == 1)
  4981. Reg = ArgRegsAndSizes.front().first;
  4982. if (Reg && Reg.isVirtual()) {
  4983. MachineRegisterInfo &RegInfo = MF.getRegInfo();
  4984. Register PR = RegInfo.getLiveInPhysReg(Reg);
  4985. if (PR)
  4986. Reg = PR;
  4987. }
  4988. if (Reg) {
  4989. Op = MachineOperand::CreateReg(Reg, false);
  4990. IsIndirect = Kind != FuncArgumentDbgValueKind::Value;
  4991. }
  4992. }
  4993. if (!Op && N.getNode()) {
  4994. // Check if frame index is available.
  4995. SDValue LCandidate = peekThroughBitcasts(N);
  4996. if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(LCandidate.getNode()))
  4997. if (FrameIndexSDNode *FINode =
  4998. dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
  4999. Op = MachineOperand::CreateFI(FINode->getIndex());
  5000. }
  5001. if (!Op) {
  5002. // Create a DBG_VALUE for each decomposed value in ArgRegs to cover Reg
  5003. auto splitMultiRegDbgValue = [&](ArrayRef<std::pair<unsigned, TypeSize>>
  5004. SplitRegs) {
  5005. unsigned Offset = 0;
  5006. for (const auto &RegAndSize : SplitRegs) {
  5007. // If the expression is already a fragment, the current register
  5008. // offset+size might extend beyond the fragment. In this case, only
  5009. // the register bits that are inside the fragment are relevant.
  5010. int RegFragmentSizeInBits = RegAndSize.second;
  5011. if (auto ExprFragmentInfo = Expr->getFragmentInfo()) {
  5012. uint64_t ExprFragmentSizeInBits = ExprFragmentInfo->SizeInBits;
  5013. // The register is entirely outside the expression fragment,
  5014. // so is irrelevant for debug info.
  5015. if (Offset >= ExprFragmentSizeInBits)
  5016. break;
  5017. // The register is partially outside the expression fragment, only
  5018. // the low bits within the fragment are relevant for debug info.
  5019. if (Offset + RegFragmentSizeInBits > ExprFragmentSizeInBits) {
  5020. RegFragmentSizeInBits = ExprFragmentSizeInBits - Offset;
  5021. }
  5022. }
  5023. auto FragmentExpr = DIExpression::createFragmentExpression(
  5024. Expr, Offset, RegFragmentSizeInBits);
  5025. Offset += RegAndSize.second;
  5026. // If a valid fragment expression cannot be created, the variable's
  5027. // correct value cannot be determined and so it is set as Undef.
  5028. if (!FragmentExpr) {
  5029. SDDbgValue *SDV = DAG.getConstantDbgValue(
  5030. Variable, Expr, UndefValue::get(V->getType()), DL, SDNodeOrder);
  5031. DAG.AddDbgValue(SDV, false);
  5032. continue;
  5033. }
  5034. MachineInstr *NewMI =
  5035. MakeVRegDbgValue(RegAndSize.first, *FragmentExpr,
  5036. Kind != FuncArgumentDbgValueKind::Value);
  5037. FuncInfo.ArgDbgValues.push_back(NewMI);
  5038. }
  5039. };
  5040. // Check if ValueMap has reg number.
  5041. DenseMap<const Value *, Register>::const_iterator
  5042. VMI = FuncInfo.ValueMap.find(V);
  5043. if (VMI != FuncInfo.ValueMap.end()) {
  5044. const auto &TLI = DAG.getTargetLoweringInfo();
  5045. RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second,
  5046. V->getType(), std::nullopt);
  5047. if (RFV.occupiesMultipleRegs()) {
  5048. splitMultiRegDbgValue(RFV.getRegsAndSizes());
  5049. return true;
  5050. }
  5051. Op = MachineOperand::CreateReg(VMI->second, false);
  5052. IsIndirect = Kind != FuncArgumentDbgValueKind::Value;
  5053. } else if (ArgRegsAndSizes.size() > 1) {
  5054. // This was split due to the calling convention, and no virtual register
  5055. // mapping exists for the value.
  5056. splitMultiRegDbgValue(ArgRegsAndSizes);
  5057. return true;
  5058. }
  5059. }
  5060. if (!Op)
  5061. return false;
  5062. assert(Variable->isValidLocationForIntrinsic(DL) &&
  5063. "Expected inlined-at fields to agree");
  5064. MachineInstr *NewMI = nullptr;
  5065. if (Op->isReg())
  5066. NewMI = MakeVRegDbgValue(Op->getReg(), Expr, IsIndirect);
  5067. else
  5068. NewMI = BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), true, *Op,
  5069. Variable, Expr);
  5070. // Otherwise, use ArgDbgValues.
  5071. FuncInfo.ArgDbgValues.push_back(NewMI);
  5072. return true;
  5073. }
  5074. /// Return the appropriate SDDbgValue based on N.
  5075. SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N,
  5076. DILocalVariable *Variable,
  5077. DIExpression *Expr,
  5078. const DebugLoc &dl,
  5079. unsigned DbgSDNodeOrder) {
  5080. if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) {
  5081. // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe
  5082. // stack slot locations.
  5083. //
  5084. // Consider "int x = 0; int *px = &x;". There are two kinds of interesting
  5085. // debug values here after optimization:
  5086. //
  5087. // dbg.value(i32* %px, !"int *px", !DIExpression()), and
  5088. // dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref))
  5089. //
  5090. // Both describe the direct values of their associated variables.
  5091. return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(),
  5092. /*IsIndirect*/ false, dl, DbgSDNodeOrder);
  5093. }
  5094. return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(),
  5095. /*IsIndirect*/ false, dl, DbgSDNodeOrder);
  5096. }
  5097. static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) {
  5098. switch (Intrinsic) {
  5099. case Intrinsic::smul_fix:
  5100. return ISD::SMULFIX;
  5101. case Intrinsic::umul_fix:
  5102. return ISD::UMULFIX;
  5103. case Intrinsic::smul_fix_sat:
  5104. return ISD::SMULFIXSAT;
  5105. case Intrinsic::umul_fix_sat:
  5106. return ISD::UMULFIXSAT;
  5107. case Intrinsic::sdiv_fix:
  5108. return ISD::SDIVFIX;
  5109. case Intrinsic::udiv_fix:
  5110. return ISD::UDIVFIX;
  5111. case Intrinsic::sdiv_fix_sat:
  5112. return ISD::SDIVFIXSAT;
  5113. case Intrinsic::udiv_fix_sat:
  5114. return ISD::UDIVFIXSAT;
  5115. default:
  5116. llvm_unreachable("Unhandled fixed point intrinsic");
  5117. }
  5118. }
  5119. void SelectionDAGBuilder::lowerCallToExternalSymbol(const CallInst &I,
  5120. const char *FunctionName) {
  5121. assert(FunctionName && "FunctionName must not be nullptr");
  5122. SDValue Callee = DAG.getExternalSymbol(
  5123. FunctionName,
  5124. DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()));
  5125. LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall());
  5126. }
  5127. /// Given a @llvm.call.preallocated.setup, return the corresponding
  5128. /// preallocated call.
  5129. static const CallBase *FindPreallocatedCall(const Value *PreallocatedSetup) {
  5130. assert(cast<CallBase>(PreallocatedSetup)
  5131. ->getCalledFunction()
  5132. ->getIntrinsicID() == Intrinsic::call_preallocated_setup &&
  5133. "expected call_preallocated_setup Value");
  5134. for (const auto *U : PreallocatedSetup->users()) {
  5135. auto *UseCall = cast<CallBase>(U);
  5136. const Function *Fn = UseCall->getCalledFunction();
  5137. if (!Fn || Fn->getIntrinsicID() != Intrinsic::call_preallocated_arg) {
  5138. return UseCall;
  5139. }
  5140. }
  5141. llvm_unreachable("expected corresponding call to preallocated setup/arg");
  5142. }
  5143. /// Lower the call to the specified intrinsic function.
  5144. void SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I,
  5145. unsigned Intrinsic) {
  5146. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  5147. SDLoc sdl = getCurSDLoc();
  5148. DebugLoc dl = getCurDebugLoc();
  5149. SDValue Res;
  5150. SDNodeFlags Flags;
  5151. if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
  5152. Flags.copyFMF(*FPOp);
  5153. switch (Intrinsic) {
  5154. default:
  5155. // By default, turn this into a target intrinsic node.
  5156. visitTargetIntrinsic(I, Intrinsic);
  5157. return;
  5158. case Intrinsic::vscale: {
  5159. match(&I, m_VScale(DAG.getDataLayout()));
  5160. EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  5161. setValue(&I, DAG.getVScale(sdl, VT, APInt(VT.getSizeInBits(), 1)));
  5162. return;
  5163. }
  5164. case Intrinsic::vastart: visitVAStart(I); return;
  5165. case Intrinsic::vaend: visitVAEnd(I); return;
  5166. case Intrinsic::vacopy: visitVACopy(I); return;
  5167. case Intrinsic::returnaddress:
  5168. setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl,
  5169. TLI.getValueType(DAG.getDataLayout(), I.getType()),
  5170. getValue(I.getArgOperand(0))));
  5171. return;
  5172. case Intrinsic::addressofreturnaddress:
  5173. setValue(&I,
  5174. DAG.getNode(ISD::ADDROFRETURNADDR, sdl,
  5175. TLI.getValueType(DAG.getDataLayout(), I.getType())));
  5176. return;
  5177. case Intrinsic::sponentry:
  5178. setValue(&I,
  5179. DAG.getNode(ISD::SPONENTRY, sdl,
  5180. TLI.getValueType(DAG.getDataLayout(), I.getType())));
  5181. return;
  5182. case Intrinsic::frameaddress:
  5183. setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl,
  5184. TLI.getFrameIndexTy(DAG.getDataLayout()),
  5185. getValue(I.getArgOperand(0))));
  5186. return;
  5187. case Intrinsic::read_volatile_register:
  5188. case Intrinsic::read_register: {
  5189. Value *Reg = I.getArgOperand(0);
  5190. SDValue Chain = getRoot();
  5191. SDValue RegName =
  5192. DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
  5193. EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  5194. Res = DAG.getNode(ISD::READ_REGISTER, sdl,
  5195. DAG.getVTList(VT, MVT::Other), Chain, RegName);
  5196. setValue(&I, Res);
  5197. DAG.setRoot(Res.getValue(1));
  5198. return;
  5199. }
  5200. case Intrinsic::write_register: {
  5201. Value *Reg = I.getArgOperand(0);
  5202. Value *RegValue = I.getArgOperand(1);
  5203. SDValue Chain = getRoot();
  5204. SDValue RegName =
  5205. DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
  5206. DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain,
  5207. RegName, getValue(RegValue)));
  5208. return;
  5209. }
  5210. case Intrinsic::memcpy: {
  5211. const auto &MCI = cast<MemCpyInst>(I);
  5212. SDValue Op1 = getValue(I.getArgOperand(0));
  5213. SDValue Op2 = getValue(I.getArgOperand(1));
  5214. SDValue Op3 = getValue(I.getArgOperand(2));
  5215. // @llvm.memcpy defines 0 and 1 to both mean no alignment.
  5216. Align DstAlign = MCI.getDestAlign().valueOrOne();
  5217. Align SrcAlign = MCI.getSourceAlign().valueOrOne();
  5218. Align Alignment = std::min(DstAlign, SrcAlign);
  5219. bool isVol = MCI.isVolatile();
  5220. bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
  5221. // FIXME: Support passing different dest/src alignments to the memcpy DAG
  5222. // node.
  5223. SDValue Root = isVol ? getRoot() : getMemoryRoot();
  5224. SDValue MC = DAG.getMemcpy(
  5225. Root, sdl, Op1, Op2, Op3, Alignment, isVol,
  5226. /* AlwaysInline */ false, isTC, MachinePointerInfo(I.getArgOperand(0)),
  5227. MachinePointerInfo(I.getArgOperand(1)), I.getAAMetadata(), AA);
  5228. updateDAGForMaybeTailCall(MC);
  5229. return;
  5230. }
  5231. case Intrinsic::memcpy_inline: {
  5232. const auto &MCI = cast<MemCpyInlineInst>(I);
  5233. SDValue Dst = getValue(I.getArgOperand(0));
  5234. SDValue Src = getValue(I.getArgOperand(1));
  5235. SDValue Size = getValue(I.getArgOperand(2));
  5236. assert(isa<ConstantSDNode>(Size) && "memcpy_inline needs constant size");
  5237. // @llvm.memcpy.inline defines 0 and 1 to both mean no alignment.
  5238. Align DstAlign = MCI.getDestAlign().valueOrOne();
  5239. Align SrcAlign = MCI.getSourceAlign().valueOrOne();
  5240. Align Alignment = std::min(DstAlign, SrcAlign);
  5241. bool isVol = MCI.isVolatile();
  5242. bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
  5243. // FIXME: Support passing different dest/src alignments to the memcpy DAG
  5244. // node.
  5245. SDValue MC = DAG.getMemcpy(
  5246. getRoot(), sdl, Dst, Src, Size, Alignment, isVol,
  5247. /* AlwaysInline */ true, isTC, MachinePointerInfo(I.getArgOperand(0)),
  5248. MachinePointerInfo(I.getArgOperand(1)), I.getAAMetadata(), AA);
  5249. updateDAGForMaybeTailCall(MC);
  5250. return;
  5251. }
  5252. case Intrinsic::memset: {
  5253. const auto &MSI = cast<MemSetInst>(I);
  5254. SDValue Op1 = getValue(I.getArgOperand(0));
  5255. SDValue Op2 = getValue(I.getArgOperand(1));
  5256. SDValue Op3 = getValue(I.getArgOperand(2));
  5257. // @llvm.memset defines 0 and 1 to both mean no alignment.
  5258. Align Alignment = MSI.getDestAlign().valueOrOne();
  5259. bool isVol = MSI.isVolatile();
  5260. bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
  5261. SDValue Root = isVol ? getRoot() : getMemoryRoot();
  5262. SDValue MS = DAG.getMemset(
  5263. Root, sdl, Op1, Op2, Op3, Alignment, isVol, /* AlwaysInline */ false,
  5264. isTC, MachinePointerInfo(I.getArgOperand(0)), I.getAAMetadata());
  5265. updateDAGForMaybeTailCall(MS);
  5266. return;
  5267. }
  5268. case Intrinsic::memset_inline: {
  5269. const auto &MSII = cast<MemSetInlineInst>(I);
  5270. SDValue Dst = getValue(I.getArgOperand(0));
  5271. SDValue Value = getValue(I.getArgOperand(1));
  5272. SDValue Size = getValue(I.getArgOperand(2));
  5273. assert(isa<ConstantSDNode>(Size) && "memset_inline needs constant size");
  5274. // @llvm.memset defines 0 and 1 to both mean no alignment.
  5275. Align DstAlign = MSII.getDestAlign().valueOrOne();
  5276. bool isVol = MSII.isVolatile();
  5277. bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
  5278. SDValue Root = isVol ? getRoot() : getMemoryRoot();
  5279. SDValue MC = DAG.getMemset(Root, sdl, Dst, Value, Size, DstAlign, isVol,
  5280. /* AlwaysInline */ true, isTC,
  5281. MachinePointerInfo(I.getArgOperand(0)),
  5282. I.getAAMetadata());
  5283. updateDAGForMaybeTailCall(MC);
  5284. return;
  5285. }
  5286. case Intrinsic::memmove: {
  5287. const auto &MMI = cast<MemMoveInst>(I);
  5288. SDValue Op1 = getValue(I.getArgOperand(0));
  5289. SDValue Op2 = getValue(I.getArgOperand(1));
  5290. SDValue Op3 = getValue(I.getArgOperand(2));
  5291. // @llvm.memmove defines 0 and 1 to both mean no alignment.
  5292. Align DstAlign = MMI.getDestAlign().valueOrOne();
  5293. Align SrcAlign = MMI.getSourceAlign().valueOrOne();
  5294. Align Alignment = std::min(DstAlign, SrcAlign);
  5295. bool isVol = MMI.isVolatile();
  5296. bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
  5297. // FIXME: Support passing different dest/src alignments to the memmove DAG
  5298. // node.
  5299. SDValue Root = isVol ? getRoot() : getMemoryRoot();
  5300. SDValue MM = DAG.getMemmove(Root, sdl, Op1, Op2, Op3, Alignment, isVol,
  5301. isTC, MachinePointerInfo(I.getArgOperand(0)),
  5302. MachinePointerInfo(I.getArgOperand(1)),
  5303. I.getAAMetadata(), AA);
  5304. updateDAGForMaybeTailCall(MM);
  5305. return;
  5306. }
  5307. case Intrinsic::memcpy_element_unordered_atomic: {
  5308. const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I);
  5309. SDValue Dst = getValue(MI.getRawDest());
  5310. SDValue Src = getValue(MI.getRawSource());
  5311. SDValue Length = getValue(MI.getLength());
  5312. Type *LengthTy = MI.getLength()->getType();
  5313. unsigned ElemSz = MI.getElementSizeInBytes();
  5314. bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
  5315. SDValue MC =
  5316. DAG.getAtomicMemcpy(getRoot(), sdl, Dst, Src, Length, LengthTy, ElemSz,
  5317. isTC, MachinePointerInfo(MI.getRawDest()),
  5318. MachinePointerInfo(MI.getRawSource()));
  5319. updateDAGForMaybeTailCall(MC);
  5320. return;
  5321. }
  5322. case Intrinsic::memmove_element_unordered_atomic: {
  5323. auto &MI = cast<AtomicMemMoveInst>(I);
  5324. SDValue Dst = getValue(MI.getRawDest());
  5325. SDValue Src = getValue(MI.getRawSource());
  5326. SDValue Length = getValue(MI.getLength());
  5327. Type *LengthTy = MI.getLength()->getType();
  5328. unsigned ElemSz = MI.getElementSizeInBytes();
  5329. bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
  5330. SDValue MC =
  5331. DAG.getAtomicMemmove(getRoot(), sdl, Dst, Src, Length, LengthTy, ElemSz,
  5332. isTC, MachinePointerInfo(MI.getRawDest()),
  5333. MachinePointerInfo(MI.getRawSource()));
  5334. updateDAGForMaybeTailCall(MC);
  5335. return;
  5336. }
  5337. case Intrinsic::memset_element_unordered_atomic: {
  5338. auto &MI = cast<AtomicMemSetInst>(I);
  5339. SDValue Dst = getValue(MI.getRawDest());
  5340. SDValue Val = getValue(MI.getValue());
  5341. SDValue Length = getValue(MI.getLength());
  5342. Type *LengthTy = MI.getLength()->getType();
  5343. unsigned ElemSz = MI.getElementSizeInBytes();
  5344. bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
  5345. SDValue MC =
  5346. DAG.getAtomicMemset(getRoot(), sdl, Dst, Val, Length, LengthTy, ElemSz,
  5347. isTC, MachinePointerInfo(MI.getRawDest()));
  5348. updateDAGForMaybeTailCall(MC);
  5349. return;
  5350. }
  5351. case Intrinsic::call_preallocated_setup: {
  5352. const CallBase *PreallocatedCall = FindPreallocatedCall(&I);
  5353. SDValue SrcValue = DAG.getSrcValue(PreallocatedCall);
  5354. SDValue Res = DAG.getNode(ISD::PREALLOCATED_SETUP, sdl, MVT::Other,
  5355. getRoot(), SrcValue);
  5356. setValue(&I, Res);
  5357. DAG.setRoot(Res);
  5358. return;
  5359. }
  5360. case Intrinsic::call_preallocated_arg: {
  5361. const CallBase *PreallocatedCall = FindPreallocatedCall(I.getOperand(0));
  5362. SDValue SrcValue = DAG.getSrcValue(PreallocatedCall);
  5363. SDValue Ops[3];
  5364. Ops[0] = getRoot();
  5365. Ops[1] = SrcValue;
  5366. Ops[2] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(1)), sdl,
  5367. MVT::i32); // arg index
  5368. SDValue Res = DAG.getNode(
  5369. ISD::PREALLOCATED_ARG, sdl,
  5370. DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Ops);
  5371. setValue(&I, Res);
  5372. DAG.setRoot(Res.getValue(1));
  5373. return;
  5374. }
  5375. case Intrinsic::dbg_addr:
  5376. case Intrinsic::dbg_declare: {
  5377. // Debug intrinsics are handled seperately in assignment tracking mode.
  5378. if (isAssignmentTrackingEnabled(*I.getFunction()->getParent()))
  5379. return;
  5380. // Assume dbg.addr and dbg.declare can not currently use DIArgList, i.e.
  5381. // they are non-variadic.
  5382. const auto &DI = cast<DbgVariableIntrinsic>(I);
  5383. assert(!DI.hasArgList() && "Only dbg.value should currently use DIArgList");
  5384. DILocalVariable *Variable = DI.getVariable();
  5385. DIExpression *Expression = DI.getExpression();
  5386. dropDanglingDebugInfo(Variable, Expression);
  5387. assert(Variable && "Missing variable");
  5388. LLVM_DEBUG(dbgs() << "SelectionDAG visiting debug intrinsic: " << DI
  5389. << "\n");
  5390. // Check if address has undef value.
  5391. const Value *Address = DI.getVariableLocationOp(0);
  5392. if (!Address || isa<UndefValue>(Address) ||
  5393. (Address->use_empty() && !isa<Argument>(Address))) {
  5394. LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI
  5395. << " (bad/undef/unused-arg address)\n");
  5396. return;
  5397. }
  5398. bool isParameter = Variable->isParameter() || isa<Argument>(Address);
  5399. // Check if this variable can be described by a frame index, typically
  5400. // either as a static alloca or a byval parameter.
  5401. int FI = std::numeric_limits<int>::max();
  5402. if (const auto *AI =
  5403. dyn_cast<AllocaInst>(Address->stripInBoundsConstantOffsets())) {
  5404. if (AI->isStaticAlloca()) {
  5405. auto I = FuncInfo.StaticAllocaMap.find(AI);
  5406. if (I != FuncInfo.StaticAllocaMap.end())
  5407. FI = I->second;
  5408. }
  5409. } else if (const auto *Arg = dyn_cast<Argument>(
  5410. Address->stripInBoundsConstantOffsets())) {
  5411. FI = FuncInfo.getArgumentFrameIndex(Arg);
  5412. }
  5413. // llvm.dbg.addr is control dependent and always generates indirect
  5414. // DBG_VALUE instructions. llvm.dbg.declare is handled as a frame index in
  5415. // the MachineFunction variable table.
  5416. if (FI != std::numeric_limits<int>::max()) {
  5417. if (Intrinsic == Intrinsic::dbg_addr) {
  5418. SDDbgValue *SDV = DAG.getFrameIndexDbgValue(
  5419. Variable, Expression, FI, getRoot().getNode(), /*IsIndirect*/ true,
  5420. dl, SDNodeOrder);
  5421. DAG.AddDbgValue(SDV, isParameter);
  5422. } else {
  5423. LLVM_DEBUG(dbgs() << "Skipping " << DI
  5424. << " (variable info stashed in MF side table)\n");
  5425. }
  5426. return;
  5427. }
  5428. SDValue &N = NodeMap[Address];
  5429. if (!N.getNode() && isa<Argument>(Address))
  5430. // Check unused arguments map.
  5431. N = UnusedArgNodeMap[Address];
  5432. SDDbgValue *SDV;
  5433. if (N.getNode()) {
  5434. if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
  5435. Address = BCI->getOperand(0);
  5436. // Parameters are handled specially.
  5437. auto FINode = dyn_cast<FrameIndexSDNode>(N.getNode());
  5438. if (isParameter && FINode) {
  5439. // Byval parameter. We have a frame index at this point.
  5440. SDV =
  5441. DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(),
  5442. /*IsIndirect*/ true, dl, SDNodeOrder);
  5443. } else if (isa<Argument>(Address)) {
  5444. // Address is an argument, so try to emit its dbg value using
  5445. // virtual register info from the FuncInfo.ValueMap.
  5446. EmitFuncArgumentDbgValue(Address, Variable, Expression, dl,
  5447. FuncArgumentDbgValueKind::Declare, N);
  5448. return;
  5449. } else {
  5450. SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(),
  5451. true, dl, SDNodeOrder);
  5452. }
  5453. DAG.AddDbgValue(SDV, isParameter);
  5454. } else {
  5455. // If Address is an argument then try to emit its dbg value using
  5456. // virtual register info from the FuncInfo.ValueMap.
  5457. if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl,
  5458. FuncArgumentDbgValueKind::Declare, N)) {
  5459. LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI
  5460. << " (could not emit func-arg dbg_value)\n");
  5461. }
  5462. }
  5463. return;
  5464. }
  5465. case Intrinsic::dbg_label: {
  5466. const DbgLabelInst &DI = cast<DbgLabelInst>(I);
  5467. DILabel *Label = DI.getLabel();
  5468. assert(Label && "Missing label");
  5469. SDDbgLabel *SDV;
  5470. SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder);
  5471. DAG.AddDbgLabel(SDV);
  5472. return;
  5473. }
  5474. case Intrinsic::dbg_assign: {
  5475. // Debug intrinsics are handled seperately in assignment tracking mode.
  5476. assert(isAssignmentTrackingEnabled(*I.getFunction()->getParent()) &&
  5477. "expected assignment tracking to be enabled");
  5478. return;
  5479. }
  5480. case Intrinsic::dbg_value: {
  5481. // Debug intrinsics are handled seperately in assignment tracking mode.
  5482. if (isAssignmentTrackingEnabled(*I.getFunction()->getParent()))
  5483. return;
  5484. const DbgValueInst &DI = cast<DbgValueInst>(I);
  5485. assert(DI.getVariable() && "Missing variable");
  5486. DILocalVariable *Variable = DI.getVariable();
  5487. DIExpression *Expression = DI.getExpression();
  5488. dropDanglingDebugInfo(Variable, Expression);
  5489. SmallVector<Value *, 4> Values(DI.getValues());
  5490. if (Values.empty())
  5491. return;
  5492. if (llvm::is_contained(Values, nullptr))
  5493. return;
  5494. bool IsVariadic = DI.hasArgList();
  5495. if (!handleDebugValue(Values, Variable, Expression, DI.getDebugLoc(),
  5496. SDNodeOrder, IsVariadic))
  5497. addDanglingDebugInfo(&DI, SDNodeOrder);
  5498. return;
  5499. }
  5500. case Intrinsic::eh_typeid_for: {
  5501. // Find the type id for the given typeinfo.
  5502. GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0));
  5503. unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV);
  5504. Res = DAG.getConstant(TypeID, sdl, MVT::i32);
  5505. setValue(&I, Res);
  5506. return;
  5507. }
  5508. case Intrinsic::eh_return_i32:
  5509. case Intrinsic::eh_return_i64:
  5510. DAG.getMachineFunction().setCallsEHReturn(true);
  5511. DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl,
  5512. MVT::Other,
  5513. getControlRoot(),
  5514. getValue(I.getArgOperand(0)),
  5515. getValue(I.getArgOperand(1))));
  5516. return;
  5517. case Intrinsic::eh_unwind_init:
  5518. DAG.getMachineFunction().setCallsUnwindInit(true);
  5519. return;
  5520. case Intrinsic::eh_dwarf_cfa:
  5521. setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl,
  5522. TLI.getPointerTy(DAG.getDataLayout()),
  5523. getValue(I.getArgOperand(0))));
  5524. return;
  5525. case Intrinsic::eh_sjlj_callsite: {
  5526. MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
  5527. ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(0));
  5528. assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!");
  5529. MMI.setCurrentCallSite(CI->getZExtValue());
  5530. return;
  5531. }
  5532. case Intrinsic::eh_sjlj_functioncontext: {
  5533. // Get and store the index of the function context.
  5534. MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
  5535. AllocaInst *FnCtx =
  5536. cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts());
  5537. int FI = FuncInfo.StaticAllocaMap[FnCtx];
  5538. MFI.setFunctionContextIndex(FI);
  5539. return;
  5540. }
  5541. case Intrinsic::eh_sjlj_setjmp: {
  5542. SDValue Ops[2];
  5543. Ops[0] = getRoot();
  5544. Ops[1] = getValue(I.getArgOperand(0));
  5545. SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl,
  5546. DAG.getVTList(MVT::i32, MVT::Other), Ops);
  5547. setValue(&I, Op.getValue(0));
  5548. DAG.setRoot(Op.getValue(1));
  5549. return;
  5550. }
  5551. case Intrinsic::eh_sjlj_longjmp:
  5552. DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other,
  5553. getRoot(), getValue(I.getArgOperand(0))));
  5554. return;
  5555. case Intrinsic::eh_sjlj_setup_dispatch:
  5556. DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other,
  5557. getRoot()));
  5558. return;
  5559. case Intrinsic::masked_gather:
  5560. visitMaskedGather(I);
  5561. return;
  5562. case Intrinsic::masked_load:
  5563. visitMaskedLoad(I);
  5564. return;
  5565. case Intrinsic::masked_scatter:
  5566. visitMaskedScatter(I);
  5567. return;
  5568. case Intrinsic::masked_store:
  5569. visitMaskedStore(I);
  5570. return;
  5571. case Intrinsic::masked_expandload:
  5572. visitMaskedLoad(I, true /* IsExpanding */);
  5573. return;
  5574. case Intrinsic::masked_compressstore:
  5575. visitMaskedStore(I, true /* IsCompressing */);
  5576. return;
  5577. case Intrinsic::powi:
  5578. setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)),
  5579. getValue(I.getArgOperand(1)), DAG));
  5580. return;
  5581. case Intrinsic::log:
  5582. setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
  5583. return;
  5584. case Intrinsic::log2:
  5585. setValue(&I,
  5586. expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
  5587. return;
  5588. case Intrinsic::log10:
  5589. setValue(&I,
  5590. expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
  5591. return;
  5592. case Intrinsic::exp:
  5593. setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
  5594. return;
  5595. case Intrinsic::exp2:
  5596. setValue(&I,
  5597. expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
  5598. return;
  5599. case Intrinsic::pow:
  5600. setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)),
  5601. getValue(I.getArgOperand(1)), DAG, TLI, Flags));
  5602. return;
  5603. case Intrinsic::sqrt:
  5604. case Intrinsic::fabs:
  5605. case Intrinsic::sin:
  5606. case Intrinsic::cos:
  5607. case Intrinsic::floor:
  5608. case Intrinsic::ceil:
  5609. case Intrinsic::trunc:
  5610. case Intrinsic::rint:
  5611. case Intrinsic::nearbyint:
  5612. case Intrinsic::round:
  5613. case Intrinsic::roundeven:
  5614. case Intrinsic::canonicalize: {
  5615. unsigned Opcode;
  5616. switch (Intrinsic) {
  5617. default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
  5618. case Intrinsic::sqrt: Opcode = ISD::FSQRT; break;
  5619. case Intrinsic::fabs: Opcode = ISD::FABS; break;
  5620. case Intrinsic::sin: Opcode = ISD::FSIN; break;
  5621. case Intrinsic::cos: Opcode = ISD::FCOS; break;
  5622. case Intrinsic::floor: Opcode = ISD::FFLOOR; break;
  5623. case Intrinsic::ceil: Opcode = ISD::FCEIL; break;
  5624. case Intrinsic::trunc: Opcode = ISD::FTRUNC; break;
  5625. case Intrinsic::rint: Opcode = ISD::FRINT; break;
  5626. case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break;
  5627. case Intrinsic::round: Opcode = ISD::FROUND; break;
  5628. case Intrinsic::roundeven: Opcode = ISD::FROUNDEVEN; break;
  5629. case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break;
  5630. }
  5631. setValue(&I, DAG.getNode(Opcode, sdl,
  5632. getValue(I.getArgOperand(0)).getValueType(),
  5633. getValue(I.getArgOperand(0)), Flags));
  5634. return;
  5635. }
  5636. case Intrinsic::lround:
  5637. case Intrinsic::llround:
  5638. case Intrinsic::lrint:
  5639. case Intrinsic::llrint: {
  5640. unsigned Opcode;
  5641. switch (Intrinsic) {
  5642. default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
  5643. case Intrinsic::lround: Opcode = ISD::LROUND; break;
  5644. case Intrinsic::llround: Opcode = ISD::LLROUND; break;
  5645. case Intrinsic::lrint: Opcode = ISD::LRINT; break;
  5646. case Intrinsic::llrint: Opcode = ISD::LLRINT; break;
  5647. }
  5648. EVT RetVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  5649. setValue(&I, DAG.getNode(Opcode, sdl, RetVT,
  5650. getValue(I.getArgOperand(0))));
  5651. return;
  5652. }
  5653. case Intrinsic::minnum:
  5654. setValue(&I, DAG.getNode(ISD::FMINNUM, sdl,
  5655. getValue(I.getArgOperand(0)).getValueType(),
  5656. getValue(I.getArgOperand(0)),
  5657. getValue(I.getArgOperand(1)), Flags));
  5658. return;
  5659. case Intrinsic::maxnum:
  5660. setValue(&I, DAG.getNode(ISD::FMAXNUM, sdl,
  5661. getValue(I.getArgOperand(0)).getValueType(),
  5662. getValue(I.getArgOperand(0)),
  5663. getValue(I.getArgOperand(1)), Flags));
  5664. return;
  5665. case Intrinsic::minimum:
  5666. setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl,
  5667. getValue(I.getArgOperand(0)).getValueType(),
  5668. getValue(I.getArgOperand(0)),
  5669. getValue(I.getArgOperand(1)), Flags));
  5670. return;
  5671. case Intrinsic::maximum:
  5672. setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl,
  5673. getValue(I.getArgOperand(0)).getValueType(),
  5674. getValue(I.getArgOperand(0)),
  5675. getValue(I.getArgOperand(1)), Flags));
  5676. return;
  5677. case Intrinsic::copysign:
  5678. setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl,
  5679. getValue(I.getArgOperand(0)).getValueType(),
  5680. getValue(I.getArgOperand(0)),
  5681. getValue(I.getArgOperand(1)), Flags));
  5682. return;
  5683. case Intrinsic::arithmetic_fence: {
  5684. setValue(&I, DAG.getNode(ISD::ARITH_FENCE, sdl,
  5685. getValue(I.getArgOperand(0)).getValueType(),
  5686. getValue(I.getArgOperand(0)), Flags));
  5687. return;
  5688. }
  5689. case Intrinsic::fma:
  5690. setValue(&I, DAG.getNode(
  5691. ISD::FMA, sdl, getValue(I.getArgOperand(0)).getValueType(),
  5692. getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)),
  5693. getValue(I.getArgOperand(2)), Flags));
  5694. return;
  5695. #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC) \
  5696. case Intrinsic::INTRINSIC:
  5697. #include "llvm/IR/ConstrainedOps.def"
  5698. visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I));
  5699. return;
  5700. #define BEGIN_REGISTER_VP_INTRINSIC(VPID, ...) case Intrinsic::VPID:
  5701. #include "llvm/IR/VPIntrinsics.def"
  5702. visitVectorPredicationIntrinsic(cast<VPIntrinsic>(I));
  5703. return;
  5704. case Intrinsic::fptrunc_round: {
  5705. // Get the last argument, the metadata and convert it to an integer in the
  5706. // call
  5707. Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(1))->getMetadata();
  5708. std::optional<RoundingMode> RoundMode =
  5709. convertStrToRoundingMode(cast<MDString>(MD)->getString());
  5710. EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  5711. // Propagate fast-math-flags from IR to node(s).
  5712. SDNodeFlags Flags;
  5713. Flags.copyFMF(*cast<FPMathOperator>(&I));
  5714. SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
  5715. SDValue Result;
  5716. Result = DAG.getNode(
  5717. ISD::FPTRUNC_ROUND, sdl, VT, getValue(I.getArgOperand(0)),
  5718. DAG.getTargetConstant((int)*RoundMode, sdl,
  5719. TLI.getPointerTy(DAG.getDataLayout())));
  5720. setValue(&I, Result);
  5721. return;
  5722. }
  5723. case Intrinsic::fmuladd: {
  5724. EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  5725. if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
  5726. TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
  5727. setValue(&I, DAG.getNode(ISD::FMA, sdl,
  5728. getValue(I.getArgOperand(0)).getValueType(),
  5729. getValue(I.getArgOperand(0)),
  5730. getValue(I.getArgOperand(1)),
  5731. getValue(I.getArgOperand(2)), Flags));
  5732. } else {
  5733. // TODO: Intrinsic calls should have fast-math-flags.
  5734. SDValue Mul = DAG.getNode(
  5735. ISD::FMUL, sdl, getValue(I.getArgOperand(0)).getValueType(),
  5736. getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)), Flags);
  5737. SDValue Add = DAG.getNode(ISD::FADD, sdl,
  5738. getValue(I.getArgOperand(0)).getValueType(),
  5739. Mul, getValue(I.getArgOperand(2)), Flags);
  5740. setValue(&I, Add);
  5741. }
  5742. return;
  5743. }
  5744. case Intrinsic::convert_to_fp16:
  5745. setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16,
  5746. DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16,
  5747. getValue(I.getArgOperand(0)),
  5748. DAG.getTargetConstant(0, sdl,
  5749. MVT::i32))));
  5750. return;
  5751. case Intrinsic::convert_from_fp16:
  5752. setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl,
  5753. TLI.getValueType(DAG.getDataLayout(), I.getType()),
  5754. DAG.getNode(ISD::BITCAST, sdl, MVT::f16,
  5755. getValue(I.getArgOperand(0)))));
  5756. return;
  5757. case Intrinsic::fptosi_sat: {
  5758. EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  5759. setValue(&I, DAG.getNode(ISD::FP_TO_SINT_SAT, sdl, VT,
  5760. getValue(I.getArgOperand(0)),
  5761. DAG.getValueType(VT.getScalarType())));
  5762. return;
  5763. }
  5764. case Intrinsic::fptoui_sat: {
  5765. EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  5766. setValue(&I, DAG.getNode(ISD::FP_TO_UINT_SAT, sdl, VT,
  5767. getValue(I.getArgOperand(0)),
  5768. DAG.getValueType(VT.getScalarType())));
  5769. return;
  5770. }
  5771. case Intrinsic::set_rounding:
  5772. Res = DAG.getNode(ISD::SET_ROUNDING, sdl, MVT::Other,
  5773. {getRoot(), getValue(I.getArgOperand(0))});
  5774. setValue(&I, Res);
  5775. DAG.setRoot(Res.getValue(0));
  5776. return;
  5777. case Intrinsic::is_fpclass: {
  5778. const DataLayout DLayout = DAG.getDataLayout();
  5779. EVT DestVT = TLI.getValueType(DLayout, I.getType());
  5780. EVT ArgVT = TLI.getValueType(DLayout, I.getArgOperand(0)->getType());
  5781. unsigned Test = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
  5782. MachineFunction &MF = DAG.getMachineFunction();
  5783. const Function &F = MF.getFunction();
  5784. SDValue Op = getValue(I.getArgOperand(0));
  5785. SDNodeFlags Flags;
  5786. Flags.setNoFPExcept(
  5787. !F.getAttributes().hasFnAttr(llvm::Attribute::StrictFP));
  5788. // If ISD::IS_FPCLASS should be expanded, do it right now, because the
  5789. // expansion can use illegal types. Making expansion early allows
  5790. // legalizing these types prior to selection.
  5791. if (!TLI.isOperationLegalOrCustom(ISD::IS_FPCLASS, ArgVT)) {
  5792. SDValue Result = TLI.expandIS_FPCLASS(DestVT, Op, Test, Flags, sdl, DAG);
  5793. setValue(&I, Result);
  5794. return;
  5795. }
  5796. SDValue Check = DAG.getTargetConstant(Test, sdl, MVT::i32);
  5797. SDValue V = DAG.getNode(ISD::IS_FPCLASS, sdl, DestVT, {Op, Check}, Flags);
  5798. setValue(&I, V);
  5799. return;
  5800. }
  5801. case Intrinsic::pcmarker: {
  5802. SDValue Tmp = getValue(I.getArgOperand(0));
  5803. DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp));
  5804. return;
  5805. }
  5806. case Intrinsic::readcyclecounter: {
  5807. SDValue Op = getRoot();
  5808. Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl,
  5809. DAG.getVTList(MVT::i64, MVT::Other), Op);
  5810. setValue(&I, Res);
  5811. DAG.setRoot(Res.getValue(1));
  5812. return;
  5813. }
  5814. case Intrinsic::bitreverse:
  5815. setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl,
  5816. getValue(I.getArgOperand(0)).getValueType(),
  5817. getValue(I.getArgOperand(0))));
  5818. return;
  5819. case Intrinsic::bswap:
  5820. setValue(&I, DAG.getNode(ISD::BSWAP, sdl,
  5821. getValue(I.getArgOperand(0)).getValueType(),
  5822. getValue(I.getArgOperand(0))));
  5823. return;
  5824. case Intrinsic::cttz: {
  5825. SDValue Arg = getValue(I.getArgOperand(0));
  5826. ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
  5827. EVT Ty = Arg.getValueType();
  5828. setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF,
  5829. sdl, Ty, Arg));
  5830. return;
  5831. }
  5832. case Intrinsic::ctlz: {
  5833. SDValue Arg = getValue(I.getArgOperand(0));
  5834. ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
  5835. EVT Ty = Arg.getValueType();
  5836. setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF,
  5837. sdl, Ty, Arg));
  5838. return;
  5839. }
  5840. case Intrinsic::ctpop: {
  5841. SDValue Arg = getValue(I.getArgOperand(0));
  5842. EVT Ty = Arg.getValueType();
  5843. setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg));
  5844. return;
  5845. }
  5846. case Intrinsic::fshl:
  5847. case Intrinsic::fshr: {
  5848. bool IsFSHL = Intrinsic == Intrinsic::fshl;
  5849. SDValue X = getValue(I.getArgOperand(0));
  5850. SDValue Y = getValue(I.getArgOperand(1));
  5851. SDValue Z = getValue(I.getArgOperand(2));
  5852. EVT VT = X.getValueType();
  5853. if (X == Y) {
  5854. auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR;
  5855. setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z));
  5856. } else {
  5857. auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR;
  5858. setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z));
  5859. }
  5860. return;
  5861. }
  5862. case Intrinsic::sadd_sat: {
  5863. SDValue Op1 = getValue(I.getArgOperand(0));
  5864. SDValue Op2 = getValue(I.getArgOperand(1));
  5865. setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2));
  5866. return;
  5867. }
  5868. case Intrinsic::uadd_sat: {
  5869. SDValue Op1 = getValue(I.getArgOperand(0));
  5870. SDValue Op2 = getValue(I.getArgOperand(1));
  5871. setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2));
  5872. return;
  5873. }
  5874. case Intrinsic::ssub_sat: {
  5875. SDValue Op1 = getValue(I.getArgOperand(0));
  5876. SDValue Op2 = getValue(I.getArgOperand(1));
  5877. setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2));
  5878. return;
  5879. }
  5880. case Intrinsic::usub_sat: {
  5881. SDValue Op1 = getValue(I.getArgOperand(0));
  5882. SDValue Op2 = getValue(I.getArgOperand(1));
  5883. setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2));
  5884. return;
  5885. }
  5886. case Intrinsic::sshl_sat: {
  5887. SDValue Op1 = getValue(I.getArgOperand(0));
  5888. SDValue Op2 = getValue(I.getArgOperand(1));
  5889. setValue(&I, DAG.getNode(ISD::SSHLSAT, sdl, Op1.getValueType(), Op1, Op2));
  5890. return;
  5891. }
  5892. case Intrinsic::ushl_sat: {
  5893. SDValue Op1 = getValue(I.getArgOperand(0));
  5894. SDValue Op2 = getValue(I.getArgOperand(1));
  5895. setValue(&I, DAG.getNode(ISD::USHLSAT, sdl, Op1.getValueType(), Op1, Op2));
  5896. return;
  5897. }
  5898. case Intrinsic::smul_fix:
  5899. case Intrinsic::umul_fix:
  5900. case Intrinsic::smul_fix_sat:
  5901. case Intrinsic::umul_fix_sat: {
  5902. SDValue Op1 = getValue(I.getArgOperand(0));
  5903. SDValue Op2 = getValue(I.getArgOperand(1));
  5904. SDValue Op3 = getValue(I.getArgOperand(2));
  5905. setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl,
  5906. Op1.getValueType(), Op1, Op2, Op3));
  5907. return;
  5908. }
  5909. case Intrinsic::sdiv_fix:
  5910. case Intrinsic::udiv_fix:
  5911. case Intrinsic::sdiv_fix_sat:
  5912. case Intrinsic::udiv_fix_sat: {
  5913. SDValue Op1 = getValue(I.getArgOperand(0));
  5914. SDValue Op2 = getValue(I.getArgOperand(1));
  5915. SDValue Op3 = getValue(I.getArgOperand(2));
  5916. setValue(&I, expandDivFix(FixedPointIntrinsicToOpcode(Intrinsic), sdl,
  5917. Op1, Op2, Op3, DAG, TLI));
  5918. return;
  5919. }
  5920. case Intrinsic::smax: {
  5921. SDValue Op1 = getValue(I.getArgOperand(0));
  5922. SDValue Op2 = getValue(I.getArgOperand(1));
  5923. setValue(&I, DAG.getNode(ISD::SMAX, sdl, Op1.getValueType(), Op1, Op2));
  5924. return;
  5925. }
  5926. case Intrinsic::smin: {
  5927. SDValue Op1 = getValue(I.getArgOperand(0));
  5928. SDValue Op2 = getValue(I.getArgOperand(1));
  5929. setValue(&I, DAG.getNode(ISD::SMIN, sdl, Op1.getValueType(), Op1, Op2));
  5930. return;
  5931. }
  5932. case Intrinsic::umax: {
  5933. SDValue Op1 = getValue(I.getArgOperand(0));
  5934. SDValue Op2 = getValue(I.getArgOperand(1));
  5935. setValue(&I, DAG.getNode(ISD::UMAX, sdl, Op1.getValueType(), Op1, Op2));
  5936. return;
  5937. }
  5938. case Intrinsic::umin: {
  5939. SDValue Op1 = getValue(I.getArgOperand(0));
  5940. SDValue Op2 = getValue(I.getArgOperand(1));
  5941. setValue(&I, DAG.getNode(ISD::UMIN, sdl, Op1.getValueType(), Op1, Op2));
  5942. return;
  5943. }
  5944. case Intrinsic::abs: {
  5945. // TODO: Preserve "int min is poison" arg in SDAG?
  5946. SDValue Op1 = getValue(I.getArgOperand(0));
  5947. setValue(&I, DAG.getNode(ISD::ABS, sdl, Op1.getValueType(), Op1));
  5948. return;
  5949. }
  5950. case Intrinsic::stacksave: {
  5951. SDValue Op = getRoot();
  5952. EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  5953. Res = DAG.getNode(ISD::STACKSAVE, sdl, DAG.getVTList(VT, MVT::Other), Op);
  5954. setValue(&I, Res);
  5955. DAG.setRoot(Res.getValue(1));
  5956. return;
  5957. }
  5958. case Intrinsic::stackrestore:
  5959. Res = getValue(I.getArgOperand(0));
  5960. DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res));
  5961. return;
  5962. case Intrinsic::get_dynamic_area_offset: {
  5963. SDValue Op = getRoot();
  5964. EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout());
  5965. EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
  5966. // Result type for @llvm.get.dynamic.area.offset should match PtrTy for
  5967. // target.
  5968. if (PtrTy.getFixedSizeInBits() < ResTy.getFixedSizeInBits())
  5969. report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset"
  5970. " intrinsic!");
  5971. Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy),
  5972. Op);
  5973. DAG.setRoot(Op);
  5974. setValue(&I, Res);
  5975. return;
  5976. }
  5977. case Intrinsic::stackguard: {
  5978. MachineFunction &MF = DAG.getMachineFunction();
  5979. const Module &M = *MF.getFunction().getParent();
  5980. SDValue Chain = getRoot();
  5981. if (TLI.useLoadStackGuardNode()) {
  5982. Res = getLoadStackGuard(DAG, sdl, Chain);
  5983. } else {
  5984. EVT PtrTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
  5985. const Value *Global = TLI.getSDagStackGuard(M);
  5986. Align Align = DAG.getDataLayout().getPrefTypeAlign(Global->getType());
  5987. Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global),
  5988. MachinePointerInfo(Global, 0), Align,
  5989. MachineMemOperand::MOVolatile);
  5990. }
  5991. if (TLI.useStackGuardXorFP())
  5992. Res = TLI.emitStackGuardXorFP(DAG, Res, sdl);
  5993. DAG.setRoot(Chain);
  5994. setValue(&I, Res);
  5995. return;
  5996. }
  5997. case Intrinsic::stackprotector: {
  5998. // Emit code into the DAG to store the stack guard onto the stack.
  5999. MachineFunction &MF = DAG.getMachineFunction();
  6000. MachineFrameInfo &MFI = MF.getFrameInfo();
  6001. SDValue Src, Chain = getRoot();
  6002. if (TLI.useLoadStackGuardNode())
  6003. Src = getLoadStackGuard(DAG, sdl, Chain);
  6004. else
  6005. Src = getValue(I.getArgOperand(0)); // The guard's value.
  6006. AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
  6007. int FI = FuncInfo.StaticAllocaMap[Slot];
  6008. MFI.setStackProtectorIndex(FI);
  6009. EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout());
  6010. SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
  6011. // Store the stack protector onto the stack.
  6012. Res = DAG.getStore(
  6013. Chain, sdl, Src, FIN,
  6014. MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
  6015. MaybeAlign(), MachineMemOperand::MOVolatile);
  6016. setValue(&I, Res);
  6017. DAG.setRoot(Res);
  6018. return;
  6019. }
  6020. case Intrinsic::objectsize:
  6021. llvm_unreachable("llvm.objectsize.* should have been lowered already");
  6022. case Intrinsic::is_constant:
  6023. llvm_unreachable("llvm.is.constant.* should have been lowered already");
  6024. case Intrinsic::annotation:
  6025. case Intrinsic::ptr_annotation:
  6026. case Intrinsic::launder_invariant_group:
  6027. case Intrinsic::strip_invariant_group:
  6028. // Drop the intrinsic, but forward the value
  6029. setValue(&I, getValue(I.getOperand(0)));
  6030. return;
  6031. case Intrinsic::assume:
  6032. case Intrinsic::experimental_noalias_scope_decl:
  6033. case Intrinsic::var_annotation:
  6034. case Intrinsic::sideeffect:
  6035. // Discard annotate attributes, noalias scope declarations, assumptions, and
  6036. // artificial side-effects.
  6037. return;
  6038. case Intrinsic::codeview_annotation: {
  6039. // Emit a label associated with this metadata.
  6040. MachineFunction &MF = DAG.getMachineFunction();
  6041. MCSymbol *Label =
  6042. MF.getMMI().getContext().createTempSymbol("annotation", true);
  6043. Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata();
  6044. MF.addCodeViewAnnotation(Label, cast<MDNode>(MD));
  6045. Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label);
  6046. DAG.setRoot(Res);
  6047. return;
  6048. }
  6049. case Intrinsic::init_trampoline: {
  6050. const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts());
  6051. SDValue Ops[6];
  6052. Ops[0] = getRoot();
  6053. Ops[1] = getValue(I.getArgOperand(0));
  6054. Ops[2] = getValue(I.getArgOperand(1));
  6055. Ops[3] = getValue(I.getArgOperand(2));
  6056. Ops[4] = DAG.getSrcValue(I.getArgOperand(0));
  6057. Ops[5] = DAG.getSrcValue(F);
  6058. Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops);
  6059. DAG.setRoot(Res);
  6060. return;
  6061. }
  6062. case Intrinsic::adjust_trampoline:
  6063. setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl,
  6064. TLI.getPointerTy(DAG.getDataLayout()),
  6065. getValue(I.getArgOperand(0))));
  6066. return;
  6067. case Intrinsic::gcroot: {
  6068. assert(DAG.getMachineFunction().getFunction().hasGC() &&
  6069. "only valid in functions with gc specified, enforced by Verifier");
  6070. assert(GFI && "implied by previous");
  6071. const Value *Alloca = I.getArgOperand(0)->stripPointerCasts();
  6072. const Constant *TypeMap = cast<Constant>(I.getArgOperand(1));
  6073. FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
  6074. GFI->addStackRoot(FI->getIndex(), TypeMap);
  6075. return;
  6076. }
  6077. case Intrinsic::gcread:
  6078. case Intrinsic::gcwrite:
  6079. llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
  6080. case Intrinsic::get_rounding:
  6081. Res = DAG.getNode(ISD::GET_ROUNDING, sdl, {MVT::i32, MVT::Other}, getRoot());
  6082. setValue(&I, Res);
  6083. DAG.setRoot(Res.getValue(1));
  6084. return;
  6085. case Intrinsic::expect:
  6086. // Just replace __builtin_expect(exp, c) with EXP.
  6087. setValue(&I, getValue(I.getArgOperand(0)));
  6088. return;
  6089. case Intrinsic::ubsantrap:
  6090. case Intrinsic::debugtrap:
  6091. case Intrinsic::trap: {
  6092. StringRef TrapFuncName =
  6093. I.getAttributes().getFnAttr("trap-func-name").getValueAsString();
  6094. if (TrapFuncName.empty()) {
  6095. switch (Intrinsic) {
  6096. case Intrinsic::trap:
  6097. DAG.setRoot(DAG.getNode(ISD::TRAP, sdl, MVT::Other, getRoot()));
  6098. break;
  6099. case Intrinsic::debugtrap:
  6100. DAG.setRoot(DAG.getNode(ISD::DEBUGTRAP, sdl, MVT::Other, getRoot()));
  6101. break;
  6102. case Intrinsic::ubsantrap:
  6103. DAG.setRoot(DAG.getNode(
  6104. ISD::UBSANTRAP, sdl, MVT::Other, getRoot(),
  6105. DAG.getTargetConstant(
  6106. cast<ConstantInt>(I.getArgOperand(0))->getZExtValue(), sdl,
  6107. MVT::i32)));
  6108. break;
  6109. default: llvm_unreachable("unknown trap intrinsic");
  6110. }
  6111. return;
  6112. }
  6113. TargetLowering::ArgListTy Args;
  6114. if (Intrinsic == Intrinsic::ubsantrap) {
  6115. Args.push_back(TargetLoweringBase::ArgListEntry());
  6116. Args[0].Val = I.getArgOperand(0);
  6117. Args[0].Node = getValue(Args[0].Val);
  6118. Args[0].Ty = Args[0].Val->getType();
  6119. }
  6120. TargetLowering::CallLoweringInfo CLI(DAG);
  6121. CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee(
  6122. CallingConv::C, I.getType(),
  6123. DAG.getExternalSymbol(TrapFuncName.data(),
  6124. TLI.getPointerTy(DAG.getDataLayout())),
  6125. std::move(Args));
  6126. std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
  6127. DAG.setRoot(Result.second);
  6128. return;
  6129. }
  6130. case Intrinsic::uadd_with_overflow:
  6131. case Intrinsic::sadd_with_overflow:
  6132. case Intrinsic::usub_with_overflow:
  6133. case Intrinsic::ssub_with_overflow:
  6134. case Intrinsic::umul_with_overflow:
  6135. case Intrinsic::smul_with_overflow: {
  6136. ISD::NodeType Op;
  6137. switch (Intrinsic) {
  6138. default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
  6139. case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break;
  6140. case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break;
  6141. case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break;
  6142. case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break;
  6143. case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break;
  6144. case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break;
  6145. }
  6146. SDValue Op1 = getValue(I.getArgOperand(0));
  6147. SDValue Op2 = getValue(I.getArgOperand(1));
  6148. EVT ResultVT = Op1.getValueType();
  6149. EVT OverflowVT = MVT::i1;
  6150. if (ResultVT.isVector())
  6151. OverflowVT = EVT::getVectorVT(
  6152. *Context, OverflowVT, ResultVT.getVectorElementCount());
  6153. SDVTList VTs = DAG.getVTList(ResultVT, OverflowVT);
  6154. setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2));
  6155. return;
  6156. }
  6157. case Intrinsic::prefetch: {
  6158. SDValue Ops[5];
  6159. unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
  6160. auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore;
  6161. Ops[0] = DAG.getRoot();
  6162. Ops[1] = getValue(I.getArgOperand(0));
  6163. Ops[2] = getValue(I.getArgOperand(1));
  6164. Ops[3] = getValue(I.getArgOperand(2));
  6165. Ops[4] = getValue(I.getArgOperand(3));
  6166. SDValue Result = DAG.getMemIntrinsicNode(
  6167. ISD::PREFETCH, sdl, DAG.getVTList(MVT::Other), Ops,
  6168. EVT::getIntegerVT(*Context, 8), MachinePointerInfo(I.getArgOperand(0)),
  6169. /* align */ std::nullopt, Flags);
  6170. // Chain the prefetch in parallell with any pending loads, to stay out of
  6171. // the way of later optimizations.
  6172. PendingLoads.push_back(Result);
  6173. Result = getRoot();
  6174. DAG.setRoot(Result);
  6175. return;
  6176. }
  6177. case Intrinsic::lifetime_start:
  6178. case Intrinsic::lifetime_end: {
  6179. bool IsStart = (Intrinsic == Intrinsic::lifetime_start);
  6180. // Stack coloring is not enabled in O0, discard region information.
  6181. if (TM.getOptLevel() == CodeGenOpt::None)
  6182. return;
  6183. const int64_t ObjectSize =
  6184. cast<ConstantInt>(I.getArgOperand(0))->getSExtValue();
  6185. Value *const ObjectPtr = I.getArgOperand(1);
  6186. SmallVector<const Value *, 4> Allocas;
  6187. getUnderlyingObjects(ObjectPtr, Allocas);
  6188. for (const Value *Alloca : Allocas) {
  6189. const AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(Alloca);
  6190. // Could not find an Alloca.
  6191. if (!LifetimeObject)
  6192. continue;
  6193. // First check that the Alloca is static, otherwise it won't have a
  6194. // valid frame index.
  6195. auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject);
  6196. if (SI == FuncInfo.StaticAllocaMap.end())
  6197. return;
  6198. const int FrameIndex = SI->second;
  6199. int64_t Offset;
  6200. if (GetPointerBaseWithConstantOffset(
  6201. ObjectPtr, Offset, DAG.getDataLayout()) != LifetimeObject)
  6202. Offset = -1; // Cannot determine offset from alloca to lifetime object.
  6203. Res = DAG.getLifetimeNode(IsStart, sdl, getRoot(), FrameIndex, ObjectSize,
  6204. Offset);
  6205. DAG.setRoot(Res);
  6206. }
  6207. return;
  6208. }
  6209. case Intrinsic::pseudoprobe: {
  6210. auto Guid = cast<ConstantInt>(I.getArgOperand(0))->getZExtValue();
  6211. auto Index = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
  6212. auto Attr = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue();
  6213. Res = DAG.getPseudoProbeNode(sdl, getRoot(), Guid, Index, Attr);
  6214. DAG.setRoot(Res);
  6215. return;
  6216. }
  6217. case Intrinsic::invariant_start:
  6218. // Discard region information.
  6219. setValue(&I,
  6220. DAG.getUNDEF(TLI.getValueType(DAG.getDataLayout(), I.getType())));
  6221. return;
  6222. case Intrinsic::invariant_end:
  6223. // Discard region information.
  6224. return;
  6225. case Intrinsic::clear_cache:
  6226. /// FunctionName may be null.
  6227. if (const char *FunctionName = TLI.getClearCacheBuiltinName())
  6228. lowerCallToExternalSymbol(I, FunctionName);
  6229. return;
  6230. case Intrinsic::donothing:
  6231. case Intrinsic::seh_try_begin:
  6232. case Intrinsic::seh_scope_begin:
  6233. case Intrinsic::seh_try_end:
  6234. case Intrinsic::seh_scope_end:
  6235. // ignore
  6236. return;
  6237. case Intrinsic::experimental_stackmap:
  6238. visitStackmap(I);
  6239. return;
  6240. case Intrinsic::experimental_patchpoint_void:
  6241. case Intrinsic::experimental_patchpoint_i64:
  6242. visitPatchpoint(I);
  6243. return;
  6244. case Intrinsic::experimental_gc_statepoint:
  6245. LowerStatepoint(cast<GCStatepointInst>(I));
  6246. return;
  6247. case Intrinsic::experimental_gc_result:
  6248. visitGCResult(cast<GCResultInst>(I));
  6249. return;
  6250. case Intrinsic::experimental_gc_relocate:
  6251. visitGCRelocate(cast<GCRelocateInst>(I));
  6252. return;
  6253. case Intrinsic::instrprof_cover:
  6254. llvm_unreachable("instrprof failed to lower a cover");
  6255. case Intrinsic::instrprof_increment:
  6256. llvm_unreachable("instrprof failed to lower an increment");
  6257. case Intrinsic::instrprof_value_profile:
  6258. llvm_unreachable("instrprof failed to lower a value profiling call");
  6259. case Intrinsic::localescape: {
  6260. MachineFunction &MF = DAG.getMachineFunction();
  6261. const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
  6262. // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission
  6263. // is the same on all targets.
  6264. for (unsigned Idx = 0, E = I.arg_size(); Idx < E; ++Idx) {
  6265. Value *Arg = I.getArgOperand(Idx)->stripPointerCasts();
  6266. if (isa<ConstantPointerNull>(Arg))
  6267. continue; // Skip null pointers. They represent a hole in index space.
  6268. AllocaInst *Slot = cast<AllocaInst>(Arg);
  6269. assert(FuncInfo.StaticAllocaMap.count(Slot) &&
  6270. "can only escape static allocas");
  6271. int FI = FuncInfo.StaticAllocaMap[Slot];
  6272. MCSymbol *FrameAllocSym =
  6273. MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
  6274. GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx);
  6275. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl,
  6276. TII->get(TargetOpcode::LOCAL_ESCAPE))
  6277. .addSym(FrameAllocSym)
  6278. .addFrameIndex(FI);
  6279. }
  6280. return;
  6281. }
  6282. case Intrinsic::localrecover: {
  6283. // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx)
  6284. MachineFunction &MF = DAG.getMachineFunction();
  6285. // Get the symbol that defines the frame offset.
  6286. auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts());
  6287. auto *Idx = cast<ConstantInt>(I.getArgOperand(2));
  6288. unsigned IdxVal =
  6289. unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max()));
  6290. MCSymbol *FrameAllocSym =
  6291. MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
  6292. GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal);
  6293. Value *FP = I.getArgOperand(1);
  6294. SDValue FPVal = getValue(FP);
  6295. EVT PtrVT = FPVal.getValueType();
  6296. // Create a MCSymbol for the label to avoid any target lowering
  6297. // that would make this PC relative.
  6298. SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT);
  6299. SDValue OffsetVal =
  6300. DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym);
  6301. // Add the offset to the FP.
  6302. SDValue Add = DAG.getMemBasePlusOffset(FPVal, OffsetVal, sdl);
  6303. setValue(&I, Add);
  6304. return;
  6305. }
  6306. case Intrinsic::eh_exceptionpointer:
  6307. case Intrinsic::eh_exceptioncode: {
  6308. // Get the exception pointer vreg, copy from it, and resize it to fit.
  6309. const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0));
  6310. MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
  6311. const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT);
  6312. unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC);
  6313. SDValue N = DAG.getCopyFromReg(DAG.getEntryNode(), sdl, VReg, PtrVT);
  6314. if (Intrinsic == Intrinsic::eh_exceptioncode)
  6315. N = DAG.getZExtOrTrunc(N, sdl, MVT::i32);
  6316. setValue(&I, N);
  6317. return;
  6318. }
  6319. case Intrinsic::xray_customevent: {
  6320. // Here we want to make sure that the intrinsic behaves as if it has a
  6321. // specific calling convention, and only for x86_64.
  6322. // FIXME: Support other platforms later.
  6323. const auto &Triple = DAG.getTarget().getTargetTriple();
  6324. if (Triple.getArch() != Triple::x86_64)
  6325. return;
  6326. SmallVector<SDValue, 8> Ops;
  6327. // We want to say that we always want the arguments in registers.
  6328. SDValue LogEntryVal = getValue(I.getArgOperand(0));
  6329. SDValue StrSizeVal = getValue(I.getArgOperand(1));
  6330. SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
  6331. SDValue Chain = getRoot();
  6332. Ops.push_back(LogEntryVal);
  6333. Ops.push_back(StrSizeVal);
  6334. Ops.push_back(Chain);
  6335. // We need to enforce the calling convention for the callsite, so that
  6336. // argument ordering is enforced correctly, and that register allocation can
  6337. // see that some registers may be assumed clobbered and have to preserve
  6338. // them across calls to the intrinsic.
  6339. MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL,
  6340. sdl, NodeTys, Ops);
  6341. SDValue patchableNode = SDValue(MN, 0);
  6342. DAG.setRoot(patchableNode);
  6343. setValue(&I, patchableNode);
  6344. return;
  6345. }
  6346. case Intrinsic::xray_typedevent: {
  6347. // Here we want to make sure that the intrinsic behaves as if it has a
  6348. // specific calling convention, and only for x86_64.
  6349. // FIXME: Support other platforms later.
  6350. const auto &Triple = DAG.getTarget().getTargetTriple();
  6351. if (Triple.getArch() != Triple::x86_64)
  6352. return;
  6353. SmallVector<SDValue, 8> Ops;
  6354. // We want to say that we always want the arguments in registers.
  6355. // It's unclear to me how manipulating the selection DAG here forces callers
  6356. // to provide arguments in registers instead of on the stack.
  6357. SDValue LogTypeId = getValue(I.getArgOperand(0));
  6358. SDValue LogEntryVal = getValue(I.getArgOperand(1));
  6359. SDValue StrSizeVal = getValue(I.getArgOperand(2));
  6360. SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
  6361. SDValue Chain = getRoot();
  6362. Ops.push_back(LogTypeId);
  6363. Ops.push_back(LogEntryVal);
  6364. Ops.push_back(StrSizeVal);
  6365. Ops.push_back(Chain);
  6366. // We need to enforce the calling convention for the callsite, so that
  6367. // argument ordering is enforced correctly, and that register allocation can
  6368. // see that some registers may be assumed clobbered and have to preserve
  6369. // them across calls to the intrinsic.
  6370. MachineSDNode *MN = DAG.getMachineNode(
  6371. TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, sdl, NodeTys, Ops);
  6372. SDValue patchableNode = SDValue(MN, 0);
  6373. DAG.setRoot(patchableNode);
  6374. setValue(&I, patchableNode);
  6375. return;
  6376. }
  6377. case Intrinsic::experimental_deoptimize:
  6378. LowerDeoptimizeCall(&I);
  6379. return;
  6380. case Intrinsic::experimental_stepvector:
  6381. visitStepVector(I);
  6382. return;
  6383. case Intrinsic::vector_reduce_fadd:
  6384. case Intrinsic::vector_reduce_fmul:
  6385. case Intrinsic::vector_reduce_add:
  6386. case Intrinsic::vector_reduce_mul:
  6387. case Intrinsic::vector_reduce_and:
  6388. case Intrinsic::vector_reduce_or:
  6389. case Intrinsic::vector_reduce_xor:
  6390. case Intrinsic::vector_reduce_smax:
  6391. case Intrinsic::vector_reduce_smin:
  6392. case Intrinsic::vector_reduce_umax:
  6393. case Intrinsic::vector_reduce_umin:
  6394. case Intrinsic::vector_reduce_fmax:
  6395. case Intrinsic::vector_reduce_fmin:
  6396. visitVectorReduce(I, Intrinsic);
  6397. return;
  6398. case Intrinsic::icall_branch_funnel: {
  6399. SmallVector<SDValue, 16> Ops;
  6400. Ops.push_back(getValue(I.getArgOperand(0)));
  6401. int64_t Offset;
  6402. auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
  6403. I.getArgOperand(1), Offset, DAG.getDataLayout()));
  6404. if (!Base)
  6405. report_fatal_error(
  6406. "llvm.icall.branch.funnel operand must be a GlobalValue");
  6407. Ops.push_back(DAG.getTargetGlobalAddress(Base, sdl, MVT::i64, 0));
  6408. struct BranchFunnelTarget {
  6409. int64_t Offset;
  6410. SDValue Target;
  6411. };
  6412. SmallVector<BranchFunnelTarget, 8> Targets;
  6413. for (unsigned Op = 1, N = I.arg_size(); Op != N; Op += 2) {
  6414. auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
  6415. I.getArgOperand(Op), Offset, DAG.getDataLayout()));
  6416. if (ElemBase != Base)
  6417. report_fatal_error("all llvm.icall.branch.funnel operands must refer "
  6418. "to the same GlobalValue");
  6419. SDValue Val = getValue(I.getArgOperand(Op + 1));
  6420. auto *GA = dyn_cast<GlobalAddressSDNode>(Val);
  6421. if (!GA)
  6422. report_fatal_error(
  6423. "llvm.icall.branch.funnel operand must be a GlobalValue");
  6424. Targets.push_back({Offset, DAG.getTargetGlobalAddress(
  6425. GA->getGlobal(), sdl, Val.getValueType(),
  6426. GA->getOffset())});
  6427. }
  6428. llvm::sort(Targets,
  6429. [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) {
  6430. return T1.Offset < T2.Offset;
  6431. });
  6432. for (auto &T : Targets) {
  6433. Ops.push_back(DAG.getTargetConstant(T.Offset, sdl, MVT::i32));
  6434. Ops.push_back(T.Target);
  6435. }
  6436. Ops.push_back(DAG.getRoot()); // Chain
  6437. SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL, sdl,
  6438. MVT::Other, Ops),
  6439. 0);
  6440. DAG.setRoot(N);
  6441. setValue(&I, N);
  6442. HasTailCall = true;
  6443. return;
  6444. }
  6445. case Intrinsic::wasm_landingpad_index:
  6446. // Information this intrinsic contained has been transferred to
  6447. // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely
  6448. // delete it now.
  6449. return;
  6450. case Intrinsic::aarch64_settag:
  6451. case Intrinsic::aarch64_settag_zero: {
  6452. const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
  6453. bool ZeroMemory = Intrinsic == Intrinsic::aarch64_settag_zero;
  6454. SDValue Val = TSI.EmitTargetCodeForSetTag(
  6455. DAG, sdl, getRoot(), getValue(I.getArgOperand(0)),
  6456. getValue(I.getArgOperand(1)), MachinePointerInfo(I.getArgOperand(0)),
  6457. ZeroMemory);
  6458. DAG.setRoot(Val);
  6459. setValue(&I, Val);
  6460. return;
  6461. }
  6462. case Intrinsic::ptrmask: {
  6463. SDValue Ptr = getValue(I.getOperand(0));
  6464. SDValue Const = getValue(I.getOperand(1));
  6465. EVT PtrVT = Ptr.getValueType();
  6466. setValue(&I, DAG.getNode(ISD::AND, sdl, PtrVT, Ptr,
  6467. DAG.getZExtOrTrunc(Const, sdl, PtrVT)));
  6468. return;
  6469. }
  6470. case Intrinsic::threadlocal_address: {
  6471. setValue(&I, getValue(I.getOperand(0)));
  6472. return;
  6473. }
  6474. case Intrinsic::get_active_lane_mask: {
  6475. EVT CCVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  6476. SDValue Index = getValue(I.getOperand(0));
  6477. EVT ElementVT = Index.getValueType();
  6478. if (!TLI.shouldExpandGetActiveLaneMask(CCVT, ElementVT)) {
  6479. visitTargetIntrinsic(I, Intrinsic);
  6480. return;
  6481. }
  6482. SDValue TripCount = getValue(I.getOperand(1));
  6483. auto VecTy = CCVT.changeVectorElementType(ElementVT);
  6484. SDValue VectorIndex = DAG.getSplat(VecTy, sdl, Index);
  6485. SDValue VectorTripCount = DAG.getSplat(VecTy, sdl, TripCount);
  6486. SDValue VectorStep = DAG.getStepVector(sdl, VecTy);
  6487. SDValue VectorInduction = DAG.getNode(
  6488. ISD::UADDSAT, sdl, VecTy, VectorIndex, VectorStep);
  6489. SDValue SetCC = DAG.getSetCC(sdl, CCVT, VectorInduction,
  6490. VectorTripCount, ISD::CondCode::SETULT);
  6491. setValue(&I, SetCC);
  6492. return;
  6493. }
  6494. case Intrinsic::vector_insert: {
  6495. SDValue Vec = getValue(I.getOperand(0));
  6496. SDValue SubVec = getValue(I.getOperand(1));
  6497. SDValue Index = getValue(I.getOperand(2));
  6498. // The intrinsic's index type is i64, but the SDNode requires an index type
  6499. // suitable for the target. Convert the index as required.
  6500. MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
  6501. if (Index.getValueType() != VectorIdxTy)
  6502. Index = DAG.getVectorIdxConstant(
  6503. cast<ConstantSDNode>(Index)->getZExtValue(), sdl);
  6504. EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  6505. setValue(&I, DAG.getNode(ISD::INSERT_SUBVECTOR, sdl, ResultVT, Vec, SubVec,
  6506. Index));
  6507. return;
  6508. }
  6509. case Intrinsic::vector_extract: {
  6510. SDValue Vec = getValue(I.getOperand(0));
  6511. SDValue Index = getValue(I.getOperand(1));
  6512. EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  6513. // The intrinsic's index type is i64, but the SDNode requires an index type
  6514. // suitable for the target. Convert the index as required.
  6515. MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
  6516. if (Index.getValueType() != VectorIdxTy)
  6517. Index = DAG.getVectorIdxConstant(
  6518. cast<ConstantSDNode>(Index)->getZExtValue(), sdl);
  6519. setValue(&I,
  6520. DAG.getNode(ISD::EXTRACT_SUBVECTOR, sdl, ResultVT, Vec, Index));
  6521. return;
  6522. }
  6523. case Intrinsic::experimental_vector_reverse:
  6524. visitVectorReverse(I);
  6525. return;
  6526. case Intrinsic::experimental_vector_splice:
  6527. visitVectorSplice(I);
  6528. return;
  6529. }
  6530. }
  6531. void SelectionDAGBuilder::visitConstrainedFPIntrinsic(
  6532. const ConstrainedFPIntrinsic &FPI) {
  6533. SDLoc sdl = getCurSDLoc();
  6534. // We do not need to serialize constrained FP intrinsics against
  6535. // each other or against (nonvolatile) loads, so they can be
  6536. // chained like loads.
  6537. SDValue Chain = DAG.getRoot();
  6538. SmallVector<SDValue, 4> Opers;
  6539. Opers.push_back(Chain);
  6540. if (FPI.isUnaryOp()) {
  6541. Opers.push_back(getValue(FPI.getArgOperand(0)));
  6542. } else if (FPI.isTernaryOp()) {
  6543. Opers.push_back(getValue(FPI.getArgOperand(0)));
  6544. Opers.push_back(getValue(FPI.getArgOperand(1)));
  6545. Opers.push_back(getValue(FPI.getArgOperand(2)));
  6546. } else {
  6547. Opers.push_back(getValue(FPI.getArgOperand(0)));
  6548. Opers.push_back(getValue(FPI.getArgOperand(1)));
  6549. }
  6550. auto pushOutChain = [this](SDValue Result, fp::ExceptionBehavior EB) {
  6551. assert(Result.getNode()->getNumValues() == 2);
  6552. // Push node to the appropriate list so that future instructions can be
  6553. // chained up correctly.
  6554. SDValue OutChain = Result.getValue(1);
  6555. switch (EB) {
  6556. case fp::ExceptionBehavior::ebIgnore:
  6557. // The only reason why ebIgnore nodes still need to be chained is that
  6558. // they might depend on the current rounding mode, and therefore must
  6559. // not be moved across instruction that may change that mode.
  6560. [[fallthrough]];
  6561. case fp::ExceptionBehavior::ebMayTrap:
  6562. // These must not be moved across calls or instructions that may change
  6563. // floating-point exception masks.
  6564. PendingConstrainedFP.push_back(OutChain);
  6565. break;
  6566. case fp::ExceptionBehavior::ebStrict:
  6567. // These must not be moved across calls or instructions that may change
  6568. // floating-point exception masks or read floating-point exception flags.
  6569. // In addition, they cannot be optimized out even if unused.
  6570. PendingConstrainedFPStrict.push_back(OutChain);
  6571. break;
  6572. }
  6573. };
  6574. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  6575. EVT VT = TLI.getValueType(DAG.getDataLayout(), FPI.getType());
  6576. SDVTList VTs = DAG.getVTList(VT, MVT::Other);
  6577. fp::ExceptionBehavior EB = *FPI.getExceptionBehavior();
  6578. SDNodeFlags Flags;
  6579. if (EB == fp::ExceptionBehavior::ebIgnore)
  6580. Flags.setNoFPExcept(true);
  6581. if (auto *FPOp = dyn_cast<FPMathOperator>(&FPI))
  6582. Flags.copyFMF(*FPOp);
  6583. unsigned Opcode;
  6584. switch (FPI.getIntrinsicID()) {
  6585. default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
  6586. #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \
  6587. case Intrinsic::INTRINSIC: \
  6588. Opcode = ISD::STRICT_##DAGN; \
  6589. break;
  6590. #include "llvm/IR/ConstrainedOps.def"
  6591. case Intrinsic::experimental_constrained_fmuladd: {
  6592. Opcode = ISD::STRICT_FMA;
  6593. // Break fmuladd into fmul and fadd.
  6594. if (TM.Options.AllowFPOpFusion == FPOpFusion::Strict ||
  6595. !TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
  6596. Opers.pop_back();
  6597. SDValue Mul = DAG.getNode(ISD::STRICT_FMUL, sdl, VTs, Opers, Flags);
  6598. pushOutChain(Mul, EB);
  6599. Opcode = ISD::STRICT_FADD;
  6600. Opers.clear();
  6601. Opers.push_back(Mul.getValue(1));
  6602. Opers.push_back(Mul.getValue(0));
  6603. Opers.push_back(getValue(FPI.getArgOperand(2)));
  6604. }
  6605. break;
  6606. }
  6607. }
  6608. // A few strict DAG nodes carry additional operands that are not
  6609. // set up by the default code above.
  6610. switch (Opcode) {
  6611. default: break;
  6612. case ISD::STRICT_FP_ROUND:
  6613. Opers.push_back(
  6614. DAG.getTargetConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())));
  6615. break;
  6616. case ISD::STRICT_FSETCC:
  6617. case ISD::STRICT_FSETCCS: {
  6618. auto *FPCmp = dyn_cast<ConstrainedFPCmpIntrinsic>(&FPI);
  6619. ISD::CondCode Condition = getFCmpCondCode(FPCmp->getPredicate());
  6620. if (TM.Options.NoNaNsFPMath)
  6621. Condition = getFCmpCodeWithoutNaN(Condition);
  6622. Opers.push_back(DAG.getCondCode(Condition));
  6623. break;
  6624. }
  6625. }
  6626. SDValue Result = DAG.getNode(Opcode, sdl, VTs, Opers, Flags);
  6627. pushOutChain(Result, EB);
  6628. SDValue FPResult = Result.getValue(0);
  6629. setValue(&FPI, FPResult);
  6630. }
  6631. static unsigned getISDForVPIntrinsic(const VPIntrinsic &VPIntrin) {
  6632. std::optional<unsigned> ResOPC;
  6633. switch (VPIntrin.getIntrinsicID()) {
  6634. case Intrinsic::vp_ctlz: {
  6635. bool IsZeroUndef = cast<ConstantInt>(VPIntrin.getArgOperand(3))->isOne();
  6636. ResOPC = IsZeroUndef ? ISD::VP_CTLZ_ZERO_UNDEF : ISD::VP_CTLZ;
  6637. break;
  6638. }
  6639. case Intrinsic::vp_cttz: {
  6640. bool IsZeroUndef = cast<ConstantInt>(VPIntrin.getArgOperand(3))->isOne();
  6641. ResOPC = IsZeroUndef ? ISD::VP_CTTZ_ZERO_UNDEF : ISD::VP_CTTZ;
  6642. break;
  6643. }
  6644. #define HELPER_MAP_VPID_TO_VPSD(VPID, VPSD) \
  6645. case Intrinsic::VPID: \
  6646. ResOPC = ISD::VPSD; \
  6647. break;
  6648. #include "llvm/IR/VPIntrinsics.def"
  6649. }
  6650. if (!ResOPC)
  6651. llvm_unreachable(
  6652. "Inconsistency: no SDNode available for this VPIntrinsic!");
  6653. if (*ResOPC == ISD::VP_REDUCE_SEQ_FADD ||
  6654. *ResOPC == ISD::VP_REDUCE_SEQ_FMUL) {
  6655. if (VPIntrin.getFastMathFlags().allowReassoc())
  6656. return *ResOPC == ISD::VP_REDUCE_SEQ_FADD ? ISD::VP_REDUCE_FADD
  6657. : ISD::VP_REDUCE_FMUL;
  6658. }
  6659. return *ResOPC;
  6660. }
  6661. void SelectionDAGBuilder::visitVPLoad(const VPIntrinsic &VPIntrin, EVT VT,
  6662. SmallVector<SDValue, 7> &OpValues) {
  6663. SDLoc DL = getCurSDLoc();
  6664. Value *PtrOperand = VPIntrin.getArgOperand(0);
  6665. MaybeAlign Alignment = VPIntrin.getPointerAlignment();
  6666. AAMDNodes AAInfo = VPIntrin.getAAMetadata();
  6667. const MDNode *Ranges = VPIntrin.getMetadata(LLVMContext::MD_range);
  6668. SDValue LD;
  6669. bool AddToChain = true;
  6670. // Do not serialize variable-length loads of constant memory with
  6671. // anything.
  6672. if (!Alignment)
  6673. Alignment = DAG.getEVTAlign(VT);
  6674. MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo);
  6675. AddToChain = !AA || !AA->pointsToConstantMemory(ML);
  6676. SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
  6677. MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
  6678. MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad,
  6679. MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges);
  6680. LD = DAG.getLoadVP(VT, DL, InChain, OpValues[0], OpValues[1], OpValues[2],
  6681. MMO, false /*IsExpanding */);
  6682. if (AddToChain)
  6683. PendingLoads.push_back(LD.getValue(1));
  6684. setValue(&VPIntrin, LD);
  6685. }
  6686. void SelectionDAGBuilder::visitVPGather(const VPIntrinsic &VPIntrin, EVT VT,
  6687. SmallVector<SDValue, 7> &OpValues) {
  6688. SDLoc DL = getCurSDLoc();
  6689. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  6690. Value *PtrOperand = VPIntrin.getArgOperand(0);
  6691. MaybeAlign Alignment = VPIntrin.getPointerAlignment();
  6692. AAMDNodes AAInfo = VPIntrin.getAAMetadata();
  6693. const MDNode *Ranges = VPIntrin.getMetadata(LLVMContext::MD_range);
  6694. SDValue LD;
  6695. if (!Alignment)
  6696. Alignment = DAG.getEVTAlign(VT.getScalarType());
  6697. unsigned AS =
  6698. PtrOperand->getType()->getScalarType()->getPointerAddressSpace();
  6699. MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
  6700. MachinePointerInfo(AS), MachineMemOperand::MOLoad,
  6701. MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges);
  6702. SDValue Base, Index, Scale;
  6703. ISD::MemIndexType IndexType;
  6704. bool UniformBase = getUniformBase(PtrOperand, Base, Index, IndexType, Scale,
  6705. this, VPIntrin.getParent(),
  6706. VT.getScalarStoreSize());
  6707. if (!UniformBase) {
  6708. Base = DAG.getConstant(0, DL, TLI.getPointerTy(DAG.getDataLayout()));
  6709. Index = getValue(PtrOperand);
  6710. IndexType = ISD::SIGNED_SCALED;
  6711. Scale = DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout()));
  6712. }
  6713. EVT IdxVT = Index.getValueType();
  6714. EVT EltTy = IdxVT.getVectorElementType();
  6715. if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
  6716. EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
  6717. Index = DAG.getNode(ISD::SIGN_EXTEND, DL, NewIdxVT, Index);
  6718. }
  6719. LD = DAG.getGatherVP(
  6720. DAG.getVTList(VT, MVT::Other), VT, DL,
  6721. {DAG.getRoot(), Base, Index, Scale, OpValues[1], OpValues[2]}, MMO,
  6722. IndexType);
  6723. PendingLoads.push_back(LD.getValue(1));
  6724. setValue(&VPIntrin, LD);
  6725. }
  6726. void SelectionDAGBuilder::visitVPStore(const VPIntrinsic &VPIntrin,
  6727. SmallVector<SDValue, 7> &OpValues) {
  6728. SDLoc DL = getCurSDLoc();
  6729. Value *PtrOperand = VPIntrin.getArgOperand(1);
  6730. EVT VT = OpValues[0].getValueType();
  6731. MaybeAlign Alignment = VPIntrin.getPointerAlignment();
  6732. AAMDNodes AAInfo = VPIntrin.getAAMetadata();
  6733. SDValue ST;
  6734. if (!Alignment)
  6735. Alignment = DAG.getEVTAlign(VT);
  6736. SDValue Ptr = OpValues[1];
  6737. SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
  6738. MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
  6739. MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore,
  6740. MemoryLocation::UnknownSize, *Alignment, AAInfo);
  6741. ST = DAG.getStoreVP(getMemoryRoot(), DL, OpValues[0], Ptr, Offset,
  6742. OpValues[2], OpValues[3], VT, MMO, ISD::UNINDEXED,
  6743. /* IsTruncating */ false, /*IsCompressing*/ false);
  6744. DAG.setRoot(ST);
  6745. setValue(&VPIntrin, ST);
  6746. }
  6747. void SelectionDAGBuilder::visitVPScatter(const VPIntrinsic &VPIntrin,
  6748. SmallVector<SDValue, 7> &OpValues) {
  6749. SDLoc DL = getCurSDLoc();
  6750. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  6751. Value *PtrOperand = VPIntrin.getArgOperand(1);
  6752. EVT VT = OpValues[0].getValueType();
  6753. MaybeAlign Alignment = VPIntrin.getPointerAlignment();
  6754. AAMDNodes AAInfo = VPIntrin.getAAMetadata();
  6755. SDValue ST;
  6756. if (!Alignment)
  6757. Alignment = DAG.getEVTAlign(VT.getScalarType());
  6758. unsigned AS =
  6759. PtrOperand->getType()->getScalarType()->getPointerAddressSpace();
  6760. MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
  6761. MachinePointerInfo(AS), MachineMemOperand::MOStore,
  6762. MemoryLocation::UnknownSize, *Alignment, AAInfo);
  6763. SDValue Base, Index, Scale;
  6764. ISD::MemIndexType IndexType;
  6765. bool UniformBase = getUniformBase(PtrOperand, Base, Index, IndexType, Scale,
  6766. this, VPIntrin.getParent(),
  6767. VT.getScalarStoreSize());
  6768. if (!UniformBase) {
  6769. Base = DAG.getConstant(0, DL, TLI.getPointerTy(DAG.getDataLayout()));
  6770. Index = getValue(PtrOperand);
  6771. IndexType = ISD::SIGNED_SCALED;
  6772. Scale =
  6773. DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout()));
  6774. }
  6775. EVT IdxVT = Index.getValueType();
  6776. EVT EltTy = IdxVT.getVectorElementType();
  6777. if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
  6778. EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
  6779. Index = DAG.getNode(ISD::SIGN_EXTEND, DL, NewIdxVT, Index);
  6780. }
  6781. ST = DAG.getScatterVP(DAG.getVTList(MVT::Other), VT, DL,
  6782. {getMemoryRoot(), OpValues[0], Base, Index, Scale,
  6783. OpValues[2], OpValues[3]},
  6784. MMO, IndexType);
  6785. DAG.setRoot(ST);
  6786. setValue(&VPIntrin, ST);
  6787. }
  6788. void SelectionDAGBuilder::visitVPStridedLoad(
  6789. const VPIntrinsic &VPIntrin, EVT VT, SmallVectorImpl<SDValue> &OpValues) {
  6790. SDLoc DL = getCurSDLoc();
  6791. Value *PtrOperand = VPIntrin.getArgOperand(0);
  6792. MaybeAlign Alignment = VPIntrin.getPointerAlignment();
  6793. if (!Alignment)
  6794. Alignment = DAG.getEVTAlign(VT.getScalarType());
  6795. AAMDNodes AAInfo = VPIntrin.getAAMetadata();
  6796. const MDNode *Ranges = VPIntrin.getMetadata(LLVMContext::MD_range);
  6797. MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo);
  6798. bool AddToChain = !AA || !AA->pointsToConstantMemory(ML);
  6799. SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
  6800. MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
  6801. MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad,
  6802. MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges);
  6803. SDValue LD = DAG.getStridedLoadVP(VT, DL, InChain, OpValues[0], OpValues[1],
  6804. OpValues[2], OpValues[3], MMO,
  6805. false /*IsExpanding*/);
  6806. if (AddToChain)
  6807. PendingLoads.push_back(LD.getValue(1));
  6808. setValue(&VPIntrin, LD);
  6809. }
  6810. void SelectionDAGBuilder::visitVPStridedStore(
  6811. const VPIntrinsic &VPIntrin, SmallVectorImpl<SDValue> &OpValues) {
  6812. SDLoc DL = getCurSDLoc();
  6813. Value *PtrOperand = VPIntrin.getArgOperand(1);
  6814. EVT VT = OpValues[0].getValueType();
  6815. MaybeAlign Alignment = VPIntrin.getPointerAlignment();
  6816. if (!Alignment)
  6817. Alignment = DAG.getEVTAlign(VT.getScalarType());
  6818. AAMDNodes AAInfo = VPIntrin.getAAMetadata();
  6819. MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
  6820. MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore,
  6821. MemoryLocation::UnknownSize, *Alignment, AAInfo);
  6822. SDValue ST = DAG.getStridedStoreVP(
  6823. getMemoryRoot(), DL, OpValues[0], OpValues[1],
  6824. DAG.getUNDEF(OpValues[1].getValueType()), OpValues[2], OpValues[3],
  6825. OpValues[4], VT, MMO, ISD::UNINDEXED, /*IsTruncating*/ false,
  6826. /*IsCompressing*/ false);
  6827. DAG.setRoot(ST);
  6828. setValue(&VPIntrin, ST);
  6829. }
  6830. void SelectionDAGBuilder::visitVPCmp(const VPCmpIntrinsic &VPIntrin) {
  6831. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  6832. SDLoc DL = getCurSDLoc();
  6833. ISD::CondCode Condition;
  6834. CmpInst::Predicate CondCode = VPIntrin.getPredicate();
  6835. bool IsFP = VPIntrin.getOperand(0)->getType()->isFPOrFPVectorTy();
  6836. if (IsFP) {
  6837. // FIXME: Regular fcmps are FPMathOperators which may have fast-math (nnan)
  6838. // flags, but calls that don't return floating-point types can't be
  6839. // FPMathOperators, like vp.fcmp. This affects constrained fcmp too.
  6840. Condition = getFCmpCondCode(CondCode);
  6841. if (TM.Options.NoNaNsFPMath)
  6842. Condition = getFCmpCodeWithoutNaN(Condition);
  6843. } else {
  6844. Condition = getICmpCondCode(CondCode);
  6845. }
  6846. SDValue Op1 = getValue(VPIntrin.getOperand(0));
  6847. SDValue Op2 = getValue(VPIntrin.getOperand(1));
  6848. // #2 is the condition code
  6849. SDValue MaskOp = getValue(VPIntrin.getOperand(3));
  6850. SDValue EVL = getValue(VPIntrin.getOperand(4));
  6851. MVT EVLParamVT = TLI.getVPExplicitVectorLengthTy();
  6852. assert(EVLParamVT.isScalarInteger() && EVLParamVT.bitsGE(MVT::i32) &&
  6853. "Unexpected target EVL type");
  6854. EVL = DAG.getNode(ISD::ZERO_EXTEND, DL, EVLParamVT, EVL);
  6855. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  6856. VPIntrin.getType());
  6857. setValue(&VPIntrin,
  6858. DAG.getSetCCVP(DL, DestVT, Op1, Op2, Condition, MaskOp, EVL));
  6859. }
  6860. void SelectionDAGBuilder::visitVectorPredicationIntrinsic(
  6861. const VPIntrinsic &VPIntrin) {
  6862. SDLoc DL = getCurSDLoc();
  6863. unsigned Opcode = getISDForVPIntrinsic(VPIntrin);
  6864. auto IID = VPIntrin.getIntrinsicID();
  6865. if (const auto *CmpI = dyn_cast<VPCmpIntrinsic>(&VPIntrin))
  6866. return visitVPCmp(*CmpI);
  6867. SmallVector<EVT, 4> ValueVTs;
  6868. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  6869. ComputeValueVTs(TLI, DAG.getDataLayout(), VPIntrin.getType(), ValueVTs);
  6870. SDVTList VTs = DAG.getVTList(ValueVTs);
  6871. auto EVLParamPos = VPIntrinsic::getVectorLengthParamPos(IID);
  6872. MVT EVLParamVT = TLI.getVPExplicitVectorLengthTy();
  6873. assert(EVLParamVT.isScalarInteger() && EVLParamVT.bitsGE(MVT::i32) &&
  6874. "Unexpected target EVL type");
  6875. // Request operands.
  6876. SmallVector<SDValue, 7> OpValues;
  6877. for (unsigned I = 0; I < VPIntrin.arg_size(); ++I) {
  6878. auto Op = getValue(VPIntrin.getArgOperand(I));
  6879. if (I == EVLParamPos)
  6880. Op = DAG.getNode(ISD::ZERO_EXTEND, DL, EVLParamVT, Op);
  6881. OpValues.push_back(Op);
  6882. }
  6883. switch (Opcode) {
  6884. default: {
  6885. SDNodeFlags SDFlags;
  6886. if (auto *FPMO = dyn_cast<FPMathOperator>(&VPIntrin))
  6887. SDFlags.copyFMF(*FPMO);
  6888. SDValue Result = DAG.getNode(Opcode, DL, VTs, OpValues, SDFlags);
  6889. setValue(&VPIntrin, Result);
  6890. break;
  6891. }
  6892. case ISD::VP_LOAD:
  6893. visitVPLoad(VPIntrin, ValueVTs[0], OpValues);
  6894. break;
  6895. case ISD::VP_GATHER:
  6896. visitVPGather(VPIntrin, ValueVTs[0], OpValues);
  6897. break;
  6898. case ISD::EXPERIMENTAL_VP_STRIDED_LOAD:
  6899. visitVPStridedLoad(VPIntrin, ValueVTs[0], OpValues);
  6900. break;
  6901. case ISD::VP_STORE:
  6902. visitVPStore(VPIntrin, OpValues);
  6903. break;
  6904. case ISD::VP_SCATTER:
  6905. visitVPScatter(VPIntrin, OpValues);
  6906. break;
  6907. case ISD::EXPERIMENTAL_VP_STRIDED_STORE:
  6908. visitVPStridedStore(VPIntrin, OpValues);
  6909. break;
  6910. case ISD::VP_FMULADD: {
  6911. assert(OpValues.size() == 5 && "Unexpected number of operands");
  6912. SDNodeFlags SDFlags;
  6913. if (auto *FPMO = dyn_cast<FPMathOperator>(&VPIntrin))
  6914. SDFlags.copyFMF(*FPMO);
  6915. if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
  6916. TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), ValueVTs[0])) {
  6917. setValue(&VPIntrin, DAG.getNode(ISD::VP_FMA, DL, VTs, OpValues, SDFlags));
  6918. } else {
  6919. SDValue Mul = DAG.getNode(
  6920. ISD::VP_FMUL, DL, VTs,
  6921. {OpValues[0], OpValues[1], OpValues[3], OpValues[4]}, SDFlags);
  6922. SDValue Add =
  6923. DAG.getNode(ISD::VP_FADD, DL, VTs,
  6924. {Mul, OpValues[2], OpValues[3], OpValues[4]}, SDFlags);
  6925. setValue(&VPIntrin, Add);
  6926. }
  6927. break;
  6928. }
  6929. case ISD::VP_INTTOPTR: {
  6930. SDValue N = OpValues[0];
  6931. EVT DestVT = TLI.getValueType(DAG.getDataLayout(), VPIntrin.getType());
  6932. EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), VPIntrin.getType());
  6933. N = DAG.getVPPtrExtOrTrunc(getCurSDLoc(), DestVT, N, OpValues[1],
  6934. OpValues[2]);
  6935. N = DAG.getVPZExtOrTrunc(getCurSDLoc(), PtrMemVT, N, OpValues[1],
  6936. OpValues[2]);
  6937. setValue(&VPIntrin, N);
  6938. break;
  6939. }
  6940. case ISD::VP_PTRTOINT: {
  6941. SDValue N = OpValues[0];
  6942. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  6943. VPIntrin.getType());
  6944. EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(),
  6945. VPIntrin.getOperand(0)->getType());
  6946. N = DAG.getVPPtrExtOrTrunc(getCurSDLoc(), PtrMemVT, N, OpValues[1],
  6947. OpValues[2]);
  6948. N = DAG.getVPZExtOrTrunc(getCurSDLoc(), DestVT, N, OpValues[1],
  6949. OpValues[2]);
  6950. setValue(&VPIntrin, N);
  6951. break;
  6952. }
  6953. case ISD::VP_ABS:
  6954. case ISD::VP_CTLZ:
  6955. case ISD::VP_CTLZ_ZERO_UNDEF:
  6956. case ISD::VP_CTTZ:
  6957. case ISD::VP_CTTZ_ZERO_UNDEF: {
  6958. // Pop is_zero_poison operand for cp.ctlz/cttz or
  6959. // is_int_min_poison operand for vp.abs.
  6960. OpValues.pop_back();
  6961. SDValue Result = DAG.getNode(Opcode, DL, VTs, OpValues);
  6962. setValue(&VPIntrin, Result);
  6963. break;
  6964. }
  6965. }
  6966. }
  6967. SDValue SelectionDAGBuilder::lowerStartEH(SDValue Chain,
  6968. const BasicBlock *EHPadBB,
  6969. MCSymbol *&BeginLabel) {
  6970. MachineFunction &MF = DAG.getMachineFunction();
  6971. MachineModuleInfo &MMI = MF.getMMI();
  6972. // Insert a label before the invoke call to mark the try range. This can be
  6973. // used to detect deletion of the invoke via the MachineModuleInfo.
  6974. BeginLabel = MMI.getContext().createTempSymbol();
  6975. // For SjLj, keep track of which landing pads go with which invokes
  6976. // so as to maintain the ordering of pads in the LSDA.
  6977. unsigned CallSiteIndex = MMI.getCurrentCallSite();
  6978. if (CallSiteIndex) {
  6979. MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex);
  6980. LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex);
  6981. // Now that the call site is handled, stop tracking it.
  6982. MMI.setCurrentCallSite(0);
  6983. }
  6984. return DAG.getEHLabel(getCurSDLoc(), Chain, BeginLabel);
  6985. }
  6986. SDValue SelectionDAGBuilder::lowerEndEH(SDValue Chain, const InvokeInst *II,
  6987. const BasicBlock *EHPadBB,
  6988. MCSymbol *BeginLabel) {
  6989. assert(BeginLabel && "BeginLabel should've been set");
  6990. MachineFunction &MF = DAG.getMachineFunction();
  6991. MachineModuleInfo &MMI = MF.getMMI();
  6992. // Insert a label at the end of the invoke call to mark the try range. This
  6993. // can be used to detect deletion of the invoke via the MachineModuleInfo.
  6994. MCSymbol *EndLabel = MMI.getContext().createTempSymbol();
  6995. Chain = DAG.getEHLabel(getCurSDLoc(), Chain, EndLabel);
  6996. // Inform MachineModuleInfo of range.
  6997. auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
  6998. // There is a platform (e.g. wasm) that uses funclet style IR but does not
  6999. // actually use outlined funclets and their LSDA info style.
  7000. if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) {
  7001. assert(II && "II should've been set");
  7002. WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo();
  7003. EHInfo->addIPToStateRange(II, BeginLabel, EndLabel);
  7004. } else if (!isScopedEHPersonality(Pers)) {
  7005. assert(EHPadBB);
  7006. MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel);
  7007. }
  7008. return Chain;
  7009. }
  7010. std::pair<SDValue, SDValue>
  7011. SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI,
  7012. const BasicBlock *EHPadBB) {
  7013. MCSymbol *BeginLabel = nullptr;
  7014. if (EHPadBB) {
  7015. // Both PendingLoads and PendingExports must be flushed here;
  7016. // this call might not return.
  7017. (void)getRoot();
  7018. DAG.setRoot(lowerStartEH(getControlRoot(), EHPadBB, BeginLabel));
  7019. CLI.setChain(getRoot());
  7020. }
  7021. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  7022. std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
  7023. assert((CLI.IsTailCall || Result.second.getNode()) &&
  7024. "Non-null chain expected with non-tail call!");
  7025. assert((Result.second.getNode() || !Result.first.getNode()) &&
  7026. "Null value expected with tail call!");
  7027. if (!Result.second.getNode()) {
  7028. // As a special case, a null chain means that a tail call has been emitted
  7029. // and the DAG root is already updated.
  7030. HasTailCall = true;
  7031. // Since there's no actual continuation from this block, nothing can be
  7032. // relying on us setting vregs for them.
  7033. PendingExports.clear();
  7034. } else {
  7035. DAG.setRoot(Result.second);
  7036. }
  7037. if (EHPadBB) {
  7038. DAG.setRoot(lowerEndEH(getRoot(), cast_or_null<InvokeInst>(CLI.CB), EHPadBB,
  7039. BeginLabel));
  7040. }
  7041. return Result;
  7042. }
  7043. void SelectionDAGBuilder::LowerCallTo(const CallBase &CB, SDValue Callee,
  7044. bool isTailCall,
  7045. bool isMustTailCall,
  7046. const BasicBlock *EHPadBB) {
  7047. auto &DL = DAG.getDataLayout();
  7048. FunctionType *FTy = CB.getFunctionType();
  7049. Type *RetTy = CB.getType();
  7050. TargetLowering::ArgListTy Args;
  7051. Args.reserve(CB.arg_size());
  7052. const Value *SwiftErrorVal = nullptr;
  7053. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  7054. if (isTailCall) {
  7055. // Avoid emitting tail calls in functions with the disable-tail-calls
  7056. // attribute.
  7057. auto *Caller = CB.getParent()->getParent();
  7058. if (Caller->getFnAttribute("disable-tail-calls").getValueAsString() ==
  7059. "true" && !isMustTailCall)
  7060. isTailCall = false;
  7061. // We can't tail call inside a function with a swifterror argument. Lowering
  7062. // does not support this yet. It would have to move into the swifterror
  7063. // register before the call.
  7064. if (TLI.supportSwiftError() &&
  7065. Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError))
  7066. isTailCall = false;
  7067. }
  7068. for (auto I = CB.arg_begin(), E = CB.arg_end(); I != E; ++I) {
  7069. TargetLowering::ArgListEntry Entry;
  7070. const Value *V = *I;
  7071. // Skip empty types
  7072. if (V->getType()->isEmptyTy())
  7073. continue;
  7074. SDValue ArgNode = getValue(V);
  7075. Entry.Node = ArgNode; Entry.Ty = V->getType();
  7076. Entry.setAttributes(&CB, I - CB.arg_begin());
  7077. // Use swifterror virtual register as input to the call.
  7078. if (Entry.IsSwiftError && TLI.supportSwiftError()) {
  7079. SwiftErrorVal = V;
  7080. // We find the virtual register for the actual swifterror argument.
  7081. // Instead of using the Value, we use the virtual register instead.
  7082. Entry.Node =
  7083. DAG.getRegister(SwiftError.getOrCreateVRegUseAt(&CB, FuncInfo.MBB, V),
  7084. EVT(TLI.getPointerTy(DL)));
  7085. }
  7086. Args.push_back(Entry);
  7087. // If we have an explicit sret argument that is an Instruction, (i.e., it
  7088. // might point to function-local memory), we can't meaningfully tail-call.
  7089. if (Entry.IsSRet && isa<Instruction>(V))
  7090. isTailCall = false;
  7091. }
  7092. // If call site has a cfguardtarget operand bundle, create and add an
  7093. // additional ArgListEntry.
  7094. if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_cfguardtarget)) {
  7095. TargetLowering::ArgListEntry Entry;
  7096. Value *V = Bundle->Inputs[0];
  7097. SDValue ArgNode = getValue(V);
  7098. Entry.Node = ArgNode;
  7099. Entry.Ty = V->getType();
  7100. Entry.IsCFGuardTarget = true;
  7101. Args.push_back(Entry);
  7102. }
  7103. // Check if target-independent constraints permit a tail call here.
  7104. // Target-dependent constraints are checked within TLI->LowerCallTo.
  7105. if (isTailCall && !isInTailCallPosition(CB, DAG.getTarget()))
  7106. isTailCall = false;
  7107. // Disable tail calls if there is an swifterror argument. Targets have not
  7108. // been updated to support tail calls.
  7109. if (TLI.supportSwiftError() && SwiftErrorVal)
  7110. isTailCall = false;
  7111. ConstantInt *CFIType = nullptr;
  7112. if (CB.isIndirectCall()) {
  7113. if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_kcfi)) {
  7114. if (!TLI.supportKCFIBundles())
  7115. report_fatal_error(
  7116. "Target doesn't support calls with kcfi operand bundles.");
  7117. CFIType = cast<ConstantInt>(Bundle->Inputs[0]);
  7118. assert(CFIType->getType()->isIntegerTy(32) && "Invalid CFI type");
  7119. }
  7120. }
  7121. TargetLowering::CallLoweringInfo CLI(DAG);
  7122. CLI.setDebugLoc(getCurSDLoc())
  7123. .setChain(getRoot())
  7124. .setCallee(RetTy, FTy, Callee, std::move(Args), CB)
  7125. .setTailCall(isTailCall)
  7126. .setConvergent(CB.isConvergent())
  7127. .setIsPreallocated(
  7128. CB.countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0)
  7129. .setCFIType(CFIType);
  7130. std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
  7131. if (Result.first.getNode()) {
  7132. Result.first = lowerRangeToAssertZExt(DAG, CB, Result.first);
  7133. setValue(&CB, Result.first);
  7134. }
  7135. // The last element of CLI.InVals has the SDValue for swifterror return.
  7136. // Here we copy it to a virtual register and update SwiftErrorMap for
  7137. // book-keeping.
  7138. if (SwiftErrorVal && TLI.supportSwiftError()) {
  7139. // Get the last element of InVals.
  7140. SDValue Src = CLI.InVals.back();
  7141. Register VReg =
  7142. SwiftError.getOrCreateVRegDefAt(&CB, FuncInfo.MBB, SwiftErrorVal);
  7143. SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src);
  7144. DAG.setRoot(CopyNode);
  7145. }
  7146. }
  7147. static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT,
  7148. SelectionDAGBuilder &Builder) {
  7149. // Check to see if this load can be trivially constant folded, e.g. if the
  7150. // input is from a string literal.
  7151. if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) {
  7152. // Cast pointer to the type we really want to load.
  7153. Type *LoadTy =
  7154. Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits());
  7155. if (LoadVT.isVector())
  7156. LoadTy = FixedVectorType::get(LoadTy, LoadVT.getVectorNumElements());
  7157. LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput),
  7158. PointerType::getUnqual(LoadTy));
  7159. if (const Constant *LoadCst =
  7160. ConstantFoldLoadFromConstPtr(const_cast<Constant *>(LoadInput),
  7161. LoadTy, Builder.DAG.getDataLayout()))
  7162. return Builder.getValue(LoadCst);
  7163. }
  7164. // Otherwise, we have to emit the load. If the pointer is to unfoldable but
  7165. // still constant memory, the input chain can be the entry node.
  7166. SDValue Root;
  7167. bool ConstantMemory = false;
  7168. // Do not serialize (non-volatile) loads of constant memory with anything.
  7169. if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) {
  7170. Root = Builder.DAG.getEntryNode();
  7171. ConstantMemory = true;
  7172. } else {
  7173. // Do not serialize non-volatile loads against each other.
  7174. Root = Builder.DAG.getRoot();
  7175. }
  7176. SDValue Ptr = Builder.getValue(PtrVal);
  7177. SDValue LoadVal =
  7178. Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root, Ptr,
  7179. MachinePointerInfo(PtrVal), Align(1));
  7180. if (!ConstantMemory)
  7181. Builder.PendingLoads.push_back(LoadVal.getValue(1));
  7182. return LoadVal;
  7183. }
  7184. /// Record the value for an instruction that produces an integer result,
  7185. /// converting the type where necessary.
  7186. void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I,
  7187. SDValue Value,
  7188. bool IsSigned) {
  7189. EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  7190. I.getType(), true);
  7191. if (IsSigned)
  7192. Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT);
  7193. else
  7194. Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT);
  7195. setValue(&I, Value);
  7196. }
  7197. /// See if we can lower a memcmp/bcmp call into an optimized form. If so, return
  7198. /// true and lower it. Otherwise return false, and it will be lowered like a
  7199. /// normal call.
  7200. /// The caller already checked that \p I calls the appropriate LibFunc with a
  7201. /// correct prototype.
  7202. bool SelectionDAGBuilder::visitMemCmpBCmpCall(const CallInst &I) {
  7203. const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1);
  7204. const Value *Size = I.getArgOperand(2);
  7205. const ConstantSDNode *CSize = dyn_cast<ConstantSDNode>(getValue(Size));
  7206. if (CSize && CSize->getZExtValue() == 0) {
  7207. EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  7208. I.getType(), true);
  7209. setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT));
  7210. return true;
  7211. }
  7212. const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
  7213. std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp(
  7214. DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS),
  7215. getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS));
  7216. if (Res.first.getNode()) {
  7217. processIntegerCallValue(I, Res.first, true);
  7218. PendingLoads.push_back(Res.second);
  7219. return true;
  7220. }
  7221. // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS) != 0
  7222. // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS) != 0
  7223. if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I))
  7224. return false;
  7225. // If the target has a fast compare for the given size, it will return a
  7226. // preferred load type for that size. Require that the load VT is legal and
  7227. // that the target supports unaligned loads of that type. Otherwise, return
  7228. // INVALID.
  7229. auto hasFastLoadsAndCompare = [&](unsigned NumBits) {
  7230. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  7231. MVT LVT = TLI.hasFastEqualityCompare(NumBits);
  7232. if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) {
  7233. // TODO: Handle 5 byte compare as 4-byte + 1 byte.
  7234. // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
  7235. // TODO: Check alignment of src and dest ptrs.
  7236. unsigned DstAS = LHS->getType()->getPointerAddressSpace();
  7237. unsigned SrcAS = RHS->getType()->getPointerAddressSpace();
  7238. if (!TLI.isTypeLegal(LVT) ||
  7239. !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) ||
  7240. !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS))
  7241. LVT = MVT::INVALID_SIMPLE_VALUE_TYPE;
  7242. }
  7243. return LVT;
  7244. };
  7245. // This turns into unaligned loads. We only do this if the target natively
  7246. // supports the MVT we'll be loading or if it is small enough (<= 4) that
  7247. // we'll only produce a small number of byte loads.
  7248. MVT LoadVT;
  7249. unsigned NumBitsToCompare = CSize->getZExtValue() * 8;
  7250. switch (NumBitsToCompare) {
  7251. default:
  7252. return false;
  7253. case 16:
  7254. LoadVT = MVT::i16;
  7255. break;
  7256. case 32:
  7257. LoadVT = MVT::i32;
  7258. break;
  7259. case 64:
  7260. case 128:
  7261. case 256:
  7262. LoadVT = hasFastLoadsAndCompare(NumBitsToCompare);
  7263. break;
  7264. }
  7265. if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE)
  7266. return false;
  7267. SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this);
  7268. SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this);
  7269. // Bitcast to a wide integer type if the loads are vectors.
  7270. if (LoadVT.isVector()) {
  7271. EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits());
  7272. LoadL = DAG.getBitcast(CmpVT, LoadL);
  7273. LoadR = DAG.getBitcast(CmpVT, LoadR);
  7274. }
  7275. SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE);
  7276. processIntegerCallValue(I, Cmp, false);
  7277. return true;
  7278. }
  7279. /// See if we can lower a memchr call into an optimized form. If so, return
  7280. /// true and lower it. Otherwise return false, and it will be lowered like a
  7281. /// normal call.
  7282. /// The caller already checked that \p I calls the appropriate LibFunc with a
  7283. /// correct prototype.
  7284. bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) {
  7285. const Value *Src = I.getArgOperand(0);
  7286. const Value *Char = I.getArgOperand(1);
  7287. const Value *Length = I.getArgOperand(2);
  7288. const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
  7289. std::pair<SDValue, SDValue> Res =
  7290. TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(),
  7291. getValue(Src), getValue(Char), getValue(Length),
  7292. MachinePointerInfo(Src));
  7293. if (Res.first.getNode()) {
  7294. setValue(&I, Res.first);
  7295. PendingLoads.push_back(Res.second);
  7296. return true;
  7297. }
  7298. return false;
  7299. }
  7300. /// See if we can lower a mempcpy call into an optimized form. If so, return
  7301. /// true and lower it. Otherwise return false, and it will be lowered like a
  7302. /// normal call.
  7303. /// The caller already checked that \p I calls the appropriate LibFunc with a
  7304. /// correct prototype.
  7305. bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) {
  7306. SDValue Dst = getValue(I.getArgOperand(0));
  7307. SDValue Src = getValue(I.getArgOperand(1));
  7308. SDValue Size = getValue(I.getArgOperand(2));
  7309. Align DstAlign = DAG.InferPtrAlign(Dst).valueOrOne();
  7310. Align SrcAlign = DAG.InferPtrAlign(Src).valueOrOne();
  7311. // DAG::getMemcpy needs Alignment to be defined.
  7312. Align Alignment = std::min(DstAlign, SrcAlign);
  7313. bool isVol = false;
  7314. SDLoc sdl = getCurSDLoc();
  7315. // In the mempcpy context we need to pass in a false value for isTailCall
  7316. // because the return pointer needs to be adjusted by the size of
  7317. // the copied memory.
  7318. SDValue Root = isVol ? getRoot() : getMemoryRoot();
  7319. SDValue MC = DAG.getMemcpy(Root, sdl, Dst, Src, Size, Alignment, isVol, false,
  7320. /*isTailCall=*/false,
  7321. MachinePointerInfo(I.getArgOperand(0)),
  7322. MachinePointerInfo(I.getArgOperand(1)),
  7323. I.getAAMetadata());
  7324. assert(MC.getNode() != nullptr &&
  7325. "** memcpy should not be lowered as TailCall in mempcpy context **");
  7326. DAG.setRoot(MC);
  7327. // Check if Size needs to be truncated or extended.
  7328. Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType());
  7329. // Adjust return pointer to point just past the last dst byte.
  7330. SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(),
  7331. Dst, Size);
  7332. setValue(&I, DstPlusSize);
  7333. return true;
  7334. }
  7335. /// See if we can lower a strcpy call into an optimized form. If so, return
  7336. /// true and lower it, otherwise return false and it will be lowered like a
  7337. /// normal call.
  7338. /// The caller already checked that \p I calls the appropriate LibFunc with a
  7339. /// correct prototype.
  7340. bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) {
  7341. const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
  7342. const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
  7343. std::pair<SDValue, SDValue> Res =
  7344. TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(),
  7345. getValue(Arg0), getValue(Arg1),
  7346. MachinePointerInfo(Arg0),
  7347. MachinePointerInfo(Arg1), isStpcpy);
  7348. if (Res.first.getNode()) {
  7349. setValue(&I, Res.first);
  7350. DAG.setRoot(Res.second);
  7351. return true;
  7352. }
  7353. return false;
  7354. }
  7355. /// See if we can lower a strcmp call into an optimized form. If so, return
  7356. /// true and lower it, otherwise return false and it will be lowered like a
  7357. /// normal call.
  7358. /// The caller already checked that \p I calls the appropriate LibFunc with a
  7359. /// correct prototype.
  7360. bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) {
  7361. const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
  7362. const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
  7363. std::pair<SDValue, SDValue> Res =
  7364. TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(),
  7365. getValue(Arg0), getValue(Arg1),
  7366. MachinePointerInfo(Arg0),
  7367. MachinePointerInfo(Arg1));
  7368. if (Res.first.getNode()) {
  7369. processIntegerCallValue(I, Res.first, true);
  7370. PendingLoads.push_back(Res.second);
  7371. return true;
  7372. }
  7373. return false;
  7374. }
  7375. /// See if we can lower a strlen call into an optimized form. If so, return
  7376. /// true and lower it, otherwise return false and it will be lowered like a
  7377. /// normal call.
  7378. /// The caller already checked that \p I calls the appropriate LibFunc with a
  7379. /// correct prototype.
  7380. bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) {
  7381. const Value *Arg0 = I.getArgOperand(0);
  7382. const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
  7383. std::pair<SDValue, SDValue> Res =
  7384. TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(),
  7385. getValue(Arg0), MachinePointerInfo(Arg0));
  7386. if (Res.first.getNode()) {
  7387. processIntegerCallValue(I, Res.first, false);
  7388. PendingLoads.push_back(Res.second);
  7389. return true;
  7390. }
  7391. return false;
  7392. }
  7393. /// See if we can lower a strnlen call into an optimized form. If so, return
  7394. /// true and lower it, otherwise return false and it will be lowered like a
  7395. /// normal call.
  7396. /// The caller already checked that \p I calls the appropriate LibFunc with a
  7397. /// correct prototype.
  7398. bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) {
  7399. const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
  7400. const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
  7401. std::pair<SDValue, SDValue> Res =
  7402. TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(),
  7403. getValue(Arg0), getValue(Arg1),
  7404. MachinePointerInfo(Arg0));
  7405. if (Res.first.getNode()) {
  7406. processIntegerCallValue(I, Res.first, false);
  7407. PendingLoads.push_back(Res.second);
  7408. return true;
  7409. }
  7410. return false;
  7411. }
  7412. /// See if we can lower a unary floating-point operation into an SDNode with
  7413. /// the specified Opcode. If so, return true and lower it, otherwise return
  7414. /// false and it will be lowered like a normal call.
  7415. /// The caller already checked that \p I calls the appropriate LibFunc with a
  7416. /// correct prototype.
  7417. bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I,
  7418. unsigned Opcode) {
  7419. // We already checked this call's prototype; verify it doesn't modify errno.
  7420. if (!I.onlyReadsMemory())
  7421. return false;
  7422. SDNodeFlags Flags;
  7423. Flags.copyFMF(cast<FPMathOperator>(I));
  7424. SDValue Tmp = getValue(I.getArgOperand(0));
  7425. setValue(&I,
  7426. DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp, Flags));
  7427. return true;
  7428. }
  7429. /// See if we can lower a binary floating-point operation into an SDNode with
  7430. /// the specified Opcode. If so, return true and lower it. Otherwise return
  7431. /// false, and it will be lowered like a normal call.
  7432. /// The caller already checked that \p I calls the appropriate LibFunc with a
  7433. /// correct prototype.
  7434. bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I,
  7435. unsigned Opcode) {
  7436. // We already checked this call's prototype; verify it doesn't modify errno.
  7437. if (!I.onlyReadsMemory())
  7438. return false;
  7439. SDNodeFlags Flags;
  7440. Flags.copyFMF(cast<FPMathOperator>(I));
  7441. SDValue Tmp0 = getValue(I.getArgOperand(0));
  7442. SDValue Tmp1 = getValue(I.getArgOperand(1));
  7443. EVT VT = Tmp0.getValueType();
  7444. setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1, Flags));
  7445. return true;
  7446. }
  7447. void SelectionDAGBuilder::visitCall(const CallInst &I) {
  7448. // Handle inline assembly differently.
  7449. if (I.isInlineAsm()) {
  7450. visitInlineAsm(I);
  7451. return;
  7452. }
  7453. diagnoseDontCall(I);
  7454. if (Function *F = I.getCalledFunction()) {
  7455. if (F->isDeclaration()) {
  7456. // Is this an LLVM intrinsic or a target-specific intrinsic?
  7457. unsigned IID = F->getIntrinsicID();
  7458. if (!IID)
  7459. if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo())
  7460. IID = II->getIntrinsicID(F);
  7461. if (IID) {
  7462. visitIntrinsicCall(I, IID);
  7463. return;
  7464. }
  7465. }
  7466. // Check for well-known libc/libm calls. If the function is internal, it
  7467. // can't be a library call. Don't do the check if marked as nobuiltin for
  7468. // some reason or the call site requires strict floating point semantics.
  7469. LibFunc Func;
  7470. if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() &&
  7471. F->hasName() && LibInfo->getLibFunc(*F, Func) &&
  7472. LibInfo->hasOptimizedCodeGen(Func)) {
  7473. switch (Func) {
  7474. default: break;
  7475. case LibFunc_bcmp:
  7476. if (visitMemCmpBCmpCall(I))
  7477. return;
  7478. break;
  7479. case LibFunc_copysign:
  7480. case LibFunc_copysignf:
  7481. case LibFunc_copysignl:
  7482. // We already checked this call's prototype; verify it doesn't modify
  7483. // errno.
  7484. if (I.onlyReadsMemory()) {
  7485. SDValue LHS = getValue(I.getArgOperand(0));
  7486. SDValue RHS = getValue(I.getArgOperand(1));
  7487. setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(),
  7488. LHS.getValueType(), LHS, RHS));
  7489. return;
  7490. }
  7491. break;
  7492. case LibFunc_fabs:
  7493. case LibFunc_fabsf:
  7494. case LibFunc_fabsl:
  7495. if (visitUnaryFloatCall(I, ISD::FABS))
  7496. return;
  7497. break;
  7498. case LibFunc_fmin:
  7499. case LibFunc_fminf:
  7500. case LibFunc_fminl:
  7501. if (visitBinaryFloatCall(I, ISD::FMINNUM))
  7502. return;
  7503. break;
  7504. case LibFunc_fmax:
  7505. case LibFunc_fmaxf:
  7506. case LibFunc_fmaxl:
  7507. if (visitBinaryFloatCall(I, ISD::FMAXNUM))
  7508. return;
  7509. break;
  7510. case LibFunc_sin:
  7511. case LibFunc_sinf:
  7512. case LibFunc_sinl:
  7513. if (visitUnaryFloatCall(I, ISD::FSIN))
  7514. return;
  7515. break;
  7516. case LibFunc_cos:
  7517. case LibFunc_cosf:
  7518. case LibFunc_cosl:
  7519. if (visitUnaryFloatCall(I, ISD::FCOS))
  7520. return;
  7521. break;
  7522. case LibFunc_sqrt:
  7523. case LibFunc_sqrtf:
  7524. case LibFunc_sqrtl:
  7525. case LibFunc_sqrt_finite:
  7526. case LibFunc_sqrtf_finite:
  7527. case LibFunc_sqrtl_finite:
  7528. if (visitUnaryFloatCall(I, ISD::FSQRT))
  7529. return;
  7530. break;
  7531. case LibFunc_floor:
  7532. case LibFunc_floorf:
  7533. case LibFunc_floorl:
  7534. if (visitUnaryFloatCall(I, ISD::FFLOOR))
  7535. return;
  7536. break;
  7537. case LibFunc_nearbyint:
  7538. case LibFunc_nearbyintf:
  7539. case LibFunc_nearbyintl:
  7540. if (visitUnaryFloatCall(I, ISD::FNEARBYINT))
  7541. return;
  7542. break;
  7543. case LibFunc_ceil:
  7544. case LibFunc_ceilf:
  7545. case LibFunc_ceill:
  7546. if (visitUnaryFloatCall(I, ISD::FCEIL))
  7547. return;
  7548. break;
  7549. case LibFunc_rint:
  7550. case LibFunc_rintf:
  7551. case LibFunc_rintl:
  7552. if (visitUnaryFloatCall(I, ISD::FRINT))
  7553. return;
  7554. break;
  7555. case LibFunc_round:
  7556. case LibFunc_roundf:
  7557. case LibFunc_roundl:
  7558. if (visitUnaryFloatCall(I, ISD::FROUND))
  7559. return;
  7560. break;
  7561. case LibFunc_trunc:
  7562. case LibFunc_truncf:
  7563. case LibFunc_truncl:
  7564. if (visitUnaryFloatCall(I, ISD::FTRUNC))
  7565. return;
  7566. break;
  7567. case LibFunc_log2:
  7568. case LibFunc_log2f:
  7569. case LibFunc_log2l:
  7570. if (visitUnaryFloatCall(I, ISD::FLOG2))
  7571. return;
  7572. break;
  7573. case LibFunc_exp2:
  7574. case LibFunc_exp2f:
  7575. case LibFunc_exp2l:
  7576. if (visitUnaryFloatCall(I, ISD::FEXP2))
  7577. return;
  7578. break;
  7579. case LibFunc_memcmp:
  7580. if (visitMemCmpBCmpCall(I))
  7581. return;
  7582. break;
  7583. case LibFunc_mempcpy:
  7584. if (visitMemPCpyCall(I))
  7585. return;
  7586. break;
  7587. case LibFunc_memchr:
  7588. if (visitMemChrCall(I))
  7589. return;
  7590. break;
  7591. case LibFunc_strcpy:
  7592. if (visitStrCpyCall(I, false))
  7593. return;
  7594. break;
  7595. case LibFunc_stpcpy:
  7596. if (visitStrCpyCall(I, true))
  7597. return;
  7598. break;
  7599. case LibFunc_strcmp:
  7600. if (visitStrCmpCall(I))
  7601. return;
  7602. break;
  7603. case LibFunc_strlen:
  7604. if (visitStrLenCall(I))
  7605. return;
  7606. break;
  7607. case LibFunc_strnlen:
  7608. if (visitStrNLenCall(I))
  7609. return;
  7610. break;
  7611. }
  7612. }
  7613. }
  7614. // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
  7615. // have to do anything here to lower funclet bundles.
  7616. // CFGuardTarget bundles are lowered in LowerCallTo.
  7617. assert(!I.hasOperandBundlesOtherThan(
  7618. {LLVMContext::OB_deopt, LLVMContext::OB_funclet,
  7619. LLVMContext::OB_cfguardtarget, LLVMContext::OB_preallocated,
  7620. LLVMContext::OB_clang_arc_attachedcall, LLVMContext::OB_kcfi}) &&
  7621. "Cannot lower calls with arbitrary operand bundles!");
  7622. SDValue Callee = getValue(I.getCalledOperand());
  7623. if (I.countOperandBundlesOfType(LLVMContext::OB_deopt))
  7624. LowerCallSiteWithDeoptBundle(&I, Callee, nullptr);
  7625. else
  7626. // Check if we can potentially perform a tail call. More detailed checking
  7627. // is be done within LowerCallTo, after more information about the call is
  7628. // known.
  7629. LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall());
  7630. }
  7631. namespace {
  7632. /// AsmOperandInfo - This contains information for each constraint that we are
  7633. /// lowering.
  7634. class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
  7635. public:
  7636. /// CallOperand - If this is the result output operand or a clobber
  7637. /// this is null, otherwise it is the incoming operand to the CallInst.
  7638. /// This gets modified as the asm is processed.
  7639. SDValue CallOperand;
  7640. /// AssignedRegs - If this is a register or register class operand, this
  7641. /// contains the set of register corresponding to the operand.
  7642. RegsForValue AssignedRegs;
  7643. explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info)
  7644. : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) {
  7645. }
  7646. /// Whether or not this operand accesses memory
  7647. bool hasMemory(const TargetLowering &TLI) const {
  7648. // Indirect operand accesses access memory.
  7649. if (isIndirect)
  7650. return true;
  7651. for (const auto &Code : Codes)
  7652. if (TLI.getConstraintType(Code) == TargetLowering::C_Memory)
  7653. return true;
  7654. return false;
  7655. }
  7656. };
  7657. } // end anonymous namespace
  7658. /// Make sure that the output operand \p OpInfo and its corresponding input
  7659. /// operand \p MatchingOpInfo have compatible constraint types (otherwise error
  7660. /// out).
  7661. static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo,
  7662. SDISelAsmOperandInfo &MatchingOpInfo,
  7663. SelectionDAG &DAG) {
  7664. if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT)
  7665. return;
  7666. const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
  7667. const auto &TLI = DAG.getTargetLoweringInfo();
  7668. std::pair<unsigned, const TargetRegisterClass *> MatchRC =
  7669. TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode,
  7670. OpInfo.ConstraintVT);
  7671. std::pair<unsigned, const TargetRegisterClass *> InputRC =
  7672. TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode,
  7673. MatchingOpInfo.ConstraintVT);
  7674. if ((OpInfo.ConstraintVT.isInteger() !=
  7675. MatchingOpInfo.ConstraintVT.isInteger()) ||
  7676. (MatchRC.second != InputRC.second)) {
  7677. // FIXME: error out in a more elegant fashion
  7678. report_fatal_error("Unsupported asm: input constraint"
  7679. " with a matching output constraint of"
  7680. " incompatible type!");
  7681. }
  7682. MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT;
  7683. }
  7684. /// Get a direct memory input to behave well as an indirect operand.
  7685. /// This may introduce stores, hence the need for a \p Chain.
  7686. /// \return The (possibly updated) chain.
  7687. static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location,
  7688. SDISelAsmOperandInfo &OpInfo,
  7689. SelectionDAG &DAG) {
  7690. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  7691. // If we don't have an indirect input, put it in the constpool if we can,
  7692. // otherwise spill it to a stack slot.
  7693. // TODO: This isn't quite right. We need to handle these according to
  7694. // the addressing mode that the constraint wants. Also, this may take
  7695. // an additional register for the computation and we don't want that
  7696. // either.
  7697. // If the operand is a float, integer, or vector constant, spill to a
  7698. // constant pool entry to get its address.
  7699. const Value *OpVal = OpInfo.CallOperandVal;
  7700. if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
  7701. isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) {
  7702. OpInfo.CallOperand = DAG.getConstantPool(
  7703. cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout()));
  7704. return Chain;
  7705. }
  7706. // Otherwise, create a stack slot and emit a store to it before the asm.
  7707. Type *Ty = OpVal->getType();
  7708. auto &DL = DAG.getDataLayout();
  7709. uint64_t TySize = DL.getTypeAllocSize(Ty);
  7710. MachineFunction &MF = DAG.getMachineFunction();
  7711. int SSFI = MF.getFrameInfo().CreateStackObject(
  7712. TySize, DL.getPrefTypeAlign(Ty), false);
  7713. SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL));
  7714. Chain = DAG.getTruncStore(Chain, Location, OpInfo.CallOperand, StackSlot,
  7715. MachinePointerInfo::getFixedStack(MF, SSFI),
  7716. TLI.getMemValueType(DL, Ty));
  7717. OpInfo.CallOperand = StackSlot;
  7718. return Chain;
  7719. }
  7720. /// GetRegistersForValue - Assign registers (virtual or physical) for the
  7721. /// specified operand. We prefer to assign virtual registers, to allow the
  7722. /// register allocator to handle the assignment process. However, if the asm
  7723. /// uses features that we can't model on machineinstrs, we have SDISel do the
  7724. /// allocation. This produces generally horrible, but correct, code.
  7725. ///
  7726. /// OpInfo describes the operand
  7727. /// RefOpInfo describes the matching operand if any, the operand otherwise
  7728. static std::optional<unsigned>
  7729. getRegistersForValue(SelectionDAG &DAG, const SDLoc &DL,
  7730. SDISelAsmOperandInfo &OpInfo,
  7731. SDISelAsmOperandInfo &RefOpInfo) {
  7732. LLVMContext &Context = *DAG.getContext();
  7733. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  7734. MachineFunction &MF = DAG.getMachineFunction();
  7735. SmallVector<unsigned, 4> Regs;
  7736. const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
  7737. // No work to do for memory/address operands.
  7738. if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
  7739. OpInfo.ConstraintType == TargetLowering::C_Address)
  7740. return std::nullopt;
  7741. // If this is a constraint for a single physreg, or a constraint for a
  7742. // register class, find it.
  7743. unsigned AssignedReg;
  7744. const TargetRegisterClass *RC;
  7745. std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint(
  7746. &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT);
  7747. // RC is unset only on failure. Return immediately.
  7748. if (!RC)
  7749. return std::nullopt;
  7750. // Get the actual register value type. This is important, because the user
  7751. // may have asked for (e.g.) the AX register in i32 type. We need to
  7752. // remember that AX is actually i16 to get the right extension.
  7753. const MVT RegVT = *TRI.legalclasstypes_begin(*RC);
  7754. if (OpInfo.ConstraintVT != MVT::Other && RegVT != MVT::Untyped) {
  7755. // If this is an FP operand in an integer register (or visa versa), or more
  7756. // generally if the operand value disagrees with the register class we plan
  7757. // to stick it in, fix the operand type.
  7758. //
  7759. // If this is an input value, the bitcast to the new type is done now.
  7760. // Bitcast for output value is done at the end of visitInlineAsm().
  7761. if ((OpInfo.Type == InlineAsm::isOutput ||
  7762. OpInfo.Type == InlineAsm::isInput) &&
  7763. !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) {
  7764. // Try to convert to the first EVT that the reg class contains. If the
  7765. // types are identical size, use a bitcast to convert (e.g. two differing
  7766. // vector types). Note: output bitcast is done at the end of
  7767. // visitInlineAsm().
  7768. if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
  7769. // Exclude indirect inputs while they are unsupported because the code
  7770. // to perform the load is missing and thus OpInfo.CallOperand still
  7771. // refers to the input address rather than the pointed-to value.
  7772. if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect)
  7773. OpInfo.CallOperand =
  7774. DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand);
  7775. OpInfo.ConstraintVT = RegVT;
  7776. // If the operand is an FP value and we want it in integer registers,
  7777. // use the corresponding integer type. This turns an f64 value into
  7778. // i64, which can be passed with two i32 values on a 32-bit machine.
  7779. } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
  7780. MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
  7781. if (OpInfo.Type == InlineAsm::isInput)
  7782. OpInfo.CallOperand =
  7783. DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand);
  7784. OpInfo.ConstraintVT = VT;
  7785. }
  7786. }
  7787. }
  7788. // No need to allocate a matching input constraint since the constraint it's
  7789. // matching to has already been allocated.
  7790. if (OpInfo.isMatchingInputConstraint())
  7791. return std::nullopt;
  7792. EVT ValueVT = OpInfo.ConstraintVT;
  7793. if (OpInfo.ConstraintVT == MVT::Other)
  7794. ValueVT = RegVT;
  7795. // Initialize NumRegs.
  7796. unsigned NumRegs = 1;
  7797. if (OpInfo.ConstraintVT != MVT::Other)
  7798. NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT, RegVT);
  7799. // If this is a constraint for a specific physical register, like {r17},
  7800. // assign it now.
  7801. // If this associated to a specific register, initialize iterator to correct
  7802. // place. If virtual, make sure we have enough registers
  7803. // Initialize iterator if necessary
  7804. TargetRegisterClass::iterator I = RC->begin();
  7805. MachineRegisterInfo &RegInfo = MF.getRegInfo();
  7806. // Do not check for single registers.
  7807. if (AssignedReg) {
  7808. I = std::find(I, RC->end(), AssignedReg);
  7809. if (I == RC->end()) {
  7810. // RC does not contain the selected register, which indicates a
  7811. // mismatch between the register and the required type/bitwidth.
  7812. return {AssignedReg};
  7813. }
  7814. }
  7815. for (; NumRegs; --NumRegs, ++I) {
  7816. assert(I != RC->end() && "Ran out of registers to allocate!");
  7817. Register R = AssignedReg ? Register(*I) : RegInfo.createVirtualRegister(RC);
  7818. Regs.push_back(R);
  7819. }
  7820. OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
  7821. return std::nullopt;
  7822. }
  7823. static unsigned
  7824. findMatchingInlineAsmOperand(unsigned OperandNo,
  7825. const std::vector<SDValue> &AsmNodeOperands) {
  7826. // Scan until we find the definition we already emitted of this operand.
  7827. unsigned CurOp = InlineAsm::Op_FirstOperand;
  7828. for (; OperandNo; --OperandNo) {
  7829. // Advance to the next operand.
  7830. unsigned OpFlag =
  7831. cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
  7832. assert((InlineAsm::isRegDefKind(OpFlag) ||
  7833. InlineAsm::isRegDefEarlyClobberKind(OpFlag) ||
  7834. InlineAsm::isMemKind(OpFlag)) &&
  7835. "Skipped past definitions?");
  7836. CurOp += InlineAsm::getNumOperandRegisters(OpFlag) + 1;
  7837. }
  7838. return CurOp;
  7839. }
  7840. namespace {
  7841. class ExtraFlags {
  7842. unsigned Flags = 0;
  7843. public:
  7844. explicit ExtraFlags(const CallBase &Call) {
  7845. const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand());
  7846. if (IA->hasSideEffects())
  7847. Flags |= InlineAsm::Extra_HasSideEffects;
  7848. if (IA->isAlignStack())
  7849. Flags |= InlineAsm::Extra_IsAlignStack;
  7850. if (Call.isConvergent())
  7851. Flags |= InlineAsm::Extra_IsConvergent;
  7852. Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect;
  7853. }
  7854. void update(const TargetLowering::AsmOperandInfo &OpInfo) {
  7855. // Ideally, we would only check against memory constraints. However, the
  7856. // meaning of an Other constraint can be target-specific and we can't easily
  7857. // reason about it. Therefore, be conservative and set MayLoad/MayStore
  7858. // for Other constraints as well.
  7859. if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
  7860. OpInfo.ConstraintType == TargetLowering::C_Other) {
  7861. if (OpInfo.Type == InlineAsm::isInput)
  7862. Flags |= InlineAsm::Extra_MayLoad;
  7863. else if (OpInfo.Type == InlineAsm::isOutput)
  7864. Flags |= InlineAsm::Extra_MayStore;
  7865. else if (OpInfo.Type == InlineAsm::isClobber)
  7866. Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore);
  7867. }
  7868. }
  7869. unsigned get() const { return Flags; }
  7870. };
  7871. } // end anonymous namespace
  7872. static bool isFunction(SDValue Op) {
  7873. if (Op && Op.getOpcode() == ISD::GlobalAddress) {
  7874. if (auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) {
  7875. auto Fn = dyn_cast_or_null<Function>(GA->getGlobal());
  7876. // In normal "call dllimport func" instruction (non-inlineasm) it force
  7877. // indirect access by specifing call opcode. And usually specially print
  7878. // asm with indirect symbol (i.g: "*") according to opcode. Inline asm can
  7879. // not do in this way now. (In fact, this is similar with "Data Access"
  7880. // action). So here we ignore dllimport function.
  7881. if (Fn && !Fn->hasDLLImportStorageClass())
  7882. return true;
  7883. }
  7884. }
  7885. return false;
  7886. }
  7887. /// visitInlineAsm - Handle a call to an InlineAsm object.
  7888. void SelectionDAGBuilder::visitInlineAsm(const CallBase &Call,
  7889. const BasicBlock *EHPadBB) {
  7890. const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand());
  7891. /// ConstraintOperands - Information about all of the constraints.
  7892. SmallVector<SDISelAsmOperandInfo, 16> ConstraintOperands;
  7893. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  7894. TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints(
  7895. DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), Call);
  7896. // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack,
  7897. // AsmDialect, MayLoad, MayStore).
  7898. bool HasSideEffect = IA->hasSideEffects();
  7899. ExtraFlags ExtraInfo(Call);
  7900. for (auto &T : TargetConstraints) {
  7901. ConstraintOperands.push_back(SDISelAsmOperandInfo(T));
  7902. SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
  7903. if (OpInfo.CallOperandVal)
  7904. OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
  7905. if (!HasSideEffect)
  7906. HasSideEffect = OpInfo.hasMemory(TLI);
  7907. // Determine if this InlineAsm MayLoad or MayStore based on the constraints.
  7908. // FIXME: Could we compute this on OpInfo rather than T?
  7909. // Compute the constraint code and ConstraintType to use.
  7910. TLI.ComputeConstraintToUse(T, SDValue());
  7911. if (T.ConstraintType == TargetLowering::C_Immediate &&
  7912. OpInfo.CallOperand && !isa<ConstantSDNode>(OpInfo.CallOperand))
  7913. // We've delayed emitting a diagnostic like the "n" constraint because
  7914. // inlining could cause an integer showing up.
  7915. return emitInlineAsmError(Call, "constraint '" + Twine(T.ConstraintCode) +
  7916. "' expects an integer constant "
  7917. "expression");
  7918. ExtraInfo.update(T);
  7919. }
  7920. // We won't need to flush pending loads if this asm doesn't touch
  7921. // memory and is nonvolatile.
  7922. SDValue Flag, Chain = (HasSideEffect) ? getRoot() : DAG.getRoot();
  7923. bool EmitEHLabels = isa<InvokeInst>(Call);
  7924. if (EmitEHLabels) {
  7925. assert(EHPadBB && "InvokeInst must have an EHPadBB");
  7926. }
  7927. bool IsCallBr = isa<CallBrInst>(Call);
  7928. if (IsCallBr || EmitEHLabels) {
  7929. // If this is a callbr or invoke we need to flush pending exports since
  7930. // inlineasm_br and invoke are terminators.
  7931. // We need to do this before nodes are glued to the inlineasm_br node.
  7932. Chain = getControlRoot();
  7933. }
  7934. MCSymbol *BeginLabel = nullptr;
  7935. if (EmitEHLabels) {
  7936. Chain = lowerStartEH(Chain, EHPadBB, BeginLabel);
  7937. }
  7938. int OpNo = -1;
  7939. SmallVector<StringRef> AsmStrs;
  7940. IA->collectAsmStrs(AsmStrs);
  7941. // Second pass over the constraints: compute which constraint option to use.
  7942. for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
  7943. if (OpInfo.hasArg() || OpInfo.Type == InlineAsm::isOutput)
  7944. OpNo++;
  7945. // If this is an output operand with a matching input operand, look up the
  7946. // matching input. If their types mismatch, e.g. one is an integer, the
  7947. // other is floating point, or their sizes are different, flag it as an
  7948. // error.
  7949. if (OpInfo.hasMatchingInput()) {
  7950. SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
  7951. patchMatchingInput(OpInfo, Input, DAG);
  7952. }
  7953. // Compute the constraint code and ConstraintType to use.
  7954. TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
  7955. if ((OpInfo.ConstraintType == TargetLowering::C_Memory &&
  7956. OpInfo.Type == InlineAsm::isClobber) ||
  7957. OpInfo.ConstraintType == TargetLowering::C_Address)
  7958. continue;
  7959. // In Linux PIC model, there are 4 cases about value/label addressing:
  7960. //
  7961. // 1: Function call or Label jmp inside the module.
  7962. // 2: Data access (such as global variable, static variable) inside module.
  7963. // 3: Function call or Label jmp outside the module.
  7964. // 4: Data access (such as global variable) outside the module.
  7965. //
  7966. // Due to current llvm inline asm architecture designed to not "recognize"
  7967. // the asm code, there are quite troubles for us to treat mem addressing
  7968. // differently for same value/adress used in different instuctions.
  7969. // For example, in pic model, call a func may in plt way or direclty
  7970. // pc-related, but lea/mov a function adress may use got.
  7971. //
  7972. // Here we try to "recognize" function call for the case 1 and case 3 in
  7973. // inline asm. And try to adjust the constraint for them.
  7974. //
  7975. // TODO: Due to current inline asm didn't encourage to jmp to the outsider
  7976. // label, so here we don't handle jmp function label now, but we need to
  7977. // enhance it (especilly in PIC model) if we meet meaningful requirements.
  7978. if (OpInfo.isIndirect && isFunction(OpInfo.CallOperand) &&
  7979. TLI.isInlineAsmTargetBranch(AsmStrs, OpNo) &&
  7980. TM.getCodeModel() != CodeModel::Large) {
  7981. OpInfo.isIndirect = false;
  7982. OpInfo.ConstraintType = TargetLowering::C_Address;
  7983. }
  7984. // If this is a memory input, and if the operand is not indirect, do what we
  7985. // need to provide an address for the memory input.
  7986. if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
  7987. !OpInfo.isIndirect) {
  7988. assert((OpInfo.isMultipleAlternative ||
  7989. (OpInfo.Type == InlineAsm::isInput)) &&
  7990. "Can only indirectify direct input operands!");
  7991. // Memory operands really want the address of the value.
  7992. Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG);
  7993. // There is no longer a Value* corresponding to this operand.
  7994. OpInfo.CallOperandVal = nullptr;
  7995. // It is now an indirect operand.
  7996. OpInfo.isIndirect = true;
  7997. }
  7998. }
  7999. // AsmNodeOperands - The operands for the ISD::INLINEASM node.
  8000. std::vector<SDValue> AsmNodeOperands;
  8001. AsmNodeOperands.push_back(SDValue()); // reserve space for input chain
  8002. AsmNodeOperands.push_back(DAG.getTargetExternalSymbol(
  8003. IA->getAsmString().c_str(), TLI.getProgramPointerTy(DAG.getDataLayout())));
  8004. // If we have a !srcloc metadata node associated with it, we want to attach
  8005. // this to the ultimately generated inline asm machineinstr. To do this, we
  8006. // pass in the third operand as this (potentially null) inline asm MDNode.
  8007. const MDNode *SrcLoc = Call.getMetadata("srcloc");
  8008. AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc));
  8009. // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore
  8010. // bits as operand 3.
  8011. AsmNodeOperands.push_back(DAG.getTargetConstant(
  8012. ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
  8013. // Third pass: Loop over operands to prepare DAG-level operands.. As part of
  8014. // this, assign virtual and physical registers for inputs and otput.
  8015. for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
  8016. // Assign Registers.
  8017. SDISelAsmOperandInfo &RefOpInfo =
  8018. OpInfo.isMatchingInputConstraint()
  8019. ? ConstraintOperands[OpInfo.getMatchedOperand()]
  8020. : OpInfo;
  8021. const auto RegError =
  8022. getRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo);
  8023. if (RegError) {
  8024. const MachineFunction &MF = DAG.getMachineFunction();
  8025. const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
  8026. const char *RegName = TRI.getName(*RegError);
  8027. emitInlineAsmError(Call, "register '" + Twine(RegName) +
  8028. "' allocated for constraint '" +
  8029. Twine(OpInfo.ConstraintCode) +
  8030. "' does not match required type");
  8031. return;
  8032. }
  8033. auto DetectWriteToReservedRegister = [&]() {
  8034. const MachineFunction &MF = DAG.getMachineFunction();
  8035. const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
  8036. for (unsigned Reg : OpInfo.AssignedRegs.Regs) {
  8037. if (Register::isPhysicalRegister(Reg) &&
  8038. TRI.isInlineAsmReadOnlyReg(MF, Reg)) {
  8039. const char *RegName = TRI.getName(Reg);
  8040. emitInlineAsmError(Call, "write to reserved register '" +
  8041. Twine(RegName) + "'");
  8042. return true;
  8043. }
  8044. }
  8045. return false;
  8046. };
  8047. assert((OpInfo.ConstraintType != TargetLowering::C_Address ||
  8048. (OpInfo.Type == InlineAsm::isInput &&
  8049. !OpInfo.isMatchingInputConstraint())) &&
  8050. "Only address as input operand is allowed.");
  8051. switch (OpInfo.Type) {
  8052. case InlineAsm::isOutput:
  8053. if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
  8054. unsigned ConstraintID =
  8055. TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
  8056. assert(ConstraintID != InlineAsm::Constraint_Unknown &&
  8057. "Failed to convert memory constraint code to constraint id.");
  8058. // Add information to the INLINEASM node to know about this output.
  8059. unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
  8060. OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID);
  8061. AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(),
  8062. MVT::i32));
  8063. AsmNodeOperands.push_back(OpInfo.CallOperand);
  8064. } else {
  8065. // Otherwise, this outputs to a register (directly for C_Register /
  8066. // C_RegisterClass, and a target-defined fashion for
  8067. // C_Immediate/C_Other). Find a register that we can use.
  8068. if (OpInfo.AssignedRegs.Regs.empty()) {
  8069. emitInlineAsmError(
  8070. Call, "couldn't allocate output register for constraint '" +
  8071. Twine(OpInfo.ConstraintCode) + "'");
  8072. return;
  8073. }
  8074. if (DetectWriteToReservedRegister())
  8075. return;
  8076. // Add information to the INLINEASM node to know that this register is
  8077. // set.
  8078. OpInfo.AssignedRegs.AddInlineAsmOperands(
  8079. OpInfo.isEarlyClobber ? InlineAsm::Kind_RegDefEarlyClobber
  8080. : InlineAsm::Kind_RegDef,
  8081. false, 0, getCurSDLoc(), DAG, AsmNodeOperands);
  8082. }
  8083. break;
  8084. case InlineAsm::isInput:
  8085. case InlineAsm::isLabel: {
  8086. SDValue InOperandVal = OpInfo.CallOperand;
  8087. if (OpInfo.isMatchingInputConstraint()) {
  8088. // If this is required to match an output register we have already set,
  8089. // just use its register.
  8090. auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(),
  8091. AsmNodeOperands);
  8092. unsigned OpFlag =
  8093. cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
  8094. if (InlineAsm::isRegDefKind(OpFlag) ||
  8095. InlineAsm::isRegDefEarlyClobberKind(OpFlag)) {
  8096. // Add (OpFlag&0xffff)>>3 registers to MatchedRegs.
  8097. if (OpInfo.isIndirect) {
  8098. // This happens on gcc/testsuite/gcc.dg/pr8788-1.c
  8099. emitInlineAsmError(Call, "inline asm not supported yet: "
  8100. "don't know how to handle tied "
  8101. "indirect register inputs");
  8102. return;
  8103. }
  8104. SmallVector<unsigned, 4> Regs;
  8105. MachineFunction &MF = DAG.getMachineFunction();
  8106. MachineRegisterInfo &MRI = MF.getRegInfo();
  8107. const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
  8108. auto *R = cast<RegisterSDNode>(AsmNodeOperands[CurOp+1]);
  8109. Register TiedReg = R->getReg();
  8110. MVT RegVT = R->getSimpleValueType(0);
  8111. const TargetRegisterClass *RC =
  8112. TiedReg.isVirtual() ? MRI.getRegClass(TiedReg)
  8113. : RegVT != MVT::Untyped ? TLI.getRegClassFor(RegVT)
  8114. : TRI.getMinimalPhysRegClass(TiedReg);
  8115. unsigned NumRegs = InlineAsm::getNumOperandRegisters(OpFlag);
  8116. for (unsigned i = 0; i != NumRegs; ++i)
  8117. Regs.push_back(MRI.createVirtualRegister(RC));
  8118. RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType());
  8119. SDLoc dl = getCurSDLoc();
  8120. // Use the produced MatchedRegs object to
  8121. MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag, &Call);
  8122. MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse,
  8123. true, OpInfo.getMatchedOperand(), dl,
  8124. DAG, AsmNodeOperands);
  8125. break;
  8126. }
  8127. assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!");
  8128. assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 &&
  8129. "Unexpected number of operands");
  8130. // Add information to the INLINEASM node to know about this input.
  8131. // See InlineAsm.h isUseOperandTiedToDef.
  8132. OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag);
  8133. OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag,
  8134. OpInfo.getMatchedOperand());
  8135. AsmNodeOperands.push_back(DAG.getTargetConstant(
  8136. OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
  8137. AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
  8138. break;
  8139. }
  8140. // Treat indirect 'X' constraint as memory.
  8141. if (OpInfo.ConstraintType == TargetLowering::C_Other &&
  8142. OpInfo.isIndirect)
  8143. OpInfo.ConstraintType = TargetLowering::C_Memory;
  8144. if (OpInfo.ConstraintType == TargetLowering::C_Immediate ||
  8145. OpInfo.ConstraintType == TargetLowering::C_Other) {
  8146. std::vector<SDValue> Ops;
  8147. TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode,
  8148. Ops, DAG);
  8149. if (Ops.empty()) {
  8150. if (OpInfo.ConstraintType == TargetLowering::C_Immediate)
  8151. if (isa<ConstantSDNode>(InOperandVal)) {
  8152. emitInlineAsmError(Call, "value out of range for constraint '" +
  8153. Twine(OpInfo.ConstraintCode) + "'");
  8154. return;
  8155. }
  8156. emitInlineAsmError(Call,
  8157. "invalid operand for inline asm constraint '" +
  8158. Twine(OpInfo.ConstraintCode) + "'");
  8159. return;
  8160. }
  8161. // Add information to the INLINEASM node to know about this input.
  8162. unsigned ResOpType =
  8163. InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size());
  8164. AsmNodeOperands.push_back(DAG.getTargetConstant(
  8165. ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
  8166. llvm::append_range(AsmNodeOperands, Ops);
  8167. break;
  8168. }
  8169. if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
  8170. assert((OpInfo.isIndirect ||
  8171. OpInfo.ConstraintType != TargetLowering::C_Memory) &&
  8172. "Operand must be indirect to be a mem!");
  8173. assert(InOperandVal.getValueType() ==
  8174. TLI.getPointerTy(DAG.getDataLayout()) &&
  8175. "Memory operands expect pointer values");
  8176. unsigned ConstraintID =
  8177. TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
  8178. assert(ConstraintID != InlineAsm::Constraint_Unknown &&
  8179. "Failed to convert memory constraint code to constraint id.");
  8180. // Add information to the INLINEASM node to know about this input.
  8181. unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
  8182. ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID);
  8183. AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
  8184. getCurSDLoc(),
  8185. MVT::i32));
  8186. AsmNodeOperands.push_back(InOperandVal);
  8187. break;
  8188. }
  8189. if (OpInfo.ConstraintType == TargetLowering::C_Address) {
  8190. assert(InOperandVal.getValueType() ==
  8191. TLI.getPointerTy(DAG.getDataLayout()) &&
  8192. "Address operands expect pointer values");
  8193. unsigned ConstraintID =
  8194. TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
  8195. assert(ConstraintID != InlineAsm::Constraint_Unknown &&
  8196. "Failed to convert memory constraint code to constraint id.");
  8197. unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
  8198. SDValue AsmOp = InOperandVal;
  8199. if (isFunction(InOperandVal)) {
  8200. auto *GA = cast<GlobalAddressSDNode>(InOperandVal);
  8201. ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Func, 1);
  8202. AsmOp = DAG.getTargetGlobalAddress(GA->getGlobal(), getCurSDLoc(),
  8203. InOperandVal.getValueType(),
  8204. GA->getOffset());
  8205. }
  8206. // Add information to the INLINEASM node to know about this input.
  8207. ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID);
  8208. AsmNodeOperands.push_back(
  8209. DAG.getTargetConstant(ResOpType, getCurSDLoc(), MVT::i32));
  8210. AsmNodeOperands.push_back(AsmOp);
  8211. break;
  8212. }
  8213. assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
  8214. OpInfo.ConstraintType == TargetLowering::C_Register) &&
  8215. "Unknown constraint type!");
  8216. // TODO: Support this.
  8217. if (OpInfo.isIndirect) {
  8218. emitInlineAsmError(
  8219. Call, "Don't know how to handle indirect register inputs yet "
  8220. "for constraint '" +
  8221. Twine(OpInfo.ConstraintCode) + "'");
  8222. return;
  8223. }
  8224. // Copy the input into the appropriate registers.
  8225. if (OpInfo.AssignedRegs.Regs.empty()) {
  8226. emitInlineAsmError(Call,
  8227. "couldn't allocate input reg for constraint '" +
  8228. Twine(OpInfo.ConstraintCode) + "'");
  8229. return;
  8230. }
  8231. if (DetectWriteToReservedRegister())
  8232. return;
  8233. SDLoc dl = getCurSDLoc();
  8234. OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag,
  8235. &Call);
  8236. OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0,
  8237. dl, DAG, AsmNodeOperands);
  8238. break;
  8239. }
  8240. case InlineAsm::isClobber:
  8241. // Add the clobbered value to the operand list, so that the register
  8242. // allocator is aware that the physreg got clobbered.
  8243. if (!OpInfo.AssignedRegs.Regs.empty())
  8244. OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber,
  8245. false, 0, getCurSDLoc(), DAG,
  8246. AsmNodeOperands);
  8247. break;
  8248. }
  8249. }
  8250. // Finish up input operands. Set the input chain and add the flag last.
  8251. AsmNodeOperands[InlineAsm::Op_InputChain] = Chain;
  8252. if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
  8253. unsigned ISDOpc = IsCallBr ? ISD::INLINEASM_BR : ISD::INLINEASM;
  8254. Chain = DAG.getNode(ISDOpc, getCurSDLoc(),
  8255. DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands);
  8256. Flag = Chain.getValue(1);
  8257. // Do additional work to generate outputs.
  8258. SmallVector<EVT, 1> ResultVTs;
  8259. SmallVector<SDValue, 1> ResultValues;
  8260. SmallVector<SDValue, 8> OutChains;
  8261. llvm::Type *CallResultType = Call.getType();
  8262. ArrayRef<Type *> ResultTypes;
  8263. if (StructType *StructResult = dyn_cast<StructType>(CallResultType))
  8264. ResultTypes = StructResult->elements();
  8265. else if (!CallResultType->isVoidTy())
  8266. ResultTypes = ArrayRef(CallResultType);
  8267. auto CurResultType = ResultTypes.begin();
  8268. auto handleRegAssign = [&](SDValue V) {
  8269. assert(CurResultType != ResultTypes.end() && "Unexpected value");
  8270. assert((*CurResultType)->isSized() && "Unexpected unsized type");
  8271. EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType);
  8272. ++CurResultType;
  8273. // If the type of the inline asm call site return value is different but has
  8274. // same size as the type of the asm output bitcast it. One example of this
  8275. // is for vectors with different width / number of elements. This can
  8276. // happen for register classes that can contain multiple different value
  8277. // types. The preg or vreg allocated may not have the same VT as was
  8278. // expected.
  8279. //
  8280. // This can also happen for a return value that disagrees with the register
  8281. // class it is put in, eg. a double in a general-purpose register on a
  8282. // 32-bit machine.
  8283. if (ResultVT != V.getValueType() &&
  8284. ResultVT.getSizeInBits() == V.getValueSizeInBits())
  8285. V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V);
  8286. else if (ResultVT != V.getValueType() && ResultVT.isInteger() &&
  8287. V.getValueType().isInteger()) {
  8288. // If a result value was tied to an input value, the computed result
  8289. // may have a wider width than the expected result. Extract the
  8290. // relevant portion.
  8291. V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V);
  8292. }
  8293. assert(ResultVT == V.getValueType() && "Asm result value mismatch!");
  8294. ResultVTs.push_back(ResultVT);
  8295. ResultValues.push_back(V);
  8296. };
  8297. // Deal with output operands.
  8298. for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
  8299. if (OpInfo.Type == InlineAsm::isOutput) {
  8300. SDValue Val;
  8301. // Skip trivial output operands.
  8302. if (OpInfo.AssignedRegs.Regs.empty())
  8303. continue;
  8304. switch (OpInfo.ConstraintType) {
  8305. case TargetLowering::C_Register:
  8306. case TargetLowering::C_RegisterClass:
  8307. Val = OpInfo.AssignedRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(),
  8308. Chain, &Flag, &Call);
  8309. break;
  8310. case TargetLowering::C_Immediate:
  8311. case TargetLowering::C_Other:
  8312. Val = TLI.LowerAsmOutputForConstraint(Chain, Flag, getCurSDLoc(),
  8313. OpInfo, DAG);
  8314. break;
  8315. case TargetLowering::C_Memory:
  8316. break; // Already handled.
  8317. case TargetLowering::C_Address:
  8318. break; // Silence warning.
  8319. case TargetLowering::C_Unknown:
  8320. assert(false && "Unexpected unknown constraint");
  8321. }
  8322. // Indirect output manifest as stores. Record output chains.
  8323. if (OpInfo.isIndirect) {
  8324. const Value *Ptr = OpInfo.CallOperandVal;
  8325. assert(Ptr && "Expected value CallOperandVal for indirect asm operand");
  8326. SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr),
  8327. MachinePointerInfo(Ptr));
  8328. OutChains.push_back(Store);
  8329. } else {
  8330. // generate CopyFromRegs to associated registers.
  8331. assert(!Call.getType()->isVoidTy() && "Bad inline asm!");
  8332. if (Val.getOpcode() == ISD::MERGE_VALUES) {
  8333. for (const SDValue &V : Val->op_values())
  8334. handleRegAssign(V);
  8335. } else
  8336. handleRegAssign(Val);
  8337. }
  8338. }
  8339. }
  8340. // Set results.
  8341. if (!ResultValues.empty()) {
  8342. assert(CurResultType == ResultTypes.end() &&
  8343. "Mismatch in number of ResultTypes");
  8344. assert(ResultValues.size() == ResultTypes.size() &&
  8345. "Mismatch in number of output operands in asm result");
  8346. SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
  8347. DAG.getVTList(ResultVTs), ResultValues);
  8348. setValue(&Call, V);
  8349. }
  8350. // Collect store chains.
  8351. if (!OutChains.empty())
  8352. Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains);
  8353. if (EmitEHLabels) {
  8354. Chain = lowerEndEH(Chain, cast<InvokeInst>(&Call), EHPadBB, BeginLabel);
  8355. }
  8356. // Only Update Root if inline assembly has a memory effect.
  8357. if (ResultValues.empty() || HasSideEffect || !OutChains.empty() || IsCallBr ||
  8358. EmitEHLabels)
  8359. DAG.setRoot(Chain);
  8360. }
  8361. void SelectionDAGBuilder::emitInlineAsmError(const CallBase &Call,
  8362. const Twine &Message) {
  8363. LLVMContext &Ctx = *DAG.getContext();
  8364. Ctx.emitError(&Call, Message);
  8365. // Make sure we leave the DAG in a valid state
  8366. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  8367. SmallVector<EVT, 1> ValueVTs;
  8368. ComputeValueVTs(TLI, DAG.getDataLayout(), Call.getType(), ValueVTs);
  8369. if (ValueVTs.empty())
  8370. return;
  8371. SmallVector<SDValue, 1> Ops;
  8372. for (unsigned i = 0, e = ValueVTs.size(); i != e; ++i)
  8373. Ops.push_back(DAG.getUNDEF(ValueVTs[i]));
  8374. setValue(&Call, DAG.getMergeValues(Ops, getCurSDLoc()));
  8375. }
  8376. void SelectionDAGBuilder::visitVAStart(const CallInst &I) {
  8377. DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(),
  8378. MVT::Other, getRoot(),
  8379. getValue(I.getArgOperand(0)),
  8380. DAG.getSrcValue(I.getArgOperand(0))));
  8381. }
  8382. void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) {
  8383. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  8384. const DataLayout &DL = DAG.getDataLayout();
  8385. SDValue V = DAG.getVAArg(
  8386. TLI.getMemValueType(DAG.getDataLayout(), I.getType()), getCurSDLoc(),
  8387. getRoot(), getValue(I.getOperand(0)), DAG.getSrcValue(I.getOperand(0)),
  8388. DL.getABITypeAlign(I.getType()).value());
  8389. DAG.setRoot(V.getValue(1));
  8390. if (I.getType()->isPointerTy())
  8391. V = DAG.getPtrExtOrTrunc(
  8392. V, getCurSDLoc(), TLI.getValueType(DAG.getDataLayout(), I.getType()));
  8393. setValue(&I, V);
  8394. }
  8395. void SelectionDAGBuilder::visitVAEnd(const CallInst &I) {
  8396. DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(),
  8397. MVT::Other, getRoot(),
  8398. getValue(I.getArgOperand(0)),
  8399. DAG.getSrcValue(I.getArgOperand(0))));
  8400. }
  8401. void SelectionDAGBuilder::visitVACopy(const CallInst &I) {
  8402. DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(),
  8403. MVT::Other, getRoot(),
  8404. getValue(I.getArgOperand(0)),
  8405. getValue(I.getArgOperand(1)),
  8406. DAG.getSrcValue(I.getArgOperand(0)),
  8407. DAG.getSrcValue(I.getArgOperand(1))));
  8408. }
  8409. SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG,
  8410. const Instruction &I,
  8411. SDValue Op) {
  8412. const MDNode *Range = I.getMetadata(LLVMContext::MD_range);
  8413. if (!Range)
  8414. return Op;
  8415. ConstantRange CR = getConstantRangeFromMetadata(*Range);
  8416. if (CR.isFullSet() || CR.isEmptySet() || CR.isUpperWrapped())
  8417. return Op;
  8418. APInt Lo = CR.getUnsignedMin();
  8419. if (!Lo.isMinValue())
  8420. return Op;
  8421. APInt Hi = CR.getUnsignedMax();
  8422. unsigned Bits = std::max(Hi.getActiveBits(),
  8423. static_cast<unsigned>(IntegerType::MIN_INT_BITS));
  8424. EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
  8425. SDLoc SL = getCurSDLoc();
  8426. SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op,
  8427. DAG.getValueType(SmallVT));
  8428. unsigned NumVals = Op.getNode()->getNumValues();
  8429. if (NumVals == 1)
  8430. return ZExt;
  8431. SmallVector<SDValue, 4> Ops;
  8432. Ops.push_back(ZExt);
  8433. for (unsigned I = 1; I != NumVals; ++I)
  8434. Ops.push_back(Op.getValue(I));
  8435. return DAG.getMergeValues(Ops, SL);
  8436. }
  8437. /// Populate a CallLowerinInfo (into \p CLI) based on the properties of
  8438. /// the call being lowered.
  8439. ///
  8440. /// This is a helper for lowering intrinsics that follow a target calling
  8441. /// convention or require stack pointer adjustment. Only a subset of the
  8442. /// intrinsic's operands need to participate in the calling convention.
  8443. void SelectionDAGBuilder::populateCallLoweringInfo(
  8444. TargetLowering::CallLoweringInfo &CLI, const CallBase *Call,
  8445. unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy,
  8446. bool IsPatchPoint) {
  8447. TargetLowering::ArgListTy Args;
  8448. Args.reserve(NumArgs);
  8449. // Populate the argument list.
  8450. // Attributes for args start at offset 1, after the return attribute.
  8451. for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs;
  8452. ArgI != ArgE; ++ArgI) {
  8453. const Value *V = Call->getOperand(ArgI);
  8454. assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic.");
  8455. TargetLowering::ArgListEntry Entry;
  8456. Entry.Node = getValue(V);
  8457. Entry.Ty = V->getType();
  8458. Entry.setAttributes(Call, ArgI);
  8459. Args.push_back(Entry);
  8460. }
  8461. CLI.setDebugLoc(getCurSDLoc())
  8462. .setChain(getRoot())
  8463. .setCallee(Call->getCallingConv(), ReturnTy, Callee, std::move(Args))
  8464. .setDiscardResult(Call->use_empty())
  8465. .setIsPatchPoint(IsPatchPoint)
  8466. .setIsPreallocated(
  8467. Call->countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0);
  8468. }
  8469. /// Add a stack map intrinsic call's live variable operands to a stackmap
  8470. /// or patchpoint target node's operand list.
  8471. ///
  8472. /// Constants are converted to TargetConstants purely as an optimization to
  8473. /// avoid constant materialization and register allocation.
  8474. ///
  8475. /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not
  8476. /// generate addess computation nodes, and so FinalizeISel can convert the
  8477. /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids
  8478. /// address materialization and register allocation, but may also be required
  8479. /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an
  8480. /// alloca in the entry block, then the runtime may assume that the alloca's
  8481. /// StackMap location can be read immediately after compilation and that the
  8482. /// location is valid at any point during execution (this is similar to the
  8483. /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were
  8484. /// only available in a register, then the runtime would need to trap when
  8485. /// execution reaches the StackMap in order to read the alloca's location.
  8486. static void addStackMapLiveVars(const CallBase &Call, unsigned StartIdx,
  8487. const SDLoc &DL, SmallVectorImpl<SDValue> &Ops,
  8488. SelectionDAGBuilder &Builder) {
  8489. SelectionDAG &DAG = Builder.DAG;
  8490. for (unsigned I = StartIdx; I < Call.arg_size(); I++) {
  8491. SDValue Op = Builder.getValue(Call.getArgOperand(I));
  8492. // Things on the stack are pointer-typed, meaning that they are already
  8493. // legal and can be emitted directly to target nodes.
  8494. if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Op)) {
  8495. Ops.push_back(DAG.getTargetFrameIndex(FI->getIndex(), Op.getValueType()));
  8496. } else {
  8497. // Otherwise emit a target independent node to be legalised.
  8498. Ops.push_back(Builder.getValue(Call.getArgOperand(I)));
  8499. }
  8500. }
  8501. }
  8502. /// Lower llvm.experimental.stackmap.
  8503. void SelectionDAGBuilder::visitStackmap(const CallInst &CI) {
  8504. // void @llvm.experimental.stackmap(i64 <id>, i32 <numShadowBytes>,
  8505. // [live variables...])
  8506. assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value.");
  8507. SDValue Chain, InFlag, Callee;
  8508. SmallVector<SDValue, 32> Ops;
  8509. SDLoc DL = getCurSDLoc();
  8510. Callee = getValue(CI.getCalledOperand());
  8511. // The stackmap intrinsic only records the live variables (the arguments
  8512. // passed to it) and emits NOPS (if requested). Unlike the patchpoint
  8513. // intrinsic, this won't be lowered to a function call. This means we don't
  8514. // have to worry about calling conventions and target specific lowering code.
  8515. // Instead we perform the call lowering right here.
  8516. //
  8517. // chain, flag = CALLSEQ_START(chain, 0, 0)
  8518. // chain, flag = STACKMAP(id, nbytes, ..., chain, flag)
  8519. // chain, flag = CALLSEQ_END(chain, 0, 0, flag)
  8520. //
  8521. Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL);
  8522. InFlag = Chain.getValue(1);
  8523. // Add the STACKMAP operands, starting with DAG house-keeping.
  8524. Ops.push_back(Chain);
  8525. Ops.push_back(InFlag);
  8526. // Add the <id>, <numShadowBytes> operands.
  8527. //
  8528. // These do not require legalisation, and can be emitted directly to target
  8529. // constant nodes.
  8530. SDValue ID = getValue(CI.getArgOperand(0));
  8531. assert(ID.getValueType() == MVT::i64);
  8532. SDValue IDConst = DAG.getTargetConstant(
  8533. cast<ConstantSDNode>(ID)->getZExtValue(), DL, ID.getValueType());
  8534. Ops.push_back(IDConst);
  8535. SDValue Shad = getValue(CI.getArgOperand(1));
  8536. assert(Shad.getValueType() == MVT::i32);
  8537. SDValue ShadConst = DAG.getTargetConstant(
  8538. cast<ConstantSDNode>(Shad)->getZExtValue(), DL, Shad.getValueType());
  8539. Ops.push_back(ShadConst);
  8540. // Add the live variables.
  8541. addStackMapLiveVars(CI, 2, DL, Ops, *this);
  8542. // Create the STACKMAP node.
  8543. SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
  8544. Chain = DAG.getNode(ISD::STACKMAP, DL, NodeTys, Ops);
  8545. InFlag = Chain.getValue(1);
  8546. Chain = DAG.getCALLSEQ_END(Chain, 0, 0, InFlag, DL);
  8547. // Stackmaps don't generate values, so nothing goes into the NodeMap.
  8548. // Set the root to the target-lowered call chain.
  8549. DAG.setRoot(Chain);
  8550. // Inform the Frame Information that we have a stackmap in this function.
  8551. FuncInfo.MF->getFrameInfo().setHasStackMap();
  8552. }
  8553. /// Lower llvm.experimental.patchpoint directly to its target opcode.
  8554. void SelectionDAGBuilder::visitPatchpoint(const CallBase &CB,
  8555. const BasicBlock *EHPadBB) {
  8556. // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>,
  8557. // i32 <numBytes>,
  8558. // i8* <target>,
  8559. // i32 <numArgs>,
  8560. // [Args...],
  8561. // [live variables...])
  8562. CallingConv::ID CC = CB.getCallingConv();
  8563. bool IsAnyRegCC = CC == CallingConv::AnyReg;
  8564. bool HasDef = !CB.getType()->isVoidTy();
  8565. SDLoc dl = getCurSDLoc();
  8566. SDValue Callee = getValue(CB.getArgOperand(PatchPointOpers::TargetPos));
  8567. // Handle immediate and symbolic callees.
  8568. if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee))
  8569. Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl,
  8570. /*isTarget=*/true);
  8571. else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee))
  8572. Callee = DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(),
  8573. SDLoc(SymbolicCallee),
  8574. SymbolicCallee->getValueType(0));
  8575. // Get the real number of arguments participating in the call <numArgs>
  8576. SDValue NArgVal = getValue(CB.getArgOperand(PatchPointOpers::NArgPos));
  8577. unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue();
  8578. // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs>
  8579. // Intrinsics include all meta-operands up to but not including CC.
  8580. unsigned NumMetaOpers = PatchPointOpers::CCPos;
  8581. assert(CB.arg_size() >= NumMetaOpers + NumArgs &&
  8582. "Not enough arguments provided to the patchpoint intrinsic");
  8583. // For AnyRegCC the arguments are lowered later on manually.
  8584. unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs;
  8585. Type *ReturnTy =
  8586. IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CB.getType();
  8587. TargetLowering::CallLoweringInfo CLI(DAG);
  8588. populateCallLoweringInfo(CLI, &CB, NumMetaOpers, NumCallArgs, Callee,
  8589. ReturnTy, true);
  8590. std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
  8591. SDNode *CallEnd = Result.second.getNode();
  8592. if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg))
  8593. CallEnd = CallEnd->getOperand(0).getNode();
  8594. /// Get a call instruction from the call sequence chain.
  8595. /// Tail calls are not allowed.
  8596. assert(CallEnd->getOpcode() == ISD::CALLSEQ_END &&
  8597. "Expected a callseq node.");
  8598. SDNode *Call = CallEnd->getOperand(0).getNode();
  8599. bool HasGlue = Call->getGluedNode();
  8600. // Replace the target specific call node with the patchable intrinsic.
  8601. SmallVector<SDValue, 8> Ops;
  8602. // Push the chain.
  8603. Ops.push_back(*(Call->op_begin()));
  8604. // Optionally, push the glue (if any).
  8605. if (HasGlue)
  8606. Ops.push_back(*(Call->op_end() - 1));
  8607. // Push the register mask info.
  8608. if (HasGlue)
  8609. Ops.push_back(*(Call->op_end() - 2));
  8610. else
  8611. Ops.push_back(*(Call->op_end() - 1));
  8612. // Add the <id> and <numBytes> constants.
  8613. SDValue IDVal = getValue(CB.getArgOperand(PatchPointOpers::IDPos));
  8614. Ops.push_back(DAG.getTargetConstant(
  8615. cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64));
  8616. SDValue NBytesVal = getValue(CB.getArgOperand(PatchPointOpers::NBytesPos));
  8617. Ops.push_back(DAG.getTargetConstant(
  8618. cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl,
  8619. MVT::i32));
  8620. // Add the callee.
  8621. Ops.push_back(Callee);
  8622. // Adjust <numArgs> to account for any arguments that have been passed on the
  8623. // stack instead.
  8624. // Call Node: Chain, Target, {Args}, RegMask, [Glue]
  8625. unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3);
  8626. NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs;
  8627. Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32));
  8628. // Add the calling convention
  8629. Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32));
  8630. // Add the arguments we omitted previously. The register allocator should
  8631. // place these in any free register.
  8632. if (IsAnyRegCC)
  8633. for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i)
  8634. Ops.push_back(getValue(CB.getArgOperand(i)));
  8635. // Push the arguments from the call instruction.
  8636. SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1;
  8637. Ops.append(Call->op_begin() + 2, e);
  8638. // Push live variables for the stack map.
  8639. addStackMapLiveVars(CB, NumMetaOpers + NumArgs, dl, Ops, *this);
  8640. SDVTList NodeTys;
  8641. if (IsAnyRegCC && HasDef) {
  8642. // Create the return types based on the intrinsic definition
  8643. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  8644. SmallVector<EVT, 3> ValueVTs;
  8645. ComputeValueVTs(TLI, DAG.getDataLayout(), CB.getType(), ValueVTs);
  8646. assert(ValueVTs.size() == 1 && "Expected only one return value type.");
  8647. // There is always a chain and a glue type at the end
  8648. ValueVTs.push_back(MVT::Other);
  8649. ValueVTs.push_back(MVT::Glue);
  8650. NodeTys = DAG.getVTList(ValueVTs);
  8651. } else
  8652. NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
  8653. // Replace the target specific call node with a PATCHPOINT node.
  8654. SDValue PPV = DAG.getNode(ISD::PATCHPOINT, dl, NodeTys, Ops);
  8655. // Update the NodeMap.
  8656. if (HasDef) {
  8657. if (IsAnyRegCC)
  8658. setValue(&CB, SDValue(PPV.getNode(), 0));
  8659. else
  8660. setValue(&CB, Result.first);
  8661. }
  8662. // Fixup the consumers of the intrinsic. The chain and glue may be used in the
  8663. // call sequence. Furthermore the location of the chain and glue can change
  8664. // when the AnyReg calling convention is used and the intrinsic returns a
  8665. // value.
  8666. if (IsAnyRegCC && HasDef) {
  8667. SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)};
  8668. SDValue To[] = {PPV.getValue(1), PPV.getValue(2)};
  8669. DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
  8670. } else
  8671. DAG.ReplaceAllUsesWith(Call, PPV.getNode());
  8672. DAG.DeleteNode(Call);
  8673. // Inform the Frame Information that we have a patchpoint in this function.
  8674. FuncInfo.MF->getFrameInfo().setHasPatchPoint();
  8675. }
  8676. void SelectionDAGBuilder::visitVectorReduce(const CallInst &I,
  8677. unsigned Intrinsic) {
  8678. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  8679. SDValue Op1 = getValue(I.getArgOperand(0));
  8680. SDValue Op2;
  8681. if (I.arg_size() > 1)
  8682. Op2 = getValue(I.getArgOperand(1));
  8683. SDLoc dl = getCurSDLoc();
  8684. EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  8685. SDValue Res;
  8686. SDNodeFlags SDFlags;
  8687. if (auto *FPMO = dyn_cast<FPMathOperator>(&I))
  8688. SDFlags.copyFMF(*FPMO);
  8689. switch (Intrinsic) {
  8690. case Intrinsic::vector_reduce_fadd:
  8691. if (SDFlags.hasAllowReassociation())
  8692. Res = DAG.getNode(ISD::FADD, dl, VT, Op1,
  8693. DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2, SDFlags),
  8694. SDFlags);
  8695. else
  8696. Res = DAG.getNode(ISD::VECREDUCE_SEQ_FADD, dl, VT, Op1, Op2, SDFlags);
  8697. break;
  8698. case Intrinsic::vector_reduce_fmul:
  8699. if (SDFlags.hasAllowReassociation())
  8700. Res = DAG.getNode(ISD::FMUL, dl, VT, Op1,
  8701. DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2, SDFlags),
  8702. SDFlags);
  8703. else
  8704. Res = DAG.getNode(ISD::VECREDUCE_SEQ_FMUL, dl, VT, Op1, Op2, SDFlags);
  8705. break;
  8706. case Intrinsic::vector_reduce_add:
  8707. Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1);
  8708. break;
  8709. case Intrinsic::vector_reduce_mul:
  8710. Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1);
  8711. break;
  8712. case Intrinsic::vector_reduce_and:
  8713. Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1);
  8714. break;
  8715. case Intrinsic::vector_reduce_or:
  8716. Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1);
  8717. break;
  8718. case Intrinsic::vector_reduce_xor:
  8719. Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1);
  8720. break;
  8721. case Intrinsic::vector_reduce_smax:
  8722. Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1);
  8723. break;
  8724. case Intrinsic::vector_reduce_smin:
  8725. Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1);
  8726. break;
  8727. case Intrinsic::vector_reduce_umax:
  8728. Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1);
  8729. break;
  8730. case Intrinsic::vector_reduce_umin:
  8731. Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1);
  8732. break;
  8733. case Intrinsic::vector_reduce_fmax:
  8734. Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1, SDFlags);
  8735. break;
  8736. case Intrinsic::vector_reduce_fmin:
  8737. Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1, SDFlags);
  8738. break;
  8739. default:
  8740. llvm_unreachable("Unhandled vector reduce intrinsic");
  8741. }
  8742. setValue(&I, Res);
  8743. }
  8744. /// Returns an AttributeList representing the attributes applied to the return
  8745. /// value of the given call.
  8746. static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) {
  8747. SmallVector<Attribute::AttrKind, 2> Attrs;
  8748. if (CLI.RetSExt)
  8749. Attrs.push_back(Attribute::SExt);
  8750. if (CLI.RetZExt)
  8751. Attrs.push_back(Attribute::ZExt);
  8752. if (CLI.IsInReg)
  8753. Attrs.push_back(Attribute::InReg);
  8754. return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex,
  8755. Attrs);
  8756. }
  8757. /// TargetLowering::LowerCallTo - This is the default LowerCallTo
  8758. /// implementation, which just calls LowerCall.
  8759. /// FIXME: When all targets are
  8760. /// migrated to using LowerCall, this hook should be integrated into SDISel.
  8761. std::pair<SDValue, SDValue>
  8762. TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const {
  8763. // Handle the incoming return values from the call.
  8764. CLI.Ins.clear();
  8765. Type *OrigRetTy = CLI.RetTy;
  8766. SmallVector<EVT, 4> RetTys;
  8767. SmallVector<uint64_t, 4> Offsets;
  8768. auto &DL = CLI.DAG.getDataLayout();
  8769. ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets);
  8770. if (CLI.IsPostTypeLegalization) {
  8771. // If we are lowering a libcall after legalization, split the return type.
  8772. SmallVector<EVT, 4> OldRetTys;
  8773. SmallVector<uint64_t, 4> OldOffsets;
  8774. RetTys.swap(OldRetTys);
  8775. Offsets.swap(OldOffsets);
  8776. for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) {
  8777. EVT RetVT = OldRetTys[i];
  8778. uint64_t Offset = OldOffsets[i];
  8779. MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT);
  8780. unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT);
  8781. unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8;
  8782. RetTys.append(NumRegs, RegisterVT);
  8783. for (unsigned j = 0; j != NumRegs; ++j)
  8784. Offsets.push_back(Offset + j * RegisterVTByteSZ);
  8785. }
  8786. }
  8787. SmallVector<ISD::OutputArg, 4> Outs;
  8788. GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL);
  8789. bool CanLowerReturn =
  8790. this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(),
  8791. CLI.IsVarArg, Outs, CLI.RetTy->getContext());
  8792. SDValue DemoteStackSlot;
  8793. int DemoteStackIdx = -100;
  8794. if (!CanLowerReturn) {
  8795. // FIXME: equivalent assert?
  8796. // assert(!CS.hasInAllocaArgument() &&
  8797. // "sret demotion is incompatible with inalloca");
  8798. uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy);
  8799. Align Alignment = DL.getPrefTypeAlign(CLI.RetTy);
  8800. MachineFunction &MF = CLI.DAG.getMachineFunction();
  8801. DemoteStackIdx =
  8802. MF.getFrameInfo().CreateStackObject(TySize, Alignment, false);
  8803. Type *StackSlotPtrType = PointerType::get(CLI.RetTy,
  8804. DL.getAllocaAddrSpace());
  8805. DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL));
  8806. ArgListEntry Entry;
  8807. Entry.Node = DemoteStackSlot;
  8808. Entry.Ty = StackSlotPtrType;
  8809. Entry.IsSExt = false;
  8810. Entry.IsZExt = false;
  8811. Entry.IsInReg = false;
  8812. Entry.IsSRet = true;
  8813. Entry.IsNest = false;
  8814. Entry.IsByVal = false;
  8815. Entry.IsByRef = false;
  8816. Entry.IsReturned = false;
  8817. Entry.IsSwiftSelf = false;
  8818. Entry.IsSwiftAsync = false;
  8819. Entry.IsSwiftError = false;
  8820. Entry.IsCFGuardTarget = false;
  8821. Entry.Alignment = Alignment;
  8822. CLI.getArgs().insert(CLI.getArgs().begin(), Entry);
  8823. CLI.NumFixedArgs += 1;
  8824. CLI.getArgs()[0].IndirectType = CLI.RetTy;
  8825. CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext());
  8826. // sret demotion isn't compatible with tail-calls, since the sret argument
  8827. // points into the callers stack frame.
  8828. CLI.IsTailCall = false;
  8829. } else {
  8830. bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
  8831. CLI.RetTy, CLI.CallConv, CLI.IsVarArg, DL);
  8832. for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
  8833. ISD::ArgFlagsTy Flags;
  8834. if (NeedsRegBlock) {
  8835. Flags.setInConsecutiveRegs();
  8836. if (I == RetTys.size() - 1)
  8837. Flags.setInConsecutiveRegsLast();
  8838. }
  8839. EVT VT = RetTys[I];
  8840. MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
  8841. CLI.CallConv, VT);
  8842. unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
  8843. CLI.CallConv, VT);
  8844. for (unsigned i = 0; i != NumRegs; ++i) {
  8845. ISD::InputArg MyFlags;
  8846. MyFlags.Flags = Flags;
  8847. MyFlags.VT = RegisterVT;
  8848. MyFlags.ArgVT = VT;
  8849. MyFlags.Used = CLI.IsReturnValueUsed;
  8850. if (CLI.RetTy->isPointerTy()) {
  8851. MyFlags.Flags.setPointer();
  8852. MyFlags.Flags.setPointerAddrSpace(
  8853. cast<PointerType>(CLI.RetTy)->getAddressSpace());
  8854. }
  8855. if (CLI.RetSExt)
  8856. MyFlags.Flags.setSExt();
  8857. if (CLI.RetZExt)
  8858. MyFlags.Flags.setZExt();
  8859. if (CLI.IsInReg)
  8860. MyFlags.Flags.setInReg();
  8861. CLI.Ins.push_back(MyFlags);
  8862. }
  8863. }
  8864. }
  8865. // We push in swifterror return as the last element of CLI.Ins.
  8866. ArgListTy &Args = CLI.getArgs();
  8867. if (supportSwiftError()) {
  8868. for (const ArgListEntry &Arg : Args) {
  8869. if (Arg.IsSwiftError) {
  8870. ISD::InputArg MyFlags;
  8871. MyFlags.VT = getPointerTy(DL);
  8872. MyFlags.ArgVT = EVT(getPointerTy(DL));
  8873. MyFlags.Flags.setSwiftError();
  8874. CLI.Ins.push_back(MyFlags);
  8875. }
  8876. }
  8877. }
  8878. // Handle all of the outgoing arguments.
  8879. CLI.Outs.clear();
  8880. CLI.OutVals.clear();
  8881. for (unsigned i = 0, e = Args.size(); i != e; ++i) {
  8882. SmallVector<EVT, 4> ValueVTs;
  8883. ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs);
  8884. // FIXME: Split arguments if CLI.IsPostTypeLegalization
  8885. Type *FinalType = Args[i].Ty;
  8886. if (Args[i].IsByVal)
  8887. FinalType = Args[i].IndirectType;
  8888. bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
  8889. FinalType, CLI.CallConv, CLI.IsVarArg, DL);
  8890. for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues;
  8891. ++Value) {
  8892. EVT VT = ValueVTs[Value];
  8893. Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext());
  8894. SDValue Op = SDValue(Args[i].Node.getNode(),
  8895. Args[i].Node.getResNo() + Value);
  8896. ISD::ArgFlagsTy Flags;
  8897. // Certain targets (such as MIPS), may have a different ABI alignment
  8898. // for a type depending on the context. Give the target a chance to
  8899. // specify the alignment it wants.
  8900. const Align OriginalAlignment(getABIAlignmentForCallingConv(ArgTy, DL));
  8901. Flags.setOrigAlign(OriginalAlignment);
  8902. if (Args[i].Ty->isPointerTy()) {
  8903. Flags.setPointer();
  8904. Flags.setPointerAddrSpace(
  8905. cast<PointerType>(Args[i].Ty)->getAddressSpace());
  8906. }
  8907. if (Args[i].IsZExt)
  8908. Flags.setZExt();
  8909. if (Args[i].IsSExt)
  8910. Flags.setSExt();
  8911. if (Args[i].IsInReg) {
  8912. // If we are using vectorcall calling convention, a structure that is
  8913. // passed InReg - is surely an HVA
  8914. if (CLI.CallConv == CallingConv::X86_VectorCall &&
  8915. isa<StructType>(FinalType)) {
  8916. // The first value of a structure is marked
  8917. if (0 == Value)
  8918. Flags.setHvaStart();
  8919. Flags.setHva();
  8920. }
  8921. // Set InReg Flag
  8922. Flags.setInReg();
  8923. }
  8924. if (Args[i].IsSRet)
  8925. Flags.setSRet();
  8926. if (Args[i].IsSwiftSelf)
  8927. Flags.setSwiftSelf();
  8928. if (Args[i].IsSwiftAsync)
  8929. Flags.setSwiftAsync();
  8930. if (Args[i].IsSwiftError)
  8931. Flags.setSwiftError();
  8932. if (Args[i].IsCFGuardTarget)
  8933. Flags.setCFGuardTarget();
  8934. if (Args[i].IsByVal)
  8935. Flags.setByVal();
  8936. if (Args[i].IsByRef)
  8937. Flags.setByRef();
  8938. if (Args[i].IsPreallocated) {
  8939. Flags.setPreallocated();
  8940. // Set the byval flag for CCAssignFn callbacks that don't know about
  8941. // preallocated. This way we can know how many bytes we should've
  8942. // allocated and how many bytes a callee cleanup function will pop. If
  8943. // we port preallocated to more targets, we'll have to add custom
  8944. // preallocated handling in the various CC lowering callbacks.
  8945. Flags.setByVal();
  8946. }
  8947. if (Args[i].IsInAlloca) {
  8948. Flags.setInAlloca();
  8949. // Set the byval flag for CCAssignFn callbacks that don't know about
  8950. // inalloca. This way we can know how many bytes we should've allocated
  8951. // and how many bytes a callee cleanup function will pop. If we port
  8952. // inalloca to more targets, we'll have to add custom inalloca handling
  8953. // in the various CC lowering callbacks.
  8954. Flags.setByVal();
  8955. }
  8956. Align MemAlign;
  8957. if (Args[i].IsByVal || Args[i].IsInAlloca || Args[i].IsPreallocated) {
  8958. unsigned FrameSize = DL.getTypeAllocSize(Args[i].IndirectType);
  8959. Flags.setByValSize(FrameSize);
  8960. // info is not there but there are cases it cannot get right.
  8961. if (auto MA = Args[i].Alignment)
  8962. MemAlign = *MA;
  8963. else
  8964. MemAlign = Align(getByValTypeAlignment(Args[i].IndirectType, DL));
  8965. } else if (auto MA = Args[i].Alignment) {
  8966. MemAlign = *MA;
  8967. } else {
  8968. MemAlign = OriginalAlignment;
  8969. }
  8970. Flags.setMemAlign(MemAlign);
  8971. if (Args[i].IsNest)
  8972. Flags.setNest();
  8973. if (NeedsRegBlock)
  8974. Flags.setInConsecutiveRegs();
  8975. MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
  8976. CLI.CallConv, VT);
  8977. unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
  8978. CLI.CallConv, VT);
  8979. SmallVector<SDValue, 4> Parts(NumParts);
  8980. ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
  8981. if (Args[i].IsSExt)
  8982. ExtendKind = ISD::SIGN_EXTEND;
  8983. else if (Args[i].IsZExt)
  8984. ExtendKind = ISD::ZERO_EXTEND;
  8985. // Conservatively only handle 'returned' on non-vectors that can be lowered,
  8986. // for now.
  8987. if (Args[i].IsReturned && !Op.getValueType().isVector() &&
  8988. CanLowerReturn) {
  8989. assert((CLI.RetTy == Args[i].Ty ||
  8990. (CLI.RetTy->isPointerTy() && Args[i].Ty->isPointerTy() &&
  8991. CLI.RetTy->getPointerAddressSpace() ==
  8992. Args[i].Ty->getPointerAddressSpace())) &&
  8993. RetTys.size() == NumValues && "unexpected use of 'returned'");
  8994. // Before passing 'returned' to the target lowering code, ensure that
  8995. // either the register MVT and the actual EVT are the same size or that
  8996. // the return value and argument are extended in the same way; in these
  8997. // cases it's safe to pass the argument register value unchanged as the
  8998. // return register value (although it's at the target's option whether
  8999. // to do so)
  9000. // TODO: allow code generation to take advantage of partially preserved
  9001. // registers rather than clobbering the entire register when the
  9002. // parameter extension method is not compatible with the return
  9003. // extension method
  9004. if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) ||
  9005. (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt &&
  9006. CLI.RetZExt == Args[i].IsZExt))
  9007. Flags.setReturned();
  9008. }
  9009. getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT, CLI.CB,
  9010. CLI.CallConv, ExtendKind);
  9011. for (unsigned j = 0; j != NumParts; ++j) {
  9012. // if it isn't first piece, alignment must be 1
  9013. // For scalable vectors the scalable part is currently handled
  9014. // by individual targets, so we just use the known minimum size here.
  9015. ISD::OutputArg MyFlags(
  9016. Flags, Parts[j].getValueType().getSimpleVT(), VT,
  9017. i < CLI.NumFixedArgs, i,
  9018. j * Parts[j].getValueType().getStoreSize().getKnownMinValue());
  9019. if (NumParts > 1 && j == 0)
  9020. MyFlags.Flags.setSplit();
  9021. else if (j != 0) {
  9022. MyFlags.Flags.setOrigAlign(Align(1));
  9023. if (j == NumParts - 1)
  9024. MyFlags.Flags.setSplitEnd();
  9025. }
  9026. CLI.Outs.push_back(MyFlags);
  9027. CLI.OutVals.push_back(Parts[j]);
  9028. }
  9029. if (NeedsRegBlock && Value == NumValues - 1)
  9030. CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast();
  9031. }
  9032. }
  9033. SmallVector<SDValue, 4> InVals;
  9034. CLI.Chain = LowerCall(CLI, InVals);
  9035. // Update CLI.InVals to use outside of this function.
  9036. CLI.InVals = InVals;
  9037. // Verify that the target's LowerCall behaved as expected.
  9038. assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other &&
  9039. "LowerCall didn't return a valid chain!");
  9040. assert((!CLI.IsTailCall || InVals.empty()) &&
  9041. "LowerCall emitted a return value for a tail call!");
  9042. assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) &&
  9043. "LowerCall didn't emit the correct number of values!");
  9044. // For a tail call, the return value is merely live-out and there aren't
  9045. // any nodes in the DAG representing it. Return a special value to
  9046. // indicate that a tail call has been emitted and no more Instructions
  9047. // should be processed in the current block.
  9048. if (CLI.IsTailCall) {
  9049. CLI.DAG.setRoot(CLI.Chain);
  9050. return std::make_pair(SDValue(), SDValue());
  9051. }
  9052. #ifndef NDEBUG
  9053. for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) {
  9054. assert(InVals[i].getNode() && "LowerCall emitted a null value!");
  9055. assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() &&
  9056. "LowerCall emitted a value with the wrong type!");
  9057. }
  9058. #endif
  9059. SmallVector<SDValue, 4> ReturnValues;
  9060. if (!CanLowerReturn) {
  9061. // The instruction result is the result of loading from the
  9062. // hidden sret parameter.
  9063. SmallVector<EVT, 1> PVTs;
  9064. Type *PtrRetTy = OrigRetTy->getPointerTo(DL.getAllocaAddrSpace());
  9065. ComputeValueVTs(*this, DL, PtrRetTy, PVTs);
  9066. assert(PVTs.size() == 1 && "Pointers should fit in one register");
  9067. EVT PtrVT = PVTs[0];
  9068. unsigned NumValues = RetTys.size();
  9069. ReturnValues.resize(NumValues);
  9070. SmallVector<SDValue, 4> Chains(NumValues);
  9071. // An aggregate return value cannot wrap around the address space, so
  9072. // offsets to its parts don't wrap either.
  9073. SDNodeFlags Flags;
  9074. Flags.setNoUnsignedWrap(true);
  9075. MachineFunction &MF = CLI.DAG.getMachineFunction();
  9076. Align HiddenSRetAlign = MF.getFrameInfo().getObjectAlign(DemoteStackIdx);
  9077. for (unsigned i = 0; i < NumValues; ++i) {
  9078. SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot,
  9079. CLI.DAG.getConstant(Offsets[i], CLI.DL,
  9080. PtrVT), Flags);
  9081. SDValue L = CLI.DAG.getLoad(
  9082. RetTys[i], CLI.DL, CLI.Chain, Add,
  9083. MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(),
  9084. DemoteStackIdx, Offsets[i]),
  9085. HiddenSRetAlign);
  9086. ReturnValues[i] = L;
  9087. Chains[i] = L.getValue(1);
  9088. }
  9089. CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains);
  9090. } else {
  9091. // Collect the legal value parts into potentially illegal values
  9092. // that correspond to the original function's return values.
  9093. std::optional<ISD::NodeType> AssertOp;
  9094. if (CLI.RetSExt)
  9095. AssertOp = ISD::AssertSext;
  9096. else if (CLI.RetZExt)
  9097. AssertOp = ISD::AssertZext;
  9098. unsigned CurReg = 0;
  9099. for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
  9100. EVT VT = RetTys[I];
  9101. MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
  9102. CLI.CallConv, VT);
  9103. unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
  9104. CLI.CallConv, VT);
  9105. ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg],
  9106. NumRegs, RegisterVT, VT, nullptr,
  9107. CLI.CallConv, AssertOp));
  9108. CurReg += NumRegs;
  9109. }
  9110. // For a function returning void, there is no return value. We can't create
  9111. // such a node, so we just return a null return value in that case. In
  9112. // that case, nothing will actually look at the value.
  9113. if (ReturnValues.empty())
  9114. return std::make_pair(SDValue(), CLI.Chain);
  9115. }
  9116. SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL,
  9117. CLI.DAG.getVTList(RetTys), ReturnValues);
  9118. return std::make_pair(Res, CLI.Chain);
  9119. }
  9120. /// Places new result values for the node in Results (their number
  9121. /// and types must exactly match those of the original return values of
  9122. /// the node), or leaves Results empty, which indicates that the node is not
  9123. /// to be custom lowered after all.
  9124. void TargetLowering::LowerOperationWrapper(SDNode *N,
  9125. SmallVectorImpl<SDValue> &Results,
  9126. SelectionDAG &DAG) const {
  9127. SDValue Res = LowerOperation(SDValue(N, 0), DAG);
  9128. if (!Res.getNode())
  9129. return;
  9130. // If the original node has one result, take the return value from
  9131. // LowerOperation as is. It might not be result number 0.
  9132. if (N->getNumValues() == 1) {
  9133. Results.push_back(Res);
  9134. return;
  9135. }
  9136. // If the original node has multiple results, then the return node should
  9137. // have the same number of results.
  9138. assert((N->getNumValues() == Res->getNumValues()) &&
  9139. "Lowering returned the wrong number of results!");
  9140. // Places new result values base on N result number.
  9141. for (unsigned I = 0, E = N->getNumValues(); I != E; ++I)
  9142. Results.push_back(Res.getValue(I));
  9143. }
  9144. SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
  9145. llvm_unreachable("LowerOperation not implemented for this target!");
  9146. }
  9147. void SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V,
  9148. unsigned Reg,
  9149. ISD::NodeType ExtendType) {
  9150. SDValue Op = getNonRegisterValue(V);
  9151. assert((Op.getOpcode() != ISD::CopyFromReg ||
  9152. cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
  9153. "Copy from a reg to the same reg!");
  9154. assert(!Register::isPhysicalRegister(Reg) && "Is a physreg");
  9155. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  9156. // If this is an InlineAsm we have to match the registers required, not the
  9157. // notional registers required by the type.
  9158. RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(),
  9159. std::nullopt); // This is not an ABI copy.
  9160. SDValue Chain = DAG.getEntryNode();
  9161. if (ExtendType == ISD::ANY_EXTEND) {
  9162. auto PreferredExtendIt = FuncInfo.PreferredExtendType.find(V);
  9163. if (PreferredExtendIt != FuncInfo.PreferredExtendType.end())
  9164. ExtendType = PreferredExtendIt->second;
  9165. }
  9166. RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType);
  9167. PendingExports.push_back(Chain);
  9168. }
  9169. #include "llvm/CodeGen/SelectionDAGISel.h"
  9170. /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
  9171. /// entry block, return true. This includes arguments used by switches, since
  9172. /// the switch may expand into multiple basic blocks.
  9173. static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) {
  9174. // With FastISel active, we may be splitting blocks, so force creation
  9175. // of virtual registers for all non-dead arguments.
  9176. if (FastISel)
  9177. return A->use_empty();
  9178. const BasicBlock &Entry = A->getParent()->front();
  9179. for (const User *U : A->users())
  9180. if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U))
  9181. return false; // Use not in entry block.
  9182. return true;
  9183. }
  9184. using ArgCopyElisionMapTy =
  9185. DenseMap<const Argument *,
  9186. std::pair<const AllocaInst *, const StoreInst *>>;
  9187. /// Scan the entry block of the function in FuncInfo for arguments that look
  9188. /// like copies into a local alloca. Record any copied arguments in
  9189. /// ArgCopyElisionCandidates.
  9190. static void
  9191. findArgumentCopyElisionCandidates(const DataLayout &DL,
  9192. FunctionLoweringInfo *FuncInfo,
  9193. ArgCopyElisionMapTy &ArgCopyElisionCandidates) {
  9194. // Record the state of every static alloca used in the entry block. Argument
  9195. // allocas are all used in the entry block, so we need approximately as many
  9196. // entries as we have arguments.
  9197. enum StaticAllocaInfo { Unknown, Clobbered, Elidable };
  9198. SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas;
  9199. unsigned NumArgs = FuncInfo->Fn->arg_size();
  9200. StaticAllocas.reserve(NumArgs * 2);
  9201. auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * {
  9202. if (!V)
  9203. return nullptr;
  9204. V = V->stripPointerCasts();
  9205. const auto *AI = dyn_cast<AllocaInst>(V);
  9206. if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI))
  9207. return nullptr;
  9208. auto Iter = StaticAllocas.insert({AI, Unknown});
  9209. return &Iter.first->second;
  9210. };
  9211. // Look for stores of arguments to static allocas. Look through bitcasts and
  9212. // GEPs to handle type coercions, as long as the alloca is fully initialized
  9213. // by the store. Any non-store use of an alloca escapes it and any subsequent
  9214. // unanalyzed store might write it.
  9215. // FIXME: Handle structs initialized with multiple stores.
  9216. for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) {
  9217. // Look for stores, and handle non-store uses conservatively.
  9218. const auto *SI = dyn_cast<StoreInst>(&I);
  9219. if (!SI) {
  9220. // We will look through cast uses, so ignore them completely.
  9221. if (I.isCast())
  9222. continue;
  9223. // Ignore debug info and pseudo op intrinsics, they don't escape or store
  9224. // to allocas.
  9225. if (I.isDebugOrPseudoInst())
  9226. continue;
  9227. // This is an unknown instruction. Assume it escapes or writes to all
  9228. // static alloca operands.
  9229. for (const Use &U : I.operands()) {
  9230. if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U))
  9231. *Info = StaticAllocaInfo::Clobbered;
  9232. }
  9233. continue;
  9234. }
  9235. // If the stored value is a static alloca, mark it as escaped.
  9236. if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand()))
  9237. *Info = StaticAllocaInfo::Clobbered;
  9238. // Check if the destination is a static alloca.
  9239. const Value *Dst = SI->getPointerOperand()->stripPointerCasts();
  9240. StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst);
  9241. if (!Info)
  9242. continue;
  9243. const AllocaInst *AI = cast<AllocaInst>(Dst);
  9244. // Skip allocas that have been initialized or clobbered.
  9245. if (*Info != StaticAllocaInfo::Unknown)
  9246. continue;
  9247. // Check if the stored value is an argument, and that this store fully
  9248. // initializes the alloca.
  9249. // If the argument type has padding bits we can't directly forward a pointer
  9250. // as the upper bits may contain garbage.
  9251. // Don't elide copies from the same argument twice.
  9252. const Value *Val = SI->getValueOperand()->stripPointerCasts();
  9253. const auto *Arg = dyn_cast<Argument>(Val);
  9254. if (!Arg || Arg->hasPassPointeeByValueCopyAttr() ||
  9255. Arg->getType()->isEmptyTy() ||
  9256. DL.getTypeStoreSize(Arg->getType()) !=
  9257. DL.getTypeAllocSize(AI->getAllocatedType()) ||
  9258. !DL.typeSizeEqualsStoreSize(Arg->getType()) ||
  9259. ArgCopyElisionCandidates.count(Arg)) {
  9260. *Info = StaticAllocaInfo::Clobbered;
  9261. continue;
  9262. }
  9263. LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI
  9264. << '\n');
  9265. // Mark this alloca and store for argument copy elision.
  9266. *Info = StaticAllocaInfo::Elidable;
  9267. ArgCopyElisionCandidates.insert({Arg, {AI, SI}});
  9268. // Stop scanning if we've seen all arguments. This will happen early in -O0
  9269. // builds, which is useful, because -O0 builds have large entry blocks and
  9270. // many allocas.
  9271. if (ArgCopyElisionCandidates.size() == NumArgs)
  9272. break;
  9273. }
  9274. }
  9275. /// Try to elide argument copies from memory into a local alloca. Succeeds if
  9276. /// ArgVal is a load from a suitable fixed stack object.
  9277. static void tryToElideArgumentCopy(
  9278. FunctionLoweringInfo &FuncInfo, SmallVectorImpl<SDValue> &Chains,
  9279. DenseMap<int, int> &ArgCopyElisionFrameIndexMap,
  9280. SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs,
  9281. ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg,
  9282. SDValue ArgVal, bool &ArgHasUses) {
  9283. // Check if this is a load from a fixed stack object.
  9284. auto *LNode = dyn_cast<LoadSDNode>(ArgVal);
  9285. if (!LNode)
  9286. return;
  9287. auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode());
  9288. if (!FINode)
  9289. return;
  9290. // Check that the fixed stack object is the right size and alignment.
  9291. // Look at the alignment that the user wrote on the alloca instead of looking
  9292. // at the stack object.
  9293. auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg);
  9294. assert(ArgCopyIter != ArgCopyElisionCandidates.end());
  9295. const AllocaInst *AI = ArgCopyIter->second.first;
  9296. int FixedIndex = FINode->getIndex();
  9297. int &AllocaIndex = FuncInfo.StaticAllocaMap[AI];
  9298. int OldIndex = AllocaIndex;
  9299. MachineFrameInfo &MFI = FuncInfo.MF->getFrameInfo();
  9300. if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) {
  9301. LLVM_DEBUG(
  9302. dbgs() << " argument copy elision failed due to bad fixed stack "
  9303. "object size\n");
  9304. return;
  9305. }
  9306. Align RequiredAlignment = AI->getAlign();
  9307. if (MFI.getObjectAlign(FixedIndex) < RequiredAlignment) {
  9308. LLVM_DEBUG(dbgs() << " argument copy elision failed: alignment of alloca "
  9309. "greater than stack argument alignment ("
  9310. << DebugStr(RequiredAlignment) << " vs "
  9311. << DebugStr(MFI.getObjectAlign(FixedIndex)) << ")\n");
  9312. return;
  9313. }
  9314. // Perform the elision. Delete the old stack object and replace its only use
  9315. // in the variable info map. Mark the stack object as mutable.
  9316. LLVM_DEBUG({
  9317. dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n'
  9318. << " Replacing frame index " << OldIndex << " with " << FixedIndex
  9319. << '\n';
  9320. });
  9321. MFI.RemoveStackObject(OldIndex);
  9322. MFI.setIsImmutableObjectIndex(FixedIndex, false);
  9323. AllocaIndex = FixedIndex;
  9324. ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex});
  9325. Chains.push_back(ArgVal.getValue(1));
  9326. // Avoid emitting code for the store implementing the copy.
  9327. const StoreInst *SI = ArgCopyIter->second.second;
  9328. ElidedArgCopyInstrs.insert(SI);
  9329. // Check for uses of the argument again so that we can avoid exporting ArgVal
  9330. // if it is't used by anything other than the store.
  9331. for (const Value *U : Arg.users()) {
  9332. if (U != SI) {
  9333. ArgHasUses = true;
  9334. break;
  9335. }
  9336. }
  9337. }
  9338. void SelectionDAGISel::LowerArguments(const Function &F) {
  9339. SelectionDAG &DAG = SDB->DAG;
  9340. SDLoc dl = SDB->getCurSDLoc();
  9341. const DataLayout &DL = DAG.getDataLayout();
  9342. SmallVector<ISD::InputArg, 16> Ins;
  9343. // In Naked functions we aren't going to save any registers.
  9344. if (F.hasFnAttribute(Attribute::Naked))
  9345. return;
  9346. if (!FuncInfo->CanLowerReturn) {
  9347. // Put in an sret pointer parameter before all the other parameters.
  9348. SmallVector<EVT, 1> ValueVTs;
  9349. ComputeValueVTs(*TLI, DAG.getDataLayout(),
  9350. F.getReturnType()->getPointerTo(
  9351. DAG.getDataLayout().getAllocaAddrSpace()),
  9352. ValueVTs);
  9353. // NOTE: Assuming that a pointer will never break down to more than one VT
  9354. // or one register.
  9355. ISD::ArgFlagsTy Flags;
  9356. Flags.setSRet();
  9357. MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]);
  9358. ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true,
  9359. ISD::InputArg::NoArgIndex, 0);
  9360. Ins.push_back(RetArg);
  9361. }
  9362. // Look for stores of arguments to static allocas. Mark such arguments with a
  9363. // flag to ask the target to give us the memory location of that argument if
  9364. // available.
  9365. ArgCopyElisionMapTy ArgCopyElisionCandidates;
  9366. findArgumentCopyElisionCandidates(DL, FuncInfo.get(),
  9367. ArgCopyElisionCandidates);
  9368. // Set up the incoming argument description vector.
  9369. for (const Argument &Arg : F.args()) {
  9370. unsigned ArgNo = Arg.getArgNo();
  9371. SmallVector<EVT, 4> ValueVTs;
  9372. ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
  9373. bool isArgValueUsed = !Arg.use_empty();
  9374. unsigned PartBase = 0;
  9375. Type *FinalType = Arg.getType();
  9376. if (Arg.hasAttribute(Attribute::ByVal))
  9377. FinalType = Arg.getParamByValType();
  9378. bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters(
  9379. FinalType, F.getCallingConv(), F.isVarArg(), DL);
  9380. for (unsigned Value = 0, NumValues = ValueVTs.size();
  9381. Value != NumValues; ++Value) {
  9382. EVT VT = ValueVTs[Value];
  9383. Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
  9384. ISD::ArgFlagsTy Flags;
  9385. if (Arg.getType()->isPointerTy()) {
  9386. Flags.setPointer();
  9387. Flags.setPointerAddrSpace(
  9388. cast<PointerType>(Arg.getType())->getAddressSpace());
  9389. }
  9390. if (Arg.hasAttribute(Attribute::ZExt))
  9391. Flags.setZExt();
  9392. if (Arg.hasAttribute(Attribute::SExt))
  9393. Flags.setSExt();
  9394. if (Arg.hasAttribute(Attribute::InReg)) {
  9395. // If we are using vectorcall calling convention, a structure that is
  9396. // passed InReg - is surely an HVA
  9397. if (F.getCallingConv() == CallingConv::X86_VectorCall &&
  9398. isa<StructType>(Arg.getType())) {
  9399. // The first value of a structure is marked
  9400. if (0 == Value)
  9401. Flags.setHvaStart();
  9402. Flags.setHva();
  9403. }
  9404. // Set InReg Flag
  9405. Flags.setInReg();
  9406. }
  9407. if (Arg.hasAttribute(Attribute::StructRet))
  9408. Flags.setSRet();
  9409. if (Arg.hasAttribute(Attribute::SwiftSelf))
  9410. Flags.setSwiftSelf();
  9411. if (Arg.hasAttribute(Attribute::SwiftAsync))
  9412. Flags.setSwiftAsync();
  9413. if (Arg.hasAttribute(Attribute::SwiftError))
  9414. Flags.setSwiftError();
  9415. if (Arg.hasAttribute(Attribute::ByVal))
  9416. Flags.setByVal();
  9417. if (Arg.hasAttribute(Attribute::ByRef))
  9418. Flags.setByRef();
  9419. if (Arg.hasAttribute(Attribute::InAlloca)) {
  9420. Flags.setInAlloca();
  9421. // Set the byval flag for CCAssignFn callbacks that don't know about
  9422. // inalloca. This way we can know how many bytes we should've allocated
  9423. // and how many bytes a callee cleanup function will pop. If we port
  9424. // inalloca to more targets, we'll have to add custom inalloca handling
  9425. // in the various CC lowering callbacks.
  9426. Flags.setByVal();
  9427. }
  9428. if (Arg.hasAttribute(Attribute::Preallocated)) {
  9429. Flags.setPreallocated();
  9430. // Set the byval flag for CCAssignFn callbacks that don't know about
  9431. // preallocated. This way we can know how many bytes we should've
  9432. // allocated and how many bytes a callee cleanup function will pop. If
  9433. // we port preallocated to more targets, we'll have to add custom
  9434. // preallocated handling in the various CC lowering callbacks.
  9435. Flags.setByVal();
  9436. }
  9437. // Certain targets (such as MIPS), may have a different ABI alignment
  9438. // for a type depending on the context. Give the target a chance to
  9439. // specify the alignment it wants.
  9440. const Align OriginalAlignment(
  9441. TLI->getABIAlignmentForCallingConv(ArgTy, DL));
  9442. Flags.setOrigAlign(OriginalAlignment);
  9443. Align MemAlign;
  9444. Type *ArgMemTy = nullptr;
  9445. if (Flags.isByVal() || Flags.isInAlloca() || Flags.isPreallocated() ||
  9446. Flags.isByRef()) {
  9447. if (!ArgMemTy)
  9448. ArgMemTy = Arg.getPointeeInMemoryValueType();
  9449. uint64_t MemSize = DL.getTypeAllocSize(ArgMemTy);
  9450. // For in-memory arguments, size and alignment should be passed from FE.
  9451. // BE will guess if this info is not there but there are cases it cannot
  9452. // get right.
  9453. if (auto ParamAlign = Arg.getParamStackAlign())
  9454. MemAlign = *ParamAlign;
  9455. else if ((ParamAlign = Arg.getParamAlign()))
  9456. MemAlign = *ParamAlign;
  9457. else
  9458. MemAlign = Align(TLI->getByValTypeAlignment(ArgMemTy, DL));
  9459. if (Flags.isByRef())
  9460. Flags.setByRefSize(MemSize);
  9461. else
  9462. Flags.setByValSize(MemSize);
  9463. } else if (auto ParamAlign = Arg.getParamStackAlign()) {
  9464. MemAlign = *ParamAlign;
  9465. } else {
  9466. MemAlign = OriginalAlignment;
  9467. }
  9468. Flags.setMemAlign(MemAlign);
  9469. if (Arg.hasAttribute(Attribute::Nest))
  9470. Flags.setNest();
  9471. if (NeedsRegBlock)
  9472. Flags.setInConsecutiveRegs();
  9473. if (ArgCopyElisionCandidates.count(&Arg))
  9474. Flags.setCopyElisionCandidate();
  9475. if (Arg.hasAttribute(Attribute::Returned))
  9476. Flags.setReturned();
  9477. MVT RegisterVT = TLI->getRegisterTypeForCallingConv(
  9478. *CurDAG->getContext(), F.getCallingConv(), VT);
  9479. unsigned NumRegs = TLI->getNumRegistersForCallingConv(
  9480. *CurDAG->getContext(), F.getCallingConv(), VT);
  9481. for (unsigned i = 0; i != NumRegs; ++i) {
  9482. // For scalable vectors, use the minimum size; individual targets
  9483. // are responsible for handling scalable vector arguments and
  9484. // return values.
  9485. ISD::InputArg MyFlags(
  9486. Flags, RegisterVT, VT, isArgValueUsed, ArgNo,
  9487. PartBase + i * RegisterVT.getStoreSize().getKnownMinValue());
  9488. if (NumRegs > 1 && i == 0)
  9489. MyFlags.Flags.setSplit();
  9490. // if it isn't first piece, alignment must be 1
  9491. else if (i > 0) {
  9492. MyFlags.Flags.setOrigAlign(Align(1));
  9493. if (i == NumRegs - 1)
  9494. MyFlags.Flags.setSplitEnd();
  9495. }
  9496. Ins.push_back(MyFlags);
  9497. }
  9498. if (NeedsRegBlock && Value == NumValues - 1)
  9499. Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast();
  9500. PartBase += VT.getStoreSize().getKnownMinValue();
  9501. }
  9502. }
  9503. // Call the target to set up the argument values.
  9504. SmallVector<SDValue, 8> InVals;
  9505. SDValue NewRoot = TLI->LowerFormalArguments(
  9506. DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals);
  9507. // Verify that the target's LowerFormalArguments behaved as expected.
  9508. assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
  9509. "LowerFormalArguments didn't return a valid chain!");
  9510. assert(InVals.size() == Ins.size() &&
  9511. "LowerFormalArguments didn't emit the correct number of values!");
  9512. LLVM_DEBUG({
  9513. for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
  9514. assert(InVals[i].getNode() &&
  9515. "LowerFormalArguments emitted a null value!");
  9516. assert(EVT(Ins[i].VT) == InVals[i].getValueType() &&
  9517. "LowerFormalArguments emitted a value with the wrong type!");
  9518. }
  9519. });
  9520. // Update the DAG with the new chain value resulting from argument lowering.
  9521. DAG.setRoot(NewRoot);
  9522. // Set up the argument values.
  9523. unsigned i = 0;
  9524. if (!FuncInfo->CanLowerReturn) {
  9525. // Create a virtual register for the sret pointer, and put in a copy
  9526. // from the sret argument into it.
  9527. SmallVector<EVT, 1> ValueVTs;
  9528. ComputeValueVTs(*TLI, DAG.getDataLayout(),
  9529. F.getReturnType()->getPointerTo(
  9530. DAG.getDataLayout().getAllocaAddrSpace()),
  9531. ValueVTs);
  9532. MVT VT = ValueVTs[0].getSimpleVT();
  9533. MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
  9534. std::optional<ISD::NodeType> AssertOp;
  9535. SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT,
  9536. nullptr, F.getCallingConv(), AssertOp);
  9537. MachineFunction& MF = SDB->DAG.getMachineFunction();
  9538. MachineRegisterInfo& RegInfo = MF.getRegInfo();
  9539. Register SRetReg =
  9540. RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT));
  9541. FuncInfo->DemoteRegister = SRetReg;
  9542. NewRoot =
  9543. SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue);
  9544. DAG.setRoot(NewRoot);
  9545. // i indexes lowered arguments. Bump it past the hidden sret argument.
  9546. ++i;
  9547. }
  9548. SmallVector<SDValue, 4> Chains;
  9549. DenseMap<int, int> ArgCopyElisionFrameIndexMap;
  9550. for (const Argument &Arg : F.args()) {
  9551. SmallVector<SDValue, 4> ArgValues;
  9552. SmallVector<EVT, 4> ValueVTs;
  9553. ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
  9554. unsigned NumValues = ValueVTs.size();
  9555. if (NumValues == 0)
  9556. continue;
  9557. bool ArgHasUses = !Arg.use_empty();
  9558. // Elide the copying store if the target loaded this argument from a
  9559. // suitable fixed stack object.
  9560. if (Ins[i].Flags.isCopyElisionCandidate()) {
  9561. tryToElideArgumentCopy(*FuncInfo, Chains, ArgCopyElisionFrameIndexMap,
  9562. ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg,
  9563. InVals[i], ArgHasUses);
  9564. }
  9565. // If this argument is unused then remember its value. It is used to generate
  9566. // debugging information.
  9567. bool isSwiftErrorArg =
  9568. TLI->supportSwiftError() &&
  9569. Arg.hasAttribute(Attribute::SwiftError);
  9570. if (!ArgHasUses && !isSwiftErrorArg) {
  9571. SDB->setUnusedArgValue(&Arg, InVals[i]);
  9572. // Also remember any frame index for use in FastISel.
  9573. if (FrameIndexSDNode *FI =
  9574. dyn_cast<FrameIndexSDNode>(InVals[i].getNode()))
  9575. FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
  9576. }
  9577. for (unsigned Val = 0; Val != NumValues; ++Val) {
  9578. EVT VT = ValueVTs[Val];
  9579. MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(),
  9580. F.getCallingConv(), VT);
  9581. unsigned NumParts = TLI->getNumRegistersForCallingConv(
  9582. *CurDAG->getContext(), F.getCallingConv(), VT);
  9583. // Even an apparent 'unused' swifterror argument needs to be returned. So
  9584. // we do generate a copy for it that can be used on return from the
  9585. // function.
  9586. if (ArgHasUses || isSwiftErrorArg) {
  9587. std::optional<ISD::NodeType> AssertOp;
  9588. if (Arg.hasAttribute(Attribute::SExt))
  9589. AssertOp = ISD::AssertSext;
  9590. else if (Arg.hasAttribute(Attribute::ZExt))
  9591. AssertOp = ISD::AssertZext;
  9592. ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts,
  9593. PartVT, VT, nullptr,
  9594. F.getCallingConv(), AssertOp));
  9595. }
  9596. i += NumParts;
  9597. }
  9598. // We don't need to do anything else for unused arguments.
  9599. if (ArgValues.empty())
  9600. continue;
  9601. // Note down frame index.
  9602. if (FrameIndexSDNode *FI =
  9603. dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode()))
  9604. FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
  9605. SDValue Res = DAG.getMergeValues(ArrayRef(ArgValues.data(), NumValues),
  9606. SDB->getCurSDLoc());
  9607. SDB->setValue(&Arg, Res);
  9608. if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) {
  9609. // We want to associate the argument with the frame index, among
  9610. // involved operands, that correspond to the lowest address. The
  9611. // getCopyFromParts function, called earlier, is swapping the order of
  9612. // the operands to BUILD_PAIR depending on endianness. The result of
  9613. // that swapping is that the least significant bits of the argument will
  9614. // be in the first operand of the BUILD_PAIR node, and the most
  9615. // significant bits will be in the second operand.
  9616. unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0;
  9617. if (LoadSDNode *LNode =
  9618. dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode()))
  9619. if (FrameIndexSDNode *FI =
  9620. dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
  9621. FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
  9622. }
  9623. // Analyses past this point are naive and don't expect an assertion.
  9624. if (Res.getOpcode() == ISD::AssertZext)
  9625. Res = Res.getOperand(0);
  9626. // Update the SwiftErrorVRegDefMap.
  9627. if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) {
  9628. unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
  9629. if (Register::isVirtualRegister(Reg))
  9630. SwiftError->setCurrentVReg(FuncInfo->MBB, SwiftError->getFunctionArg(),
  9631. Reg);
  9632. }
  9633. // If this argument is live outside of the entry block, insert a copy from
  9634. // wherever we got it to the vreg that other BB's will reference it as.
  9635. if (Res.getOpcode() == ISD::CopyFromReg) {
  9636. // If we can, though, try to skip creating an unnecessary vreg.
  9637. // FIXME: This isn't very clean... it would be nice to make this more
  9638. // general.
  9639. unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
  9640. if (Register::isVirtualRegister(Reg)) {
  9641. FuncInfo->ValueMap[&Arg] = Reg;
  9642. continue;
  9643. }
  9644. }
  9645. if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) {
  9646. FuncInfo->InitializeRegForValue(&Arg);
  9647. SDB->CopyToExportRegsIfNeeded(&Arg);
  9648. }
  9649. }
  9650. if (!Chains.empty()) {
  9651. Chains.push_back(NewRoot);
  9652. NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
  9653. }
  9654. DAG.setRoot(NewRoot);
  9655. assert(i == InVals.size() && "Argument register count mismatch!");
  9656. // If any argument copy elisions occurred and we have debug info, update the
  9657. // stale frame indices used in the dbg.declare variable info table.
  9658. MachineFunction::VariableDbgInfoMapTy &DbgDeclareInfo = MF->getVariableDbgInfo();
  9659. if (!DbgDeclareInfo.empty() && !ArgCopyElisionFrameIndexMap.empty()) {
  9660. for (MachineFunction::VariableDbgInfo &VI : DbgDeclareInfo) {
  9661. auto I = ArgCopyElisionFrameIndexMap.find(VI.Slot);
  9662. if (I != ArgCopyElisionFrameIndexMap.end())
  9663. VI.Slot = I->second;
  9664. }
  9665. }
  9666. // Finally, if the target has anything special to do, allow it to do so.
  9667. emitFunctionEntryCode();
  9668. }
  9669. /// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
  9670. /// ensure constants are generated when needed. Remember the virtual registers
  9671. /// that need to be added to the Machine PHI nodes as input. We cannot just
  9672. /// directly add them, because expansion might result in multiple MBB's for one
  9673. /// BB. As such, the start of the BB might correspond to a different MBB than
  9674. /// the end.
  9675. void
  9676. SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
  9677. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  9678. SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
  9679. // Check PHI nodes in successors that expect a value to be available from this
  9680. // block.
  9681. for (const BasicBlock *SuccBB : successors(LLVMBB->getTerminator())) {
  9682. if (!isa<PHINode>(SuccBB->begin())) continue;
  9683. MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
  9684. // If this terminator has multiple identical successors (common for
  9685. // switches), only handle each succ once.
  9686. if (!SuccsHandled.insert(SuccMBB).second)
  9687. continue;
  9688. MachineBasicBlock::iterator MBBI = SuccMBB->begin();
  9689. // At this point we know that there is a 1-1 correspondence between LLVM PHI
  9690. // nodes and Machine PHI nodes, but the incoming operands have not been
  9691. // emitted yet.
  9692. for (const PHINode &PN : SuccBB->phis()) {
  9693. // Ignore dead phi's.
  9694. if (PN.use_empty())
  9695. continue;
  9696. // Skip empty types
  9697. if (PN.getType()->isEmptyTy())
  9698. continue;
  9699. unsigned Reg;
  9700. const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB);
  9701. if (const auto *C = dyn_cast<Constant>(PHIOp)) {
  9702. unsigned &RegOut = ConstantsOut[C];
  9703. if (RegOut == 0) {
  9704. RegOut = FuncInfo.CreateRegs(C);
  9705. // We need to zero/sign extend ConstantInt phi operands to match
  9706. // assumptions in FunctionLoweringInfo::ComputePHILiveOutRegInfo.
  9707. ISD::NodeType ExtendType = ISD::ANY_EXTEND;
  9708. if (auto *CI = dyn_cast<ConstantInt>(C))
  9709. ExtendType = TLI.signExtendConstant(CI) ? ISD::SIGN_EXTEND
  9710. : ISD::ZERO_EXTEND;
  9711. CopyValueToVirtualRegister(C, RegOut, ExtendType);
  9712. }
  9713. Reg = RegOut;
  9714. } else {
  9715. DenseMap<const Value *, Register>::iterator I =
  9716. FuncInfo.ValueMap.find(PHIOp);
  9717. if (I != FuncInfo.ValueMap.end())
  9718. Reg = I->second;
  9719. else {
  9720. assert(isa<AllocaInst>(PHIOp) &&
  9721. FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
  9722. "Didn't codegen value into a register!??");
  9723. Reg = FuncInfo.CreateRegs(PHIOp);
  9724. CopyValueToVirtualRegister(PHIOp, Reg);
  9725. }
  9726. }
  9727. // Remember that this register needs to added to the machine PHI node as
  9728. // the input for this MBB.
  9729. SmallVector<EVT, 4> ValueVTs;
  9730. ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs);
  9731. for (EVT VT : ValueVTs) {
  9732. const unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT);
  9733. for (unsigned i = 0; i != NumRegisters; ++i)
  9734. FuncInfo.PHINodesToUpdate.push_back(
  9735. std::make_pair(&*MBBI++, Reg + i));
  9736. Reg += NumRegisters;
  9737. }
  9738. }
  9739. }
  9740. ConstantsOut.clear();
  9741. }
  9742. MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) {
  9743. MachineFunction::iterator I(MBB);
  9744. if (++I == FuncInfo.MF->end())
  9745. return nullptr;
  9746. return &*I;
  9747. }
  9748. /// During lowering new call nodes can be created (such as memset, etc.).
  9749. /// Those will become new roots of the current DAG, but complications arise
  9750. /// when they are tail calls. In such cases, the call lowering will update
  9751. /// the root, but the builder still needs to know that a tail call has been
  9752. /// lowered in order to avoid generating an additional return.
  9753. void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) {
  9754. // If the node is null, we do have a tail call.
  9755. if (MaybeTC.getNode() != nullptr)
  9756. DAG.setRoot(MaybeTC);
  9757. else
  9758. HasTailCall = true;
  9759. }
  9760. void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond,
  9761. MachineBasicBlock *SwitchMBB,
  9762. MachineBasicBlock *DefaultMBB) {
  9763. MachineFunction *CurMF = FuncInfo.MF;
  9764. MachineBasicBlock *NextMBB = nullptr;
  9765. MachineFunction::iterator BBI(W.MBB);
  9766. if (++BBI != FuncInfo.MF->end())
  9767. NextMBB = &*BBI;
  9768. unsigned Size = W.LastCluster - W.FirstCluster + 1;
  9769. BranchProbabilityInfo *BPI = FuncInfo.BPI;
  9770. if (Size == 2 && W.MBB == SwitchMBB) {
  9771. // If any two of the cases has the same destination, and if one value
  9772. // is the same as the other, but has one bit unset that the other has set,
  9773. // use bit manipulation to do two compares at once. For example:
  9774. // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
  9775. // TODO: This could be extended to merge any 2 cases in switches with 3
  9776. // cases.
  9777. // TODO: Handle cases where W.CaseBB != SwitchBB.
  9778. CaseCluster &Small = *W.FirstCluster;
  9779. CaseCluster &Big = *W.LastCluster;
  9780. if (Small.Low == Small.High && Big.Low == Big.High &&
  9781. Small.MBB == Big.MBB) {
  9782. const APInt &SmallValue = Small.Low->getValue();
  9783. const APInt &BigValue = Big.Low->getValue();
  9784. // Check that there is only one bit different.
  9785. APInt CommonBit = BigValue ^ SmallValue;
  9786. if (CommonBit.isPowerOf2()) {
  9787. SDValue CondLHS = getValue(Cond);
  9788. EVT VT = CondLHS.getValueType();
  9789. SDLoc DL = getCurSDLoc();
  9790. SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS,
  9791. DAG.getConstant(CommonBit, DL, VT));
  9792. SDValue Cond = DAG.getSetCC(
  9793. DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT),
  9794. ISD::SETEQ);
  9795. // Update successor info.
  9796. // Both Small and Big will jump to Small.BB, so we sum up the
  9797. // probabilities.
  9798. addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob);
  9799. if (BPI)
  9800. addSuccessorWithProb(
  9801. SwitchMBB, DefaultMBB,
  9802. // The default destination is the first successor in IR.
  9803. BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0));
  9804. else
  9805. addSuccessorWithProb(SwitchMBB, DefaultMBB);
  9806. // Insert the true branch.
  9807. SDValue BrCond =
  9808. DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond,
  9809. DAG.getBasicBlock(Small.MBB));
  9810. // Insert the false branch.
  9811. BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond,
  9812. DAG.getBasicBlock(DefaultMBB));
  9813. DAG.setRoot(BrCond);
  9814. return;
  9815. }
  9816. }
  9817. }
  9818. if (TM.getOptLevel() != CodeGenOpt::None) {
  9819. // Here, we order cases by probability so the most likely case will be
  9820. // checked first. However, two clusters can have the same probability in
  9821. // which case their relative ordering is non-deterministic. So we use Low
  9822. // as a tie-breaker as clusters are guaranteed to never overlap.
  9823. llvm::sort(W.FirstCluster, W.LastCluster + 1,
  9824. [](const CaseCluster &a, const CaseCluster &b) {
  9825. return a.Prob != b.Prob ?
  9826. a.Prob > b.Prob :
  9827. a.Low->getValue().slt(b.Low->getValue());
  9828. });
  9829. // Rearrange the case blocks so that the last one falls through if possible
  9830. // without changing the order of probabilities.
  9831. for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) {
  9832. --I;
  9833. if (I->Prob > W.LastCluster->Prob)
  9834. break;
  9835. if (I->Kind == CC_Range && I->MBB == NextMBB) {
  9836. std::swap(*I, *W.LastCluster);
  9837. break;
  9838. }
  9839. }
  9840. }
  9841. // Compute total probability.
  9842. BranchProbability DefaultProb = W.DefaultProb;
  9843. BranchProbability UnhandledProbs = DefaultProb;
  9844. for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I)
  9845. UnhandledProbs += I->Prob;
  9846. MachineBasicBlock *CurMBB = W.MBB;
  9847. for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) {
  9848. bool FallthroughUnreachable = false;
  9849. MachineBasicBlock *Fallthrough;
  9850. if (I == W.LastCluster) {
  9851. // For the last cluster, fall through to the default destination.
  9852. Fallthrough = DefaultMBB;
  9853. FallthroughUnreachable = isa<UnreachableInst>(
  9854. DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg());
  9855. } else {
  9856. Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock());
  9857. CurMF->insert(BBI, Fallthrough);
  9858. // Put Cond in a virtual register to make it available from the new blocks.
  9859. ExportFromCurrentBlock(Cond);
  9860. }
  9861. UnhandledProbs -= I->Prob;
  9862. switch (I->Kind) {
  9863. case CC_JumpTable: {
  9864. // FIXME: Optimize away range check based on pivot comparisons.
  9865. JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first;
  9866. SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second;
  9867. // The jump block hasn't been inserted yet; insert it here.
  9868. MachineBasicBlock *JumpMBB = JT->MBB;
  9869. CurMF->insert(BBI, JumpMBB);
  9870. auto JumpProb = I->Prob;
  9871. auto FallthroughProb = UnhandledProbs;
  9872. // If the default statement is a target of the jump table, we evenly
  9873. // distribute the default probability to successors of CurMBB. Also
  9874. // update the probability on the edge from JumpMBB to Fallthrough.
  9875. for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(),
  9876. SE = JumpMBB->succ_end();
  9877. SI != SE; ++SI) {
  9878. if (*SI == DefaultMBB) {
  9879. JumpProb += DefaultProb / 2;
  9880. FallthroughProb -= DefaultProb / 2;
  9881. JumpMBB->setSuccProbability(SI, DefaultProb / 2);
  9882. JumpMBB->normalizeSuccProbs();
  9883. break;
  9884. }
  9885. }
  9886. if (FallthroughUnreachable)
  9887. JTH->FallthroughUnreachable = true;
  9888. if (!JTH->FallthroughUnreachable)
  9889. addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb);
  9890. addSuccessorWithProb(CurMBB, JumpMBB, JumpProb);
  9891. CurMBB->normalizeSuccProbs();
  9892. // The jump table header will be inserted in our current block, do the
  9893. // range check, and fall through to our fallthrough block.
  9894. JTH->HeaderBB = CurMBB;
  9895. JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader.
  9896. // If we're in the right place, emit the jump table header right now.
  9897. if (CurMBB == SwitchMBB) {
  9898. visitJumpTableHeader(*JT, *JTH, SwitchMBB);
  9899. JTH->Emitted = true;
  9900. }
  9901. break;
  9902. }
  9903. case CC_BitTests: {
  9904. // FIXME: Optimize away range check based on pivot comparisons.
  9905. BitTestBlock *BTB = &SL->BitTestCases[I->BTCasesIndex];
  9906. // The bit test blocks haven't been inserted yet; insert them here.
  9907. for (BitTestCase &BTC : BTB->Cases)
  9908. CurMF->insert(BBI, BTC.ThisBB);
  9909. // Fill in fields of the BitTestBlock.
  9910. BTB->Parent = CurMBB;
  9911. BTB->Default = Fallthrough;
  9912. BTB->DefaultProb = UnhandledProbs;
  9913. // If the cases in bit test don't form a contiguous range, we evenly
  9914. // distribute the probability on the edge to Fallthrough to two
  9915. // successors of CurMBB.
  9916. if (!BTB->ContiguousRange) {
  9917. BTB->Prob += DefaultProb / 2;
  9918. BTB->DefaultProb -= DefaultProb / 2;
  9919. }
  9920. if (FallthroughUnreachable)
  9921. BTB->FallthroughUnreachable = true;
  9922. // If we're in the right place, emit the bit test header right now.
  9923. if (CurMBB == SwitchMBB) {
  9924. visitBitTestHeader(*BTB, SwitchMBB);
  9925. BTB->Emitted = true;
  9926. }
  9927. break;
  9928. }
  9929. case CC_Range: {
  9930. const Value *RHS, *LHS, *MHS;
  9931. ISD::CondCode CC;
  9932. if (I->Low == I->High) {
  9933. // Check Cond == I->Low.
  9934. CC = ISD::SETEQ;
  9935. LHS = Cond;
  9936. RHS=I->Low;
  9937. MHS = nullptr;
  9938. } else {
  9939. // Check I->Low <= Cond <= I->High.
  9940. CC = ISD::SETLE;
  9941. LHS = I->Low;
  9942. MHS = Cond;
  9943. RHS = I->High;
  9944. }
  9945. // If Fallthrough is unreachable, fold away the comparison.
  9946. if (FallthroughUnreachable)
  9947. CC = ISD::SETTRUE;
  9948. // The false probability is the sum of all unhandled cases.
  9949. CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB,
  9950. getCurSDLoc(), I->Prob, UnhandledProbs);
  9951. if (CurMBB == SwitchMBB)
  9952. visitSwitchCase(CB, SwitchMBB);
  9953. else
  9954. SL->SwitchCases.push_back(CB);
  9955. break;
  9956. }
  9957. }
  9958. CurMBB = Fallthrough;
  9959. }
  9960. }
  9961. unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC,
  9962. CaseClusterIt First,
  9963. CaseClusterIt Last) {
  9964. return std::count_if(First, Last + 1, [&](const CaseCluster &X) {
  9965. if (X.Prob != CC.Prob)
  9966. return X.Prob > CC.Prob;
  9967. // Ties are broken by comparing the case value.
  9968. return X.Low->getValue().slt(CC.Low->getValue());
  9969. });
  9970. }
  9971. void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList,
  9972. const SwitchWorkListItem &W,
  9973. Value *Cond,
  9974. MachineBasicBlock *SwitchMBB) {
  9975. assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) &&
  9976. "Clusters not sorted?");
  9977. assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!");
  9978. // Balance the tree based on branch probabilities to create a near-optimal (in
  9979. // terms of search time given key frequency) binary search tree. See e.g. Kurt
  9980. // Mehlhorn "Nearly Optimal Binary Search Trees" (1975).
  9981. CaseClusterIt LastLeft = W.FirstCluster;
  9982. CaseClusterIt FirstRight = W.LastCluster;
  9983. auto LeftProb = LastLeft->Prob + W.DefaultProb / 2;
  9984. auto RightProb = FirstRight->Prob + W.DefaultProb / 2;
  9985. // Move LastLeft and FirstRight towards each other from opposite directions to
  9986. // find a partitioning of the clusters which balances the probability on both
  9987. // sides. If LeftProb and RightProb are equal, alternate which side is
  9988. // taken to ensure 0-probability nodes are distributed evenly.
  9989. unsigned I = 0;
  9990. while (LastLeft + 1 < FirstRight) {
  9991. if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1)))
  9992. LeftProb += (++LastLeft)->Prob;
  9993. else
  9994. RightProb += (--FirstRight)->Prob;
  9995. I++;
  9996. }
  9997. while (true) {
  9998. // Our binary search tree differs from a typical BST in that ours can have up
  9999. // to three values in each leaf. The pivot selection above doesn't take that
  10000. // into account, which means the tree might require more nodes and be less
  10001. // efficient. We compensate for this here.
  10002. unsigned NumLeft = LastLeft - W.FirstCluster + 1;
  10003. unsigned NumRight = W.LastCluster - FirstRight + 1;
  10004. if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) {
  10005. // If one side has less than 3 clusters, and the other has more than 3,
  10006. // consider taking a cluster from the other side.
  10007. if (NumLeft < NumRight) {
  10008. // Consider moving the first cluster on the right to the left side.
  10009. CaseCluster &CC = *FirstRight;
  10010. unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
  10011. unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
  10012. if (LeftSideRank <= RightSideRank) {
  10013. // Moving the cluster to the left does not demote it.
  10014. ++LastLeft;
  10015. ++FirstRight;
  10016. continue;
  10017. }
  10018. } else {
  10019. assert(NumRight < NumLeft);
  10020. // Consider moving the last element on the left to the right side.
  10021. CaseCluster &CC = *LastLeft;
  10022. unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
  10023. unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
  10024. if (RightSideRank <= LeftSideRank) {
  10025. // Moving the cluster to the right does not demot it.
  10026. --LastLeft;
  10027. --FirstRight;
  10028. continue;
  10029. }
  10030. }
  10031. }
  10032. break;
  10033. }
  10034. assert(LastLeft + 1 == FirstRight);
  10035. assert(LastLeft >= W.FirstCluster);
  10036. assert(FirstRight <= W.LastCluster);
  10037. // Use the first element on the right as pivot since we will make less-than
  10038. // comparisons against it.
  10039. CaseClusterIt PivotCluster = FirstRight;
  10040. assert(PivotCluster > W.FirstCluster);
  10041. assert(PivotCluster <= W.LastCluster);
  10042. CaseClusterIt FirstLeft = W.FirstCluster;
  10043. CaseClusterIt LastRight = W.LastCluster;
  10044. const ConstantInt *Pivot = PivotCluster->Low;
  10045. // New blocks will be inserted immediately after the current one.
  10046. MachineFunction::iterator BBI(W.MBB);
  10047. ++BBI;
  10048. // We will branch to the LHS if Value < Pivot. If LHS is a single cluster,
  10049. // we can branch to its destination directly if it's squeezed exactly in
  10050. // between the known lower bound and Pivot - 1.
  10051. MachineBasicBlock *LeftMBB;
  10052. if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range &&
  10053. FirstLeft->Low == W.GE &&
  10054. (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) {
  10055. LeftMBB = FirstLeft->MBB;
  10056. } else {
  10057. LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
  10058. FuncInfo.MF->insert(BBI, LeftMBB);
  10059. WorkList.push_back(
  10060. {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2});
  10061. // Put Cond in a virtual register to make it available from the new blocks.
  10062. ExportFromCurrentBlock(Cond);
  10063. }
  10064. // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a
  10065. // single cluster, RHS.Low == Pivot, and we can branch to its destination
  10066. // directly if RHS.High equals the current upper bound.
  10067. MachineBasicBlock *RightMBB;
  10068. if (FirstRight == LastRight && FirstRight->Kind == CC_Range &&
  10069. W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) {
  10070. RightMBB = FirstRight->MBB;
  10071. } else {
  10072. RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
  10073. FuncInfo.MF->insert(BBI, RightMBB);
  10074. WorkList.push_back(
  10075. {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2});
  10076. // Put Cond in a virtual register to make it available from the new blocks.
  10077. ExportFromCurrentBlock(Cond);
  10078. }
  10079. // Create the CaseBlock record that will be used to lower the branch.
  10080. CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB,
  10081. getCurSDLoc(), LeftProb, RightProb);
  10082. if (W.MBB == SwitchMBB)
  10083. visitSwitchCase(CB, SwitchMBB);
  10084. else
  10085. SL->SwitchCases.push_back(CB);
  10086. }
  10087. // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb
  10088. // from the swith statement.
  10089. static BranchProbability scaleCaseProbality(BranchProbability CaseProb,
  10090. BranchProbability PeeledCaseProb) {
  10091. if (PeeledCaseProb == BranchProbability::getOne())
  10092. return BranchProbability::getZero();
  10093. BranchProbability SwitchProb = PeeledCaseProb.getCompl();
  10094. uint32_t Numerator = CaseProb.getNumerator();
  10095. uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator());
  10096. return BranchProbability(Numerator, std::max(Numerator, Denominator));
  10097. }
  10098. // Try to peel the top probability case if it exceeds the threshold.
  10099. // Return current MachineBasicBlock for the switch statement if the peeling
  10100. // does not occur.
  10101. // If the peeling is performed, return the newly created MachineBasicBlock
  10102. // for the peeled switch statement. Also update Clusters to remove the peeled
  10103. // case. PeeledCaseProb is the BranchProbability for the peeled case.
  10104. MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster(
  10105. const SwitchInst &SI, CaseClusterVector &Clusters,
  10106. BranchProbability &PeeledCaseProb) {
  10107. MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
  10108. // Don't perform if there is only one cluster or optimizing for size.
  10109. if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 ||
  10110. TM.getOptLevel() == CodeGenOpt::None ||
  10111. SwitchMBB->getParent()->getFunction().hasMinSize())
  10112. return SwitchMBB;
  10113. BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100);
  10114. unsigned PeeledCaseIndex = 0;
  10115. bool SwitchPeeled = false;
  10116. for (unsigned Index = 0; Index < Clusters.size(); ++Index) {
  10117. CaseCluster &CC = Clusters[Index];
  10118. if (CC.Prob < TopCaseProb)
  10119. continue;
  10120. TopCaseProb = CC.Prob;
  10121. PeeledCaseIndex = Index;
  10122. SwitchPeeled = true;
  10123. }
  10124. if (!SwitchPeeled)
  10125. return SwitchMBB;
  10126. LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: "
  10127. << TopCaseProb << "\n");
  10128. // Record the MBB for the peeled switch statement.
  10129. MachineFunction::iterator BBI(SwitchMBB);
  10130. ++BBI;
  10131. MachineBasicBlock *PeeledSwitchMBB =
  10132. FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock());
  10133. FuncInfo.MF->insert(BBI, PeeledSwitchMBB);
  10134. ExportFromCurrentBlock(SI.getCondition());
  10135. auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex;
  10136. SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt,
  10137. nullptr, nullptr, TopCaseProb.getCompl()};
  10138. lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB);
  10139. Clusters.erase(PeeledCaseIt);
  10140. for (CaseCluster &CC : Clusters) {
  10141. LLVM_DEBUG(
  10142. dbgs() << "Scale the probablity for one cluster, before scaling: "
  10143. << CC.Prob << "\n");
  10144. CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb);
  10145. LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n");
  10146. }
  10147. PeeledCaseProb = TopCaseProb;
  10148. return PeeledSwitchMBB;
  10149. }
  10150. void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) {
  10151. // Extract cases from the switch.
  10152. BranchProbabilityInfo *BPI = FuncInfo.BPI;
  10153. CaseClusterVector Clusters;
  10154. Clusters.reserve(SI.getNumCases());
  10155. for (auto I : SI.cases()) {
  10156. MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()];
  10157. const ConstantInt *CaseVal = I.getCaseValue();
  10158. BranchProbability Prob =
  10159. BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex())
  10160. : BranchProbability(1, SI.getNumCases() + 1);
  10161. Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob));
  10162. }
  10163. MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()];
  10164. // Cluster adjacent cases with the same destination. We do this at all
  10165. // optimization levels because it's cheap to do and will make codegen faster
  10166. // if there are many clusters.
  10167. sortAndRangeify(Clusters);
  10168. // The branch probablity of the peeled case.
  10169. BranchProbability PeeledCaseProb = BranchProbability::getZero();
  10170. MachineBasicBlock *PeeledSwitchMBB =
  10171. peelDominantCaseCluster(SI, Clusters, PeeledCaseProb);
  10172. // If there is only the default destination, jump there directly.
  10173. MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
  10174. if (Clusters.empty()) {
  10175. assert(PeeledSwitchMBB == SwitchMBB);
  10176. SwitchMBB->addSuccessor(DefaultMBB);
  10177. if (DefaultMBB != NextBlock(SwitchMBB)) {
  10178. DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
  10179. getControlRoot(), DAG.getBasicBlock(DefaultMBB)));
  10180. }
  10181. return;
  10182. }
  10183. SL->findJumpTables(Clusters, &SI, DefaultMBB, DAG.getPSI(), DAG.getBFI());
  10184. SL->findBitTestClusters(Clusters, &SI);
  10185. LLVM_DEBUG({
  10186. dbgs() << "Case clusters: ";
  10187. for (const CaseCluster &C : Clusters) {
  10188. if (C.Kind == CC_JumpTable)
  10189. dbgs() << "JT:";
  10190. if (C.Kind == CC_BitTests)
  10191. dbgs() << "BT:";
  10192. C.Low->getValue().print(dbgs(), true);
  10193. if (C.Low != C.High) {
  10194. dbgs() << '-';
  10195. C.High->getValue().print(dbgs(), true);
  10196. }
  10197. dbgs() << ' ';
  10198. }
  10199. dbgs() << '\n';
  10200. });
  10201. assert(!Clusters.empty());
  10202. SwitchWorkList WorkList;
  10203. CaseClusterIt First = Clusters.begin();
  10204. CaseClusterIt Last = Clusters.end() - 1;
  10205. auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB);
  10206. // Scale the branchprobability for DefaultMBB if the peel occurs and
  10207. // DefaultMBB is not replaced.
  10208. if (PeeledCaseProb != BranchProbability::getZero() &&
  10209. DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()])
  10210. DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb);
  10211. WorkList.push_back(
  10212. {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb});
  10213. while (!WorkList.empty()) {
  10214. SwitchWorkListItem W = WorkList.pop_back_val();
  10215. unsigned NumClusters = W.LastCluster - W.FirstCluster + 1;
  10216. if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None &&
  10217. !DefaultMBB->getParent()->getFunction().hasMinSize()) {
  10218. // For optimized builds, lower large range as a balanced binary tree.
  10219. splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB);
  10220. continue;
  10221. }
  10222. lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB);
  10223. }
  10224. }
  10225. void SelectionDAGBuilder::visitStepVector(const CallInst &I) {
  10226. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  10227. auto DL = getCurSDLoc();
  10228. EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  10229. setValue(&I, DAG.getStepVector(DL, ResultVT));
  10230. }
  10231. void SelectionDAGBuilder::visitVectorReverse(const CallInst &I) {
  10232. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  10233. EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  10234. SDLoc DL = getCurSDLoc();
  10235. SDValue V = getValue(I.getOperand(0));
  10236. assert(VT == V.getValueType() && "Malformed vector.reverse!");
  10237. if (VT.isScalableVector()) {
  10238. setValue(&I, DAG.getNode(ISD::VECTOR_REVERSE, DL, VT, V));
  10239. return;
  10240. }
  10241. // Use VECTOR_SHUFFLE for the fixed-length vector
  10242. // to maintain existing behavior.
  10243. SmallVector<int, 8> Mask;
  10244. unsigned NumElts = VT.getVectorMinNumElements();
  10245. for (unsigned i = 0; i != NumElts; ++i)
  10246. Mask.push_back(NumElts - 1 - i);
  10247. setValue(&I, DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), Mask));
  10248. }
  10249. void SelectionDAGBuilder::visitFreeze(const FreezeInst &I) {
  10250. SmallVector<EVT, 4> ValueVTs;
  10251. ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
  10252. ValueVTs);
  10253. unsigned NumValues = ValueVTs.size();
  10254. if (NumValues == 0) return;
  10255. SmallVector<SDValue, 4> Values(NumValues);
  10256. SDValue Op = getValue(I.getOperand(0));
  10257. for (unsigned i = 0; i != NumValues; ++i)
  10258. Values[i] = DAG.getNode(ISD::FREEZE, getCurSDLoc(), ValueVTs[i],
  10259. SDValue(Op.getNode(), Op.getResNo() + i));
  10260. setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
  10261. DAG.getVTList(ValueVTs), Values));
  10262. }
  10263. void SelectionDAGBuilder::visitVectorSplice(const CallInst &I) {
  10264. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  10265. EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  10266. SDLoc DL = getCurSDLoc();
  10267. SDValue V1 = getValue(I.getOperand(0));
  10268. SDValue V2 = getValue(I.getOperand(1));
  10269. int64_t Imm = cast<ConstantInt>(I.getOperand(2))->getSExtValue();
  10270. // VECTOR_SHUFFLE doesn't support a scalable mask so use a dedicated node.
  10271. if (VT.isScalableVector()) {
  10272. MVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout());
  10273. setValue(&I, DAG.getNode(ISD::VECTOR_SPLICE, DL, VT, V1, V2,
  10274. DAG.getConstant(Imm, DL, IdxVT)));
  10275. return;
  10276. }
  10277. unsigned NumElts = VT.getVectorNumElements();
  10278. uint64_t Idx = (NumElts + Imm) % NumElts;
  10279. // Use VECTOR_SHUFFLE to maintain original behaviour for fixed-length vectors.
  10280. SmallVector<int, 8> Mask;
  10281. for (unsigned i = 0; i < NumElts; ++i)
  10282. Mask.push_back(Idx + i);
  10283. setValue(&I, DAG.getVectorShuffle(VT, DL, V1, V2, Mask));
  10284. }