SelectionDAGBuilder.cpp 406 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452
  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/ArrayRef.h"
  17. #include "llvm/ADT/BitVector.h"
  18. #include "llvm/ADT/DenseMap.h"
  19. #include "llvm/ADT/None.h"
  20. #include "llvm/ADT/Optional.h"
  21. #include "llvm/ADT/STLExtras.h"
  22. #include "llvm/ADT/SmallPtrSet.h"
  23. #include "llvm/ADT/SmallSet.h"
  24. #include "llvm/ADT/SmallVector.h"
  25. #include "llvm/ADT/StringRef.h"
  26. #include "llvm/ADT/Triple.h"
  27. #include "llvm/ADT/Twine.h"
  28. #include "llvm/Analysis/AliasAnalysis.h"
  29. #include "llvm/Analysis/BranchProbabilityInfo.h"
  30. #include "llvm/Analysis/ConstantFolding.h"
  31. #include "llvm/Analysis/EHPersonalities.h"
  32. #include "llvm/Analysis/Loads.h"
  33. #include "llvm/Analysis/MemoryLocation.h"
  34. #include "llvm/Analysis/TargetLibraryInfo.h"
  35. #include "llvm/Analysis/ValueTracking.h"
  36. #include "llvm/Analysis/VectorUtils.h"
  37. #include "llvm/CodeGen/Analysis.h"
  38. #include "llvm/CodeGen/FunctionLoweringInfo.h"
  39. #include "llvm/CodeGen/GCMetadata.h"
  40. #include "llvm/CodeGen/ISDOpcodes.h"
  41. #include "llvm/CodeGen/MachineBasicBlock.h"
  42. #include "llvm/CodeGen/MachineFrameInfo.h"
  43. #include "llvm/CodeGen/MachineFunction.h"
  44. #include "llvm/CodeGen/MachineInstr.h"
  45. #include "llvm/CodeGen/MachineInstrBuilder.h"
  46. #include "llvm/CodeGen/MachineJumpTableInfo.h"
  47. #include "llvm/CodeGen/MachineMemOperand.h"
  48. #include "llvm/CodeGen/MachineModuleInfo.h"
  49. #include "llvm/CodeGen/MachineOperand.h"
  50. #include "llvm/CodeGen/MachineRegisterInfo.h"
  51. #include "llvm/CodeGen/RuntimeLibcalls.h"
  52. #include "llvm/CodeGen/SelectionDAG.h"
  53. #include "llvm/CodeGen/SelectionDAGNodes.h"
  54. #include "llvm/CodeGen/SelectionDAGTargetInfo.h"
  55. #include "llvm/CodeGen/StackMaps.h"
  56. #include "llvm/CodeGen/SwiftErrorValueTracking.h"
  57. #include "llvm/CodeGen/TargetFrameLowering.h"
  58. #include "llvm/CodeGen/TargetInstrInfo.h"
  59. #include "llvm/CodeGen/TargetLowering.h"
  60. #include "llvm/CodeGen/TargetOpcodes.h"
  61. #include "llvm/CodeGen/TargetRegisterInfo.h"
  62. #include "llvm/CodeGen/TargetSubtargetInfo.h"
  63. #include "llvm/CodeGen/ValueTypes.h"
  64. #include "llvm/CodeGen/WinEHFuncInfo.h"
  65. #include "llvm/IR/Argument.h"
  66. #include "llvm/IR/Attributes.h"
  67. #include "llvm/IR/BasicBlock.h"
  68. #include "llvm/IR/CFG.h"
  69. #include "llvm/IR/CallSite.h"
  70. #include "llvm/IR/CallingConv.h"
  71. #include "llvm/IR/Constant.h"
  72. #include "llvm/IR/ConstantRange.h"
  73. #include "llvm/IR/Constants.h"
  74. #include "llvm/IR/DataLayout.h"
  75. #include "llvm/IR/DebugInfoMetadata.h"
  76. #include "llvm/IR/DebugLoc.h"
  77. #include "llvm/IR/DerivedTypes.h"
  78. #include "llvm/IR/Function.h"
  79. #include "llvm/IR/GetElementPtrTypeIterator.h"
  80. #include "llvm/IR/InlineAsm.h"
  81. #include "llvm/IR/InstrTypes.h"
  82. #include "llvm/IR/Instruction.h"
  83. #include "llvm/IR/Instructions.h"
  84. #include "llvm/IR/IntrinsicInst.h"
  85. #include "llvm/IR/Intrinsics.h"
  86. #include "llvm/IR/LLVMContext.h"
  87. #include "llvm/IR/Metadata.h"
  88. #include "llvm/IR/Module.h"
  89. #include "llvm/IR/Operator.h"
  90. #include "llvm/IR/PatternMatch.h"
  91. #include "llvm/IR/Statepoint.h"
  92. #include "llvm/IR/Type.h"
  93. #include "llvm/IR/User.h"
  94. #include "llvm/IR/Value.h"
  95. #include "llvm/MC/MCContext.h"
  96. #include "llvm/MC/MCSymbol.h"
  97. #include "llvm/Support/AtomicOrdering.h"
  98. #include "llvm/Support/BranchProbability.h"
  99. #include "llvm/Support/Casting.h"
  100. #include "llvm/Support/CodeGen.h"
  101. #include "llvm/Support/CommandLine.h"
  102. #include "llvm/Support/Compiler.h"
  103. #include "llvm/Support/Debug.h"
  104. #include "llvm/Support/ErrorHandling.h"
  105. #include "llvm/Support/MachineValueType.h"
  106. #include "llvm/Support/MathExtras.h"
  107. #include "llvm/Support/raw_ostream.h"
  108. #include "llvm/Target/TargetIntrinsicInfo.h"
  109. #include "llvm/Target/TargetMachine.h"
  110. #include "llvm/Target/TargetOptions.h"
  111. #include "llvm/Transforms/Utils/Local.h"
  112. #include <algorithm>
  113. #include <cassert>
  114. #include <cstddef>
  115. #include <cstdint>
  116. #include <cstring>
  117. #include <iterator>
  118. #include <limits>
  119. #include <numeric>
  120. #include <tuple>
  121. #include <utility>
  122. #include <vector>
  123. using namespace llvm;
  124. using namespace PatternMatch;
  125. using namespace SwitchCG;
  126. #define DEBUG_TYPE "isel"
  127. /// LimitFloatPrecision - Generate low-precision inline sequences for
  128. /// some float libcalls (6, 8 or 12 bits).
  129. static unsigned LimitFloatPrecision;
  130. static cl::opt<unsigned, true>
  131. LimitFPPrecision("limit-float-precision",
  132. cl::desc("Generate low-precision inline sequences "
  133. "for some float libcalls"),
  134. cl::location(LimitFloatPrecision), cl::Hidden,
  135. cl::init(0));
  136. static cl::opt<unsigned> SwitchPeelThreshold(
  137. "switch-peel-threshold", cl::Hidden, cl::init(66),
  138. cl::desc("Set the case probability threshold for peeling the case from a "
  139. "switch statement. A value greater than 100 will void this "
  140. "optimization"));
  141. // Limit the width of DAG chains. This is important in general to prevent
  142. // DAG-based analysis from blowing up. For example, alias analysis and
  143. // load clustering may not complete in reasonable time. It is difficult to
  144. // recognize and avoid this situation within each individual analysis, and
  145. // future analyses are likely to have the same behavior. Limiting DAG width is
  146. // the safe approach and will be especially important with global DAGs.
  147. //
  148. // MaxParallelChains default is arbitrarily high to avoid affecting
  149. // optimization, but could be lowered to improve compile time. Any ld-ld-st-st
  150. // sequence over this should have been converted to llvm.memcpy by the
  151. // frontend. It is easy to induce this behavior with .ll code such as:
  152. // %buffer = alloca [4096 x i8]
  153. // %data = load [4096 x i8]* %argPtr
  154. // store [4096 x i8] %data, [4096 x i8]* %buffer
  155. static const unsigned MaxParallelChains = 64;
  156. // Return the calling convention if the Value passed requires ABI mangling as it
  157. // is a parameter to a function or a return value from a function which is not
  158. // an intrinsic.
  159. static Optional<CallingConv::ID> getABIRegCopyCC(const Value *V) {
  160. if (auto *R = dyn_cast<ReturnInst>(V))
  161. return R->getParent()->getParent()->getCallingConv();
  162. if (auto *CI = dyn_cast<CallInst>(V)) {
  163. const bool IsInlineAsm = CI->isInlineAsm();
  164. const bool IsIndirectFunctionCall =
  165. !IsInlineAsm && !CI->getCalledFunction();
  166. // It is possible that the call instruction is an inline asm statement or an
  167. // indirect function call in which case the return value of
  168. // getCalledFunction() would be nullptr.
  169. const bool IsInstrinsicCall =
  170. !IsInlineAsm && !IsIndirectFunctionCall &&
  171. CI->getCalledFunction()->getIntrinsicID() != Intrinsic::not_intrinsic;
  172. if (!IsInlineAsm && !IsInstrinsicCall)
  173. return CI->getCallingConv();
  174. }
  175. return None;
  176. }
  177. static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
  178. const SDValue *Parts, unsigned NumParts,
  179. MVT PartVT, EVT ValueVT, const Value *V,
  180. Optional<CallingConv::ID> CC);
  181. /// getCopyFromParts - Create a value that contains the specified legal parts
  182. /// combined into the value they represent. If the parts combine to a type
  183. /// larger than ValueVT then AssertOp can be used to specify whether the extra
  184. /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
  185. /// (ISD::AssertSext).
  186. static SDValue getCopyFromParts(SelectionDAG &DAG, const SDLoc &DL,
  187. const SDValue *Parts, unsigned NumParts,
  188. MVT PartVT, EVT ValueVT, const Value *V,
  189. Optional<CallingConv::ID> CC = None,
  190. Optional<ISD::NodeType> AssertOp = None) {
  191. if (ValueVT.isVector())
  192. return getCopyFromPartsVector(DAG, DL, Parts, NumParts, PartVT, ValueVT, V,
  193. CC);
  194. assert(NumParts > 0 && "No parts to assemble!");
  195. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  196. SDValue Val = Parts[0];
  197. if (NumParts > 1) {
  198. // Assemble the value from multiple parts.
  199. if (ValueVT.isInteger()) {
  200. unsigned PartBits = PartVT.getSizeInBits();
  201. unsigned ValueBits = ValueVT.getSizeInBits();
  202. // Assemble the power of 2 part.
  203. unsigned RoundParts =
  204. (NumParts & (NumParts - 1)) ? 1 << Log2_32(NumParts) : NumParts;
  205. unsigned RoundBits = PartBits * RoundParts;
  206. EVT RoundVT = RoundBits == ValueBits ?
  207. ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits);
  208. SDValue Lo, Hi;
  209. EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2);
  210. if (RoundParts > 2) {
  211. Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2,
  212. PartVT, HalfVT, V);
  213. Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2,
  214. RoundParts / 2, PartVT, HalfVT, V);
  215. } else {
  216. Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]);
  217. Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]);
  218. }
  219. if (DAG.getDataLayout().isBigEndian())
  220. std::swap(Lo, Hi);
  221. Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi);
  222. if (RoundParts < NumParts) {
  223. // Assemble the trailing non-power-of-2 part.
  224. unsigned OddParts = NumParts - RoundParts;
  225. EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits);
  226. Hi = getCopyFromParts(DAG, DL, Parts + RoundParts, OddParts, PartVT,
  227. OddVT, V, CC);
  228. // Combine the round and odd parts.
  229. Lo = Val;
  230. if (DAG.getDataLayout().isBigEndian())
  231. std::swap(Lo, Hi);
  232. EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
  233. Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi);
  234. Hi =
  235. DAG.getNode(ISD::SHL, DL, TotalVT, Hi,
  236. DAG.getConstant(Lo.getValueSizeInBits(), DL,
  237. TLI.getPointerTy(DAG.getDataLayout())));
  238. Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo);
  239. Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi);
  240. }
  241. } else if (PartVT.isFloatingPoint()) {
  242. // FP split into multiple FP parts (for ppcf128)
  243. assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 &&
  244. "Unexpected split");
  245. SDValue Lo, Hi;
  246. Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]);
  247. Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]);
  248. if (TLI.hasBigEndianPartOrdering(ValueVT, DAG.getDataLayout()))
  249. std::swap(Lo, Hi);
  250. Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi);
  251. } else {
  252. // FP split into integer parts (soft fp)
  253. assert(ValueVT.isFloatingPoint() && PartVT.isInteger() &&
  254. !PartVT.isVector() && "Unexpected split");
  255. EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
  256. Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V, CC);
  257. }
  258. }
  259. // There is now one part, held in Val. Correct it to match ValueVT.
  260. // PartEVT is the type of the register class that holds the value.
  261. // ValueVT is the type of the inline asm operation.
  262. EVT PartEVT = Val.getValueType();
  263. if (PartEVT == ValueVT)
  264. return Val;
  265. if (PartEVT.isInteger() && ValueVT.isFloatingPoint() &&
  266. ValueVT.bitsLT(PartEVT)) {
  267. // For an FP value in an integer part, we need to truncate to the right
  268. // width first.
  269. PartEVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
  270. Val = DAG.getNode(ISD::TRUNCATE, DL, PartEVT, Val);
  271. }
  272. // Handle types that have the same size.
  273. if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits())
  274. return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
  275. // Handle types with different sizes.
  276. if (PartEVT.isInteger() && ValueVT.isInteger()) {
  277. if (ValueVT.bitsLT(PartEVT)) {
  278. // For a truncate, see if we have any information to
  279. // indicate whether the truncated bits will always be
  280. // zero or sign-extension.
  281. if (AssertOp.hasValue())
  282. Val = DAG.getNode(*AssertOp, DL, PartEVT, Val,
  283. DAG.getValueType(ValueVT));
  284. return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
  285. }
  286. return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val);
  287. }
  288. if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
  289. // FP_ROUND's are always exact here.
  290. if (ValueVT.bitsLT(Val.getValueType()))
  291. return DAG.getNode(
  292. ISD::FP_ROUND, DL, ValueVT, Val,
  293. DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout())));
  294. return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val);
  295. }
  296. // Handle MMX to a narrower integer type by bitcasting MMX to integer and
  297. // then truncating.
  298. if (PartEVT == MVT::x86mmx && ValueVT.isInteger() &&
  299. ValueVT.bitsLT(PartEVT)) {
  300. Val = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Val);
  301. return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
  302. }
  303. report_fatal_error("Unknown mismatch in getCopyFromParts!");
  304. }
  305. static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V,
  306. const Twine &ErrMsg) {
  307. const Instruction *I = dyn_cast_or_null<Instruction>(V);
  308. if (!V)
  309. return Ctx.emitError(ErrMsg);
  310. const char *AsmError = ", possible invalid constraint for vector type";
  311. if (const CallInst *CI = dyn_cast<CallInst>(I))
  312. if (isa<InlineAsm>(CI->getCalledValue()))
  313. return Ctx.emitError(I, ErrMsg + AsmError);
  314. return Ctx.emitError(I, ErrMsg);
  315. }
  316. /// getCopyFromPartsVector - Create a value that contains the specified legal
  317. /// parts combined into the value they represent. If the parts combine to a
  318. /// type larger than ValueVT then AssertOp can be used to specify whether the
  319. /// extra bits are known to be zero (ISD::AssertZext) or sign extended from
  320. /// ValueVT (ISD::AssertSext).
  321. static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
  322. const SDValue *Parts, unsigned NumParts,
  323. MVT PartVT, EVT ValueVT, const Value *V,
  324. Optional<CallingConv::ID> CallConv) {
  325. assert(ValueVT.isVector() && "Not a vector value");
  326. assert(NumParts > 0 && "No parts to assemble!");
  327. const bool IsABIRegCopy = CallConv.hasValue();
  328. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  329. SDValue Val = Parts[0];
  330. // Handle a multi-element vector.
  331. if (NumParts > 1) {
  332. EVT IntermediateVT;
  333. MVT RegisterVT;
  334. unsigned NumIntermediates;
  335. unsigned NumRegs;
  336. if (IsABIRegCopy) {
  337. NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
  338. *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT,
  339. NumIntermediates, RegisterVT);
  340. } else {
  341. NumRegs =
  342. TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
  343. NumIntermediates, RegisterVT);
  344. }
  345. assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
  346. NumParts = NumRegs; // Silence a compiler warning.
  347. assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
  348. assert(RegisterVT.getSizeInBits() ==
  349. Parts[0].getSimpleValueType().getSizeInBits() &&
  350. "Part type sizes don't match!");
  351. // Assemble the parts into intermediate operands.
  352. SmallVector<SDValue, 8> Ops(NumIntermediates);
  353. if (NumIntermediates == NumParts) {
  354. // If the register was not expanded, truncate or copy the value,
  355. // as appropriate.
  356. for (unsigned i = 0; i != NumParts; ++i)
  357. Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1,
  358. PartVT, IntermediateVT, V);
  359. } else if (NumParts > 0) {
  360. // If the intermediate type was expanded, build the intermediate
  361. // operands from the parts.
  362. assert(NumParts % NumIntermediates == 0 &&
  363. "Must expand into a divisible number of parts!");
  364. unsigned Factor = NumParts / NumIntermediates;
  365. for (unsigned i = 0; i != NumIntermediates; ++i)
  366. Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor,
  367. PartVT, IntermediateVT, V);
  368. }
  369. // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the
  370. // intermediate operands.
  371. EVT BuiltVectorTy =
  372. EVT::getVectorVT(*DAG.getContext(), IntermediateVT.getScalarType(),
  373. (IntermediateVT.isVector()
  374. ? IntermediateVT.getVectorNumElements() * NumParts
  375. : NumIntermediates));
  376. Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS
  377. : ISD::BUILD_VECTOR,
  378. DL, BuiltVectorTy, Ops);
  379. }
  380. // There is now one part, held in Val. Correct it to match ValueVT.
  381. EVT PartEVT = Val.getValueType();
  382. if (PartEVT == ValueVT)
  383. return Val;
  384. if (PartEVT.isVector()) {
  385. // If the element type of the source/dest vectors are the same, but the
  386. // parts vector has more elements than the value vector, then we have a
  387. // vector widening case (e.g. <2 x float> -> <4 x float>). Extract the
  388. // elements we want.
  389. if (PartEVT.getVectorElementType() == ValueVT.getVectorElementType()) {
  390. assert(PartEVT.getVectorNumElements() > ValueVT.getVectorNumElements() &&
  391. "Cannot narrow, it would be a lossy transformation");
  392. return DAG.getNode(
  393. ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
  394. DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
  395. }
  396. // Vector/Vector bitcast.
  397. if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits())
  398. return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
  399. assert(PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements() &&
  400. "Cannot handle this kind of promotion");
  401. // Promoted vector extract
  402. return DAG.getAnyExtOrTrunc(Val, DL, ValueVT);
  403. }
  404. // Trivial bitcast if the types are the same size and the destination
  405. // vector type is legal.
  406. if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() &&
  407. TLI.isTypeLegal(ValueVT))
  408. return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
  409. if (ValueVT.getVectorNumElements() != 1) {
  410. // Certain ABIs require that vectors are passed as integers. For vectors
  411. // are the same size, this is an obvious bitcast.
  412. if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) {
  413. return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
  414. } else if (ValueVT.getSizeInBits() < PartEVT.getSizeInBits()) {
  415. // Bitcast Val back the original type and extract the corresponding
  416. // vector we want.
  417. unsigned Elts = PartEVT.getSizeInBits() / ValueVT.getScalarSizeInBits();
  418. EVT WiderVecType = EVT::getVectorVT(*DAG.getContext(),
  419. ValueVT.getVectorElementType(), Elts);
  420. Val = DAG.getBitcast(WiderVecType, Val);
  421. return DAG.getNode(
  422. ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
  423. DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
  424. }
  425. diagnosePossiblyInvalidConstraint(
  426. *DAG.getContext(), V, "non-trivial scalar-to-vector conversion");
  427. return DAG.getUNDEF(ValueVT);
  428. }
  429. // Handle cases such as i8 -> <1 x i1>
  430. EVT ValueSVT = ValueVT.getVectorElementType();
  431. if (ValueVT.getVectorNumElements() == 1 && ValueSVT != PartEVT)
  432. Val = ValueVT.isFloatingPoint() ? DAG.getFPExtendOrRound(Val, DL, ValueSVT)
  433. : DAG.getAnyExtOrTrunc(Val, DL, ValueSVT);
  434. return DAG.getBuildVector(ValueVT, DL, Val);
  435. }
  436. static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl,
  437. SDValue Val, SDValue *Parts, unsigned NumParts,
  438. MVT PartVT, const Value *V,
  439. Optional<CallingConv::ID> CallConv);
  440. /// getCopyToParts - Create a series of nodes that contain the specified value
  441. /// split into legal parts. If the parts contain more bits than Val, then, for
  442. /// integers, ExtendKind can be used to specify how to generate the extra bits.
  443. static void getCopyToParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val,
  444. SDValue *Parts, unsigned NumParts, MVT PartVT,
  445. const Value *V,
  446. Optional<CallingConv::ID> CallConv = None,
  447. ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
  448. EVT ValueVT = Val.getValueType();
  449. // Handle the vector case separately.
  450. if (ValueVT.isVector())
  451. return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V,
  452. CallConv);
  453. unsigned PartBits = PartVT.getSizeInBits();
  454. unsigned OrigNumParts = NumParts;
  455. assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) &&
  456. "Copying to an illegal type!");
  457. if (NumParts == 0)
  458. return;
  459. assert(!ValueVT.isVector() && "Vector case handled elsewhere");
  460. EVT PartEVT = PartVT;
  461. if (PartEVT == ValueVT) {
  462. assert(NumParts == 1 && "No-op copy with multiple parts!");
  463. Parts[0] = Val;
  464. return;
  465. }
  466. if (NumParts * PartBits > ValueVT.getSizeInBits()) {
  467. // If the parts cover more bits than the value has, promote the value.
  468. if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
  469. assert(NumParts == 1 && "Do not know what to promote to!");
  470. Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val);
  471. } else {
  472. if (ValueVT.isFloatingPoint()) {
  473. // FP values need to be bitcast, then extended if they are being put
  474. // into a larger container.
  475. ValueVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
  476. Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
  477. }
  478. assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
  479. ValueVT.isInteger() &&
  480. "Unknown mismatch!");
  481. ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
  482. Val = DAG.getNode(ExtendKind, DL, ValueVT, Val);
  483. if (PartVT == MVT::x86mmx)
  484. Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
  485. }
  486. } else if (PartBits == ValueVT.getSizeInBits()) {
  487. // Different types of the same size.
  488. assert(NumParts == 1 && PartEVT != ValueVT);
  489. Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
  490. } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
  491. // If the parts cover less bits than value has, truncate the value.
  492. assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
  493. ValueVT.isInteger() &&
  494. "Unknown mismatch!");
  495. ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
  496. Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
  497. if (PartVT == MVT::x86mmx)
  498. Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
  499. }
  500. // The value may have changed - recompute ValueVT.
  501. ValueVT = Val.getValueType();
  502. assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
  503. "Failed to tile the value with PartVT!");
  504. if (NumParts == 1) {
  505. if (PartEVT != ValueVT) {
  506. diagnosePossiblyInvalidConstraint(*DAG.getContext(), V,
  507. "scalar-to-vector conversion failed");
  508. Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
  509. }
  510. Parts[0] = Val;
  511. return;
  512. }
  513. // Expand the value into multiple parts.
  514. if (NumParts & (NumParts - 1)) {
  515. // The number of parts is not a power of 2. Split off and copy the tail.
  516. assert(PartVT.isInteger() && ValueVT.isInteger() &&
  517. "Do not know what to expand to!");
  518. unsigned RoundParts = 1 << Log2_32(NumParts);
  519. unsigned RoundBits = RoundParts * PartBits;
  520. unsigned OddParts = NumParts - RoundParts;
  521. SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val,
  522. DAG.getShiftAmountConstant(RoundBits, ValueVT, DL, /*LegalTypes*/false));
  523. getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V,
  524. CallConv);
  525. if (DAG.getDataLayout().isBigEndian())
  526. // The odd parts were reversed by getCopyToParts - unreverse them.
  527. std::reverse(Parts + RoundParts, Parts + NumParts);
  528. NumParts = RoundParts;
  529. ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
  530. Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
  531. }
  532. // The number of parts is a power of 2. Repeatedly bisect the value using
  533. // EXTRACT_ELEMENT.
  534. Parts[0] = DAG.getNode(ISD::BITCAST, DL,
  535. EVT::getIntegerVT(*DAG.getContext(),
  536. ValueVT.getSizeInBits()),
  537. Val);
  538. for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
  539. for (unsigned i = 0; i < NumParts; i += StepSize) {
  540. unsigned ThisBits = StepSize * PartBits / 2;
  541. EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits);
  542. SDValue &Part0 = Parts[i];
  543. SDValue &Part1 = Parts[i+StepSize/2];
  544. Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
  545. ThisVT, Part0, DAG.getIntPtrConstant(1, DL));
  546. Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
  547. ThisVT, Part0, DAG.getIntPtrConstant(0, DL));
  548. if (ThisBits == PartBits && ThisVT != PartVT) {
  549. Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0);
  550. Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1);
  551. }
  552. }
  553. }
  554. if (DAG.getDataLayout().isBigEndian())
  555. std::reverse(Parts, Parts + OrigNumParts);
  556. }
  557. static SDValue widenVectorToPartType(SelectionDAG &DAG,
  558. SDValue Val, const SDLoc &DL, EVT PartVT) {
  559. if (!PartVT.isVector())
  560. return SDValue();
  561. EVT ValueVT = Val.getValueType();
  562. unsigned PartNumElts = PartVT.getVectorNumElements();
  563. unsigned ValueNumElts = ValueVT.getVectorNumElements();
  564. if (PartNumElts > ValueNumElts &&
  565. PartVT.getVectorElementType() == ValueVT.getVectorElementType()) {
  566. EVT ElementVT = PartVT.getVectorElementType();
  567. // Vector widening case, e.g. <2 x float> -> <4 x float>. Shuffle in
  568. // undef elements.
  569. SmallVector<SDValue, 16> Ops;
  570. DAG.ExtractVectorElements(Val, Ops);
  571. SDValue EltUndef = DAG.getUNDEF(ElementVT);
  572. for (unsigned i = ValueNumElts, e = PartNumElts; i != e; ++i)
  573. Ops.push_back(EltUndef);
  574. // FIXME: Use CONCAT for 2x -> 4x.
  575. return DAG.getBuildVector(PartVT, DL, Ops);
  576. }
  577. return SDValue();
  578. }
  579. /// getCopyToPartsVector - Create a series of nodes that contain the specified
  580. /// value split into legal parts.
  581. static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL,
  582. SDValue Val, SDValue *Parts, unsigned NumParts,
  583. MVT PartVT, const Value *V,
  584. Optional<CallingConv::ID> CallConv) {
  585. EVT ValueVT = Val.getValueType();
  586. assert(ValueVT.isVector() && "Not a vector");
  587. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  588. const bool IsABIRegCopy = CallConv.hasValue();
  589. if (NumParts == 1) {
  590. EVT PartEVT = PartVT;
  591. if (PartEVT == ValueVT) {
  592. // Nothing to do.
  593. } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) {
  594. // Bitconvert vector->vector case.
  595. Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
  596. } else if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, PartVT)) {
  597. Val = Widened;
  598. } else if (PartVT.isVector() &&
  599. PartEVT.getVectorElementType().bitsGE(
  600. ValueVT.getVectorElementType()) &&
  601. PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements()) {
  602. // Promoted vector extract
  603. Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
  604. } else {
  605. if (ValueVT.getVectorNumElements() == 1) {
  606. Val = DAG.getNode(
  607. ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val,
  608. DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
  609. } else {
  610. assert(PartVT.getSizeInBits() > ValueVT.getSizeInBits() &&
  611. "lossy conversion of vector to scalar type");
  612. EVT IntermediateType =
  613. EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
  614. Val = DAG.getBitcast(IntermediateType, Val);
  615. Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
  616. }
  617. }
  618. assert(Val.getValueType() == PartVT && "Unexpected vector part value type");
  619. Parts[0] = Val;
  620. return;
  621. }
  622. // Handle a multi-element vector.
  623. EVT IntermediateVT;
  624. MVT RegisterVT;
  625. unsigned NumIntermediates;
  626. unsigned NumRegs;
  627. if (IsABIRegCopy) {
  628. NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
  629. *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT,
  630. NumIntermediates, RegisterVT);
  631. } else {
  632. NumRegs =
  633. TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
  634. NumIntermediates, RegisterVT);
  635. }
  636. assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
  637. NumParts = NumRegs; // Silence a compiler warning.
  638. assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
  639. unsigned IntermediateNumElts = IntermediateVT.isVector() ?
  640. IntermediateVT.getVectorNumElements() : 1;
  641. // Convert the vector to the appropiate type if necessary.
  642. unsigned DestVectorNoElts = NumIntermediates * IntermediateNumElts;
  643. EVT BuiltVectorTy = EVT::getVectorVT(
  644. *DAG.getContext(), IntermediateVT.getScalarType(), DestVectorNoElts);
  645. MVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout());
  646. if (ValueVT != BuiltVectorTy) {
  647. if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, BuiltVectorTy))
  648. Val = Widened;
  649. Val = DAG.getNode(ISD::BITCAST, DL, BuiltVectorTy, Val);
  650. }
  651. // Split the vector into intermediate operands.
  652. SmallVector<SDValue, 8> Ops(NumIntermediates);
  653. for (unsigned i = 0; i != NumIntermediates; ++i) {
  654. if (IntermediateVT.isVector()) {
  655. Ops[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val,
  656. DAG.getConstant(i * IntermediateNumElts, DL, IdxVT));
  657. } else {
  658. Ops[i] = DAG.getNode(
  659. ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val,
  660. DAG.getConstant(i, DL, IdxVT));
  661. }
  662. }
  663. // Split the intermediate operands into legal parts.
  664. if (NumParts == NumIntermediates) {
  665. // If the register was not expanded, promote or copy the value,
  666. // as appropriate.
  667. for (unsigned i = 0; i != NumParts; ++i)
  668. getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V, CallConv);
  669. } else if (NumParts > 0) {
  670. // If the intermediate type was expanded, split each the value into
  671. // legal parts.
  672. assert(NumIntermediates != 0 && "division by zero");
  673. assert(NumParts % NumIntermediates == 0 &&
  674. "Must expand into a divisible number of parts!");
  675. unsigned Factor = NumParts / NumIntermediates;
  676. for (unsigned i = 0; i != NumIntermediates; ++i)
  677. getCopyToParts(DAG, DL, Ops[i], &Parts[i * Factor], Factor, PartVT, V,
  678. CallConv);
  679. }
  680. }
  681. RegsForValue::RegsForValue(const SmallVector<unsigned, 4> &regs, MVT regvt,
  682. EVT valuevt, Optional<CallingConv::ID> CC)
  683. : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs),
  684. RegCount(1, regs.size()), CallConv(CC) {}
  685. RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI,
  686. const DataLayout &DL, unsigned Reg, Type *Ty,
  687. Optional<CallingConv::ID> CC) {
  688. ComputeValueVTs(TLI, DL, Ty, ValueVTs);
  689. CallConv = CC;
  690. for (EVT ValueVT : ValueVTs) {
  691. unsigned NumRegs =
  692. isABIMangled()
  693. ? TLI.getNumRegistersForCallingConv(Context, CC.getValue(), ValueVT)
  694. : TLI.getNumRegisters(Context, ValueVT);
  695. MVT RegisterVT =
  696. isABIMangled()
  697. ? TLI.getRegisterTypeForCallingConv(Context, CC.getValue(), ValueVT)
  698. : TLI.getRegisterType(Context, ValueVT);
  699. for (unsigned i = 0; i != NumRegs; ++i)
  700. Regs.push_back(Reg + i);
  701. RegVTs.push_back(RegisterVT);
  702. RegCount.push_back(NumRegs);
  703. Reg += NumRegs;
  704. }
  705. }
  706. SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
  707. FunctionLoweringInfo &FuncInfo,
  708. const SDLoc &dl, SDValue &Chain,
  709. SDValue *Flag, const Value *V) const {
  710. // A Value with type {} or [0 x %t] needs no registers.
  711. if (ValueVTs.empty())
  712. return SDValue();
  713. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  714. // Assemble the legal parts into the final values.
  715. SmallVector<SDValue, 4> Values(ValueVTs.size());
  716. SmallVector<SDValue, 8> Parts;
  717. for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
  718. // Copy the legal parts from the registers.
  719. EVT ValueVT = ValueVTs[Value];
  720. unsigned NumRegs = RegCount[Value];
  721. MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv(
  722. *DAG.getContext(),
  723. CallConv.getValue(), RegVTs[Value])
  724. : RegVTs[Value];
  725. Parts.resize(NumRegs);
  726. for (unsigned i = 0; i != NumRegs; ++i) {
  727. SDValue P;
  728. if (!Flag) {
  729. P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT);
  730. } else {
  731. P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag);
  732. *Flag = P.getValue(2);
  733. }
  734. Chain = P.getValue(1);
  735. Parts[i] = P;
  736. // If the source register was virtual and if we know something about it,
  737. // add an assert node.
  738. if (!TargetRegisterInfo::isVirtualRegister(Regs[Part+i]) ||
  739. !RegisterVT.isInteger())
  740. continue;
  741. const FunctionLoweringInfo::LiveOutInfo *LOI =
  742. FuncInfo.GetLiveOutRegInfo(Regs[Part+i]);
  743. if (!LOI)
  744. continue;
  745. unsigned RegSize = RegisterVT.getScalarSizeInBits();
  746. unsigned NumSignBits = LOI->NumSignBits;
  747. unsigned NumZeroBits = LOI->Known.countMinLeadingZeros();
  748. if (NumZeroBits == RegSize) {
  749. // The current value is a zero.
  750. // Explicitly express that as it would be easier for
  751. // optimizations to kick in.
  752. Parts[i] = DAG.getConstant(0, dl, RegisterVT);
  753. continue;
  754. }
  755. // FIXME: We capture more information than the dag can represent. For
  756. // now, just use the tightest assertzext/assertsext possible.
  757. bool isSExt;
  758. EVT FromVT(MVT::Other);
  759. if (NumZeroBits) {
  760. FromVT = EVT::getIntegerVT(*DAG.getContext(), RegSize - NumZeroBits);
  761. isSExt = false;
  762. } else if (NumSignBits > 1) {
  763. FromVT =
  764. EVT::getIntegerVT(*DAG.getContext(), RegSize - NumSignBits + 1);
  765. isSExt = true;
  766. } else {
  767. continue;
  768. }
  769. // Add an assertion node.
  770. assert(FromVT != MVT::Other);
  771. Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl,
  772. RegisterVT, P, DAG.getValueType(FromVT));
  773. }
  774. Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(), NumRegs,
  775. RegisterVT, ValueVT, V, CallConv);
  776. Part += NumRegs;
  777. Parts.clear();
  778. }
  779. return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values);
  780. }
  781. void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG,
  782. const SDLoc &dl, SDValue &Chain, SDValue *Flag,
  783. const Value *V,
  784. ISD::NodeType PreferredExtendType) const {
  785. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  786. ISD::NodeType ExtendKind = PreferredExtendType;
  787. // Get the list of the values's legal parts.
  788. unsigned NumRegs = Regs.size();
  789. SmallVector<SDValue, 8> Parts(NumRegs);
  790. for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
  791. unsigned NumParts = RegCount[Value];
  792. MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv(
  793. *DAG.getContext(),
  794. CallConv.getValue(), RegVTs[Value])
  795. : RegVTs[Value];
  796. if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT))
  797. ExtendKind = ISD::ZERO_EXTEND;
  798. getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value), &Parts[Part],
  799. NumParts, RegisterVT, V, CallConv, ExtendKind);
  800. Part += NumParts;
  801. }
  802. // Copy the parts into the registers.
  803. SmallVector<SDValue, 8> Chains(NumRegs);
  804. for (unsigned i = 0; i != NumRegs; ++i) {
  805. SDValue Part;
  806. if (!Flag) {
  807. Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]);
  808. } else {
  809. Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag);
  810. *Flag = Part.getValue(1);
  811. }
  812. Chains[i] = Part.getValue(0);
  813. }
  814. if (NumRegs == 1 || Flag)
  815. // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
  816. // flagged to it. That is the CopyToReg nodes and the user are considered
  817. // a single scheduling unit. If we create a TokenFactor and return it as
  818. // chain, then the TokenFactor is both a predecessor (operand) of the
  819. // user as well as a successor (the TF operands are flagged to the user).
  820. // c1, f1 = CopyToReg
  821. // c2, f2 = CopyToReg
  822. // c3 = TokenFactor c1, c2
  823. // ...
  824. // = op c3, ..., f2
  825. Chain = Chains[NumRegs-1];
  826. else
  827. Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
  828. }
  829. void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching,
  830. unsigned MatchingIdx, const SDLoc &dl,
  831. SelectionDAG &DAG,
  832. std::vector<SDValue> &Ops) const {
  833. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  834. unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size());
  835. if (HasMatching)
  836. Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx);
  837. else if (!Regs.empty() &&
  838. TargetRegisterInfo::isVirtualRegister(Regs.front())) {
  839. // Put the register class of the virtual registers in the flag word. That
  840. // way, later passes can recompute register class constraints for inline
  841. // assembly as well as normal instructions.
  842. // Don't do this for tied operands that can use the regclass information
  843. // from the def.
  844. const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
  845. const TargetRegisterClass *RC = MRI.getRegClass(Regs.front());
  846. Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID());
  847. }
  848. SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32);
  849. Ops.push_back(Res);
  850. if (Code == InlineAsm::Kind_Clobber) {
  851. // Clobbers should always have a 1:1 mapping with registers, and may
  852. // reference registers that have illegal (e.g. vector) types. Hence, we
  853. // shouldn't try to apply any sort of splitting logic to them.
  854. assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() &&
  855. "No 1:1 mapping from clobbers to regs?");
  856. unsigned SP = TLI.getStackPointerRegisterToSaveRestore();
  857. (void)SP;
  858. for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) {
  859. Ops.push_back(DAG.getRegister(Regs[I], RegVTs[I]));
  860. assert(
  861. (Regs[I] != SP ||
  862. DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment()) &&
  863. "If we clobbered the stack pointer, MFI should know about it.");
  864. }
  865. return;
  866. }
  867. for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
  868. unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value]);
  869. MVT RegisterVT = RegVTs[Value];
  870. for (unsigned i = 0; i != NumRegs; ++i) {
  871. assert(Reg < Regs.size() && "Mismatch in # registers expected");
  872. unsigned TheReg = Regs[Reg++];
  873. Ops.push_back(DAG.getRegister(TheReg, RegisterVT));
  874. }
  875. }
  876. }
  877. SmallVector<std::pair<unsigned, unsigned>, 4>
  878. RegsForValue::getRegsAndSizes() const {
  879. SmallVector<std::pair<unsigned, unsigned>, 4> OutVec;
  880. unsigned I = 0;
  881. for (auto CountAndVT : zip_first(RegCount, RegVTs)) {
  882. unsigned RegCount = std::get<0>(CountAndVT);
  883. MVT RegisterVT = std::get<1>(CountAndVT);
  884. unsigned RegisterSize = RegisterVT.getSizeInBits();
  885. for (unsigned E = I + RegCount; I != E; ++I)
  886. OutVec.push_back(std::make_pair(Regs[I], RegisterSize));
  887. }
  888. return OutVec;
  889. }
  890. void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis *aa,
  891. const TargetLibraryInfo *li) {
  892. AA = aa;
  893. GFI = gfi;
  894. LibInfo = li;
  895. DL = &DAG.getDataLayout();
  896. Context = DAG.getContext();
  897. LPadToCallSiteMap.clear();
  898. SL->init(DAG.getTargetLoweringInfo(), TM, DAG.getDataLayout());
  899. }
  900. void SelectionDAGBuilder::clear() {
  901. NodeMap.clear();
  902. UnusedArgNodeMap.clear();
  903. PendingLoads.clear();
  904. PendingExports.clear();
  905. CurInst = nullptr;
  906. HasTailCall = false;
  907. SDNodeOrder = LowestSDNodeOrder;
  908. StatepointLowering.clear();
  909. }
  910. void SelectionDAGBuilder::clearDanglingDebugInfo() {
  911. DanglingDebugInfoMap.clear();
  912. }
  913. SDValue SelectionDAGBuilder::getRoot() {
  914. if (PendingLoads.empty())
  915. return DAG.getRoot();
  916. if (PendingLoads.size() == 1) {
  917. SDValue Root = PendingLoads[0];
  918. DAG.setRoot(Root);
  919. PendingLoads.clear();
  920. return Root;
  921. }
  922. // Otherwise, we have to make a token factor node.
  923. SDValue Root = DAG.getTokenFactor(getCurSDLoc(), PendingLoads);
  924. PendingLoads.clear();
  925. DAG.setRoot(Root);
  926. return Root;
  927. }
  928. SDValue SelectionDAGBuilder::getControlRoot() {
  929. SDValue Root = DAG.getRoot();
  930. if (PendingExports.empty())
  931. return Root;
  932. // Turn all of the CopyToReg chains into one factored node.
  933. if (Root.getOpcode() != ISD::EntryToken) {
  934. unsigned i = 0, e = PendingExports.size();
  935. for (; i != e; ++i) {
  936. assert(PendingExports[i].getNode()->getNumOperands() > 1);
  937. if (PendingExports[i].getNode()->getOperand(0) == Root)
  938. break; // Don't add the root if we already indirectly depend on it.
  939. }
  940. if (i == e)
  941. PendingExports.push_back(Root);
  942. }
  943. Root = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other,
  944. PendingExports);
  945. PendingExports.clear();
  946. DAG.setRoot(Root);
  947. return Root;
  948. }
  949. void SelectionDAGBuilder::visit(const Instruction &I) {
  950. // Set up outgoing PHI node register values before emitting the terminator.
  951. if (I.isTerminator()) {
  952. HandlePHINodesInSuccessorBlocks(I.getParent());
  953. }
  954. // Increase the SDNodeOrder if dealing with a non-debug instruction.
  955. if (!isa<DbgInfoIntrinsic>(I))
  956. ++SDNodeOrder;
  957. CurInst = &I;
  958. visit(I.getOpcode(), I);
  959. if (auto *FPMO = dyn_cast<FPMathOperator>(&I)) {
  960. // Propagate the fast-math-flags of this IR instruction to the DAG node that
  961. // maps to this instruction.
  962. // TODO: We could handle all flags (nsw, etc) here.
  963. // TODO: If an IR instruction maps to >1 node, only the final node will have
  964. // flags set.
  965. if (SDNode *Node = getNodeForIRValue(&I)) {
  966. SDNodeFlags IncomingFlags;
  967. IncomingFlags.copyFMF(*FPMO);
  968. if (!Node->getFlags().isDefined())
  969. Node->setFlags(IncomingFlags);
  970. else
  971. Node->intersectFlagsWith(IncomingFlags);
  972. }
  973. }
  974. if (!I.isTerminator() && !HasTailCall &&
  975. !isStatepoint(&I)) // statepoints handle their exports internally
  976. CopyToExportRegsIfNeeded(&I);
  977. CurInst = nullptr;
  978. }
  979. void SelectionDAGBuilder::visitPHI(const PHINode &) {
  980. llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!");
  981. }
  982. void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) {
  983. // Note: this doesn't use InstVisitor, because it has to work with
  984. // ConstantExpr's in addition to instructions.
  985. switch (Opcode) {
  986. default: llvm_unreachable("Unknown instruction type encountered!");
  987. // Build the switch statement using the Instruction.def file.
  988. #define HANDLE_INST(NUM, OPCODE, CLASS) \
  989. case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break;
  990. #include "llvm/IR/Instruction.def"
  991. }
  992. }
  993. void SelectionDAGBuilder::dropDanglingDebugInfo(const DILocalVariable *Variable,
  994. const DIExpression *Expr) {
  995. auto isMatchingDbgValue = [&](DanglingDebugInfo &DDI) {
  996. const DbgValueInst *DI = DDI.getDI();
  997. DIVariable *DanglingVariable = DI->getVariable();
  998. DIExpression *DanglingExpr = DI->getExpression();
  999. if (DanglingVariable == Variable && Expr->fragmentsOverlap(DanglingExpr)) {
  1000. LLVM_DEBUG(dbgs() << "Dropping dangling debug info for " << *DI << "\n");
  1001. return true;
  1002. }
  1003. return false;
  1004. };
  1005. for (auto &DDIMI : DanglingDebugInfoMap) {
  1006. DanglingDebugInfoVector &DDIV = DDIMI.second;
  1007. // If debug info is to be dropped, run it through final checks to see
  1008. // whether it can be salvaged.
  1009. for (auto &DDI : DDIV)
  1010. if (isMatchingDbgValue(DDI))
  1011. salvageUnresolvedDbgValue(DDI);
  1012. DDIV.erase(remove_if(DDIV, isMatchingDbgValue), DDIV.end());
  1013. }
  1014. }
  1015. // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V,
  1016. // generate the debug data structures now that we've seen its definition.
  1017. void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V,
  1018. SDValue Val) {
  1019. auto DanglingDbgInfoIt = DanglingDebugInfoMap.find(V);
  1020. if (DanglingDbgInfoIt == DanglingDebugInfoMap.end())
  1021. return;
  1022. DanglingDebugInfoVector &DDIV = DanglingDbgInfoIt->second;
  1023. for (auto &DDI : DDIV) {
  1024. const DbgValueInst *DI = DDI.getDI();
  1025. assert(DI && "Ill-formed DanglingDebugInfo");
  1026. DebugLoc dl = DDI.getdl();
  1027. unsigned ValSDNodeOrder = Val.getNode()->getIROrder();
  1028. unsigned DbgSDNodeOrder = DDI.getSDNodeOrder();
  1029. DILocalVariable *Variable = DI->getVariable();
  1030. DIExpression *Expr = DI->getExpression();
  1031. assert(Variable->isValidLocationForIntrinsic(dl) &&
  1032. "Expected inlined-at fields to agree");
  1033. SDDbgValue *SDV;
  1034. if (Val.getNode()) {
  1035. // FIXME: I doubt that it is correct to resolve a dangling DbgValue as a
  1036. // FuncArgumentDbgValue (it would be hoisted to the function entry, and if
  1037. // we couldn't resolve it directly when examining the DbgValue intrinsic
  1038. // in the first place we should not be more successful here). Unless we
  1039. // have some test case that prove this to be correct we should avoid
  1040. // calling EmitFuncArgumentDbgValue here.
  1041. if (!EmitFuncArgumentDbgValue(V, Variable, Expr, dl, false, Val)) {
  1042. LLVM_DEBUG(dbgs() << "Resolve dangling debug info [order="
  1043. << DbgSDNodeOrder << "] for:\n " << *DI << "\n");
  1044. LLVM_DEBUG(dbgs() << " By mapping to:\n "; Val.dump());
  1045. // Increase the SDNodeOrder for the DbgValue here to make sure it is
  1046. // inserted after the definition of Val when emitting the instructions
  1047. // after ISel. An alternative could be to teach
  1048. // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly.
  1049. LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs()
  1050. << "changing SDNodeOrder from " << DbgSDNodeOrder << " to "
  1051. << ValSDNodeOrder << "\n");
  1052. SDV = getDbgValue(Val, Variable, Expr, dl,
  1053. std::max(DbgSDNodeOrder, ValSDNodeOrder));
  1054. DAG.AddDbgValue(SDV, Val.getNode(), false);
  1055. } else
  1056. LLVM_DEBUG(dbgs() << "Resolved dangling debug info for " << *DI
  1057. << "in EmitFuncArgumentDbgValue\n");
  1058. } else {
  1059. LLVM_DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
  1060. auto Undef =
  1061. UndefValue::get(DDI.getDI()->getVariableLocation()->getType());
  1062. auto SDV =
  1063. DAG.getConstantDbgValue(Variable, Expr, Undef, dl, DbgSDNodeOrder);
  1064. DAG.AddDbgValue(SDV, nullptr, false);
  1065. }
  1066. }
  1067. DDIV.clear();
  1068. }
  1069. void SelectionDAGBuilder::salvageUnresolvedDbgValue(DanglingDebugInfo &DDI) {
  1070. Value *V = DDI.getDI()->getValue();
  1071. DILocalVariable *Var = DDI.getDI()->getVariable();
  1072. DIExpression *Expr = DDI.getDI()->getExpression();
  1073. DebugLoc DL = DDI.getdl();
  1074. DebugLoc InstDL = DDI.getDI()->getDebugLoc();
  1075. unsigned SDOrder = DDI.getSDNodeOrder();
  1076. // Currently we consider only dbg.value intrinsics -- we tell the salvager
  1077. // that DW_OP_stack_value is desired.
  1078. assert(isa<DbgValueInst>(DDI.getDI()));
  1079. bool StackValue = true;
  1080. // Can this Value can be encoded without any further work?
  1081. if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder))
  1082. return;
  1083. // Attempt to salvage back through as many instructions as possible. Bail if
  1084. // a non-instruction is seen, such as a constant expression or global
  1085. // variable. FIXME: Further work could recover those too.
  1086. while (isa<Instruction>(V)) {
  1087. Instruction &VAsInst = *cast<Instruction>(V);
  1088. DIExpression *NewExpr = salvageDebugInfoImpl(VAsInst, Expr, StackValue);
  1089. // If we cannot salvage any further, and haven't yet found a suitable debug
  1090. // expression, bail out.
  1091. if (!NewExpr)
  1092. break;
  1093. // New value and expr now represent this debuginfo.
  1094. V = VAsInst.getOperand(0);
  1095. Expr = NewExpr;
  1096. // Some kind of simplification occurred: check whether the operand of the
  1097. // salvaged debug expression can be encoded in this DAG.
  1098. if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder)) {
  1099. LLVM_DEBUG(dbgs() << "Salvaged debug location info for:\n "
  1100. << DDI.getDI() << "\nBy stripping back to:\n " << V);
  1101. return;
  1102. }
  1103. }
  1104. // This was the final opportunity to salvage this debug information, and it
  1105. // couldn't be done. Place an undef DBG_VALUE at this location to terminate
  1106. // any earlier variable location.
  1107. auto Undef = UndefValue::get(DDI.getDI()->getVariableLocation()->getType());
  1108. auto SDV = DAG.getConstantDbgValue(Var, Expr, Undef, DL, SDNodeOrder);
  1109. DAG.AddDbgValue(SDV, nullptr, false);
  1110. LLVM_DEBUG(dbgs() << "Dropping debug value info for:\n " << DDI.getDI()
  1111. << "\n");
  1112. LLVM_DEBUG(dbgs() << " Last seen at:\n " << *DDI.getDI()->getOperand(0)
  1113. << "\n");
  1114. }
  1115. bool SelectionDAGBuilder::handleDebugValue(const Value *V, DILocalVariable *Var,
  1116. DIExpression *Expr, DebugLoc dl,
  1117. DebugLoc InstDL, unsigned Order) {
  1118. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  1119. SDDbgValue *SDV;
  1120. if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V) ||
  1121. isa<ConstantPointerNull>(V)) {
  1122. SDV = DAG.getConstantDbgValue(Var, Expr, V, dl, SDNodeOrder);
  1123. DAG.AddDbgValue(SDV, nullptr, false);
  1124. return true;
  1125. }
  1126. // If the Value is a frame index, we can create a FrameIndex debug value
  1127. // without relying on the DAG at all.
  1128. if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
  1129. auto SI = FuncInfo.StaticAllocaMap.find(AI);
  1130. if (SI != FuncInfo.StaticAllocaMap.end()) {
  1131. auto SDV =
  1132. DAG.getFrameIndexDbgValue(Var, Expr, SI->second,
  1133. /*IsIndirect*/ false, dl, SDNodeOrder);
  1134. // Do not attach the SDNodeDbgValue to an SDNode: this variable location
  1135. // is still available even if the SDNode gets optimized out.
  1136. DAG.AddDbgValue(SDV, nullptr, false);
  1137. return true;
  1138. }
  1139. }
  1140. // Do not use getValue() in here; we don't want to generate code at
  1141. // this point if it hasn't been done yet.
  1142. SDValue N = NodeMap[V];
  1143. if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map.
  1144. N = UnusedArgNodeMap[V];
  1145. if (N.getNode()) {
  1146. if (EmitFuncArgumentDbgValue(V, Var, Expr, dl, false, N))
  1147. return true;
  1148. SDV = getDbgValue(N, Var, Expr, dl, SDNodeOrder);
  1149. DAG.AddDbgValue(SDV, N.getNode(), false);
  1150. return true;
  1151. }
  1152. // Special rules apply for the first dbg.values of parameter variables in a
  1153. // function. Identify them by the fact they reference Argument Values, that
  1154. // they're parameters, and they are parameters of the current function. We
  1155. // need to let them dangle until they get an SDNode.
  1156. bool IsParamOfFunc = isa<Argument>(V) && Var->isParameter() &&
  1157. !InstDL.getInlinedAt();
  1158. if (!IsParamOfFunc) {
  1159. // The value is not used in this block yet (or it would have an SDNode).
  1160. // We still want the value to appear for the user if possible -- if it has
  1161. // an associated VReg, we can refer to that instead.
  1162. auto VMI = FuncInfo.ValueMap.find(V);
  1163. if (VMI != FuncInfo.ValueMap.end()) {
  1164. unsigned Reg = VMI->second;
  1165. // If this is a PHI node, it may be split up into several MI PHI nodes
  1166. // (in FunctionLoweringInfo::set).
  1167. RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg,
  1168. V->getType(), None);
  1169. if (RFV.occupiesMultipleRegs()) {
  1170. unsigned Offset = 0;
  1171. unsigned BitsToDescribe = 0;
  1172. if (auto VarSize = Var->getSizeInBits())
  1173. BitsToDescribe = *VarSize;
  1174. if (auto Fragment = Expr->getFragmentInfo())
  1175. BitsToDescribe = Fragment->SizeInBits;
  1176. for (auto RegAndSize : RFV.getRegsAndSizes()) {
  1177. unsigned RegisterSize = RegAndSize.second;
  1178. // Bail out if all bits are described already.
  1179. if (Offset >= BitsToDescribe)
  1180. break;
  1181. unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe)
  1182. ? BitsToDescribe - Offset
  1183. : RegisterSize;
  1184. auto FragmentExpr = DIExpression::createFragmentExpression(
  1185. Expr, Offset, FragmentSize);
  1186. if (!FragmentExpr)
  1187. continue;
  1188. SDV = DAG.getVRegDbgValue(Var, *FragmentExpr, RegAndSize.first,
  1189. false, dl, SDNodeOrder);
  1190. DAG.AddDbgValue(SDV, nullptr, false);
  1191. Offset += RegisterSize;
  1192. }
  1193. } else {
  1194. SDV = DAG.getVRegDbgValue(Var, Expr, Reg, false, dl, SDNodeOrder);
  1195. DAG.AddDbgValue(SDV, nullptr, false);
  1196. }
  1197. return true;
  1198. }
  1199. }
  1200. return false;
  1201. }
  1202. void SelectionDAGBuilder::resolveOrClearDbgInfo() {
  1203. // Try to fixup any remaining dangling debug info -- and drop it if we can't.
  1204. for (auto &Pair : DanglingDebugInfoMap)
  1205. for (auto &DDI : Pair.second)
  1206. salvageUnresolvedDbgValue(DDI);
  1207. clearDanglingDebugInfo();
  1208. }
  1209. /// getCopyFromRegs - If there was virtual register allocated for the value V
  1210. /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise.
  1211. SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) {
  1212. DenseMap<const Value *, unsigned>::iterator It = FuncInfo.ValueMap.find(V);
  1213. SDValue Result;
  1214. if (It != FuncInfo.ValueMap.end()) {
  1215. unsigned InReg = It->second;
  1216. RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(),
  1217. DAG.getDataLayout(), InReg, Ty,
  1218. None); // This is not an ABI copy.
  1219. SDValue Chain = DAG.getEntryNode();
  1220. Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr,
  1221. V);
  1222. resolveDanglingDebugInfo(V, Result);
  1223. }
  1224. return Result;
  1225. }
  1226. /// getValue - Return an SDValue for the given Value.
  1227. SDValue SelectionDAGBuilder::getValue(const Value *V) {
  1228. // If we already have an SDValue for this value, use it. It's important
  1229. // to do this first, so that we don't create a CopyFromReg if we already
  1230. // have a regular SDValue.
  1231. SDValue &N = NodeMap[V];
  1232. if (N.getNode()) return N;
  1233. // If there's a virtual register allocated and initialized for this
  1234. // value, use it.
  1235. if (SDValue copyFromReg = getCopyFromRegs(V, V->getType()))
  1236. return copyFromReg;
  1237. // Otherwise create a new SDValue and remember it.
  1238. SDValue Val = getValueImpl(V);
  1239. NodeMap[V] = Val;
  1240. resolveDanglingDebugInfo(V, Val);
  1241. return Val;
  1242. }
  1243. // Return true if SDValue exists for the given Value
  1244. bool SelectionDAGBuilder::findValue(const Value *V) const {
  1245. return (NodeMap.find(V) != NodeMap.end()) ||
  1246. (FuncInfo.ValueMap.find(V) != FuncInfo.ValueMap.end());
  1247. }
  1248. /// getNonRegisterValue - Return an SDValue for the given Value, but
  1249. /// don't look in FuncInfo.ValueMap for a virtual register.
  1250. SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) {
  1251. // If we already have an SDValue for this value, use it.
  1252. SDValue &N = NodeMap[V];
  1253. if (N.getNode()) {
  1254. if (isa<ConstantSDNode>(N) || isa<ConstantFPSDNode>(N)) {
  1255. // Remove the debug location from the node as the node is about to be used
  1256. // in a location which may differ from the original debug location. This
  1257. // is relevant to Constant and ConstantFP nodes because they can appear
  1258. // as constant expressions inside PHI nodes.
  1259. N->setDebugLoc(DebugLoc());
  1260. }
  1261. return N;
  1262. }
  1263. // Otherwise create a new SDValue and remember it.
  1264. SDValue Val = getValueImpl(V);
  1265. NodeMap[V] = Val;
  1266. resolveDanglingDebugInfo(V, Val);
  1267. return Val;
  1268. }
  1269. /// getValueImpl - Helper function for getValue and getNonRegisterValue.
  1270. /// Create an SDValue for the given value.
  1271. SDValue SelectionDAGBuilder::getValueImpl(const Value *V) {
  1272. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  1273. if (const Constant *C = dyn_cast<Constant>(V)) {
  1274. EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true);
  1275. if (const ConstantInt *CI = dyn_cast<ConstantInt>(C))
  1276. return DAG.getConstant(*CI, getCurSDLoc(), VT);
  1277. if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
  1278. return DAG.getGlobalAddress(GV, getCurSDLoc(), VT);
  1279. if (isa<ConstantPointerNull>(C)) {
  1280. unsigned AS = V->getType()->getPointerAddressSpace();
  1281. return DAG.getConstant(0, getCurSDLoc(),
  1282. TLI.getPointerTy(DAG.getDataLayout(), AS));
  1283. }
  1284. if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
  1285. return DAG.getConstantFP(*CFP, getCurSDLoc(), VT);
  1286. if (isa<UndefValue>(C) && !V->getType()->isAggregateType())
  1287. return DAG.getUNDEF(VT);
  1288. if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
  1289. visit(CE->getOpcode(), *CE);
  1290. SDValue N1 = NodeMap[V];
  1291. assert(N1.getNode() && "visit didn't populate the NodeMap!");
  1292. return N1;
  1293. }
  1294. if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
  1295. SmallVector<SDValue, 4> Constants;
  1296. for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end();
  1297. OI != OE; ++OI) {
  1298. SDNode *Val = getValue(*OI).getNode();
  1299. // If the operand is an empty aggregate, there are no values.
  1300. if (!Val) continue;
  1301. // Add each leaf value from the operand to the Constants list
  1302. // to form a flattened list of all the values.
  1303. for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
  1304. Constants.push_back(SDValue(Val, i));
  1305. }
  1306. return DAG.getMergeValues(Constants, getCurSDLoc());
  1307. }
  1308. if (const ConstantDataSequential *CDS =
  1309. dyn_cast<ConstantDataSequential>(C)) {
  1310. SmallVector<SDValue, 4> Ops;
  1311. for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
  1312. SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode();
  1313. // Add each leaf value from the operand to the Constants list
  1314. // to form a flattened list of all the values.
  1315. for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
  1316. Ops.push_back(SDValue(Val, i));
  1317. }
  1318. if (isa<ArrayType>(CDS->getType()))
  1319. return DAG.getMergeValues(Ops, getCurSDLoc());
  1320. return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
  1321. }
  1322. if (C->getType()->isStructTy() || C->getType()->isArrayTy()) {
  1323. assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
  1324. "Unknown struct or array constant!");
  1325. SmallVector<EVT, 4> ValueVTs;
  1326. ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs);
  1327. unsigned NumElts = ValueVTs.size();
  1328. if (NumElts == 0)
  1329. return SDValue(); // empty struct
  1330. SmallVector<SDValue, 4> Constants(NumElts);
  1331. for (unsigned i = 0; i != NumElts; ++i) {
  1332. EVT EltVT = ValueVTs[i];
  1333. if (isa<UndefValue>(C))
  1334. Constants[i] = DAG.getUNDEF(EltVT);
  1335. else if (EltVT.isFloatingPoint())
  1336. Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
  1337. else
  1338. Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT);
  1339. }
  1340. return DAG.getMergeValues(Constants, getCurSDLoc());
  1341. }
  1342. if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
  1343. return DAG.getBlockAddress(BA, VT);
  1344. VectorType *VecTy = cast<VectorType>(V->getType());
  1345. unsigned NumElements = VecTy->getNumElements();
  1346. // Now that we know the number and type of the elements, get that number of
  1347. // elements into the Ops array based on what kind of constant it is.
  1348. SmallVector<SDValue, 16> Ops;
  1349. if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) {
  1350. for (unsigned i = 0; i != NumElements; ++i)
  1351. Ops.push_back(getValue(CV->getOperand(i)));
  1352. } else {
  1353. assert(isa<ConstantAggregateZero>(C) && "Unknown vector constant!");
  1354. EVT EltVT =
  1355. TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType());
  1356. SDValue Op;
  1357. if (EltVT.isFloatingPoint())
  1358. Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
  1359. else
  1360. Op = DAG.getConstant(0, getCurSDLoc(), EltVT);
  1361. Ops.assign(NumElements, Op);
  1362. }
  1363. // Create a BUILD_VECTOR node.
  1364. return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
  1365. }
  1366. // If this is a static alloca, generate it as the frameindex instead of
  1367. // computation.
  1368. if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
  1369. DenseMap<const AllocaInst*, int>::iterator SI =
  1370. FuncInfo.StaticAllocaMap.find(AI);
  1371. if (SI != FuncInfo.StaticAllocaMap.end())
  1372. return DAG.getFrameIndex(SI->second,
  1373. TLI.getFrameIndexTy(DAG.getDataLayout()));
  1374. }
  1375. // If this is an instruction which fast-isel has deferred, select it now.
  1376. if (const Instruction *Inst = dyn_cast<Instruction>(V)) {
  1377. unsigned InReg = FuncInfo.InitializeRegForValue(Inst);
  1378. RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg,
  1379. Inst->getType(), getABIRegCopyCC(V));
  1380. SDValue Chain = DAG.getEntryNode();
  1381. return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V);
  1382. }
  1383. llvm_unreachable("Can't get register for value!");
  1384. }
  1385. void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) {
  1386. auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
  1387. bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX;
  1388. bool IsCoreCLR = Pers == EHPersonality::CoreCLR;
  1389. bool IsSEH = isAsynchronousEHPersonality(Pers);
  1390. bool IsWasmCXX = Pers == EHPersonality::Wasm_CXX;
  1391. MachineBasicBlock *CatchPadMBB = FuncInfo.MBB;
  1392. if (!IsSEH)
  1393. CatchPadMBB->setIsEHScopeEntry();
  1394. // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues.
  1395. if (IsMSVCCXX || IsCoreCLR)
  1396. CatchPadMBB->setIsEHFuncletEntry();
  1397. // Wasm does not need catchpads anymore
  1398. if (!IsWasmCXX)
  1399. DAG.setRoot(DAG.getNode(ISD::CATCHPAD, getCurSDLoc(), MVT::Other,
  1400. getControlRoot()));
  1401. }
  1402. void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) {
  1403. // Update machine-CFG edge.
  1404. MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()];
  1405. FuncInfo.MBB->addSuccessor(TargetMBB);
  1406. auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
  1407. bool IsSEH = isAsynchronousEHPersonality(Pers);
  1408. if (IsSEH) {
  1409. // If this is not a fall-through branch or optimizations are switched off,
  1410. // emit the branch.
  1411. if (TargetMBB != NextBlock(FuncInfo.MBB) ||
  1412. TM.getOptLevel() == CodeGenOpt::None)
  1413. DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
  1414. getControlRoot(), DAG.getBasicBlock(TargetMBB)));
  1415. return;
  1416. }
  1417. // Figure out the funclet membership for the catchret's successor.
  1418. // This will be used by the FuncletLayout pass to determine how to order the
  1419. // BB's.
  1420. // A 'catchret' returns to the outer scope's color.
  1421. Value *ParentPad = I.getCatchSwitchParentPad();
  1422. const BasicBlock *SuccessorColor;
  1423. if (isa<ConstantTokenNone>(ParentPad))
  1424. SuccessorColor = &FuncInfo.Fn->getEntryBlock();
  1425. else
  1426. SuccessorColor = cast<Instruction>(ParentPad)->getParent();
  1427. assert(SuccessorColor && "No parent funclet for catchret!");
  1428. MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor];
  1429. assert(SuccessorColorMBB && "No MBB for SuccessorColor!");
  1430. // Create the terminator node.
  1431. SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other,
  1432. getControlRoot(), DAG.getBasicBlock(TargetMBB),
  1433. DAG.getBasicBlock(SuccessorColorMBB));
  1434. DAG.setRoot(Ret);
  1435. }
  1436. void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) {
  1437. // Don't emit any special code for the cleanuppad instruction. It just marks
  1438. // the start of an EH scope/funclet.
  1439. FuncInfo.MBB->setIsEHScopeEntry();
  1440. auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
  1441. if (Pers != EHPersonality::Wasm_CXX) {
  1442. FuncInfo.MBB->setIsEHFuncletEntry();
  1443. FuncInfo.MBB->setIsCleanupFuncletEntry();
  1444. }
  1445. }
  1446. // For wasm, there's alwyas a single catch pad attached to a catchswitch, and
  1447. // the control flow always stops at the single catch pad, as it does for a
  1448. // cleanup pad. In case the exception caught is not of the types the catch pad
  1449. // catches, it will be rethrown by a rethrow.
  1450. static void findWasmUnwindDestinations(
  1451. FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
  1452. BranchProbability Prob,
  1453. SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
  1454. &UnwindDests) {
  1455. while (EHPadBB) {
  1456. const Instruction *Pad = EHPadBB->getFirstNonPHI();
  1457. if (isa<CleanupPadInst>(Pad)) {
  1458. // Stop on cleanup pads.
  1459. UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
  1460. UnwindDests.back().first->setIsEHScopeEntry();
  1461. break;
  1462. } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
  1463. // Add the catchpad handlers to the possible destinations. We don't
  1464. // continue to the unwind destination of the catchswitch for wasm.
  1465. for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
  1466. UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
  1467. UnwindDests.back().first->setIsEHScopeEntry();
  1468. }
  1469. break;
  1470. } else {
  1471. continue;
  1472. }
  1473. }
  1474. }
  1475. /// When an invoke or a cleanupret unwinds to the next EH pad, there are
  1476. /// many places it could ultimately go. In the IR, we have a single unwind
  1477. /// destination, but in the machine CFG, we enumerate all the possible blocks.
  1478. /// This function skips over imaginary basic blocks that hold catchswitch
  1479. /// instructions, and finds all the "real" machine
  1480. /// basic block destinations. As those destinations may not be successors of
  1481. /// EHPadBB, here we also calculate the edge probability to those destinations.
  1482. /// The passed-in Prob is the edge probability to EHPadBB.
  1483. static void findUnwindDestinations(
  1484. FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
  1485. BranchProbability Prob,
  1486. SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
  1487. &UnwindDests) {
  1488. EHPersonality Personality =
  1489. classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
  1490. bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX;
  1491. bool IsCoreCLR = Personality == EHPersonality::CoreCLR;
  1492. bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX;
  1493. bool IsSEH = isAsynchronousEHPersonality(Personality);
  1494. if (IsWasmCXX) {
  1495. findWasmUnwindDestinations(FuncInfo, EHPadBB, Prob, UnwindDests);
  1496. assert(UnwindDests.size() <= 1 &&
  1497. "There should be at most one unwind destination for wasm");
  1498. return;
  1499. }
  1500. while (EHPadBB) {
  1501. const Instruction *Pad = EHPadBB->getFirstNonPHI();
  1502. BasicBlock *NewEHPadBB = nullptr;
  1503. if (isa<LandingPadInst>(Pad)) {
  1504. // Stop on landingpads. They are not funclets.
  1505. UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
  1506. break;
  1507. } else if (isa<CleanupPadInst>(Pad)) {
  1508. // Stop on cleanup pads. Cleanups are always funclet entries for all known
  1509. // personalities.
  1510. UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
  1511. UnwindDests.back().first->setIsEHScopeEntry();
  1512. UnwindDests.back().first->setIsEHFuncletEntry();
  1513. break;
  1514. } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
  1515. // Add the catchpad handlers to the possible destinations.
  1516. for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
  1517. UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
  1518. // For MSVC++ and the CLR, catchblocks are funclets and need prologues.
  1519. if (IsMSVCCXX || IsCoreCLR)
  1520. UnwindDests.back().first->setIsEHFuncletEntry();
  1521. if (!IsSEH)
  1522. UnwindDests.back().first->setIsEHScopeEntry();
  1523. }
  1524. NewEHPadBB = CatchSwitch->getUnwindDest();
  1525. } else {
  1526. continue;
  1527. }
  1528. BranchProbabilityInfo *BPI = FuncInfo.BPI;
  1529. if (BPI && NewEHPadBB)
  1530. Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB);
  1531. EHPadBB = NewEHPadBB;
  1532. }
  1533. }
  1534. void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) {
  1535. // Update successor info.
  1536. SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
  1537. auto UnwindDest = I.getUnwindDest();
  1538. BranchProbabilityInfo *BPI = FuncInfo.BPI;
  1539. BranchProbability UnwindDestProb =
  1540. (BPI && UnwindDest)
  1541. ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest)
  1542. : BranchProbability::getZero();
  1543. findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests);
  1544. for (auto &UnwindDest : UnwindDests) {
  1545. UnwindDest.first->setIsEHPad();
  1546. addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second);
  1547. }
  1548. FuncInfo.MBB->normalizeSuccProbs();
  1549. // Create the terminator node.
  1550. SDValue Ret =
  1551. DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot());
  1552. DAG.setRoot(Ret);
  1553. }
  1554. void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) {
  1555. report_fatal_error("visitCatchSwitch not yet implemented!");
  1556. }
  1557. void SelectionDAGBuilder::visitRet(const ReturnInst &I) {
  1558. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  1559. auto &DL = DAG.getDataLayout();
  1560. SDValue Chain = getControlRoot();
  1561. SmallVector<ISD::OutputArg, 8> Outs;
  1562. SmallVector<SDValue, 8> OutVals;
  1563. // Calls to @llvm.experimental.deoptimize don't generate a return value, so
  1564. // lower
  1565. //
  1566. // %val = call <ty> @llvm.experimental.deoptimize()
  1567. // ret <ty> %val
  1568. //
  1569. // differently.
  1570. if (I.getParent()->getTerminatingDeoptimizeCall()) {
  1571. LowerDeoptimizingReturn();
  1572. return;
  1573. }
  1574. if (!FuncInfo.CanLowerReturn) {
  1575. unsigned DemoteReg = FuncInfo.DemoteRegister;
  1576. const Function *F = I.getParent()->getParent();
  1577. // Emit a store of the return value through the virtual register.
  1578. // Leave Outs empty so that LowerReturn won't try to load return
  1579. // registers the usual way.
  1580. SmallVector<EVT, 1> PtrValueVTs;
  1581. ComputeValueVTs(TLI, DL,
  1582. F->getReturnType()->getPointerTo(
  1583. DAG.getDataLayout().getAllocaAddrSpace()),
  1584. PtrValueVTs);
  1585. SDValue RetPtr = DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(),
  1586. DemoteReg, PtrValueVTs[0]);
  1587. SDValue RetOp = getValue(I.getOperand(0));
  1588. SmallVector<EVT, 4> ValueVTs, MemVTs;
  1589. SmallVector<uint64_t, 4> Offsets;
  1590. ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &MemVTs,
  1591. &Offsets);
  1592. unsigned NumValues = ValueVTs.size();
  1593. SmallVector<SDValue, 4> Chains(NumValues);
  1594. for (unsigned i = 0; i != NumValues; ++i) {
  1595. // An aggregate return value cannot wrap around the address space, so
  1596. // offsets to its parts don't wrap either.
  1597. SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr, Offsets[i]);
  1598. SDValue Val = RetOp.getValue(i);
  1599. if (MemVTs[i] != ValueVTs[i])
  1600. Val = DAG.getPtrExtOrTrunc(Val, getCurSDLoc(), MemVTs[i]);
  1601. Chains[i] = DAG.getStore(Chain, getCurSDLoc(), Val,
  1602. // FIXME: better loc info would be nice.
  1603. Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction()));
  1604. }
  1605. Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
  1606. MVT::Other, Chains);
  1607. } else if (I.getNumOperands() != 0) {
  1608. SmallVector<EVT, 4> ValueVTs;
  1609. ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs);
  1610. unsigned NumValues = ValueVTs.size();
  1611. if (NumValues) {
  1612. SDValue RetOp = getValue(I.getOperand(0));
  1613. const Function *F = I.getParent()->getParent();
  1614. bool NeedsRegBlock = TLI.functionArgumentNeedsConsecutiveRegisters(
  1615. I.getOperand(0)->getType(), F->getCallingConv(),
  1616. /*IsVarArg*/ false);
  1617. ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
  1618. if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex,
  1619. Attribute::SExt))
  1620. ExtendKind = ISD::SIGN_EXTEND;
  1621. else if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex,
  1622. Attribute::ZExt))
  1623. ExtendKind = ISD::ZERO_EXTEND;
  1624. LLVMContext &Context = F->getContext();
  1625. bool RetInReg = F->getAttributes().hasAttribute(
  1626. AttributeList::ReturnIndex, Attribute::InReg);
  1627. for (unsigned j = 0; j != NumValues; ++j) {
  1628. EVT VT = ValueVTs[j];
  1629. if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger())
  1630. VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind);
  1631. CallingConv::ID CC = F->getCallingConv();
  1632. unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT);
  1633. MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT);
  1634. SmallVector<SDValue, 4> Parts(NumParts);
  1635. getCopyToParts(DAG, getCurSDLoc(),
  1636. SDValue(RetOp.getNode(), RetOp.getResNo() + j),
  1637. &Parts[0], NumParts, PartVT, &I, CC, ExtendKind);
  1638. // 'inreg' on function refers to return value
  1639. ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
  1640. if (RetInReg)
  1641. Flags.setInReg();
  1642. if (I.getOperand(0)->getType()->isPointerTy()) {
  1643. Flags.setPointer();
  1644. Flags.setPointerAddrSpace(
  1645. cast<PointerType>(I.getOperand(0)->getType())->getAddressSpace());
  1646. }
  1647. if (NeedsRegBlock) {
  1648. Flags.setInConsecutiveRegs();
  1649. if (j == NumValues - 1)
  1650. Flags.setInConsecutiveRegsLast();
  1651. }
  1652. // Propagate extension type if any
  1653. if (ExtendKind == ISD::SIGN_EXTEND)
  1654. Flags.setSExt();
  1655. else if (ExtendKind == ISD::ZERO_EXTEND)
  1656. Flags.setZExt();
  1657. for (unsigned i = 0; i < NumParts; ++i) {
  1658. Outs.push_back(ISD::OutputArg(Flags, Parts[i].getValueType(),
  1659. VT, /*isfixed=*/true, 0, 0));
  1660. OutVals.push_back(Parts[i]);
  1661. }
  1662. }
  1663. }
  1664. }
  1665. // Push in swifterror virtual register as the last element of Outs. This makes
  1666. // sure swifterror virtual register will be returned in the swifterror
  1667. // physical register.
  1668. const Function *F = I.getParent()->getParent();
  1669. if (TLI.supportSwiftError() &&
  1670. F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) {
  1671. assert(SwiftError.getFunctionArg() && "Need a swift error argument");
  1672. ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
  1673. Flags.setSwiftError();
  1674. Outs.push_back(ISD::OutputArg(Flags, EVT(TLI.getPointerTy(DL)) /*vt*/,
  1675. EVT(TLI.getPointerTy(DL)) /*argvt*/,
  1676. true /*isfixed*/, 1 /*origidx*/,
  1677. 0 /*partOffs*/));
  1678. // Create SDNode for the swifterror virtual register.
  1679. OutVals.push_back(
  1680. DAG.getRegister(SwiftError.getOrCreateVRegUseAt(
  1681. &I, FuncInfo.MBB, SwiftError.getFunctionArg()),
  1682. EVT(TLI.getPointerTy(DL))));
  1683. }
  1684. bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg();
  1685. CallingConv::ID CallConv =
  1686. DAG.getMachineFunction().getFunction().getCallingConv();
  1687. Chain = DAG.getTargetLoweringInfo().LowerReturn(
  1688. Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG);
  1689. // Verify that the target's LowerReturn behaved as expected.
  1690. assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
  1691. "LowerReturn didn't return a valid chain!");
  1692. // Update the DAG with the new chain value resulting from return lowering.
  1693. DAG.setRoot(Chain);
  1694. }
  1695. /// CopyToExportRegsIfNeeded - If the given value has virtual registers
  1696. /// created for it, emit nodes to copy the value into the virtual
  1697. /// registers.
  1698. void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) {
  1699. // Skip empty types
  1700. if (V->getType()->isEmptyTy())
  1701. return;
  1702. DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
  1703. if (VMI != FuncInfo.ValueMap.end()) {
  1704. assert(!V->use_empty() && "Unused value assigned virtual registers!");
  1705. CopyValueToVirtualRegister(V, VMI->second);
  1706. }
  1707. }
  1708. /// ExportFromCurrentBlock - If this condition isn't known to be exported from
  1709. /// the current basic block, add it to ValueMap now so that we'll get a
  1710. /// CopyTo/FromReg.
  1711. void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) {
  1712. // No need to export constants.
  1713. if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
  1714. // Already exported?
  1715. if (FuncInfo.isExportedInst(V)) return;
  1716. unsigned Reg = FuncInfo.InitializeRegForValue(V);
  1717. CopyValueToVirtualRegister(V, Reg);
  1718. }
  1719. bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V,
  1720. const BasicBlock *FromBB) {
  1721. // The operands of the setcc have to be in this block. We don't know
  1722. // how to export them from some other block.
  1723. if (const Instruction *VI = dyn_cast<Instruction>(V)) {
  1724. // Can export from current BB.
  1725. if (VI->getParent() == FromBB)
  1726. return true;
  1727. // Is already exported, noop.
  1728. return FuncInfo.isExportedInst(V);
  1729. }
  1730. // If this is an argument, we can export it if the BB is the entry block or
  1731. // if it is already exported.
  1732. if (isa<Argument>(V)) {
  1733. if (FromBB == &FromBB->getParent()->getEntryBlock())
  1734. return true;
  1735. // Otherwise, can only export this if it is already exported.
  1736. return FuncInfo.isExportedInst(V);
  1737. }
  1738. // Otherwise, constants can always be exported.
  1739. return true;
  1740. }
  1741. /// Return branch probability calculated by BranchProbabilityInfo for IR blocks.
  1742. BranchProbability
  1743. SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src,
  1744. const MachineBasicBlock *Dst) const {
  1745. BranchProbabilityInfo *BPI = FuncInfo.BPI;
  1746. const BasicBlock *SrcBB = Src->getBasicBlock();
  1747. const BasicBlock *DstBB = Dst->getBasicBlock();
  1748. if (!BPI) {
  1749. // If BPI is not available, set the default probability as 1 / N, where N is
  1750. // the number of successors.
  1751. auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1);
  1752. return BranchProbability(1, SuccSize);
  1753. }
  1754. return BPI->getEdgeProbability(SrcBB, DstBB);
  1755. }
  1756. void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src,
  1757. MachineBasicBlock *Dst,
  1758. BranchProbability Prob) {
  1759. if (!FuncInfo.BPI)
  1760. Src->addSuccessorWithoutProb(Dst);
  1761. else {
  1762. if (Prob.isUnknown())
  1763. Prob = getEdgeProbability(Src, Dst);
  1764. Src->addSuccessor(Dst, Prob);
  1765. }
  1766. }
  1767. static bool InBlock(const Value *V, const BasicBlock *BB) {
  1768. if (const Instruction *I = dyn_cast<Instruction>(V))
  1769. return I->getParent() == BB;
  1770. return true;
  1771. }
  1772. /// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
  1773. /// This function emits a branch and is used at the leaves of an OR or an
  1774. /// AND operator tree.
  1775. void
  1776. SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond,
  1777. MachineBasicBlock *TBB,
  1778. MachineBasicBlock *FBB,
  1779. MachineBasicBlock *CurBB,
  1780. MachineBasicBlock *SwitchBB,
  1781. BranchProbability TProb,
  1782. BranchProbability FProb,
  1783. bool InvertCond) {
  1784. const BasicBlock *BB = CurBB->getBasicBlock();
  1785. // If the leaf of the tree is a comparison, merge the condition into
  1786. // the caseblock.
  1787. if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
  1788. // The operands of the cmp have to be in this block. We don't know
  1789. // how to export them from some other block. If this is the first block
  1790. // of the sequence, no exporting is needed.
  1791. if (CurBB == SwitchBB ||
  1792. (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
  1793. isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
  1794. ISD::CondCode Condition;
  1795. if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
  1796. ICmpInst::Predicate Pred =
  1797. InvertCond ? IC->getInversePredicate() : IC->getPredicate();
  1798. Condition = getICmpCondCode(Pred);
  1799. } else {
  1800. const FCmpInst *FC = cast<FCmpInst>(Cond);
  1801. FCmpInst::Predicate Pred =
  1802. InvertCond ? FC->getInversePredicate() : FC->getPredicate();
  1803. Condition = getFCmpCondCode(Pred);
  1804. if (TM.Options.NoNaNsFPMath)
  1805. Condition = getFCmpCodeWithoutNaN(Condition);
  1806. }
  1807. CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr,
  1808. TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
  1809. SL->SwitchCases.push_back(CB);
  1810. return;
  1811. }
  1812. }
  1813. // Create a CaseBlock record representing this branch.
  1814. ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ;
  1815. CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()),
  1816. nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
  1817. SL->SwitchCases.push_back(CB);
  1818. }
  1819. void SelectionDAGBuilder::FindMergedConditions(const Value *Cond,
  1820. MachineBasicBlock *TBB,
  1821. MachineBasicBlock *FBB,
  1822. MachineBasicBlock *CurBB,
  1823. MachineBasicBlock *SwitchBB,
  1824. Instruction::BinaryOps Opc,
  1825. BranchProbability TProb,
  1826. BranchProbability FProb,
  1827. bool InvertCond) {
  1828. // Skip over not part of the tree and remember to invert op and operands at
  1829. // next level.
  1830. Value *NotCond;
  1831. if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) &&
  1832. InBlock(NotCond, CurBB->getBasicBlock())) {
  1833. FindMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb,
  1834. !InvertCond);
  1835. return;
  1836. }
  1837. const Instruction *BOp = dyn_cast<Instruction>(Cond);
  1838. // Compute the effective opcode for Cond, taking into account whether it needs
  1839. // to be inverted, e.g.
  1840. // and (not (or A, B)), C
  1841. // gets lowered as
  1842. // and (and (not A, not B), C)
  1843. unsigned BOpc = 0;
  1844. if (BOp) {
  1845. BOpc = BOp->getOpcode();
  1846. if (InvertCond) {
  1847. if (BOpc == Instruction::And)
  1848. BOpc = Instruction::Or;
  1849. else if (BOpc == Instruction::Or)
  1850. BOpc = Instruction::And;
  1851. }
  1852. }
  1853. // If this node is not part of the or/and tree, emit it as a branch.
  1854. if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
  1855. BOpc != unsigned(Opc) || !BOp->hasOneUse() ||
  1856. BOp->getParent() != CurBB->getBasicBlock() ||
  1857. !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
  1858. !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
  1859. EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB,
  1860. TProb, FProb, InvertCond);
  1861. return;
  1862. }
  1863. // Create TmpBB after CurBB.
  1864. MachineFunction::iterator BBI(CurBB);
  1865. MachineFunction &MF = DAG.getMachineFunction();
  1866. MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
  1867. CurBB->getParent()->insert(++BBI, TmpBB);
  1868. if (Opc == Instruction::Or) {
  1869. // Codegen X | Y as:
  1870. // BB1:
  1871. // jmp_if_X TBB
  1872. // jmp TmpBB
  1873. // TmpBB:
  1874. // jmp_if_Y TBB
  1875. // jmp FBB
  1876. //
  1877. // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
  1878. // The requirement is that
  1879. // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
  1880. // = TrueProb for original BB.
  1881. // Assuming the original probabilities are A and B, one choice is to set
  1882. // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to
  1883. // A/(1+B) and 2B/(1+B). This choice assumes that
  1884. // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
  1885. // Another choice is to assume TrueProb for BB1 equals to TrueProb for
  1886. // TmpBB, but the math is more complicated.
  1887. auto NewTrueProb = TProb / 2;
  1888. auto NewFalseProb = TProb / 2 + FProb;
  1889. // Emit the LHS condition.
  1890. FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, SwitchBB, Opc,
  1891. NewTrueProb, NewFalseProb, InvertCond);
  1892. // Normalize A/2 and B to get A/(1+B) and 2B/(1+B).
  1893. SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb};
  1894. BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
  1895. // Emit the RHS condition into TmpBB.
  1896. FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc,
  1897. Probs[0], Probs[1], InvertCond);
  1898. } else {
  1899. assert(Opc == Instruction::And && "Unknown merge op!");
  1900. // Codegen X & Y as:
  1901. // BB1:
  1902. // jmp_if_X TmpBB
  1903. // jmp FBB
  1904. // TmpBB:
  1905. // jmp_if_Y TBB
  1906. // jmp FBB
  1907. //
  1908. // This requires creation of TmpBB after CurBB.
  1909. // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
  1910. // The requirement is that
  1911. // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
  1912. // = FalseProb for original BB.
  1913. // Assuming the original probabilities are A and B, one choice is to set
  1914. // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to
  1915. // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 ==
  1916. // TrueProb for BB1 * FalseProb for TmpBB.
  1917. auto NewTrueProb = TProb + FProb / 2;
  1918. auto NewFalseProb = FProb / 2;
  1919. // Emit the LHS condition.
  1920. FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, SwitchBB, Opc,
  1921. NewTrueProb, NewFalseProb, InvertCond);
  1922. // Normalize A and B/2 to get 2A/(1+A) and B/(1+A).
  1923. SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2};
  1924. BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
  1925. // Emit the RHS condition into TmpBB.
  1926. FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc,
  1927. Probs[0], Probs[1], InvertCond);
  1928. }
  1929. }
  1930. /// If the set of cases should be emitted as a series of branches, return true.
  1931. /// If we should emit this as a bunch of and/or'd together conditions, return
  1932. /// false.
  1933. bool
  1934. SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) {
  1935. if (Cases.size() != 2) return true;
  1936. // If this is two comparisons of the same values or'd or and'd together, they
  1937. // will get folded into a single comparison, so don't emit two blocks.
  1938. if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
  1939. Cases[0].CmpRHS == Cases[1].CmpRHS) ||
  1940. (Cases[0].CmpRHS == Cases[1].CmpLHS &&
  1941. Cases[0].CmpLHS == Cases[1].CmpRHS)) {
  1942. return false;
  1943. }
  1944. // Handle: (X != null) | (Y != null) --> (X|Y) != 0
  1945. // Handle: (X == null) & (Y == null) --> (X|Y) == 0
  1946. if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
  1947. Cases[0].CC == Cases[1].CC &&
  1948. isa<Constant>(Cases[0].CmpRHS) &&
  1949. cast<Constant>(Cases[0].CmpRHS)->isNullValue()) {
  1950. if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB)
  1951. return false;
  1952. if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB)
  1953. return false;
  1954. }
  1955. return true;
  1956. }
  1957. void SelectionDAGBuilder::visitBr(const BranchInst &I) {
  1958. MachineBasicBlock *BrMBB = FuncInfo.MBB;
  1959. // Update machine-CFG edges.
  1960. MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
  1961. if (I.isUnconditional()) {
  1962. // Update machine-CFG edges.
  1963. BrMBB->addSuccessor(Succ0MBB);
  1964. // If this is not a fall-through branch or optimizations are switched off,
  1965. // emit the branch.
  1966. if (Succ0MBB != NextBlock(BrMBB) || TM.getOptLevel() == CodeGenOpt::None)
  1967. DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
  1968. MVT::Other, getControlRoot(),
  1969. DAG.getBasicBlock(Succ0MBB)));
  1970. return;
  1971. }
  1972. // If this condition is one of the special cases we handle, do special stuff
  1973. // now.
  1974. const Value *CondVal = I.getCondition();
  1975. MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
  1976. // If this is a series of conditions that are or'd or and'd together, emit
  1977. // this as a sequence of branches instead of setcc's with and/or operations.
  1978. // As long as jumps are not expensive, this should improve performance.
  1979. // For example, instead of something like:
  1980. // cmp A, B
  1981. // C = seteq
  1982. // cmp D, E
  1983. // F = setle
  1984. // or C, F
  1985. // jnz foo
  1986. // Emit:
  1987. // cmp A, B
  1988. // je foo
  1989. // cmp D, E
  1990. // jle foo
  1991. if (const BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
  1992. Instruction::BinaryOps Opcode = BOp->getOpcode();
  1993. if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp->hasOneUse() &&
  1994. !I.getMetadata(LLVMContext::MD_unpredictable) &&
  1995. (Opcode == Instruction::And || Opcode == Instruction::Or)) {
  1996. FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB,
  1997. Opcode,
  1998. getEdgeProbability(BrMBB, Succ0MBB),
  1999. getEdgeProbability(BrMBB, Succ1MBB),
  2000. /*InvertCond=*/false);
  2001. // If the compares in later blocks need to use values not currently
  2002. // exported from this block, export them now. This block should always
  2003. // be the first entry.
  2004. assert(SL->SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!");
  2005. // Allow some cases to be rejected.
  2006. if (ShouldEmitAsBranches(SL->SwitchCases)) {
  2007. for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) {
  2008. ExportFromCurrentBlock(SL->SwitchCases[i].CmpLHS);
  2009. ExportFromCurrentBlock(SL->SwitchCases[i].CmpRHS);
  2010. }
  2011. // Emit the branch for this block.
  2012. visitSwitchCase(SL->SwitchCases[0], BrMBB);
  2013. SL->SwitchCases.erase(SL->SwitchCases.begin());
  2014. return;
  2015. }
  2016. // Okay, we decided not to do this, remove any inserted MBB's and clear
  2017. // SwitchCases.
  2018. for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i)
  2019. FuncInfo.MF->erase(SL->SwitchCases[i].ThisBB);
  2020. SL->SwitchCases.clear();
  2021. }
  2022. }
  2023. // Create a CaseBlock record representing this branch.
  2024. CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
  2025. nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc());
  2026. // Use visitSwitchCase to actually insert the fast branch sequence for this
  2027. // cond branch.
  2028. visitSwitchCase(CB, BrMBB);
  2029. }
  2030. /// visitSwitchCase - Emits the necessary code to represent a single node in
  2031. /// the binary search tree resulting from lowering a switch instruction.
  2032. void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB,
  2033. MachineBasicBlock *SwitchBB) {
  2034. SDValue Cond;
  2035. SDValue CondLHS = getValue(CB.CmpLHS);
  2036. SDLoc dl = CB.DL;
  2037. if (CB.CC == ISD::SETTRUE) {
  2038. // Branch or fall through to TrueBB.
  2039. addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
  2040. SwitchBB->normalizeSuccProbs();
  2041. if (CB.TrueBB != NextBlock(SwitchBB)) {
  2042. DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, getControlRoot(),
  2043. DAG.getBasicBlock(CB.TrueBB)));
  2044. }
  2045. return;
  2046. }
  2047. auto &TLI = DAG.getTargetLoweringInfo();
  2048. EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), CB.CmpLHS->getType());
  2049. // Build the setcc now.
  2050. if (!CB.CmpMHS) {
  2051. // Fold "(X == true)" to X and "(X == false)" to !X to
  2052. // handle common cases produced by branch lowering.
  2053. if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
  2054. CB.CC == ISD::SETEQ)
  2055. Cond = CondLHS;
  2056. else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
  2057. CB.CC == ISD::SETEQ) {
  2058. SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType());
  2059. Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
  2060. } else {
  2061. SDValue CondRHS = getValue(CB.CmpRHS);
  2062. // If a pointer's DAG type is larger than its memory type then the DAG
  2063. // values are zero-extended. This breaks signed comparisons so truncate
  2064. // back to the underlying type before doing the compare.
  2065. if (CondLHS.getValueType() != MemVT) {
  2066. CondLHS = DAG.getPtrExtOrTrunc(CondLHS, getCurSDLoc(), MemVT);
  2067. CondRHS = DAG.getPtrExtOrTrunc(CondRHS, getCurSDLoc(), MemVT);
  2068. }
  2069. Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, CondRHS, CB.CC);
  2070. }
  2071. } else {
  2072. assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
  2073. const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
  2074. const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
  2075. SDValue CmpOp = getValue(CB.CmpMHS);
  2076. EVT VT = CmpOp.getValueType();
  2077. if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
  2078. Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT),
  2079. ISD::SETLE);
  2080. } else {
  2081. SDValue SUB = DAG.getNode(ISD::SUB, dl,
  2082. VT, CmpOp, DAG.getConstant(Low, dl, VT));
  2083. Cond = DAG.getSetCC(dl, MVT::i1, SUB,
  2084. DAG.getConstant(High-Low, dl, VT), ISD::SETULE);
  2085. }
  2086. }
  2087. // Update successor info
  2088. addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
  2089. // TrueBB and FalseBB are always different unless the incoming IR is
  2090. // degenerate. This only happens when running llc on weird IR.
  2091. if (CB.TrueBB != CB.FalseBB)
  2092. addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb);
  2093. SwitchBB->normalizeSuccProbs();
  2094. // If the lhs block is the next block, invert the condition so that we can
  2095. // fall through to the lhs instead of the rhs block.
  2096. if (CB.TrueBB == NextBlock(SwitchBB)) {
  2097. std::swap(CB.TrueBB, CB.FalseBB);
  2098. SDValue True = DAG.getConstant(1, dl, Cond.getValueType());
  2099. Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
  2100. }
  2101. SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
  2102. MVT::Other, getControlRoot(), Cond,
  2103. DAG.getBasicBlock(CB.TrueBB));
  2104. // Insert the false branch. Do this even if it's a fall through branch,
  2105. // this makes it easier to do DAG optimizations which require inverting
  2106. // the branch condition.
  2107. BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
  2108. DAG.getBasicBlock(CB.FalseBB));
  2109. DAG.setRoot(BrCond);
  2110. }
  2111. /// visitJumpTable - Emit JumpTable node in the current MBB
  2112. void SelectionDAGBuilder::visitJumpTable(SwitchCG::JumpTable &JT) {
  2113. // Emit the code for the jump table
  2114. assert(JT.Reg != -1U && "Should lower JT Header first!");
  2115. EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
  2116. SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(),
  2117. JT.Reg, PTy);
  2118. SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
  2119. SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(),
  2120. MVT::Other, Index.getValue(1),
  2121. Table, Index);
  2122. DAG.setRoot(BrJumpTable);
  2123. }
  2124. /// visitJumpTableHeader - This function emits necessary code to produce index
  2125. /// in the JumpTable from switch case.
  2126. void SelectionDAGBuilder::visitJumpTableHeader(SwitchCG::JumpTable &JT,
  2127. JumpTableHeader &JTH,
  2128. MachineBasicBlock *SwitchBB) {
  2129. SDLoc dl = getCurSDLoc();
  2130. // Subtract the lowest switch case value from the value being switched on.
  2131. SDValue SwitchOp = getValue(JTH.SValue);
  2132. EVT VT = SwitchOp.getValueType();
  2133. SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp,
  2134. DAG.getConstant(JTH.First, dl, VT));
  2135. // The SDNode we just created, which holds the value being switched on minus
  2136. // the smallest case value, needs to be copied to a virtual register so it
  2137. // can be used as an index into the jump table in a subsequent basic block.
  2138. // This value may be smaller or larger than the target's pointer type, and
  2139. // therefore require extension or truncating.
  2140. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2141. SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout()));
  2142. unsigned JumpTableReg =
  2143. FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout()));
  2144. SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl,
  2145. JumpTableReg, SwitchOp);
  2146. JT.Reg = JumpTableReg;
  2147. if (!JTH.OmitRangeCheck) {
  2148. // Emit the range check for the jump table, and branch to the default block
  2149. // for the switch statement if the value being switched on exceeds the
  2150. // largest case in the switch.
  2151. SDValue CMP = DAG.getSetCC(
  2152. dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
  2153. Sub.getValueType()),
  2154. Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT);
  2155. SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
  2156. MVT::Other, CopyTo, CMP,
  2157. DAG.getBasicBlock(JT.Default));
  2158. // Avoid emitting unnecessary branches to the next block.
  2159. if (JT.MBB != NextBlock(SwitchBB))
  2160. BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
  2161. DAG.getBasicBlock(JT.MBB));
  2162. DAG.setRoot(BrCond);
  2163. } else {
  2164. // Avoid emitting unnecessary branches to the next block.
  2165. if (JT.MBB != NextBlock(SwitchBB))
  2166. DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, CopyTo,
  2167. DAG.getBasicBlock(JT.MBB)));
  2168. else
  2169. DAG.setRoot(CopyTo);
  2170. }
  2171. }
  2172. /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global
  2173. /// variable if there exists one.
  2174. static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL,
  2175. SDValue &Chain) {
  2176. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2177. EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
  2178. EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout());
  2179. MachineFunction &MF = DAG.getMachineFunction();
  2180. Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent());
  2181. MachineSDNode *Node =
  2182. DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain);
  2183. if (Global) {
  2184. MachinePointerInfo MPInfo(Global);
  2185. auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant |
  2186. MachineMemOperand::MODereferenceable;
  2187. MachineMemOperand *MemRef = MF.getMachineMemOperand(
  2188. MPInfo, Flags, PtrTy.getSizeInBits() / 8, DAG.getEVTAlignment(PtrTy));
  2189. DAG.setNodeMemRefs(Node, {MemRef});
  2190. }
  2191. if (PtrTy != PtrMemTy)
  2192. return DAG.getPtrExtOrTrunc(SDValue(Node, 0), DL, PtrMemTy);
  2193. return SDValue(Node, 0);
  2194. }
  2195. /// Codegen a new tail for a stack protector check ParentMBB which has had its
  2196. /// tail spliced into a stack protector check success bb.
  2197. ///
  2198. /// For a high level explanation of how this fits into the stack protector
  2199. /// generation see the comment on the declaration of class
  2200. /// StackProtectorDescriptor.
  2201. void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD,
  2202. MachineBasicBlock *ParentBB) {
  2203. // First create the loads to the guard/stack slot for the comparison.
  2204. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2205. EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
  2206. EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout());
  2207. MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo();
  2208. int FI = MFI.getStackProtectorIndex();
  2209. SDValue Guard;
  2210. SDLoc dl = getCurSDLoc();
  2211. SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy);
  2212. const Module &M = *ParentBB->getParent()->getFunction().getParent();
  2213. unsigned Align = DL->getPrefTypeAlignment(Type::getInt8PtrTy(M.getContext()));
  2214. // Generate code to load the content of the guard slot.
  2215. SDValue GuardVal = DAG.getLoad(
  2216. PtrMemTy, dl, DAG.getEntryNode(), StackSlotPtr,
  2217. MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align,
  2218. MachineMemOperand::MOVolatile);
  2219. if (TLI.useStackGuardXorFP())
  2220. GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl);
  2221. // Retrieve guard check function, nullptr if instrumentation is inlined.
  2222. if (const Function *GuardCheckFn = TLI.getSSPStackGuardCheck(M)) {
  2223. // The target provides a guard check function to validate the guard value.
  2224. // Generate a call to that function with the content of the guard slot as
  2225. // argument.
  2226. FunctionType *FnTy = GuardCheckFn->getFunctionType();
  2227. assert(FnTy->getNumParams() == 1 && "Invalid function signature");
  2228. TargetLowering::ArgListTy Args;
  2229. TargetLowering::ArgListEntry Entry;
  2230. Entry.Node = GuardVal;
  2231. Entry.Ty = FnTy->getParamType(0);
  2232. if (GuardCheckFn->hasAttribute(1, Attribute::AttrKind::InReg))
  2233. Entry.IsInReg = true;
  2234. Args.push_back(Entry);
  2235. TargetLowering::CallLoweringInfo CLI(DAG);
  2236. CLI.setDebugLoc(getCurSDLoc())
  2237. .setChain(DAG.getEntryNode())
  2238. .setCallee(GuardCheckFn->getCallingConv(), FnTy->getReturnType(),
  2239. getValue(GuardCheckFn), std::move(Args));
  2240. std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
  2241. DAG.setRoot(Result.second);
  2242. return;
  2243. }
  2244. // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD.
  2245. // Otherwise, emit a volatile load to retrieve the stack guard value.
  2246. SDValue Chain = DAG.getEntryNode();
  2247. if (TLI.useLoadStackGuardNode()) {
  2248. Guard = getLoadStackGuard(DAG, dl, Chain);
  2249. } else {
  2250. const Value *IRGuard = TLI.getSDagStackGuard(M);
  2251. SDValue GuardPtr = getValue(IRGuard);
  2252. Guard = DAG.getLoad(PtrMemTy, dl, Chain, GuardPtr,
  2253. MachinePointerInfo(IRGuard, 0), Align,
  2254. MachineMemOperand::MOVolatile);
  2255. }
  2256. // Perform the comparison via a subtract/getsetcc.
  2257. EVT VT = Guard.getValueType();
  2258. SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, Guard, GuardVal);
  2259. SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(),
  2260. *DAG.getContext(),
  2261. Sub.getValueType()),
  2262. Sub, DAG.getConstant(0, dl, VT), ISD::SETNE);
  2263. // If the sub is not 0, then we know the guard/stackslot do not equal, so
  2264. // branch to failure MBB.
  2265. SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
  2266. MVT::Other, GuardVal.getOperand(0),
  2267. Cmp, DAG.getBasicBlock(SPD.getFailureMBB()));
  2268. // Otherwise branch to success MBB.
  2269. SDValue Br = DAG.getNode(ISD::BR, dl,
  2270. MVT::Other, BrCond,
  2271. DAG.getBasicBlock(SPD.getSuccessMBB()));
  2272. DAG.setRoot(Br);
  2273. }
  2274. /// Codegen the failure basic block for a stack protector check.
  2275. ///
  2276. /// A failure stack protector machine basic block consists simply of a call to
  2277. /// __stack_chk_fail().
  2278. ///
  2279. /// For a high level explanation of how this fits into the stack protector
  2280. /// generation see the comment on the declaration of class
  2281. /// StackProtectorDescriptor.
  2282. void
  2283. SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) {
  2284. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2285. SDValue Chain =
  2286. TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid,
  2287. None, false, getCurSDLoc(), false, false).second;
  2288. // On PS4, the "return address" must still be within the calling function,
  2289. // even if it's at the very end, so emit an explicit TRAP here.
  2290. // Passing 'true' for doesNotReturn above won't generate the trap for us.
  2291. if (TM.getTargetTriple().isPS4CPU())
  2292. Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain);
  2293. DAG.setRoot(Chain);
  2294. }
  2295. /// visitBitTestHeader - This function emits necessary code to produce value
  2296. /// suitable for "bit tests"
  2297. void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B,
  2298. MachineBasicBlock *SwitchBB) {
  2299. SDLoc dl = getCurSDLoc();
  2300. // Subtract the minimum value
  2301. SDValue SwitchOp = getValue(B.SValue);
  2302. EVT VT = SwitchOp.getValueType();
  2303. SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp,
  2304. DAG.getConstant(B.First, dl, VT));
  2305. // Check range
  2306. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2307. SDValue RangeCmp = DAG.getSetCC(
  2308. dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
  2309. Sub.getValueType()),
  2310. Sub, DAG.getConstant(B.Range, dl, VT), ISD::SETUGT);
  2311. // Determine the type of the test operands.
  2312. bool UsePtrType = false;
  2313. if (!TLI.isTypeLegal(VT))
  2314. UsePtrType = true;
  2315. else {
  2316. for (unsigned i = 0, e = B.Cases.size(); i != e; ++i)
  2317. if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) {
  2318. // Switch table case range are encoded into series of masks.
  2319. // Just use pointer type, it's guaranteed to fit.
  2320. UsePtrType = true;
  2321. break;
  2322. }
  2323. }
  2324. if (UsePtrType) {
  2325. VT = TLI.getPointerTy(DAG.getDataLayout());
  2326. Sub = DAG.getZExtOrTrunc(Sub, dl, VT);
  2327. }
  2328. B.RegVT = VT.getSimpleVT();
  2329. B.Reg = FuncInfo.CreateReg(B.RegVT);
  2330. SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub);
  2331. MachineBasicBlock* MBB = B.Cases[0].ThisBB;
  2332. addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb);
  2333. addSuccessorWithProb(SwitchBB, MBB, B.Prob);
  2334. SwitchBB->normalizeSuccProbs();
  2335. SDValue BrRange = DAG.getNode(ISD::BRCOND, dl,
  2336. MVT::Other, CopyTo, RangeCmp,
  2337. DAG.getBasicBlock(B.Default));
  2338. // Avoid emitting unnecessary branches to the next block.
  2339. if (MBB != NextBlock(SwitchBB))
  2340. BrRange = DAG.getNode(ISD::BR, dl, MVT::Other, BrRange,
  2341. DAG.getBasicBlock(MBB));
  2342. DAG.setRoot(BrRange);
  2343. }
  2344. /// visitBitTestCase - this function produces one "bit test"
  2345. void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB,
  2346. MachineBasicBlock* NextMBB,
  2347. BranchProbability BranchProbToNext,
  2348. unsigned Reg,
  2349. BitTestCase &B,
  2350. MachineBasicBlock *SwitchBB) {
  2351. SDLoc dl = getCurSDLoc();
  2352. MVT VT = BB.RegVT;
  2353. SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT);
  2354. SDValue Cmp;
  2355. unsigned PopCount = countPopulation(B.Mask);
  2356. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2357. if (PopCount == 1) {
  2358. // Testing for a single bit; just compare the shift count with what it
  2359. // would need to be to shift a 1 bit in that position.
  2360. Cmp = DAG.getSetCC(
  2361. dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
  2362. ShiftOp, DAG.getConstant(countTrailingZeros(B.Mask), dl, VT),
  2363. ISD::SETEQ);
  2364. } else if (PopCount == BB.Range) {
  2365. // There is only one zero bit in the range, test for it directly.
  2366. Cmp = DAG.getSetCC(
  2367. dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
  2368. ShiftOp, DAG.getConstant(countTrailingOnes(B.Mask), dl, VT),
  2369. ISD::SETNE);
  2370. } else {
  2371. // Make desired shift
  2372. SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT,
  2373. DAG.getConstant(1, dl, VT), ShiftOp);
  2374. // Emit bit tests and jumps
  2375. SDValue AndOp = DAG.getNode(ISD::AND, dl,
  2376. VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT));
  2377. Cmp = DAG.getSetCC(
  2378. dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
  2379. AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE);
  2380. }
  2381. // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb.
  2382. addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb);
  2383. // The branch probability from SwitchBB to NextMBB is BranchProbToNext.
  2384. addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext);
  2385. // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is
  2386. // one as they are relative probabilities (and thus work more like weights),
  2387. // and hence we need to normalize them to let the sum of them become one.
  2388. SwitchBB->normalizeSuccProbs();
  2389. SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl,
  2390. MVT::Other, getControlRoot(),
  2391. Cmp, DAG.getBasicBlock(B.TargetBB));
  2392. // Avoid emitting unnecessary branches to the next block.
  2393. if (NextMBB != NextBlock(SwitchBB))
  2394. BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd,
  2395. DAG.getBasicBlock(NextMBB));
  2396. DAG.setRoot(BrAnd);
  2397. }
  2398. void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) {
  2399. MachineBasicBlock *InvokeMBB = FuncInfo.MBB;
  2400. // Retrieve successors. Look through artificial IR level blocks like
  2401. // catchswitch for successors.
  2402. MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
  2403. const BasicBlock *EHPadBB = I.getSuccessor(1);
  2404. // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
  2405. // have to do anything here to lower funclet bundles.
  2406. assert(!I.hasOperandBundlesOtherThan(
  2407. {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) &&
  2408. "Cannot lower invokes with arbitrary operand bundles yet!");
  2409. const Value *Callee(I.getCalledValue());
  2410. const Function *Fn = dyn_cast<Function>(Callee);
  2411. if (isa<InlineAsm>(Callee))
  2412. visitInlineAsm(&I);
  2413. else if (Fn && Fn->isIntrinsic()) {
  2414. switch (Fn->getIntrinsicID()) {
  2415. default:
  2416. llvm_unreachable("Cannot invoke this intrinsic");
  2417. case Intrinsic::donothing:
  2418. // Ignore invokes to @llvm.donothing: jump directly to the next BB.
  2419. break;
  2420. case Intrinsic::experimental_patchpoint_void:
  2421. case Intrinsic::experimental_patchpoint_i64:
  2422. visitPatchpoint(&I, EHPadBB);
  2423. break;
  2424. case Intrinsic::experimental_gc_statepoint:
  2425. LowerStatepoint(ImmutableStatepoint(&I), EHPadBB);
  2426. break;
  2427. case Intrinsic::wasm_rethrow_in_catch: {
  2428. // This is usually done in visitTargetIntrinsic, but this intrinsic is
  2429. // special because it can be invoked, so we manually lower it to a DAG
  2430. // node here.
  2431. SmallVector<SDValue, 8> Ops;
  2432. Ops.push_back(getRoot()); // inchain
  2433. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2434. Ops.push_back(
  2435. DAG.getTargetConstant(Intrinsic::wasm_rethrow_in_catch, getCurSDLoc(),
  2436. TLI.getPointerTy(DAG.getDataLayout())));
  2437. SDVTList VTs = DAG.getVTList(ArrayRef<EVT>({MVT::Other})); // outchain
  2438. DAG.setRoot(DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops));
  2439. break;
  2440. }
  2441. }
  2442. } else if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) {
  2443. // Currently we do not lower any intrinsic calls with deopt operand bundles.
  2444. // Eventually we will support lowering the @llvm.experimental.deoptimize
  2445. // intrinsic, and right now there are no plans to support other intrinsics
  2446. // with deopt state.
  2447. LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB);
  2448. } else {
  2449. LowerCallTo(&I, getValue(Callee), false, EHPadBB);
  2450. }
  2451. // If the value of the invoke is used outside of its defining block, make it
  2452. // available as a virtual register.
  2453. // We already took care of the exported value for the statepoint instruction
  2454. // during call to the LowerStatepoint.
  2455. if (!isStatepoint(I)) {
  2456. CopyToExportRegsIfNeeded(&I);
  2457. }
  2458. SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
  2459. BranchProbabilityInfo *BPI = FuncInfo.BPI;
  2460. BranchProbability EHPadBBProb =
  2461. BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB)
  2462. : BranchProbability::getZero();
  2463. findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests);
  2464. // Update successor info.
  2465. addSuccessorWithProb(InvokeMBB, Return);
  2466. for (auto &UnwindDest : UnwindDests) {
  2467. UnwindDest.first->setIsEHPad();
  2468. addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second);
  2469. }
  2470. InvokeMBB->normalizeSuccProbs();
  2471. // Drop into normal successor.
  2472. DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, getControlRoot(),
  2473. DAG.getBasicBlock(Return)));
  2474. }
  2475. void SelectionDAGBuilder::visitCallBr(const CallBrInst &I) {
  2476. MachineBasicBlock *CallBrMBB = FuncInfo.MBB;
  2477. // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
  2478. // have to do anything here to lower funclet bundles.
  2479. assert(!I.hasOperandBundlesOtherThan(
  2480. {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) &&
  2481. "Cannot lower callbrs with arbitrary operand bundles yet!");
  2482. assert(isa<InlineAsm>(I.getCalledValue()) &&
  2483. "Only know how to handle inlineasm callbr");
  2484. visitInlineAsm(&I);
  2485. // Retrieve successors.
  2486. MachineBasicBlock *Return = FuncInfo.MBBMap[I.getDefaultDest()];
  2487. // Update successor info.
  2488. addSuccessorWithProb(CallBrMBB, Return);
  2489. for (unsigned i = 0, e = I.getNumIndirectDests(); i < e; ++i) {
  2490. MachineBasicBlock *Target = FuncInfo.MBBMap[I.getIndirectDest(i)];
  2491. addSuccessorWithProb(CallBrMBB, Target);
  2492. }
  2493. CallBrMBB->normalizeSuccProbs();
  2494. // Drop into default successor.
  2495. DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
  2496. MVT::Other, getControlRoot(),
  2497. DAG.getBasicBlock(Return)));
  2498. }
  2499. void SelectionDAGBuilder::visitResume(const ResumeInst &RI) {
  2500. llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!");
  2501. }
  2502. void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) {
  2503. assert(FuncInfo.MBB->isEHPad() &&
  2504. "Call to landingpad not in landing pad!");
  2505. // If there aren't registers to copy the values into (e.g., during SjLj
  2506. // exceptions), then don't bother to create these DAG nodes.
  2507. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2508. const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn();
  2509. if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 &&
  2510. TLI.getExceptionSelectorRegister(PersonalityFn) == 0)
  2511. return;
  2512. // If landingpad's return type is token type, we don't create DAG nodes
  2513. // for its exception pointer and selector value. The extraction of exception
  2514. // pointer or selector value from token type landingpads is not currently
  2515. // supported.
  2516. if (LP.getType()->isTokenTy())
  2517. return;
  2518. SmallVector<EVT, 2> ValueVTs;
  2519. SDLoc dl = getCurSDLoc();
  2520. ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs);
  2521. assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported");
  2522. // Get the two live-in registers as SDValues. The physregs have already been
  2523. // copied into virtual registers.
  2524. SDValue Ops[2];
  2525. if (FuncInfo.ExceptionPointerVirtReg) {
  2526. Ops[0] = DAG.getZExtOrTrunc(
  2527. DAG.getCopyFromReg(DAG.getEntryNode(), dl,
  2528. FuncInfo.ExceptionPointerVirtReg,
  2529. TLI.getPointerTy(DAG.getDataLayout())),
  2530. dl, ValueVTs[0]);
  2531. } else {
  2532. Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout()));
  2533. }
  2534. Ops[1] = DAG.getZExtOrTrunc(
  2535. DAG.getCopyFromReg(DAG.getEntryNode(), dl,
  2536. FuncInfo.ExceptionSelectorVirtReg,
  2537. TLI.getPointerTy(DAG.getDataLayout())),
  2538. dl, ValueVTs[1]);
  2539. // Merge into one.
  2540. SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl,
  2541. DAG.getVTList(ValueVTs), Ops);
  2542. setValue(&LP, Res);
  2543. }
  2544. void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First,
  2545. MachineBasicBlock *Last) {
  2546. // Update JTCases.
  2547. for (unsigned i = 0, e = SL->JTCases.size(); i != e; ++i)
  2548. if (SL->JTCases[i].first.HeaderBB == First)
  2549. SL->JTCases[i].first.HeaderBB = Last;
  2550. // Update BitTestCases.
  2551. for (unsigned i = 0, e = SL->BitTestCases.size(); i != e; ++i)
  2552. if (SL->BitTestCases[i].Parent == First)
  2553. SL->BitTestCases[i].Parent = Last;
  2554. }
  2555. void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) {
  2556. MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB;
  2557. // Update machine-CFG edges with unique successors.
  2558. SmallSet<BasicBlock*, 32> Done;
  2559. for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) {
  2560. BasicBlock *BB = I.getSuccessor(i);
  2561. bool Inserted = Done.insert(BB).second;
  2562. if (!Inserted)
  2563. continue;
  2564. MachineBasicBlock *Succ = FuncInfo.MBBMap[BB];
  2565. addSuccessorWithProb(IndirectBrMBB, Succ);
  2566. }
  2567. IndirectBrMBB->normalizeSuccProbs();
  2568. DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(),
  2569. MVT::Other, getControlRoot(),
  2570. getValue(I.getAddress())));
  2571. }
  2572. void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) {
  2573. if (!DAG.getTarget().Options.TrapUnreachable)
  2574. return;
  2575. // We may be able to ignore unreachable behind a noreturn call.
  2576. if (DAG.getTarget().Options.NoTrapAfterNoreturn) {
  2577. const BasicBlock &BB = *I.getParent();
  2578. if (&I != &BB.front()) {
  2579. BasicBlock::const_iterator PredI =
  2580. std::prev(BasicBlock::const_iterator(&I));
  2581. if (const CallInst *Call = dyn_cast<CallInst>(&*PredI)) {
  2582. if (Call->doesNotReturn())
  2583. return;
  2584. }
  2585. }
  2586. }
  2587. DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot()));
  2588. }
  2589. void SelectionDAGBuilder::visitFSub(const User &I) {
  2590. // -0.0 - X --> fneg
  2591. Type *Ty = I.getType();
  2592. if (isa<Constant>(I.getOperand(0)) &&
  2593. I.getOperand(0) == ConstantFP::getZeroValueForNegation(Ty)) {
  2594. SDValue Op2 = getValue(I.getOperand(1));
  2595. setValue(&I, DAG.getNode(ISD::FNEG, getCurSDLoc(),
  2596. Op2.getValueType(), Op2));
  2597. return;
  2598. }
  2599. visitBinary(I, ISD::FSUB);
  2600. }
  2601. /// Checks if the given instruction performs a vector reduction, in which case
  2602. /// we have the freedom to alter the elements in the result as long as the
  2603. /// reduction of them stays unchanged.
  2604. static bool isVectorReductionOp(const User *I) {
  2605. const Instruction *Inst = dyn_cast<Instruction>(I);
  2606. if (!Inst || !Inst->getType()->isVectorTy())
  2607. return false;
  2608. auto OpCode = Inst->getOpcode();
  2609. switch (OpCode) {
  2610. case Instruction::Add:
  2611. case Instruction::Mul:
  2612. case Instruction::And:
  2613. case Instruction::Or:
  2614. case Instruction::Xor:
  2615. break;
  2616. case Instruction::FAdd:
  2617. case Instruction::FMul:
  2618. if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(Inst))
  2619. if (FPOp->getFastMathFlags().isFast())
  2620. break;
  2621. LLVM_FALLTHROUGH;
  2622. default:
  2623. return false;
  2624. }
  2625. unsigned ElemNum = Inst->getType()->getVectorNumElements();
  2626. // Ensure the reduction size is a power of 2.
  2627. if (!isPowerOf2_32(ElemNum))
  2628. return false;
  2629. unsigned ElemNumToReduce = ElemNum;
  2630. // Do DFS search on the def-use chain from the given instruction. We only
  2631. // allow four kinds of operations during the search until we reach the
  2632. // instruction that extracts the first element from the vector:
  2633. //
  2634. // 1. The reduction operation of the same opcode as the given instruction.
  2635. //
  2636. // 2. PHI node.
  2637. //
  2638. // 3. ShuffleVector instruction together with a reduction operation that
  2639. // does a partial reduction.
  2640. //
  2641. // 4. ExtractElement that extracts the first element from the vector, and we
  2642. // stop searching the def-use chain here.
  2643. //
  2644. // 3 & 4 above perform a reduction on all elements of the vector. We push defs
  2645. // from 1-3 to the stack to continue the DFS. The given instruction is not
  2646. // a reduction operation if we meet any other instructions other than those
  2647. // listed above.
  2648. SmallVector<const User *, 16> UsersToVisit{Inst};
  2649. SmallPtrSet<const User *, 16> Visited;
  2650. bool ReduxExtracted = false;
  2651. while (!UsersToVisit.empty()) {
  2652. auto User = UsersToVisit.back();
  2653. UsersToVisit.pop_back();
  2654. if (!Visited.insert(User).second)
  2655. continue;
  2656. for (const auto &U : User->users()) {
  2657. auto Inst = dyn_cast<Instruction>(U);
  2658. if (!Inst)
  2659. return false;
  2660. if (Inst->getOpcode() == OpCode || isa<PHINode>(U)) {
  2661. if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(Inst))
  2662. if (!isa<PHINode>(FPOp) && !FPOp->getFastMathFlags().isFast())
  2663. return false;
  2664. UsersToVisit.push_back(U);
  2665. } else if (const ShuffleVectorInst *ShufInst =
  2666. dyn_cast<ShuffleVectorInst>(U)) {
  2667. // Detect the following pattern: A ShuffleVector instruction together
  2668. // with a reduction that do partial reduction on the first and second
  2669. // ElemNumToReduce / 2 elements, and store the result in
  2670. // ElemNumToReduce / 2 elements in another vector.
  2671. unsigned ResultElements = ShufInst->getType()->getVectorNumElements();
  2672. if (ResultElements < ElemNum)
  2673. return false;
  2674. if (ElemNumToReduce == 1)
  2675. return false;
  2676. if (!isa<UndefValue>(U->getOperand(1)))
  2677. return false;
  2678. for (unsigned i = 0; i < ElemNumToReduce / 2; ++i)
  2679. if (ShufInst->getMaskValue(i) != int(i + ElemNumToReduce / 2))
  2680. return false;
  2681. for (unsigned i = ElemNumToReduce / 2; i < ElemNum; ++i)
  2682. if (ShufInst->getMaskValue(i) != -1)
  2683. return false;
  2684. // There is only one user of this ShuffleVector instruction, which
  2685. // must be a reduction operation.
  2686. if (!U->hasOneUse())
  2687. return false;
  2688. auto U2 = dyn_cast<Instruction>(*U->user_begin());
  2689. if (!U2 || U2->getOpcode() != OpCode)
  2690. return false;
  2691. // Check operands of the reduction operation.
  2692. if ((U2->getOperand(0) == U->getOperand(0) && U2->getOperand(1) == U) ||
  2693. (U2->getOperand(1) == U->getOperand(0) && U2->getOperand(0) == U)) {
  2694. UsersToVisit.push_back(U2);
  2695. ElemNumToReduce /= 2;
  2696. } else
  2697. return false;
  2698. } else if (isa<ExtractElementInst>(U)) {
  2699. // At this moment we should have reduced all elements in the vector.
  2700. if (ElemNumToReduce != 1)
  2701. return false;
  2702. const ConstantInt *Val = dyn_cast<ConstantInt>(U->getOperand(1));
  2703. if (!Val || !Val->isZero())
  2704. return false;
  2705. ReduxExtracted = true;
  2706. } else
  2707. return false;
  2708. }
  2709. }
  2710. return ReduxExtracted;
  2711. }
  2712. void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) {
  2713. SDNodeFlags Flags;
  2714. SDValue Op = getValue(I.getOperand(0));
  2715. SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(),
  2716. Op, Flags);
  2717. setValue(&I, UnNodeValue);
  2718. }
  2719. void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) {
  2720. SDNodeFlags Flags;
  2721. if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) {
  2722. Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap());
  2723. Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap());
  2724. }
  2725. if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I)) {
  2726. Flags.setExact(ExactOp->isExact());
  2727. }
  2728. if (isVectorReductionOp(&I)) {
  2729. Flags.setVectorReduction(true);
  2730. LLVM_DEBUG(dbgs() << "Detected a reduction operation:" << I << "\n");
  2731. }
  2732. SDValue Op1 = getValue(I.getOperand(0));
  2733. SDValue Op2 = getValue(I.getOperand(1));
  2734. SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(),
  2735. Op1, Op2, Flags);
  2736. setValue(&I, BinNodeValue);
  2737. }
  2738. void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) {
  2739. SDValue Op1 = getValue(I.getOperand(0));
  2740. SDValue Op2 = getValue(I.getOperand(1));
  2741. EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy(
  2742. Op1.getValueType(), DAG.getDataLayout());
  2743. // Coerce the shift amount to the right type if we can.
  2744. if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) {
  2745. unsigned ShiftSize = ShiftTy.getSizeInBits();
  2746. unsigned Op2Size = Op2.getValueSizeInBits();
  2747. SDLoc DL = getCurSDLoc();
  2748. // If the operand is smaller than the shift count type, promote it.
  2749. if (ShiftSize > Op2Size)
  2750. Op2 = DAG.getNode(ISD::ZERO_EXTEND, DL, ShiftTy, Op2);
  2751. // If the operand is larger than the shift count type but the shift
  2752. // count type has enough bits to represent any shift value, truncate
  2753. // it now. This is a common case and it exposes the truncate to
  2754. // optimization early.
  2755. else if (ShiftSize >= Log2_32_Ceil(Op2.getValueSizeInBits()))
  2756. Op2 = DAG.getNode(ISD::TRUNCATE, DL, ShiftTy, Op2);
  2757. // Otherwise we'll need to temporarily settle for some other convenient
  2758. // type. Type legalization will make adjustments once the shiftee is split.
  2759. else
  2760. Op2 = DAG.getZExtOrTrunc(Op2, DL, MVT::i32);
  2761. }
  2762. bool nuw = false;
  2763. bool nsw = false;
  2764. bool exact = false;
  2765. if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) {
  2766. if (const OverflowingBinaryOperator *OFBinOp =
  2767. dyn_cast<const OverflowingBinaryOperator>(&I)) {
  2768. nuw = OFBinOp->hasNoUnsignedWrap();
  2769. nsw = OFBinOp->hasNoSignedWrap();
  2770. }
  2771. if (const PossiblyExactOperator *ExactOp =
  2772. dyn_cast<const PossiblyExactOperator>(&I))
  2773. exact = ExactOp->isExact();
  2774. }
  2775. SDNodeFlags Flags;
  2776. Flags.setExact(exact);
  2777. Flags.setNoSignedWrap(nsw);
  2778. Flags.setNoUnsignedWrap(nuw);
  2779. SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2,
  2780. Flags);
  2781. setValue(&I, Res);
  2782. }
  2783. void SelectionDAGBuilder::visitSDiv(const User &I) {
  2784. SDValue Op1 = getValue(I.getOperand(0));
  2785. SDValue Op2 = getValue(I.getOperand(1));
  2786. SDNodeFlags Flags;
  2787. Flags.setExact(isa<PossiblyExactOperator>(&I) &&
  2788. cast<PossiblyExactOperator>(&I)->isExact());
  2789. setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1,
  2790. Op2, Flags));
  2791. }
  2792. void SelectionDAGBuilder::visitICmp(const User &I) {
  2793. ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
  2794. if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I))
  2795. predicate = IC->getPredicate();
  2796. else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
  2797. predicate = ICmpInst::Predicate(IC->getPredicate());
  2798. SDValue Op1 = getValue(I.getOperand(0));
  2799. SDValue Op2 = getValue(I.getOperand(1));
  2800. ISD::CondCode Opcode = getICmpCondCode(predicate);
  2801. auto &TLI = DAG.getTargetLoweringInfo();
  2802. EVT MemVT =
  2803. TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
  2804. // If a pointer's DAG type is larger than its memory type then the DAG values
  2805. // are zero-extended. This breaks signed comparisons so truncate back to the
  2806. // underlying type before doing the compare.
  2807. if (Op1.getValueType() != MemVT) {
  2808. Op1 = DAG.getPtrExtOrTrunc(Op1, getCurSDLoc(), MemVT);
  2809. Op2 = DAG.getPtrExtOrTrunc(Op2, getCurSDLoc(), MemVT);
  2810. }
  2811. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  2812. I.getType());
  2813. setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode));
  2814. }
  2815. void SelectionDAGBuilder::visitFCmp(const User &I) {
  2816. FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
  2817. if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I))
  2818. predicate = FC->getPredicate();
  2819. else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
  2820. predicate = FCmpInst::Predicate(FC->getPredicate());
  2821. SDValue Op1 = getValue(I.getOperand(0));
  2822. SDValue Op2 = getValue(I.getOperand(1));
  2823. ISD::CondCode Condition = getFCmpCondCode(predicate);
  2824. auto *FPMO = dyn_cast<FPMathOperator>(&I);
  2825. if ((FPMO && FPMO->hasNoNaNs()) || TM.Options.NoNaNsFPMath)
  2826. Condition = getFCmpCodeWithoutNaN(Condition);
  2827. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  2828. I.getType());
  2829. setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition));
  2830. }
  2831. // Check if the condition of the select has one use or two users that are both
  2832. // selects with the same condition.
  2833. static bool hasOnlySelectUsers(const Value *Cond) {
  2834. return llvm::all_of(Cond->users(), [](const Value *V) {
  2835. return isa<SelectInst>(V);
  2836. });
  2837. }
  2838. void SelectionDAGBuilder::visitSelect(const User &I) {
  2839. SmallVector<EVT, 4> ValueVTs;
  2840. ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
  2841. ValueVTs);
  2842. unsigned NumValues = ValueVTs.size();
  2843. if (NumValues == 0) return;
  2844. SmallVector<SDValue, 4> Values(NumValues);
  2845. SDValue Cond = getValue(I.getOperand(0));
  2846. SDValue LHSVal = getValue(I.getOperand(1));
  2847. SDValue RHSVal = getValue(I.getOperand(2));
  2848. auto BaseOps = {Cond};
  2849. ISD::NodeType OpCode = Cond.getValueType().isVector() ?
  2850. ISD::VSELECT : ISD::SELECT;
  2851. bool IsUnaryAbs = false;
  2852. // Min/max matching is only viable if all output VTs are the same.
  2853. if (is_splat(ValueVTs)) {
  2854. EVT VT = ValueVTs[0];
  2855. LLVMContext &Ctx = *DAG.getContext();
  2856. auto &TLI = DAG.getTargetLoweringInfo();
  2857. // We care about the legality of the operation after it has been type
  2858. // legalized.
  2859. while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal &&
  2860. VT != TLI.getTypeToTransformTo(Ctx, VT))
  2861. VT = TLI.getTypeToTransformTo(Ctx, VT);
  2862. // If the vselect is legal, assume we want to leave this as a vector setcc +
  2863. // vselect. Otherwise, if this is going to be scalarized, we want to see if
  2864. // min/max is legal on the scalar type.
  2865. bool UseScalarMinMax = VT.isVector() &&
  2866. !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT);
  2867. Value *LHS, *RHS;
  2868. auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS);
  2869. ISD::NodeType Opc = ISD::DELETED_NODE;
  2870. switch (SPR.Flavor) {
  2871. case SPF_UMAX: Opc = ISD::UMAX; break;
  2872. case SPF_UMIN: Opc = ISD::UMIN; break;
  2873. case SPF_SMAX: Opc = ISD::SMAX; break;
  2874. case SPF_SMIN: Opc = ISD::SMIN; break;
  2875. case SPF_FMINNUM:
  2876. switch (SPR.NaNBehavior) {
  2877. case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
  2878. case SPNB_RETURNS_NAN: Opc = ISD::FMINIMUM; break;
  2879. case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break;
  2880. case SPNB_RETURNS_ANY: {
  2881. if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT))
  2882. Opc = ISD::FMINNUM;
  2883. else if (TLI.isOperationLegalOrCustom(ISD::FMINIMUM, VT))
  2884. Opc = ISD::FMINIMUM;
  2885. else if (UseScalarMinMax)
  2886. Opc = TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType()) ?
  2887. ISD::FMINNUM : ISD::FMINIMUM;
  2888. break;
  2889. }
  2890. }
  2891. break;
  2892. case SPF_FMAXNUM:
  2893. switch (SPR.NaNBehavior) {
  2894. case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
  2895. case SPNB_RETURNS_NAN: Opc = ISD::FMAXIMUM; break;
  2896. case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break;
  2897. case SPNB_RETURNS_ANY:
  2898. if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT))
  2899. Opc = ISD::FMAXNUM;
  2900. else if (TLI.isOperationLegalOrCustom(ISD::FMAXIMUM, VT))
  2901. Opc = ISD::FMAXIMUM;
  2902. else if (UseScalarMinMax)
  2903. Opc = TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType()) ?
  2904. ISD::FMAXNUM : ISD::FMAXIMUM;
  2905. break;
  2906. }
  2907. break;
  2908. case SPF_ABS:
  2909. IsUnaryAbs = true;
  2910. Opc = ISD::ABS;
  2911. break;
  2912. case SPF_NABS:
  2913. // TODO: we need to produce sub(0, abs(X)).
  2914. default: break;
  2915. }
  2916. if (!IsUnaryAbs && Opc != ISD::DELETED_NODE &&
  2917. (TLI.isOperationLegalOrCustom(Opc, VT) ||
  2918. (UseScalarMinMax &&
  2919. TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) &&
  2920. // If the underlying comparison instruction is used by any other
  2921. // instruction, the consumed instructions won't be destroyed, so it is
  2922. // not profitable to convert to a min/max.
  2923. hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) {
  2924. OpCode = Opc;
  2925. LHSVal = getValue(LHS);
  2926. RHSVal = getValue(RHS);
  2927. BaseOps = {};
  2928. }
  2929. if (IsUnaryAbs) {
  2930. OpCode = Opc;
  2931. LHSVal = getValue(LHS);
  2932. BaseOps = {};
  2933. }
  2934. }
  2935. if (IsUnaryAbs) {
  2936. for (unsigned i = 0; i != NumValues; ++i) {
  2937. Values[i] =
  2938. DAG.getNode(OpCode, getCurSDLoc(),
  2939. LHSVal.getNode()->getValueType(LHSVal.getResNo() + i),
  2940. SDValue(LHSVal.getNode(), LHSVal.getResNo() + i));
  2941. }
  2942. } else {
  2943. for (unsigned i = 0; i != NumValues; ++i) {
  2944. SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end());
  2945. Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i));
  2946. Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i));
  2947. Values[i] = DAG.getNode(
  2948. OpCode, getCurSDLoc(),
  2949. LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), Ops);
  2950. }
  2951. }
  2952. setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
  2953. DAG.getVTList(ValueVTs), Values));
  2954. }
  2955. void SelectionDAGBuilder::visitTrunc(const User &I) {
  2956. // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
  2957. SDValue N = getValue(I.getOperand(0));
  2958. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  2959. I.getType());
  2960. setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N));
  2961. }
  2962. void SelectionDAGBuilder::visitZExt(const User &I) {
  2963. // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
  2964. // ZExt also can't be a cast to bool for same reason. So, nothing much to do
  2965. SDValue N = getValue(I.getOperand(0));
  2966. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  2967. I.getType());
  2968. setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N));
  2969. }
  2970. void SelectionDAGBuilder::visitSExt(const User &I) {
  2971. // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
  2972. // SExt also can't be a cast to bool for same reason. So, nothing much to do
  2973. SDValue N = getValue(I.getOperand(0));
  2974. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  2975. I.getType());
  2976. setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
  2977. }
  2978. void SelectionDAGBuilder::visitFPTrunc(const User &I) {
  2979. // FPTrunc is never a no-op cast, no need to check
  2980. SDValue N = getValue(I.getOperand(0));
  2981. SDLoc dl = getCurSDLoc();
  2982. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2983. EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  2984. setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N,
  2985. DAG.getTargetConstant(
  2986. 0, dl, TLI.getPointerTy(DAG.getDataLayout()))));
  2987. }
  2988. void SelectionDAGBuilder::visitFPExt(const User &I) {
  2989. // FPExt is never a no-op cast, no need to check
  2990. SDValue N = getValue(I.getOperand(0));
  2991. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  2992. I.getType());
  2993. setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N));
  2994. }
  2995. void SelectionDAGBuilder::visitFPToUI(const User &I) {
  2996. // FPToUI is never a no-op cast, no need to check
  2997. SDValue N = getValue(I.getOperand(0));
  2998. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  2999. I.getType());
  3000. setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N));
  3001. }
  3002. void SelectionDAGBuilder::visitFPToSI(const User &I) {
  3003. // FPToSI is never a no-op cast, no need to check
  3004. SDValue N = getValue(I.getOperand(0));
  3005. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  3006. I.getType());
  3007. setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N));
  3008. }
  3009. void SelectionDAGBuilder::visitUIToFP(const User &I) {
  3010. // UIToFP is never a no-op cast, no need to check
  3011. SDValue N = getValue(I.getOperand(0));
  3012. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  3013. I.getType());
  3014. setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N));
  3015. }
  3016. void SelectionDAGBuilder::visitSIToFP(const User &I) {
  3017. // SIToFP is never a no-op cast, no need to check
  3018. SDValue N = getValue(I.getOperand(0));
  3019. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  3020. I.getType());
  3021. setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N));
  3022. }
  3023. void SelectionDAGBuilder::visitPtrToInt(const User &I) {
  3024. // What to do depends on the size of the integer and the size of the pointer.
  3025. // We can either truncate, zero extend, or no-op, accordingly.
  3026. SDValue N = getValue(I.getOperand(0));
  3027. auto &TLI = DAG.getTargetLoweringInfo();
  3028. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  3029. I.getType());
  3030. EVT PtrMemVT =
  3031. TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
  3032. N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
  3033. N = DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT);
  3034. setValue(&I, N);
  3035. }
  3036. void SelectionDAGBuilder::visitIntToPtr(const User &I) {
  3037. // What to do depends on the size of the integer and the size of the pointer.
  3038. // We can either truncate, zero extend, or no-op, accordingly.
  3039. SDValue N = getValue(I.getOperand(0));
  3040. auto &TLI = DAG.getTargetLoweringInfo();
  3041. EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  3042. EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
  3043. N = DAG.getZExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
  3044. N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), DestVT);
  3045. setValue(&I, N);
  3046. }
  3047. void SelectionDAGBuilder::visitBitCast(const User &I) {
  3048. SDValue N = getValue(I.getOperand(0));
  3049. SDLoc dl = getCurSDLoc();
  3050. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  3051. I.getType());
  3052. // BitCast assures us that source and destination are the same size so this is
  3053. // either a BITCAST or a no-op.
  3054. if (DestVT != N.getValueType())
  3055. setValue(&I, DAG.getNode(ISD::BITCAST, dl,
  3056. DestVT, N)); // convert types.
  3057. // Check if the original LLVM IR Operand was a ConstantInt, because getValue()
  3058. // might fold any kind of constant expression to an integer constant and that
  3059. // is not what we are looking for. Only recognize a bitcast of a genuine
  3060. // constant integer as an opaque constant.
  3061. else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0)))
  3062. setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false,
  3063. /*isOpaque*/true));
  3064. else
  3065. setValue(&I, N); // noop cast.
  3066. }
  3067. void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) {
  3068. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3069. const Value *SV = I.getOperand(0);
  3070. SDValue N = getValue(SV);
  3071. EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  3072. unsigned SrcAS = SV->getType()->getPointerAddressSpace();
  3073. unsigned DestAS = I.getType()->getPointerAddressSpace();
  3074. if (!TLI.isNoopAddrSpaceCast(SrcAS, DestAS))
  3075. N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS);
  3076. setValue(&I, N);
  3077. }
  3078. void SelectionDAGBuilder::visitInsertElement(const User &I) {
  3079. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3080. SDValue InVec = getValue(I.getOperand(0));
  3081. SDValue InVal = getValue(I.getOperand(1));
  3082. SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(),
  3083. TLI.getVectorIdxTy(DAG.getDataLayout()));
  3084. setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(),
  3085. TLI.getValueType(DAG.getDataLayout(), I.getType()),
  3086. InVec, InVal, InIdx));
  3087. }
  3088. void SelectionDAGBuilder::visitExtractElement(const User &I) {
  3089. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3090. SDValue InVec = getValue(I.getOperand(0));
  3091. SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(),
  3092. TLI.getVectorIdxTy(DAG.getDataLayout()));
  3093. setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(),
  3094. TLI.getValueType(DAG.getDataLayout(), I.getType()),
  3095. InVec, InIdx));
  3096. }
  3097. void SelectionDAGBuilder::visitShuffleVector(const User &I) {
  3098. SDValue Src1 = getValue(I.getOperand(0));
  3099. SDValue Src2 = getValue(I.getOperand(1));
  3100. SDLoc DL = getCurSDLoc();
  3101. SmallVector<int, 8> Mask;
  3102. ShuffleVectorInst::getShuffleMask(cast<Constant>(I.getOperand(2)), Mask);
  3103. unsigned MaskNumElts = Mask.size();
  3104. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3105. EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  3106. EVT SrcVT = Src1.getValueType();
  3107. unsigned SrcNumElts = SrcVT.getVectorNumElements();
  3108. if (SrcNumElts == MaskNumElts) {
  3109. setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask));
  3110. return;
  3111. }
  3112. // Normalize the shuffle vector since mask and vector length don't match.
  3113. if (SrcNumElts < MaskNumElts) {
  3114. // Mask is longer than the source vectors. We can use concatenate vector to
  3115. // make the mask and vectors lengths match.
  3116. if (MaskNumElts % SrcNumElts == 0) {
  3117. // Mask length is a multiple of the source vector length.
  3118. // Check if the shuffle is some kind of concatenation of the input
  3119. // vectors.
  3120. unsigned NumConcat = MaskNumElts / SrcNumElts;
  3121. bool IsConcat = true;
  3122. SmallVector<int, 8> ConcatSrcs(NumConcat, -1);
  3123. for (unsigned i = 0; i != MaskNumElts; ++i) {
  3124. int Idx = Mask[i];
  3125. if (Idx < 0)
  3126. continue;
  3127. // Ensure the indices in each SrcVT sized piece are sequential and that
  3128. // the same source is used for the whole piece.
  3129. if ((Idx % SrcNumElts != (i % SrcNumElts)) ||
  3130. (ConcatSrcs[i / SrcNumElts] >= 0 &&
  3131. ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) {
  3132. IsConcat = false;
  3133. break;
  3134. }
  3135. // Remember which source this index came from.
  3136. ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts;
  3137. }
  3138. // The shuffle is concatenating multiple vectors together. Just emit
  3139. // a CONCAT_VECTORS operation.
  3140. if (IsConcat) {
  3141. SmallVector<SDValue, 8> ConcatOps;
  3142. for (auto Src : ConcatSrcs) {
  3143. if (Src < 0)
  3144. ConcatOps.push_back(DAG.getUNDEF(SrcVT));
  3145. else if (Src == 0)
  3146. ConcatOps.push_back(Src1);
  3147. else
  3148. ConcatOps.push_back(Src2);
  3149. }
  3150. setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps));
  3151. return;
  3152. }
  3153. }
  3154. unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts);
  3155. unsigned NumConcat = PaddedMaskNumElts / SrcNumElts;
  3156. EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
  3157. PaddedMaskNumElts);
  3158. // Pad both vectors with undefs to make them the same length as the mask.
  3159. SDValue UndefVal = DAG.getUNDEF(SrcVT);
  3160. SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
  3161. SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
  3162. MOps1[0] = Src1;
  3163. MOps2[0] = Src2;
  3164. Src1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1);
  3165. Src2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2);
  3166. // Readjust mask for new input vector length.
  3167. SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1);
  3168. for (unsigned i = 0; i != MaskNumElts; ++i) {
  3169. int Idx = Mask[i];
  3170. if (Idx >= (int)SrcNumElts)
  3171. Idx -= SrcNumElts - PaddedMaskNumElts;
  3172. MappedOps[i] = Idx;
  3173. }
  3174. SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps);
  3175. // If the concatenated vector was padded, extract a subvector with the
  3176. // correct number of elements.
  3177. if (MaskNumElts != PaddedMaskNumElts)
  3178. Result = DAG.getNode(
  3179. ISD::EXTRACT_SUBVECTOR, DL, VT, Result,
  3180. DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
  3181. setValue(&I, Result);
  3182. return;
  3183. }
  3184. if (SrcNumElts > MaskNumElts) {
  3185. // Analyze the access pattern of the vector to see if we can extract
  3186. // two subvectors and do the shuffle.
  3187. int StartIdx[2] = { -1, -1 }; // StartIdx to extract from
  3188. bool CanExtract = true;
  3189. for (int Idx : Mask) {
  3190. unsigned Input = 0;
  3191. if (Idx < 0)
  3192. continue;
  3193. if (Idx >= (int)SrcNumElts) {
  3194. Input = 1;
  3195. Idx -= SrcNumElts;
  3196. }
  3197. // If all the indices come from the same MaskNumElts sized portion of
  3198. // the sources we can use extract. Also make sure the extract wouldn't
  3199. // extract past the end of the source.
  3200. int NewStartIdx = alignDown(Idx, MaskNumElts);
  3201. if (NewStartIdx + MaskNumElts > SrcNumElts ||
  3202. (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx))
  3203. CanExtract = false;
  3204. // Make sure we always update StartIdx as we use it to track if all
  3205. // elements are undef.
  3206. StartIdx[Input] = NewStartIdx;
  3207. }
  3208. if (StartIdx[0] < 0 && StartIdx[1] < 0) {
  3209. setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
  3210. return;
  3211. }
  3212. if (CanExtract) {
  3213. // Extract appropriate subvector and generate a vector shuffle
  3214. for (unsigned Input = 0; Input < 2; ++Input) {
  3215. SDValue &Src = Input == 0 ? Src1 : Src2;
  3216. if (StartIdx[Input] < 0)
  3217. Src = DAG.getUNDEF(VT);
  3218. else {
  3219. Src = DAG.getNode(
  3220. ISD::EXTRACT_SUBVECTOR, DL, VT, Src,
  3221. DAG.getConstant(StartIdx[Input], DL,
  3222. TLI.getVectorIdxTy(DAG.getDataLayout())));
  3223. }
  3224. }
  3225. // Calculate new mask.
  3226. SmallVector<int, 8> MappedOps(Mask.begin(), Mask.end());
  3227. for (int &Idx : MappedOps) {
  3228. if (Idx >= (int)SrcNumElts)
  3229. Idx -= SrcNumElts + StartIdx[1] - MaskNumElts;
  3230. else if (Idx >= 0)
  3231. Idx -= StartIdx[0];
  3232. }
  3233. setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps));
  3234. return;
  3235. }
  3236. }
  3237. // We can't use either concat vectors or extract subvectors so fall back to
  3238. // replacing the shuffle with extract and build vector.
  3239. // to insert and build vector.
  3240. EVT EltVT = VT.getVectorElementType();
  3241. EVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout());
  3242. SmallVector<SDValue,8> Ops;
  3243. for (int Idx : Mask) {
  3244. SDValue Res;
  3245. if (Idx < 0) {
  3246. Res = DAG.getUNDEF(EltVT);
  3247. } else {
  3248. SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2;
  3249. if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts;
  3250. Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
  3251. EltVT, Src, DAG.getConstant(Idx, DL, IdxVT));
  3252. }
  3253. Ops.push_back(Res);
  3254. }
  3255. setValue(&I, DAG.getBuildVector(VT, DL, Ops));
  3256. }
  3257. void SelectionDAGBuilder::visitInsertValue(const User &I) {
  3258. ArrayRef<unsigned> Indices;
  3259. if (const InsertValueInst *IV = dyn_cast<InsertValueInst>(&I))
  3260. Indices = IV->getIndices();
  3261. else
  3262. Indices = cast<ConstantExpr>(&I)->getIndices();
  3263. const Value *Op0 = I.getOperand(0);
  3264. const Value *Op1 = I.getOperand(1);
  3265. Type *AggTy = I.getType();
  3266. Type *ValTy = Op1->getType();
  3267. bool IntoUndef = isa<UndefValue>(Op0);
  3268. bool FromUndef = isa<UndefValue>(Op1);
  3269. unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
  3270. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3271. SmallVector<EVT, 4> AggValueVTs;
  3272. ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs);
  3273. SmallVector<EVT, 4> ValValueVTs;
  3274. ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
  3275. unsigned NumAggValues = AggValueVTs.size();
  3276. unsigned NumValValues = ValValueVTs.size();
  3277. SmallVector<SDValue, 4> Values(NumAggValues);
  3278. // Ignore an insertvalue that produces an empty object
  3279. if (!NumAggValues) {
  3280. setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
  3281. return;
  3282. }
  3283. SDValue Agg = getValue(Op0);
  3284. unsigned i = 0;
  3285. // Copy the beginning value(s) from the original aggregate.
  3286. for (; i != LinearIndex; ++i)
  3287. Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
  3288. SDValue(Agg.getNode(), Agg.getResNo() + i);
  3289. // Copy values from the inserted value(s).
  3290. if (NumValValues) {
  3291. SDValue Val = getValue(Op1);
  3292. for (; i != LinearIndex + NumValValues; ++i)
  3293. Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
  3294. SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
  3295. }
  3296. // Copy remaining value(s) from the original aggregate.
  3297. for (; i != NumAggValues; ++i)
  3298. Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
  3299. SDValue(Agg.getNode(), Agg.getResNo() + i);
  3300. setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
  3301. DAG.getVTList(AggValueVTs), Values));
  3302. }
  3303. void SelectionDAGBuilder::visitExtractValue(const User &I) {
  3304. ArrayRef<unsigned> Indices;
  3305. if (const ExtractValueInst *EV = dyn_cast<ExtractValueInst>(&I))
  3306. Indices = EV->getIndices();
  3307. else
  3308. Indices = cast<ConstantExpr>(&I)->getIndices();
  3309. const Value *Op0 = I.getOperand(0);
  3310. Type *AggTy = Op0->getType();
  3311. Type *ValTy = I.getType();
  3312. bool OutOfUndef = isa<UndefValue>(Op0);
  3313. unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
  3314. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3315. SmallVector<EVT, 4> ValValueVTs;
  3316. ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
  3317. unsigned NumValValues = ValValueVTs.size();
  3318. // Ignore a extractvalue that produces an empty object
  3319. if (!NumValValues) {
  3320. setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
  3321. return;
  3322. }
  3323. SmallVector<SDValue, 4> Values(NumValValues);
  3324. SDValue Agg = getValue(Op0);
  3325. // Copy out the selected value(s).
  3326. for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
  3327. Values[i - LinearIndex] =
  3328. OutOfUndef ?
  3329. DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
  3330. SDValue(Agg.getNode(), Agg.getResNo() + i);
  3331. setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
  3332. DAG.getVTList(ValValueVTs), Values));
  3333. }
  3334. void SelectionDAGBuilder::visitGetElementPtr(const User &I) {
  3335. Value *Op0 = I.getOperand(0);
  3336. // Note that the pointer operand may be a vector of pointers. Take the scalar
  3337. // element which holds a pointer.
  3338. unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace();
  3339. SDValue N = getValue(Op0);
  3340. SDLoc dl = getCurSDLoc();
  3341. auto &TLI = DAG.getTargetLoweringInfo();
  3342. MVT PtrTy = TLI.getPointerTy(DAG.getDataLayout(), AS);
  3343. MVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout(), AS);
  3344. // Normalize Vector GEP - all scalar operands should be converted to the
  3345. // splat vector.
  3346. unsigned VectorWidth = I.getType()->isVectorTy() ?
  3347. cast<VectorType>(I.getType())->getVectorNumElements() : 0;
  3348. if (VectorWidth && !N.getValueType().isVector()) {
  3349. LLVMContext &Context = *DAG.getContext();
  3350. EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorWidth);
  3351. N = DAG.getSplatBuildVector(VT, dl, N);
  3352. }
  3353. for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I);
  3354. GTI != E; ++GTI) {
  3355. const Value *Idx = GTI.getOperand();
  3356. if (StructType *StTy = GTI.getStructTypeOrNull()) {
  3357. unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
  3358. if (Field) {
  3359. // N = N + Offset
  3360. uint64_t Offset = DL->getStructLayout(StTy)->getElementOffset(Field);
  3361. // In an inbounds GEP with an offset that is nonnegative even when
  3362. // interpreted as signed, assume there is no unsigned overflow.
  3363. SDNodeFlags Flags;
  3364. if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds())
  3365. Flags.setNoUnsignedWrap(true);
  3366. N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N,
  3367. DAG.getConstant(Offset, dl, N.getValueType()), Flags);
  3368. }
  3369. } else {
  3370. unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS);
  3371. MVT IdxTy = MVT::getIntegerVT(IdxSize);
  3372. APInt ElementSize(IdxSize, DL->getTypeAllocSize(GTI.getIndexedType()));
  3373. // If this is a scalar constant or a splat vector of constants,
  3374. // handle it quickly.
  3375. const auto *CI = dyn_cast<ConstantInt>(Idx);
  3376. if (!CI && isa<ConstantDataVector>(Idx) &&
  3377. cast<ConstantDataVector>(Idx)->getSplatValue())
  3378. CI = cast<ConstantInt>(cast<ConstantDataVector>(Idx)->getSplatValue());
  3379. if (CI) {
  3380. if (CI->isZero())
  3381. continue;
  3382. APInt Offs = ElementSize * CI->getValue().sextOrTrunc(IdxSize);
  3383. LLVMContext &Context = *DAG.getContext();
  3384. SDValue OffsVal = VectorWidth ?
  3385. DAG.getConstant(Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorWidth)) :
  3386. DAG.getConstant(Offs, dl, IdxTy);
  3387. // In an inbouds GEP with an offset that is nonnegative even when
  3388. // interpreted as signed, assume there is no unsigned overflow.
  3389. SDNodeFlags Flags;
  3390. if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds())
  3391. Flags.setNoUnsignedWrap(true);
  3392. OffsVal = DAG.getSExtOrTrunc(OffsVal, dl, N.getValueType());
  3393. N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags);
  3394. continue;
  3395. }
  3396. // N = N + Idx * ElementSize;
  3397. SDValue IdxN = getValue(Idx);
  3398. if (!IdxN.getValueType().isVector() && VectorWidth) {
  3399. EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(), VectorWidth);
  3400. IdxN = DAG.getSplatBuildVector(VT, dl, IdxN);
  3401. }
  3402. // If the index is smaller or larger than intptr_t, truncate or extend
  3403. // it.
  3404. IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType());
  3405. // If this is a multiply by a power of two, turn it into a shl
  3406. // immediately. This is a very common case.
  3407. if (ElementSize != 1) {
  3408. if (ElementSize.isPowerOf2()) {
  3409. unsigned Amt = ElementSize.logBase2();
  3410. IdxN = DAG.getNode(ISD::SHL, dl,
  3411. N.getValueType(), IdxN,
  3412. DAG.getConstant(Amt, dl, IdxN.getValueType()));
  3413. } else {
  3414. SDValue Scale = DAG.getConstant(ElementSize.getZExtValue(), dl,
  3415. IdxN.getValueType());
  3416. IdxN = DAG.getNode(ISD::MUL, dl,
  3417. N.getValueType(), IdxN, Scale);
  3418. }
  3419. }
  3420. N = DAG.getNode(ISD::ADD, dl,
  3421. N.getValueType(), N, IdxN);
  3422. }
  3423. }
  3424. if (PtrMemTy != PtrTy && !cast<GEPOperator>(I).isInBounds())
  3425. N = DAG.getPtrExtendInReg(N, dl, PtrMemTy);
  3426. setValue(&I, N);
  3427. }
  3428. void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) {
  3429. // If this is a fixed sized alloca in the entry block of the function,
  3430. // allocate it statically on the stack.
  3431. if (FuncInfo.StaticAllocaMap.count(&I))
  3432. return; // getValue will auto-populate this.
  3433. SDLoc dl = getCurSDLoc();
  3434. Type *Ty = I.getAllocatedType();
  3435. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3436. auto &DL = DAG.getDataLayout();
  3437. uint64_t TySize = DL.getTypeAllocSize(Ty);
  3438. unsigned Align =
  3439. std::max((unsigned)DL.getPrefTypeAlignment(Ty), I.getAlignment());
  3440. SDValue AllocSize = getValue(I.getArraySize());
  3441. EVT IntPtr = TLI.getPointerTy(DAG.getDataLayout(), DL.getAllocaAddrSpace());
  3442. if (AllocSize.getValueType() != IntPtr)
  3443. AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr);
  3444. AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr,
  3445. AllocSize,
  3446. DAG.getConstant(TySize, dl, IntPtr));
  3447. // Handle alignment. If the requested alignment is less than or equal to
  3448. // the stack alignment, ignore it. If the size is greater than or equal to
  3449. // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
  3450. unsigned StackAlign =
  3451. DAG.getSubtarget().getFrameLowering()->getStackAlignment();
  3452. if (Align <= StackAlign)
  3453. Align = 0;
  3454. // Round the size of the allocation up to the stack alignment size
  3455. // by add SA-1 to the size. This doesn't overflow because we're computing
  3456. // an address inside an alloca.
  3457. SDNodeFlags Flags;
  3458. Flags.setNoUnsignedWrap(true);
  3459. AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize,
  3460. DAG.getConstant(StackAlign - 1, dl, IntPtr), Flags);
  3461. // Mask out the low bits for alignment purposes.
  3462. AllocSize =
  3463. DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize,
  3464. DAG.getConstant(~(uint64_t)(StackAlign - 1), dl, IntPtr));
  3465. SDValue Ops[] = {getRoot(), AllocSize, DAG.getConstant(Align, dl, IntPtr)};
  3466. SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
  3467. SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops);
  3468. setValue(&I, DSA);
  3469. DAG.setRoot(DSA.getValue(1));
  3470. assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects());
  3471. }
  3472. void SelectionDAGBuilder::visitLoad(const LoadInst &I) {
  3473. if (I.isAtomic())
  3474. return visitAtomicLoad(I);
  3475. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3476. const Value *SV = I.getOperand(0);
  3477. if (TLI.supportSwiftError()) {
  3478. // Swifterror values can come from either a function parameter with
  3479. // swifterror attribute or an alloca with swifterror attribute.
  3480. if (const Argument *Arg = dyn_cast<Argument>(SV)) {
  3481. if (Arg->hasSwiftErrorAttr())
  3482. return visitLoadFromSwiftError(I);
  3483. }
  3484. if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) {
  3485. if (Alloca->isSwiftError())
  3486. return visitLoadFromSwiftError(I);
  3487. }
  3488. }
  3489. SDValue Ptr = getValue(SV);
  3490. Type *Ty = I.getType();
  3491. bool isVolatile = I.isVolatile();
  3492. bool isNonTemporal = I.getMetadata(LLVMContext::MD_nontemporal) != nullptr;
  3493. bool isInvariant = I.getMetadata(LLVMContext::MD_invariant_load) != nullptr;
  3494. bool isDereferenceable = isDereferenceablePointer(SV, DAG.getDataLayout());
  3495. unsigned Alignment = I.getAlignment();
  3496. AAMDNodes AAInfo;
  3497. I.getAAMetadata(AAInfo);
  3498. const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
  3499. SmallVector<EVT, 4> ValueVTs, MemVTs;
  3500. SmallVector<uint64_t, 4> Offsets;
  3501. ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &MemVTs, &Offsets);
  3502. unsigned NumValues = ValueVTs.size();
  3503. if (NumValues == 0)
  3504. return;
  3505. SDValue Root;
  3506. bool ConstantMemory = false;
  3507. if (isVolatile || NumValues > MaxParallelChains)
  3508. // Serialize volatile loads with other side effects.
  3509. Root = getRoot();
  3510. else if (AA &&
  3511. AA->pointsToConstantMemory(MemoryLocation(
  3512. SV,
  3513. LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
  3514. AAInfo))) {
  3515. // Do not serialize (non-volatile) loads of constant memory with anything.
  3516. Root = DAG.getEntryNode();
  3517. ConstantMemory = true;
  3518. } else {
  3519. // Do not serialize non-volatile loads against each other.
  3520. Root = DAG.getRoot();
  3521. }
  3522. SDLoc dl = getCurSDLoc();
  3523. if (isVolatile)
  3524. Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG);
  3525. // An aggregate load cannot wrap around the address space, so offsets to its
  3526. // parts don't wrap either.
  3527. SDNodeFlags Flags;
  3528. Flags.setNoUnsignedWrap(true);
  3529. SmallVector<SDValue, 4> Values(NumValues);
  3530. SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
  3531. EVT PtrVT = Ptr.getValueType();
  3532. unsigned ChainI = 0;
  3533. for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
  3534. // Serializing loads here may result in excessive register pressure, and
  3535. // TokenFactor places arbitrary choke points on the scheduler. SD scheduling
  3536. // could recover a bit by hoisting nodes upward in the chain by recognizing
  3537. // they are side-effect free or do not alias. The optimizer should really
  3538. // avoid this case by converting large object/array copies to llvm.memcpy
  3539. // (MaxParallelChains should always remain as failsafe).
  3540. if (ChainI == MaxParallelChains) {
  3541. assert(PendingLoads.empty() && "PendingLoads must be serialized first");
  3542. SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
  3543. makeArrayRef(Chains.data(), ChainI));
  3544. Root = Chain;
  3545. ChainI = 0;
  3546. }
  3547. SDValue A = DAG.getNode(ISD::ADD, dl,
  3548. PtrVT, Ptr,
  3549. DAG.getConstant(Offsets[i], dl, PtrVT),
  3550. Flags);
  3551. auto MMOFlags = MachineMemOperand::MONone;
  3552. if (isVolatile)
  3553. MMOFlags |= MachineMemOperand::MOVolatile;
  3554. if (isNonTemporal)
  3555. MMOFlags |= MachineMemOperand::MONonTemporal;
  3556. if (isInvariant)
  3557. MMOFlags |= MachineMemOperand::MOInvariant;
  3558. if (isDereferenceable)
  3559. MMOFlags |= MachineMemOperand::MODereferenceable;
  3560. MMOFlags |= TLI.getMMOFlags(I);
  3561. SDValue L = DAG.getLoad(MemVTs[i], dl, Root, A,
  3562. MachinePointerInfo(SV, Offsets[i]), Alignment,
  3563. MMOFlags, AAInfo, Ranges);
  3564. Chains[ChainI] = L.getValue(1);
  3565. if (MemVTs[i] != ValueVTs[i])
  3566. L = DAG.getZExtOrTrunc(L, dl, ValueVTs[i]);
  3567. Values[i] = L;
  3568. }
  3569. if (!ConstantMemory) {
  3570. SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
  3571. makeArrayRef(Chains.data(), ChainI));
  3572. if (isVolatile)
  3573. DAG.setRoot(Chain);
  3574. else
  3575. PendingLoads.push_back(Chain);
  3576. }
  3577. setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl,
  3578. DAG.getVTList(ValueVTs), Values));
  3579. }
  3580. void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) {
  3581. assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
  3582. "call visitStoreToSwiftError when backend supports swifterror");
  3583. SmallVector<EVT, 4> ValueVTs;
  3584. SmallVector<uint64_t, 4> Offsets;
  3585. const Value *SrcV = I.getOperand(0);
  3586. ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
  3587. SrcV->getType(), ValueVTs, &Offsets);
  3588. assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
  3589. "expect a single EVT for swifterror");
  3590. SDValue Src = getValue(SrcV);
  3591. // Create a virtual register, then update the virtual register.
  3592. unsigned VReg =
  3593. SwiftError.getOrCreateVRegDefAt(&I, FuncInfo.MBB, I.getPointerOperand());
  3594. // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue
  3595. // Chain can be getRoot or getControlRoot.
  3596. SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg,
  3597. SDValue(Src.getNode(), Src.getResNo()));
  3598. DAG.setRoot(CopyNode);
  3599. }
  3600. void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) {
  3601. assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
  3602. "call visitLoadFromSwiftError when backend supports swifterror");
  3603. assert(!I.isVolatile() &&
  3604. I.getMetadata(LLVMContext::MD_nontemporal) == nullptr &&
  3605. I.getMetadata(LLVMContext::MD_invariant_load) == nullptr &&
  3606. "Support volatile, non temporal, invariant for load_from_swift_error");
  3607. const Value *SV = I.getOperand(0);
  3608. Type *Ty = I.getType();
  3609. AAMDNodes AAInfo;
  3610. I.getAAMetadata(AAInfo);
  3611. assert(
  3612. (!AA ||
  3613. !AA->pointsToConstantMemory(MemoryLocation(
  3614. SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
  3615. AAInfo))) &&
  3616. "load_from_swift_error should not be constant memory");
  3617. SmallVector<EVT, 4> ValueVTs;
  3618. SmallVector<uint64_t, 4> Offsets;
  3619. ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty,
  3620. ValueVTs, &Offsets);
  3621. assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
  3622. "expect a single EVT for swifterror");
  3623. // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT
  3624. SDValue L = DAG.getCopyFromReg(
  3625. getRoot(), getCurSDLoc(),
  3626. SwiftError.getOrCreateVRegUseAt(&I, FuncInfo.MBB, SV), ValueVTs[0]);
  3627. setValue(&I, L);
  3628. }
  3629. void SelectionDAGBuilder::visitStore(const StoreInst &I) {
  3630. if (I.isAtomic())
  3631. return visitAtomicStore(I);
  3632. const Value *SrcV = I.getOperand(0);
  3633. const Value *PtrV = I.getOperand(1);
  3634. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3635. if (TLI.supportSwiftError()) {
  3636. // Swifterror values can come from either a function parameter with
  3637. // swifterror attribute or an alloca with swifterror attribute.
  3638. if (const Argument *Arg = dyn_cast<Argument>(PtrV)) {
  3639. if (Arg->hasSwiftErrorAttr())
  3640. return visitStoreToSwiftError(I);
  3641. }
  3642. if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) {
  3643. if (Alloca->isSwiftError())
  3644. return visitStoreToSwiftError(I);
  3645. }
  3646. }
  3647. SmallVector<EVT, 4> ValueVTs, MemVTs;
  3648. SmallVector<uint64_t, 4> Offsets;
  3649. ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
  3650. SrcV->getType(), ValueVTs, &MemVTs, &Offsets);
  3651. unsigned NumValues = ValueVTs.size();
  3652. if (NumValues == 0)
  3653. return;
  3654. // Get the lowered operands. Note that we do this after
  3655. // checking if NumResults is zero, because with zero results
  3656. // the operands won't have values in the map.
  3657. SDValue Src = getValue(SrcV);
  3658. SDValue Ptr = getValue(PtrV);
  3659. SDValue Root = getRoot();
  3660. SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
  3661. SDLoc dl = getCurSDLoc();
  3662. EVT PtrVT = Ptr.getValueType();
  3663. unsigned Alignment = I.getAlignment();
  3664. AAMDNodes AAInfo;
  3665. I.getAAMetadata(AAInfo);
  3666. auto MMOFlags = MachineMemOperand::MONone;
  3667. if (I.isVolatile())
  3668. MMOFlags |= MachineMemOperand::MOVolatile;
  3669. if (I.getMetadata(LLVMContext::MD_nontemporal) != nullptr)
  3670. MMOFlags |= MachineMemOperand::MONonTemporal;
  3671. MMOFlags |= TLI.getMMOFlags(I);
  3672. // An aggregate load cannot wrap around the address space, so offsets to its
  3673. // parts don't wrap either.
  3674. SDNodeFlags Flags;
  3675. Flags.setNoUnsignedWrap(true);
  3676. unsigned ChainI = 0;
  3677. for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
  3678. // See visitLoad comments.
  3679. if (ChainI == MaxParallelChains) {
  3680. SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
  3681. makeArrayRef(Chains.data(), ChainI));
  3682. Root = Chain;
  3683. ChainI = 0;
  3684. }
  3685. SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, Ptr,
  3686. DAG.getConstant(Offsets[i], dl, PtrVT), Flags);
  3687. SDValue Val = SDValue(Src.getNode(), Src.getResNo() + i);
  3688. if (MemVTs[i] != ValueVTs[i])
  3689. Val = DAG.getPtrExtOrTrunc(Val, dl, MemVTs[i]);
  3690. SDValue St =
  3691. DAG.getStore(Root, dl, Val, Add, MachinePointerInfo(PtrV, Offsets[i]),
  3692. Alignment, MMOFlags, AAInfo);
  3693. Chains[ChainI] = St;
  3694. }
  3695. SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
  3696. makeArrayRef(Chains.data(), ChainI));
  3697. DAG.setRoot(StoreNode);
  3698. }
  3699. void SelectionDAGBuilder::visitMaskedStore(const CallInst &I,
  3700. bool IsCompressing) {
  3701. SDLoc sdl = getCurSDLoc();
  3702. auto getMaskedStoreOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
  3703. unsigned& Alignment) {
  3704. // llvm.masked.store.*(Src0, Ptr, alignment, Mask)
  3705. Src0 = I.getArgOperand(0);
  3706. Ptr = I.getArgOperand(1);
  3707. Alignment = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue();
  3708. Mask = I.getArgOperand(3);
  3709. };
  3710. auto getCompressingStoreOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
  3711. unsigned& Alignment) {
  3712. // llvm.masked.compressstore.*(Src0, Ptr, Mask)
  3713. Src0 = I.getArgOperand(0);
  3714. Ptr = I.getArgOperand(1);
  3715. Mask = I.getArgOperand(2);
  3716. Alignment = 0;
  3717. };
  3718. Value *PtrOperand, *MaskOperand, *Src0Operand;
  3719. unsigned Alignment;
  3720. if (IsCompressing)
  3721. getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
  3722. else
  3723. getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
  3724. SDValue Ptr = getValue(PtrOperand);
  3725. SDValue Src0 = getValue(Src0Operand);
  3726. SDValue Mask = getValue(MaskOperand);
  3727. EVT VT = Src0.getValueType();
  3728. if (!Alignment)
  3729. Alignment = DAG.getEVTAlignment(VT);
  3730. AAMDNodes AAInfo;
  3731. I.getAAMetadata(AAInfo);
  3732. MachineMemOperand *MMO =
  3733. DAG.getMachineFunction().
  3734. getMachineMemOperand(MachinePointerInfo(PtrOperand),
  3735. MachineMemOperand::MOStore, VT.getStoreSize(),
  3736. Alignment, AAInfo);
  3737. SDValue StoreNode = DAG.getMaskedStore(getRoot(), sdl, Src0, Ptr, Mask, VT,
  3738. MMO, false /* Truncating */,
  3739. IsCompressing);
  3740. DAG.setRoot(StoreNode);
  3741. setValue(&I, StoreNode);
  3742. }
  3743. // Get a uniform base for the Gather/Scatter intrinsic.
  3744. // The first argument of the Gather/Scatter intrinsic is a vector of pointers.
  3745. // We try to represent it as a base pointer + vector of indices.
  3746. // Usually, the vector of pointers comes from a 'getelementptr' instruction.
  3747. // The first operand of the GEP may be a single pointer or a vector of pointers
  3748. // Example:
  3749. // %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind
  3750. // or
  3751. // %gep.ptr = getelementptr i32, i32* %ptr, <8 x i32> %ind
  3752. // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, ..
  3753. //
  3754. // When the first GEP operand is a single pointer - it is the uniform base we
  3755. // are looking for. If first operand of the GEP is a splat vector - we
  3756. // extract the splat value and use it as a uniform base.
  3757. // In all other cases the function returns 'false'.
  3758. static bool getUniformBase(const Value* &Ptr, SDValue& Base, SDValue& Index,
  3759. SDValue &Scale, SelectionDAGBuilder* SDB) {
  3760. SelectionDAG& DAG = SDB->DAG;
  3761. LLVMContext &Context = *DAG.getContext();
  3762. assert(Ptr->getType()->isVectorTy() && "Uexpected pointer type");
  3763. const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr);
  3764. if (!GEP)
  3765. return false;
  3766. const Value *GEPPtr = GEP->getPointerOperand();
  3767. if (!GEPPtr->getType()->isVectorTy())
  3768. Ptr = GEPPtr;
  3769. else if (!(Ptr = getSplatValue(GEPPtr)))
  3770. return false;
  3771. unsigned FinalIndex = GEP->getNumOperands() - 1;
  3772. Value *IndexVal = GEP->getOperand(FinalIndex);
  3773. // Ensure all the other indices are 0.
  3774. for (unsigned i = 1; i < FinalIndex; ++i) {
  3775. auto *C = dyn_cast<ConstantInt>(GEP->getOperand(i));
  3776. if (!C || !C->isZero())
  3777. return false;
  3778. }
  3779. // The operands of the GEP may be defined in another basic block.
  3780. // In this case we'll not find nodes for the operands.
  3781. if (!SDB->findValue(Ptr) || !SDB->findValue(IndexVal))
  3782. return false;
  3783. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3784. const DataLayout &DL = DAG.getDataLayout();
  3785. Scale = DAG.getTargetConstant(DL.getTypeAllocSize(GEP->getResultElementType()),
  3786. SDB->getCurSDLoc(), TLI.getPointerTy(DL));
  3787. Base = SDB->getValue(Ptr);
  3788. Index = SDB->getValue(IndexVal);
  3789. if (!Index.getValueType().isVector()) {
  3790. unsigned GEPWidth = GEP->getType()->getVectorNumElements();
  3791. EVT VT = EVT::getVectorVT(Context, Index.getValueType(), GEPWidth);
  3792. Index = DAG.getSplatBuildVector(VT, SDLoc(Index), Index);
  3793. }
  3794. return true;
  3795. }
  3796. void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) {
  3797. SDLoc sdl = getCurSDLoc();
  3798. // llvm.masked.scatter.*(Src0, Ptrs, alignemt, Mask)
  3799. const Value *Ptr = I.getArgOperand(1);
  3800. SDValue Src0 = getValue(I.getArgOperand(0));
  3801. SDValue Mask = getValue(I.getArgOperand(3));
  3802. EVT VT = Src0.getValueType();
  3803. unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(2)))->getZExtValue();
  3804. if (!Alignment)
  3805. Alignment = DAG.getEVTAlignment(VT);
  3806. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3807. AAMDNodes AAInfo;
  3808. I.getAAMetadata(AAInfo);
  3809. SDValue Base;
  3810. SDValue Index;
  3811. SDValue Scale;
  3812. const Value *BasePtr = Ptr;
  3813. bool UniformBase = getUniformBase(BasePtr, Base, Index, Scale, this);
  3814. const Value *MemOpBasePtr = UniformBase ? BasePtr : nullptr;
  3815. MachineMemOperand *MMO = DAG.getMachineFunction().
  3816. getMachineMemOperand(MachinePointerInfo(MemOpBasePtr),
  3817. MachineMemOperand::MOStore, VT.getStoreSize(),
  3818. Alignment, AAInfo);
  3819. if (!UniformBase) {
  3820. Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
  3821. Index = getValue(Ptr);
  3822. Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
  3823. }
  3824. SDValue Ops[] = { getRoot(), Src0, Mask, Base, Index, Scale };
  3825. SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl,
  3826. Ops, MMO);
  3827. DAG.setRoot(Scatter);
  3828. setValue(&I, Scatter);
  3829. }
  3830. void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) {
  3831. SDLoc sdl = getCurSDLoc();
  3832. auto getMaskedLoadOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
  3833. unsigned& Alignment) {
  3834. // @llvm.masked.load.*(Ptr, alignment, Mask, Src0)
  3835. Ptr = I.getArgOperand(0);
  3836. Alignment = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
  3837. Mask = I.getArgOperand(2);
  3838. Src0 = I.getArgOperand(3);
  3839. };
  3840. auto getExpandingLoadOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
  3841. unsigned& Alignment) {
  3842. // @llvm.masked.expandload.*(Ptr, Mask, Src0)
  3843. Ptr = I.getArgOperand(0);
  3844. Alignment = 0;
  3845. Mask = I.getArgOperand(1);
  3846. Src0 = I.getArgOperand(2);
  3847. };
  3848. Value *PtrOperand, *MaskOperand, *Src0Operand;
  3849. unsigned Alignment;
  3850. if (IsExpanding)
  3851. getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
  3852. else
  3853. getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
  3854. SDValue Ptr = getValue(PtrOperand);
  3855. SDValue Src0 = getValue(Src0Operand);
  3856. SDValue Mask = getValue(MaskOperand);
  3857. EVT VT = Src0.getValueType();
  3858. if (!Alignment)
  3859. Alignment = DAG.getEVTAlignment(VT);
  3860. AAMDNodes AAInfo;
  3861. I.getAAMetadata(AAInfo);
  3862. const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
  3863. // Do not serialize masked loads of constant memory with anything.
  3864. bool AddToChain =
  3865. !AA || !AA->pointsToConstantMemory(MemoryLocation(
  3866. PtrOperand,
  3867. LocationSize::precise(
  3868. DAG.getDataLayout().getTypeStoreSize(I.getType())),
  3869. AAInfo));
  3870. SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
  3871. MachineMemOperand *MMO =
  3872. DAG.getMachineFunction().
  3873. getMachineMemOperand(MachinePointerInfo(PtrOperand),
  3874. MachineMemOperand::MOLoad, VT.getStoreSize(),
  3875. Alignment, AAInfo, Ranges);
  3876. SDValue Load = DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Mask, Src0, VT, MMO,
  3877. ISD::NON_EXTLOAD, IsExpanding);
  3878. if (AddToChain)
  3879. PendingLoads.push_back(Load.getValue(1));
  3880. setValue(&I, Load);
  3881. }
  3882. void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) {
  3883. SDLoc sdl = getCurSDLoc();
  3884. // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0)
  3885. const Value *Ptr = I.getArgOperand(0);
  3886. SDValue Src0 = getValue(I.getArgOperand(3));
  3887. SDValue Mask = getValue(I.getArgOperand(2));
  3888. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3889. EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  3890. unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(1)))->getZExtValue();
  3891. if (!Alignment)
  3892. Alignment = DAG.getEVTAlignment(VT);
  3893. AAMDNodes AAInfo;
  3894. I.getAAMetadata(AAInfo);
  3895. const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
  3896. SDValue Root = DAG.getRoot();
  3897. SDValue Base;
  3898. SDValue Index;
  3899. SDValue Scale;
  3900. const Value *BasePtr = Ptr;
  3901. bool UniformBase = getUniformBase(BasePtr, Base, Index, Scale, this);
  3902. bool ConstantMemory = false;
  3903. if (UniformBase && AA &&
  3904. AA->pointsToConstantMemory(
  3905. MemoryLocation(BasePtr,
  3906. LocationSize::precise(
  3907. DAG.getDataLayout().getTypeStoreSize(I.getType())),
  3908. AAInfo))) {
  3909. // Do not serialize (non-volatile) loads of constant memory with anything.
  3910. Root = DAG.getEntryNode();
  3911. ConstantMemory = true;
  3912. }
  3913. MachineMemOperand *MMO =
  3914. DAG.getMachineFunction().
  3915. getMachineMemOperand(MachinePointerInfo(UniformBase ? BasePtr : nullptr),
  3916. MachineMemOperand::MOLoad, VT.getStoreSize(),
  3917. Alignment, AAInfo, Ranges);
  3918. if (!UniformBase) {
  3919. Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
  3920. Index = getValue(Ptr);
  3921. Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
  3922. }
  3923. SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale };
  3924. SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl,
  3925. Ops, MMO);
  3926. SDValue OutChain = Gather.getValue(1);
  3927. if (!ConstantMemory)
  3928. PendingLoads.push_back(OutChain);
  3929. setValue(&I, Gather);
  3930. }
  3931. void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) {
  3932. SDLoc dl = getCurSDLoc();
  3933. AtomicOrdering SuccessOrdering = I.getSuccessOrdering();
  3934. AtomicOrdering FailureOrdering = I.getFailureOrdering();
  3935. SyncScope::ID SSID = I.getSyncScopeID();
  3936. SDValue InChain = getRoot();
  3937. MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType();
  3938. SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other);
  3939. auto Alignment = DAG.getEVTAlignment(MemVT);
  3940. auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
  3941. if (I.isVolatile())
  3942. Flags |= MachineMemOperand::MOVolatile;
  3943. Flags |= DAG.getTargetLoweringInfo().getMMOFlags(I);
  3944. MachineFunction &MF = DAG.getMachineFunction();
  3945. MachineMemOperand *MMO =
  3946. MF.getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()),
  3947. Flags, MemVT.getStoreSize(), Alignment,
  3948. AAMDNodes(), nullptr, SSID, SuccessOrdering,
  3949. FailureOrdering);
  3950. SDValue L = DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS,
  3951. dl, MemVT, VTs, InChain,
  3952. getValue(I.getPointerOperand()),
  3953. getValue(I.getCompareOperand()),
  3954. getValue(I.getNewValOperand()), MMO);
  3955. SDValue OutChain = L.getValue(2);
  3956. setValue(&I, L);
  3957. DAG.setRoot(OutChain);
  3958. }
  3959. void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) {
  3960. SDLoc dl = getCurSDLoc();
  3961. ISD::NodeType NT;
  3962. switch (I.getOperation()) {
  3963. default: llvm_unreachable("Unknown atomicrmw operation");
  3964. case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break;
  3965. case AtomicRMWInst::Add: NT = ISD::ATOMIC_LOAD_ADD; break;
  3966. case AtomicRMWInst::Sub: NT = ISD::ATOMIC_LOAD_SUB; break;
  3967. case AtomicRMWInst::And: NT = ISD::ATOMIC_LOAD_AND; break;
  3968. case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break;
  3969. case AtomicRMWInst::Or: NT = ISD::ATOMIC_LOAD_OR; break;
  3970. case AtomicRMWInst::Xor: NT = ISD::ATOMIC_LOAD_XOR; break;
  3971. case AtomicRMWInst::Max: NT = ISD::ATOMIC_LOAD_MAX; break;
  3972. case AtomicRMWInst::Min: NT = ISD::ATOMIC_LOAD_MIN; break;
  3973. case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break;
  3974. case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break;
  3975. case AtomicRMWInst::FAdd: NT = ISD::ATOMIC_LOAD_FADD; break;
  3976. case AtomicRMWInst::FSub: NT = ISD::ATOMIC_LOAD_FSUB; break;
  3977. }
  3978. AtomicOrdering Ordering = I.getOrdering();
  3979. SyncScope::ID SSID = I.getSyncScopeID();
  3980. SDValue InChain = getRoot();
  3981. auto MemVT = getValue(I.getValOperand()).getSimpleValueType();
  3982. auto Alignment = DAG.getEVTAlignment(MemVT);
  3983. auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
  3984. if (I.isVolatile())
  3985. Flags |= MachineMemOperand::MOVolatile;
  3986. Flags |= DAG.getTargetLoweringInfo().getMMOFlags(I);
  3987. MachineFunction &MF = DAG.getMachineFunction();
  3988. MachineMemOperand *MMO =
  3989. MF.getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()), Flags,
  3990. MemVT.getStoreSize(), Alignment, AAMDNodes(),
  3991. nullptr, SSID, Ordering);
  3992. SDValue L =
  3993. DAG.getAtomic(NT, dl, MemVT, InChain,
  3994. getValue(I.getPointerOperand()), getValue(I.getValOperand()),
  3995. MMO);
  3996. SDValue OutChain = L.getValue(1);
  3997. setValue(&I, L);
  3998. DAG.setRoot(OutChain);
  3999. }
  4000. void SelectionDAGBuilder::visitFence(const FenceInst &I) {
  4001. SDLoc dl = getCurSDLoc();
  4002. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  4003. SDValue Ops[3];
  4004. Ops[0] = getRoot();
  4005. Ops[1] = DAG.getConstant((unsigned)I.getOrdering(), dl,
  4006. TLI.getFenceOperandTy(DAG.getDataLayout()));
  4007. Ops[2] = DAG.getConstant(I.getSyncScopeID(), dl,
  4008. TLI.getFenceOperandTy(DAG.getDataLayout()));
  4009. DAG.setRoot(DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops));
  4010. }
  4011. void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) {
  4012. SDLoc dl = getCurSDLoc();
  4013. AtomicOrdering Order = I.getOrdering();
  4014. SyncScope::ID SSID = I.getSyncScopeID();
  4015. SDValue InChain = getRoot();
  4016. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  4017. EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  4018. EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
  4019. if (!TLI.supportsUnalignedAtomics() &&
  4020. I.getAlignment() < MemVT.getSizeInBits() / 8)
  4021. report_fatal_error("Cannot generate unaligned atomic load");
  4022. auto Flags = MachineMemOperand::MOLoad;
  4023. if (I.isVolatile())
  4024. Flags |= MachineMemOperand::MOVolatile;
  4025. if (I.getMetadata(LLVMContext::MD_invariant_load) != nullptr)
  4026. Flags |= MachineMemOperand::MOInvariant;
  4027. if (isDereferenceablePointer(I.getPointerOperand(), DAG.getDataLayout()))
  4028. Flags |= MachineMemOperand::MODereferenceable;
  4029. Flags |= TLI.getMMOFlags(I);
  4030. MachineMemOperand *MMO =
  4031. DAG.getMachineFunction().
  4032. getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()),
  4033. Flags, MemVT.getStoreSize(),
  4034. I.getAlignment() ? I.getAlignment() :
  4035. DAG.getEVTAlignment(MemVT),
  4036. AAMDNodes(), nullptr, SSID, Order);
  4037. InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG);
  4038. SDValue L =
  4039. DAG.getAtomic(ISD::ATOMIC_LOAD, dl, MemVT, MemVT, InChain,
  4040. getValue(I.getPointerOperand()), MMO);
  4041. SDValue OutChain = L.getValue(1);
  4042. if (MemVT != VT)
  4043. L = DAG.getPtrExtOrTrunc(L, dl, VT);
  4044. setValue(&I, L);
  4045. DAG.setRoot(OutChain);
  4046. }
  4047. void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) {
  4048. SDLoc dl = getCurSDLoc();
  4049. AtomicOrdering Ordering = I.getOrdering();
  4050. SyncScope::ID SSID = I.getSyncScopeID();
  4051. SDValue InChain = getRoot();
  4052. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  4053. EVT MemVT =
  4054. TLI.getMemValueType(DAG.getDataLayout(), I.getValueOperand()->getType());
  4055. if (I.getAlignment() < MemVT.getSizeInBits() / 8)
  4056. report_fatal_error("Cannot generate unaligned atomic store");
  4057. auto Flags = MachineMemOperand::MOStore;
  4058. if (I.isVolatile())
  4059. Flags |= MachineMemOperand::MOVolatile;
  4060. Flags |= TLI.getMMOFlags(I);
  4061. MachineFunction &MF = DAG.getMachineFunction();
  4062. MachineMemOperand *MMO =
  4063. MF.getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()), Flags,
  4064. MemVT.getStoreSize(), I.getAlignment(), AAMDNodes(),
  4065. nullptr, SSID, Ordering);
  4066. SDValue Val = getValue(I.getValueOperand());
  4067. if (Val.getValueType() != MemVT)
  4068. Val = DAG.getPtrExtOrTrunc(Val, dl, MemVT);
  4069. SDValue OutChain = DAG.getAtomic(ISD::ATOMIC_STORE, dl, MemVT, InChain,
  4070. getValue(I.getPointerOperand()), Val, MMO);
  4071. DAG.setRoot(OutChain);
  4072. }
  4073. /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
  4074. /// node.
  4075. void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I,
  4076. unsigned Intrinsic) {
  4077. // Ignore the callsite's attributes. A specific call site may be marked with
  4078. // readnone, but the lowering code will expect the chain based on the
  4079. // definition.
  4080. const Function *F = I.getCalledFunction();
  4081. bool HasChain = !F->doesNotAccessMemory();
  4082. bool OnlyLoad = HasChain && F->onlyReadsMemory();
  4083. // Build the operand list.
  4084. SmallVector<SDValue, 8> Ops;
  4085. if (HasChain) { // If this intrinsic has side-effects, chainify it.
  4086. if (OnlyLoad) {
  4087. // We don't need to serialize loads against other loads.
  4088. Ops.push_back(DAG.getRoot());
  4089. } else {
  4090. Ops.push_back(getRoot());
  4091. }
  4092. }
  4093. // Info is set by getTgtMemInstrinsic
  4094. TargetLowering::IntrinsicInfo Info;
  4095. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  4096. bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I,
  4097. DAG.getMachineFunction(),
  4098. Intrinsic);
  4099. // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
  4100. if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID ||
  4101. Info.opc == ISD::INTRINSIC_W_CHAIN)
  4102. Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(),
  4103. TLI.getPointerTy(DAG.getDataLayout())));
  4104. // Add all operands of the call to the operand list.
  4105. for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) {
  4106. SDValue Op = getValue(I.getArgOperand(i));
  4107. Ops.push_back(Op);
  4108. }
  4109. SmallVector<EVT, 4> ValueVTs;
  4110. ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs);
  4111. if (HasChain)
  4112. ValueVTs.push_back(MVT::Other);
  4113. SDVTList VTs = DAG.getVTList(ValueVTs);
  4114. // Create the node.
  4115. SDValue Result;
  4116. if (IsTgtIntrinsic) {
  4117. // This is target intrinsic that touches memory
  4118. Result = DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(), VTs,
  4119. Ops, Info.memVT,
  4120. MachinePointerInfo(Info.ptrVal, Info.offset), Info.align,
  4121. Info.flags, Info.size);
  4122. } else if (!HasChain) {
  4123. Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops);
  4124. } else if (!I.getType()->isVoidTy()) {
  4125. Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops);
  4126. } else {
  4127. Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops);
  4128. }
  4129. if (HasChain) {
  4130. SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
  4131. if (OnlyLoad)
  4132. PendingLoads.push_back(Chain);
  4133. else
  4134. DAG.setRoot(Chain);
  4135. }
  4136. if (!I.getType()->isVoidTy()) {
  4137. if (VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
  4138. EVT VT = TLI.getValueType(DAG.getDataLayout(), PTy);
  4139. Result = DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT, Result);
  4140. } else
  4141. Result = lowerRangeToAssertZExt(DAG, I, Result);
  4142. setValue(&I, Result);
  4143. }
  4144. }
  4145. /// GetSignificand - Get the significand and build it into a floating-point
  4146. /// number with exponent of 1:
  4147. ///
  4148. /// Op = (Op & 0x007fffff) | 0x3f800000;
  4149. ///
  4150. /// where Op is the hexadecimal representation of floating point value.
  4151. static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) {
  4152. SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
  4153. DAG.getConstant(0x007fffff, dl, MVT::i32));
  4154. SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
  4155. DAG.getConstant(0x3f800000, dl, MVT::i32));
  4156. return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2);
  4157. }
  4158. /// GetExponent - Get the exponent:
  4159. ///
  4160. /// (float)(int)(((Op & 0x7f800000) >> 23) - 127);
  4161. ///
  4162. /// where Op is the hexadecimal representation of floating point value.
  4163. static SDValue GetExponent(SelectionDAG &DAG, SDValue Op,
  4164. const TargetLowering &TLI, const SDLoc &dl) {
  4165. SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
  4166. DAG.getConstant(0x7f800000, dl, MVT::i32));
  4167. SDValue t1 = DAG.getNode(
  4168. ISD::SRL, dl, MVT::i32, t0,
  4169. DAG.getConstant(23, dl, TLI.getPointerTy(DAG.getDataLayout())));
  4170. SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
  4171. DAG.getConstant(127, dl, MVT::i32));
  4172. return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
  4173. }
  4174. /// getF32Constant - Get 32-bit floating point constant.
  4175. static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt,
  4176. const SDLoc &dl) {
  4177. return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl,
  4178. MVT::f32);
  4179. }
  4180. static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl,
  4181. SelectionDAG &DAG) {
  4182. // TODO: What fast-math-flags should be set on the floating-point nodes?
  4183. // IntegerPartOfX = ((int32_t)(t0);
  4184. SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
  4185. // FractionalPartOfX = t0 - (float)IntegerPartOfX;
  4186. SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
  4187. SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
  4188. // IntegerPartOfX <<= 23;
  4189. IntegerPartOfX = DAG.getNode(
  4190. ISD::SHL, dl, MVT::i32, IntegerPartOfX,
  4191. DAG.getConstant(23, dl, DAG.getTargetLoweringInfo().getPointerTy(
  4192. DAG.getDataLayout())));
  4193. SDValue TwoToFractionalPartOfX;
  4194. if (LimitFloatPrecision <= 6) {
  4195. // For floating-point precision of 6:
  4196. //
  4197. // TwoToFractionalPartOfX =
  4198. // 0.997535578f +
  4199. // (0.735607626f + 0.252464424f * x) * x;
  4200. //
  4201. // error 0.0144103317, which is 6 bits
  4202. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  4203. getF32Constant(DAG, 0x3e814304, dl));
  4204. SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
  4205. getF32Constant(DAG, 0x3f3c50c8, dl));
  4206. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  4207. TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  4208. getF32Constant(DAG, 0x3f7f5e7e, dl));
  4209. } else if (LimitFloatPrecision <= 12) {
  4210. // For floating-point precision of 12:
  4211. //
  4212. // TwoToFractionalPartOfX =
  4213. // 0.999892986f +
  4214. // (0.696457318f +
  4215. // (0.224338339f + 0.792043434e-1f * x) * x) * x;
  4216. //
  4217. // error 0.000107046256, which is 13 to 14 bits
  4218. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  4219. getF32Constant(DAG, 0x3da235e3, dl));
  4220. SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
  4221. getF32Constant(DAG, 0x3e65b8f3, dl));
  4222. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  4223. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  4224. getF32Constant(DAG, 0x3f324b07, dl));
  4225. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  4226. TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
  4227. getF32Constant(DAG, 0x3f7ff8fd, dl));
  4228. } else { // LimitFloatPrecision <= 18
  4229. // For floating-point precision of 18:
  4230. //
  4231. // TwoToFractionalPartOfX =
  4232. // 0.999999982f +
  4233. // (0.693148872f +
  4234. // (0.240227044f +
  4235. // (0.554906021e-1f +
  4236. // (0.961591928e-2f +
  4237. // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
  4238. // error 2.47208000*10^(-7), which is better than 18 bits
  4239. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  4240. getF32Constant(DAG, 0x3924b03e, dl));
  4241. SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
  4242. getF32Constant(DAG, 0x3ab24b87, dl));
  4243. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  4244. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  4245. getF32Constant(DAG, 0x3c1d8c17, dl));
  4246. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  4247. SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
  4248. getF32Constant(DAG, 0x3d634a1d, dl));
  4249. SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
  4250. SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
  4251. getF32Constant(DAG, 0x3e75fe14, dl));
  4252. SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
  4253. SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
  4254. getF32Constant(DAG, 0x3f317234, dl));
  4255. SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
  4256. TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
  4257. getF32Constant(DAG, 0x3f800000, dl));
  4258. }
  4259. // Add the exponent into the result in integer domain.
  4260. SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX);
  4261. return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
  4262. DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX));
  4263. }
  4264. /// expandExp - Lower an exp intrinsic. Handles the special sequences for
  4265. /// limited-precision mode.
  4266. static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
  4267. const TargetLowering &TLI) {
  4268. if (Op.getValueType() == MVT::f32 &&
  4269. LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
  4270. // Put the exponent in the right bit position for later addition to the
  4271. // final result:
  4272. //
  4273. // #define LOG2OFe 1.4426950f
  4274. // t0 = Op * LOG2OFe
  4275. // TODO: What fast-math-flags should be set here?
  4276. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
  4277. getF32Constant(DAG, 0x3fb8aa3b, dl));
  4278. return getLimitedPrecisionExp2(t0, dl, DAG);
  4279. }
  4280. // No special expansion.
  4281. return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op);
  4282. }
  4283. /// expandLog - Lower a log intrinsic. Handles the special sequences for
  4284. /// limited-precision mode.
  4285. static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
  4286. const TargetLowering &TLI) {
  4287. // TODO: What fast-math-flags should be set on the floating-point nodes?
  4288. if (Op.getValueType() == MVT::f32 &&
  4289. LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
  4290. SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
  4291. // Scale the exponent by log(2) [0.69314718f].
  4292. SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
  4293. SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
  4294. getF32Constant(DAG, 0x3f317218, dl));
  4295. // Get the significand and build it into a floating-point number with
  4296. // exponent of 1.
  4297. SDValue X = GetSignificand(DAG, Op1, dl);
  4298. SDValue LogOfMantissa;
  4299. if (LimitFloatPrecision <= 6) {
  4300. // For floating-point precision of 6:
  4301. //
  4302. // LogofMantissa =
  4303. // -1.1609546f +
  4304. // (1.4034025f - 0.23903021f * x) * x;
  4305. //
  4306. // error 0.0034276066, which is better than 8 bits
  4307. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  4308. getF32Constant(DAG, 0xbe74c456, dl));
  4309. SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
  4310. getF32Constant(DAG, 0x3fb3a2b1, dl));
  4311. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  4312. LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
  4313. getF32Constant(DAG, 0x3f949a29, dl));
  4314. } else if (LimitFloatPrecision <= 12) {
  4315. // For floating-point precision of 12:
  4316. //
  4317. // LogOfMantissa =
  4318. // -1.7417939f +
  4319. // (2.8212026f +
  4320. // (-1.4699568f +
  4321. // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
  4322. //
  4323. // error 0.000061011436, which is 14 bits
  4324. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  4325. getF32Constant(DAG, 0xbd67b6d6, dl));
  4326. SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
  4327. getF32Constant(DAG, 0x3ee4f4b8, dl));
  4328. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  4329. SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
  4330. getF32Constant(DAG, 0x3fbc278b, dl));
  4331. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  4332. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  4333. getF32Constant(DAG, 0x40348e95, dl));
  4334. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  4335. LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
  4336. getF32Constant(DAG, 0x3fdef31a, dl));
  4337. } else { // LimitFloatPrecision <= 18
  4338. // For floating-point precision of 18:
  4339. //
  4340. // LogOfMantissa =
  4341. // -2.1072184f +
  4342. // (4.2372794f +
  4343. // (-3.7029485f +
  4344. // (2.2781945f +
  4345. // (-0.87823314f +
  4346. // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
  4347. //
  4348. // error 0.0000023660568, which is better than 18 bits
  4349. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  4350. getF32Constant(DAG, 0xbc91e5ac, dl));
  4351. SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
  4352. getF32Constant(DAG, 0x3e4350aa, dl));
  4353. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  4354. SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
  4355. getF32Constant(DAG, 0x3f60d3e3, dl));
  4356. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  4357. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  4358. getF32Constant(DAG, 0x4011cdf0, dl));
  4359. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  4360. SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
  4361. getF32Constant(DAG, 0x406cfd1c, dl));
  4362. SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
  4363. SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
  4364. getF32Constant(DAG, 0x408797cb, dl));
  4365. SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
  4366. LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
  4367. getF32Constant(DAG, 0x4006dcab, dl));
  4368. }
  4369. return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa);
  4370. }
  4371. // No special expansion.
  4372. return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op);
  4373. }
  4374. /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for
  4375. /// limited-precision mode.
  4376. static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
  4377. const TargetLowering &TLI) {
  4378. // TODO: What fast-math-flags should be set on the floating-point nodes?
  4379. if (Op.getValueType() == MVT::f32 &&
  4380. LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
  4381. SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
  4382. // Get the exponent.
  4383. SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
  4384. // Get the significand and build it into a floating-point number with
  4385. // exponent of 1.
  4386. SDValue X = GetSignificand(DAG, Op1, dl);
  4387. // Different possible minimax approximations of significand in
  4388. // floating-point for various degrees of accuracy over [1,2].
  4389. SDValue Log2ofMantissa;
  4390. if (LimitFloatPrecision <= 6) {
  4391. // For floating-point precision of 6:
  4392. //
  4393. // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
  4394. //
  4395. // error 0.0049451742, which is more than 7 bits
  4396. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  4397. getF32Constant(DAG, 0xbeb08fe0, dl));
  4398. SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
  4399. getF32Constant(DAG, 0x40019463, dl));
  4400. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  4401. Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
  4402. getF32Constant(DAG, 0x3fd6633d, dl));
  4403. } else if (LimitFloatPrecision <= 12) {
  4404. // For floating-point precision of 12:
  4405. //
  4406. // Log2ofMantissa =
  4407. // -2.51285454f +
  4408. // (4.07009056f +
  4409. // (-2.12067489f +
  4410. // (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
  4411. //
  4412. // error 0.0000876136000, which is better than 13 bits
  4413. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  4414. getF32Constant(DAG, 0xbda7262e, dl));
  4415. SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
  4416. getF32Constant(DAG, 0x3f25280b, dl));
  4417. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  4418. SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
  4419. getF32Constant(DAG, 0x4007b923, dl));
  4420. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  4421. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  4422. getF32Constant(DAG, 0x40823e2f, dl));
  4423. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  4424. Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
  4425. getF32Constant(DAG, 0x4020d29c, dl));
  4426. } else { // LimitFloatPrecision <= 18
  4427. // For floating-point precision of 18:
  4428. //
  4429. // Log2ofMantissa =
  4430. // -3.0400495f +
  4431. // (6.1129976f +
  4432. // (-5.3420409f +
  4433. // (3.2865683f +
  4434. // (-1.2669343f +
  4435. // (0.27515199f -
  4436. // 0.25691327e-1f * x) * x) * x) * x) * x) * x;
  4437. //
  4438. // error 0.0000018516, which is better than 18 bits
  4439. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  4440. getF32Constant(DAG, 0xbcd2769e, dl));
  4441. SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
  4442. getF32Constant(DAG, 0x3e8ce0b9, dl));
  4443. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  4444. SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
  4445. getF32Constant(DAG, 0x3fa22ae7, dl));
  4446. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  4447. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  4448. getF32Constant(DAG, 0x40525723, dl));
  4449. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  4450. SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
  4451. getF32Constant(DAG, 0x40aaf200, dl));
  4452. SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
  4453. SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
  4454. getF32Constant(DAG, 0x40c39dad, dl));
  4455. SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
  4456. Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
  4457. getF32Constant(DAG, 0x4042902c, dl));
  4458. }
  4459. return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa);
  4460. }
  4461. // No special expansion.
  4462. return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op);
  4463. }
  4464. /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for
  4465. /// limited-precision mode.
  4466. static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
  4467. const TargetLowering &TLI) {
  4468. // TODO: What fast-math-flags should be set on the floating-point nodes?
  4469. if (Op.getValueType() == MVT::f32 &&
  4470. LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
  4471. SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
  4472. // Scale the exponent by log10(2) [0.30102999f].
  4473. SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
  4474. SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
  4475. getF32Constant(DAG, 0x3e9a209a, dl));
  4476. // Get the significand and build it into a floating-point number with
  4477. // exponent of 1.
  4478. SDValue X = GetSignificand(DAG, Op1, dl);
  4479. SDValue Log10ofMantissa;
  4480. if (LimitFloatPrecision <= 6) {
  4481. // For floating-point precision of 6:
  4482. //
  4483. // Log10ofMantissa =
  4484. // -0.50419619f +
  4485. // (0.60948995f - 0.10380950f * x) * x;
  4486. //
  4487. // error 0.0014886165, which is 6 bits
  4488. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  4489. getF32Constant(DAG, 0xbdd49a13, dl));
  4490. SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
  4491. getF32Constant(DAG, 0x3f1c0789, dl));
  4492. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  4493. Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
  4494. getF32Constant(DAG, 0x3f011300, dl));
  4495. } else if (LimitFloatPrecision <= 12) {
  4496. // For floating-point precision of 12:
  4497. //
  4498. // Log10ofMantissa =
  4499. // -0.64831180f +
  4500. // (0.91751397f +
  4501. // (-0.31664806f + 0.47637168e-1f * x) * x) * x;
  4502. //
  4503. // error 0.00019228036, which is better than 12 bits
  4504. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  4505. getF32Constant(DAG, 0x3d431f31, dl));
  4506. SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
  4507. getF32Constant(DAG, 0x3ea21fb2, dl));
  4508. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  4509. SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
  4510. getF32Constant(DAG, 0x3f6ae232, dl));
  4511. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  4512. Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
  4513. getF32Constant(DAG, 0x3f25f7c3, dl));
  4514. } else { // LimitFloatPrecision <= 18
  4515. // For floating-point precision of 18:
  4516. //
  4517. // Log10ofMantissa =
  4518. // -0.84299375f +
  4519. // (1.5327582f +
  4520. // (-1.0688956f +
  4521. // (0.49102474f +
  4522. // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
  4523. //
  4524. // error 0.0000037995730, which is better than 18 bits
  4525. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  4526. getF32Constant(DAG, 0x3c5d51ce, dl));
  4527. SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
  4528. getF32Constant(DAG, 0x3e00685a, dl));
  4529. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  4530. SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
  4531. getF32Constant(DAG, 0x3efb6798, dl));
  4532. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  4533. SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
  4534. getF32Constant(DAG, 0x3f88d192, dl));
  4535. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  4536. SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
  4537. getF32Constant(DAG, 0x3fc4316c, dl));
  4538. SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
  4539. Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
  4540. getF32Constant(DAG, 0x3f57ce70, dl));
  4541. }
  4542. return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa);
  4543. }
  4544. // No special expansion.
  4545. return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op);
  4546. }
  4547. /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for
  4548. /// limited-precision mode.
  4549. static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
  4550. const TargetLowering &TLI) {
  4551. if (Op.getValueType() == MVT::f32 &&
  4552. LimitFloatPrecision > 0 && LimitFloatPrecision <= 18)
  4553. return getLimitedPrecisionExp2(Op, dl, DAG);
  4554. // No special expansion.
  4555. return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op);
  4556. }
  4557. /// visitPow - Lower a pow intrinsic. Handles the special sequences for
  4558. /// limited-precision mode with x == 10.0f.
  4559. static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS,
  4560. SelectionDAG &DAG, const TargetLowering &TLI) {
  4561. bool IsExp10 = false;
  4562. if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 &&
  4563. LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
  4564. if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) {
  4565. APFloat Ten(10.0f);
  4566. IsExp10 = LHSC->isExactlyValue(Ten);
  4567. }
  4568. }
  4569. // TODO: What fast-math-flags should be set on the FMUL node?
  4570. if (IsExp10) {
  4571. // Put the exponent in the right bit position for later addition to the
  4572. // final result:
  4573. //
  4574. // #define LOG2OF10 3.3219281f
  4575. // t0 = Op * LOG2OF10;
  4576. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS,
  4577. getF32Constant(DAG, 0x40549a78, dl));
  4578. return getLimitedPrecisionExp2(t0, dl, DAG);
  4579. }
  4580. // No special expansion.
  4581. return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS);
  4582. }
  4583. /// ExpandPowI - Expand a llvm.powi intrinsic.
  4584. static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS,
  4585. SelectionDAG &DAG) {
  4586. // If RHS is a constant, we can expand this out to a multiplication tree,
  4587. // otherwise we end up lowering to a call to __powidf2 (for example). When
  4588. // optimizing for size, we only want to do this if the expansion would produce
  4589. // a small number of multiplies, otherwise we do the full expansion.
  4590. if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
  4591. // Get the exponent as a positive value.
  4592. unsigned Val = RHSC->getSExtValue();
  4593. if ((int)Val < 0) Val = -Val;
  4594. // powi(x, 0) -> 1.0
  4595. if (Val == 0)
  4596. return DAG.getConstantFP(1.0, DL, LHS.getValueType());
  4597. const Function &F = DAG.getMachineFunction().getFunction();
  4598. if (!F.hasOptSize() ||
  4599. // If optimizing for size, don't insert too many multiplies.
  4600. // This inserts up to 5 multiplies.
  4601. countPopulation(Val) + Log2_32(Val) < 7) {
  4602. // We use the simple binary decomposition method to generate the multiply
  4603. // sequence. There are more optimal ways to do this (for example,
  4604. // powi(x,15) generates one more multiply than it should), but this has
  4605. // the benefit of being both really simple and much better than a libcall.
  4606. SDValue Res; // Logically starts equal to 1.0
  4607. SDValue CurSquare = LHS;
  4608. // TODO: Intrinsics should have fast-math-flags that propagate to these
  4609. // nodes.
  4610. while (Val) {
  4611. if (Val & 1) {
  4612. if (Res.getNode())
  4613. Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare);
  4614. else
  4615. Res = CurSquare; // 1.0*CurSquare.
  4616. }
  4617. CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(),
  4618. CurSquare, CurSquare);
  4619. Val >>= 1;
  4620. }
  4621. // If the original was negative, invert the result, producing 1/(x*x*x).
  4622. if (RHSC->getSExtValue() < 0)
  4623. Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(),
  4624. DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res);
  4625. return Res;
  4626. }
  4627. }
  4628. // Otherwise, expand to a libcall.
  4629. return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS);
  4630. }
  4631. // getUnderlyingArgReg - Find underlying register used for a truncated or
  4632. // bitcasted argument.
  4633. static unsigned getUnderlyingArgReg(const SDValue &N) {
  4634. switch (N.getOpcode()) {
  4635. case ISD::CopyFromReg:
  4636. return cast<RegisterSDNode>(N.getOperand(1))->getReg();
  4637. case ISD::BITCAST:
  4638. case ISD::AssertZext:
  4639. case ISD::AssertSext:
  4640. case ISD::TRUNCATE:
  4641. return getUnderlyingArgReg(N.getOperand(0));
  4642. default:
  4643. return 0;
  4644. }
  4645. }
  4646. /// If the DbgValueInst is a dbg_value of a function argument, create the
  4647. /// corresponding DBG_VALUE machine instruction for it now. At the end of
  4648. /// instruction selection, they will be inserted to the entry BB.
  4649. bool SelectionDAGBuilder::EmitFuncArgumentDbgValue(
  4650. const Value *V, DILocalVariable *Variable, DIExpression *Expr,
  4651. DILocation *DL, bool IsDbgDeclare, const SDValue &N) {
  4652. const Argument *Arg = dyn_cast<Argument>(V);
  4653. if (!Arg)
  4654. return false;
  4655. if (!IsDbgDeclare) {
  4656. // ArgDbgValues are hoisted to the beginning of the entry block. So we
  4657. // should only emit as ArgDbgValue if the dbg.value intrinsic is found in
  4658. // the entry block.
  4659. bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front();
  4660. if (!IsInEntryBlock)
  4661. return false;
  4662. // ArgDbgValues are hoisted to the beginning of the entry block. So we
  4663. // should only emit as ArgDbgValue if the dbg.value intrinsic describes a
  4664. // variable that also is a param.
  4665. //
  4666. // Although, if we are at the top of the entry block already, we can still
  4667. // emit using ArgDbgValue. This might catch some situations when the
  4668. // dbg.value refers to an argument that isn't used in the entry block, so
  4669. // any CopyToReg node would be optimized out and the only way to express
  4670. // this DBG_VALUE is by using the physical reg (or FI) as done in this
  4671. // method. ArgDbgValues are hoisted to the beginning of the entry block. So
  4672. // we should only emit as ArgDbgValue if the Variable is an argument to the
  4673. // current function, and the dbg.value intrinsic is found in the entry
  4674. // block.
  4675. bool VariableIsFunctionInputArg = Variable->isParameter() &&
  4676. !DL->getInlinedAt();
  4677. bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder;
  4678. if (!IsInPrologue && !VariableIsFunctionInputArg)
  4679. return false;
  4680. // Here we assume that a function argument on IR level only can be used to
  4681. // describe one input parameter on source level. If we for example have
  4682. // source code like this
  4683. //
  4684. // struct A { long x, y; };
  4685. // void foo(struct A a, long b) {
  4686. // ...
  4687. // b = a.x;
  4688. // ...
  4689. // }
  4690. //
  4691. // and IR like this
  4692. //
  4693. // define void @foo(i32 %a1, i32 %a2, i32 %b) {
  4694. // entry:
  4695. // call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment
  4696. // call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment
  4697. // call void @llvm.dbg.value(metadata i32 %b, "b",
  4698. // ...
  4699. // call void @llvm.dbg.value(metadata i32 %a1, "b"
  4700. // ...
  4701. //
  4702. // then the last dbg.value is describing a parameter "b" using a value that
  4703. // is an argument. But since we already has used %a1 to describe a parameter
  4704. // we should not handle that last dbg.value here (that would result in an
  4705. // incorrect hoisting of the DBG_VALUE to the function entry).
  4706. // Notice that we allow one dbg.value per IR level argument, to accomodate
  4707. // for the situation with fragments above.
  4708. if (VariableIsFunctionInputArg) {
  4709. unsigned ArgNo = Arg->getArgNo();
  4710. if (ArgNo >= FuncInfo.DescribedArgs.size())
  4711. FuncInfo.DescribedArgs.resize(ArgNo + 1, false);
  4712. else if (!IsInPrologue && FuncInfo.DescribedArgs.test(ArgNo))
  4713. return false;
  4714. FuncInfo.DescribedArgs.set(ArgNo);
  4715. }
  4716. }
  4717. MachineFunction &MF = DAG.getMachineFunction();
  4718. const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
  4719. bool IsIndirect = false;
  4720. Optional<MachineOperand> Op;
  4721. // Some arguments' frame index is recorded during argument lowering.
  4722. int FI = FuncInfo.getArgumentFrameIndex(Arg);
  4723. if (FI != std::numeric_limits<int>::max())
  4724. Op = MachineOperand::CreateFI(FI);
  4725. if (!Op && N.getNode()) {
  4726. unsigned Reg = getUnderlyingArgReg(N);
  4727. if (Reg && TargetRegisterInfo::isVirtualRegister(Reg)) {
  4728. MachineRegisterInfo &RegInfo = MF.getRegInfo();
  4729. unsigned PR = RegInfo.getLiveInPhysReg(Reg);
  4730. if (PR)
  4731. Reg = PR;
  4732. }
  4733. if (Reg) {
  4734. Op = MachineOperand::CreateReg(Reg, false);
  4735. IsIndirect = IsDbgDeclare;
  4736. }
  4737. }
  4738. if (!Op && N.getNode()) {
  4739. // Check if frame index is available.
  4740. SDValue LCandidate = peekThroughBitcasts(N);
  4741. if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(LCandidate.getNode()))
  4742. if (FrameIndexSDNode *FINode =
  4743. dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
  4744. Op = MachineOperand::CreateFI(FINode->getIndex());
  4745. }
  4746. if (!Op) {
  4747. // Check if ValueMap has reg number.
  4748. DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
  4749. if (VMI != FuncInfo.ValueMap.end()) {
  4750. const auto &TLI = DAG.getTargetLoweringInfo();
  4751. RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second,
  4752. V->getType(), getABIRegCopyCC(V));
  4753. if (RFV.occupiesMultipleRegs()) {
  4754. unsigned Offset = 0;
  4755. for (auto RegAndSize : RFV.getRegsAndSizes()) {
  4756. Op = MachineOperand::CreateReg(RegAndSize.first, false);
  4757. auto FragmentExpr = DIExpression::createFragmentExpression(
  4758. Expr, Offset, RegAndSize.second);
  4759. if (!FragmentExpr)
  4760. continue;
  4761. FuncInfo.ArgDbgValues.push_back(
  4762. BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsDbgDeclare,
  4763. Op->getReg(), Variable, *FragmentExpr));
  4764. Offset += RegAndSize.second;
  4765. }
  4766. return true;
  4767. }
  4768. Op = MachineOperand::CreateReg(VMI->second, false);
  4769. IsIndirect = IsDbgDeclare;
  4770. }
  4771. }
  4772. if (!Op)
  4773. return false;
  4774. assert(Variable->isValidLocationForIntrinsic(DL) &&
  4775. "Expected inlined-at fields to agree");
  4776. IsIndirect = (Op->isReg()) ? IsIndirect : true;
  4777. FuncInfo.ArgDbgValues.push_back(
  4778. BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsIndirect,
  4779. *Op, Variable, Expr));
  4780. return true;
  4781. }
  4782. /// Return the appropriate SDDbgValue based on N.
  4783. SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N,
  4784. DILocalVariable *Variable,
  4785. DIExpression *Expr,
  4786. const DebugLoc &dl,
  4787. unsigned DbgSDNodeOrder) {
  4788. if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) {
  4789. // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe
  4790. // stack slot locations.
  4791. //
  4792. // Consider "int x = 0; int *px = &x;". There are two kinds of interesting
  4793. // debug values here after optimization:
  4794. //
  4795. // dbg.value(i32* %px, !"int *px", !DIExpression()), and
  4796. // dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref))
  4797. //
  4798. // Both describe the direct values of their associated variables.
  4799. return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(),
  4800. /*IsIndirect*/ false, dl, DbgSDNodeOrder);
  4801. }
  4802. return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(),
  4803. /*IsIndirect*/ false, dl, DbgSDNodeOrder);
  4804. }
  4805. // VisualStudio defines setjmp as _setjmp
  4806. #if defined(_MSC_VER) && defined(setjmp) && \
  4807. !defined(setjmp_undefined_for_msvc)
  4808. # pragma push_macro("setjmp")
  4809. # undef setjmp
  4810. # define setjmp_undefined_for_msvc
  4811. #endif
  4812. static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) {
  4813. switch (Intrinsic) {
  4814. case Intrinsic::smul_fix:
  4815. return ISD::SMULFIX;
  4816. case Intrinsic::umul_fix:
  4817. return ISD::UMULFIX;
  4818. default:
  4819. llvm_unreachable("Unhandled fixed point intrinsic");
  4820. }
  4821. }
  4822. void SelectionDAGBuilder::lowerCallToExternalSymbol(const CallInst &I,
  4823. const char *FunctionName) {
  4824. assert(FunctionName && "FunctionName must not be nullptr");
  4825. SDValue Callee = DAG.getExternalSymbol(
  4826. FunctionName,
  4827. DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()));
  4828. LowerCallTo(&I, Callee, I.isTailCall());
  4829. }
  4830. /// Lower the call to the specified intrinsic function.
  4831. void SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I,
  4832. unsigned Intrinsic) {
  4833. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  4834. SDLoc sdl = getCurSDLoc();
  4835. DebugLoc dl = getCurDebugLoc();
  4836. SDValue Res;
  4837. switch (Intrinsic) {
  4838. default:
  4839. // By default, turn this into a target intrinsic node.
  4840. visitTargetIntrinsic(I, Intrinsic);
  4841. return;
  4842. case Intrinsic::vastart: visitVAStart(I); return;
  4843. case Intrinsic::vaend: visitVAEnd(I); return;
  4844. case Intrinsic::vacopy: visitVACopy(I); return;
  4845. case Intrinsic::returnaddress:
  4846. setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl,
  4847. TLI.getPointerTy(DAG.getDataLayout()),
  4848. getValue(I.getArgOperand(0))));
  4849. return;
  4850. case Intrinsic::addressofreturnaddress:
  4851. setValue(&I, DAG.getNode(ISD::ADDROFRETURNADDR, sdl,
  4852. TLI.getPointerTy(DAG.getDataLayout())));
  4853. return;
  4854. case Intrinsic::sponentry:
  4855. setValue(&I, DAG.getNode(ISD::SPONENTRY, sdl,
  4856. TLI.getPointerTy(DAG.getDataLayout())));
  4857. return;
  4858. case Intrinsic::frameaddress:
  4859. setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl,
  4860. TLI.getPointerTy(DAG.getDataLayout()),
  4861. getValue(I.getArgOperand(0))));
  4862. return;
  4863. case Intrinsic::read_register: {
  4864. Value *Reg = I.getArgOperand(0);
  4865. SDValue Chain = getRoot();
  4866. SDValue RegName =
  4867. DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
  4868. EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  4869. Res = DAG.getNode(ISD::READ_REGISTER, sdl,
  4870. DAG.getVTList(VT, MVT::Other), Chain, RegName);
  4871. setValue(&I, Res);
  4872. DAG.setRoot(Res.getValue(1));
  4873. return;
  4874. }
  4875. case Intrinsic::write_register: {
  4876. Value *Reg = I.getArgOperand(0);
  4877. Value *RegValue = I.getArgOperand(1);
  4878. SDValue Chain = getRoot();
  4879. SDValue RegName =
  4880. DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
  4881. DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain,
  4882. RegName, getValue(RegValue)));
  4883. return;
  4884. }
  4885. case Intrinsic::setjmp:
  4886. lowerCallToExternalSymbol(I, &"_setjmp"[!TLI.usesUnderscoreSetJmp()]);
  4887. return;
  4888. case Intrinsic::longjmp:
  4889. lowerCallToExternalSymbol(I, &"_longjmp"[!TLI.usesUnderscoreLongJmp()]);
  4890. return;
  4891. case Intrinsic::memcpy: {
  4892. const auto &MCI = cast<MemCpyInst>(I);
  4893. SDValue Op1 = getValue(I.getArgOperand(0));
  4894. SDValue Op2 = getValue(I.getArgOperand(1));
  4895. SDValue Op3 = getValue(I.getArgOperand(2));
  4896. // @llvm.memcpy defines 0 and 1 to both mean no alignment.
  4897. unsigned DstAlign = std::max<unsigned>(MCI.getDestAlignment(), 1);
  4898. unsigned SrcAlign = std::max<unsigned>(MCI.getSourceAlignment(), 1);
  4899. unsigned Align = MinAlign(DstAlign, SrcAlign);
  4900. bool isVol = MCI.isVolatile();
  4901. bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
  4902. // FIXME: Support passing different dest/src alignments to the memcpy DAG
  4903. // node.
  4904. SDValue MC = DAG.getMemcpy(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
  4905. false, isTC,
  4906. MachinePointerInfo(I.getArgOperand(0)),
  4907. MachinePointerInfo(I.getArgOperand(1)));
  4908. updateDAGForMaybeTailCall(MC);
  4909. return;
  4910. }
  4911. case Intrinsic::memset: {
  4912. const auto &MSI = cast<MemSetInst>(I);
  4913. SDValue Op1 = getValue(I.getArgOperand(0));
  4914. SDValue Op2 = getValue(I.getArgOperand(1));
  4915. SDValue Op3 = getValue(I.getArgOperand(2));
  4916. // @llvm.memset defines 0 and 1 to both mean no alignment.
  4917. unsigned Align = std::max<unsigned>(MSI.getDestAlignment(), 1);
  4918. bool isVol = MSI.isVolatile();
  4919. bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
  4920. SDValue MS = DAG.getMemset(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
  4921. isTC, MachinePointerInfo(I.getArgOperand(0)));
  4922. updateDAGForMaybeTailCall(MS);
  4923. return;
  4924. }
  4925. case Intrinsic::memmove: {
  4926. const auto &MMI = cast<MemMoveInst>(I);
  4927. SDValue Op1 = getValue(I.getArgOperand(0));
  4928. SDValue Op2 = getValue(I.getArgOperand(1));
  4929. SDValue Op3 = getValue(I.getArgOperand(2));
  4930. // @llvm.memmove defines 0 and 1 to both mean no alignment.
  4931. unsigned DstAlign = std::max<unsigned>(MMI.getDestAlignment(), 1);
  4932. unsigned SrcAlign = std::max<unsigned>(MMI.getSourceAlignment(), 1);
  4933. unsigned Align = MinAlign(DstAlign, SrcAlign);
  4934. bool isVol = MMI.isVolatile();
  4935. bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
  4936. // FIXME: Support passing different dest/src alignments to the memmove DAG
  4937. // node.
  4938. SDValue MM = DAG.getMemmove(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
  4939. isTC, MachinePointerInfo(I.getArgOperand(0)),
  4940. MachinePointerInfo(I.getArgOperand(1)));
  4941. updateDAGForMaybeTailCall(MM);
  4942. return;
  4943. }
  4944. case Intrinsic::memcpy_element_unordered_atomic: {
  4945. const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I);
  4946. SDValue Dst = getValue(MI.getRawDest());
  4947. SDValue Src = getValue(MI.getRawSource());
  4948. SDValue Length = getValue(MI.getLength());
  4949. unsigned DstAlign = MI.getDestAlignment();
  4950. unsigned SrcAlign = MI.getSourceAlignment();
  4951. Type *LengthTy = MI.getLength()->getType();
  4952. unsigned ElemSz = MI.getElementSizeInBytes();
  4953. bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
  4954. SDValue MC = DAG.getAtomicMemcpy(getRoot(), sdl, Dst, DstAlign, Src,
  4955. SrcAlign, Length, LengthTy, ElemSz, isTC,
  4956. MachinePointerInfo(MI.getRawDest()),
  4957. MachinePointerInfo(MI.getRawSource()));
  4958. updateDAGForMaybeTailCall(MC);
  4959. return;
  4960. }
  4961. case Intrinsic::memmove_element_unordered_atomic: {
  4962. auto &MI = cast<AtomicMemMoveInst>(I);
  4963. SDValue Dst = getValue(MI.getRawDest());
  4964. SDValue Src = getValue(MI.getRawSource());
  4965. SDValue Length = getValue(MI.getLength());
  4966. unsigned DstAlign = MI.getDestAlignment();
  4967. unsigned SrcAlign = MI.getSourceAlignment();
  4968. Type *LengthTy = MI.getLength()->getType();
  4969. unsigned ElemSz = MI.getElementSizeInBytes();
  4970. bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
  4971. SDValue MC = DAG.getAtomicMemmove(getRoot(), sdl, Dst, DstAlign, Src,
  4972. SrcAlign, Length, LengthTy, ElemSz, isTC,
  4973. MachinePointerInfo(MI.getRawDest()),
  4974. MachinePointerInfo(MI.getRawSource()));
  4975. updateDAGForMaybeTailCall(MC);
  4976. return;
  4977. }
  4978. case Intrinsic::memset_element_unordered_atomic: {
  4979. auto &MI = cast<AtomicMemSetInst>(I);
  4980. SDValue Dst = getValue(MI.getRawDest());
  4981. SDValue Val = getValue(MI.getValue());
  4982. SDValue Length = getValue(MI.getLength());
  4983. unsigned DstAlign = MI.getDestAlignment();
  4984. Type *LengthTy = MI.getLength()->getType();
  4985. unsigned ElemSz = MI.getElementSizeInBytes();
  4986. bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
  4987. SDValue MC = DAG.getAtomicMemset(getRoot(), sdl, Dst, DstAlign, Val, Length,
  4988. LengthTy, ElemSz, isTC,
  4989. MachinePointerInfo(MI.getRawDest()));
  4990. updateDAGForMaybeTailCall(MC);
  4991. return;
  4992. }
  4993. case Intrinsic::dbg_addr:
  4994. case Intrinsic::dbg_declare: {
  4995. const auto &DI = cast<DbgVariableIntrinsic>(I);
  4996. DILocalVariable *Variable = DI.getVariable();
  4997. DIExpression *Expression = DI.getExpression();
  4998. dropDanglingDebugInfo(Variable, Expression);
  4999. assert(Variable && "Missing variable");
  5000. // Check if address has undef value.
  5001. const Value *Address = DI.getVariableLocation();
  5002. if (!Address || isa<UndefValue>(Address) ||
  5003. (Address->use_empty() && !isa<Argument>(Address))) {
  5004. LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
  5005. return;
  5006. }
  5007. bool isParameter = Variable->isParameter() || isa<Argument>(Address);
  5008. // Check if this variable can be described by a frame index, typically
  5009. // either as a static alloca or a byval parameter.
  5010. int FI = std::numeric_limits<int>::max();
  5011. if (const auto *AI =
  5012. dyn_cast<AllocaInst>(Address->stripInBoundsConstantOffsets())) {
  5013. if (AI->isStaticAlloca()) {
  5014. auto I = FuncInfo.StaticAllocaMap.find(AI);
  5015. if (I != FuncInfo.StaticAllocaMap.end())
  5016. FI = I->second;
  5017. }
  5018. } else if (const auto *Arg = dyn_cast<Argument>(
  5019. Address->stripInBoundsConstantOffsets())) {
  5020. FI = FuncInfo.getArgumentFrameIndex(Arg);
  5021. }
  5022. // llvm.dbg.addr is control dependent and always generates indirect
  5023. // DBG_VALUE instructions. llvm.dbg.declare is handled as a frame index in
  5024. // the MachineFunction variable table.
  5025. if (FI != std::numeric_limits<int>::max()) {
  5026. if (Intrinsic == Intrinsic::dbg_addr) {
  5027. SDDbgValue *SDV = DAG.getFrameIndexDbgValue(
  5028. Variable, Expression, FI, /*IsIndirect*/ true, dl, SDNodeOrder);
  5029. DAG.AddDbgValue(SDV, getRoot().getNode(), isParameter);
  5030. }
  5031. return;
  5032. }
  5033. SDValue &N = NodeMap[Address];
  5034. if (!N.getNode() && isa<Argument>(Address))
  5035. // Check unused arguments map.
  5036. N = UnusedArgNodeMap[Address];
  5037. SDDbgValue *SDV;
  5038. if (N.getNode()) {
  5039. if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
  5040. Address = BCI->getOperand(0);
  5041. // Parameters are handled specially.
  5042. auto FINode = dyn_cast<FrameIndexSDNode>(N.getNode());
  5043. if (isParameter && FINode) {
  5044. // Byval parameter. We have a frame index at this point.
  5045. SDV =
  5046. DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(),
  5047. /*IsIndirect*/ true, dl, SDNodeOrder);
  5048. } else if (isa<Argument>(Address)) {
  5049. // Address is an argument, so try to emit its dbg value using
  5050. // virtual register info from the FuncInfo.ValueMap.
  5051. EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, N);
  5052. return;
  5053. } else {
  5054. SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(),
  5055. true, dl, SDNodeOrder);
  5056. }
  5057. DAG.AddDbgValue(SDV, N.getNode(), isParameter);
  5058. } else {
  5059. // If Address is an argument then try to emit its dbg value using
  5060. // virtual register info from the FuncInfo.ValueMap.
  5061. if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true,
  5062. N)) {
  5063. LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
  5064. }
  5065. }
  5066. return;
  5067. }
  5068. case Intrinsic::dbg_label: {
  5069. const DbgLabelInst &DI = cast<DbgLabelInst>(I);
  5070. DILabel *Label = DI.getLabel();
  5071. assert(Label && "Missing label");
  5072. SDDbgLabel *SDV;
  5073. SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder);
  5074. DAG.AddDbgLabel(SDV);
  5075. return;
  5076. }
  5077. case Intrinsic::dbg_value: {
  5078. const DbgValueInst &DI = cast<DbgValueInst>(I);
  5079. assert(DI.getVariable() && "Missing variable");
  5080. DILocalVariable *Variable = DI.getVariable();
  5081. DIExpression *Expression = DI.getExpression();
  5082. dropDanglingDebugInfo(Variable, Expression);
  5083. const Value *V = DI.getValue();
  5084. if (!V)
  5085. return;
  5086. if (handleDebugValue(V, Variable, Expression, dl, DI.getDebugLoc(),
  5087. SDNodeOrder))
  5088. return;
  5089. // TODO: Dangling debug info will eventually either be resolved or produce
  5090. // an Undef DBG_VALUE. However in the resolution case, a gap may appear
  5091. // between the original dbg.value location and its resolved DBG_VALUE, which
  5092. // we should ideally fill with an extra Undef DBG_VALUE.
  5093. DanglingDebugInfoMap[V].emplace_back(&DI, dl, SDNodeOrder);
  5094. return;
  5095. }
  5096. case Intrinsic::eh_typeid_for: {
  5097. // Find the type id for the given typeinfo.
  5098. GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0));
  5099. unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV);
  5100. Res = DAG.getConstant(TypeID, sdl, MVT::i32);
  5101. setValue(&I, Res);
  5102. return;
  5103. }
  5104. case Intrinsic::eh_return_i32:
  5105. case Intrinsic::eh_return_i64:
  5106. DAG.getMachineFunction().setCallsEHReturn(true);
  5107. DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl,
  5108. MVT::Other,
  5109. getControlRoot(),
  5110. getValue(I.getArgOperand(0)),
  5111. getValue(I.getArgOperand(1))));
  5112. return;
  5113. case Intrinsic::eh_unwind_init:
  5114. DAG.getMachineFunction().setCallsUnwindInit(true);
  5115. return;
  5116. case Intrinsic::eh_dwarf_cfa:
  5117. setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl,
  5118. TLI.getPointerTy(DAG.getDataLayout()),
  5119. getValue(I.getArgOperand(0))));
  5120. return;
  5121. case Intrinsic::eh_sjlj_callsite: {
  5122. MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
  5123. ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0));
  5124. assert(CI && "Non-constant call site value in eh.sjlj.callsite!");
  5125. assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!");
  5126. MMI.setCurrentCallSite(CI->getZExtValue());
  5127. return;
  5128. }
  5129. case Intrinsic::eh_sjlj_functioncontext: {
  5130. // Get and store the index of the function context.
  5131. MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
  5132. AllocaInst *FnCtx =
  5133. cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts());
  5134. int FI = FuncInfo.StaticAllocaMap[FnCtx];
  5135. MFI.setFunctionContextIndex(FI);
  5136. return;
  5137. }
  5138. case Intrinsic::eh_sjlj_setjmp: {
  5139. SDValue Ops[2];
  5140. Ops[0] = getRoot();
  5141. Ops[1] = getValue(I.getArgOperand(0));
  5142. SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl,
  5143. DAG.getVTList(MVT::i32, MVT::Other), Ops);
  5144. setValue(&I, Op.getValue(0));
  5145. DAG.setRoot(Op.getValue(1));
  5146. return;
  5147. }
  5148. case Intrinsic::eh_sjlj_longjmp:
  5149. DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other,
  5150. getRoot(), getValue(I.getArgOperand(0))));
  5151. return;
  5152. case Intrinsic::eh_sjlj_setup_dispatch:
  5153. DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other,
  5154. getRoot()));
  5155. return;
  5156. case Intrinsic::masked_gather:
  5157. visitMaskedGather(I);
  5158. return;
  5159. case Intrinsic::masked_load:
  5160. visitMaskedLoad(I);
  5161. return;
  5162. case Intrinsic::masked_scatter:
  5163. visitMaskedScatter(I);
  5164. return;
  5165. case Intrinsic::masked_store:
  5166. visitMaskedStore(I);
  5167. return;
  5168. case Intrinsic::masked_expandload:
  5169. visitMaskedLoad(I, true /* IsExpanding */);
  5170. return;
  5171. case Intrinsic::masked_compressstore:
  5172. visitMaskedStore(I, true /* IsCompressing */);
  5173. return;
  5174. case Intrinsic::x86_mmx_pslli_w:
  5175. case Intrinsic::x86_mmx_pslli_d:
  5176. case Intrinsic::x86_mmx_pslli_q:
  5177. case Intrinsic::x86_mmx_psrli_w:
  5178. case Intrinsic::x86_mmx_psrli_d:
  5179. case Intrinsic::x86_mmx_psrli_q:
  5180. case Intrinsic::x86_mmx_psrai_w:
  5181. case Intrinsic::x86_mmx_psrai_d: {
  5182. SDValue ShAmt = getValue(I.getArgOperand(1));
  5183. if (isa<ConstantSDNode>(ShAmt)) {
  5184. visitTargetIntrinsic(I, Intrinsic);
  5185. return;
  5186. }
  5187. unsigned NewIntrinsic = 0;
  5188. EVT ShAmtVT = MVT::v2i32;
  5189. switch (Intrinsic) {
  5190. case Intrinsic::x86_mmx_pslli_w:
  5191. NewIntrinsic = Intrinsic::x86_mmx_psll_w;
  5192. break;
  5193. case Intrinsic::x86_mmx_pslli_d:
  5194. NewIntrinsic = Intrinsic::x86_mmx_psll_d;
  5195. break;
  5196. case Intrinsic::x86_mmx_pslli_q:
  5197. NewIntrinsic = Intrinsic::x86_mmx_psll_q;
  5198. break;
  5199. case Intrinsic::x86_mmx_psrli_w:
  5200. NewIntrinsic = Intrinsic::x86_mmx_psrl_w;
  5201. break;
  5202. case Intrinsic::x86_mmx_psrli_d:
  5203. NewIntrinsic = Intrinsic::x86_mmx_psrl_d;
  5204. break;
  5205. case Intrinsic::x86_mmx_psrli_q:
  5206. NewIntrinsic = Intrinsic::x86_mmx_psrl_q;
  5207. break;
  5208. case Intrinsic::x86_mmx_psrai_w:
  5209. NewIntrinsic = Intrinsic::x86_mmx_psra_w;
  5210. break;
  5211. case Intrinsic::x86_mmx_psrai_d:
  5212. NewIntrinsic = Intrinsic::x86_mmx_psra_d;
  5213. break;
  5214. default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
  5215. }
  5216. // The vector shift intrinsics with scalars uses 32b shift amounts but
  5217. // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
  5218. // to be zero.
  5219. // We must do this early because v2i32 is not a legal type.
  5220. SDValue ShOps[2];
  5221. ShOps[0] = ShAmt;
  5222. ShOps[1] = DAG.getConstant(0, sdl, MVT::i32);
  5223. ShAmt = DAG.getBuildVector(ShAmtVT, sdl, ShOps);
  5224. EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  5225. ShAmt = DAG.getNode(ISD::BITCAST, sdl, DestVT, ShAmt);
  5226. Res = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, sdl, DestVT,
  5227. DAG.getConstant(NewIntrinsic, sdl, MVT::i32),
  5228. getValue(I.getArgOperand(0)), ShAmt);
  5229. setValue(&I, Res);
  5230. return;
  5231. }
  5232. case Intrinsic::powi:
  5233. setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)),
  5234. getValue(I.getArgOperand(1)), DAG));
  5235. return;
  5236. case Intrinsic::log:
  5237. setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
  5238. return;
  5239. case Intrinsic::log2:
  5240. setValue(&I, expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
  5241. return;
  5242. case Intrinsic::log10:
  5243. setValue(&I, expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
  5244. return;
  5245. case Intrinsic::exp:
  5246. setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
  5247. return;
  5248. case Intrinsic::exp2:
  5249. setValue(&I, expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
  5250. return;
  5251. case Intrinsic::pow:
  5252. setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)),
  5253. getValue(I.getArgOperand(1)), DAG, TLI));
  5254. return;
  5255. case Intrinsic::sqrt:
  5256. case Intrinsic::fabs:
  5257. case Intrinsic::sin:
  5258. case Intrinsic::cos:
  5259. case Intrinsic::floor:
  5260. case Intrinsic::ceil:
  5261. case Intrinsic::trunc:
  5262. case Intrinsic::rint:
  5263. case Intrinsic::nearbyint:
  5264. case Intrinsic::round:
  5265. case Intrinsic::canonicalize: {
  5266. unsigned Opcode;
  5267. switch (Intrinsic) {
  5268. default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
  5269. case Intrinsic::sqrt: Opcode = ISD::FSQRT; break;
  5270. case Intrinsic::fabs: Opcode = ISD::FABS; break;
  5271. case Intrinsic::sin: Opcode = ISD::FSIN; break;
  5272. case Intrinsic::cos: Opcode = ISD::FCOS; break;
  5273. case Intrinsic::floor: Opcode = ISD::FFLOOR; break;
  5274. case Intrinsic::ceil: Opcode = ISD::FCEIL; break;
  5275. case Intrinsic::trunc: Opcode = ISD::FTRUNC; break;
  5276. case Intrinsic::rint: Opcode = ISD::FRINT; break;
  5277. case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break;
  5278. case Intrinsic::round: Opcode = ISD::FROUND; break;
  5279. case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break;
  5280. }
  5281. setValue(&I, DAG.getNode(Opcode, sdl,
  5282. getValue(I.getArgOperand(0)).getValueType(),
  5283. getValue(I.getArgOperand(0))));
  5284. return;
  5285. }
  5286. case Intrinsic::lround:
  5287. case Intrinsic::llround:
  5288. case Intrinsic::lrint:
  5289. case Intrinsic::llrint: {
  5290. unsigned Opcode;
  5291. switch (Intrinsic) {
  5292. default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
  5293. case Intrinsic::lround: Opcode = ISD::LROUND; break;
  5294. case Intrinsic::llround: Opcode = ISD::LLROUND; break;
  5295. case Intrinsic::lrint: Opcode = ISD::LRINT; break;
  5296. case Intrinsic::llrint: Opcode = ISD::LLRINT; break;
  5297. }
  5298. EVT RetVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  5299. setValue(&I, DAG.getNode(Opcode, sdl, RetVT,
  5300. getValue(I.getArgOperand(0))));
  5301. return;
  5302. }
  5303. case Intrinsic::minnum: {
  5304. auto VT = getValue(I.getArgOperand(0)).getValueType();
  5305. unsigned Opc =
  5306. I.hasNoNaNs() && TLI.isOperationLegalOrCustom(ISD::FMINIMUM, VT)
  5307. ? ISD::FMINIMUM
  5308. : ISD::FMINNUM;
  5309. setValue(&I, DAG.getNode(Opc, sdl, VT,
  5310. getValue(I.getArgOperand(0)),
  5311. getValue(I.getArgOperand(1))));
  5312. return;
  5313. }
  5314. case Intrinsic::maxnum: {
  5315. auto VT = getValue(I.getArgOperand(0)).getValueType();
  5316. unsigned Opc =
  5317. I.hasNoNaNs() && TLI.isOperationLegalOrCustom(ISD::FMAXIMUM, VT)
  5318. ? ISD::FMAXIMUM
  5319. : ISD::FMAXNUM;
  5320. setValue(&I, DAG.getNode(Opc, sdl, VT,
  5321. getValue(I.getArgOperand(0)),
  5322. getValue(I.getArgOperand(1))));
  5323. return;
  5324. }
  5325. case Intrinsic::minimum:
  5326. setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl,
  5327. getValue(I.getArgOperand(0)).getValueType(),
  5328. getValue(I.getArgOperand(0)),
  5329. getValue(I.getArgOperand(1))));
  5330. return;
  5331. case Intrinsic::maximum:
  5332. setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl,
  5333. getValue(I.getArgOperand(0)).getValueType(),
  5334. getValue(I.getArgOperand(0)),
  5335. getValue(I.getArgOperand(1))));
  5336. return;
  5337. case Intrinsic::copysign:
  5338. setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl,
  5339. getValue(I.getArgOperand(0)).getValueType(),
  5340. getValue(I.getArgOperand(0)),
  5341. getValue(I.getArgOperand(1))));
  5342. return;
  5343. case Intrinsic::fma:
  5344. setValue(&I, DAG.getNode(ISD::FMA, sdl,
  5345. getValue(I.getArgOperand(0)).getValueType(),
  5346. getValue(I.getArgOperand(0)),
  5347. getValue(I.getArgOperand(1)),
  5348. getValue(I.getArgOperand(2))));
  5349. return;
  5350. case Intrinsic::experimental_constrained_fadd:
  5351. case Intrinsic::experimental_constrained_fsub:
  5352. case Intrinsic::experimental_constrained_fmul:
  5353. case Intrinsic::experimental_constrained_fdiv:
  5354. case Intrinsic::experimental_constrained_frem:
  5355. case Intrinsic::experimental_constrained_fma:
  5356. case Intrinsic::experimental_constrained_fptrunc:
  5357. case Intrinsic::experimental_constrained_fpext:
  5358. case Intrinsic::experimental_constrained_sqrt:
  5359. case Intrinsic::experimental_constrained_pow:
  5360. case Intrinsic::experimental_constrained_powi:
  5361. case Intrinsic::experimental_constrained_sin:
  5362. case Intrinsic::experimental_constrained_cos:
  5363. case Intrinsic::experimental_constrained_exp:
  5364. case Intrinsic::experimental_constrained_exp2:
  5365. case Intrinsic::experimental_constrained_log:
  5366. case Intrinsic::experimental_constrained_log10:
  5367. case Intrinsic::experimental_constrained_log2:
  5368. case Intrinsic::experimental_constrained_rint:
  5369. case Intrinsic::experimental_constrained_nearbyint:
  5370. case Intrinsic::experimental_constrained_maxnum:
  5371. case Intrinsic::experimental_constrained_minnum:
  5372. case Intrinsic::experimental_constrained_ceil:
  5373. case Intrinsic::experimental_constrained_floor:
  5374. case Intrinsic::experimental_constrained_round:
  5375. case Intrinsic::experimental_constrained_trunc:
  5376. visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I));
  5377. return;
  5378. case Intrinsic::fmuladd: {
  5379. EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  5380. if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
  5381. TLI.isFMAFasterThanFMulAndFAdd(VT)) {
  5382. setValue(&I, DAG.getNode(ISD::FMA, sdl,
  5383. getValue(I.getArgOperand(0)).getValueType(),
  5384. getValue(I.getArgOperand(0)),
  5385. getValue(I.getArgOperand(1)),
  5386. getValue(I.getArgOperand(2))));
  5387. } else {
  5388. // TODO: Intrinsic calls should have fast-math-flags.
  5389. SDValue Mul = DAG.getNode(ISD::FMUL, sdl,
  5390. getValue(I.getArgOperand(0)).getValueType(),
  5391. getValue(I.getArgOperand(0)),
  5392. getValue(I.getArgOperand(1)));
  5393. SDValue Add = DAG.getNode(ISD::FADD, sdl,
  5394. getValue(I.getArgOperand(0)).getValueType(),
  5395. Mul,
  5396. getValue(I.getArgOperand(2)));
  5397. setValue(&I, Add);
  5398. }
  5399. return;
  5400. }
  5401. case Intrinsic::convert_to_fp16:
  5402. setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16,
  5403. DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16,
  5404. getValue(I.getArgOperand(0)),
  5405. DAG.getTargetConstant(0, sdl,
  5406. MVT::i32))));
  5407. return;
  5408. case Intrinsic::convert_from_fp16:
  5409. setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl,
  5410. TLI.getValueType(DAG.getDataLayout(), I.getType()),
  5411. DAG.getNode(ISD::BITCAST, sdl, MVT::f16,
  5412. getValue(I.getArgOperand(0)))));
  5413. return;
  5414. case Intrinsic::pcmarker: {
  5415. SDValue Tmp = getValue(I.getArgOperand(0));
  5416. DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp));
  5417. return;
  5418. }
  5419. case Intrinsic::readcyclecounter: {
  5420. SDValue Op = getRoot();
  5421. Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl,
  5422. DAG.getVTList(MVT::i64, MVT::Other), Op);
  5423. setValue(&I, Res);
  5424. DAG.setRoot(Res.getValue(1));
  5425. return;
  5426. }
  5427. case Intrinsic::bitreverse:
  5428. setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl,
  5429. getValue(I.getArgOperand(0)).getValueType(),
  5430. getValue(I.getArgOperand(0))));
  5431. return;
  5432. case Intrinsic::bswap:
  5433. setValue(&I, DAG.getNode(ISD::BSWAP, sdl,
  5434. getValue(I.getArgOperand(0)).getValueType(),
  5435. getValue(I.getArgOperand(0))));
  5436. return;
  5437. case Intrinsic::cttz: {
  5438. SDValue Arg = getValue(I.getArgOperand(0));
  5439. ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
  5440. EVT Ty = Arg.getValueType();
  5441. setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF,
  5442. sdl, Ty, Arg));
  5443. return;
  5444. }
  5445. case Intrinsic::ctlz: {
  5446. SDValue Arg = getValue(I.getArgOperand(0));
  5447. ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
  5448. EVT Ty = Arg.getValueType();
  5449. setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF,
  5450. sdl, Ty, Arg));
  5451. return;
  5452. }
  5453. case Intrinsic::ctpop: {
  5454. SDValue Arg = getValue(I.getArgOperand(0));
  5455. EVT Ty = Arg.getValueType();
  5456. setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg));
  5457. return;
  5458. }
  5459. case Intrinsic::fshl:
  5460. case Intrinsic::fshr: {
  5461. bool IsFSHL = Intrinsic == Intrinsic::fshl;
  5462. SDValue X = getValue(I.getArgOperand(0));
  5463. SDValue Y = getValue(I.getArgOperand(1));
  5464. SDValue Z = getValue(I.getArgOperand(2));
  5465. EVT VT = X.getValueType();
  5466. SDValue BitWidthC = DAG.getConstant(VT.getScalarSizeInBits(), sdl, VT);
  5467. SDValue Zero = DAG.getConstant(0, sdl, VT);
  5468. SDValue ShAmt = DAG.getNode(ISD::UREM, sdl, VT, Z, BitWidthC);
  5469. auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR;
  5470. if (TLI.isOperationLegalOrCustom(FunnelOpcode, VT)) {
  5471. setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z));
  5472. return;
  5473. }
  5474. // When X == Y, this is rotate. If the data type has a power-of-2 size, we
  5475. // avoid the select that is necessary in the general case to filter out
  5476. // the 0-shift possibility that leads to UB.
  5477. if (X == Y && isPowerOf2_32(VT.getScalarSizeInBits())) {
  5478. auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR;
  5479. if (TLI.isOperationLegalOrCustom(RotateOpcode, VT)) {
  5480. setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z));
  5481. return;
  5482. }
  5483. // Some targets only rotate one way. Try the opposite direction.
  5484. RotateOpcode = IsFSHL ? ISD::ROTR : ISD::ROTL;
  5485. if (TLI.isOperationLegalOrCustom(RotateOpcode, VT)) {
  5486. // Negate the shift amount because it is safe to ignore the high bits.
  5487. SDValue NegShAmt = DAG.getNode(ISD::SUB, sdl, VT, Zero, Z);
  5488. setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, NegShAmt));
  5489. return;
  5490. }
  5491. // fshl (rotl): (X << (Z % BW)) | (X >> ((0 - Z) % BW))
  5492. // fshr (rotr): (X << ((0 - Z) % BW)) | (X >> (Z % BW))
  5493. SDValue NegZ = DAG.getNode(ISD::SUB, sdl, VT, Zero, Z);
  5494. SDValue NShAmt = DAG.getNode(ISD::UREM, sdl, VT, NegZ, BitWidthC);
  5495. SDValue ShX = DAG.getNode(ISD::SHL, sdl, VT, X, IsFSHL ? ShAmt : NShAmt);
  5496. SDValue ShY = DAG.getNode(ISD::SRL, sdl, VT, X, IsFSHL ? NShAmt : ShAmt);
  5497. setValue(&I, DAG.getNode(ISD::OR, sdl, VT, ShX, ShY));
  5498. return;
  5499. }
  5500. // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW)))
  5501. // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW))
  5502. SDValue InvShAmt = DAG.getNode(ISD::SUB, sdl, VT, BitWidthC, ShAmt);
  5503. SDValue ShX = DAG.getNode(ISD::SHL, sdl, VT, X, IsFSHL ? ShAmt : InvShAmt);
  5504. SDValue ShY = DAG.getNode(ISD::SRL, sdl, VT, Y, IsFSHL ? InvShAmt : ShAmt);
  5505. SDValue Or = DAG.getNode(ISD::OR, sdl, VT, ShX, ShY);
  5506. // If (Z % BW == 0), then the opposite direction shift is shift-by-bitwidth,
  5507. // and that is undefined. We must compare and select to avoid UB.
  5508. EVT CCVT = MVT::i1;
  5509. if (VT.isVector())
  5510. CCVT = EVT::getVectorVT(*Context, CCVT, VT.getVectorNumElements());
  5511. // For fshl, 0-shift returns the 1st arg (X).
  5512. // For fshr, 0-shift returns the 2nd arg (Y).
  5513. SDValue IsZeroShift = DAG.getSetCC(sdl, CCVT, ShAmt, Zero, ISD::SETEQ);
  5514. setValue(&I, DAG.getSelect(sdl, VT, IsZeroShift, IsFSHL ? X : Y, Or));
  5515. return;
  5516. }
  5517. case Intrinsic::sadd_sat: {
  5518. SDValue Op1 = getValue(I.getArgOperand(0));
  5519. SDValue Op2 = getValue(I.getArgOperand(1));
  5520. setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2));
  5521. return;
  5522. }
  5523. case Intrinsic::uadd_sat: {
  5524. SDValue Op1 = getValue(I.getArgOperand(0));
  5525. SDValue Op2 = getValue(I.getArgOperand(1));
  5526. setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2));
  5527. return;
  5528. }
  5529. case Intrinsic::ssub_sat: {
  5530. SDValue Op1 = getValue(I.getArgOperand(0));
  5531. SDValue Op2 = getValue(I.getArgOperand(1));
  5532. setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2));
  5533. return;
  5534. }
  5535. case Intrinsic::usub_sat: {
  5536. SDValue Op1 = getValue(I.getArgOperand(0));
  5537. SDValue Op2 = getValue(I.getArgOperand(1));
  5538. setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2));
  5539. return;
  5540. }
  5541. case Intrinsic::smul_fix:
  5542. case Intrinsic::umul_fix: {
  5543. SDValue Op1 = getValue(I.getArgOperand(0));
  5544. SDValue Op2 = getValue(I.getArgOperand(1));
  5545. SDValue Op3 = getValue(I.getArgOperand(2));
  5546. setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl,
  5547. Op1.getValueType(), Op1, Op2, Op3));
  5548. return;
  5549. }
  5550. case Intrinsic::smul_fix_sat: {
  5551. SDValue Op1 = getValue(I.getArgOperand(0));
  5552. SDValue Op2 = getValue(I.getArgOperand(1));
  5553. SDValue Op3 = getValue(I.getArgOperand(2));
  5554. setValue(&I, DAG.getNode(ISD::SMULFIXSAT, sdl, Op1.getValueType(), Op1, Op2,
  5555. Op3));
  5556. return;
  5557. }
  5558. case Intrinsic::stacksave: {
  5559. SDValue Op = getRoot();
  5560. Res = DAG.getNode(
  5561. ISD::STACKSAVE, sdl,
  5562. DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Op);
  5563. setValue(&I, Res);
  5564. DAG.setRoot(Res.getValue(1));
  5565. return;
  5566. }
  5567. case Intrinsic::stackrestore:
  5568. Res = getValue(I.getArgOperand(0));
  5569. DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res));
  5570. return;
  5571. case Intrinsic::get_dynamic_area_offset: {
  5572. SDValue Op = getRoot();
  5573. EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
  5574. EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
  5575. // Result type for @llvm.get.dynamic.area.offset should match PtrTy for
  5576. // target.
  5577. if (PtrTy.getSizeInBits() < ResTy.getSizeInBits())
  5578. report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset"
  5579. " intrinsic!");
  5580. Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy),
  5581. Op);
  5582. DAG.setRoot(Op);
  5583. setValue(&I, Res);
  5584. return;
  5585. }
  5586. case Intrinsic::stackguard: {
  5587. EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
  5588. MachineFunction &MF = DAG.getMachineFunction();
  5589. const Module &M = *MF.getFunction().getParent();
  5590. SDValue Chain = getRoot();
  5591. if (TLI.useLoadStackGuardNode()) {
  5592. Res = getLoadStackGuard(DAG, sdl, Chain);
  5593. } else {
  5594. const Value *Global = TLI.getSDagStackGuard(M);
  5595. unsigned Align = DL->getPrefTypeAlignment(Global->getType());
  5596. Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global),
  5597. MachinePointerInfo(Global, 0), Align,
  5598. MachineMemOperand::MOVolatile);
  5599. }
  5600. if (TLI.useStackGuardXorFP())
  5601. Res = TLI.emitStackGuardXorFP(DAG, Res, sdl);
  5602. DAG.setRoot(Chain);
  5603. setValue(&I, Res);
  5604. return;
  5605. }
  5606. case Intrinsic::stackprotector: {
  5607. // Emit code into the DAG to store the stack guard onto the stack.
  5608. MachineFunction &MF = DAG.getMachineFunction();
  5609. MachineFrameInfo &MFI = MF.getFrameInfo();
  5610. EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
  5611. SDValue Src, Chain = getRoot();
  5612. if (TLI.useLoadStackGuardNode())
  5613. Src = getLoadStackGuard(DAG, sdl, Chain);
  5614. else
  5615. Src = getValue(I.getArgOperand(0)); // The guard's value.
  5616. AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
  5617. int FI = FuncInfo.StaticAllocaMap[Slot];
  5618. MFI.setStackProtectorIndex(FI);
  5619. SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
  5620. // Store the stack protector onto the stack.
  5621. Res = DAG.getStore(Chain, sdl, Src, FIN, MachinePointerInfo::getFixedStack(
  5622. DAG.getMachineFunction(), FI),
  5623. /* Alignment = */ 0, MachineMemOperand::MOVolatile);
  5624. setValue(&I, Res);
  5625. DAG.setRoot(Res);
  5626. return;
  5627. }
  5628. case Intrinsic::objectsize: {
  5629. // If we don't know by now, we're never going to know.
  5630. ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(1));
  5631. assert(CI && "Non-constant type in __builtin_object_size?");
  5632. SDValue Arg = getValue(I.getCalledValue());
  5633. EVT Ty = Arg.getValueType();
  5634. if (CI->isZero())
  5635. Res = DAG.getConstant(-1ULL, sdl, Ty);
  5636. else
  5637. Res = DAG.getConstant(0, sdl, Ty);
  5638. setValue(&I, Res);
  5639. return;
  5640. }
  5641. case Intrinsic::is_constant:
  5642. // If this wasn't constant-folded away by now, then it's not a
  5643. // constant.
  5644. setValue(&I, DAG.getConstant(0, sdl, MVT::i1));
  5645. return;
  5646. case Intrinsic::annotation:
  5647. case Intrinsic::ptr_annotation:
  5648. case Intrinsic::launder_invariant_group:
  5649. case Intrinsic::strip_invariant_group:
  5650. // Drop the intrinsic, but forward the value
  5651. setValue(&I, getValue(I.getOperand(0)));
  5652. return;
  5653. case Intrinsic::assume:
  5654. case Intrinsic::var_annotation:
  5655. case Intrinsic::sideeffect:
  5656. // Discard annotate attributes, assumptions, and artificial side-effects.
  5657. return;
  5658. case Intrinsic::codeview_annotation: {
  5659. // Emit a label associated with this metadata.
  5660. MachineFunction &MF = DAG.getMachineFunction();
  5661. MCSymbol *Label =
  5662. MF.getMMI().getContext().createTempSymbol("annotation", true);
  5663. Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata();
  5664. MF.addCodeViewAnnotation(Label, cast<MDNode>(MD));
  5665. Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label);
  5666. DAG.setRoot(Res);
  5667. return;
  5668. }
  5669. case Intrinsic::init_trampoline: {
  5670. const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts());
  5671. SDValue Ops[6];
  5672. Ops[0] = getRoot();
  5673. Ops[1] = getValue(I.getArgOperand(0));
  5674. Ops[2] = getValue(I.getArgOperand(1));
  5675. Ops[3] = getValue(I.getArgOperand(2));
  5676. Ops[4] = DAG.getSrcValue(I.getArgOperand(0));
  5677. Ops[5] = DAG.getSrcValue(F);
  5678. Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops);
  5679. DAG.setRoot(Res);
  5680. return;
  5681. }
  5682. case Intrinsic::adjust_trampoline:
  5683. setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl,
  5684. TLI.getPointerTy(DAG.getDataLayout()),
  5685. getValue(I.getArgOperand(0))));
  5686. return;
  5687. case Intrinsic::gcroot: {
  5688. assert(DAG.getMachineFunction().getFunction().hasGC() &&
  5689. "only valid in functions with gc specified, enforced by Verifier");
  5690. assert(GFI && "implied by previous");
  5691. const Value *Alloca = I.getArgOperand(0)->stripPointerCasts();
  5692. const Constant *TypeMap = cast<Constant>(I.getArgOperand(1));
  5693. FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
  5694. GFI->addStackRoot(FI->getIndex(), TypeMap);
  5695. return;
  5696. }
  5697. case Intrinsic::gcread:
  5698. case Intrinsic::gcwrite:
  5699. llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
  5700. case Intrinsic::flt_rounds:
  5701. setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, sdl, MVT::i32));
  5702. return;
  5703. case Intrinsic::expect:
  5704. // Just replace __builtin_expect(exp, c) with EXP.
  5705. setValue(&I, getValue(I.getArgOperand(0)));
  5706. return;
  5707. case Intrinsic::debugtrap:
  5708. case Intrinsic::trap: {
  5709. StringRef TrapFuncName =
  5710. I.getAttributes()
  5711. .getAttribute(AttributeList::FunctionIndex, "trap-func-name")
  5712. .getValueAsString();
  5713. if (TrapFuncName.empty()) {
  5714. ISD::NodeType Op = (Intrinsic == Intrinsic::trap) ?
  5715. ISD::TRAP : ISD::DEBUGTRAP;
  5716. DAG.setRoot(DAG.getNode(Op, sdl,MVT::Other, getRoot()));
  5717. return;
  5718. }
  5719. TargetLowering::ArgListTy Args;
  5720. TargetLowering::CallLoweringInfo CLI(DAG);
  5721. CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee(
  5722. CallingConv::C, I.getType(),
  5723. DAG.getExternalSymbol(TrapFuncName.data(),
  5724. TLI.getPointerTy(DAG.getDataLayout())),
  5725. std::move(Args));
  5726. std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
  5727. DAG.setRoot(Result.second);
  5728. return;
  5729. }
  5730. case Intrinsic::uadd_with_overflow:
  5731. case Intrinsic::sadd_with_overflow:
  5732. case Intrinsic::usub_with_overflow:
  5733. case Intrinsic::ssub_with_overflow:
  5734. case Intrinsic::umul_with_overflow:
  5735. case Intrinsic::smul_with_overflow: {
  5736. ISD::NodeType Op;
  5737. switch (Intrinsic) {
  5738. default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
  5739. case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break;
  5740. case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break;
  5741. case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break;
  5742. case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break;
  5743. case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break;
  5744. case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break;
  5745. }
  5746. SDValue Op1 = getValue(I.getArgOperand(0));
  5747. SDValue Op2 = getValue(I.getArgOperand(1));
  5748. EVT ResultVT = Op1.getValueType();
  5749. EVT OverflowVT = MVT::i1;
  5750. if (ResultVT.isVector())
  5751. OverflowVT = EVT::getVectorVT(
  5752. *Context, OverflowVT, ResultVT.getVectorNumElements());
  5753. SDVTList VTs = DAG.getVTList(ResultVT, OverflowVT);
  5754. setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2));
  5755. return;
  5756. }
  5757. case Intrinsic::prefetch: {
  5758. SDValue Ops[5];
  5759. unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
  5760. auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore;
  5761. Ops[0] = DAG.getRoot();
  5762. Ops[1] = getValue(I.getArgOperand(0));
  5763. Ops[2] = getValue(I.getArgOperand(1));
  5764. Ops[3] = getValue(I.getArgOperand(2));
  5765. Ops[4] = getValue(I.getArgOperand(3));
  5766. SDValue Result = DAG.getMemIntrinsicNode(ISD::PREFETCH, sdl,
  5767. DAG.getVTList(MVT::Other), Ops,
  5768. EVT::getIntegerVT(*Context, 8),
  5769. MachinePointerInfo(I.getArgOperand(0)),
  5770. 0, /* align */
  5771. Flags);
  5772. // Chain the prefetch in parallell with any pending loads, to stay out of
  5773. // the way of later optimizations.
  5774. PendingLoads.push_back(Result);
  5775. Result = getRoot();
  5776. DAG.setRoot(Result);
  5777. return;
  5778. }
  5779. case Intrinsic::lifetime_start:
  5780. case Intrinsic::lifetime_end: {
  5781. bool IsStart = (Intrinsic == Intrinsic::lifetime_start);
  5782. // Stack coloring is not enabled in O0, discard region information.
  5783. if (TM.getOptLevel() == CodeGenOpt::None)
  5784. return;
  5785. const int64_t ObjectSize =
  5786. cast<ConstantInt>(I.getArgOperand(0))->getSExtValue();
  5787. Value *const ObjectPtr = I.getArgOperand(1);
  5788. SmallVector<const Value *, 4> Allocas;
  5789. GetUnderlyingObjects(ObjectPtr, Allocas, *DL);
  5790. for (SmallVectorImpl<const Value*>::iterator Object = Allocas.begin(),
  5791. E = Allocas.end(); Object != E; ++Object) {
  5792. const AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(*Object);
  5793. // Could not find an Alloca.
  5794. if (!LifetimeObject)
  5795. continue;
  5796. // First check that the Alloca is static, otherwise it won't have a
  5797. // valid frame index.
  5798. auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject);
  5799. if (SI == FuncInfo.StaticAllocaMap.end())
  5800. return;
  5801. const int FrameIndex = SI->second;
  5802. int64_t Offset;
  5803. if (GetPointerBaseWithConstantOffset(
  5804. ObjectPtr, Offset, DAG.getDataLayout()) != LifetimeObject)
  5805. Offset = -1; // Cannot determine offset from alloca to lifetime object.
  5806. Res = DAG.getLifetimeNode(IsStart, sdl, getRoot(), FrameIndex, ObjectSize,
  5807. Offset);
  5808. DAG.setRoot(Res);
  5809. }
  5810. return;
  5811. }
  5812. case Intrinsic::invariant_start:
  5813. // Discard region information.
  5814. setValue(&I, DAG.getUNDEF(TLI.getPointerTy(DAG.getDataLayout())));
  5815. return;
  5816. case Intrinsic::invariant_end:
  5817. // Discard region information.
  5818. return;
  5819. case Intrinsic::clear_cache:
  5820. /// FunctionName may be null.
  5821. if (const char *FunctionName = TLI.getClearCacheBuiltinName())
  5822. lowerCallToExternalSymbol(I, FunctionName);
  5823. return;
  5824. case Intrinsic::donothing:
  5825. // ignore
  5826. return;
  5827. case Intrinsic::experimental_stackmap:
  5828. visitStackmap(I);
  5829. return;
  5830. case Intrinsic::experimental_patchpoint_void:
  5831. case Intrinsic::experimental_patchpoint_i64:
  5832. visitPatchpoint(&I);
  5833. return;
  5834. case Intrinsic::experimental_gc_statepoint:
  5835. LowerStatepoint(ImmutableStatepoint(&I));
  5836. return;
  5837. case Intrinsic::experimental_gc_result:
  5838. visitGCResult(cast<GCResultInst>(I));
  5839. return;
  5840. case Intrinsic::experimental_gc_relocate:
  5841. visitGCRelocate(cast<GCRelocateInst>(I));
  5842. return;
  5843. case Intrinsic::instrprof_increment:
  5844. llvm_unreachable("instrprof failed to lower an increment");
  5845. case Intrinsic::instrprof_value_profile:
  5846. llvm_unreachable("instrprof failed to lower a value profiling call");
  5847. case Intrinsic::localescape: {
  5848. MachineFunction &MF = DAG.getMachineFunction();
  5849. const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
  5850. // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission
  5851. // is the same on all targets.
  5852. for (unsigned Idx = 0, E = I.getNumArgOperands(); Idx < E; ++Idx) {
  5853. Value *Arg = I.getArgOperand(Idx)->stripPointerCasts();
  5854. if (isa<ConstantPointerNull>(Arg))
  5855. continue; // Skip null pointers. They represent a hole in index space.
  5856. AllocaInst *Slot = cast<AllocaInst>(Arg);
  5857. assert(FuncInfo.StaticAllocaMap.count(Slot) &&
  5858. "can only escape static allocas");
  5859. int FI = FuncInfo.StaticAllocaMap[Slot];
  5860. MCSymbol *FrameAllocSym =
  5861. MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
  5862. GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx);
  5863. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl,
  5864. TII->get(TargetOpcode::LOCAL_ESCAPE))
  5865. .addSym(FrameAllocSym)
  5866. .addFrameIndex(FI);
  5867. }
  5868. return;
  5869. }
  5870. case Intrinsic::localrecover: {
  5871. // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx)
  5872. MachineFunction &MF = DAG.getMachineFunction();
  5873. MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout(), 0);
  5874. // Get the symbol that defines the frame offset.
  5875. auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts());
  5876. auto *Idx = cast<ConstantInt>(I.getArgOperand(2));
  5877. unsigned IdxVal =
  5878. unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max()));
  5879. MCSymbol *FrameAllocSym =
  5880. MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
  5881. GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal);
  5882. // Create a MCSymbol for the label to avoid any target lowering
  5883. // that would make this PC relative.
  5884. SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT);
  5885. SDValue OffsetVal =
  5886. DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym);
  5887. // Add the offset to the FP.
  5888. Value *FP = I.getArgOperand(1);
  5889. SDValue FPVal = getValue(FP);
  5890. SDValue Add = DAG.getNode(ISD::ADD, sdl, PtrVT, FPVal, OffsetVal);
  5891. setValue(&I, Add);
  5892. return;
  5893. }
  5894. case Intrinsic::eh_exceptionpointer:
  5895. case Intrinsic::eh_exceptioncode: {
  5896. // Get the exception pointer vreg, copy from it, and resize it to fit.
  5897. const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0));
  5898. MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
  5899. const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT);
  5900. unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC);
  5901. SDValue N =
  5902. DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), VReg, PtrVT);
  5903. if (Intrinsic == Intrinsic::eh_exceptioncode)
  5904. N = DAG.getZExtOrTrunc(N, getCurSDLoc(), MVT::i32);
  5905. setValue(&I, N);
  5906. return;
  5907. }
  5908. case Intrinsic::xray_customevent: {
  5909. // Here we want to make sure that the intrinsic behaves as if it has a
  5910. // specific calling convention, and only for x86_64.
  5911. // FIXME: Support other platforms later.
  5912. const auto &Triple = DAG.getTarget().getTargetTriple();
  5913. if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux())
  5914. return;
  5915. SDLoc DL = getCurSDLoc();
  5916. SmallVector<SDValue, 8> Ops;
  5917. // We want to say that we always want the arguments in registers.
  5918. SDValue LogEntryVal = getValue(I.getArgOperand(0));
  5919. SDValue StrSizeVal = getValue(I.getArgOperand(1));
  5920. SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
  5921. SDValue Chain = getRoot();
  5922. Ops.push_back(LogEntryVal);
  5923. Ops.push_back(StrSizeVal);
  5924. Ops.push_back(Chain);
  5925. // We need to enforce the calling convention for the callsite, so that
  5926. // argument ordering is enforced correctly, and that register allocation can
  5927. // see that some registers may be assumed clobbered and have to preserve
  5928. // them across calls to the intrinsic.
  5929. MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL,
  5930. DL, NodeTys, Ops);
  5931. SDValue patchableNode = SDValue(MN, 0);
  5932. DAG.setRoot(patchableNode);
  5933. setValue(&I, patchableNode);
  5934. return;
  5935. }
  5936. case Intrinsic::xray_typedevent: {
  5937. // Here we want to make sure that the intrinsic behaves as if it has a
  5938. // specific calling convention, and only for x86_64.
  5939. // FIXME: Support other platforms later.
  5940. const auto &Triple = DAG.getTarget().getTargetTriple();
  5941. if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux())
  5942. return;
  5943. SDLoc DL = getCurSDLoc();
  5944. SmallVector<SDValue, 8> Ops;
  5945. // We want to say that we always want the arguments in registers.
  5946. // It's unclear to me how manipulating the selection DAG here forces callers
  5947. // to provide arguments in registers instead of on the stack.
  5948. SDValue LogTypeId = getValue(I.getArgOperand(0));
  5949. SDValue LogEntryVal = getValue(I.getArgOperand(1));
  5950. SDValue StrSizeVal = getValue(I.getArgOperand(2));
  5951. SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
  5952. SDValue Chain = getRoot();
  5953. Ops.push_back(LogTypeId);
  5954. Ops.push_back(LogEntryVal);
  5955. Ops.push_back(StrSizeVal);
  5956. Ops.push_back(Chain);
  5957. // We need to enforce the calling convention for the callsite, so that
  5958. // argument ordering is enforced correctly, and that register allocation can
  5959. // see that some registers may be assumed clobbered and have to preserve
  5960. // them across calls to the intrinsic.
  5961. MachineSDNode *MN = DAG.getMachineNode(
  5962. TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, DL, NodeTys, Ops);
  5963. SDValue patchableNode = SDValue(MN, 0);
  5964. DAG.setRoot(patchableNode);
  5965. setValue(&I, patchableNode);
  5966. return;
  5967. }
  5968. case Intrinsic::experimental_deoptimize:
  5969. LowerDeoptimizeCall(&I);
  5970. return;
  5971. case Intrinsic::experimental_vector_reduce_v2_fadd:
  5972. case Intrinsic::experimental_vector_reduce_v2_fmul:
  5973. case Intrinsic::experimental_vector_reduce_add:
  5974. case Intrinsic::experimental_vector_reduce_mul:
  5975. case Intrinsic::experimental_vector_reduce_and:
  5976. case Intrinsic::experimental_vector_reduce_or:
  5977. case Intrinsic::experimental_vector_reduce_xor:
  5978. case Intrinsic::experimental_vector_reduce_smax:
  5979. case Intrinsic::experimental_vector_reduce_smin:
  5980. case Intrinsic::experimental_vector_reduce_umax:
  5981. case Intrinsic::experimental_vector_reduce_umin:
  5982. case Intrinsic::experimental_vector_reduce_fmax:
  5983. case Intrinsic::experimental_vector_reduce_fmin:
  5984. visitVectorReduce(I, Intrinsic);
  5985. return;
  5986. case Intrinsic::icall_branch_funnel: {
  5987. SmallVector<SDValue, 16> Ops;
  5988. Ops.push_back(DAG.getRoot());
  5989. Ops.push_back(getValue(I.getArgOperand(0)));
  5990. int64_t Offset;
  5991. auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
  5992. I.getArgOperand(1), Offset, DAG.getDataLayout()));
  5993. if (!Base)
  5994. report_fatal_error(
  5995. "llvm.icall.branch.funnel operand must be a GlobalValue");
  5996. Ops.push_back(DAG.getTargetGlobalAddress(Base, getCurSDLoc(), MVT::i64, 0));
  5997. struct BranchFunnelTarget {
  5998. int64_t Offset;
  5999. SDValue Target;
  6000. };
  6001. SmallVector<BranchFunnelTarget, 8> Targets;
  6002. for (unsigned Op = 1, N = I.getNumArgOperands(); Op != N; Op += 2) {
  6003. auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
  6004. I.getArgOperand(Op), Offset, DAG.getDataLayout()));
  6005. if (ElemBase != Base)
  6006. report_fatal_error("all llvm.icall.branch.funnel operands must refer "
  6007. "to the same GlobalValue");
  6008. SDValue Val = getValue(I.getArgOperand(Op + 1));
  6009. auto *GA = dyn_cast<GlobalAddressSDNode>(Val);
  6010. if (!GA)
  6011. report_fatal_error(
  6012. "llvm.icall.branch.funnel operand must be a GlobalValue");
  6013. Targets.push_back({Offset, DAG.getTargetGlobalAddress(
  6014. GA->getGlobal(), getCurSDLoc(),
  6015. Val.getValueType(), GA->getOffset())});
  6016. }
  6017. llvm::sort(Targets,
  6018. [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) {
  6019. return T1.Offset < T2.Offset;
  6020. });
  6021. for (auto &T : Targets) {
  6022. Ops.push_back(DAG.getTargetConstant(T.Offset, getCurSDLoc(), MVT::i32));
  6023. Ops.push_back(T.Target);
  6024. }
  6025. SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL,
  6026. getCurSDLoc(), MVT::Other, Ops),
  6027. 0);
  6028. DAG.setRoot(N);
  6029. setValue(&I, N);
  6030. HasTailCall = true;
  6031. return;
  6032. }
  6033. case Intrinsic::wasm_landingpad_index:
  6034. // Information this intrinsic contained has been transferred to
  6035. // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely
  6036. // delete it now.
  6037. return;
  6038. }
  6039. }
  6040. void SelectionDAGBuilder::visitConstrainedFPIntrinsic(
  6041. const ConstrainedFPIntrinsic &FPI) {
  6042. SDLoc sdl = getCurSDLoc();
  6043. unsigned Opcode;
  6044. switch (FPI.getIntrinsicID()) {
  6045. default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
  6046. case Intrinsic::experimental_constrained_fadd:
  6047. Opcode = ISD::STRICT_FADD;
  6048. break;
  6049. case Intrinsic::experimental_constrained_fsub:
  6050. Opcode = ISD::STRICT_FSUB;
  6051. break;
  6052. case Intrinsic::experimental_constrained_fmul:
  6053. Opcode = ISD::STRICT_FMUL;
  6054. break;
  6055. case Intrinsic::experimental_constrained_fdiv:
  6056. Opcode = ISD::STRICT_FDIV;
  6057. break;
  6058. case Intrinsic::experimental_constrained_frem:
  6059. Opcode = ISD::STRICT_FREM;
  6060. break;
  6061. case Intrinsic::experimental_constrained_fma:
  6062. Opcode = ISD::STRICT_FMA;
  6063. break;
  6064. case Intrinsic::experimental_constrained_fptrunc:
  6065. Opcode = ISD::STRICT_FP_ROUND;
  6066. break;
  6067. case Intrinsic::experimental_constrained_fpext:
  6068. Opcode = ISD::STRICT_FP_EXTEND;
  6069. break;
  6070. case Intrinsic::experimental_constrained_sqrt:
  6071. Opcode = ISD::STRICT_FSQRT;
  6072. break;
  6073. case Intrinsic::experimental_constrained_pow:
  6074. Opcode = ISD::STRICT_FPOW;
  6075. break;
  6076. case Intrinsic::experimental_constrained_powi:
  6077. Opcode = ISD::STRICT_FPOWI;
  6078. break;
  6079. case Intrinsic::experimental_constrained_sin:
  6080. Opcode = ISD::STRICT_FSIN;
  6081. break;
  6082. case Intrinsic::experimental_constrained_cos:
  6083. Opcode = ISD::STRICT_FCOS;
  6084. break;
  6085. case Intrinsic::experimental_constrained_exp:
  6086. Opcode = ISD::STRICT_FEXP;
  6087. break;
  6088. case Intrinsic::experimental_constrained_exp2:
  6089. Opcode = ISD::STRICT_FEXP2;
  6090. break;
  6091. case Intrinsic::experimental_constrained_log:
  6092. Opcode = ISD::STRICT_FLOG;
  6093. break;
  6094. case Intrinsic::experimental_constrained_log10:
  6095. Opcode = ISD::STRICT_FLOG10;
  6096. break;
  6097. case Intrinsic::experimental_constrained_log2:
  6098. Opcode = ISD::STRICT_FLOG2;
  6099. break;
  6100. case Intrinsic::experimental_constrained_rint:
  6101. Opcode = ISD::STRICT_FRINT;
  6102. break;
  6103. case Intrinsic::experimental_constrained_nearbyint:
  6104. Opcode = ISD::STRICT_FNEARBYINT;
  6105. break;
  6106. case Intrinsic::experimental_constrained_maxnum:
  6107. Opcode = ISD::STRICT_FMAXNUM;
  6108. break;
  6109. case Intrinsic::experimental_constrained_minnum:
  6110. Opcode = ISD::STRICT_FMINNUM;
  6111. break;
  6112. case Intrinsic::experimental_constrained_ceil:
  6113. Opcode = ISD::STRICT_FCEIL;
  6114. break;
  6115. case Intrinsic::experimental_constrained_floor:
  6116. Opcode = ISD::STRICT_FFLOOR;
  6117. break;
  6118. case Intrinsic::experimental_constrained_round:
  6119. Opcode = ISD::STRICT_FROUND;
  6120. break;
  6121. case Intrinsic::experimental_constrained_trunc:
  6122. Opcode = ISD::STRICT_FTRUNC;
  6123. break;
  6124. }
  6125. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  6126. SDValue Chain = getRoot();
  6127. SmallVector<EVT, 4> ValueVTs;
  6128. ComputeValueVTs(TLI, DAG.getDataLayout(), FPI.getType(), ValueVTs);
  6129. ValueVTs.push_back(MVT::Other); // Out chain
  6130. SDVTList VTs = DAG.getVTList(ValueVTs);
  6131. SDValue Result;
  6132. if (Opcode == ISD::STRICT_FP_ROUND)
  6133. Result = DAG.getNode(Opcode, sdl, VTs,
  6134. { Chain, getValue(FPI.getArgOperand(0)),
  6135. DAG.getTargetConstant(0, sdl,
  6136. TLI.getPointerTy(DAG.getDataLayout())) });
  6137. else if (FPI.isUnaryOp())
  6138. Result = DAG.getNode(Opcode, sdl, VTs,
  6139. { Chain, getValue(FPI.getArgOperand(0)) });
  6140. else if (FPI.isTernaryOp())
  6141. Result = DAG.getNode(Opcode, sdl, VTs,
  6142. { Chain, getValue(FPI.getArgOperand(0)),
  6143. getValue(FPI.getArgOperand(1)),
  6144. getValue(FPI.getArgOperand(2)) });
  6145. else
  6146. Result = DAG.getNode(Opcode, sdl, VTs,
  6147. { Chain, getValue(FPI.getArgOperand(0)),
  6148. getValue(FPI.getArgOperand(1)) });
  6149. if (FPI.getExceptionBehavior() !=
  6150. ConstrainedFPIntrinsic::ExceptionBehavior::ebIgnore) {
  6151. SDNodeFlags Flags;
  6152. Flags.setFPExcept(true);
  6153. Result->setFlags(Flags);
  6154. }
  6155. assert(Result.getNode()->getNumValues() == 2);
  6156. SDValue OutChain = Result.getValue(1);
  6157. DAG.setRoot(OutChain);
  6158. SDValue FPResult = Result.getValue(0);
  6159. setValue(&FPI, FPResult);
  6160. }
  6161. std::pair<SDValue, SDValue>
  6162. SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI,
  6163. const BasicBlock *EHPadBB) {
  6164. MachineFunction &MF = DAG.getMachineFunction();
  6165. MachineModuleInfo &MMI = MF.getMMI();
  6166. MCSymbol *BeginLabel = nullptr;
  6167. if (EHPadBB) {
  6168. // Insert a label before the invoke call to mark the try range. This can be
  6169. // used to detect deletion of the invoke via the MachineModuleInfo.
  6170. BeginLabel = MMI.getContext().createTempSymbol();
  6171. // For SjLj, keep track of which landing pads go with which invokes
  6172. // so as to maintain the ordering of pads in the LSDA.
  6173. unsigned CallSiteIndex = MMI.getCurrentCallSite();
  6174. if (CallSiteIndex) {
  6175. MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex);
  6176. LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex);
  6177. // Now that the call site is handled, stop tracking it.
  6178. MMI.setCurrentCallSite(0);
  6179. }
  6180. // Both PendingLoads and PendingExports must be flushed here;
  6181. // this call might not return.
  6182. (void)getRoot();
  6183. DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getControlRoot(), BeginLabel));
  6184. CLI.setChain(getRoot());
  6185. }
  6186. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  6187. std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
  6188. assert((CLI.IsTailCall || Result.second.getNode()) &&
  6189. "Non-null chain expected with non-tail call!");
  6190. assert((Result.second.getNode() || !Result.first.getNode()) &&
  6191. "Null value expected with tail call!");
  6192. if (!Result.second.getNode()) {
  6193. // As a special case, a null chain means that a tail call has been emitted
  6194. // and the DAG root is already updated.
  6195. HasTailCall = true;
  6196. // Since there's no actual continuation from this block, nothing can be
  6197. // relying on us setting vregs for them.
  6198. PendingExports.clear();
  6199. } else {
  6200. DAG.setRoot(Result.second);
  6201. }
  6202. if (EHPadBB) {
  6203. // Insert a label at the end of the invoke call to mark the try range. This
  6204. // can be used to detect deletion of the invoke via the MachineModuleInfo.
  6205. MCSymbol *EndLabel = MMI.getContext().createTempSymbol();
  6206. DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getRoot(), EndLabel));
  6207. // Inform MachineModuleInfo of range.
  6208. auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
  6209. // There is a platform (e.g. wasm) that uses funclet style IR but does not
  6210. // actually use outlined funclets and their LSDA info style.
  6211. if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) {
  6212. assert(CLI.CS);
  6213. WinEHFuncInfo *EHInfo = DAG.getMachineFunction().getWinEHFuncInfo();
  6214. EHInfo->addIPToStateRange(cast<InvokeInst>(CLI.CS.getInstruction()),
  6215. BeginLabel, EndLabel);
  6216. } else if (!isScopedEHPersonality(Pers)) {
  6217. MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel);
  6218. }
  6219. }
  6220. return Result;
  6221. }
  6222. void SelectionDAGBuilder::LowerCallTo(ImmutableCallSite CS, SDValue Callee,
  6223. bool isTailCall,
  6224. const BasicBlock *EHPadBB) {
  6225. auto &DL = DAG.getDataLayout();
  6226. FunctionType *FTy = CS.getFunctionType();
  6227. Type *RetTy = CS.getType();
  6228. TargetLowering::ArgListTy Args;
  6229. Args.reserve(CS.arg_size());
  6230. const Value *SwiftErrorVal = nullptr;
  6231. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  6232. // We can't tail call inside a function with a swifterror argument. Lowering
  6233. // does not support this yet. It would have to move into the swifterror
  6234. // register before the call.
  6235. auto *Caller = CS.getInstruction()->getParent()->getParent();
  6236. if (TLI.supportSwiftError() &&
  6237. Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError))
  6238. isTailCall = false;
  6239. for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
  6240. i != e; ++i) {
  6241. TargetLowering::ArgListEntry Entry;
  6242. const Value *V = *i;
  6243. // Skip empty types
  6244. if (V->getType()->isEmptyTy())
  6245. continue;
  6246. SDValue ArgNode = getValue(V);
  6247. Entry.Node = ArgNode; Entry.Ty = V->getType();
  6248. Entry.setAttributes(&CS, i - CS.arg_begin());
  6249. // Use swifterror virtual register as input to the call.
  6250. if (Entry.IsSwiftError && TLI.supportSwiftError()) {
  6251. SwiftErrorVal = V;
  6252. // We find the virtual register for the actual swifterror argument.
  6253. // Instead of using the Value, we use the virtual register instead.
  6254. Entry.Node = DAG.getRegister(
  6255. SwiftError.getOrCreateVRegUseAt(CS.getInstruction(), FuncInfo.MBB, V),
  6256. EVT(TLI.getPointerTy(DL)));
  6257. }
  6258. Args.push_back(Entry);
  6259. // If we have an explicit sret argument that is an Instruction, (i.e., it
  6260. // might point to function-local memory), we can't meaningfully tail-call.
  6261. if (Entry.IsSRet && isa<Instruction>(V))
  6262. isTailCall = false;
  6263. }
  6264. // Check if target-independent constraints permit a tail call here.
  6265. // Target-dependent constraints are checked within TLI->LowerCallTo.
  6266. if (isTailCall && !isInTailCallPosition(CS, DAG.getTarget()))
  6267. isTailCall = false;
  6268. // Disable tail calls if there is an swifterror argument. Targets have not
  6269. // been updated to support tail calls.
  6270. if (TLI.supportSwiftError() && SwiftErrorVal)
  6271. isTailCall = false;
  6272. TargetLowering::CallLoweringInfo CLI(DAG);
  6273. CLI.setDebugLoc(getCurSDLoc())
  6274. .setChain(getRoot())
  6275. .setCallee(RetTy, FTy, Callee, std::move(Args), CS)
  6276. .setTailCall(isTailCall)
  6277. .setConvergent(CS.isConvergent());
  6278. std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
  6279. if (Result.first.getNode()) {
  6280. const Instruction *Inst = CS.getInstruction();
  6281. Result.first = lowerRangeToAssertZExt(DAG, *Inst, Result.first);
  6282. setValue(Inst, Result.first);
  6283. }
  6284. // The last element of CLI.InVals has the SDValue for swifterror return.
  6285. // Here we copy it to a virtual register and update SwiftErrorMap for
  6286. // book-keeping.
  6287. if (SwiftErrorVal && TLI.supportSwiftError()) {
  6288. // Get the last element of InVals.
  6289. SDValue Src = CLI.InVals.back();
  6290. unsigned VReg = SwiftError.getOrCreateVRegDefAt(
  6291. CS.getInstruction(), FuncInfo.MBB, SwiftErrorVal);
  6292. SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src);
  6293. DAG.setRoot(CopyNode);
  6294. }
  6295. }
  6296. static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT,
  6297. SelectionDAGBuilder &Builder) {
  6298. // Check to see if this load can be trivially constant folded, e.g. if the
  6299. // input is from a string literal.
  6300. if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) {
  6301. // Cast pointer to the type we really want to load.
  6302. Type *LoadTy =
  6303. Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits());
  6304. if (LoadVT.isVector())
  6305. LoadTy = VectorType::get(LoadTy, LoadVT.getVectorNumElements());
  6306. LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput),
  6307. PointerType::getUnqual(LoadTy));
  6308. if (const Constant *LoadCst = ConstantFoldLoadFromConstPtr(
  6309. const_cast<Constant *>(LoadInput), LoadTy, *Builder.DL))
  6310. return Builder.getValue(LoadCst);
  6311. }
  6312. // Otherwise, we have to emit the load. If the pointer is to unfoldable but
  6313. // still constant memory, the input chain can be the entry node.
  6314. SDValue Root;
  6315. bool ConstantMemory = false;
  6316. // Do not serialize (non-volatile) loads of constant memory with anything.
  6317. if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) {
  6318. Root = Builder.DAG.getEntryNode();
  6319. ConstantMemory = true;
  6320. } else {
  6321. // Do not serialize non-volatile loads against each other.
  6322. Root = Builder.DAG.getRoot();
  6323. }
  6324. SDValue Ptr = Builder.getValue(PtrVal);
  6325. SDValue LoadVal = Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root,
  6326. Ptr, MachinePointerInfo(PtrVal),
  6327. /* Alignment = */ 1);
  6328. if (!ConstantMemory)
  6329. Builder.PendingLoads.push_back(LoadVal.getValue(1));
  6330. return LoadVal;
  6331. }
  6332. /// Record the value for an instruction that produces an integer result,
  6333. /// converting the type where necessary.
  6334. void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I,
  6335. SDValue Value,
  6336. bool IsSigned) {
  6337. EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  6338. I.getType(), true);
  6339. if (IsSigned)
  6340. Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT);
  6341. else
  6342. Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT);
  6343. setValue(&I, Value);
  6344. }
  6345. /// See if we can lower a memcmp call into an optimized form. If so, return
  6346. /// true and lower it. Otherwise return false, and it will be lowered like a
  6347. /// normal call.
  6348. /// The caller already checked that \p I calls the appropriate LibFunc with a
  6349. /// correct prototype.
  6350. bool SelectionDAGBuilder::visitMemCmpCall(const CallInst &I) {
  6351. const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1);
  6352. const Value *Size = I.getArgOperand(2);
  6353. const ConstantInt *CSize = dyn_cast<ConstantInt>(Size);
  6354. if (CSize && CSize->getZExtValue() == 0) {
  6355. EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  6356. I.getType(), true);
  6357. setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT));
  6358. return true;
  6359. }
  6360. const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
  6361. std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp(
  6362. DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS),
  6363. getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS));
  6364. if (Res.first.getNode()) {
  6365. processIntegerCallValue(I, Res.first, true);
  6366. PendingLoads.push_back(Res.second);
  6367. return true;
  6368. }
  6369. // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS) != 0
  6370. // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS) != 0
  6371. if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I))
  6372. return false;
  6373. // If the target has a fast compare for the given size, it will return a
  6374. // preferred load type for that size. Require that the load VT is legal and
  6375. // that the target supports unaligned loads of that type. Otherwise, return
  6376. // INVALID.
  6377. auto hasFastLoadsAndCompare = [&](unsigned NumBits) {
  6378. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  6379. MVT LVT = TLI.hasFastEqualityCompare(NumBits);
  6380. if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) {
  6381. // TODO: Handle 5 byte compare as 4-byte + 1 byte.
  6382. // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
  6383. // TODO: Check alignment of src and dest ptrs.
  6384. unsigned DstAS = LHS->getType()->getPointerAddressSpace();
  6385. unsigned SrcAS = RHS->getType()->getPointerAddressSpace();
  6386. if (!TLI.isTypeLegal(LVT) ||
  6387. !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) ||
  6388. !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS))
  6389. LVT = MVT::INVALID_SIMPLE_VALUE_TYPE;
  6390. }
  6391. return LVT;
  6392. };
  6393. // This turns into unaligned loads. We only do this if the target natively
  6394. // supports the MVT we'll be loading or if it is small enough (<= 4) that
  6395. // we'll only produce a small number of byte loads.
  6396. MVT LoadVT;
  6397. unsigned NumBitsToCompare = CSize->getZExtValue() * 8;
  6398. switch (NumBitsToCompare) {
  6399. default:
  6400. return false;
  6401. case 16:
  6402. LoadVT = MVT::i16;
  6403. break;
  6404. case 32:
  6405. LoadVT = MVT::i32;
  6406. break;
  6407. case 64:
  6408. case 128:
  6409. case 256:
  6410. LoadVT = hasFastLoadsAndCompare(NumBitsToCompare);
  6411. break;
  6412. }
  6413. if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE)
  6414. return false;
  6415. SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this);
  6416. SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this);
  6417. // Bitcast to a wide integer type if the loads are vectors.
  6418. if (LoadVT.isVector()) {
  6419. EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits());
  6420. LoadL = DAG.getBitcast(CmpVT, LoadL);
  6421. LoadR = DAG.getBitcast(CmpVT, LoadR);
  6422. }
  6423. SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE);
  6424. processIntegerCallValue(I, Cmp, false);
  6425. return true;
  6426. }
  6427. /// See if we can lower a memchr call into an optimized form. If so, return
  6428. /// true and lower it. Otherwise return false, and it will be lowered like a
  6429. /// normal call.
  6430. /// The caller already checked that \p I calls the appropriate LibFunc with a
  6431. /// correct prototype.
  6432. bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) {
  6433. const Value *Src = I.getArgOperand(0);
  6434. const Value *Char = I.getArgOperand(1);
  6435. const Value *Length = I.getArgOperand(2);
  6436. const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
  6437. std::pair<SDValue, SDValue> Res =
  6438. TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(),
  6439. getValue(Src), getValue(Char), getValue(Length),
  6440. MachinePointerInfo(Src));
  6441. if (Res.first.getNode()) {
  6442. setValue(&I, Res.first);
  6443. PendingLoads.push_back(Res.second);
  6444. return true;
  6445. }
  6446. return false;
  6447. }
  6448. /// See if we can lower a mempcpy call into an optimized form. If so, return
  6449. /// true and lower it. Otherwise return false, and it will be lowered like a
  6450. /// normal call.
  6451. /// The caller already checked that \p I calls the appropriate LibFunc with a
  6452. /// correct prototype.
  6453. bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) {
  6454. SDValue Dst = getValue(I.getArgOperand(0));
  6455. SDValue Src = getValue(I.getArgOperand(1));
  6456. SDValue Size = getValue(I.getArgOperand(2));
  6457. unsigned DstAlign = DAG.InferPtrAlignment(Dst);
  6458. unsigned SrcAlign = DAG.InferPtrAlignment(Src);
  6459. unsigned Align = std::min(DstAlign, SrcAlign);
  6460. if (Align == 0) // Alignment of one or both could not be inferred.
  6461. Align = 1; // 0 and 1 both specify no alignment, but 0 is reserved.
  6462. bool isVol = false;
  6463. SDLoc sdl = getCurSDLoc();
  6464. // In the mempcpy context we need to pass in a false value for isTailCall
  6465. // because the return pointer needs to be adjusted by the size of
  6466. // the copied memory.
  6467. SDValue MC = DAG.getMemcpy(getRoot(), sdl, Dst, Src, Size, Align, isVol,
  6468. false, /*isTailCall=*/false,
  6469. MachinePointerInfo(I.getArgOperand(0)),
  6470. MachinePointerInfo(I.getArgOperand(1)));
  6471. assert(MC.getNode() != nullptr &&
  6472. "** memcpy should not be lowered as TailCall in mempcpy context **");
  6473. DAG.setRoot(MC);
  6474. // Check if Size needs to be truncated or extended.
  6475. Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType());
  6476. // Adjust return pointer to point just past the last dst byte.
  6477. SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(),
  6478. Dst, Size);
  6479. setValue(&I, DstPlusSize);
  6480. return true;
  6481. }
  6482. /// See if we can lower a strcpy call into an optimized form. If so, return
  6483. /// true and lower it, otherwise return false and it will be lowered like a
  6484. /// normal call.
  6485. /// The caller already checked that \p I calls the appropriate LibFunc with a
  6486. /// correct prototype.
  6487. bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) {
  6488. const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
  6489. const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
  6490. std::pair<SDValue, SDValue> Res =
  6491. TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(),
  6492. getValue(Arg0), getValue(Arg1),
  6493. MachinePointerInfo(Arg0),
  6494. MachinePointerInfo(Arg1), isStpcpy);
  6495. if (Res.first.getNode()) {
  6496. setValue(&I, Res.first);
  6497. DAG.setRoot(Res.second);
  6498. return true;
  6499. }
  6500. return false;
  6501. }
  6502. /// See if we can lower a strcmp call into an optimized form. If so, return
  6503. /// true and lower it, otherwise return false and it will be lowered like a
  6504. /// normal call.
  6505. /// The caller already checked that \p I calls the appropriate LibFunc with a
  6506. /// correct prototype.
  6507. bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) {
  6508. const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
  6509. const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
  6510. std::pair<SDValue, SDValue> Res =
  6511. TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(),
  6512. getValue(Arg0), getValue(Arg1),
  6513. MachinePointerInfo(Arg0),
  6514. MachinePointerInfo(Arg1));
  6515. if (Res.first.getNode()) {
  6516. processIntegerCallValue(I, Res.first, true);
  6517. PendingLoads.push_back(Res.second);
  6518. return true;
  6519. }
  6520. return false;
  6521. }
  6522. /// See if we can lower a strlen call into an optimized form. If so, return
  6523. /// true and lower it, otherwise return false and it will be lowered like a
  6524. /// normal call.
  6525. /// The caller already checked that \p I calls the appropriate LibFunc with a
  6526. /// correct prototype.
  6527. bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) {
  6528. const Value *Arg0 = I.getArgOperand(0);
  6529. const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
  6530. std::pair<SDValue, SDValue> Res =
  6531. TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(),
  6532. getValue(Arg0), MachinePointerInfo(Arg0));
  6533. if (Res.first.getNode()) {
  6534. processIntegerCallValue(I, Res.first, false);
  6535. PendingLoads.push_back(Res.second);
  6536. return true;
  6537. }
  6538. return false;
  6539. }
  6540. /// See if we can lower a strnlen call into an optimized form. If so, return
  6541. /// true and lower it, otherwise return false and it will be lowered like a
  6542. /// normal call.
  6543. /// The caller already checked that \p I calls the appropriate LibFunc with a
  6544. /// correct prototype.
  6545. bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) {
  6546. const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
  6547. const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
  6548. std::pair<SDValue, SDValue> Res =
  6549. TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(),
  6550. getValue(Arg0), getValue(Arg1),
  6551. MachinePointerInfo(Arg0));
  6552. if (Res.first.getNode()) {
  6553. processIntegerCallValue(I, Res.first, false);
  6554. PendingLoads.push_back(Res.second);
  6555. return true;
  6556. }
  6557. return false;
  6558. }
  6559. /// See if we can lower a unary floating-point operation into an SDNode with
  6560. /// the specified Opcode. If so, return true and lower it, otherwise return
  6561. /// false and it will be lowered like a normal call.
  6562. /// The caller already checked that \p I calls the appropriate LibFunc with a
  6563. /// correct prototype.
  6564. bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I,
  6565. unsigned Opcode) {
  6566. // We already checked this call's prototype; verify it doesn't modify errno.
  6567. if (!I.onlyReadsMemory())
  6568. return false;
  6569. SDValue Tmp = getValue(I.getArgOperand(0));
  6570. setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp));
  6571. return true;
  6572. }
  6573. /// See if we can lower a binary floating-point operation into an SDNode with
  6574. /// the specified Opcode. If so, return true and lower it. Otherwise return
  6575. /// false, and it will be lowered like a normal call.
  6576. /// The caller already checked that \p I calls the appropriate LibFunc with a
  6577. /// correct prototype.
  6578. bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I,
  6579. unsigned Opcode) {
  6580. // We already checked this call's prototype; verify it doesn't modify errno.
  6581. if (!I.onlyReadsMemory())
  6582. return false;
  6583. SDValue Tmp0 = getValue(I.getArgOperand(0));
  6584. SDValue Tmp1 = getValue(I.getArgOperand(1));
  6585. EVT VT = Tmp0.getValueType();
  6586. setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1));
  6587. return true;
  6588. }
  6589. void SelectionDAGBuilder::visitCall(const CallInst &I) {
  6590. // Handle inline assembly differently.
  6591. if (isa<InlineAsm>(I.getCalledValue())) {
  6592. visitInlineAsm(&I);
  6593. return;
  6594. }
  6595. if (Function *F = I.getCalledFunction()) {
  6596. if (F->isDeclaration()) {
  6597. // Is this an LLVM intrinsic or a target-specific intrinsic?
  6598. unsigned IID = F->getIntrinsicID();
  6599. if (!IID)
  6600. if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo())
  6601. IID = II->getIntrinsicID(F);
  6602. if (IID) {
  6603. visitIntrinsicCall(I, IID);
  6604. return;
  6605. }
  6606. }
  6607. // Check for well-known libc/libm calls. If the function is internal, it
  6608. // can't be a library call. Don't do the check if marked as nobuiltin for
  6609. // some reason or the call site requires strict floating point semantics.
  6610. LibFunc Func;
  6611. if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() &&
  6612. F->hasName() && LibInfo->getLibFunc(*F, Func) &&
  6613. LibInfo->hasOptimizedCodeGen(Func)) {
  6614. switch (Func) {
  6615. default: break;
  6616. case LibFunc_copysign:
  6617. case LibFunc_copysignf:
  6618. case LibFunc_copysignl:
  6619. // We already checked this call's prototype; verify it doesn't modify
  6620. // errno.
  6621. if (I.onlyReadsMemory()) {
  6622. SDValue LHS = getValue(I.getArgOperand(0));
  6623. SDValue RHS = getValue(I.getArgOperand(1));
  6624. setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(),
  6625. LHS.getValueType(), LHS, RHS));
  6626. return;
  6627. }
  6628. break;
  6629. case LibFunc_fabs:
  6630. case LibFunc_fabsf:
  6631. case LibFunc_fabsl:
  6632. if (visitUnaryFloatCall(I, ISD::FABS))
  6633. return;
  6634. break;
  6635. case LibFunc_fmin:
  6636. case LibFunc_fminf:
  6637. case LibFunc_fminl:
  6638. if (visitBinaryFloatCall(I, ISD::FMINNUM))
  6639. return;
  6640. break;
  6641. case LibFunc_fmax:
  6642. case LibFunc_fmaxf:
  6643. case LibFunc_fmaxl:
  6644. if (visitBinaryFloatCall(I, ISD::FMAXNUM))
  6645. return;
  6646. break;
  6647. case LibFunc_sin:
  6648. case LibFunc_sinf:
  6649. case LibFunc_sinl:
  6650. if (visitUnaryFloatCall(I, ISD::FSIN))
  6651. return;
  6652. break;
  6653. case LibFunc_cos:
  6654. case LibFunc_cosf:
  6655. case LibFunc_cosl:
  6656. if (visitUnaryFloatCall(I, ISD::FCOS))
  6657. return;
  6658. break;
  6659. case LibFunc_sqrt:
  6660. case LibFunc_sqrtf:
  6661. case LibFunc_sqrtl:
  6662. case LibFunc_sqrt_finite:
  6663. case LibFunc_sqrtf_finite:
  6664. case LibFunc_sqrtl_finite:
  6665. if (visitUnaryFloatCall(I, ISD::FSQRT))
  6666. return;
  6667. break;
  6668. case LibFunc_floor:
  6669. case LibFunc_floorf:
  6670. case LibFunc_floorl:
  6671. if (visitUnaryFloatCall(I, ISD::FFLOOR))
  6672. return;
  6673. break;
  6674. case LibFunc_nearbyint:
  6675. case LibFunc_nearbyintf:
  6676. case LibFunc_nearbyintl:
  6677. if (visitUnaryFloatCall(I, ISD::FNEARBYINT))
  6678. return;
  6679. break;
  6680. case LibFunc_ceil:
  6681. case LibFunc_ceilf:
  6682. case LibFunc_ceill:
  6683. if (visitUnaryFloatCall(I, ISD::FCEIL))
  6684. return;
  6685. break;
  6686. case LibFunc_rint:
  6687. case LibFunc_rintf:
  6688. case LibFunc_rintl:
  6689. if (visitUnaryFloatCall(I, ISD::FRINT))
  6690. return;
  6691. break;
  6692. case LibFunc_round:
  6693. case LibFunc_roundf:
  6694. case LibFunc_roundl:
  6695. if (visitUnaryFloatCall(I, ISD::FROUND))
  6696. return;
  6697. break;
  6698. case LibFunc_trunc:
  6699. case LibFunc_truncf:
  6700. case LibFunc_truncl:
  6701. if (visitUnaryFloatCall(I, ISD::FTRUNC))
  6702. return;
  6703. break;
  6704. case LibFunc_log2:
  6705. case LibFunc_log2f:
  6706. case LibFunc_log2l:
  6707. if (visitUnaryFloatCall(I, ISD::FLOG2))
  6708. return;
  6709. break;
  6710. case LibFunc_exp2:
  6711. case LibFunc_exp2f:
  6712. case LibFunc_exp2l:
  6713. if (visitUnaryFloatCall(I, ISD::FEXP2))
  6714. return;
  6715. break;
  6716. case LibFunc_memcmp:
  6717. if (visitMemCmpCall(I))
  6718. return;
  6719. break;
  6720. case LibFunc_mempcpy:
  6721. if (visitMemPCpyCall(I))
  6722. return;
  6723. break;
  6724. case LibFunc_memchr:
  6725. if (visitMemChrCall(I))
  6726. return;
  6727. break;
  6728. case LibFunc_strcpy:
  6729. if (visitStrCpyCall(I, false))
  6730. return;
  6731. break;
  6732. case LibFunc_stpcpy:
  6733. if (visitStrCpyCall(I, true))
  6734. return;
  6735. break;
  6736. case LibFunc_strcmp:
  6737. if (visitStrCmpCall(I))
  6738. return;
  6739. break;
  6740. case LibFunc_strlen:
  6741. if (visitStrLenCall(I))
  6742. return;
  6743. break;
  6744. case LibFunc_strnlen:
  6745. if (visitStrNLenCall(I))
  6746. return;
  6747. break;
  6748. }
  6749. }
  6750. }
  6751. // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
  6752. // have to do anything here to lower funclet bundles.
  6753. assert(!I.hasOperandBundlesOtherThan(
  6754. {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) &&
  6755. "Cannot lower calls with arbitrary operand bundles!");
  6756. SDValue Callee = getValue(I.getCalledValue());
  6757. if (I.countOperandBundlesOfType(LLVMContext::OB_deopt))
  6758. LowerCallSiteWithDeoptBundle(&I, Callee, nullptr);
  6759. else
  6760. // Check if we can potentially perform a tail call. More detailed checking
  6761. // is be done within LowerCallTo, after more information about the call is
  6762. // known.
  6763. LowerCallTo(&I, Callee, I.isTailCall());
  6764. }
  6765. namespace {
  6766. /// AsmOperandInfo - This contains information for each constraint that we are
  6767. /// lowering.
  6768. class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
  6769. public:
  6770. /// CallOperand - If this is the result output operand or a clobber
  6771. /// this is null, otherwise it is the incoming operand to the CallInst.
  6772. /// This gets modified as the asm is processed.
  6773. SDValue CallOperand;
  6774. /// AssignedRegs - If this is a register or register class operand, this
  6775. /// contains the set of register corresponding to the operand.
  6776. RegsForValue AssignedRegs;
  6777. explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info)
  6778. : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) {
  6779. }
  6780. /// Whether or not this operand accesses memory
  6781. bool hasMemory(const TargetLowering &TLI) const {
  6782. // Indirect operand accesses access memory.
  6783. if (isIndirect)
  6784. return true;
  6785. for (const auto &Code : Codes)
  6786. if (TLI.getConstraintType(Code) == TargetLowering::C_Memory)
  6787. return true;
  6788. return false;
  6789. }
  6790. /// getCallOperandValEVT - Return the EVT of the Value* that this operand
  6791. /// corresponds to. If there is no Value* for this operand, it returns
  6792. /// MVT::Other.
  6793. EVT getCallOperandValEVT(LLVMContext &Context, const TargetLowering &TLI,
  6794. const DataLayout &DL) const {
  6795. if (!CallOperandVal) return MVT::Other;
  6796. if (isa<BasicBlock>(CallOperandVal))
  6797. return TLI.getPointerTy(DL);
  6798. llvm::Type *OpTy = CallOperandVal->getType();
  6799. // FIXME: code duplicated from TargetLowering::ParseConstraints().
  6800. // If this is an indirect operand, the operand is a pointer to the
  6801. // accessed type.
  6802. if (isIndirect) {
  6803. PointerType *PtrTy = dyn_cast<PointerType>(OpTy);
  6804. if (!PtrTy)
  6805. report_fatal_error("Indirect operand for inline asm not a pointer!");
  6806. OpTy = PtrTy->getElementType();
  6807. }
  6808. // Look for vector wrapped in a struct. e.g. { <16 x i8> }.
  6809. if (StructType *STy = dyn_cast<StructType>(OpTy))
  6810. if (STy->getNumElements() == 1)
  6811. OpTy = STy->getElementType(0);
  6812. // If OpTy is not a single value, it may be a struct/union that we
  6813. // can tile with integers.
  6814. if (!OpTy->isSingleValueType() && OpTy->isSized()) {
  6815. unsigned BitSize = DL.getTypeSizeInBits(OpTy);
  6816. switch (BitSize) {
  6817. default: break;
  6818. case 1:
  6819. case 8:
  6820. case 16:
  6821. case 32:
  6822. case 64:
  6823. case 128:
  6824. OpTy = IntegerType::get(Context, BitSize);
  6825. break;
  6826. }
  6827. }
  6828. return TLI.getValueType(DL, OpTy, true);
  6829. }
  6830. };
  6831. using SDISelAsmOperandInfoVector = SmallVector<SDISelAsmOperandInfo, 16>;
  6832. } // end anonymous namespace
  6833. /// Make sure that the output operand \p OpInfo and its corresponding input
  6834. /// operand \p MatchingOpInfo have compatible constraint types (otherwise error
  6835. /// out).
  6836. static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo,
  6837. SDISelAsmOperandInfo &MatchingOpInfo,
  6838. SelectionDAG &DAG) {
  6839. if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT)
  6840. return;
  6841. const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
  6842. const auto &TLI = DAG.getTargetLoweringInfo();
  6843. std::pair<unsigned, const TargetRegisterClass *> MatchRC =
  6844. TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode,
  6845. OpInfo.ConstraintVT);
  6846. std::pair<unsigned, const TargetRegisterClass *> InputRC =
  6847. TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode,
  6848. MatchingOpInfo.ConstraintVT);
  6849. if ((OpInfo.ConstraintVT.isInteger() !=
  6850. MatchingOpInfo.ConstraintVT.isInteger()) ||
  6851. (MatchRC.second != InputRC.second)) {
  6852. // FIXME: error out in a more elegant fashion
  6853. report_fatal_error("Unsupported asm: input constraint"
  6854. " with a matching output constraint of"
  6855. " incompatible type!");
  6856. }
  6857. MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT;
  6858. }
  6859. /// Get a direct memory input to behave well as an indirect operand.
  6860. /// This may introduce stores, hence the need for a \p Chain.
  6861. /// \return The (possibly updated) chain.
  6862. static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location,
  6863. SDISelAsmOperandInfo &OpInfo,
  6864. SelectionDAG &DAG) {
  6865. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  6866. // If we don't have an indirect input, put it in the constpool if we can,
  6867. // otherwise spill it to a stack slot.
  6868. // TODO: This isn't quite right. We need to handle these according to
  6869. // the addressing mode that the constraint wants. Also, this may take
  6870. // an additional register for the computation and we don't want that
  6871. // either.
  6872. // If the operand is a float, integer, or vector constant, spill to a
  6873. // constant pool entry to get its address.
  6874. const Value *OpVal = OpInfo.CallOperandVal;
  6875. if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
  6876. isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) {
  6877. OpInfo.CallOperand = DAG.getConstantPool(
  6878. cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout()));
  6879. return Chain;
  6880. }
  6881. // Otherwise, create a stack slot and emit a store to it before the asm.
  6882. Type *Ty = OpVal->getType();
  6883. auto &DL = DAG.getDataLayout();
  6884. uint64_t TySize = DL.getTypeAllocSize(Ty);
  6885. unsigned Align = DL.getPrefTypeAlignment(Ty);
  6886. MachineFunction &MF = DAG.getMachineFunction();
  6887. int SSFI = MF.getFrameInfo().CreateStackObject(TySize, Align, false);
  6888. SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL));
  6889. Chain = DAG.getTruncStore(Chain, Location, OpInfo.CallOperand, StackSlot,
  6890. MachinePointerInfo::getFixedStack(MF, SSFI),
  6891. TLI.getMemValueType(DL, Ty));
  6892. OpInfo.CallOperand = StackSlot;
  6893. return Chain;
  6894. }
  6895. /// GetRegistersForValue - Assign registers (virtual or physical) for the
  6896. /// specified operand. We prefer to assign virtual registers, to allow the
  6897. /// register allocator to handle the assignment process. However, if the asm
  6898. /// uses features that we can't model on machineinstrs, we have SDISel do the
  6899. /// allocation. This produces generally horrible, but correct, code.
  6900. ///
  6901. /// OpInfo describes the operand
  6902. /// RefOpInfo describes the matching operand if any, the operand otherwise
  6903. static void GetRegistersForValue(SelectionDAG &DAG, const SDLoc &DL,
  6904. SDISelAsmOperandInfo &OpInfo,
  6905. SDISelAsmOperandInfo &RefOpInfo) {
  6906. LLVMContext &Context = *DAG.getContext();
  6907. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  6908. MachineFunction &MF = DAG.getMachineFunction();
  6909. SmallVector<unsigned, 4> Regs;
  6910. const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
  6911. // No work to do for memory operations.
  6912. if (OpInfo.ConstraintType == TargetLowering::C_Memory)
  6913. return;
  6914. // If this is a constraint for a single physreg, or a constraint for a
  6915. // register class, find it.
  6916. unsigned AssignedReg;
  6917. const TargetRegisterClass *RC;
  6918. std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint(
  6919. &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT);
  6920. // RC is unset only on failure. Return immediately.
  6921. if (!RC)
  6922. return;
  6923. // Get the actual register value type. This is important, because the user
  6924. // may have asked for (e.g.) the AX register in i32 type. We need to
  6925. // remember that AX is actually i16 to get the right extension.
  6926. const MVT RegVT = *TRI.legalclasstypes_begin(*RC);
  6927. if (OpInfo.ConstraintVT != MVT::Other) {
  6928. // If this is an FP operand in an integer register (or visa versa), or more
  6929. // generally if the operand value disagrees with the register class we plan
  6930. // to stick it in, fix the operand type.
  6931. //
  6932. // If this is an input value, the bitcast to the new type is done now.
  6933. // Bitcast for output value is done at the end of visitInlineAsm().
  6934. if ((OpInfo.Type == InlineAsm::isOutput ||
  6935. OpInfo.Type == InlineAsm::isInput) &&
  6936. !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) {
  6937. // Try to convert to the first EVT that the reg class contains. If the
  6938. // types are identical size, use a bitcast to convert (e.g. two differing
  6939. // vector types). Note: output bitcast is done at the end of
  6940. // visitInlineAsm().
  6941. if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
  6942. // Exclude indirect inputs while they are unsupported because the code
  6943. // to perform the load is missing and thus OpInfo.CallOperand still
  6944. // refers to the input address rather than the pointed-to value.
  6945. if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect)
  6946. OpInfo.CallOperand =
  6947. DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand);
  6948. OpInfo.ConstraintVT = RegVT;
  6949. // If the operand is an FP value and we want it in integer registers,
  6950. // use the corresponding integer type. This turns an f64 value into
  6951. // i64, which can be passed with two i32 values on a 32-bit machine.
  6952. } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
  6953. MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
  6954. if (OpInfo.Type == InlineAsm::isInput)
  6955. OpInfo.CallOperand =
  6956. DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand);
  6957. OpInfo.ConstraintVT = VT;
  6958. }
  6959. }
  6960. }
  6961. // No need to allocate a matching input constraint since the constraint it's
  6962. // matching to has already been allocated.
  6963. if (OpInfo.isMatchingInputConstraint())
  6964. return;
  6965. EVT ValueVT = OpInfo.ConstraintVT;
  6966. if (OpInfo.ConstraintVT == MVT::Other)
  6967. ValueVT = RegVT;
  6968. // Initialize NumRegs.
  6969. unsigned NumRegs = 1;
  6970. if (OpInfo.ConstraintVT != MVT::Other)
  6971. NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT);
  6972. // If this is a constraint for a specific physical register, like {r17},
  6973. // assign it now.
  6974. // If this associated to a specific register, initialize iterator to correct
  6975. // place. If virtual, make sure we have enough registers
  6976. // Initialize iterator if necessary
  6977. TargetRegisterClass::iterator I = RC->begin();
  6978. MachineRegisterInfo &RegInfo = MF.getRegInfo();
  6979. // Do not check for single registers.
  6980. if (AssignedReg) {
  6981. for (; *I != AssignedReg; ++I)
  6982. assert(I != RC->end() && "AssignedReg should be member of RC");
  6983. }
  6984. for (; NumRegs; --NumRegs, ++I) {
  6985. assert(I != RC->end() && "Ran out of registers to allocate!");
  6986. Register R = AssignedReg ? Register(*I) : RegInfo.createVirtualRegister(RC);
  6987. Regs.push_back(R);
  6988. }
  6989. OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
  6990. }
  6991. static unsigned
  6992. findMatchingInlineAsmOperand(unsigned OperandNo,
  6993. const std::vector<SDValue> &AsmNodeOperands) {
  6994. // Scan until we find the definition we already emitted of this operand.
  6995. unsigned CurOp = InlineAsm::Op_FirstOperand;
  6996. for (; OperandNo; --OperandNo) {
  6997. // Advance to the next operand.
  6998. unsigned OpFlag =
  6999. cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
  7000. assert((InlineAsm::isRegDefKind(OpFlag) ||
  7001. InlineAsm::isRegDefEarlyClobberKind(OpFlag) ||
  7002. InlineAsm::isMemKind(OpFlag)) &&
  7003. "Skipped past definitions?");
  7004. CurOp += InlineAsm::getNumOperandRegisters(OpFlag) + 1;
  7005. }
  7006. return CurOp;
  7007. }
  7008. namespace {
  7009. class ExtraFlags {
  7010. unsigned Flags = 0;
  7011. public:
  7012. explicit ExtraFlags(ImmutableCallSite CS) {
  7013. const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
  7014. if (IA->hasSideEffects())
  7015. Flags |= InlineAsm::Extra_HasSideEffects;
  7016. if (IA->isAlignStack())
  7017. Flags |= InlineAsm::Extra_IsAlignStack;
  7018. if (CS.isConvergent())
  7019. Flags |= InlineAsm::Extra_IsConvergent;
  7020. Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect;
  7021. }
  7022. void update(const TargetLowering::AsmOperandInfo &OpInfo) {
  7023. // Ideally, we would only check against memory constraints. However, the
  7024. // meaning of an Other constraint can be target-specific and we can't easily
  7025. // reason about it. Therefore, be conservative and set MayLoad/MayStore
  7026. // for Other constraints as well.
  7027. if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
  7028. OpInfo.ConstraintType == TargetLowering::C_Other) {
  7029. if (OpInfo.Type == InlineAsm::isInput)
  7030. Flags |= InlineAsm::Extra_MayLoad;
  7031. else if (OpInfo.Type == InlineAsm::isOutput)
  7032. Flags |= InlineAsm::Extra_MayStore;
  7033. else if (OpInfo.Type == InlineAsm::isClobber)
  7034. Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore);
  7035. }
  7036. }
  7037. unsigned get() const { return Flags; }
  7038. };
  7039. } // end anonymous namespace
  7040. /// visitInlineAsm - Handle a call to an InlineAsm object.
  7041. void SelectionDAGBuilder::visitInlineAsm(ImmutableCallSite CS) {
  7042. const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
  7043. /// ConstraintOperands - Information about all of the constraints.
  7044. SDISelAsmOperandInfoVector ConstraintOperands;
  7045. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  7046. TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints(
  7047. DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), CS);
  7048. // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack,
  7049. // AsmDialect, MayLoad, MayStore).
  7050. bool HasSideEffect = IA->hasSideEffects();
  7051. ExtraFlags ExtraInfo(CS);
  7052. unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
  7053. unsigned ResNo = 0; // ResNo - The result number of the next output.
  7054. for (auto &T : TargetConstraints) {
  7055. ConstraintOperands.push_back(SDISelAsmOperandInfo(T));
  7056. SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
  7057. // Compute the value type for each operand.
  7058. if (OpInfo.Type == InlineAsm::isInput ||
  7059. (OpInfo.Type == InlineAsm::isOutput && OpInfo.isIndirect)) {
  7060. OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
  7061. // Process the call argument. BasicBlocks are labels, currently appearing
  7062. // only in asm's.
  7063. const Instruction *I = CS.getInstruction();
  7064. if (isa<CallBrInst>(I) &&
  7065. (ArgNo - 1) >= (cast<CallBrInst>(I)->getNumArgOperands() -
  7066. cast<CallBrInst>(I)->getNumIndirectDests())) {
  7067. const auto *BA = cast<BlockAddress>(OpInfo.CallOperandVal);
  7068. EVT VT = TLI.getValueType(DAG.getDataLayout(), BA->getType(), true);
  7069. OpInfo.CallOperand = DAG.getTargetBlockAddress(BA, VT);
  7070. } else if (const auto *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) {
  7071. OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
  7072. } else {
  7073. OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
  7074. }
  7075. OpInfo.ConstraintVT =
  7076. OpInfo
  7077. .getCallOperandValEVT(*DAG.getContext(), TLI, DAG.getDataLayout())
  7078. .getSimpleVT();
  7079. } else if (OpInfo.Type == InlineAsm::isOutput && !OpInfo.isIndirect) {
  7080. // The return value of the call is this value. As such, there is no
  7081. // corresponding argument.
  7082. assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
  7083. if (StructType *STy = dyn_cast<StructType>(CS.getType())) {
  7084. OpInfo.ConstraintVT = TLI.getSimpleValueType(
  7085. DAG.getDataLayout(), STy->getElementType(ResNo));
  7086. } else {
  7087. assert(ResNo == 0 && "Asm only has one result!");
  7088. OpInfo.ConstraintVT =
  7089. TLI.getSimpleValueType(DAG.getDataLayout(), CS.getType());
  7090. }
  7091. ++ResNo;
  7092. } else {
  7093. OpInfo.ConstraintVT = MVT::Other;
  7094. }
  7095. if (!HasSideEffect)
  7096. HasSideEffect = OpInfo.hasMemory(TLI);
  7097. // Determine if this InlineAsm MayLoad or MayStore based on the constraints.
  7098. // FIXME: Could we compute this on OpInfo rather than T?
  7099. // Compute the constraint code and ConstraintType to use.
  7100. TLI.ComputeConstraintToUse(T, SDValue());
  7101. ExtraInfo.update(T);
  7102. }
  7103. // We won't need to flush pending loads if this asm doesn't touch
  7104. // memory and is nonvolatile.
  7105. SDValue Flag, Chain = (HasSideEffect) ? getRoot() : DAG.getRoot();
  7106. bool IsCallBr = isa<CallBrInst>(CS.getInstruction());
  7107. if (IsCallBr) {
  7108. // If this is a callbr we need to flush pending exports since inlineasm_br
  7109. // is a terminator. We need to do this before nodes are glued to
  7110. // the inlineasm_br node.
  7111. Chain = getControlRoot();
  7112. }
  7113. // Second pass over the constraints: compute which constraint option to use.
  7114. for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
  7115. // If this is an output operand with a matching input operand, look up the
  7116. // matching input. If their types mismatch, e.g. one is an integer, the
  7117. // other is floating point, or their sizes are different, flag it as an
  7118. // error.
  7119. if (OpInfo.hasMatchingInput()) {
  7120. SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
  7121. patchMatchingInput(OpInfo, Input, DAG);
  7122. }
  7123. // Compute the constraint code and ConstraintType to use.
  7124. TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
  7125. if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
  7126. OpInfo.Type == InlineAsm::isClobber)
  7127. continue;
  7128. // If this is a memory input, and if the operand is not indirect, do what we
  7129. // need to provide an address for the memory input.
  7130. if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
  7131. !OpInfo.isIndirect) {
  7132. assert((OpInfo.isMultipleAlternative ||
  7133. (OpInfo.Type == InlineAsm::isInput)) &&
  7134. "Can only indirectify direct input operands!");
  7135. // Memory operands really want the address of the value.
  7136. Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG);
  7137. // There is no longer a Value* corresponding to this operand.
  7138. OpInfo.CallOperandVal = nullptr;
  7139. // It is now an indirect operand.
  7140. OpInfo.isIndirect = true;
  7141. }
  7142. }
  7143. // AsmNodeOperands - The operands for the ISD::INLINEASM node.
  7144. std::vector<SDValue> AsmNodeOperands;
  7145. AsmNodeOperands.push_back(SDValue()); // reserve space for input chain
  7146. AsmNodeOperands.push_back(DAG.getTargetExternalSymbol(
  7147. IA->getAsmString().c_str(), TLI.getPointerTy(DAG.getDataLayout())));
  7148. // If we have a !srcloc metadata node associated with it, we want to attach
  7149. // this to the ultimately generated inline asm machineinstr. To do this, we
  7150. // pass in the third operand as this (potentially null) inline asm MDNode.
  7151. const MDNode *SrcLoc = CS.getInstruction()->getMetadata("srcloc");
  7152. AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc));
  7153. // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore
  7154. // bits as operand 3.
  7155. AsmNodeOperands.push_back(DAG.getTargetConstant(
  7156. ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
  7157. // Third pass: Loop over operands to prepare DAG-level operands.. As part of
  7158. // this, assign virtual and physical registers for inputs and otput.
  7159. for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
  7160. // Assign Registers.
  7161. SDISelAsmOperandInfo &RefOpInfo =
  7162. OpInfo.isMatchingInputConstraint()
  7163. ? ConstraintOperands[OpInfo.getMatchedOperand()]
  7164. : OpInfo;
  7165. GetRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo);
  7166. switch (OpInfo.Type) {
  7167. case InlineAsm::isOutput:
  7168. if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
  7169. (OpInfo.ConstraintType == TargetLowering::C_Other &&
  7170. OpInfo.isIndirect)) {
  7171. unsigned ConstraintID =
  7172. TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
  7173. assert(ConstraintID != InlineAsm::Constraint_Unknown &&
  7174. "Failed to convert memory constraint code to constraint id.");
  7175. // Add information to the INLINEASM node to know about this output.
  7176. unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
  7177. OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID);
  7178. AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(),
  7179. MVT::i32));
  7180. AsmNodeOperands.push_back(OpInfo.CallOperand);
  7181. break;
  7182. } else if ((OpInfo.ConstraintType == TargetLowering::C_Other &&
  7183. !OpInfo.isIndirect) ||
  7184. OpInfo.ConstraintType == TargetLowering::C_Register ||
  7185. OpInfo.ConstraintType == TargetLowering::C_RegisterClass) {
  7186. // Otherwise, this outputs to a register (directly for C_Register /
  7187. // C_RegisterClass, and a target-defined fashion for C_Other). Find a
  7188. // register that we can use.
  7189. if (OpInfo.AssignedRegs.Regs.empty()) {
  7190. emitInlineAsmError(
  7191. CS, "couldn't allocate output register for constraint '" +
  7192. Twine(OpInfo.ConstraintCode) + "'");
  7193. return;
  7194. }
  7195. // Add information to the INLINEASM node to know that this register is
  7196. // set.
  7197. OpInfo.AssignedRegs.AddInlineAsmOperands(
  7198. OpInfo.isEarlyClobber ? InlineAsm::Kind_RegDefEarlyClobber
  7199. : InlineAsm::Kind_RegDef,
  7200. false, 0, getCurSDLoc(), DAG, AsmNodeOperands);
  7201. }
  7202. break;
  7203. case InlineAsm::isInput: {
  7204. SDValue InOperandVal = OpInfo.CallOperand;
  7205. if (OpInfo.isMatchingInputConstraint()) {
  7206. // If this is required to match an output register we have already set,
  7207. // just use its register.
  7208. auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(),
  7209. AsmNodeOperands);
  7210. unsigned OpFlag =
  7211. cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
  7212. if (InlineAsm::isRegDefKind(OpFlag) ||
  7213. InlineAsm::isRegDefEarlyClobberKind(OpFlag)) {
  7214. // Add (OpFlag&0xffff)>>3 registers to MatchedRegs.
  7215. if (OpInfo.isIndirect) {
  7216. // This happens on gcc/testsuite/gcc.dg/pr8788-1.c
  7217. emitInlineAsmError(CS, "inline asm not supported yet:"
  7218. " don't know how to handle tied "
  7219. "indirect register inputs");
  7220. return;
  7221. }
  7222. MVT RegVT = AsmNodeOperands[CurOp+1].getSimpleValueType();
  7223. SmallVector<unsigned, 4> Regs;
  7224. if (const TargetRegisterClass *RC = TLI.getRegClassFor(RegVT)) {
  7225. unsigned NumRegs = InlineAsm::getNumOperandRegisters(OpFlag);
  7226. MachineRegisterInfo &RegInfo =
  7227. DAG.getMachineFunction().getRegInfo();
  7228. for (unsigned i = 0; i != NumRegs; ++i)
  7229. Regs.push_back(RegInfo.createVirtualRegister(RC));
  7230. } else {
  7231. emitInlineAsmError(CS, "inline asm error: This value type register "
  7232. "class is not natively supported!");
  7233. return;
  7234. }
  7235. RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType());
  7236. SDLoc dl = getCurSDLoc();
  7237. // Use the produced MatchedRegs object to
  7238. MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag,
  7239. CS.getInstruction());
  7240. MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse,
  7241. true, OpInfo.getMatchedOperand(), dl,
  7242. DAG, AsmNodeOperands);
  7243. break;
  7244. }
  7245. assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!");
  7246. assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 &&
  7247. "Unexpected number of operands");
  7248. // Add information to the INLINEASM node to know about this input.
  7249. // See InlineAsm.h isUseOperandTiedToDef.
  7250. OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag);
  7251. OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag,
  7252. OpInfo.getMatchedOperand());
  7253. AsmNodeOperands.push_back(DAG.getTargetConstant(
  7254. OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
  7255. AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
  7256. break;
  7257. }
  7258. // Treat indirect 'X' constraint as memory.
  7259. if (OpInfo.ConstraintType == TargetLowering::C_Other &&
  7260. OpInfo.isIndirect)
  7261. OpInfo.ConstraintType = TargetLowering::C_Memory;
  7262. if (OpInfo.ConstraintType == TargetLowering::C_Other) {
  7263. std::vector<SDValue> Ops;
  7264. TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode,
  7265. Ops, DAG);
  7266. if (Ops.empty()) {
  7267. emitInlineAsmError(CS, "invalid operand for inline asm constraint '" +
  7268. Twine(OpInfo.ConstraintCode) + "'");
  7269. return;
  7270. }
  7271. // Add information to the INLINEASM node to know about this input.
  7272. unsigned ResOpType =
  7273. InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size());
  7274. AsmNodeOperands.push_back(DAG.getTargetConstant(
  7275. ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
  7276. AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
  7277. break;
  7278. }
  7279. if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
  7280. assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
  7281. assert(InOperandVal.getValueType() ==
  7282. TLI.getPointerTy(DAG.getDataLayout()) &&
  7283. "Memory operands expect pointer values");
  7284. unsigned ConstraintID =
  7285. TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
  7286. assert(ConstraintID != InlineAsm::Constraint_Unknown &&
  7287. "Failed to convert memory constraint code to constraint id.");
  7288. // Add information to the INLINEASM node to know about this input.
  7289. unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
  7290. ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID);
  7291. AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
  7292. getCurSDLoc(),
  7293. MVT::i32));
  7294. AsmNodeOperands.push_back(InOperandVal);
  7295. break;
  7296. }
  7297. assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
  7298. OpInfo.ConstraintType == TargetLowering::C_Register) &&
  7299. "Unknown constraint type!");
  7300. // TODO: Support this.
  7301. if (OpInfo.isIndirect) {
  7302. emitInlineAsmError(
  7303. CS, "Don't know how to handle indirect register inputs yet "
  7304. "for constraint '" +
  7305. Twine(OpInfo.ConstraintCode) + "'");
  7306. return;
  7307. }
  7308. // Copy the input into the appropriate registers.
  7309. if (OpInfo.AssignedRegs.Regs.empty()) {
  7310. emitInlineAsmError(CS, "couldn't allocate input reg for constraint '" +
  7311. Twine(OpInfo.ConstraintCode) + "'");
  7312. return;
  7313. }
  7314. SDLoc dl = getCurSDLoc();
  7315. OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl,
  7316. Chain, &Flag, CS.getInstruction());
  7317. OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0,
  7318. dl, DAG, AsmNodeOperands);
  7319. break;
  7320. }
  7321. case InlineAsm::isClobber:
  7322. // Add the clobbered value to the operand list, so that the register
  7323. // allocator is aware that the physreg got clobbered.
  7324. if (!OpInfo.AssignedRegs.Regs.empty())
  7325. OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber,
  7326. false, 0, getCurSDLoc(), DAG,
  7327. AsmNodeOperands);
  7328. break;
  7329. }
  7330. }
  7331. // Finish up input operands. Set the input chain and add the flag last.
  7332. AsmNodeOperands[InlineAsm::Op_InputChain] = Chain;
  7333. if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
  7334. unsigned ISDOpc = IsCallBr ? ISD::INLINEASM_BR : ISD::INLINEASM;
  7335. Chain = DAG.getNode(ISDOpc, getCurSDLoc(),
  7336. DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands);
  7337. Flag = Chain.getValue(1);
  7338. // Do additional work to generate outputs.
  7339. SmallVector<EVT, 1> ResultVTs;
  7340. SmallVector<SDValue, 1> ResultValues;
  7341. SmallVector<SDValue, 8> OutChains;
  7342. llvm::Type *CSResultType = CS.getType();
  7343. ArrayRef<Type *> ResultTypes;
  7344. if (StructType *StructResult = dyn_cast<StructType>(CSResultType))
  7345. ResultTypes = StructResult->elements();
  7346. else if (!CSResultType->isVoidTy())
  7347. ResultTypes = makeArrayRef(CSResultType);
  7348. auto CurResultType = ResultTypes.begin();
  7349. auto handleRegAssign = [&](SDValue V) {
  7350. assert(CurResultType != ResultTypes.end() && "Unexpected value");
  7351. assert((*CurResultType)->isSized() && "Unexpected unsized type");
  7352. EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType);
  7353. ++CurResultType;
  7354. // If the type of the inline asm call site return value is different but has
  7355. // same size as the type of the asm output bitcast it. One example of this
  7356. // is for vectors with different width / number of elements. This can
  7357. // happen for register classes that can contain multiple different value
  7358. // types. The preg or vreg allocated may not have the same VT as was
  7359. // expected.
  7360. //
  7361. // This can also happen for a return value that disagrees with the register
  7362. // class it is put in, eg. a double in a general-purpose register on a
  7363. // 32-bit machine.
  7364. if (ResultVT != V.getValueType() &&
  7365. ResultVT.getSizeInBits() == V.getValueSizeInBits())
  7366. V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V);
  7367. else if (ResultVT != V.getValueType() && ResultVT.isInteger() &&
  7368. V.getValueType().isInteger()) {
  7369. // If a result value was tied to an input value, the computed result
  7370. // may have a wider width than the expected result. Extract the
  7371. // relevant portion.
  7372. V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V);
  7373. }
  7374. assert(ResultVT == V.getValueType() && "Asm result value mismatch!");
  7375. ResultVTs.push_back(ResultVT);
  7376. ResultValues.push_back(V);
  7377. };
  7378. // Deal with output operands.
  7379. for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
  7380. if (OpInfo.Type == InlineAsm::isOutput) {
  7381. SDValue Val;
  7382. // Skip trivial output operands.
  7383. if (OpInfo.AssignedRegs.Regs.empty())
  7384. continue;
  7385. switch (OpInfo.ConstraintType) {
  7386. case TargetLowering::C_Register:
  7387. case TargetLowering::C_RegisterClass:
  7388. Val = OpInfo.AssignedRegs.getCopyFromRegs(
  7389. DAG, FuncInfo, getCurSDLoc(), Chain, &Flag, CS.getInstruction());
  7390. break;
  7391. case TargetLowering::C_Other:
  7392. Val = TLI.LowerAsmOutputForConstraint(Chain, Flag, getCurSDLoc(),
  7393. OpInfo, DAG);
  7394. break;
  7395. case TargetLowering::C_Memory:
  7396. break; // Already handled.
  7397. case TargetLowering::C_Unknown:
  7398. assert(false && "Unexpected unknown constraint");
  7399. }
  7400. // Indirect output manifest as stores. Record output chains.
  7401. if (OpInfo.isIndirect) {
  7402. const Value *Ptr = OpInfo.CallOperandVal;
  7403. assert(Ptr && "Expected value CallOperandVal for indirect asm operand");
  7404. SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr),
  7405. MachinePointerInfo(Ptr));
  7406. OutChains.push_back(Store);
  7407. } else {
  7408. // generate CopyFromRegs to associated registers.
  7409. assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
  7410. if (Val.getOpcode() == ISD::MERGE_VALUES) {
  7411. for (const SDValue &V : Val->op_values())
  7412. handleRegAssign(V);
  7413. } else
  7414. handleRegAssign(Val);
  7415. }
  7416. }
  7417. }
  7418. // Set results.
  7419. if (!ResultValues.empty()) {
  7420. assert(CurResultType == ResultTypes.end() &&
  7421. "Mismatch in number of ResultTypes");
  7422. assert(ResultValues.size() == ResultTypes.size() &&
  7423. "Mismatch in number of output operands in asm result");
  7424. SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
  7425. DAG.getVTList(ResultVTs), ResultValues);
  7426. setValue(CS.getInstruction(), V);
  7427. }
  7428. // Collect store chains.
  7429. if (!OutChains.empty())
  7430. Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains);
  7431. // Only Update Root if inline assembly has a memory effect.
  7432. if (ResultValues.empty() || HasSideEffect || !OutChains.empty() || IsCallBr)
  7433. DAG.setRoot(Chain);
  7434. }
  7435. void SelectionDAGBuilder::emitInlineAsmError(ImmutableCallSite CS,
  7436. const Twine &Message) {
  7437. LLVMContext &Ctx = *DAG.getContext();
  7438. Ctx.emitError(CS.getInstruction(), Message);
  7439. // Make sure we leave the DAG in a valid state
  7440. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  7441. SmallVector<EVT, 1> ValueVTs;
  7442. ComputeValueVTs(TLI, DAG.getDataLayout(), CS->getType(), ValueVTs);
  7443. if (ValueVTs.empty())
  7444. return;
  7445. SmallVector<SDValue, 1> Ops;
  7446. for (unsigned i = 0, e = ValueVTs.size(); i != e; ++i)
  7447. Ops.push_back(DAG.getUNDEF(ValueVTs[i]));
  7448. setValue(CS.getInstruction(), DAG.getMergeValues(Ops, getCurSDLoc()));
  7449. }
  7450. void SelectionDAGBuilder::visitVAStart(const CallInst &I) {
  7451. DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(),
  7452. MVT::Other, getRoot(),
  7453. getValue(I.getArgOperand(0)),
  7454. DAG.getSrcValue(I.getArgOperand(0))));
  7455. }
  7456. void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) {
  7457. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  7458. const DataLayout &DL = DAG.getDataLayout();
  7459. SDValue V = DAG.getVAArg(
  7460. TLI.getMemValueType(DAG.getDataLayout(), I.getType()), getCurSDLoc(),
  7461. getRoot(), getValue(I.getOperand(0)), DAG.getSrcValue(I.getOperand(0)),
  7462. DL.getABITypeAlignment(I.getType()));
  7463. DAG.setRoot(V.getValue(1));
  7464. if (I.getType()->isPointerTy())
  7465. V = DAG.getPtrExtOrTrunc(
  7466. V, getCurSDLoc(), TLI.getValueType(DAG.getDataLayout(), I.getType()));
  7467. setValue(&I, V);
  7468. }
  7469. void SelectionDAGBuilder::visitVAEnd(const CallInst &I) {
  7470. DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(),
  7471. MVT::Other, getRoot(),
  7472. getValue(I.getArgOperand(0)),
  7473. DAG.getSrcValue(I.getArgOperand(0))));
  7474. }
  7475. void SelectionDAGBuilder::visitVACopy(const CallInst &I) {
  7476. DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(),
  7477. MVT::Other, getRoot(),
  7478. getValue(I.getArgOperand(0)),
  7479. getValue(I.getArgOperand(1)),
  7480. DAG.getSrcValue(I.getArgOperand(0)),
  7481. DAG.getSrcValue(I.getArgOperand(1))));
  7482. }
  7483. SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG,
  7484. const Instruction &I,
  7485. SDValue Op) {
  7486. const MDNode *Range = I.getMetadata(LLVMContext::MD_range);
  7487. if (!Range)
  7488. return Op;
  7489. ConstantRange CR = getConstantRangeFromMetadata(*Range);
  7490. if (CR.isFullSet() || CR.isEmptySet() || CR.isUpperWrapped())
  7491. return Op;
  7492. APInt Lo = CR.getUnsignedMin();
  7493. if (!Lo.isMinValue())
  7494. return Op;
  7495. APInt Hi = CR.getUnsignedMax();
  7496. unsigned Bits = std::max(Hi.getActiveBits(),
  7497. static_cast<unsigned>(IntegerType::MIN_INT_BITS));
  7498. EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
  7499. SDLoc SL = getCurSDLoc();
  7500. SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op,
  7501. DAG.getValueType(SmallVT));
  7502. unsigned NumVals = Op.getNode()->getNumValues();
  7503. if (NumVals == 1)
  7504. return ZExt;
  7505. SmallVector<SDValue, 4> Ops;
  7506. Ops.push_back(ZExt);
  7507. for (unsigned I = 1; I != NumVals; ++I)
  7508. Ops.push_back(Op.getValue(I));
  7509. return DAG.getMergeValues(Ops, SL);
  7510. }
  7511. /// Populate a CallLowerinInfo (into \p CLI) based on the properties of
  7512. /// the call being lowered.
  7513. ///
  7514. /// This is a helper for lowering intrinsics that follow a target calling
  7515. /// convention or require stack pointer adjustment. Only a subset of the
  7516. /// intrinsic's operands need to participate in the calling convention.
  7517. void SelectionDAGBuilder::populateCallLoweringInfo(
  7518. TargetLowering::CallLoweringInfo &CLI, const CallBase *Call,
  7519. unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy,
  7520. bool IsPatchPoint) {
  7521. TargetLowering::ArgListTy Args;
  7522. Args.reserve(NumArgs);
  7523. // Populate the argument list.
  7524. // Attributes for args start at offset 1, after the return attribute.
  7525. for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs;
  7526. ArgI != ArgE; ++ArgI) {
  7527. const Value *V = Call->getOperand(ArgI);
  7528. assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic.");
  7529. TargetLowering::ArgListEntry Entry;
  7530. Entry.Node = getValue(V);
  7531. Entry.Ty = V->getType();
  7532. Entry.setAttributes(Call, ArgI);
  7533. Args.push_back(Entry);
  7534. }
  7535. CLI.setDebugLoc(getCurSDLoc())
  7536. .setChain(getRoot())
  7537. .setCallee(Call->getCallingConv(), ReturnTy, Callee, std::move(Args))
  7538. .setDiscardResult(Call->use_empty())
  7539. .setIsPatchPoint(IsPatchPoint);
  7540. }
  7541. /// Add a stack map intrinsic call's live variable operands to a stackmap
  7542. /// or patchpoint target node's operand list.
  7543. ///
  7544. /// Constants are converted to TargetConstants purely as an optimization to
  7545. /// avoid constant materialization and register allocation.
  7546. ///
  7547. /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not
  7548. /// generate addess computation nodes, and so FinalizeISel can convert the
  7549. /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids
  7550. /// address materialization and register allocation, but may also be required
  7551. /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an
  7552. /// alloca in the entry block, then the runtime may assume that the alloca's
  7553. /// StackMap location can be read immediately after compilation and that the
  7554. /// location is valid at any point during execution (this is similar to the
  7555. /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were
  7556. /// only available in a register, then the runtime would need to trap when
  7557. /// execution reaches the StackMap in order to read the alloca's location.
  7558. static void addStackMapLiveVars(ImmutableCallSite CS, unsigned StartIdx,
  7559. const SDLoc &DL, SmallVectorImpl<SDValue> &Ops,
  7560. SelectionDAGBuilder &Builder) {
  7561. for (unsigned i = StartIdx, e = CS.arg_size(); i != e; ++i) {
  7562. SDValue OpVal = Builder.getValue(CS.getArgument(i));
  7563. if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(OpVal)) {
  7564. Ops.push_back(
  7565. Builder.DAG.getTargetConstant(StackMaps::ConstantOp, DL, MVT::i64));
  7566. Ops.push_back(
  7567. Builder.DAG.getTargetConstant(C->getSExtValue(), DL, MVT::i64));
  7568. } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(OpVal)) {
  7569. const TargetLowering &TLI = Builder.DAG.getTargetLoweringInfo();
  7570. Ops.push_back(Builder.DAG.getTargetFrameIndex(
  7571. FI->getIndex(), TLI.getFrameIndexTy(Builder.DAG.getDataLayout())));
  7572. } else
  7573. Ops.push_back(OpVal);
  7574. }
  7575. }
  7576. /// Lower llvm.experimental.stackmap directly to its target opcode.
  7577. void SelectionDAGBuilder::visitStackmap(const CallInst &CI) {
  7578. // void @llvm.experimental.stackmap(i32 <id>, i32 <numShadowBytes>,
  7579. // [live variables...])
  7580. assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value.");
  7581. SDValue Chain, InFlag, Callee, NullPtr;
  7582. SmallVector<SDValue, 32> Ops;
  7583. SDLoc DL = getCurSDLoc();
  7584. Callee = getValue(CI.getCalledValue());
  7585. NullPtr = DAG.getIntPtrConstant(0, DL, true);
  7586. // The stackmap intrinsic only records the live variables (the arguemnts
  7587. // passed to it) and emits NOPS (if requested). Unlike the patchpoint
  7588. // intrinsic, this won't be lowered to a function call. This means we don't
  7589. // have to worry about calling conventions and target specific lowering code.
  7590. // Instead we perform the call lowering right here.
  7591. //
  7592. // chain, flag = CALLSEQ_START(chain, 0, 0)
  7593. // chain, flag = STACKMAP(id, nbytes, ..., chain, flag)
  7594. // chain, flag = CALLSEQ_END(chain, 0, 0, flag)
  7595. //
  7596. Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL);
  7597. InFlag = Chain.getValue(1);
  7598. // Add the <id> and <numBytes> constants.
  7599. SDValue IDVal = getValue(CI.getOperand(PatchPointOpers::IDPos));
  7600. Ops.push_back(DAG.getTargetConstant(
  7601. cast<ConstantSDNode>(IDVal)->getZExtValue(), DL, MVT::i64));
  7602. SDValue NBytesVal = getValue(CI.getOperand(PatchPointOpers::NBytesPos));
  7603. Ops.push_back(DAG.getTargetConstant(
  7604. cast<ConstantSDNode>(NBytesVal)->getZExtValue(), DL,
  7605. MVT::i32));
  7606. // Push live variables for the stack map.
  7607. addStackMapLiveVars(&CI, 2, DL, Ops, *this);
  7608. // We are not pushing any register mask info here on the operands list,
  7609. // because the stackmap doesn't clobber anything.
  7610. // Push the chain and the glue flag.
  7611. Ops.push_back(Chain);
  7612. Ops.push_back(InFlag);
  7613. // Create the STACKMAP node.
  7614. SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
  7615. SDNode *SM = DAG.getMachineNode(TargetOpcode::STACKMAP, DL, NodeTys, Ops);
  7616. Chain = SDValue(SM, 0);
  7617. InFlag = Chain.getValue(1);
  7618. Chain = DAG.getCALLSEQ_END(Chain, NullPtr, NullPtr, InFlag, DL);
  7619. // Stackmaps don't generate values, so nothing goes into the NodeMap.
  7620. // Set the root to the target-lowered call chain.
  7621. DAG.setRoot(Chain);
  7622. // Inform the Frame Information that we have a stackmap in this function.
  7623. FuncInfo.MF->getFrameInfo().setHasStackMap();
  7624. }
  7625. /// Lower llvm.experimental.patchpoint directly to its target opcode.
  7626. void SelectionDAGBuilder::visitPatchpoint(ImmutableCallSite CS,
  7627. const BasicBlock *EHPadBB) {
  7628. // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>,
  7629. // i32 <numBytes>,
  7630. // i8* <target>,
  7631. // i32 <numArgs>,
  7632. // [Args...],
  7633. // [live variables...])
  7634. CallingConv::ID CC = CS.getCallingConv();
  7635. bool IsAnyRegCC = CC == CallingConv::AnyReg;
  7636. bool HasDef = !CS->getType()->isVoidTy();
  7637. SDLoc dl = getCurSDLoc();
  7638. SDValue Callee = getValue(CS->getOperand(PatchPointOpers::TargetPos));
  7639. // Handle immediate and symbolic callees.
  7640. if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee))
  7641. Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl,
  7642. /*isTarget=*/true);
  7643. else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee))
  7644. Callee = DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(),
  7645. SDLoc(SymbolicCallee),
  7646. SymbolicCallee->getValueType(0));
  7647. // Get the real number of arguments participating in the call <numArgs>
  7648. SDValue NArgVal = getValue(CS.getArgument(PatchPointOpers::NArgPos));
  7649. unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue();
  7650. // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs>
  7651. // Intrinsics include all meta-operands up to but not including CC.
  7652. unsigned NumMetaOpers = PatchPointOpers::CCPos;
  7653. assert(CS.arg_size() >= NumMetaOpers + NumArgs &&
  7654. "Not enough arguments provided to the patchpoint intrinsic");
  7655. // For AnyRegCC the arguments are lowered later on manually.
  7656. unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs;
  7657. Type *ReturnTy =
  7658. IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CS->getType();
  7659. TargetLowering::CallLoweringInfo CLI(DAG);
  7660. populateCallLoweringInfo(CLI, cast<CallBase>(CS.getInstruction()),
  7661. NumMetaOpers, NumCallArgs, Callee, ReturnTy, true);
  7662. std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
  7663. SDNode *CallEnd = Result.second.getNode();
  7664. if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg))
  7665. CallEnd = CallEnd->getOperand(0).getNode();
  7666. /// Get a call instruction from the call sequence chain.
  7667. /// Tail calls are not allowed.
  7668. assert(CallEnd->getOpcode() == ISD::CALLSEQ_END &&
  7669. "Expected a callseq node.");
  7670. SDNode *Call = CallEnd->getOperand(0).getNode();
  7671. bool HasGlue = Call->getGluedNode();
  7672. // Replace the target specific call node with the patchable intrinsic.
  7673. SmallVector<SDValue, 8> Ops;
  7674. // Add the <id> and <numBytes> constants.
  7675. SDValue IDVal = getValue(CS->getOperand(PatchPointOpers::IDPos));
  7676. Ops.push_back(DAG.getTargetConstant(
  7677. cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64));
  7678. SDValue NBytesVal = getValue(CS->getOperand(PatchPointOpers::NBytesPos));
  7679. Ops.push_back(DAG.getTargetConstant(
  7680. cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl,
  7681. MVT::i32));
  7682. // Add the callee.
  7683. Ops.push_back(Callee);
  7684. // Adjust <numArgs> to account for any arguments that have been passed on the
  7685. // stack instead.
  7686. // Call Node: Chain, Target, {Args}, RegMask, [Glue]
  7687. unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3);
  7688. NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs;
  7689. Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32));
  7690. // Add the calling convention
  7691. Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32));
  7692. // Add the arguments we omitted previously. The register allocator should
  7693. // place these in any free register.
  7694. if (IsAnyRegCC)
  7695. for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i)
  7696. Ops.push_back(getValue(CS.getArgument(i)));
  7697. // Push the arguments from the call instruction up to the register mask.
  7698. SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1;
  7699. Ops.append(Call->op_begin() + 2, e);
  7700. // Push live variables for the stack map.
  7701. addStackMapLiveVars(CS, NumMetaOpers + NumArgs, dl, Ops, *this);
  7702. // Push the register mask info.
  7703. if (HasGlue)
  7704. Ops.push_back(*(Call->op_end()-2));
  7705. else
  7706. Ops.push_back(*(Call->op_end()-1));
  7707. // Push the chain (this is originally the first operand of the call, but
  7708. // becomes now the last or second to last operand).
  7709. Ops.push_back(*(Call->op_begin()));
  7710. // Push the glue flag (last operand).
  7711. if (HasGlue)
  7712. Ops.push_back(*(Call->op_end()-1));
  7713. SDVTList NodeTys;
  7714. if (IsAnyRegCC && HasDef) {
  7715. // Create the return types based on the intrinsic definition
  7716. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  7717. SmallVector<EVT, 3> ValueVTs;
  7718. ComputeValueVTs(TLI, DAG.getDataLayout(), CS->getType(), ValueVTs);
  7719. assert(ValueVTs.size() == 1 && "Expected only one return value type.");
  7720. // There is always a chain and a glue type at the end
  7721. ValueVTs.push_back(MVT::Other);
  7722. ValueVTs.push_back(MVT::Glue);
  7723. NodeTys = DAG.getVTList(ValueVTs);
  7724. } else
  7725. NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
  7726. // Replace the target specific call node with a PATCHPOINT node.
  7727. MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHPOINT,
  7728. dl, NodeTys, Ops);
  7729. // Update the NodeMap.
  7730. if (HasDef) {
  7731. if (IsAnyRegCC)
  7732. setValue(CS.getInstruction(), SDValue(MN, 0));
  7733. else
  7734. setValue(CS.getInstruction(), Result.first);
  7735. }
  7736. // Fixup the consumers of the intrinsic. The chain and glue may be used in the
  7737. // call sequence. Furthermore the location of the chain and glue can change
  7738. // when the AnyReg calling convention is used and the intrinsic returns a
  7739. // value.
  7740. if (IsAnyRegCC && HasDef) {
  7741. SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)};
  7742. SDValue To[] = {SDValue(MN, 1), SDValue(MN, 2)};
  7743. DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
  7744. } else
  7745. DAG.ReplaceAllUsesWith(Call, MN);
  7746. DAG.DeleteNode(Call);
  7747. // Inform the Frame Information that we have a patchpoint in this function.
  7748. FuncInfo.MF->getFrameInfo().setHasPatchPoint();
  7749. }
  7750. void SelectionDAGBuilder::visitVectorReduce(const CallInst &I,
  7751. unsigned Intrinsic) {
  7752. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  7753. SDValue Op1 = getValue(I.getArgOperand(0));
  7754. SDValue Op2;
  7755. if (I.getNumArgOperands() > 1)
  7756. Op2 = getValue(I.getArgOperand(1));
  7757. SDLoc dl = getCurSDLoc();
  7758. EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  7759. SDValue Res;
  7760. FastMathFlags FMF;
  7761. if (isa<FPMathOperator>(I))
  7762. FMF = I.getFastMathFlags();
  7763. switch (Intrinsic) {
  7764. case Intrinsic::experimental_vector_reduce_v2_fadd:
  7765. if (FMF.allowReassoc())
  7766. Res = DAG.getNode(ISD::FADD, dl, VT, Op1,
  7767. DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2));
  7768. else
  7769. Res = DAG.getNode(ISD::VECREDUCE_STRICT_FADD, dl, VT, Op1, Op2);
  7770. break;
  7771. case Intrinsic::experimental_vector_reduce_v2_fmul:
  7772. if (FMF.allowReassoc())
  7773. Res = DAG.getNode(ISD::FMUL, dl, VT, Op1,
  7774. DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2));
  7775. else
  7776. Res = DAG.getNode(ISD::VECREDUCE_STRICT_FMUL, dl, VT, Op1, Op2);
  7777. break;
  7778. case Intrinsic::experimental_vector_reduce_add:
  7779. Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1);
  7780. break;
  7781. case Intrinsic::experimental_vector_reduce_mul:
  7782. Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1);
  7783. break;
  7784. case Intrinsic::experimental_vector_reduce_and:
  7785. Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1);
  7786. break;
  7787. case Intrinsic::experimental_vector_reduce_or:
  7788. Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1);
  7789. break;
  7790. case Intrinsic::experimental_vector_reduce_xor:
  7791. Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1);
  7792. break;
  7793. case Intrinsic::experimental_vector_reduce_smax:
  7794. Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1);
  7795. break;
  7796. case Intrinsic::experimental_vector_reduce_smin:
  7797. Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1);
  7798. break;
  7799. case Intrinsic::experimental_vector_reduce_umax:
  7800. Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1);
  7801. break;
  7802. case Intrinsic::experimental_vector_reduce_umin:
  7803. Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1);
  7804. break;
  7805. case Intrinsic::experimental_vector_reduce_fmax:
  7806. Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1);
  7807. break;
  7808. case Intrinsic::experimental_vector_reduce_fmin:
  7809. Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1);
  7810. break;
  7811. default:
  7812. llvm_unreachable("Unhandled vector reduce intrinsic");
  7813. }
  7814. setValue(&I, Res);
  7815. }
  7816. /// Returns an AttributeList representing the attributes applied to the return
  7817. /// value of the given call.
  7818. static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) {
  7819. SmallVector<Attribute::AttrKind, 2> Attrs;
  7820. if (CLI.RetSExt)
  7821. Attrs.push_back(Attribute::SExt);
  7822. if (CLI.RetZExt)
  7823. Attrs.push_back(Attribute::ZExt);
  7824. if (CLI.IsInReg)
  7825. Attrs.push_back(Attribute::InReg);
  7826. return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex,
  7827. Attrs);
  7828. }
  7829. /// TargetLowering::LowerCallTo - This is the default LowerCallTo
  7830. /// implementation, which just calls LowerCall.
  7831. /// FIXME: When all targets are
  7832. /// migrated to using LowerCall, this hook should be integrated into SDISel.
  7833. std::pair<SDValue, SDValue>
  7834. TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const {
  7835. // Handle the incoming return values from the call.
  7836. CLI.Ins.clear();
  7837. Type *OrigRetTy = CLI.RetTy;
  7838. SmallVector<EVT, 4> RetTys;
  7839. SmallVector<uint64_t, 4> Offsets;
  7840. auto &DL = CLI.DAG.getDataLayout();
  7841. ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets);
  7842. if (CLI.IsPostTypeLegalization) {
  7843. // If we are lowering a libcall after legalization, split the return type.
  7844. SmallVector<EVT, 4> OldRetTys;
  7845. SmallVector<uint64_t, 4> OldOffsets;
  7846. RetTys.swap(OldRetTys);
  7847. Offsets.swap(OldOffsets);
  7848. for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) {
  7849. EVT RetVT = OldRetTys[i];
  7850. uint64_t Offset = OldOffsets[i];
  7851. MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT);
  7852. unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT);
  7853. unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8;
  7854. RetTys.append(NumRegs, RegisterVT);
  7855. for (unsigned j = 0; j != NumRegs; ++j)
  7856. Offsets.push_back(Offset + j * RegisterVTByteSZ);
  7857. }
  7858. }
  7859. SmallVector<ISD::OutputArg, 4> Outs;
  7860. GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL);
  7861. bool CanLowerReturn =
  7862. this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(),
  7863. CLI.IsVarArg, Outs, CLI.RetTy->getContext());
  7864. SDValue DemoteStackSlot;
  7865. int DemoteStackIdx = -100;
  7866. if (!CanLowerReturn) {
  7867. // FIXME: equivalent assert?
  7868. // assert(!CS.hasInAllocaArgument() &&
  7869. // "sret demotion is incompatible with inalloca");
  7870. uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy);
  7871. unsigned Align = DL.getPrefTypeAlignment(CLI.RetTy);
  7872. MachineFunction &MF = CLI.DAG.getMachineFunction();
  7873. DemoteStackIdx = MF.getFrameInfo().CreateStackObject(TySize, Align, false);
  7874. Type *StackSlotPtrType = PointerType::get(CLI.RetTy,
  7875. DL.getAllocaAddrSpace());
  7876. DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL));
  7877. ArgListEntry Entry;
  7878. Entry.Node = DemoteStackSlot;
  7879. Entry.Ty = StackSlotPtrType;
  7880. Entry.IsSExt = false;
  7881. Entry.IsZExt = false;
  7882. Entry.IsInReg = false;
  7883. Entry.IsSRet = true;
  7884. Entry.IsNest = false;
  7885. Entry.IsByVal = false;
  7886. Entry.IsReturned = false;
  7887. Entry.IsSwiftSelf = false;
  7888. Entry.IsSwiftError = false;
  7889. Entry.Alignment = Align;
  7890. CLI.getArgs().insert(CLI.getArgs().begin(), Entry);
  7891. CLI.NumFixedArgs += 1;
  7892. CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext());
  7893. // sret demotion isn't compatible with tail-calls, since the sret argument
  7894. // points into the callers stack frame.
  7895. CLI.IsTailCall = false;
  7896. } else {
  7897. bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
  7898. CLI.RetTy, CLI.CallConv, CLI.IsVarArg);
  7899. for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
  7900. ISD::ArgFlagsTy Flags;
  7901. if (NeedsRegBlock) {
  7902. Flags.setInConsecutiveRegs();
  7903. if (I == RetTys.size() - 1)
  7904. Flags.setInConsecutiveRegsLast();
  7905. }
  7906. EVT VT = RetTys[I];
  7907. MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
  7908. CLI.CallConv, VT);
  7909. unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
  7910. CLI.CallConv, VT);
  7911. for (unsigned i = 0; i != NumRegs; ++i) {
  7912. ISD::InputArg MyFlags;
  7913. MyFlags.Flags = Flags;
  7914. MyFlags.VT = RegisterVT;
  7915. MyFlags.ArgVT = VT;
  7916. MyFlags.Used = CLI.IsReturnValueUsed;
  7917. if (CLI.RetTy->isPointerTy()) {
  7918. MyFlags.Flags.setPointer();
  7919. MyFlags.Flags.setPointerAddrSpace(
  7920. cast<PointerType>(CLI.RetTy)->getAddressSpace());
  7921. }
  7922. if (CLI.RetSExt)
  7923. MyFlags.Flags.setSExt();
  7924. if (CLI.RetZExt)
  7925. MyFlags.Flags.setZExt();
  7926. if (CLI.IsInReg)
  7927. MyFlags.Flags.setInReg();
  7928. CLI.Ins.push_back(MyFlags);
  7929. }
  7930. }
  7931. }
  7932. // We push in swifterror return as the last element of CLI.Ins.
  7933. ArgListTy &Args = CLI.getArgs();
  7934. if (supportSwiftError()) {
  7935. for (unsigned i = 0, e = Args.size(); i != e; ++i) {
  7936. if (Args[i].IsSwiftError) {
  7937. ISD::InputArg MyFlags;
  7938. MyFlags.VT = getPointerTy(DL);
  7939. MyFlags.ArgVT = EVT(getPointerTy(DL));
  7940. MyFlags.Flags.setSwiftError();
  7941. CLI.Ins.push_back(MyFlags);
  7942. }
  7943. }
  7944. }
  7945. // Handle all of the outgoing arguments.
  7946. CLI.Outs.clear();
  7947. CLI.OutVals.clear();
  7948. for (unsigned i = 0, e = Args.size(); i != e; ++i) {
  7949. SmallVector<EVT, 4> ValueVTs;
  7950. ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs);
  7951. // FIXME: Split arguments if CLI.IsPostTypeLegalization
  7952. Type *FinalType = Args[i].Ty;
  7953. if (Args[i].IsByVal)
  7954. FinalType = cast<PointerType>(Args[i].Ty)->getElementType();
  7955. bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
  7956. FinalType, CLI.CallConv, CLI.IsVarArg);
  7957. for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues;
  7958. ++Value) {
  7959. EVT VT = ValueVTs[Value];
  7960. Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext());
  7961. SDValue Op = SDValue(Args[i].Node.getNode(),
  7962. Args[i].Node.getResNo() + Value);
  7963. ISD::ArgFlagsTy Flags;
  7964. // Certain targets (such as MIPS), may have a different ABI alignment
  7965. // for a type depending on the context. Give the target a chance to
  7966. // specify the alignment it wants.
  7967. unsigned OriginalAlignment = getABIAlignmentForCallingConv(ArgTy, DL);
  7968. if (Args[i].Ty->isPointerTy()) {
  7969. Flags.setPointer();
  7970. Flags.setPointerAddrSpace(
  7971. cast<PointerType>(Args[i].Ty)->getAddressSpace());
  7972. }
  7973. if (Args[i].IsZExt)
  7974. Flags.setZExt();
  7975. if (Args[i].IsSExt)
  7976. Flags.setSExt();
  7977. if (Args[i].IsInReg) {
  7978. // If we are using vectorcall calling convention, a structure that is
  7979. // passed InReg - is surely an HVA
  7980. if (CLI.CallConv == CallingConv::X86_VectorCall &&
  7981. isa<StructType>(FinalType)) {
  7982. // The first value of a structure is marked
  7983. if (0 == Value)
  7984. Flags.setHvaStart();
  7985. Flags.setHva();
  7986. }
  7987. // Set InReg Flag
  7988. Flags.setInReg();
  7989. }
  7990. if (Args[i].IsSRet)
  7991. Flags.setSRet();
  7992. if (Args[i].IsSwiftSelf)
  7993. Flags.setSwiftSelf();
  7994. if (Args[i].IsSwiftError)
  7995. Flags.setSwiftError();
  7996. if (Args[i].IsByVal)
  7997. Flags.setByVal();
  7998. if (Args[i].IsInAlloca) {
  7999. Flags.setInAlloca();
  8000. // Set the byval flag for CCAssignFn callbacks that don't know about
  8001. // inalloca. This way we can know how many bytes we should've allocated
  8002. // and how many bytes a callee cleanup function will pop. If we port
  8003. // inalloca to more targets, we'll have to add custom inalloca handling
  8004. // in the various CC lowering callbacks.
  8005. Flags.setByVal();
  8006. }
  8007. if (Args[i].IsByVal || Args[i].IsInAlloca) {
  8008. PointerType *Ty = cast<PointerType>(Args[i].Ty);
  8009. Type *ElementTy = Ty->getElementType();
  8010. unsigned FrameSize = DL.getTypeAllocSize(
  8011. Args[i].ByValType ? Args[i].ByValType : ElementTy);
  8012. Flags.setByValSize(FrameSize);
  8013. // info is not there but there are cases it cannot get right.
  8014. unsigned FrameAlign;
  8015. if (Args[i].Alignment)
  8016. FrameAlign = Args[i].Alignment;
  8017. else
  8018. FrameAlign = getByValTypeAlignment(ElementTy, DL);
  8019. Flags.setByValAlign(FrameAlign);
  8020. }
  8021. if (Args[i].IsNest)
  8022. Flags.setNest();
  8023. if (NeedsRegBlock)
  8024. Flags.setInConsecutiveRegs();
  8025. Flags.setOrigAlign(OriginalAlignment);
  8026. MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
  8027. CLI.CallConv, VT);
  8028. unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
  8029. CLI.CallConv, VT);
  8030. SmallVector<SDValue, 4> Parts(NumParts);
  8031. ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
  8032. if (Args[i].IsSExt)
  8033. ExtendKind = ISD::SIGN_EXTEND;
  8034. else if (Args[i].IsZExt)
  8035. ExtendKind = ISD::ZERO_EXTEND;
  8036. // Conservatively only handle 'returned' on non-vectors that can be lowered,
  8037. // for now.
  8038. if (Args[i].IsReturned && !Op.getValueType().isVector() &&
  8039. CanLowerReturn) {
  8040. assert((CLI.RetTy == Args[i].Ty ||
  8041. (CLI.RetTy->isPointerTy() && Args[i].Ty->isPointerTy() &&
  8042. CLI.RetTy->getPointerAddressSpace() ==
  8043. Args[i].Ty->getPointerAddressSpace())) &&
  8044. RetTys.size() == NumValues && "unexpected use of 'returned'");
  8045. // Before passing 'returned' to the target lowering code, ensure that
  8046. // either the register MVT and the actual EVT are the same size or that
  8047. // the return value and argument are extended in the same way; in these
  8048. // cases it's safe to pass the argument register value unchanged as the
  8049. // return register value (although it's at the target's option whether
  8050. // to do so)
  8051. // TODO: allow code generation to take advantage of partially preserved
  8052. // registers rather than clobbering the entire register when the
  8053. // parameter extension method is not compatible with the return
  8054. // extension method
  8055. if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) ||
  8056. (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt &&
  8057. CLI.RetZExt == Args[i].IsZExt))
  8058. Flags.setReturned();
  8059. }
  8060. getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT,
  8061. CLI.CS.getInstruction(), CLI.CallConv, ExtendKind);
  8062. for (unsigned j = 0; j != NumParts; ++j) {
  8063. // if it isn't first piece, alignment must be 1
  8064. ISD::OutputArg MyFlags(Flags, Parts[j].getValueType(), VT,
  8065. i < CLI.NumFixedArgs,
  8066. i, j*Parts[j].getValueType().getStoreSize());
  8067. if (NumParts > 1 && j == 0)
  8068. MyFlags.Flags.setSplit();
  8069. else if (j != 0) {
  8070. MyFlags.Flags.setOrigAlign(1);
  8071. if (j == NumParts - 1)
  8072. MyFlags.Flags.setSplitEnd();
  8073. }
  8074. CLI.Outs.push_back(MyFlags);
  8075. CLI.OutVals.push_back(Parts[j]);
  8076. }
  8077. if (NeedsRegBlock && Value == NumValues - 1)
  8078. CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast();
  8079. }
  8080. }
  8081. SmallVector<SDValue, 4> InVals;
  8082. CLI.Chain = LowerCall(CLI, InVals);
  8083. // Update CLI.InVals to use outside of this function.
  8084. CLI.InVals = InVals;
  8085. // Verify that the target's LowerCall behaved as expected.
  8086. assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other &&
  8087. "LowerCall didn't return a valid chain!");
  8088. assert((!CLI.IsTailCall || InVals.empty()) &&
  8089. "LowerCall emitted a return value for a tail call!");
  8090. assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) &&
  8091. "LowerCall didn't emit the correct number of values!");
  8092. // For a tail call, the return value is merely live-out and there aren't
  8093. // any nodes in the DAG representing it. Return a special value to
  8094. // indicate that a tail call has been emitted and no more Instructions
  8095. // should be processed in the current block.
  8096. if (CLI.IsTailCall) {
  8097. CLI.DAG.setRoot(CLI.Chain);
  8098. return std::make_pair(SDValue(), SDValue());
  8099. }
  8100. #ifndef NDEBUG
  8101. for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) {
  8102. assert(InVals[i].getNode() && "LowerCall emitted a null value!");
  8103. assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() &&
  8104. "LowerCall emitted a value with the wrong type!");
  8105. }
  8106. #endif
  8107. SmallVector<SDValue, 4> ReturnValues;
  8108. if (!CanLowerReturn) {
  8109. // The instruction result is the result of loading from the
  8110. // hidden sret parameter.
  8111. SmallVector<EVT, 1> PVTs;
  8112. Type *PtrRetTy = OrigRetTy->getPointerTo(DL.getAllocaAddrSpace());
  8113. ComputeValueVTs(*this, DL, PtrRetTy, PVTs);
  8114. assert(PVTs.size() == 1 && "Pointers should fit in one register");
  8115. EVT PtrVT = PVTs[0];
  8116. unsigned NumValues = RetTys.size();
  8117. ReturnValues.resize(NumValues);
  8118. SmallVector<SDValue, 4> Chains(NumValues);
  8119. // An aggregate return value cannot wrap around the address space, so
  8120. // offsets to its parts don't wrap either.
  8121. SDNodeFlags Flags;
  8122. Flags.setNoUnsignedWrap(true);
  8123. for (unsigned i = 0; i < NumValues; ++i) {
  8124. SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot,
  8125. CLI.DAG.getConstant(Offsets[i], CLI.DL,
  8126. PtrVT), Flags);
  8127. SDValue L = CLI.DAG.getLoad(
  8128. RetTys[i], CLI.DL, CLI.Chain, Add,
  8129. MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(),
  8130. DemoteStackIdx, Offsets[i]),
  8131. /* Alignment = */ 1);
  8132. ReturnValues[i] = L;
  8133. Chains[i] = L.getValue(1);
  8134. }
  8135. CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains);
  8136. } else {
  8137. // Collect the legal value parts into potentially illegal values
  8138. // that correspond to the original function's return values.
  8139. Optional<ISD::NodeType> AssertOp;
  8140. if (CLI.RetSExt)
  8141. AssertOp = ISD::AssertSext;
  8142. else if (CLI.RetZExt)
  8143. AssertOp = ISD::AssertZext;
  8144. unsigned CurReg = 0;
  8145. for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
  8146. EVT VT = RetTys[I];
  8147. MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
  8148. CLI.CallConv, VT);
  8149. unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
  8150. CLI.CallConv, VT);
  8151. ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg],
  8152. NumRegs, RegisterVT, VT, nullptr,
  8153. CLI.CallConv, AssertOp));
  8154. CurReg += NumRegs;
  8155. }
  8156. // For a function returning void, there is no return value. We can't create
  8157. // such a node, so we just return a null return value in that case. In
  8158. // that case, nothing will actually look at the value.
  8159. if (ReturnValues.empty())
  8160. return std::make_pair(SDValue(), CLI.Chain);
  8161. }
  8162. SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL,
  8163. CLI.DAG.getVTList(RetTys), ReturnValues);
  8164. return std::make_pair(Res, CLI.Chain);
  8165. }
  8166. void TargetLowering::LowerOperationWrapper(SDNode *N,
  8167. SmallVectorImpl<SDValue> &Results,
  8168. SelectionDAG &DAG) const {
  8169. if (SDValue Res = LowerOperation(SDValue(N, 0), DAG))
  8170. Results.push_back(Res);
  8171. }
  8172. SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
  8173. llvm_unreachable("LowerOperation not implemented for this target!");
  8174. }
  8175. void
  8176. SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) {
  8177. SDValue Op = getNonRegisterValue(V);
  8178. assert((Op.getOpcode() != ISD::CopyFromReg ||
  8179. cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
  8180. "Copy from a reg to the same reg!");
  8181. assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg");
  8182. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  8183. // If this is an InlineAsm we have to match the registers required, not the
  8184. // notional registers required by the type.
  8185. RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(),
  8186. None); // This is not an ABI copy.
  8187. SDValue Chain = DAG.getEntryNode();
  8188. ISD::NodeType ExtendType = (FuncInfo.PreferredExtendType.find(V) ==
  8189. FuncInfo.PreferredExtendType.end())
  8190. ? ISD::ANY_EXTEND
  8191. : FuncInfo.PreferredExtendType[V];
  8192. RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType);
  8193. PendingExports.push_back(Chain);
  8194. }
  8195. #include "llvm/CodeGen/SelectionDAGISel.h"
  8196. /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
  8197. /// entry block, return true. This includes arguments used by switches, since
  8198. /// the switch may expand into multiple basic blocks.
  8199. static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) {
  8200. // With FastISel active, we may be splitting blocks, so force creation
  8201. // of virtual registers for all non-dead arguments.
  8202. if (FastISel)
  8203. return A->use_empty();
  8204. const BasicBlock &Entry = A->getParent()->front();
  8205. for (const User *U : A->users())
  8206. if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U))
  8207. return false; // Use not in entry block.
  8208. return true;
  8209. }
  8210. using ArgCopyElisionMapTy =
  8211. DenseMap<const Argument *,
  8212. std::pair<const AllocaInst *, const StoreInst *>>;
  8213. /// Scan the entry block of the function in FuncInfo for arguments that look
  8214. /// like copies into a local alloca. Record any copied arguments in
  8215. /// ArgCopyElisionCandidates.
  8216. static void
  8217. findArgumentCopyElisionCandidates(const DataLayout &DL,
  8218. FunctionLoweringInfo *FuncInfo,
  8219. ArgCopyElisionMapTy &ArgCopyElisionCandidates) {
  8220. // Record the state of every static alloca used in the entry block. Argument
  8221. // allocas are all used in the entry block, so we need approximately as many
  8222. // entries as we have arguments.
  8223. enum StaticAllocaInfo { Unknown, Clobbered, Elidable };
  8224. SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas;
  8225. unsigned NumArgs = FuncInfo->Fn->arg_size();
  8226. StaticAllocas.reserve(NumArgs * 2);
  8227. auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * {
  8228. if (!V)
  8229. return nullptr;
  8230. V = V->stripPointerCasts();
  8231. const auto *AI = dyn_cast<AllocaInst>(V);
  8232. if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI))
  8233. return nullptr;
  8234. auto Iter = StaticAllocas.insert({AI, Unknown});
  8235. return &Iter.first->second;
  8236. };
  8237. // Look for stores of arguments to static allocas. Look through bitcasts and
  8238. // GEPs to handle type coercions, as long as the alloca is fully initialized
  8239. // by the store. Any non-store use of an alloca escapes it and any subsequent
  8240. // unanalyzed store might write it.
  8241. // FIXME: Handle structs initialized with multiple stores.
  8242. for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) {
  8243. // Look for stores, and handle non-store uses conservatively.
  8244. const auto *SI = dyn_cast<StoreInst>(&I);
  8245. if (!SI) {
  8246. // We will look through cast uses, so ignore them completely.
  8247. if (I.isCast())
  8248. continue;
  8249. // Ignore debug info intrinsics, they don't escape or store to allocas.
  8250. if (isa<DbgInfoIntrinsic>(I))
  8251. continue;
  8252. // This is an unknown instruction. Assume it escapes or writes to all
  8253. // static alloca operands.
  8254. for (const Use &U : I.operands()) {
  8255. if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U))
  8256. *Info = StaticAllocaInfo::Clobbered;
  8257. }
  8258. continue;
  8259. }
  8260. // If the stored value is a static alloca, mark it as escaped.
  8261. if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand()))
  8262. *Info = StaticAllocaInfo::Clobbered;
  8263. // Check if the destination is a static alloca.
  8264. const Value *Dst = SI->getPointerOperand()->stripPointerCasts();
  8265. StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst);
  8266. if (!Info)
  8267. continue;
  8268. const AllocaInst *AI = cast<AllocaInst>(Dst);
  8269. // Skip allocas that have been initialized or clobbered.
  8270. if (*Info != StaticAllocaInfo::Unknown)
  8271. continue;
  8272. // Check if the stored value is an argument, and that this store fully
  8273. // initializes the alloca. Don't elide copies from the same argument twice.
  8274. const Value *Val = SI->getValueOperand()->stripPointerCasts();
  8275. const auto *Arg = dyn_cast<Argument>(Val);
  8276. if (!Arg || Arg->hasInAllocaAttr() || Arg->hasByValAttr() ||
  8277. Arg->getType()->isEmptyTy() ||
  8278. DL.getTypeStoreSize(Arg->getType()) !=
  8279. DL.getTypeAllocSize(AI->getAllocatedType()) ||
  8280. ArgCopyElisionCandidates.count(Arg)) {
  8281. *Info = StaticAllocaInfo::Clobbered;
  8282. continue;
  8283. }
  8284. LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI
  8285. << '\n');
  8286. // Mark this alloca and store for argument copy elision.
  8287. *Info = StaticAllocaInfo::Elidable;
  8288. ArgCopyElisionCandidates.insert({Arg, {AI, SI}});
  8289. // Stop scanning if we've seen all arguments. This will happen early in -O0
  8290. // builds, which is useful, because -O0 builds have large entry blocks and
  8291. // many allocas.
  8292. if (ArgCopyElisionCandidates.size() == NumArgs)
  8293. break;
  8294. }
  8295. }
  8296. /// Try to elide argument copies from memory into a local alloca. Succeeds if
  8297. /// ArgVal is a load from a suitable fixed stack object.
  8298. static void tryToElideArgumentCopy(
  8299. FunctionLoweringInfo *FuncInfo, SmallVectorImpl<SDValue> &Chains,
  8300. DenseMap<int, int> &ArgCopyElisionFrameIndexMap,
  8301. SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs,
  8302. ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg,
  8303. SDValue ArgVal, bool &ArgHasUses) {
  8304. // Check if this is a load from a fixed stack object.
  8305. auto *LNode = dyn_cast<LoadSDNode>(ArgVal);
  8306. if (!LNode)
  8307. return;
  8308. auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode());
  8309. if (!FINode)
  8310. return;
  8311. // Check that the fixed stack object is the right size and alignment.
  8312. // Look at the alignment that the user wrote on the alloca instead of looking
  8313. // at the stack object.
  8314. auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg);
  8315. assert(ArgCopyIter != ArgCopyElisionCandidates.end());
  8316. const AllocaInst *AI = ArgCopyIter->second.first;
  8317. int FixedIndex = FINode->getIndex();
  8318. int &AllocaIndex = FuncInfo->StaticAllocaMap[AI];
  8319. int OldIndex = AllocaIndex;
  8320. MachineFrameInfo &MFI = FuncInfo->MF->getFrameInfo();
  8321. if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) {
  8322. LLVM_DEBUG(
  8323. dbgs() << " argument copy elision failed due to bad fixed stack "
  8324. "object size\n");
  8325. return;
  8326. }
  8327. unsigned RequiredAlignment = AI->getAlignment();
  8328. if (!RequiredAlignment) {
  8329. RequiredAlignment = FuncInfo->MF->getDataLayout().getABITypeAlignment(
  8330. AI->getAllocatedType());
  8331. }
  8332. if (MFI.getObjectAlignment(FixedIndex) < RequiredAlignment) {
  8333. LLVM_DEBUG(dbgs() << " argument copy elision failed: alignment of alloca "
  8334. "greater than stack argument alignment ("
  8335. << RequiredAlignment << " vs "
  8336. << MFI.getObjectAlignment(FixedIndex) << ")\n");
  8337. return;
  8338. }
  8339. // Perform the elision. Delete the old stack object and replace its only use
  8340. // in the variable info map. Mark the stack object as mutable.
  8341. LLVM_DEBUG({
  8342. dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n'
  8343. << " Replacing frame index " << OldIndex << " with " << FixedIndex
  8344. << '\n';
  8345. });
  8346. MFI.RemoveStackObject(OldIndex);
  8347. MFI.setIsImmutableObjectIndex(FixedIndex, false);
  8348. AllocaIndex = FixedIndex;
  8349. ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex});
  8350. Chains.push_back(ArgVal.getValue(1));
  8351. // Avoid emitting code for the store implementing the copy.
  8352. const StoreInst *SI = ArgCopyIter->second.second;
  8353. ElidedArgCopyInstrs.insert(SI);
  8354. // Check for uses of the argument again so that we can avoid exporting ArgVal
  8355. // if it is't used by anything other than the store.
  8356. for (const Value *U : Arg.users()) {
  8357. if (U != SI) {
  8358. ArgHasUses = true;
  8359. break;
  8360. }
  8361. }
  8362. }
  8363. void SelectionDAGISel::LowerArguments(const Function &F) {
  8364. SelectionDAG &DAG = SDB->DAG;
  8365. SDLoc dl = SDB->getCurSDLoc();
  8366. const DataLayout &DL = DAG.getDataLayout();
  8367. SmallVector<ISD::InputArg, 16> Ins;
  8368. if (!FuncInfo->CanLowerReturn) {
  8369. // Put in an sret pointer parameter before all the other parameters.
  8370. SmallVector<EVT, 1> ValueVTs;
  8371. ComputeValueVTs(*TLI, DAG.getDataLayout(),
  8372. F.getReturnType()->getPointerTo(
  8373. DAG.getDataLayout().getAllocaAddrSpace()),
  8374. ValueVTs);
  8375. // NOTE: Assuming that a pointer will never break down to more than one VT
  8376. // or one register.
  8377. ISD::ArgFlagsTy Flags;
  8378. Flags.setSRet();
  8379. MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]);
  8380. ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true,
  8381. ISD::InputArg::NoArgIndex, 0);
  8382. Ins.push_back(RetArg);
  8383. }
  8384. // Look for stores of arguments to static allocas. Mark such arguments with a
  8385. // flag to ask the target to give us the memory location of that argument if
  8386. // available.
  8387. ArgCopyElisionMapTy ArgCopyElisionCandidates;
  8388. findArgumentCopyElisionCandidates(DL, FuncInfo, ArgCopyElisionCandidates);
  8389. // Set up the incoming argument description vector.
  8390. for (const Argument &Arg : F.args()) {
  8391. unsigned ArgNo = Arg.getArgNo();
  8392. SmallVector<EVT, 4> ValueVTs;
  8393. ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
  8394. bool isArgValueUsed = !Arg.use_empty();
  8395. unsigned PartBase = 0;
  8396. Type *FinalType = Arg.getType();
  8397. if (Arg.hasAttribute(Attribute::ByVal))
  8398. FinalType = cast<PointerType>(FinalType)->getElementType();
  8399. bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters(
  8400. FinalType, F.getCallingConv(), F.isVarArg());
  8401. for (unsigned Value = 0, NumValues = ValueVTs.size();
  8402. Value != NumValues; ++Value) {
  8403. EVT VT = ValueVTs[Value];
  8404. Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
  8405. ISD::ArgFlagsTy Flags;
  8406. // Certain targets (such as MIPS), may have a different ABI alignment
  8407. // for a type depending on the context. Give the target a chance to
  8408. // specify the alignment it wants.
  8409. unsigned OriginalAlignment =
  8410. TLI->getABIAlignmentForCallingConv(ArgTy, DL);
  8411. if (Arg.getType()->isPointerTy()) {
  8412. Flags.setPointer();
  8413. Flags.setPointerAddrSpace(
  8414. cast<PointerType>(Arg.getType())->getAddressSpace());
  8415. }
  8416. if (Arg.hasAttribute(Attribute::ZExt))
  8417. Flags.setZExt();
  8418. if (Arg.hasAttribute(Attribute::SExt))
  8419. Flags.setSExt();
  8420. if (Arg.hasAttribute(Attribute::InReg)) {
  8421. // If we are using vectorcall calling convention, a structure that is
  8422. // passed InReg - is surely an HVA
  8423. if (F.getCallingConv() == CallingConv::X86_VectorCall &&
  8424. isa<StructType>(Arg.getType())) {
  8425. // The first value of a structure is marked
  8426. if (0 == Value)
  8427. Flags.setHvaStart();
  8428. Flags.setHva();
  8429. }
  8430. // Set InReg Flag
  8431. Flags.setInReg();
  8432. }
  8433. if (Arg.hasAttribute(Attribute::StructRet))
  8434. Flags.setSRet();
  8435. if (Arg.hasAttribute(Attribute::SwiftSelf))
  8436. Flags.setSwiftSelf();
  8437. if (Arg.hasAttribute(Attribute::SwiftError))
  8438. Flags.setSwiftError();
  8439. if (Arg.hasAttribute(Attribute::ByVal))
  8440. Flags.setByVal();
  8441. if (Arg.hasAttribute(Attribute::InAlloca)) {
  8442. Flags.setInAlloca();
  8443. // Set the byval flag for CCAssignFn callbacks that don't know about
  8444. // inalloca. This way we can know how many bytes we should've allocated
  8445. // and how many bytes a callee cleanup function will pop. If we port
  8446. // inalloca to more targets, we'll have to add custom inalloca handling
  8447. // in the various CC lowering callbacks.
  8448. Flags.setByVal();
  8449. }
  8450. if (F.getCallingConv() == CallingConv::X86_INTR) {
  8451. // IA Interrupt passes frame (1st parameter) by value in the stack.
  8452. if (ArgNo == 0)
  8453. Flags.setByVal();
  8454. }
  8455. if (Flags.isByVal() || Flags.isInAlloca()) {
  8456. PointerType *Ty = cast<PointerType>(Arg.getType());
  8457. Type *ElementTy = Ty->getElementType();
  8458. // For ByVal, size and alignment should be passed from FE. BE will
  8459. // guess if this info is not there but there are cases it cannot get
  8460. // right.
  8461. unsigned FrameSize = DL.getTypeAllocSize(Arg.getParamByValType());
  8462. Flags.setByValSize(FrameSize);
  8463. unsigned FrameAlign;
  8464. if (Arg.getParamAlignment())
  8465. FrameAlign = Arg.getParamAlignment();
  8466. else
  8467. FrameAlign = TLI->getByValTypeAlignment(ElementTy, DL);
  8468. Flags.setByValAlign(FrameAlign);
  8469. }
  8470. if (Arg.hasAttribute(Attribute::Nest))
  8471. Flags.setNest();
  8472. if (NeedsRegBlock)
  8473. Flags.setInConsecutiveRegs();
  8474. Flags.setOrigAlign(OriginalAlignment);
  8475. if (ArgCopyElisionCandidates.count(&Arg))
  8476. Flags.setCopyElisionCandidate();
  8477. MVT RegisterVT = TLI->getRegisterTypeForCallingConv(
  8478. *CurDAG->getContext(), F.getCallingConv(), VT);
  8479. unsigned NumRegs = TLI->getNumRegistersForCallingConv(
  8480. *CurDAG->getContext(), F.getCallingConv(), VT);
  8481. for (unsigned i = 0; i != NumRegs; ++i) {
  8482. ISD::InputArg MyFlags(Flags, RegisterVT, VT, isArgValueUsed,
  8483. ArgNo, PartBase+i*RegisterVT.getStoreSize());
  8484. if (NumRegs > 1 && i == 0)
  8485. MyFlags.Flags.setSplit();
  8486. // if it isn't first piece, alignment must be 1
  8487. else if (i > 0) {
  8488. MyFlags.Flags.setOrigAlign(1);
  8489. if (i == NumRegs - 1)
  8490. MyFlags.Flags.setSplitEnd();
  8491. }
  8492. Ins.push_back(MyFlags);
  8493. }
  8494. if (NeedsRegBlock && Value == NumValues - 1)
  8495. Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast();
  8496. PartBase += VT.getStoreSize();
  8497. }
  8498. }
  8499. // Call the target to set up the argument values.
  8500. SmallVector<SDValue, 8> InVals;
  8501. SDValue NewRoot = TLI->LowerFormalArguments(
  8502. DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals);
  8503. // Verify that the target's LowerFormalArguments behaved as expected.
  8504. assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
  8505. "LowerFormalArguments didn't return a valid chain!");
  8506. assert(InVals.size() == Ins.size() &&
  8507. "LowerFormalArguments didn't emit the correct number of values!");
  8508. LLVM_DEBUG({
  8509. for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
  8510. assert(InVals[i].getNode() &&
  8511. "LowerFormalArguments emitted a null value!");
  8512. assert(EVT(Ins[i].VT) == InVals[i].getValueType() &&
  8513. "LowerFormalArguments emitted a value with the wrong type!");
  8514. }
  8515. });
  8516. // Update the DAG with the new chain value resulting from argument lowering.
  8517. DAG.setRoot(NewRoot);
  8518. // Set up the argument values.
  8519. unsigned i = 0;
  8520. if (!FuncInfo->CanLowerReturn) {
  8521. // Create a virtual register for the sret pointer, and put in a copy
  8522. // from the sret argument into it.
  8523. SmallVector<EVT, 1> ValueVTs;
  8524. ComputeValueVTs(*TLI, DAG.getDataLayout(),
  8525. F.getReturnType()->getPointerTo(
  8526. DAG.getDataLayout().getAllocaAddrSpace()),
  8527. ValueVTs);
  8528. MVT VT = ValueVTs[0].getSimpleVT();
  8529. MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
  8530. Optional<ISD::NodeType> AssertOp = None;
  8531. SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT,
  8532. nullptr, F.getCallingConv(), AssertOp);
  8533. MachineFunction& MF = SDB->DAG.getMachineFunction();
  8534. MachineRegisterInfo& RegInfo = MF.getRegInfo();
  8535. unsigned SRetReg = RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT));
  8536. FuncInfo->DemoteRegister = SRetReg;
  8537. NewRoot =
  8538. SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue);
  8539. DAG.setRoot(NewRoot);
  8540. // i indexes lowered arguments. Bump it past the hidden sret argument.
  8541. ++i;
  8542. }
  8543. SmallVector<SDValue, 4> Chains;
  8544. DenseMap<int, int> ArgCopyElisionFrameIndexMap;
  8545. for (const Argument &Arg : F.args()) {
  8546. SmallVector<SDValue, 4> ArgValues;
  8547. SmallVector<EVT, 4> ValueVTs;
  8548. ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
  8549. unsigned NumValues = ValueVTs.size();
  8550. if (NumValues == 0)
  8551. continue;
  8552. bool ArgHasUses = !Arg.use_empty();
  8553. // Elide the copying store if the target loaded this argument from a
  8554. // suitable fixed stack object.
  8555. if (Ins[i].Flags.isCopyElisionCandidate()) {
  8556. tryToElideArgumentCopy(FuncInfo, Chains, ArgCopyElisionFrameIndexMap,
  8557. ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg,
  8558. InVals[i], ArgHasUses);
  8559. }
  8560. // If this argument is unused then remember its value. It is used to generate
  8561. // debugging information.
  8562. bool isSwiftErrorArg =
  8563. TLI->supportSwiftError() &&
  8564. Arg.hasAttribute(Attribute::SwiftError);
  8565. if (!ArgHasUses && !isSwiftErrorArg) {
  8566. SDB->setUnusedArgValue(&Arg, InVals[i]);
  8567. // Also remember any frame index for use in FastISel.
  8568. if (FrameIndexSDNode *FI =
  8569. dyn_cast<FrameIndexSDNode>(InVals[i].getNode()))
  8570. FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
  8571. }
  8572. for (unsigned Val = 0; Val != NumValues; ++Val) {
  8573. EVT VT = ValueVTs[Val];
  8574. MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(),
  8575. F.getCallingConv(), VT);
  8576. unsigned NumParts = TLI->getNumRegistersForCallingConv(
  8577. *CurDAG->getContext(), F.getCallingConv(), VT);
  8578. // Even an apparant 'unused' swifterror argument needs to be returned. So
  8579. // we do generate a copy for it that can be used on return from the
  8580. // function.
  8581. if (ArgHasUses || isSwiftErrorArg) {
  8582. Optional<ISD::NodeType> AssertOp;
  8583. if (Arg.hasAttribute(Attribute::SExt))
  8584. AssertOp = ISD::AssertSext;
  8585. else if (Arg.hasAttribute(Attribute::ZExt))
  8586. AssertOp = ISD::AssertZext;
  8587. ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts,
  8588. PartVT, VT, nullptr,
  8589. F.getCallingConv(), AssertOp));
  8590. }
  8591. i += NumParts;
  8592. }
  8593. // We don't need to do anything else for unused arguments.
  8594. if (ArgValues.empty())
  8595. continue;
  8596. // Note down frame index.
  8597. if (FrameIndexSDNode *FI =
  8598. dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode()))
  8599. FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
  8600. SDValue Res = DAG.getMergeValues(makeArrayRef(ArgValues.data(), NumValues),
  8601. SDB->getCurSDLoc());
  8602. SDB->setValue(&Arg, Res);
  8603. if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) {
  8604. // We want to associate the argument with the frame index, among
  8605. // involved operands, that correspond to the lowest address. The
  8606. // getCopyFromParts function, called earlier, is swapping the order of
  8607. // the operands to BUILD_PAIR depending on endianness. The result of
  8608. // that swapping is that the least significant bits of the argument will
  8609. // be in the first operand of the BUILD_PAIR node, and the most
  8610. // significant bits will be in the second operand.
  8611. unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0;
  8612. if (LoadSDNode *LNode =
  8613. dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode()))
  8614. if (FrameIndexSDNode *FI =
  8615. dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
  8616. FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
  8617. }
  8618. // Update the SwiftErrorVRegDefMap.
  8619. if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) {
  8620. unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
  8621. if (TargetRegisterInfo::isVirtualRegister(Reg))
  8622. SwiftError->setCurrentVReg(FuncInfo->MBB, SwiftError->getFunctionArg(),
  8623. Reg);
  8624. }
  8625. // If this argument is live outside of the entry block, insert a copy from
  8626. // wherever we got it to the vreg that other BB's will reference it as.
  8627. if (Res.getOpcode() == ISD::CopyFromReg) {
  8628. // If we can, though, try to skip creating an unnecessary vreg.
  8629. // FIXME: This isn't very clean... it would be nice to make this more
  8630. // general.
  8631. unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
  8632. if (TargetRegisterInfo::isVirtualRegister(Reg)) {
  8633. FuncInfo->ValueMap[&Arg] = Reg;
  8634. continue;
  8635. }
  8636. }
  8637. if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) {
  8638. FuncInfo->InitializeRegForValue(&Arg);
  8639. SDB->CopyToExportRegsIfNeeded(&Arg);
  8640. }
  8641. }
  8642. if (!Chains.empty()) {
  8643. Chains.push_back(NewRoot);
  8644. NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
  8645. }
  8646. DAG.setRoot(NewRoot);
  8647. assert(i == InVals.size() && "Argument register count mismatch!");
  8648. // If any argument copy elisions occurred and we have debug info, update the
  8649. // stale frame indices used in the dbg.declare variable info table.
  8650. MachineFunction::VariableDbgInfoMapTy &DbgDeclareInfo = MF->getVariableDbgInfo();
  8651. if (!DbgDeclareInfo.empty() && !ArgCopyElisionFrameIndexMap.empty()) {
  8652. for (MachineFunction::VariableDbgInfo &VI : DbgDeclareInfo) {
  8653. auto I = ArgCopyElisionFrameIndexMap.find(VI.Slot);
  8654. if (I != ArgCopyElisionFrameIndexMap.end())
  8655. VI.Slot = I->second;
  8656. }
  8657. }
  8658. // Finally, if the target has anything special to do, allow it to do so.
  8659. EmitFunctionEntryCode();
  8660. }
  8661. /// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
  8662. /// ensure constants are generated when needed. Remember the virtual registers
  8663. /// that need to be added to the Machine PHI nodes as input. We cannot just
  8664. /// directly add them, because expansion might result in multiple MBB's for one
  8665. /// BB. As such, the start of the BB might correspond to a different MBB than
  8666. /// the end.
  8667. void
  8668. SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
  8669. const Instruction *TI = LLVMBB->getTerminator();
  8670. SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
  8671. // Check PHI nodes in successors that expect a value to be available from this
  8672. // block.
  8673. for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
  8674. const BasicBlock *SuccBB = TI->getSuccessor(succ);
  8675. if (!isa<PHINode>(SuccBB->begin())) continue;
  8676. MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
  8677. // If this terminator has multiple identical successors (common for
  8678. // switches), only handle each succ once.
  8679. if (!SuccsHandled.insert(SuccMBB).second)
  8680. continue;
  8681. MachineBasicBlock::iterator MBBI = SuccMBB->begin();
  8682. // At this point we know that there is a 1-1 correspondence between LLVM PHI
  8683. // nodes and Machine PHI nodes, but the incoming operands have not been
  8684. // emitted yet.
  8685. for (const PHINode &PN : SuccBB->phis()) {
  8686. // Ignore dead phi's.
  8687. if (PN.use_empty())
  8688. continue;
  8689. // Skip empty types
  8690. if (PN.getType()->isEmptyTy())
  8691. continue;
  8692. unsigned Reg;
  8693. const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB);
  8694. if (const Constant *C = dyn_cast<Constant>(PHIOp)) {
  8695. unsigned &RegOut = ConstantsOut[C];
  8696. if (RegOut == 0) {
  8697. RegOut = FuncInfo.CreateRegs(C);
  8698. CopyValueToVirtualRegister(C, RegOut);
  8699. }
  8700. Reg = RegOut;
  8701. } else {
  8702. DenseMap<const Value *, unsigned>::iterator I =
  8703. FuncInfo.ValueMap.find(PHIOp);
  8704. if (I != FuncInfo.ValueMap.end())
  8705. Reg = I->second;
  8706. else {
  8707. assert(isa<AllocaInst>(PHIOp) &&
  8708. FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
  8709. "Didn't codegen value into a register!??");
  8710. Reg = FuncInfo.CreateRegs(PHIOp);
  8711. CopyValueToVirtualRegister(PHIOp, Reg);
  8712. }
  8713. }
  8714. // Remember that this register needs to added to the machine PHI node as
  8715. // the input for this MBB.
  8716. SmallVector<EVT, 4> ValueVTs;
  8717. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  8718. ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs);
  8719. for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
  8720. EVT VT = ValueVTs[vti];
  8721. unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT);
  8722. for (unsigned i = 0, e = NumRegisters; i != e; ++i)
  8723. FuncInfo.PHINodesToUpdate.push_back(
  8724. std::make_pair(&*MBBI++, Reg + i));
  8725. Reg += NumRegisters;
  8726. }
  8727. }
  8728. }
  8729. ConstantsOut.clear();
  8730. }
  8731. /// Add a successor MBB to ParentMBB< creating a new MachineBB for BB if SuccMBB
  8732. /// is 0.
  8733. MachineBasicBlock *
  8734. SelectionDAGBuilder::StackProtectorDescriptor::
  8735. AddSuccessorMBB(const BasicBlock *BB,
  8736. MachineBasicBlock *ParentMBB,
  8737. bool IsLikely,
  8738. MachineBasicBlock *SuccMBB) {
  8739. // If SuccBB has not been created yet, create it.
  8740. if (!SuccMBB) {
  8741. MachineFunction *MF = ParentMBB->getParent();
  8742. MachineFunction::iterator BBI(ParentMBB);
  8743. SuccMBB = MF->CreateMachineBasicBlock(BB);
  8744. MF->insert(++BBI, SuccMBB);
  8745. }
  8746. // Add it as a successor of ParentMBB.
  8747. ParentMBB->addSuccessor(
  8748. SuccMBB, BranchProbabilityInfo::getBranchProbStackProtector(IsLikely));
  8749. return SuccMBB;
  8750. }
  8751. MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) {
  8752. MachineFunction::iterator I(MBB);
  8753. if (++I == FuncInfo.MF->end())
  8754. return nullptr;
  8755. return &*I;
  8756. }
  8757. /// During lowering new call nodes can be created (such as memset, etc.).
  8758. /// Those will become new roots of the current DAG, but complications arise
  8759. /// when they are tail calls. In such cases, the call lowering will update
  8760. /// the root, but the builder still needs to know that a tail call has been
  8761. /// lowered in order to avoid generating an additional return.
  8762. void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) {
  8763. // If the node is null, we do have a tail call.
  8764. if (MaybeTC.getNode() != nullptr)
  8765. DAG.setRoot(MaybeTC);
  8766. else
  8767. HasTailCall = true;
  8768. }
  8769. void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond,
  8770. MachineBasicBlock *SwitchMBB,
  8771. MachineBasicBlock *DefaultMBB) {
  8772. MachineFunction *CurMF = FuncInfo.MF;
  8773. MachineBasicBlock *NextMBB = nullptr;
  8774. MachineFunction::iterator BBI(W.MBB);
  8775. if (++BBI != FuncInfo.MF->end())
  8776. NextMBB = &*BBI;
  8777. unsigned Size = W.LastCluster - W.FirstCluster + 1;
  8778. BranchProbabilityInfo *BPI = FuncInfo.BPI;
  8779. if (Size == 2 && W.MBB == SwitchMBB) {
  8780. // If any two of the cases has the same destination, and if one value
  8781. // is the same as the other, but has one bit unset that the other has set,
  8782. // use bit manipulation to do two compares at once. For example:
  8783. // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
  8784. // TODO: This could be extended to merge any 2 cases in switches with 3
  8785. // cases.
  8786. // TODO: Handle cases where W.CaseBB != SwitchBB.
  8787. CaseCluster &Small = *W.FirstCluster;
  8788. CaseCluster &Big = *W.LastCluster;
  8789. if (Small.Low == Small.High && Big.Low == Big.High &&
  8790. Small.MBB == Big.MBB) {
  8791. const APInt &SmallValue = Small.Low->getValue();
  8792. const APInt &BigValue = Big.Low->getValue();
  8793. // Check that there is only one bit different.
  8794. APInt CommonBit = BigValue ^ SmallValue;
  8795. if (CommonBit.isPowerOf2()) {
  8796. SDValue CondLHS = getValue(Cond);
  8797. EVT VT = CondLHS.getValueType();
  8798. SDLoc DL = getCurSDLoc();
  8799. SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS,
  8800. DAG.getConstant(CommonBit, DL, VT));
  8801. SDValue Cond = DAG.getSetCC(
  8802. DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT),
  8803. ISD::SETEQ);
  8804. // Update successor info.
  8805. // Both Small and Big will jump to Small.BB, so we sum up the
  8806. // probabilities.
  8807. addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob);
  8808. if (BPI)
  8809. addSuccessorWithProb(
  8810. SwitchMBB, DefaultMBB,
  8811. // The default destination is the first successor in IR.
  8812. BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0));
  8813. else
  8814. addSuccessorWithProb(SwitchMBB, DefaultMBB);
  8815. // Insert the true branch.
  8816. SDValue BrCond =
  8817. DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond,
  8818. DAG.getBasicBlock(Small.MBB));
  8819. // Insert the false branch.
  8820. BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond,
  8821. DAG.getBasicBlock(DefaultMBB));
  8822. DAG.setRoot(BrCond);
  8823. return;
  8824. }
  8825. }
  8826. }
  8827. if (TM.getOptLevel() != CodeGenOpt::None) {
  8828. // Here, we order cases by probability so the most likely case will be
  8829. // checked first. However, two clusters can have the same probability in
  8830. // which case their relative ordering is non-deterministic. So we use Low
  8831. // as a tie-breaker as clusters are guaranteed to never overlap.
  8832. llvm::sort(W.FirstCluster, W.LastCluster + 1,
  8833. [](const CaseCluster &a, const CaseCluster &b) {
  8834. return a.Prob != b.Prob ?
  8835. a.Prob > b.Prob :
  8836. a.Low->getValue().slt(b.Low->getValue());
  8837. });
  8838. // Rearrange the case blocks so that the last one falls through if possible
  8839. // without changing the order of probabilities.
  8840. for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) {
  8841. --I;
  8842. if (I->Prob > W.LastCluster->Prob)
  8843. break;
  8844. if (I->Kind == CC_Range && I->MBB == NextMBB) {
  8845. std::swap(*I, *W.LastCluster);
  8846. break;
  8847. }
  8848. }
  8849. }
  8850. // Compute total probability.
  8851. BranchProbability DefaultProb = W.DefaultProb;
  8852. BranchProbability UnhandledProbs = DefaultProb;
  8853. for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I)
  8854. UnhandledProbs += I->Prob;
  8855. MachineBasicBlock *CurMBB = W.MBB;
  8856. for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) {
  8857. bool FallthroughUnreachable = false;
  8858. MachineBasicBlock *Fallthrough;
  8859. if (I == W.LastCluster) {
  8860. // For the last cluster, fall through to the default destination.
  8861. Fallthrough = DefaultMBB;
  8862. FallthroughUnreachable = isa<UnreachableInst>(
  8863. DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg());
  8864. } else {
  8865. Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock());
  8866. CurMF->insert(BBI, Fallthrough);
  8867. // Put Cond in a virtual register to make it available from the new blocks.
  8868. ExportFromCurrentBlock(Cond);
  8869. }
  8870. UnhandledProbs -= I->Prob;
  8871. switch (I->Kind) {
  8872. case CC_JumpTable: {
  8873. // FIXME: Optimize away range check based on pivot comparisons.
  8874. JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first;
  8875. SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second;
  8876. // The jump block hasn't been inserted yet; insert it here.
  8877. MachineBasicBlock *JumpMBB = JT->MBB;
  8878. CurMF->insert(BBI, JumpMBB);
  8879. auto JumpProb = I->Prob;
  8880. auto FallthroughProb = UnhandledProbs;
  8881. // If the default statement is a target of the jump table, we evenly
  8882. // distribute the default probability to successors of CurMBB. Also
  8883. // update the probability on the edge from JumpMBB to Fallthrough.
  8884. for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(),
  8885. SE = JumpMBB->succ_end();
  8886. SI != SE; ++SI) {
  8887. if (*SI == DefaultMBB) {
  8888. JumpProb += DefaultProb / 2;
  8889. FallthroughProb -= DefaultProb / 2;
  8890. JumpMBB->setSuccProbability(SI, DefaultProb / 2);
  8891. JumpMBB->normalizeSuccProbs();
  8892. break;
  8893. }
  8894. }
  8895. if (FallthroughUnreachable) {
  8896. // Skip the range check if the fallthrough block is unreachable.
  8897. JTH->OmitRangeCheck = true;
  8898. }
  8899. if (!JTH->OmitRangeCheck)
  8900. addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb);
  8901. addSuccessorWithProb(CurMBB, JumpMBB, JumpProb);
  8902. CurMBB->normalizeSuccProbs();
  8903. // The jump table header will be inserted in our current block, do the
  8904. // range check, and fall through to our fallthrough block.
  8905. JTH->HeaderBB = CurMBB;
  8906. JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader.
  8907. // If we're in the right place, emit the jump table header right now.
  8908. if (CurMBB == SwitchMBB) {
  8909. visitJumpTableHeader(*JT, *JTH, SwitchMBB);
  8910. JTH->Emitted = true;
  8911. }
  8912. break;
  8913. }
  8914. case CC_BitTests: {
  8915. // FIXME: If Fallthrough is unreachable, skip the range check.
  8916. // FIXME: Optimize away range check based on pivot comparisons.
  8917. BitTestBlock *BTB = &SL->BitTestCases[I->BTCasesIndex];
  8918. // The bit test blocks haven't been inserted yet; insert them here.
  8919. for (BitTestCase &BTC : BTB->Cases)
  8920. CurMF->insert(BBI, BTC.ThisBB);
  8921. // Fill in fields of the BitTestBlock.
  8922. BTB->Parent = CurMBB;
  8923. BTB->Default = Fallthrough;
  8924. BTB->DefaultProb = UnhandledProbs;
  8925. // If the cases in bit test don't form a contiguous range, we evenly
  8926. // distribute the probability on the edge to Fallthrough to two
  8927. // successors of CurMBB.
  8928. if (!BTB->ContiguousRange) {
  8929. BTB->Prob += DefaultProb / 2;
  8930. BTB->DefaultProb -= DefaultProb / 2;
  8931. }
  8932. // If we're in the right place, emit the bit test header right now.
  8933. if (CurMBB == SwitchMBB) {
  8934. visitBitTestHeader(*BTB, SwitchMBB);
  8935. BTB->Emitted = true;
  8936. }
  8937. break;
  8938. }
  8939. case CC_Range: {
  8940. const Value *RHS, *LHS, *MHS;
  8941. ISD::CondCode CC;
  8942. if (I->Low == I->High) {
  8943. // Check Cond == I->Low.
  8944. CC = ISD::SETEQ;
  8945. LHS = Cond;
  8946. RHS=I->Low;
  8947. MHS = nullptr;
  8948. } else {
  8949. // Check I->Low <= Cond <= I->High.
  8950. CC = ISD::SETLE;
  8951. LHS = I->Low;
  8952. MHS = Cond;
  8953. RHS = I->High;
  8954. }
  8955. // If Fallthrough is unreachable, fold away the comparison.
  8956. if (FallthroughUnreachable)
  8957. CC = ISD::SETTRUE;
  8958. // The false probability is the sum of all unhandled cases.
  8959. CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB,
  8960. getCurSDLoc(), I->Prob, UnhandledProbs);
  8961. if (CurMBB == SwitchMBB)
  8962. visitSwitchCase(CB, SwitchMBB);
  8963. else
  8964. SL->SwitchCases.push_back(CB);
  8965. break;
  8966. }
  8967. }
  8968. CurMBB = Fallthrough;
  8969. }
  8970. }
  8971. unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC,
  8972. CaseClusterIt First,
  8973. CaseClusterIt Last) {
  8974. return std::count_if(First, Last + 1, [&](const CaseCluster &X) {
  8975. if (X.Prob != CC.Prob)
  8976. return X.Prob > CC.Prob;
  8977. // Ties are broken by comparing the case value.
  8978. return X.Low->getValue().slt(CC.Low->getValue());
  8979. });
  8980. }
  8981. void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList,
  8982. const SwitchWorkListItem &W,
  8983. Value *Cond,
  8984. MachineBasicBlock *SwitchMBB) {
  8985. assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) &&
  8986. "Clusters not sorted?");
  8987. assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!");
  8988. // Balance the tree based on branch probabilities to create a near-optimal (in
  8989. // terms of search time given key frequency) binary search tree. See e.g. Kurt
  8990. // Mehlhorn "Nearly Optimal Binary Search Trees" (1975).
  8991. CaseClusterIt LastLeft = W.FirstCluster;
  8992. CaseClusterIt FirstRight = W.LastCluster;
  8993. auto LeftProb = LastLeft->Prob + W.DefaultProb / 2;
  8994. auto RightProb = FirstRight->Prob + W.DefaultProb / 2;
  8995. // Move LastLeft and FirstRight towards each other from opposite directions to
  8996. // find a partitioning of the clusters which balances the probability on both
  8997. // sides. If LeftProb and RightProb are equal, alternate which side is
  8998. // taken to ensure 0-probability nodes are distributed evenly.
  8999. unsigned I = 0;
  9000. while (LastLeft + 1 < FirstRight) {
  9001. if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1)))
  9002. LeftProb += (++LastLeft)->Prob;
  9003. else
  9004. RightProb += (--FirstRight)->Prob;
  9005. I++;
  9006. }
  9007. while (true) {
  9008. // Our binary search tree differs from a typical BST in that ours can have up
  9009. // to three values in each leaf. The pivot selection above doesn't take that
  9010. // into account, which means the tree might require more nodes and be less
  9011. // efficient. We compensate for this here.
  9012. unsigned NumLeft = LastLeft - W.FirstCluster + 1;
  9013. unsigned NumRight = W.LastCluster - FirstRight + 1;
  9014. if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) {
  9015. // If one side has less than 3 clusters, and the other has more than 3,
  9016. // consider taking a cluster from the other side.
  9017. if (NumLeft < NumRight) {
  9018. // Consider moving the first cluster on the right to the left side.
  9019. CaseCluster &CC = *FirstRight;
  9020. unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
  9021. unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
  9022. if (LeftSideRank <= RightSideRank) {
  9023. // Moving the cluster to the left does not demote it.
  9024. ++LastLeft;
  9025. ++FirstRight;
  9026. continue;
  9027. }
  9028. } else {
  9029. assert(NumRight < NumLeft);
  9030. // Consider moving the last element on the left to the right side.
  9031. CaseCluster &CC = *LastLeft;
  9032. unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
  9033. unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
  9034. if (RightSideRank <= LeftSideRank) {
  9035. // Moving the cluster to the right does not demot it.
  9036. --LastLeft;
  9037. --FirstRight;
  9038. continue;
  9039. }
  9040. }
  9041. }
  9042. break;
  9043. }
  9044. assert(LastLeft + 1 == FirstRight);
  9045. assert(LastLeft >= W.FirstCluster);
  9046. assert(FirstRight <= W.LastCluster);
  9047. // Use the first element on the right as pivot since we will make less-than
  9048. // comparisons against it.
  9049. CaseClusterIt PivotCluster = FirstRight;
  9050. assert(PivotCluster > W.FirstCluster);
  9051. assert(PivotCluster <= W.LastCluster);
  9052. CaseClusterIt FirstLeft = W.FirstCluster;
  9053. CaseClusterIt LastRight = W.LastCluster;
  9054. const ConstantInt *Pivot = PivotCluster->Low;
  9055. // New blocks will be inserted immediately after the current one.
  9056. MachineFunction::iterator BBI(W.MBB);
  9057. ++BBI;
  9058. // We will branch to the LHS if Value < Pivot. If LHS is a single cluster,
  9059. // we can branch to its destination directly if it's squeezed exactly in
  9060. // between the known lower bound and Pivot - 1.
  9061. MachineBasicBlock *LeftMBB;
  9062. if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range &&
  9063. FirstLeft->Low == W.GE &&
  9064. (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) {
  9065. LeftMBB = FirstLeft->MBB;
  9066. } else {
  9067. LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
  9068. FuncInfo.MF->insert(BBI, LeftMBB);
  9069. WorkList.push_back(
  9070. {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2});
  9071. // Put Cond in a virtual register to make it available from the new blocks.
  9072. ExportFromCurrentBlock(Cond);
  9073. }
  9074. // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a
  9075. // single cluster, RHS.Low == Pivot, and we can branch to its destination
  9076. // directly if RHS.High equals the current upper bound.
  9077. MachineBasicBlock *RightMBB;
  9078. if (FirstRight == LastRight && FirstRight->Kind == CC_Range &&
  9079. W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) {
  9080. RightMBB = FirstRight->MBB;
  9081. } else {
  9082. RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
  9083. FuncInfo.MF->insert(BBI, RightMBB);
  9084. WorkList.push_back(
  9085. {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2});
  9086. // Put Cond in a virtual register to make it available from the new blocks.
  9087. ExportFromCurrentBlock(Cond);
  9088. }
  9089. // Create the CaseBlock record that will be used to lower the branch.
  9090. CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB,
  9091. getCurSDLoc(), LeftProb, RightProb);
  9092. if (W.MBB == SwitchMBB)
  9093. visitSwitchCase(CB, SwitchMBB);
  9094. else
  9095. SL->SwitchCases.push_back(CB);
  9096. }
  9097. // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb
  9098. // from the swith statement.
  9099. static BranchProbability scaleCaseProbality(BranchProbability CaseProb,
  9100. BranchProbability PeeledCaseProb) {
  9101. if (PeeledCaseProb == BranchProbability::getOne())
  9102. return BranchProbability::getZero();
  9103. BranchProbability SwitchProb = PeeledCaseProb.getCompl();
  9104. uint32_t Numerator = CaseProb.getNumerator();
  9105. uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator());
  9106. return BranchProbability(Numerator, std::max(Numerator, Denominator));
  9107. }
  9108. // Try to peel the top probability case if it exceeds the threshold.
  9109. // Return current MachineBasicBlock for the switch statement if the peeling
  9110. // does not occur.
  9111. // If the peeling is performed, return the newly created MachineBasicBlock
  9112. // for the peeled switch statement. Also update Clusters to remove the peeled
  9113. // case. PeeledCaseProb is the BranchProbability for the peeled case.
  9114. MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster(
  9115. const SwitchInst &SI, CaseClusterVector &Clusters,
  9116. BranchProbability &PeeledCaseProb) {
  9117. MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
  9118. // Don't perform if there is only one cluster or optimizing for size.
  9119. if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 ||
  9120. TM.getOptLevel() == CodeGenOpt::None ||
  9121. SwitchMBB->getParent()->getFunction().hasMinSize())
  9122. return SwitchMBB;
  9123. BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100);
  9124. unsigned PeeledCaseIndex = 0;
  9125. bool SwitchPeeled = false;
  9126. for (unsigned Index = 0; Index < Clusters.size(); ++Index) {
  9127. CaseCluster &CC = Clusters[Index];
  9128. if (CC.Prob < TopCaseProb)
  9129. continue;
  9130. TopCaseProb = CC.Prob;
  9131. PeeledCaseIndex = Index;
  9132. SwitchPeeled = true;
  9133. }
  9134. if (!SwitchPeeled)
  9135. return SwitchMBB;
  9136. LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: "
  9137. << TopCaseProb << "\n");
  9138. // Record the MBB for the peeled switch statement.
  9139. MachineFunction::iterator BBI(SwitchMBB);
  9140. ++BBI;
  9141. MachineBasicBlock *PeeledSwitchMBB =
  9142. FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock());
  9143. FuncInfo.MF->insert(BBI, PeeledSwitchMBB);
  9144. ExportFromCurrentBlock(SI.getCondition());
  9145. auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex;
  9146. SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt,
  9147. nullptr, nullptr, TopCaseProb.getCompl()};
  9148. lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB);
  9149. Clusters.erase(PeeledCaseIt);
  9150. for (CaseCluster &CC : Clusters) {
  9151. LLVM_DEBUG(
  9152. dbgs() << "Scale the probablity for one cluster, before scaling: "
  9153. << CC.Prob << "\n");
  9154. CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb);
  9155. LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n");
  9156. }
  9157. PeeledCaseProb = TopCaseProb;
  9158. return PeeledSwitchMBB;
  9159. }
  9160. void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) {
  9161. // Extract cases from the switch.
  9162. BranchProbabilityInfo *BPI = FuncInfo.BPI;
  9163. CaseClusterVector Clusters;
  9164. Clusters.reserve(SI.getNumCases());
  9165. for (auto I : SI.cases()) {
  9166. MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()];
  9167. const ConstantInt *CaseVal = I.getCaseValue();
  9168. BranchProbability Prob =
  9169. BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex())
  9170. : BranchProbability(1, SI.getNumCases() + 1);
  9171. Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob));
  9172. }
  9173. MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()];
  9174. // Cluster adjacent cases with the same destination. We do this at all
  9175. // optimization levels because it's cheap to do and will make codegen faster
  9176. // if there are many clusters.
  9177. sortAndRangeify(Clusters);
  9178. // The branch probablity of the peeled case.
  9179. BranchProbability PeeledCaseProb = BranchProbability::getZero();
  9180. MachineBasicBlock *PeeledSwitchMBB =
  9181. peelDominantCaseCluster(SI, Clusters, PeeledCaseProb);
  9182. // If there is only the default destination, jump there directly.
  9183. MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
  9184. if (Clusters.empty()) {
  9185. assert(PeeledSwitchMBB == SwitchMBB);
  9186. SwitchMBB->addSuccessor(DefaultMBB);
  9187. if (DefaultMBB != NextBlock(SwitchMBB)) {
  9188. DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
  9189. getControlRoot(), DAG.getBasicBlock(DefaultMBB)));
  9190. }
  9191. return;
  9192. }
  9193. SL->findJumpTables(Clusters, &SI, DefaultMBB);
  9194. SL->findBitTestClusters(Clusters, &SI);
  9195. LLVM_DEBUG({
  9196. dbgs() << "Case clusters: ";
  9197. for (const CaseCluster &C : Clusters) {
  9198. if (C.Kind == CC_JumpTable)
  9199. dbgs() << "JT:";
  9200. if (C.Kind == CC_BitTests)
  9201. dbgs() << "BT:";
  9202. C.Low->getValue().print(dbgs(), true);
  9203. if (C.Low != C.High) {
  9204. dbgs() << '-';
  9205. C.High->getValue().print(dbgs(), true);
  9206. }
  9207. dbgs() << ' ';
  9208. }
  9209. dbgs() << '\n';
  9210. });
  9211. assert(!Clusters.empty());
  9212. SwitchWorkList WorkList;
  9213. CaseClusterIt First = Clusters.begin();
  9214. CaseClusterIt Last = Clusters.end() - 1;
  9215. auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB);
  9216. // Scale the branchprobability for DefaultMBB if the peel occurs and
  9217. // DefaultMBB is not replaced.
  9218. if (PeeledCaseProb != BranchProbability::getZero() &&
  9219. DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()])
  9220. DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb);
  9221. WorkList.push_back(
  9222. {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb});
  9223. while (!WorkList.empty()) {
  9224. SwitchWorkListItem W = WorkList.back();
  9225. WorkList.pop_back();
  9226. unsigned NumClusters = W.LastCluster - W.FirstCluster + 1;
  9227. if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None &&
  9228. !DefaultMBB->getParent()->getFunction().hasMinSize()) {
  9229. // For optimized builds, lower large range as a balanced binary tree.
  9230. splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB);
  9231. continue;
  9232. }
  9233. lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB);
  9234. }
  9235. }