SelectionDAGBuilder.cpp 419 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791
  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/TargetFrameLowering.h"
  57. #include "llvm/CodeGen/TargetInstrInfo.h"
  58. #include "llvm/CodeGen/TargetLowering.h"
  59. #include "llvm/CodeGen/TargetOpcodes.h"
  60. #include "llvm/CodeGen/TargetRegisterInfo.h"
  61. #include "llvm/CodeGen/TargetSubtargetInfo.h"
  62. #include "llvm/CodeGen/ValueTypes.h"
  63. #include "llvm/CodeGen/WinEHFuncInfo.h"
  64. #include "llvm/IR/Argument.h"
  65. #include "llvm/IR/Attributes.h"
  66. #include "llvm/IR/BasicBlock.h"
  67. #include "llvm/IR/CFG.h"
  68. #include "llvm/IR/CallSite.h"
  69. #include "llvm/IR/CallingConv.h"
  70. #include "llvm/IR/Constant.h"
  71. #include "llvm/IR/ConstantRange.h"
  72. #include "llvm/IR/Constants.h"
  73. #include "llvm/IR/DataLayout.h"
  74. #include "llvm/IR/DebugInfoMetadata.h"
  75. #include "llvm/IR/DebugLoc.h"
  76. #include "llvm/IR/DerivedTypes.h"
  77. #include "llvm/IR/Function.h"
  78. #include "llvm/IR/GetElementPtrTypeIterator.h"
  79. #include "llvm/IR/InlineAsm.h"
  80. #include "llvm/IR/InstrTypes.h"
  81. #include "llvm/IR/Instruction.h"
  82. #include "llvm/IR/Instructions.h"
  83. #include "llvm/IR/IntrinsicInst.h"
  84. #include "llvm/IR/Intrinsics.h"
  85. #include "llvm/IR/LLVMContext.h"
  86. #include "llvm/IR/Metadata.h"
  87. #include "llvm/IR/Module.h"
  88. #include "llvm/IR/Operator.h"
  89. #include "llvm/IR/PatternMatch.h"
  90. #include "llvm/IR/Statepoint.h"
  91. #include "llvm/IR/Type.h"
  92. #include "llvm/IR/User.h"
  93. #include "llvm/IR/Value.h"
  94. #include "llvm/MC/MCContext.h"
  95. #include "llvm/MC/MCSymbol.h"
  96. #include "llvm/Support/AtomicOrdering.h"
  97. #include "llvm/Support/BranchProbability.h"
  98. #include "llvm/Support/Casting.h"
  99. #include "llvm/Support/CodeGen.h"
  100. #include "llvm/Support/CommandLine.h"
  101. #include "llvm/Support/Compiler.h"
  102. #include "llvm/Support/Debug.h"
  103. #include "llvm/Support/ErrorHandling.h"
  104. #include "llvm/Support/MachineValueType.h"
  105. #include "llvm/Support/MathExtras.h"
  106. #include "llvm/Support/raw_ostream.h"
  107. #include "llvm/Target/TargetIntrinsicInfo.h"
  108. #include "llvm/Target/TargetMachine.h"
  109. #include "llvm/Target/TargetOptions.h"
  110. #include "llvm/Transforms/Utils/Local.h"
  111. #include <algorithm>
  112. #include <cassert>
  113. #include <cstddef>
  114. #include <cstdint>
  115. #include <cstring>
  116. #include <iterator>
  117. #include <limits>
  118. #include <numeric>
  119. #include <tuple>
  120. #include <utility>
  121. #include <vector>
  122. using namespace llvm;
  123. using namespace PatternMatch;
  124. #define DEBUG_TYPE "isel"
  125. /// LimitFloatPrecision - Generate low-precision inline sequences for
  126. /// some float libcalls (6, 8 or 12 bits).
  127. static unsigned LimitFloatPrecision;
  128. static cl::opt<unsigned, true>
  129. LimitFPPrecision("limit-float-precision",
  130. cl::desc("Generate low-precision inline sequences "
  131. "for some float libcalls"),
  132. cl::location(LimitFloatPrecision), cl::Hidden,
  133. cl::init(0));
  134. static cl::opt<unsigned> SwitchPeelThreshold(
  135. "switch-peel-threshold", cl::Hidden, cl::init(66),
  136. cl::desc("Set the case probability threshold for peeling the case from a "
  137. "switch statement. A value greater than 100 will void this "
  138. "optimization"));
  139. // Limit the width of DAG chains. This is important in general to prevent
  140. // DAG-based analysis from blowing up. For example, alias analysis and
  141. // load clustering may not complete in reasonable time. It is difficult to
  142. // recognize and avoid this situation within each individual analysis, and
  143. // future analyses are likely to have the same behavior. Limiting DAG width is
  144. // the safe approach and will be especially important with global DAGs.
  145. //
  146. // MaxParallelChains default is arbitrarily high to avoid affecting
  147. // optimization, but could be lowered to improve compile time. Any ld-ld-st-st
  148. // sequence over this should have been converted to llvm.memcpy by the
  149. // frontend. It is easy to induce this behavior with .ll code such as:
  150. // %buffer = alloca [4096 x i8]
  151. // %data = load [4096 x i8]* %argPtr
  152. // store [4096 x i8] %data, [4096 x i8]* %buffer
  153. static const unsigned MaxParallelChains = 64;
  154. // Return the calling convention if the Value passed requires ABI mangling as it
  155. // is a parameter to a function or a return value from a function which is not
  156. // an intrinsic.
  157. static Optional<CallingConv::ID> getABIRegCopyCC(const Value *V) {
  158. if (auto *R = dyn_cast<ReturnInst>(V))
  159. return R->getParent()->getParent()->getCallingConv();
  160. if (auto *CI = dyn_cast<CallInst>(V)) {
  161. const bool IsInlineAsm = CI->isInlineAsm();
  162. const bool IsIndirectFunctionCall =
  163. !IsInlineAsm && !CI->getCalledFunction();
  164. // It is possible that the call instruction is an inline asm statement or an
  165. // indirect function call in which case the return value of
  166. // getCalledFunction() would be nullptr.
  167. const bool IsInstrinsicCall =
  168. !IsInlineAsm && !IsIndirectFunctionCall &&
  169. CI->getCalledFunction()->getIntrinsicID() != Intrinsic::not_intrinsic;
  170. if (!IsInlineAsm && !IsInstrinsicCall)
  171. return CI->getCallingConv();
  172. }
  173. return None;
  174. }
  175. static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
  176. const SDValue *Parts, unsigned NumParts,
  177. MVT PartVT, EVT ValueVT, const Value *V,
  178. Optional<CallingConv::ID> CC);
  179. /// getCopyFromParts - Create a value that contains the specified legal parts
  180. /// combined into the value they represent. If the parts combine to a type
  181. /// larger than ValueVT then AssertOp can be used to specify whether the extra
  182. /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
  183. /// (ISD::AssertSext).
  184. static SDValue getCopyFromParts(SelectionDAG &DAG, const SDLoc &DL,
  185. const SDValue *Parts, unsigned NumParts,
  186. MVT PartVT, EVT ValueVT, const Value *V,
  187. Optional<CallingConv::ID> CC = None,
  188. Optional<ISD::NodeType> AssertOp = None) {
  189. if (ValueVT.isVector())
  190. return getCopyFromPartsVector(DAG, DL, Parts, NumParts, PartVT, ValueVT, V,
  191. CC);
  192. assert(NumParts > 0 && "No parts to assemble!");
  193. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  194. SDValue Val = Parts[0];
  195. if (NumParts > 1) {
  196. // Assemble the value from multiple parts.
  197. if (ValueVT.isInteger()) {
  198. unsigned PartBits = PartVT.getSizeInBits();
  199. unsigned ValueBits = ValueVT.getSizeInBits();
  200. // Assemble the power of 2 part.
  201. unsigned RoundParts = NumParts & (NumParts - 1) ?
  202. 1 << Log2_32(NumParts) : NumParts;
  203. unsigned RoundBits = PartBits * RoundParts;
  204. EVT RoundVT = RoundBits == ValueBits ?
  205. ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits);
  206. SDValue Lo, Hi;
  207. EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2);
  208. if (RoundParts > 2) {
  209. Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2,
  210. PartVT, HalfVT, V);
  211. Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2,
  212. RoundParts / 2, PartVT, HalfVT, V);
  213. } else {
  214. Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]);
  215. Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]);
  216. }
  217. if (DAG.getDataLayout().isBigEndian())
  218. std::swap(Lo, Hi);
  219. Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi);
  220. if (RoundParts < NumParts) {
  221. // Assemble the trailing non-power-of-2 part.
  222. unsigned OddParts = NumParts - RoundParts;
  223. EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits);
  224. Hi = getCopyFromParts(DAG, DL, Parts + RoundParts, OddParts, PartVT,
  225. OddVT, V, CC);
  226. // Combine the round and odd parts.
  227. Lo = Val;
  228. if (DAG.getDataLayout().isBigEndian())
  229. std::swap(Lo, Hi);
  230. EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
  231. Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi);
  232. Hi =
  233. DAG.getNode(ISD::SHL, DL, TotalVT, Hi,
  234. DAG.getConstant(Lo.getValueSizeInBits(), DL,
  235. TLI.getPointerTy(DAG.getDataLayout())));
  236. Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo);
  237. Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi);
  238. }
  239. } else if (PartVT.isFloatingPoint()) {
  240. // FP split into multiple FP parts (for ppcf128)
  241. assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 &&
  242. "Unexpected split");
  243. SDValue Lo, Hi;
  244. Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]);
  245. Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]);
  246. if (TLI.hasBigEndianPartOrdering(ValueVT, DAG.getDataLayout()))
  247. std::swap(Lo, Hi);
  248. Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi);
  249. } else {
  250. // FP split into integer parts (soft fp)
  251. assert(ValueVT.isFloatingPoint() && PartVT.isInteger() &&
  252. !PartVT.isVector() && "Unexpected split");
  253. EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
  254. Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V, CC);
  255. }
  256. }
  257. // There is now one part, held in Val. Correct it to match ValueVT.
  258. // PartEVT is the type of the register class that holds the value.
  259. // ValueVT is the type of the inline asm operation.
  260. EVT PartEVT = Val.getValueType();
  261. if (PartEVT == ValueVT)
  262. return Val;
  263. if (PartEVT.isInteger() && ValueVT.isFloatingPoint() &&
  264. ValueVT.bitsLT(PartEVT)) {
  265. // For an FP value in an integer part, we need to truncate to the right
  266. // width first.
  267. PartEVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
  268. Val = DAG.getNode(ISD::TRUNCATE, DL, PartEVT, Val);
  269. }
  270. // Handle types that have the same size.
  271. if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits())
  272. return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
  273. // Handle types with different sizes.
  274. if (PartEVT.isInteger() && ValueVT.isInteger()) {
  275. if (ValueVT.bitsLT(PartEVT)) {
  276. // For a truncate, see if we have any information to
  277. // indicate whether the truncated bits will always be
  278. // zero or sign-extension.
  279. if (AssertOp.hasValue())
  280. Val = DAG.getNode(*AssertOp, DL, PartEVT, Val,
  281. DAG.getValueType(ValueVT));
  282. return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
  283. }
  284. return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val);
  285. }
  286. if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
  287. // FP_ROUND's are always exact here.
  288. if (ValueVT.bitsLT(Val.getValueType()))
  289. return DAG.getNode(
  290. ISD::FP_ROUND, DL, ValueVT, Val,
  291. DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout())));
  292. return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val);
  293. }
  294. llvm_unreachable("Unknown mismatch!");
  295. }
  296. static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V,
  297. const Twine &ErrMsg) {
  298. const Instruction *I = dyn_cast_or_null<Instruction>(V);
  299. if (!V)
  300. return Ctx.emitError(ErrMsg);
  301. const char *AsmError = ", possible invalid constraint for vector type";
  302. if (const CallInst *CI = dyn_cast<CallInst>(I))
  303. if (isa<InlineAsm>(CI->getCalledValue()))
  304. return Ctx.emitError(I, ErrMsg + AsmError);
  305. return Ctx.emitError(I, ErrMsg);
  306. }
  307. /// getCopyFromPartsVector - Create a value that contains the specified legal
  308. /// parts combined into the value they represent. If the parts combine to a
  309. /// type larger than ValueVT then AssertOp can be used to specify whether the
  310. /// extra bits are known to be zero (ISD::AssertZext) or sign extended from
  311. /// ValueVT (ISD::AssertSext).
  312. static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
  313. const SDValue *Parts, unsigned NumParts,
  314. MVT PartVT, EVT ValueVT, const Value *V,
  315. Optional<CallingConv::ID> CallConv) {
  316. assert(ValueVT.isVector() && "Not a vector value");
  317. assert(NumParts > 0 && "No parts to assemble!");
  318. const bool IsABIRegCopy = CallConv.hasValue();
  319. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  320. SDValue Val = Parts[0];
  321. // Handle a multi-element vector.
  322. if (NumParts > 1) {
  323. EVT IntermediateVT;
  324. MVT RegisterVT;
  325. unsigned NumIntermediates;
  326. unsigned NumRegs;
  327. if (IsABIRegCopy) {
  328. NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
  329. *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT,
  330. NumIntermediates, RegisterVT);
  331. } else {
  332. NumRegs =
  333. TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
  334. NumIntermediates, RegisterVT);
  335. }
  336. assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
  337. NumParts = NumRegs; // Silence a compiler warning.
  338. assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
  339. assert(RegisterVT.getSizeInBits() ==
  340. Parts[0].getSimpleValueType().getSizeInBits() &&
  341. "Part type sizes don't match!");
  342. // Assemble the parts into intermediate operands.
  343. SmallVector<SDValue, 8> Ops(NumIntermediates);
  344. if (NumIntermediates == NumParts) {
  345. // If the register was not expanded, truncate or copy the value,
  346. // as appropriate.
  347. for (unsigned i = 0; i != NumParts; ++i)
  348. Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1,
  349. PartVT, IntermediateVT, V);
  350. } else if (NumParts > 0) {
  351. // If the intermediate type was expanded, build the intermediate
  352. // operands from the parts.
  353. assert(NumParts % NumIntermediates == 0 &&
  354. "Must expand into a divisible number of parts!");
  355. unsigned Factor = NumParts / NumIntermediates;
  356. for (unsigned i = 0; i != NumIntermediates; ++i)
  357. Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor,
  358. PartVT, IntermediateVT, V);
  359. }
  360. // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the
  361. // intermediate operands.
  362. EVT BuiltVectorTy =
  363. EVT::getVectorVT(*DAG.getContext(), IntermediateVT.getScalarType(),
  364. (IntermediateVT.isVector()
  365. ? IntermediateVT.getVectorNumElements() * NumParts
  366. : NumIntermediates));
  367. Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS
  368. : ISD::BUILD_VECTOR,
  369. DL, BuiltVectorTy, Ops);
  370. }
  371. // There is now one part, held in Val. Correct it to match ValueVT.
  372. EVT PartEVT = Val.getValueType();
  373. if (PartEVT == ValueVT)
  374. return Val;
  375. if (PartEVT.isVector()) {
  376. // If the element type of the source/dest vectors are the same, but the
  377. // parts vector has more elements than the value vector, then we have a
  378. // vector widening case (e.g. <2 x float> -> <4 x float>). Extract the
  379. // elements we want.
  380. if (PartEVT.getVectorElementType() == ValueVT.getVectorElementType()) {
  381. assert(PartEVT.getVectorNumElements() > ValueVT.getVectorNumElements() &&
  382. "Cannot narrow, it would be a lossy transformation");
  383. return DAG.getNode(
  384. ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
  385. DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
  386. }
  387. // Vector/Vector bitcast.
  388. if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits())
  389. return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
  390. assert(PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements() &&
  391. "Cannot handle this kind of promotion");
  392. // Promoted vector extract
  393. return DAG.getAnyExtOrTrunc(Val, DL, ValueVT);
  394. }
  395. // Trivial bitcast if the types are the same size and the destination
  396. // vector type is legal.
  397. if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() &&
  398. TLI.isTypeLegal(ValueVT))
  399. return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
  400. if (ValueVT.getVectorNumElements() != 1) {
  401. // Certain ABIs require that vectors are passed as integers. For vectors
  402. // are the same size, this is an obvious bitcast.
  403. if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) {
  404. return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
  405. } else if (ValueVT.getSizeInBits() < PartEVT.getSizeInBits()) {
  406. // Bitcast Val back the original type and extract the corresponding
  407. // vector we want.
  408. unsigned Elts = PartEVT.getSizeInBits() / ValueVT.getScalarSizeInBits();
  409. EVT WiderVecType = EVT::getVectorVT(*DAG.getContext(),
  410. ValueVT.getVectorElementType(), Elts);
  411. Val = DAG.getBitcast(WiderVecType, Val);
  412. return DAG.getNode(
  413. ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
  414. DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
  415. }
  416. diagnosePossiblyInvalidConstraint(
  417. *DAG.getContext(), V, "non-trivial scalar-to-vector conversion");
  418. return DAG.getUNDEF(ValueVT);
  419. }
  420. // Handle cases such as i8 -> <1 x i1>
  421. EVT ValueSVT = ValueVT.getVectorElementType();
  422. if (ValueVT.getVectorNumElements() == 1 && ValueSVT != PartEVT)
  423. Val = ValueVT.isFloatingPoint() ? DAG.getFPExtendOrRound(Val, DL, ValueSVT)
  424. : DAG.getAnyExtOrTrunc(Val, DL, ValueSVT);
  425. return DAG.getBuildVector(ValueVT, DL, Val);
  426. }
  427. static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl,
  428. SDValue Val, SDValue *Parts, unsigned NumParts,
  429. MVT PartVT, const Value *V,
  430. Optional<CallingConv::ID> CallConv);
  431. /// getCopyToParts - Create a series of nodes that contain the specified value
  432. /// split into legal parts. If the parts contain more bits than Val, then, for
  433. /// integers, ExtendKind can be used to specify how to generate the extra bits.
  434. static void getCopyToParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val,
  435. SDValue *Parts, unsigned NumParts, MVT PartVT,
  436. const Value *V,
  437. Optional<CallingConv::ID> CallConv = None,
  438. ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
  439. EVT ValueVT = Val.getValueType();
  440. // Handle the vector case separately.
  441. if (ValueVT.isVector())
  442. return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V,
  443. CallConv);
  444. unsigned PartBits = PartVT.getSizeInBits();
  445. unsigned OrigNumParts = NumParts;
  446. assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) &&
  447. "Copying to an illegal type!");
  448. if (NumParts == 0)
  449. return;
  450. assert(!ValueVT.isVector() && "Vector case handled elsewhere");
  451. EVT PartEVT = PartVT;
  452. if (PartEVT == ValueVT) {
  453. assert(NumParts == 1 && "No-op copy with multiple parts!");
  454. Parts[0] = Val;
  455. return;
  456. }
  457. if (NumParts * PartBits > ValueVT.getSizeInBits()) {
  458. // If the parts cover more bits than the value has, promote the value.
  459. if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
  460. assert(NumParts == 1 && "Do not know what to promote to!");
  461. Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val);
  462. } else {
  463. if (ValueVT.isFloatingPoint()) {
  464. // FP values need to be bitcast, then extended if they are being put
  465. // into a larger container.
  466. ValueVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
  467. Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
  468. }
  469. assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
  470. ValueVT.isInteger() &&
  471. "Unknown mismatch!");
  472. ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
  473. Val = DAG.getNode(ExtendKind, DL, ValueVT, Val);
  474. if (PartVT == MVT::x86mmx)
  475. Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
  476. }
  477. } else if (PartBits == ValueVT.getSizeInBits()) {
  478. // Different types of the same size.
  479. assert(NumParts == 1 && PartEVT != ValueVT);
  480. Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
  481. } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
  482. // If the parts cover less bits than value has, truncate the value.
  483. assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
  484. ValueVT.isInteger() &&
  485. "Unknown mismatch!");
  486. ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
  487. Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
  488. if (PartVT == MVT::x86mmx)
  489. Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
  490. }
  491. // The value may have changed - recompute ValueVT.
  492. ValueVT = Val.getValueType();
  493. assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
  494. "Failed to tile the value with PartVT!");
  495. if (NumParts == 1) {
  496. if (PartEVT != ValueVT) {
  497. diagnosePossiblyInvalidConstraint(*DAG.getContext(), V,
  498. "scalar-to-vector conversion failed");
  499. Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
  500. }
  501. Parts[0] = Val;
  502. return;
  503. }
  504. // Expand the value into multiple parts.
  505. if (NumParts & (NumParts - 1)) {
  506. // The number of parts is not a power of 2. Split off and copy the tail.
  507. assert(PartVT.isInteger() && ValueVT.isInteger() &&
  508. "Do not know what to expand to!");
  509. unsigned RoundParts = 1 << Log2_32(NumParts);
  510. unsigned RoundBits = RoundParts * PartBits;
  511. unsigned OddParts = NumParts - RoundParts;
  512. SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val,
  513. DAG.getShiftAmountConstant(RoundBits, ValueVT, DL, /*LegalTypes*/false));
  514. getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V,
  515. CallConv);
  516. if (DAG.getDataLayout().isBigEndian())
  517. // The odd parts were reversed by getCopyToParts - unreverse them.
  518. std::reverse(Parts + RoundParts, Parts + NumParts);
  519. NumParts = RoundParts;
  520. ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
  521. Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
  522. }
  523. // The number of parts is a power of 2. Repeatedly bisect the value using
  524. // EXTRACT_ELEMENT.
  525. Parts[0] = DAG.getNode(ISD::BITCAST, DL,
  526. EVT::getIntegerVT(*DAG.getContext(),
  527. ValueVT.getSizeInBits()),
  528. Val);
  529. for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
  530. for (unsigned i = 0; i < NumParts; i += StepSize) {
  531. unsigned ThisBits = StepSize * PartBits / 2;
  532. EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits);
  533. SDValue &Part0 = Parts[i];
  534. SDValue &Part1 = Parts[i+StepSize/2];
  535. Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
  536. ThisVT, Part0, DAG.getIntPtrConstant(1, DL));
  537. Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
  538. ThisVT, Part0, DAG.getIntPtrConstant(0, DL));
  539. if (ThisBits == PartBits && ThisVT != PartVT) {
  540. Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0);
  541. Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1);
  542. }
  543. }
  544. }
  545. if (DAG.getDataLayout().isBigEndian())
  546. std::reverse(Parts, Parts + OrigNumParts);
  547. }
  548. static SDValue widenVectorToPartType(SelectionDAG &DAG,
  549. SDValue Val, const SDLoc &DL, EVT PartVT) {
  550. if (!PartVT.isVector())
  551. return SDValue();
  552. EVT ValueVT = Val.getValueType();
  553. unsigned PartNumElts = PartVT.getVectorNumElements();
  554. unsigned ValueNumElts = ValueVT.getVectorNumElements();
  555. if (PartNumElts > ValueNumElts &&
  556. PartVT.getVectorElementType() == ValueVT.getVectorElementType()) {
  557. EVT ElementVT = PartVT.getVectorElementType();
  558. // Vector widening case, e.g. <2 x float> -> <4 x float>. Shuffle in
  559. // undef elements.
  560. SmallVector<SDValue, 16> Ops;
  561. DAG.ExtractVectorElements(Val, Ops);
  562. SDValue EltUndef = DAG.getUNDEF(ElementVT);
  563. for (unsigned i = ValueNumElts, e = PartNumElts; i != e; ++i)
  564. Ops.push_back(EltUndef);
  565. // FIXME: Use CONCAT for 2x -> 4x.
  566. return DAG.getBuildVector(PartVT, DL, Ops);
  567. }
  568. return SDValue();
  569. }
  570. /// getCopyToPartsVector - Create a series of nodes that contain the specified
  571. /// value split into legal parts.
  572. static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL,
  573. SDValue Val, SDValue *Parts, unsigned NumParts,
  574. MVT PartVT, const Value *V,
  575. Optional<CallingConv::ID> CallConv) {
  576. EVT ValueVT = Val.getValueType();
  577. assert(ValueVT.isVector() && "Not a vector");
  578. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  579. const bool IsABIRegCopy = CallConv.hasValue();
  580. if (NumParts == 1) {
  581. EVT PartEVT = PartVT;
  582. if (PartEVT == ValueVT) {
  583. // Nothing to do.
  584. } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) {
  585. // Bitconvert vector->vector case.
  586. Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
  587. } else if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, PartVT)) {
  588. Val = Widened;
  589. } else if (PartVT.isVector() &&
  590. PartEVT.getVectorElementType().bitsGE(
  591. ValueVT.getVectorElementType()) &&
  592. PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements()) {
  593. // Promoted vector extract
  594. Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
  595. } else {
  596. if (ValueVT.getVectorNumElements() == 1) {
  597. Val = DAG.getNode(
  598. ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val,
  599. DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
  600. } else {
  601. assert(PartVT.getSizeInBits() > ValueVT.getSizeInBits() &&
  602. "lossy conversion of vector to scalar type");
  603. EVT IntermediateType =
  604. EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
  605. Val = DAG.getBitcast(IntermediateType, Val);
  606. Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
  607. }
  608. }
  609. assert(Val.getValueType() == PartVT && "Unexpected vector part value type");
  610. Parts[0] = Val;
  611. return;
  612. }
  613. // Handle a multi-element vector.
  614. EVT IntermediateVT;
  615. MVT RegisterVT;
  616. unsigned NumIntermediates;
  617. unsigned NumRegs;
  618. if (IsABIRegCopy) {
  619. NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
  620. *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT,
  621. NumIntermediates, RegisterVT);
  622. } else {
  623. NumRegs =
  624. TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
  625. NumIntermediates, RegisterVT);
  626. }
  627. assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
  628. NumParts = NumRegs; // Silence a compiler warning.
  629. assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
  630. unsigned IntermediateNumElts = IntermediateVT.isVector() ?
  631. IntermediateVT.getVectorNumElements() : 1;
  632. // Convert the vector to the appropiate type if necessary.
  633. unsigned DestVectorNoElts = NumIntermediates * IntermediateNumElts;
  634. EVT BuiltVectorTy = EVT::getVectorVT(
  635. *DAG.getContext(), IntermediateVT.getScalarType(), DestVectorNoElts);
  636. MVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout());
  637. if (ValueVT != BuiltVectorTy) {
  638. if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, BuiltVectorTy))
  639. Val = Widened;
  640. Val = DAG.getNode(ISD::BITCAST, DL, BuiltVectorTy, Val);
  641. }
  642. // Split the vector into intermediate operands.
  643. SmallVector<SDValue, 8> Ops(NumIntermediates);
  644. for (unsigned i = 0; i != NumIntermediates; ++i) {
  645. if (IntermediateVT.isVector()) {
  646. Ops[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val,
  647. DAG.getConstant(i * IntermediateNumElts, DL, IdxVT));
  648. } else {
  649. Ops[i] = DAG.getNode(
  650. ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val,
  651. DAG.getConstant(i, DL, IdxVT));
  652. }
  653. }
  654. // Split the intermediate operands into legal parts.
  655. if (NumParts == NumIntermediates) {
  656. // If the register was not expanded, promote or copy the value,
  657. // as appropriate.
  658. for (unsigned i = 0; i != NumParts; ++i)
  659. getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V, CallConv);
  660. } else if (NumParts > 0) {
  661. // If the intermediate type was expanded, split each the value into
  662. // legal parts.
  663. assert(NumIntermediates != 0 && "division by zero");
  664. assert(NumParts % NumIntermediates == 0 &&
  665. "Must expand into a divisible number of parts!");
  666. unsigned Factor = NumParts / NumIntermediates;
  667. for (unsigned i = 0; i != NumIntermediates; ++i)
  668. getCopyToParts(DAG, DL, Ops[i], &Parts[i * Factor], Factor, PartVT, V,
  669. CallConv);
  670. }
  671. }
  672. RegsForValue::RegsForValue(const SmallVector<unsigned, 4> &regs, MVT regvt,
  673. EVT valuevt, Optional<CallingConv::ID> CC)
  674. : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs),
  675. RegCount(1, regs.size()), CallConv(CC) {}
  676. RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI,
  677. const DataLayout &DL, unsigned Reg, Type *Ty,
  678. Optional<CallingConv::ID> CC) {
  679. ComputeValueVTs(TLI, DL, Ty, ValueVTs);
  680. CallConv = CC;
  681. for (EVT ValueVT : ValueVTs) {
  682. unsigned NumRegs =
  683. isABIMangled()
  684. ? TLI.getNumRegistersForCallingConv(Context, CC.getValue(), ValueVT)
  685. : TLI.getNumRegisters(Context, ValueVT);
  686. MVT RegisterVT =
  687. isABIMangled()
  688. ? TLI.getRegisterTypeForCallingConv(Context, CC.getValue(), ValueVT)
  689. : TLI.getRegisterType(Context, ValueVT);
  690. for (unsigned i = 0; i != NumRegs; ++i)
  691. Regs.push_back(Reg + i);
  692. RegVTs.push_back(RegisterVT);
  693. RegCount.push_back(NumRegs);
  694. Reg += NumRegs;
  695. }
  696. }
  697. SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
  698. FunctionLoweringInfo &FuncInfo,
  699. const SDLoc &dl, SDValue &Chain,
  700. SDValue *Flag, const Value *V) const {
  701. // A Value with type {} or [0 x %t] needs no registers.
  702. if (ValueVTs.empty())
  703. return SDValue();
  704. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  705. // Assemble the legal parts into the final values.
  706. SmallVector<SDValue, 4> Values(ValueVTs.size());
  707. SmallVector<SDValue, 8> Parts;
  708. for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
  709. // Copy the legal parts from the registers.
  710. EVT ValueVT = ValueVTs[Value];
  711. unsigned NumRegs = RegCount[Value];
  712. MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv(
  713. *DAG.getContext(),
  714. CallConv.getValue(), RegVTs[Value])
  715. : RegVTs[Value];
  716. Parts.resize(NumRegs);
  717. for (unsigned i = 0; i != NumRegs; ++i) {
  718. SDValue P;
  719. if (!Flag) {
  720. P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT);
  721. } else {
  722. P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag);
  723. *Flag = P.getValue(2);
  724. }
  725. Chain = P.getValue(1);
  726. Parts[i] = P;
  727. // If the source register was virtual and if we know something about it,
  728. // add an assert node.
  729. if (!TargetRegisterInfo::isVirtualRegister(Regs[Part+i]) ||
  730. !RegisterVT.isInteger())
  731. continue;
  732. const FunctionLoweringInfo::LiveOutInfo *LOI =
  733. FuncInfo.GetLiveOutRegInfo(Regs[Part+i]);
  734. if (!LOI)
  735. continue;
  736. unsigned RegSize = RegisterVT.getScalarSizeInBits();
  737. unsigned NumSignBits = LOI->NumSignBits;
  738. unsigned NumZeroBits = LOI->Known.countMinLeadingZeros();
  739. if (NumZeroBits == RegSize) {
  740. // The current value is a zero.
  741. // Explicitly express that as it would be easier for
  742. // optimizations to kick in.
  743. Parts[i] = DAG.getConstant(0, dl, RegisterVT);
  744. continue;
  745. }
  746. // FIXME: We capture more information than the dag can represent. For
  747. // now, just use the tightest assertzext/assertsext possible.
  748. bool isSExt;
  749. EVT FromVT(MVT::Other);
  750. if (NumZeroBits) {
  751. FromVT = EVT::getIntegerVT(*DAG.getContext(), RegSize - NumZeroBits);
  752. isSExt = false;
  753. } else if (NumSignBits > 1) {
  754. FromVT =
  755. EVT::getIntegerVT(*DAG.getContext(), RegSize - NumSignBits + 1);
  756. isSExt = true;
  757. } else {
  758. continue;
  759. }
  760. // Add an assertion node.
  761. assert(FromVT != MVT::Other);
  762. Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl,
  763. RegisterVT, P, DAG.getValueType(FromVT));
  764. }
  765. Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(), NumRegs,
  766. RegisterVT, ValueVT, V, CallConv);
  767. Part += NumRegs;
  768. Parts.clear();
  769. }
  770. return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values);
  771. }
  772. void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG,
  773. const SDLoc &dl, SDValue &Chain, SDValue *Flag,
  774. const Value *V,
  775. ISD::NodeType PreferredExtendType) const {
  776. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  777. ISD::NodeType ExtendKind = PreferredExtendType;
  778. // Get the list of the values's legal parts.
  779. unsigned NumRegs = Regs.size();
  780. SmallVector<SDValue, 8> Parts(NumRegs);
  781. for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
  782. unsigned NumParts = RegCount[Value];
  783. MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv(
  784. *DAG.getContext(),
  785. CallConv.getValue(), RegVTs[Value])
  786. : RegVTs[Value];
  787. if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT))
  788. ExtendKind = ISD::ZERO_EXTEND;
  789. getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value), &Parts[Part],
  790. NumParts, RegisterVT, V, CallConv, ExtendKind);
  791. Part += NumParts;
  792. }
  793. // Copy the parts into the registers.
  794. SmallVector<SDValue, 8> Chains(NumRegs);
  795. for (unsigned i = 0; i != NumRegs; ++i) {
  796. SDValue Part;
  797. if (!Flag) {
  798. Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]);
  799. } else {
  800. Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag);
  801. *Flag = Part.getValue(1);
  802. }
  803. Chains[i] = Part.getValue(0);
  804. }
  805. if (NumRegs == 1 || Flag)
  806. // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
  807. // flagged to it. That is the CopyToReg nodes and the user are considered
  808. // a single scheduling unit. If we create a TokenFactor and return it as
  809. // chain, then the TokenFactor is both a predecessor (operand) of the
  810. // user as well as a successor (the TF operands are flagged to the user).
  811. // c1, f1 = CopyToReg
  812. // c2, f2 = CopyToReg
  813. // c3 = TokenFactor c1, c2
  814. // ...
  815. // = op c3, ..., f2
  816. Chain = Chains[NumRegs-1];
  817. else
  818. Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
  819. }
  820. void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching,
  821. unsigned MatchingIdx, const SDLoc &dl,
  822. SelectionDAG &DAG,
  823. std::vector<SDValue> &Ops) const {
  824. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  825. unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size());
  826. if (HasMatching)
  827. Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx);
  828. else if (!Regs.empty() &&
  829. TargetRegisterInfo::isVirtualRegister(Regs.front())) {
  830. // Put the register class of the virtual registers in the flag word. That
  831. // way, later passes can recompute register class constraints for inline
  832. // assembly as well as normal instructions.
  833. // Don't do this for tied operands that can use the regclass information
  834. // from the def.
  835. const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
  836. const TargetRegisterClass *RC = MRI.getRegClass(Regs.front());
  837. Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID());
  838. }
  839. SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32);
  840. Ops.push_back(Res);
  841. if (Code == InlineAsm::Kind_Clobber) {
  842. // Clobbers should always have a 1:1 mapping with registers, and may
  843. // reference registers that have illegal (e.g. vector) types. Hence, we
  844. // shouldn't try to apply any sort of splitting logic to them.
  845. assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() &&
  846. "No 1:1 mapping from clobbers to regs?");
  847. unsigned SP = TLI.getStackPointerRegisterToSaveRestore();
  848. (void)SP;
  849. for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) {
  850. Ops.push_back(DAG.getRegister(Regs[I], RegVTs[I]));
  851. assert(
  852. (Regs[I] != SP ||
  853. DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment()) &&
  854. "If we clobbered the stack pointer, MFI should know about it.");
  855. }
  856. return;
  857. }
  858. for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
  859. unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value]);
  860. MVT RegisterVT = RegVTs[Value];
  861. for (unsigned i = 0; i != NumRegs; ++i) {
  862. assert(Reg < Regs.size() && "Mismatch in # registers expected");
  863. unsigned TheReg = Regs[Reg++];
  864. Ops.push_back(DAG.getRegister(TheReg, RegisterVT));
  865. }
  866. }
  867. }
  868. SmallVector<std::pair<unsigned, unsigned>, 4>
  869. RegsForValue::getRegsAndSizes() const {
  870. SmallVector<std::pair<unsigned, unsigned>, 4> OutVec;
  871. unsigned I = 0;
  872. for (auto CountAndVT : zip_first(RegCount, RegVTs)) {
  873. unsigned RegCount = std::get<0>(CountAndVT);
  874. MVT RegisterVT = std::get<1>(CountAndVT);
  875. unsigned RegisterSize = RegisterVT.getSizeInBits();
  876. for (unsigned E = I + RegCount; I != E; ++I)
  877. OutVec.push_back(std::make_pair(Regs[I], RegisterSize));
  878. }
  879. return OutVec;
  880. }
  881. void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis *aa,
  882. const TargetLibraryInfo *li) {
  883. AA = aa;
  884. GFI = gfi;
  885. LibInfo = li;
  886. DL = &DAG.getDataLayout();
  887. Context = DAG.getContext();
  888. LPadToCallSiteMap.clear();
  889. }
  890. void SelectionDAGBuilder::clear() {
  891. NodeMap.clear();
  892. UnusedArgNodeMap.clear();
  893. PendingLoads.clear();
  894. PendingExports.clear();
  895. CurInst = nullptr;
  896. HasTailCall = false;
  897. SDNodeOrder = LowestSDNodeOrder;
  898. StatepointLowering.clear();
  899. }
  900. void SelectionDAGBuilder::clearDanglingDebugInfo() {
  901. DanglingDebugInfoMap.clear();
  902. }
  903. SDValue SelectionDAGBuilder::getRoot() {
  904. if (PendingLoads.empty())
  905. return DAG.getRoot();
  906. if (PendingLoads.size() == 1) {
  907. SDValue Root = PendingLoads[0];
  908. DAG.setRoot(Root);
  909. PendingLoads.clear();
  910. return Root;
  911. }
  912. // Otherwise, we have to make a token factor node.
  913. SDValue Root = DAG.getTokenFactor(getCurSDLoc(), PendingLoads);
  914. PendingLoads.clear();
  915. DAG.setRoot(Root);
  916. return Root;
  917. }
  918. SDValue SelectionDAGBuilder::getControlRoot() {
  919. SDValue Root = DAG.getRoot();
  920. if (PendingExports.empty())
  921. return Root;
  922. // Turn all of the CopyToReg chains into one factored node.
  923. if (Root.getOpcode() != ISD::EntryToken) {
  924. unsigned i = 0, e = PendingExports.size();
  925. for (; i != e; ++i) {
  926. assert(PendingExports[i].getNode()->getNumOperands() > 1);
  927. if (PendingExports[i].getNode()->getOperand(0) == Root)
  928. break; // Don't add the root if we already indirectly depend on it.
  929. }
  930. if (i == e)
  931. PendingExports.push_back(Root);
  932. }
  933. Root = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other,
  934. PendingExports);
  935. PendingExports.clear();
  936. DAG.setRoot(Root);
  937. return Root;
  938. }
  939. void SelectionDAGBuilder::visit(const Instruction &I) {
  940. // Set up outgoing PHI node register values before emitting the terminator.
  941. if (I.isTerminator()) {
  942. HandlePHINodesInSuccessorBlocks(I.getParent());
  943. }
  944. // Increase the SDNodeOrder if dealing with a non-debug instruction.
  945. if (!isa<DbgInfoIntrinsic>(I))
  946. ++SDNodeOrder;
  947. CurInst = &I;
  948. visit(I.getOpcode(), I);
  949. if (auto *FPMO = dyn_cast<FPMathOperator>(&I)) {
  950. // Propagate the fast-math-flags of this IR instruction to the DAG node that
  951. // maps to this instruction.
  952. // TODO: We could handle all flags (nsw, etc) here.
  953. // TODO: If an IR instruction maps to >1 node, only the final node will have
  954. // flags set.
  955. if (SDNode *Node = getNodeForIRValue(&I)) {
  956. SDNodeFlags IncomingFlags;
  957. IncomingFlags.copyFMF(*FPMO);
  958. if (!Node->getFlags().isDefined())
  959. Node->setFlags(IncomingFlags);
  960. else
  961. Node->intersectFlagsWith(IncomingFlags);
  962. }
  963. }
  964. if (!I.isTerminator() && !HasTailCall &&
  965. !isStatepoint(&I)) // statepoints handle their exports internally
  966. CopyToExportRegsIfNeeded(&I);
  967. CurInst = nullptr;
  968. }
  969. void SelectionDAGBuilder::visitPHI(const PHINode &) {
  970. llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!");
  971. }
  972. void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) {
  973. // Note: this doesn't use InstVisitor, because it has to work with
  974. // ConstantExpr's in addition to instructions.
  975. switch (Opcode) {
  976. default: llvm_unreachable("Unknown instruction type encountered!");
  977. // Build the switch statement using the Instruction.def file.
  978. #define HANDLE_INST(NUM, OPCODE, CLASS) \
  979. case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break;
  980. #include "llvm/IR/Instruction.def"
  981. }
  982. }
  983. void SelectionDAGBuilder::dropDanglingDebugInfo(const DILocalVariable *Variable,
  984. const DIExpression *Expr) {
  985. auto isMatchingDbgValue = [&](DanglingDebugInfo &DDI) {
  986. const DbgValueInst *DI = DDI.getDI();
  987. DIVariable *DanglingVariable = DI->getVariable();
  988. DIExpression *DanglingExpr = DI->getExpression();
  989. if (DanglingVariable == Variable && Expr->fragmentsOverlap(DanglingExpr)) {
  990. LLVM_DEBUG(dbgs() << "Dropping dangling debug info for " << *DI << "\n");
  991. return true;
  992. }
  993. return false;
  994. };
  995. for (auto &DDIMI : DanglingDebugInfoMap) {
  996. DanglingDebugInfoVector &DDIV = DDIMI.second;
  997. // If debug info is to be dropped, run it through final checks to see
  998. // whether it can be salvaged.
  999. for (auto &DDI : DDIV)
  1000. if (isMatchingDbgValue(DDI))
  1001. salvageUnresolvedDbgValue(DDI);
  1002. DDIV.erase(remove_if(DDIV, isMatchingDbgValue), DDIV.end());
  1003. }
  1004. }
  1005. // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V,
  1006. // generate the debug data structures now that we've seen its definition.
  1007. void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V,
  1008. SDValue Val) {
  1009. auto DanglingDbgInfoIt = DanglingDebugInfoMap.find(V);
  1010. if (DanglingDbgInfoIt == DanglingDebugInfoMap.end())
  1011. return;
  1012. DanglingDebugInfoVector &DDIV = DanglingDbgInfoIt->second;
  1013. for (auto &DDI : DDIV) {
  1014. const DbgValueInst *DI = DDI.getDI();
  1015. assert(DI && "Ill-formed DanglingDebugInfo");
  1016. DebugLoc dl = DDI.getdl();
  1017. unsigned ValSDNodeOrder = Val.getNode()->getIROrder();
  1018. unsigned DbgSDNodeOrder = DDI.getSDNodeOrder();
  1019. DILocalVariable *Variable = DI->getVariable();
  1020. DIExpression *Expr = DI->getExpression();
  1021. assert(Variable->isValidLocationForIntrinsic(dl) &&
  1022. "Expected inlined-at fields to agree");
  1023. SDDbgValue *SDV;
  1024. if (Val.getNode()) {
  1025. // FIXME: I doubt that it is correct to resolve a dangling DbgValue as a
  1026. // FuncArgumentDbgValue (it would be hoisted to the function entry, and if
  1027. // we couldn't resolve it directly when examining the DbgValue intrinsic
  1028. // in the first place we should not be more successful here). Unless we
  1029. // have some test case that prove this to be correct we should avoid
  1030. // calling EmitFuncArgumentDbgValue here.
  1031. if (!EmitFuncArgumentDbgValue(V, Variable, Expr, dl, false, Val)) {
  1032. LLVM_DEBUG(dbgs() << "Resolve dangling debug info [order="
  1033. << DbgSDNodeOrder << "] for:\n " << *DI << "\n");
  1034. LLVM_DEBUG(dbgs() << " By mapping to:\n "; Val.dump());
  1035. // Increase the SDNodeOrder for the DbgValue here to make sure it is
  1036. // inserted after the definition of Val when emitting the instructions
  1037. // after ISel. An alternative could be to teach
  1038. // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly.
  1039. LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs()
  1040. << "changing SDNodeOrder from " << DbgSDNodeOrder << " to "
  1041. << ValSDNodeOrder << "\n");
  1042. SDV = getDbgValue(Val, Variable, Expr, dl,
  1043. std::max(DbgSDNodeOrder, ValSDNodeOrder));
  1044. DAG.AddDbgValue(SDV, Val.getNode(), false);
  1045. } else
  1046. LLVM_DEBUG(dbgs() << "Resolved dangling debug info for " << *DI
  1047. << "in EmitFuncArgumentDbgValue\n");
  1048. } else {
  1049. LLVM_DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
  1050. auto Undef =
  1051. UndefValue::get(DDI.getDI()->getVariableLocation()->getType());
  1052. auto SDV =
  1053. DAG.getConstantDbgValue(Variable, Expr, Undef, dl, DbgSDNodeOrder);
  1054. DAG.AddDbgValue(SDV, nullptr, false);
  1055. }
  1056. }
  1057. DDIV.clear();
  1058. }
  1059. void SelectionDAGBuilder::salvageUnresolvedDbgValue(DanglingDebugInfo &DDI) {
  1060. Value *V = DDI.getDI()->getValue();
  1061. DILocalVariable *Var = DDI.getDI()->getVariable();
  1062. DIExpression *Expr = DDI.getDI()->getExpression();
  1063. DebugLoc DL = DDI.getdl();
  1064. DebugLoc InstDL = DDI.getDI()->getDebugLoc();
  1065. unsigned SDOrder = DDI.getSDNodeOrder();
  1066. // Currently we consider only dbg.value intrinsics -- we tell the salvager
  1067. // that DW_OP_stack_value is desired.
  1068. assert(isa<DbgValueInst>(DDI.getDI()));
  1069. bool StackValue = true;
  1070. // Can this Value can be encoded without any further work?
  1071. if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder))
  1072. return;
  1073. // Attempt to salvage back through as many instructions as possible. Bail if
  1074. // a non-instruction is seen, such as a constant expression or global
  1075. // variable. FIXME: Further work could recover those too.
  1076. while (isa<Instruction>(V)) {
  1077. Instruction &VAsInst = *cast<Instruction>(V);
  1078. DIExpression *NewExpr = salvageDebugInfoImpl(VAsInst, Expr, StackValue);
  1079. // If we cannot salvage any further, and haven't yet found a suitable debug
  1080. // expression, bail out.
  1081. if (!NewExpr)
  1082. break;
  1083. // New value and expr now represent this debuginfo.
  1084. V = VAsInst.getOperand(0);
  1085. Expr = NewExpr;
  1086. // Some kind of simplification occurred: check whether the operand of the
  1087. // salvaged debug expression can be encoded in this DAG.
  1088. if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder)) {
  1089. LLVM_DEBUG(dbgs() << "Salvaged debug location info for:\n "
  1090. << DDI.getDI() << "\nBy stripping back to:\n " << V);
  1091. return;
  1092. }
  1093. }
  1094. // This was the final opportunity to salvage this debug information, and it
  1095. // couldn't be done. Place an undef DBG_VALUE at this location to terminate
  1096. // any earlier variable location.
  1097. auto Undef = UndefValue::get(DDI.getDI()->getVariableLocation()->getType());
  1098. auto SDV = DAG.getConstantDbgValue(Var, Expr, Undef, DL, SDNodeOrder);
  1099. DAG.AddDbgValue(SDV, nullptr, false);
  1100. LLVM_DEBUG(dbgs() << "Dropping debug value info for:\n " << DDI.getDI()
  1101. << "\n");
  1102. LLVM_DEBUG(dbgs() << " Last seen at:\n " << *DDI.getDI()->getOperand(0)
  1103. << "\n");
  1104. }
  1105. bool SelectionDAGBuilder::handleDebugValue(const Value *V, DILocalVariable *Var,
  1106. DIExpression *Expr, DebugLoc dl,
  1107. DebugLoc InstDL, unsigned Order) {
  1108. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  1109. SDDbgValue *SDV;
  1110. if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V) ||
  1111. isa<ConstantPointerNull>(V)) {
  1112. SDV = DAG.getConstantDbgValue(Var, Expr, V, dl, SDNodeOrder);
  1113. DAG.AddDbgValue(SDV, nullptr, false);
  1114. return true;
  1115. }
  1116. // If the Value is a frame index, we can create a FrameIndex debug value
  1117. // without relying on the DAG at all.
  1118. if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
  1119. auto SI = FuncInfo.StaticAllocaMap.find(AI);
  1120. if (SI != FuncInfo.StaticAllocaMap.end()) {
  1121. auto SDV =
  1122. DAG.getFrameIndexDbgValue(Var, Expr, SI->second,
  1123. /*IsIndirect*/ false, dl, SDNodeOrder);
  1124. // Do not attach the SDNodeDbgValue to an SDNode: this variable location
  1125. // is still available even if the SDNode gets optimized out.
  1126. DAG.AddDbgValue(SDV, nullptr, false);
  1127. return true;
  1128. }
  1129. }
  1130. // Do not use getValue() in here; we don't want to generate code at
  1131. // this point if it hasn't been done yet.
  1132. SDValue N = NodeMap[V];
  1133. if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map.
  1134. N = UnusedArgNodeMap[V];
  1135. if (N.getNode()) {
  1136. if (EmitFuncArgumentDbgValue(V, Var, Expr, dl, false, N))
  1137. return true;
  1138. SDV = getDbgValue(N, Var, Expr, dl, SDNodeOrder);
  1139. DAG.AddDbgValue(SDV, N.getNode(), false);
  1140. return true;
  1141. }
  1142. // Special rules apply for the first dbg.values of parameter variables in a
  1143. // function. Identify them by the fact they reference Argument Values, that
  1144. // they're parameters, and they are parameters of the current function. We
  1145. // need to let them dangle until they get an SDNode.
  1146. bool IsParamOfFunc = isa<Argument>(V) && Var->isParameter() &&
  1147. !InstDL.getInlinedAt();
  1148. if (!IsParamOfFunc) {
  1149. // The value is not used in this block yet (or it would have an SDNode).
  1150. // We still want the value to appear for the user if possible -- if it has
  1151. // an associated VReg, we can refer to that instead.
  1152. auto VMI = FuncInfo.ValueMap.find(V);
  1153. if (VMI != FuncInfo.ValueMap.end()) {
  1154. unsigned Reg = VMI->second;
  1155. // If this is a PHI node, it may be split up into several MI PHI nodes
  1156. // (in FunctionLoweringInfo::set).
  1157. RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg,
  1158. V->getType(), None);
  1159. if (RFV.occupiesMultipleRegs()) {
  1160. unsigned Offset = 0;
  1161. unsigned BitsToDescribe = 0;
  1162. if (auto VarSize = Var->getSizeInBits())
  1163. BitsToDescribe = *VarSize;
  1164. if (auto Fragment = Expr->getFragmentInfo())
  1165. BitsToDescribe = Fragment->SizeInBits;
  1166. for (auto RegAndSize : RFV.getRegsAndSizes()) {
  1167. unsigned RegisterSize = RegAndSize.second;
  1168. // Bail out if all bits are described already.
  1169. if (Offset >= BitsToDescribe)
  1170. break;
  1171. unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe)
  1172. ? BitsToDescribe - Offset
  1173. : RegisterSize;
  1174. auto FragmentExpr = DIExpression::createFragmentExpression(
  1175. Expr, Offset, FragmentSize);
  1176. if (!FragmentExpr)
  1177. continue;
  1178. SDV = DAG.getVRegDbgValue(Var, *FragmentExpr, RegAndSize.first,
  1179. false, dl, SDNodeOrder);
  1180. DAG.AddDbgValue(SDV, nullptr, false);
  1181. Offset += RegisterSize;
  1182. }
  1183. } else {
  1184. SDV = DAG.getVRegDbgValue(Var, Expr, Reg, false, dl, SDNodeOrder);
  1185. DAG.AddDbgValue(SDV, nullptr, false);
  1186. }
  1187. return true;
  1188. }
  1189. }
  1190. return false;
  1191. }
  1192. void SelectionDAGBuilder::resolveOrClearDbgInfo() {
  1193. // Try to fixup any remaining dangling debug info -- and drop it if we can't.
  1194. for (auto &Pair : DanglingDebugInfoMap)
  1195. for (auto &DDI : Pair.second)
  1196. salvageUnresolvedDbgValue(DDI);
  1197. clearDanglingDebugInfo();
  1198. }
  1199. /// getCopyFromRegs - If there was virtual register allocated for the value V
  1200. /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise.
  1201. SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) {
  1202. DenseMap<const Value *, unsigned>::iterator It = FuncInfo.ValueMap.find(V);
  1203. SDValue Result;
  1204. if (It != FuncInfo.ValueMap.end()) {
  1205. unsigned InReg = It->second;
  1206. RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(),
  1207. DAG.getDataLayout(), InReg, Ty,
  1208. None); // This is not an ABI copy.
  1209. SDValue Chain = DAG.getEntryNode();
  1210. Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr,
  1211. V);
  1212. resolveDanglingDebugInfo(V, Result);
  1213. }
  1214. return Result;
  1215. }
  1216. /// getValue - Return an SDValue for the given Value.
  1217. SDValue SelectionDAGBuilder::getValue(const Value *V) {
  1218. // If we already have an SDValue for this value, use it. It's important
  1219. // to do this first, so that we don't create a CopyFromReg if we already
  1220. // have a regular SDValue.
  1221. SDValue &N = NodeMap[V];
  1222. if (N.getNode()) return N;
  1223. // If there's a virtual register allocated and initialized for this
  1224. // value, use it.
  1225. if (SDValue copyFromReg = getCopyFromRegs(V, V->getType()))
  1226. return copyFromReg;
  1227. // Otherwise create a new SDValue and remember it.
  1228. SDValue Val = getValueImpl(V);
  1229. NodeMap[V] = Val;
  1230. resolveDanglingDebugInfo(V, Val);
  1231. return Val;
  1232. }
  1233. // Return true if SDValue exists for the given Value
  1234. bool SelectionDAGBuilder::findValue(const Value *V) const {
  1235. return (NodeMap.find(V) != NodeMap.end()) ||
  1236. (FuncInfo.ValueMap.find(V) != FuncInfo.ValueMap.end());
  1237. }
  1238. /// getNonRegisterValue - Return an SDValue for the given Value, but
  1239. /// don't look in FuncInfo.ValueMap for a virtual register.
  1240. SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) {
  1241. // If we already have an SDValue for this value, use it.
  1242. SDValue &N = NodeMap[V];
  1243. if (N.getNode()) {
  1244. if (isa<ConstantSDNode>(N) || isa<ConstantFPSDNode>(N)) {
  1245. // Remove the debug location from the node as the node is about to be used
  1246. // in a location which may differ from the original debug location. This
  1247. // is relevant to Constant and ConstantFP nodes because they can appear
  1248. // as constant expressions inside PHI nodes.
  1249. N->setDebugLoc(DebugLoc());
  1250. }
  1251. return N;
  1252. }
  1253. // Otherwise create a new SDValue and remember it.
  1254. SDValue Val = getValueImpl(V);
  1255. NodeMap[V] = Val;
  1256. resolveDanglingDebugInfo(V, Val);
  1257. return Val;
  1258. }
  1259. /// getValueImpl - Helper function for getValue and getNonRegisterValue.
  1260. /// Create an SDValue for the given value.
  1261. SDValue SelectionDAGBuilder::getValueImpl(const Value *V) {
  1262. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  1263. if (const Constant *C = dyn_cast<Constant>(V)) {
  1264. EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true);
  1265. if (const ConstantInt *CI = dyn_cast<ConstantInt>(C))
  1266. return DAG.getConstant(*CI, getCurSDLoc(), VT);
  1267. if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
  1268. return DAG.getGlobalAddress(GV, getCurSDLoc(), VT);
  1269. if (isa<ConstantPointerNull>(C)) {
  1270. unsigned AS = V->getType()->getPointerAddressSpace();
  1271. return DAG.getConstant(0, getCurSDLoc(),
  1272. TLI.getPointerTy(DAG.getDataLayout(), AS));
  1273. }
  1274. if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
  1275. return DAG.getConstantFP(*CFP, getCurSDLoc(), VT);
  1276. if (isa<UndefValue>(C) && !V->getType()->isAggregateType())
  1277. return DAG.getUNDEF(VT);
  1278. if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
  1279. visit(CE->getOpcode(), *CE);
  1280. SDValue N1 = NodeMap[V];
  1281. assert(N1.getNode() && "visit didn't populate the NodeMap!");
  1282. return N1;
  1283. }
  1284. if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
  1285. SmallVector<SDValue, 4> Constants;
  1286. for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end();
  1287. OI != OE; ++OI) {
  1288. SDNode *Val = getValue(*OI).getNode();
  1289. // If the operand is an empty aggregate, there are no values.
  1290. if (!Val) continue;
  1291. // Add each leaf value from the operand to the Constants list
  1292. // to form a flattened list of all the values.
  1293. for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
  1294. Constants.push_back(SDValue(Val, i));
  1295. }
  1296. return DAG.getMergeValues(Constants, getCurSDLoc());
  1297. }
  1298. if (const ConstantDataSequential *CDS =
  1299. dyn_cast<ConstantDataSequential>(C)) {
  1300. SmallVector<SDValue, 4> Ops;
  1301. for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
  1302. SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode();
  1303. // Add each leaf value from the operand to the Constants list
  1304. // to form a flattened list of all the values.
  1305. for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
  1306. Ops.push_back(SDValue(Val, i));
  1307. }
  1308. if (isa<ArrayType>(CDS->getType()))
  1309. return DAG.getMergeValues(Ops, getCurSDLoc());
  1310. return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
  1311. }
  1312. if (C->getType()->isStructTy() || C->getType()->isArrayTy()) {
  1313. assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
  1314. "Unknown struct or array constant!");
  1315. SmallVector<EVT, 4> ValueVTs;
  1316. ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs);
  1317. unsigned NumElts = ValueVTs.size();
  1318. if (NumElts == 0)
  1319. return SDValue(); // empty struct
  1320. SmallVector<SDValue, 4> Constants(NumElts);
  1321. for (unsigned i = 0; i != NumElts; ++i) {
  1322. EVT EltVT = ValueVTs[i];
  1323. if (isa<UndefValue>(C))
  1324. Constants[i] = DAG.getUNDEF(EltVT);
  1325. else if (EltVT.isFloatingPoint())
  1326. Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
  1327. else
  1328. Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT);
  1329. }
  1330. return DAG.getMergeValues(Constants, getCurSDLoc());
  1331. }
  1332. if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
  1333. return DAG.getBlockAddress(BA, VT);
  1334. VectorType *VecTy = cast<VectorType>(V->getType());
  1335. unsigned NumElements = VecTy->getNumElements();
  1336. // Now that we know the number and type of the elements, get that number of
  1337. // elements into the Ops array based on what kind of constant it is.
  1338. SmallVector<SDValue, 16> Ops;
  1339. if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) {
  1340. for (unsigned i = 0; i != NumElements; ++i)
  1341. Ops.push_back(getValue(CV->getOperand(i)));
  1342. } else {
  1343. assert(isa<ConstantAggregateZero>(C) && "Unknown vector constant!");
  1344. EVT EltVT =
  1345. TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType());
  1346. SDValue Op;
  1347. if (EltVT.isFloatingPoint())
  1348. Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
  1349. else
  1350. Op = DAG.getConstant(0, getCurSDLoc(), EltVT);
  1351. Ops.assign(NumElements, Op);
  1352. }
  1353. // Create a BUILD_VECTOR node.
  1354. return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
  1355. }
  1356. // If this is a static alloca, generate it as the frameindex instead of
  1357. // computation.
  1358. if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
  1359. DenseMap<const AllocaInst*, int>::iterator SI =
  1360. FuncInfo.StaticAllocaMap.find(AI);
  1361. if (SI != FuncInfo.StaticAllocaMap.end())
  1362. return DAG.getFrameIndex(SI->second,
  1363. TLI.getFrameIndexTy(DAG.getDataLayout()));
  1364. }
  1365. // If this is an instruction which fast-isel has deferred, select it now.
  1366. if (const Instruction *Inst = dyn_cast<Instruction>(V)) {
  1367. unsigned InReg = FuncInfo.InitializeRegForValue(Inst);
  1368. RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg,
  1369. Inst->getType(), getABIRegCopyCC(V));
  1370. SDValue Chain = DAG.getEntryNode();
  1371. return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V);
  1372. }
  1373. llvm_unreachable("Can't get register for value!");
  1374. }
  1375. void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) {
  1376. auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
  1377. bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX;
  1378. bool IsCoreCLR = Pers == EHPersonality::CoreCLR;
  1379. bool IsSEH = isAsynchronousEHPersonality(Pers);
  1380. bool IsWasmCXX = Pers == EHPersonality::Wasm_CXX;
  1381. MachineBasicBlock *CatchPadMBB = FuncInfo.MBB;
  1382. if (!IsSEH)
  1383. CatchPadMBB->setIsEHScopeEntry();
  1384. // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues.
  1385. if (IsMSVCCXX || IsCoreCLR)
  1386. CatchPadMBB->setIsEHFuncletEntry();
  1387. // Wasm does not need catchpads anymore
  1388. if (!IsWasmCXX)
  1389. DAG.setRoot(DAG.getNode(ISD::CATCHPAD, getCurSDLoc(), MVT::Other,
  1390. getControlRoot()));
  1391. }
  1392. void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) {
  1393. // Update machine-CFG edge.
  1394. MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()];
  1395. FuncInfo.MBB->addSuccessor(TargetMBB);
  1396. auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
  1397. bool IsSEH = isAsynchronousEHPersonality(Pers);
  1398. if (IsSEH) {
  1399. // If this is not a fall-through branch or optimizations are switched off,
  1400. // emit the branch.
  1401. if (TargetMBB != NextBlock(FuncInfo.MBB) ||
  1402. TM.getOptLevel() == CodeGenOpt::None)
  1403. DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
  1404. getControlRoot(), DAG.getBasicBlock(TargetMBB)));
  1405. return;
  1406. }
  1407. // Figure out the funclet membership for the catchret's successor.
  1408. // This will be used by the FuncletLayout pass to determine how to order the
  1409. // BB's.
  1410. // A 'catchret' returns to the outer scope's color.
  1411. Value *ParentPad = I.getCatchSwitchParentPad();
  1412. const BasicBlock *SuccessorColor;
  1413. if (isa<ConstantTokenNone>(ParentPad))
  1414. SuccessorColor = &FuncInfo.Fn->getEntryBlock();
  1415. else
  1416. SuccessorColor = cast<Instruction>(ParentPad)->getParent();
  1417. assert(SuccessorColor && "No parent funclet for catchret!");
  1418. MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor];
  1419. assert(SuccessorColorMBB && "No MBB for SuccessorColor!");
  1420. // Create the terminator node.
  1421. SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other,
  1422. getControlRoot(), DAG.getBasicBlock(TargetMBB),
  1423. DAG.getBasicBlock(SuccessorColorMBB));
  1424. DAG.setRoot(Ret);
  1425. }
  1426. void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) {
  1427. // Don't emit any special code for the cleanuppad instruction. It just marks
  1428. // the start of an EH scope/funclet.
  1429. FuncInfo.MBB->setIsEHScopeEntry();
  1430. auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
  1431. if (Pers != EHPersonality::Wasm_CXX) {
  1432. FuncInfo.MBB->setIsEHFuncletEntry();
  1433. FuncInfo.MBB->setIsCleanupFuncletEntry();
  1434. }
  1435. }
  1436. // For wasm, there's alwyas a single catch pad attached to a catchswitch, and
  1437. // the control flow always stops at the single catch pad, as it does for a
  1438. // cleanup pad. In case the exception caught is not of the types the catch pad
  1439. // catches, it will be rethrown by a rethrow.
  1440. static void findWasmUnwindDestinations(
  1441. FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
  1442. BranchProbability Prob,
  1443. SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
  1444. &UnwindDests) {
  1445. while (EHPadBB) {
  1446. const Instruction *Pad = EHPadBB->getFirstNonPHI();
  1447. if (isa<CleanupPadInst>(Pad)) {
  1448. // Stop on cleanup pads.
  1449. UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
  1450. UnwindDests.back().first->setIsEHScopeEntry();
  1451. break;
  1452. } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
  1453. // Add the catchpad handlers to the possible destinations. We don't
  1454. // continue to the unwind destination of the catchswitch for wasm.
  1455. for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
  1456. UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
  1457. UnwindDests.back().first->setIsEHScopeEntry();
  1458. }
  1459. break;
  1460. } else {
  1461. continue;
  1462. }
  1463. }
  1464. }
  1465. /// When an invoke or a cleanupret unwinds to the next EH pad, there are
  1466. /// many places it could ultimately go. In the IR, we have a single unwind
  1467. /// destination, but in the machine CFG, we enumerate all the possible blocks.
  1468. /// This function skips over imaginary basic blocks that hold catchswitch
  1469. /// instructions, and finds all the "real" machine
  1470. /// basic block destinations. As those destinations may not be successors of
  1471. /// EHPadBB, here we also calculate the edge probability to those destinations.
  1472. /// The passed-in Prob is the edge probability to EHPadBB.
  1473. static void findUnwindDestinations(
  1474. FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
  1475. BranchProbability Prob,
  1476. SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
  1477. &UnwindDests) {
  1478. EHPersonality Personality =
  1479. classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
  1480. bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX;
  1481. bool IsCoreCLR = Personality == EHPersonality::CoreCLR;
  1482. bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX;
  1483. bool IsSEH = isAsynchronousEHPersonality(Personality);
  1484. if (IsWasmCXX) {
  1485. findWasmUnwindDestinations(FuncInfo, EHPadBB, Prob, UnwindDests);
  1486. assert(UnwindDests.size() <= 1 &&
  1487. "There should be at most one unwind destination for wasm");
  1488. return;
  1489. }
  1490. while (EHPadBB) {
  1491. const Instruction *Pad = EHPadBB->getFirstNonPHI();
  1492. BasicBlock *NewEHPadBB = nullptr;
  1493. if (isa<LandingPadInst>(Pad)) {
  1494. // Stop on landingpads. They are not funclets.
  1495. UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
  1496. break;
  1497. } else if (isa<CleanupPadInst>(Pad)) {
  1498. // Stop on cleanup pads. Cleanups are always funclet entries for all known
  1499. // personalities.
  1500. UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
  1501. UnwindDests.back().first->setIsEHScopeEntry();
  1502. UnwindDests.back().first->setIsEHFuncletEntry();
  1503. break;
  1504. } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
  1505. // Add the catchpad handlers to the possible destinations.
  1506. for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
  1507. UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
  1508. // For MSVC++ and the CLR, catchblocks are funclets and need prologues.
  1509. if (IsMSVCCXX || IsCoreCLR)
  1510. UnwindDests.back().first->setIsEHFuncletEntry();
  1511. if (!IsSEH)
  1512. UnwindDests.back().first->setIsEHScopeEntry();
  1513. }
  1514. NewEHPadBB = CatchSwitch->getUnwindDest();
  1515. } else {
  1516. continue;
  1517. }
  1518. BranchProbabilityInfo *BPI = FuncInfo.BPI;
  1519. if (BPI && NewEHPadBB)
  1520. Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB);
  1521. EHPadBB = NewEHPadBB;
  1522. }
  1523. }
  1524. void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) {
  1525. // Update successor info.
  1526. SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
  1527. auto UnwindDest = I.getUnwindDest();
  1528. BranchProbabilityInfo *BPI = FuncInfo.BPI;
  1529. BranchProbability UnwindDestProb =
  1530. (BPI && UnwindDest)
  1531. ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest)
  1532. : BranchProbability::getZero();
  1533. findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests);
  1534. for (auto &UnwindDest : UnwindDests) {
  1535. UnwindDest.first->setIsEHPad();
  1536. addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second);
  1537. }
  1538. FuncInfo.MBB->normalizeSuccProbs();
  1539. // Create the terminator node.
  1540. SDValue Ret =
  1541. DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot());
  1542. DAG.setRoot(Ret);
  1543. }
  1544. void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) {
  1545. report_fatal_error("visitCatchSwitch not yet implemented!");
  1546. }
  1547. void SelectionDAGBuilder::visitRet(const ReturnInst &I) {
  1548. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  1549. auto &DL = DAG.getDataLayout();
  1550. SDValue Chain = getControlRoot();
  1551. SmallVector<ISD::OutputArg, 8> Outs;
  1552. SmallVector<SDValue, 8> OutVals;
  1553. // Calls to @llvm.experimental.deoptimize don't generate a return value, so
  1554. // lower
  1555. //
  1556. // %val = call <ty> @llvm.experimental.deoptimize()
  1557. // ret <ty> %val
  1558. //
  1559. // differently.
  1560. if (I.getParent()->getTerminatingDeoptimizeCall()) {
  1561. LowerDeoptimizingReturn();
  1562. return;
  1563. }
  1564. if (!FuncInfo.CanLowerReturn) {
  1565. unsigned DemoteReg = FuncInfo.DemoteRegister;
  1566. const Function *F = I.getParent()->getParent();
  1567. // Emit a store of the return value through the virtual register.
  1568. // Leave Outs empty so that LowerReturn won't try to load return
  1569. // registers the usual way.
  1570. SmallVector<EVT, 1> PtrValueVTs;
  1571. ComputeValueVTs(TLI, DL,
  1572. F->getReturnType()->getPointerTo(
  1573. DAG.getDataLayout().getAllocaAddrSpace()),
  1574. PtrValueVTs);
  1575. SDValue RetPtr = DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(),
  1576. DemoteReg, PtrValueVTs[0]);
  1577. SDValue RetOp = getValue(I.getOperand(0));
  1578. SmallVector<EVT, 4> ValueVTs;
  1579. SmallVector<uint64_t, 4> Offsets;
  1580. ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &Offsets);
  1581. unsigned NumValues = ValueVTs.size();
  1582. SmallVector<SDValue, 4> Chains(NumValues);
  1583. for (unsigned i = 0; i != NumValues; ++i) {
  1584. // An aggregate return value cannot wrap around the address space, so
  1585. // offsets to its parts don't wrap either.
  1586. SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr, Offsets[i]);
  1587. Chains[i] = DAG.getStore(
  1588. Chain, getCurSDLoc(), SDValue(RetOp.getNode(), RetOp.getResNo() + i),
  1589. // FIXME: better loc info would be nice.
  1590. Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction()));
  1591. }
  1592. Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
  1593. MVT::Other, Chains);
  1594. } else if (I.getNumOperands() != 0) {
  1595. SmallVector<EVT, 4> ValueVTs;
  1596. ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs);
  1597. unsigned NumValues = ValueVTs.size();
  1598. if (NumValues) {
  1599. SDValue RetOp = getValue(I.getOperand(0));
  1600. const Function *F = I.getParent()->getParent();
  1601. bool NeedsRegBlock = TLI.functionArgumentNeedsConsecutiveRegisters(
  1602. I.getOperand(0)->getType(), F->getCallingConv(),
  1603. /*IsVarArg*/ false);
  1604. ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
  1605. if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex,
  1606. Attribute::SExt))
  1607. ExtendKind = ISD::SIGN_EXTEND;
  1608. else if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex,
  1609. Attribute::ZExt))
  1610. ExtendKind = ISD::ZERO_EXTEND;
  1611. LLVMContext &Context = F->getContext();
  1612. bool RetInReg = F->getAttributes().hasAttribute(
  1613. AttributeList::ReturnIndex, Attribute::InReg);
  1614. for (unsigned j = 0; j != NumValues; ++j) {
  1615. EVT VT = ValueVTs[j];
  1616. if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger())
  1617. VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind);
  1618. CallingConv::ID CC = F->getCallingConv();
  1619. unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT);
  1620. MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT);
  1621. SmallVector<SDValue, 4> Parts(NumParts);
  1622. getCopyToParts(DAG, getCurSDLoc(),
  1623. SDValue(RetOp.getNode(), RetOp.getResNo() + j),
  1624. &Parts[0], NumParts, PartVT, &I, CC, ExtendKind);
  1625. // 'inreg' on function refers to return value
  1626. ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
  1627. if (RetInReg)
  1628. Flags.setInReg();
  1629. if (I.getOperand(0)->getType()->isPointerTy()) {
  1630. Flags.setPointer();
  1631. Flags.setPointerAddrSpace(
  1632. cast<PointerType>(I.getOperand(0)->getType())->getAddressSpace());
  1633. }
  1634. if (NeedsRegBlock) {
  1635. Flags.setInConsecutiveRegs();
  1636. if (j == NumValues - 1)
  1637. Flags.setInConsecutiveRegsLast();
  1638. }
  1639. // Propagate extension type if any
  1640. if (ExtendKind == ISD::SIGN_EXTEND)
  1641. Flags.setSExt();
  1642. else if (ExtendKind == ISD::ZERO_EXTEND)
  1643. Flags.setZExt();
  1644. for (unsigned i = 0; i < NumParts; ++i) {
  1645. Outs.push_back(ISD::OutputArg(Flags, Parts[i].getValueType(),
  1646. VT, /*isfixed=*/true, 0, 0));
  1647. OutVals.push_back(Parts[i]);
  1648. }
  1649. }
  1650. }
  1651. }
  1652. // Push in swifterror virtual register as the last element of Outs. This makes
  1653. // sure swifterror virtual register will be returned in the swifterror
  1654. // physical register.
  1655. const Function *F = I.getParent()->getParent();
  1656. if (TLI.supportSwiftError() &&
  1657. F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) {
  1658. assert(FuncInfo.SwiftErrorArg && "Need a swift error argument");
  1659. ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
  1660. Flags.setSwiftError();
  1661. Outs.push_back(ISD::OutputArg(Flags, EVT(TLI.getPointerTy(DL)) /*vt*/,
  1662. EVT(TLI.getPointerTy(DL)) /*argvt*/,
  1663. true /*isfixed*/, 1 /*origidx*/,
  1664. 0 /*partOffs*/));
  1665. // Create SDNode for the swifterror virtual register.
  1666. OutVals.push_back(
  1667. DAG.getRegister(FuncInfo.getOrCreateSwiftErrorVRegUseAt(
  1668. &I, FuncInfo.MBB, FuncInfo.SwiftErrorArg).first,
  1669. EVT(TLI.getPointerTy(DL))));
  1670. }
  1671. bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg();
  1672. CallingConv::ID CallConv =
  1673. DAG.getMachineFunction().getFunction().getCallingConv();
  1674. Chain = DAG.getTargetLoweringInfo().LowerReturn(
  1675. Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG);
  1676. // Verify that the target's LowerReturn behaved as expected.
  1677. assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
  1678. "LowerReturn didn't return a valid chain!");
  1679. // Update the DAG with the new chain value resulting from return lowering.
  1680. DAG.setRoot(Chain);
  1681. }
  1682. /// CopyToExportRegsIfNeeded - If the given value has virtual registers
  1683. /// created for it, emit nodes to copy the value into the virtual
  1684. /// registers.
  1685. void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) {
  1686. // Skip empty types
  1687. if (V->getType()->isEmptyTy())
  1688. return;
  1689. DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
  1690. if (VMI != FuncInfo.ValueMap.end()) {
  1691. assert(!V->use_empty() && "Unused value assigned virtual registers!");
  1692. CopyValueToVirtualRegister(V, VMI->second);
  1693. }
  1694. }
  1695. /// ExportFromCurrentBlock - If this condition isn't known to be exported from
  1696. /// the current basic block, add it to ValueMap now so that we'll get a
  1697. /// CopyTo/FromReg.
  1698. void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) {
  1699. // No need to export constants.
  1700. if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
  1701. // Already exported?
  1702. if (FuncInfo.isExportedInst(V)) return;
  1703. unsigned Reg = FuncInfo.InitializeRegForValue(V);
  1704. CopyValueToVirtualRegister(V, Reg);
  1705. }
  1706. bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V,
  1707. const BasicBlock *FromBB) {
  1708. // The operands of the setcc have to be in this block. We don't know
  1709. // how to export them from some other block.
  1710. if (const Instruction *VI = dyn_cast<Instruction>(V)) {
  1711. // Can export from current BB.
  1712. if (VI->getParent() == FromBB)
  1713. return true;
  1714. // Is already exported, noop.
  1715. return FuncInfo.isExportedInst(V);
  1716. }
  1717. // If this is an argument, we can export it if the BB is the entry block or
  1718. // if it is already exported.
  1719. if (isa<Argument>(V)) {
  1720. if (FromBB == &FromBB->getParent()->getEntryBlock())
  1721. return true;
  1722. // Otherwise, can only export this if it is already exported.
  1723. return FuncInfo.isExportedInst(V);
  1724. }
  1725. // Otherwise, constants can always be exported.
  1726. return true;
  1727. }
  1728. /// Return branch probability calculated by BranchProbabilityInfo for IR blocks.
  1729. BranchProbability
  1730. SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src,
  1731. const MachineBasicBlock *Dst) const {
  1732. BranchProbabilityInfo *BPI = FuncInfo.BPI;
  1733. const BasicBlock *SrcBB = Src->getBasicBlock();
  1734. const BasicBlock *DstBB = Dst->getBasicBlock();
  1735. if (!BPI) {
  1736. // If BPI is not available, set the default probability as 1 / N, where N is
  1737. // the number of successors.
  1738. auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1);
  1739. return BranchProbability(1, SuccSize);
  1740. }
  1741. return BPI->getEdgeProbability(SrcBB, DstBB);
  1742. }
  1743. void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src,
  1744. MachineBasicBlock *Dst,
  1745. BranchProbability Prob) {
  1746. if (!FuncInfo.BPI)
  1747. Src->addSuccessorWithoutProb(Dst);
  1748. else {
  1749. if (Prob.isUnknown())
  1750. Prob = getEdgeProbability(Src, Dst);
  1751. Src->addSuccessor(Dst, Prob);
  1752. }
  1753. }
  1754. static bool InBlock(const Value *V, const BasicBlock *BB) {
  1755. if (const Instruction *I = dyn_cast<Instruction>(V))
  1756. return I->getParent() == BB;
  1757. return true;
  1758. }
  1759. /// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
  1760. /// This function emits a branch and is used at the leaves of an OR or an
  1761. /// AND operator tree.
  1762. void
  1763. SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond,
  1764. MachineBasicBlock *TBB,
  1765. MachineBasicBlock *FBB,
  1766. MachineBasicBlock *CurBB,
  1767. MachineBasicBlock *SwitchBB,
  1768. BranchProbability TProb,
  1769. BranchProbability FProb,
  1770. bool InvertCond) {
  1771. const BasicBlock *BB = CurBB->getBasicBlock();
  1772. // If the leaf of the tree is a comparison, merge the condition into
  1773. // the caseblock.
  1774. if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
  1775. // The operands of the cmp have to be in this block. We don't know
  1776. // how to export them from some other block. If this is the first block
  1777. // of the sequence, no exporting is needed.
  1778. if (CurBB == SwitchBB ||
  1779. (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
  1780. isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
  1781. ISD::CondCode Condition;
  1782. if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
  1783. ICmpInst::Predicate Pred =
  1784. InvertCond ? IC->getInversePredicate() : IC->getPredicate();
  1785. Condition = getICmpCondCode(Pred);
  1786. } else {
  1787. const FCmpInst *FC = cast<FCmpInst>(Cond);
  1788. FCmpInst::Predicate Pred =
  1789. InvertCond ? FC->getInversePredicate() : FC->getPredicate();
  1790. Condition = getFCmpCondCode(Pred);
  1791. if (TM.Options.NoNaNsFPMath)
  1792. Condition = getFCmpCodeWithoutNaN(Condition);
  1793. }
  1794. CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr,
  1795. TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
  1796. SwitchCases.push_back(CB);
  1797. return;
  1798. }
  1799. }
  1800. // Create a CaseBlock record representing this branch.
  1801. ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ;
  1802. CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()),
  1803. nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
  1804. SwitchCases.push_back(CB);
  1805. }
  1806. void SelectionDAGBuilder::FindMergedConditions(const Value *Cond,
  1807. MachineBasicBlock *TBB,
  1808. MachineBasicBlock *FBB,
  1809. MachineBasicBlock *CurBB,
  1810. MachineBasicBlock *SwitchBB,
  1811. Instruction::BinaryOps Opc,
  1812. BranchProbability TProb,
  1813. BranchProbability FProb,
  1814. bool InvertCond) {
  1815. // Skip over not part of the tree and remember to invert op and operands at
  1816. // next level.
  1817. Value *NotCond;
  1818. if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) &&
  1819. InBlock(NotCond, CurBB->getBasicBlock())) {
  1820. FindMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb,
  1821. !InvertCond);
  1822. return;
  1823. }
  1824. const Instruction *BOp = dyn_cast<Instruction>(Cond);
  1825. // Compute the effective opcode for Cond, taking into account whether it needs
  1826. // to be inverted, e.g.
  1827. // and (not (or A, B)), C
  1828. // gets lowered as
  1829. // and (and (not A, not B), C)
  1830. unsigned BOpc = 0;
  1831. if (BOp) {
  1832. BOpc = BOp->getOpcode();
  1833. if (InvertCond) {
  1834. if (BOpc == Instruction::And)
  1835. BOpc = Instruction::Or;
  1836. else if (BOpc == Instruction::Or)
  1837. BOpc = Instruction::And;
  1838. }
  1839. }
  1840. // If this node is not part of the or/and tree, emit it as a branch.
  1841. if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
  1842. BOpc != unsigned(Opc) || !BOp->hasOneUse() ||
  1843. BOp->getParent() != CurBB->getBasicBlock() ||
  1844. !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
  1845. !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
  1846. EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB,
  1847. TProb, FProb, InvertCond);
  1848. return;
  1849. }
  1850. // Create TmpBB after CurBB.
  1851. MachineFunction::iterator BBI(CurBB);
  1852. MachineFunction &MF = DAG.getMachineFunction();
  1853. MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
  1854. CurBB->getParent()->insert(++BBI, TmpBB);
  1855. if (Opc == Instruction::Or) {
  1856. // Codegen X | Y as:
  1857. // BB1:
  1858. // jmp_if_X TBB
  1859. // jmp TmpBB
  1860. // TmpBB:
  1861. // jmp_if_Y TBB
  1862. // jmp FBB
  1863. //
  1864. // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
  1865. // The requirement is that
  1866. // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
  1867. // = TrueProb for original BB.
  1868. // Assuming the original probabilities are A and B, one choice is to set
  1869. // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to
  1870. // A/(1+B) and 2B/(1+B). This choice assumes that
  1871. // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
  1872. // Another choice is to assume TrueProb for BB1 equals to TrueProb for
  1873. // TmpBB, but the math is more complicated.
  1874. auto NewTrueProb = TProb / 2;
  1875. auto NewFalseProb = TProb / 2 + FProb;
  1876. // Emit the LHS condition.
  1877. FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, SwitchBB, Opc,
  1878. NewTrueProb, NewFalseProb, InvertCond);
  1879. // Normalize A/2 and B to get A/(1+B) and 2B/(1+B).
  1880. SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb};
  1881. BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
  1882. // Emit the RHS condition into TmpBB.
  1883. FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc,
  1884. Probs[0], Probs[1], InvertCond);
  1885. } else {
  1886. assert(Opc == Instruction::And && "Unknown merge op!");
  1887. // Codegen X & Y as:
  1888. // BB1:
  1889. // jmp_if_X TmpBB
  1890. // jmp FBB
  1891. // TmpBB:
  1892. // jmp_if_Y TBB
  1893. // jmp FBB
  1894. //
  1895. // This requires creation of TmpBB after CurBB.
  1896. // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
  1897. // The requirement is that
  1898. // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
  1899. // = FalseProb for original BB.
  1900. // Assuming the original probabilities are A and B, one choice is to set
  1901. // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to
  1902. // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 ==
  1903. // TrueProb for BB1 * FalseProb for TmpBB.
  1904. auto NewTrueProb = TProb + FProb / 2;
  1905. auto NewFalseProb = FProb / 2;
  1906. // Emit the LHS condition.
  1907. FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, SwitchBB, Opc,
  1908. NewTrueProb, NewFalseProb, InvertCond);
  1909. // Normalize A and B/2 to get 2A/(1+A) and B/(1+A).
  1910. SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2};
  1911. BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
  1912. // Emit the RHS condition into TmpBB.
  1913. FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc,
  1914. Probs[0], Probs[1], InvertCond);
  1915. }
  1916. }
  1917. /// If the set of cases should be emitted as a series of branches, return true.
  1918. /// If we should emit this as a bunch of and/or'd together conditions, return
  1919. /// false.
  1920. bool
  1921. SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) {
  1922. if (Cases.size() != 2) return true;
  1923. // If this is two comparisons of the same values or'd or and'd together, they
  1924. // will get folded into a single comparison, so don't emit two blocks.
  1925. if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
  1926. Cases[0].CmpRHS == Cases[1].CmpRHS) ||
  1927. (Cases[0].CmpRHS == Cases[1].CmpLHS &&
  1928. Cases[0].CmpLHS == Cases[1].CmpRHS)) {
  1929. return false;
  1930. }
  1931. // Handle: (X != null) | (Y != null) --> (X|Y) != 0
  1932. // Handle: (X == null) & (Y == null) --> (X|Y) == 0
  1933. if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
  1934. Cases[0].CC == Cases[1].CC &&
  1935. isa<Constant>(Cases[0].CmpRHS) &&
  1936. cast<Constant>(Cases[0].CmpRHS)->isNullValue()) {
  1937. if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB)
  1938. return false;
  1939. if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB)
  1940. return false;
  1941. }
  1942. return true;
  1943. }
  1944. void SelectionDAGBuilder::visitBr(const BranchInst &I) {
  1945. MachineBasicBlock *BrMBB = FuncInfo.MBB;
  1946. // Update machine-CFG edges.
  1947. MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
  1948. if (I.isUnconditional()) {
  1949. // Update machine-CFG edges.
  1950. BrMBB->addSuccessor(Succ0MBB);
  1951. // If this is not a fall-through branch or optimizations are switched off,
  1952. // emit the branch.
  1953. if (Succ0MBB != NextBlock(BrMBB) || TM.getOptLevel() == CodeGenOpt::None)
  1954. DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
  1955. MVT::Other, getControlRoot(),
  1956. DAG.getBasicBlock(Succ0MBB)));
  1957. return;
  1958. }
  1959. // If this condition is one of the special cases we handle, do special stuff
  1960. // now.
  1961. const Value *CondVal = I.getCondition();
  1962. MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
  1963. // If this is a series of conditions that are or'd or and'd together, emit
  1964. // this as a sequence of branches instead of setcc's with and/or operations.
  1965. // As long as jumps are not expensive, this should improve performance.
  1966. // For example, instead of something like:
  1967. // cmp A, B
  1968. // C = seteq
  1969. // cmp D, E
  1970. // F = setle
  1971. // or C, F
  1972. // jnz foo
  1973. // Emit:
  1974. // cmp A, B
  1975. // je foo
  1976. // cmp D, E
  1977. // jle foo
  1978. if (const BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
  1979. Instruction::BinaryOps Opcode = BOp->getOpcode();
  1980. if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp->hasOneUse() &&
  1981. !I.getMetadata(LLVMContext::MD_unpredictable) &&
  1982. (Opcode == Instruction::And || Opcode == Instruction::Or)) {
  1983. FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB,
  1984. Opcode,
  1985. getEdgeProbability(BrMBB, Succ0MBB),
  1986. getEdgeProbability(BrMBB, Succ1MBB),
  1987. /*InvertCond=*/false);
  1988. // If the compares in later blocks need to use values not currently
  1989. // exported from this block, export them now. This block should always
  1990. // be the first entry.
  1991. assert(SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!");
  1992. // Allow some cases to be rejected.
  1993. if (ShouldEmitAsBranches(SwitchCases)) {
  1994. for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
  1995. ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
  1996. ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
  1997. }
  1998. // Emit the branch for this block.
  1999. visitSwitchCase(SwitchCases[0], BrMBB);
  2000. SwitchCases.erase(SwitchCases.begin());
  2001. return;
  2002. }
  2003. // Okay, we decided not to do this, remove any inserted MBB's and clear
  2004. // SwitchCases.
  2005. for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
  2006. FuncInfo.MF->erase(SwitchCases[i].ThisBB);
  2007. SwitchCases.clear();
  2008. }
  2009. }
  2010. // Create a CaseBlock record representing this branch.
  2011. CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
  2012. nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc());
  2013. // Use visitSwitchCase to actually insert the fast branch sequence for this
  2014. // cond branch.
  2015. visitSwitchCase(CB, BrMBB);
  2016. }
  2017. /// visitSwitchCase - Emits the necessary code to represent a single node in
  2018. /// the binary search tree resulting from lowering a switch instruction.
  2019. void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB,
  2020. MachineBasicBlock *SwitchBB) {
  2021. SDValue Cond;
  2022. SDValue CondLHS = getValue(CB.CmpLHS);
  2023. SDLoc dl = CB.DL;
  2024. if (CB.CC == ISD::SETTRUE) {
  2025. // Branch or fall through to TrueBB.
  2026. addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
  2027. SwitchBB->normalizeSuccProbs();
  2028. if (CB.TrueBB != NextBlock(SwitchBB)) {
  2029. DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, getControlRoot(),
  2030. DAG.getBasicBlock(CB.TrueBB)));
  2031. }
  2032. return;
  2033. }
  2034. // Build the setcc now.
  2035. if (!CB.CmpMHS) {
  2036. // Fold "(X == true)" to X and "(X == false)" to !X to
  2037. // handle common cases produced by branch lowering.
  2038. if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
  2039. CB.CC == ISD::SETEQ)
  2040. Cond = CondLHS;
  2041. else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
  2042. CB.CC == ISD::SETEQ) {
  2043. SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType());
  2044. Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
  2045. } else
  2046. Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
  2047. } else {
  2048. assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
  2049. const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
  2050. const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
  2051. SDValue CmpOp = getValue(CB.CmpMHS);
  2052. EVT VT = CmpOp.getValueType();
  2053. if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
  2054. Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT),
  2055. ISD::SETLE);
  2056. } else {
  2057. SDValue SUB = DAG.getNode(ISD::SUB, dl,
  2058. VT, CmpOp, DAG.getConstant(Low, dl, VT));
  2059. Cond = DAG.getSetCC(dl, MVT::i1, SUB,
  2060. DAG.getConstant(High-Low, dl, VT), ISD::SETULE);
  2061. }
  2062. }
  2063. // Update successor info
  2064. addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
  2065. // TrueBB and FalseBB are always different unless the incoming IR is
  2066. // degenerate. This only happens when running llc on weird IR.
  2067. if (CB.TrueBB != CB.FalseBB)
  2068. addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb);
  2069. SwitchBB->normalizeSuccProbs();
  2070. // If the lhs block is the next block, invert the condition so that we can
  2071. // fall through to the lhs instead of the rhs block.
  2072. if (CB.TrueBB == NextBlock(SwitchBB)) {
  2073. std::swap(CB.TrueBB, CB.FalseBB);
  2074. SDValue True = DAG.getConstant(1, dl, Cond.getValueType());
  2075. Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
  2076. }
  2077. SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
  2078. MVT::Other, getControlRoot(), Cond,
  2079. DAG.getBasicBlock(CB.TrueBB));
  2080. // Insert the false branch. Do this even if it's a fall through branch,
  2081. // this makes it easier to do DAG optimizations which require inverting
  2082. // the branch condition.
  2083. BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
  2084. DAG.getBasicBlock(CB.FalseBB));
  2085. DAG.setRoot(BrCond);
  2086. }
  2087. /// visitJumpTable - Emit JumpTable node in the current MBB
  2088. void SelectionDAGBuilder::visitJumpTable(JumpTable &JT) {
  2089. // Emit the code for the jump table
  2090. assert(JT.Reg != -1U && "Should lower JT Header first!");
  2091. EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
  2092. SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(),
  2093. JT.Reg, PTy);
  2094. SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
  2095. SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(),
  2096. MVT::Other, Index.getValue(1),
  2097. Table, Index);
  2098. DAG.setRoot(BrJumpTable);
  2099. }
  2100. /// visitJumpTableHeader - This function emits necessary code to produce index
  2101. /// in the JumpTable from switch case.
  2102. void SelectionDAGBuilder::visitJumpTableHeader(JumpTable &JT,
  2103. JumpTableHeader &JTH,
  2104. MachineBasicBlock *SwitchBB) {
  2105. SDLoc dl = getCurSDLoc();
  2106. // Subtract the lowest switch case value from the value being switched on.
  2107. SDValue SwitchOp = getValue(JTH.SValue);
  2108. EVT VT = SwitchOp.getValueType();
  2109. SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp,
  2110. DAG.getConstant(JTH.First, dl, VT));
  2111. // The SDNode we just created, which holds the value being switched on minus
  2112. // the smallest case value, needs to be copied to a virtual register so it
  2113. // can be used as an index into the jump table in a subsequent basic block.
  2114. // This value may be smaller or larger than the target's pointer type, and
  2115. // therefore require extension or truncating.
  2116. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2117. SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout()));
  2118. unsigned JumpTableReg =
  2119. FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout()));
  2120. SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl,
  2121. JumpTableReg, SwitchOp);
  2122. JT.Reg = JumpTableReg;
  2123. if (!JTH.OmitRangeCheck) {
  2124. // Emit the range check for the jump table, and branch to the default block
  2125. // for the switch statement if the value being switched on exceeds the
  2126. // largest case in the switch.
  2127. SDValue CMP = DAG.getSetCC(
  2128. dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
  2129. Sub.getValueType()),
  2130. Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT);
  2131. SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
  2132. MVT::Other, CopyTo, CMP,
  2133. DAG.getBasicBlock(JT.Default));
  2134. // Avoid emitting unnecessary branches to the next block.
  2135. if (JT.MBB != NextBlock(SwitchBB))
  2136. BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
  2137. DAG.getBasicBlock(JT.MBB));
  2138. DAG.setRoot(BrCond);
  2139. } else {
  2140. // Avoid emitting unnecessary branches to the next block.
  2141. if (JT.MBB != NextBlock(SwitchBB))
  2142. DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, CopyTo,
  2143. DAG.getBasicBlock(JT.MBB)));
  2144. else
  2145. DAG.setRoot(CopyTo);
  2146. }
  2147. }
  2148. /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global
  2149. /// variable if there exists one.
  2150. static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL,
  2151. SDValue &Chain) {
  2152. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2153. EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
  2154. MachineFunction &MF = DAG.getMachineFunction();
  2155. Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent());
  2156. MachineSDNode *Node =
  2157. DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain);
  2158. if (Global) {
  2159. MachinePointerInfo MPInfo(Global);
  2160. auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant |
  2161. MachineMemOperand::MODereferenceable;
  2162. MachineMemOperand *MemRef = MF.getMachineMemOperand(
  2163. MPInfo, Flags, PtrTy.getSizeInBits() / 8, DAG.getEVTAlignment(PtrTy));
  2164. DAG.setNodeMemRefs(Node, {MemRef});
  2165. }
  2166. return SDValue(Node, 0);
  2167. }
  2168. /// Codegen a new tail for a stack protector check ParentMBB which has had its
  2169. /// tail spliced into a stack protector check success bb.
  2170. ///
  2171. /// For a high level explanation of how this fits into the stack protector
  2172. /// generation see the comment on the declaration of class
  2173. /// StackProtectorDescriptor.
  2174. void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD,
  2175. MachineBasicBlock *ParentBB) {
  2176. // First create the loads to the guard/stack slot for the comparison.
  2177. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2178. EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
  2179. MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo();
  2180. int FI = MFI.getStackProtectorIndex();
  2181. SDValue Guard;
  2182. SDLoc dl = getCurSDLoc();
  2183. SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy);
  2184. const Module &M = *ParentBB->getParent()->getFunction().getParent();
  2185. unsigned Align = DL->getPrefTypeAlignment(Type::getInt8PtrTy(M.getContext()));
  2186. // Generate code to load the content of the guard slot.
  2187. SDValue GuardVal = DAG.getLoad(
  2188. PtrTy, dl, DAG.getEntryNode(), StackSlotPtr,
  2189. MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align,
  2190. MachineMemOperand::MOVolatile);
  2191. if (TLI.useStackGuardXorFP())
  2192. GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl);
  2193. // Retrieve guard check function, nullptr if instrumentation is inlined.
  2194. if (const Function *GuardCheckFn = TLI.getSSPStackGuardCheck(M)) {
  2195. // The target provides a guard check function to validate the guard value.
  2196. // Generate a call to that function with the content of the guard slot as
  2197. // argument.
  2198. FunctionType *FnTy = GuardCheckFn->getFunctionType();
  2199. assert(FnTy->getNumParams() == 1 && "Invalid function signature");
  2200. TargetLowering::ArgListTy Args;
  2201. TargetLowering::ArgListEntry Entry;
  2202. Entry.Node = GuardVal;
  2203. Entry.Ty = FnTy->getParamType(0);
  2204. if (GuardCheckFn->hasAttribute(1, Attribute::AttrKind::InReg))
  2205. Entry.IsInReg = true;
  2206. Args.push_back(Entry);
  2207. TargetLowering::CallLoweringInfo CLI(DAG);
  2208. CLI.setDebugLoc(getCurSDLoc())
  2209. .setChain(DAG.getEntryNode())
  2210. .setCallee(GuardCheckFn->getCallingConv(), FnTy->getReturnType(),
  2211. getValue(GuardCheckFn), std::move(Args));
  2212. std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
  2213. DAG.setRoot(Result.second);
  2214. return;
  2215. }
  2216. // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD.
  2217. // Otherwise, emit a volatile load to retrieve the stack guard value.
  2218. SDValue Chain = DAG.getEntryNode();
  2219. if (TLI.useLoadStackGuardNode()) {
  2220. Guard = getLoadStackGuard(DAG, dl, Chain);
  2221. } else {
  2222. const Value *IRGuard = TLI.getSDagStackGuard(M);
  2223. SDValue GuardPtr = getValue(IRGuard);
  2224. Guard =
  2225. DAG.getLoad(PtrTy, dl, Chain, GuardPtr, MachinePointerInfo(IRGuard, 0),
  2226. Align, MachineMemOperand::MOVolatile);
  2227. }
  2228. // Perform the comparison via a subtract/getsetcc.
  2229. EVT VT = Guard.getValueType();
  2230. SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, Guard, GuardVal);
  2231. SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(),
  2232. *DAG.getContext(),
  2233. Sub.getValueType()),
  2234. Sub, DAG.getConstant(0, dl, VT), ISD::SETNE);
  2235. // If the sub is not 0, then we know the guard/stackslot do not equal, so
  2236. // branch to failure MBB.
  2237. SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
  2238. MVT::Other, GuardVal.getOperand(0),
  2239. Cmp, DAG.getBasicBlock(SPD.getFailureMBB()));
  2240. // Otherwise branch to success MBB.
  2241. SDValue Br = DAG.getNode(ISD::BR, dl,
  2242. MVT::Other, BrCond,
  2243. DAG.getBasicBlock(SPD.getSuccessMBB()));
  2244. DAG.setRoot(Br);
  2245. }
  2246. /// Codegen the failure basic block for a stack protector check.
  2247. ///
  2248. /// A failure stack protector machine basic block consists simply of a call to
  2249. /// __stack_chk_fail().
  2250. ///
  2251. /// For a high level explanation of how this fits into the stack protector
  2252. /// generation see the comment on the declaration of class
  2253. /// StackProtectorDescriptor.
  2254. void
  2255. SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) {
  2256. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2257. SDValue Chain =
  2258. TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid,
  2259. None, false, getCurSDLoc(), false, false).second;
  2260. // On PS4, the "return address" must still be within the calling function,
  2261. // even if it's at the very end, so emit an explicit TRAP here.
  2262. // Passing 'true' for doesNotReturn above won't generate the trap for us.
  2263. if (TM.getTargetTriple().isPS4CPU())
  2264. Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain);
  2265. DAG.setRoot(Chain);
  2266. }
  2267. /// visitBitTestHeader - This function emits necessary code to produce value
  2268. /// suitable for "bit tests"
  2269. void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B,
  2270. MachineBasicBlock *SwitchBB) {
  2271. SDLoc dl = getCurSDLoc();
  2272. // Subtract the minimum value
  2273. SDValue SwitchOp = getValue(B.SValue);
  2274. EVT VT = SwitchOp.getValueType();
  2275. SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp,
  2276. DAG.getConstant(B.First, dl, VT));
  2277. // Check range
  2278. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2279. SDValue RangeCmp = DAG.getSetCC(
  2280. dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
  2281. Sub.getValueType()),
  2282. Sub, DAG.getConstant(B.Range, dl, VT), ISD::SETUGT);
  2283. // Determine the type of the test operands.
  2284. bool UsePtrType = false;
  2285. if (!TLI.isTypeLegal(VT))
  2286. UsePtrType = true;
  2287. else {
  2288. for (unsigned i = 0, e = B.Cases.size(); i != e; ++i)
  2289. if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) {
  2290. // Switch table case range are encoded into series of masks.
  2291. // Just use pointer type, it's guaranteed to fit.
  2292. UsePtrType = true;
  2293. break;
  2294. }
  2295. }
  2296. if (UsePtrType) {
  2297. VT = TLI.getPointerTy(DAG.getDataLayout());
  2298. Sub = DAG.getZExtOrTrunc(Sub, dl, VT);
  2299. }
  2300. B.RegVT = VT.getSimpleVT();
  2301. B.Reg = FuncInfo.CreateReg(B.RegVT);
  2302. SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub);
  2303. MachineBasicBlock* MBB = B.Cases[0].ThisBB;
  2304. addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb);
  2305. addSuccessorWithProb(SwitchBB, MBB, B.Prob);
  2306. SwitchBB->normalizeSuccProbs();
  2307. SDValue BrRange = DAG.getNode(ISD::BRCOND, dl,
  2308. MVT::Other, CopyTo, RangeCmp,
  2309. DAG.getBasicBlock(B.Default));
  2310. // Avoid emitting unnecessary branches to the next block.
  2311. if (MBB != NextBlock(SwitchBB))
  2312. BrRange = DAG.getNode(ISD::BR, dl, MVT::Other, BrRange,
  2313. DAG.getBasicBlock(MBB));
  2314. DAG.setRoot(BrRange);
  2315. }
  2316. /// visitBitTestCase - this function produces one "bit test"
  2317. void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB,
  2318. MachineBasicBlock* NextMBB,
  2319. BranchProbability BranchProbToNext,
  2320. unsigned Reg,
  2321. BitTestCase &B,
  2322. MachineBasicBlock *SwitchBB) {
  2323. SDLoc dl = getCurSDLoc();
  2324. MVT VT = BB.RegVT;
  2325. SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT);
  2326. SDValue Cmp;
  2327. unsigned PopCount = countPopulation(B.Mask);
  2328. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2329. if (PopCount == 1) {
  2330. // Testing for a single bit; just compare the shift count with what it
  2331. // would need to be to shift a 1 bit in that position.
  2332. Cmp = DAG.getSetCC(
  2333. dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
  2334. ShiftOp, DAG.getConstant(countTrailingZeros(B.Mask), dl, VT),
  2335. ISD::SETEQ);
  2336. } else if (PopCount == BB.Range) {
  2337. // There is only one zero bit in the range, test for it directly.
  2338. Cmp = DAG.getSetCC(
  2339. dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
  2340. ShiftOp, DAG.getConstant(countTrailingOnes(B.Mask), dl, VT),
  2341. ISD::SETNE);
  2342. } else {
  2343. // Make desired shift
  2344. SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT,
  2345. DAG.getConstant(1, dl, VT), ShiftOp);
  2346. // Emit bit tests and jumps
  2347. SDValue AndOp = DAG.getNode(ISD::AND, dl,
  2348. VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT));
  2349. Cmp = DAG.getSetCC(
  2350. dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
  2351. AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE);
  2352. }
  2353. // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb.
  2354. addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb);
  2355. // The branch probability from SwitchBB to NextMBB is BranchProbToNext.
  2356. addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext);
  2357. // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is
  2358. // one as they are relative probabilities (and thus work more like weights),
  2359. // and hence we need to normalize them to let the sum of them become one.
  2360. SwitchBB->normalizeSuccProbs();
  2361. SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl,
  2362. MVT::Other, getControlRoot(),
  2363. Cmp, DAG.getBasicBlock(B.TargetBB));
  2364. // Avoid emitting unnecessary branches to the next block.
  2365. if (NextMBB != NextBlock(SwitchBB))
  2366. BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd,
  2367. DAG.getBasicBlock(NextMBB));
  2368. DAG.setRoot(BrAnd);
  2369. }
  2370. void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) {
  2371. MachineBasicBlock *InvokeMBB = FuncInfo.MBB;
  2372. // Retrieve successors. Look through artificial IR level blocks like
  2373. // catchswitch for successors.
  2374. MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
  2375. const BasicBlock *EHPadBB = I.getSuccessor(1);
  2376. // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
  2377. // have to do anything here to lower funclet bundles.
  2378. assert(!I.hasOperandBundlesOtherThan(
  2379. {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) &&
  2380. "Cannot lower invokes with arbitrary operand bundles yet!");
  2381. const Value *Callee(I.getCalledValue());
  2382. const Function *Fn = dyn_cast<Function>(Callee);
  2383. if (isa<InlineAsm>(Callee))
  2384. visitInlineAsm(&I);
  2385. else if (Fn && Fn->isIntrinsic()) {
  2386. switch (Fn->getIntrinsicID()) {
  2387. default:
  2388. llvm_unreachable("Cannot invoke this intrinsic");
  2389. case Intrinsic::donothing:
  2390. // Ignore invokes to @llvm.donothing: jump directly to the next BB.
  2391. break;
  2392. case Intrinsic::experimental_patchpoint_void:
  2393. case Intrinsic::experimental_patchpoint_i64:
  2394. visitPatchpoint(&I, EHPadBB);
  2395. break;
  2396. case Intrinsic::experimental_gc_statepoint:
  2397. LowerStatepoint(ImmutableStatepoint(&I), EHPadBB);
  2398. break;
  2399. case Intrinsic::wasm_rethrow_in_catch: {
  2400. // This is usually done in visitTargetIntrinsic, but this intrinsic is
  2401. // special because it can be invoked, so we manually lower it to a DAG
  2402. // node here.
  2403. SmallVector<SDValue, 8> Ops;
  2404. Ops.push_back(getRoot()); // inchain
  2405. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2406. Ops.push_back(
  2407. DAG.getTargetConstant(Intrinsic::wasm_rethrow_in_catch, getCurSDLoc(),
  2408. TLI.getPointerTy(DAG.getDataLayout())));
  2409. SDVTList VTs = DAG.getVTList(ArrayRef<EVT>({MVT::Other})); // outchain
  2410. DAG.setRoot(DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops));
  2411. break;
  2412. }
  2413. }
  2414. } else if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) {
  2415. // Currently we do not lower any intrinsic calls with deopt operand bundles.
  2416. // Eventually we will support lowering the @llvm.experimental.deoptimize
  2417. // intrinsic, and right now there are no plans to support other intrinsics
  2418. // with deopt state.
  2419. LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB);
  2420. } else {
  2421. LowerCallTo(&I, getValue(Callee), false, EHPadBB);
  2422. }
  2423. // If the value of the invoke is used outside of its defining block, make it
  2424. // available as a virtual register.
  2425. // We already took care of the exported value for the statepoint instruction
  2426. // during call to the LowerStatepoint.
  2427. if (!isStatepoint(I)) {
  2428. CopyToExportRegsIfNeeded(&I);
  2429. }
  2430. SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
  2431. BranchProbabilityInfo *BPI = FuncInfo.BPI;
  2432. BranchProbability EHPadBBProb =
  2433. BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB)
  2434. : BranchProbability::getZero();
  2435. findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests);
  2436. // Update successor info.
  2437. addSuccessorWithProb(InvokeMBB, Return);
  2438. for (auto &UnwindDest : UnwindDests) {
  2439. UnwindDest.first->setIsEHPad();
  2440. addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second);
  2441. }
  2442. InvokeMBB->normalizeSuccProbs();
  2443. // Drop into normal successor.
  2444. DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, getControlRoot(),
  2445. DAG.getBasicBlock(Return)));
  2446. }
  2447. void SelectionDAGBuilder::visitCallBr(const CallBrInst &I) {
  2448. MachineBasicBlock *CallBrMBB = FuncInfo.MBB;
  2449. // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
  2450. // have to do anything here to lower funclet bundles.
  2451. assert(!I.hasOperandBundlesOtherThan(
  2452. {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) &&
  2453. "Cannot lower callbrs with arbitrary operand bundles yet!");
  2454. assert(isa<InlineAsm>(I.getCalledValue()) &&
  2455. "Only know how to handle inlineasm callbr");
  2456. visitInlineAsm(&I);
  2457. // Retrieve successors.
  2458. MachineBasicBlock *Return = FuncInfo.MBBMap[I.getDefaultDest()];
  2459. // Update successor info.
  2460. addSuccessorWithProb(CallBrMBB, Return);
  2461. for (unsigned i = 0, e = I.getNumIndirectDests(); i < e; ++i) {
  2462. MachineBasicBlock *Target = FuncInfo.MBBMap[I.getIndirectDest(i)];
  2463. addSuccessorWithProb(CallBrMBB, Target);
  2464. }
  2465. CallBrMBB->normalizeSuccProbs();
  2466. // Drop into default successor.
  2467. DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
  2468. MVT::Other, getControlRoot(),
  2469. DAG.getBasicBlock(Return)));
  2470. }
  2471. void SelectionDAGBuilder::visitResume(const ResumeInst &RI) {
  2472. llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!");
  2473. }
  2474. void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) {
  2475. assert(FuncInfo.MBB->isEHPad() &&
  2476. "Call to landingpad not in landing pad!");
  2477. // If there aren't registers to copy the values into (e.g., during SjLj
  2478. // exceptions), then don't bother to create these DAG nodes.
  2479. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2480. const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn();
  2481. if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 &&
  2482. TLI.getExceptionSelectorRegister(PersonalityFn) == 0)
  2483. return;
  2484. // If landingpad's return type is token type, we don't create DAG nodes
  2485. // for its exception pointer and selector value. The extraction of exception
  2486. // pointer or selector value from token type landingpads is not currently
  2487. // supported.
  2488. if (LP.getType()->isTokenTy())
  2489. return;
  2490. SmallVector<EVT, 2> ValueVTs;
  2491. SDLoc dl = getCurSDLoc();
  2492. ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs);
  2493. assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported");
  2494. // Get the two live-in registers as SDValues. The physregs have already been
  2495. // copied into virtual registers.
  2496. SDValue Ops[2];
  2497. if (FuncInfo.ExceptionPointerVirtReg) {
  2498. Ops[0] = DAG.getZExtOrTrunc(
  2499. DAG.getCopyFromReg(DAG.getEntryNode(), dl,
  2500. FuncInfo.ExceptionPointerVirtReg,
  2501. TLI.getPointerTy(DAG.getDataLayout())),
  2502. dl, ValueVTs[0]);
  2503. } else {
  2504. Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout()));
  2505. }
  2506. Ops[1] = DAG.getZExtOrTrunc(
  2507. DAG.getCopyFromReg(DAG.getEntryNode(), dl,
  2508. FuncInfo.ExceptionSelectorVirtReg,
  2509. TLI.getPointerTy(DAG.getDataLayout())),
  2510. dl, ValueVTs[1]);
  2511. // Merge into one.
  2512. SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl,
  2513. DAG.getVTList(ValueVTs), Ops);
  2514. setValue(&LP, Res);
  2515. }
  2516. void SelectionDAGBuilder::sortAndRangeify(CaseClusterVector &Clusters) {
  2517. #ifndef NDEBUG
  2518. for (const CaseCluster &CC : Clusters)
  2519. assert(CC.Low == CC.High && "Input clusters must be single-case");
  2520. #endif
  2521. llvm::sort(Clusters, [](const CaseCluster &a, const CaseCluster &b) {
  2522. return a.Low->getValue().slt(b.Low->getValue());
  2523. });
  2524. // Merge adjacent clusters with the same destination.
  2525. const unsigned N = Clusters.size();
  2526. unsigned DstIndex = 0;
  2527. for (unsigned SrcIndex = 0; SrcIndex < N; ++SrcIndex) {
  2528. CaseCluster &CC = Clusters[SrcIndex];
  2529. const ConstantInt *CaseVal = CC.Low;
  2530. MachineBasicBlock *Succ = CC.MBB;
  2531. if (DstIndex != 0 && Clusters[DstIndex - 1].MBB == Succ &&
  2532. (CaseVal->getValue() - Clusters[DstIndex - 1].High->getValue()) == 1) {
  2533. // If this case has the same successor and is a neighbour, merge it into
  2534. // the previous cluster.
  2535. Clusters[DstIndex - 1].High = CaseVal;
  2536. Clusters[DstIndex - 1].Prob += CC.Prob;
  2537. } else {
  2538. std::memmove(&Clusters[DstIndex++], &Clusters[SrcIndex],
  2539. sizeof(Clusters[SrcIndex]));
  2540. }
  2541. }
  2542. Clusters.resize(DstIndex);
  2543. }
  2544. void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First,
  2545. MachineBasicBlock *Last) {
  2546. // Update JTCases.
  2547. for (unsigned i = 0, e = JTCases.size(); i != e; ++i)
  2548. if (JTCases[i].first.HeaderBB == First)
  2549. JTCases[i].first.HeaderBB = Last;
  2550. // Update BitTestCases.
  2551. for (unsigned i = 0, e = BitTestCases.size(); i != e; ++i)
  2552. if (BitTestCases[i].Parent == First)
  2553. 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. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  2802. I.getType());
  2803. setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode));
  2804. }
  2805. void SelectionDAGBuilder::visitFCmp(const User &I) {
  2806. FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
  2807. if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I))
  2808. predicate = FC->getPredicate();
  2809. else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
  2810. predicate = FCmpInst::Predicate(FC->getPredicate());
  2811. SDValue Op1 = getValue(I.getOperand(0));
  2812. SDValue Op2 = getValue(I.getOperand(1));
  2813. ISD::CondCode Condition = getFCmpCondCode(predicate);
  2814. auto *FPMO = dyn_cast<FPMathOperator>(&I);
  2815. if ((FPMO && FPMO->hasNoNaNs()) || TM.Options.NoNaNsFPMath)
  2816. Condition = getFCmpCodeWithoutNaN(Condition);
  2817. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  2818. I.getType());
  2819. setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition));
  2820. }
  2821. // Check if the condition of the select has one use or two users that are both
  2822. // selects with the same condition.
  2823. static bool hasOnlySelectUsers(const Value *Cond) {
  2824. return llvm::all_of(Cond->users(), [](const Value *V) {
  2825. return isa<SelectInst>(V);
  2826. });
  2827. }
  2828. void SelectionDAGBuilder::visitSelect(const User &I) {
  2829. SmallVector<EVT, 4> ValueVTs;
  2830. ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
  2831. ValueVTs);
  2832. unsigned NumValues = ValueVTs.size();
  2833. if (NumValues == 0) return;
  2834. SmallVector<SDValue, 4> Values(NumValues);
  2835. SDValue Cond = getValue(I.getOperand(0));
  2836. SDValue LHSVal = getValue(I.getOperand(1));
  2837. SDValue RHSVal = getValue(I.getOperand(2));
  2838. auto BaseOps = {Cond};
  2839. ISD::NodeType OpCode = Cond.getValueType().isVector() ?
  2840. ISD::VSELECT : ISD::SELECT;
  2841. bool IsUnaryAbs = false;
  2842. // Min/max matching is only viable if all output VTs are the same.
  2843. if (is_splat(ValueVTs)) {
  2844. EVT VT = ValueVTs[0];
  2845. LLVMContext &Ctx = *DAG.getContext();
  2846. auto &TLI = DAG.getTargetLoweringInfo();
  2847. // We care about the legality of the operation after it has been type
  2848. // legalized.
  2849. while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal &&
  2850. VT != TLI.getTypeToTransformTo(Ctx, VT))
  2851. VT = TLI.getTypeToTransformTo(Ctx, VT);
  2852. // If the vselect is legal, assume we want to leave this as a vector setcc +
  2853. // vselect. Otherwise, if this is going to be scalarized, we want to see if
  2854. // min/max is legal on the scalar type.
  2855. bool UseScalarMinMax = VT.isVector() &&
  2856. !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT);
  2857. Value *LHS, *RHS;
  2858. auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS);
  2859. ISD::NodeType Opc = ISD::DELETED_NODE;
  2860. switch (SPR.Flavor) {
  2861. case SPF_UMAX: Opc = ISD::UMAX; break;
  2862. case SPF_UMIN: Opc = ISD::UMIN; break;
  2863. case SPF_SMAX: Opc = ISD::SMAX; break;
  2864. case SPF_SMIN: Opc = ISD::SMIN; break;
  2865. case SPF_FMINNUM:
  2866. switch (SPR.NaNBehavior) {
  2867. case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
  2868. case SPNB_RETURNS_NAN: Opc = ISD::FMINIMUM; break;
  2869. case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break;
  2870. case SPNB_RETURNS_ANY: {
  2871. if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT))
  2872. Opc = ISD::FMINNUM;
  2873. else if (TLI.isOperationLegalOrCustom(ISD::FMINIMUM, VT))
  2874. Opc = ISD::FMINIMUM;
  2875. else if (UseScalarMinMax)
  2876. Opc = TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType()) ?
  2877. ISD::FMINNUM : ISD::FMINIMUM;
  2878. break;
  2879. }
  2880. }
  2881. break;
  2882. case SPF_FMAXNUM:
  2883. switch (SPR.NaNBehavior) {
  2884. case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
  2885. case SPNB_RETURNS_NAN: Opc = ISD::FMAXIMUM; break;
  2886. case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break;
  2887. case SPNB_RETURNS_ANY:
  2888. if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT))
  2889. Opc = ISD::FMAXNUM;
  2890. else if (TLI.isOperationLegalOrCustom(ISD::FMAXIMUM, VT))
  2891. Opc = ISD::FMAXIMUM;
  2892. else if (UseScalarMinMax)
  2893. Opc = TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType()) ?
  2894. ISD::FMAXNUM : ISD::FMAXIMUM;
  2895. break;
  2896. }
  2897. break;
  2898. case SPF_ABS:
  2899. IsUnaryAbs = true;
  2900. Opc = ISD::ABS;
  2901. break;
  2902. case SPF_NABS:
  2903. // TODO: we need to produce sub(0, abs(X)).
  2904. default: break;
  2905. }
  2906. if (!IsUnaryAbs && Opc != ISD::DELETED_NODE &&
  2907. (TLI.isOperationLegalOrCustom(Opc, VT) ||
  2908. (UseScalarMinMax &&
  2909. TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) &&
  2910. // If the underlying comparison instruction is used by any other
  2911. // instruction, the consumed instructions won't be destroyed, so it is
  2912. // not profitable to convert to a min/max.
  2913. hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) {
  2914. OpCode = Opc;
  2915. LHSVal = getValue(LHS);
  2916. RHSVal = getValue(RHS);
  2917. BaseOps = {};
  2918. }
  2919. if (IsUnaryAbs) {
  2920. OpCode = Opc;
  2921. LHSVal = getValue(LHS);
  2922. BaseOps = {};
  2923. }
  2924. }
  2925. if (IsUnaryAbs) {
  2926. for (unsigned i = 0; i != NumValues; ++i) {
  2927. Values[i] =
  2928. DAG.getNode(OpCode, getCurSDLoc(),
  2929. LHSVal.getNode()->getValueType(LHSVal.getResNo() + i),
  2930. SDValue(LHSVal.getNode(), LHSVal.getResNo() + i));
  2931. }
  2932. } else {
  2933. for (unsigned i = 0; i != NumValues; ++i) {
  2934. SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end());
  2935. Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i));
  2936. Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i));
  2937. Values[i] = DAG.getNode(
  2938. OpCode, getCurSDLoc(),
  2939. LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), Ops);
  2940. }
  2941. }
  2942. setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
  2943. DAG.getVTList(ValueVTs), Values));
  2944. }
  2945. void SelectionDAGBuilder::visitTrunc(const User &I) {
  2946. // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
  2947. SDValue N = getValue(I.getOperand(0));
  2948. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  2949. I.getType());
  2950. setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N));
  2951. }
  2952. void SelectionDAGBuilder::visitZExt(const User &I) {
  2953. // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
  2954. // ZExt also can't be a cast to bool for same reason. So, nothing much to do
  2955. SDValue N = getValue(I.getOperand(0));
  2956. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  2957. I.getType());
  2958. setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N));
  2959. }
  2960. void SelectionDAGBuilder::visitSExt(const User &I) {
  2961. // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
  2962. // SExt also can't be a cast to bool for same reason. So, nothing much to do
  2963. SDValue N = getValue(I.getOperand(0));
  2964. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  2965. I.getType());
  2966. setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
  2967. }
  2968. void SelectionDAGBuilder::visitFPTrunc(const User &I) {
  2969. // FPTrunc is never a no-op cast, no need to check
  2970. SDValue N = getValue(I.getOperand(0));
  2971. SDLoc dl = getCurSDLoc();
  2972. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2973. EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  2974. setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N,
  2975. DAG.getTargetConstant(
  2976. 0, dl, TLI.getPointerTy(DAG.getDataLayout()))));
  2977. }
  2978. void SelectionDAGBuilder::visitFPExt(const User &I) {
  2979. // FPExt is never a no-op cast, no need to check
  2980. SDValue N = getValue(I.getOperand(0));
  2981. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  2982. I.getType());
  2983. setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N));
  2984. }
  2985. void SelectionDAGBuilder::visitFPToUI(const User &I) {
  2986. // FPToUI is never a no-op cast, no need to check
  2987. SDValue N = getValue(I.getOperand(0));
  2988. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  2989. I.getType());
  2990. setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N));
  2991. }
  2992. void SelectionDAGBuilder::visitFPToSI(const User &I) {
  2993. // FPToSI is never a no-op cast, no need to check
  2994. SDValue N = getValue(I.getOperand(0));
  2995. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  2996. I.getType());
  2997. setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N));
  2998. }
  2999. void SelectionDAGBuilder::visitUIToFP(const User &I) {
  3000. // UIToFP is never a no-op cast, no need to check
  3001. SDValue N = getValue(I.getOperand(0));
  3002. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  3003. I.getType());
  3004. setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N));
  3005. }
  3006. void SelectionDAGBuilder::visitSIToFP(const User &I) {
  3007. // SIToFP is never a no-op cast, no need to check
  3008. SDValue N = getValue(I.getOperand(0));
  3009. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  3010. I.getType());
  3011. setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N));
  3012. }
  3013. void SelectionDAGBuilder::visitPtrToInt(const User &I) {
  3014. // What to do depends on the size of the integer and the size of the pointer.
  3015. // We can either truncate, zero extend, or no-op, accordingly.
  3016. SDValue N = getValue(I.getOperand(0));
  3017. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  3018. I.getType());
  3019. setValue(&I, DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT));
  3020. }
  3021. void SelectionDAGBuilder::visitIntToPtr(const User &I) {
  3022. // What to do depends on the size of the integer and the size of the pointer.
  3023. // We can either truncate, zero extend, or no-op, accordingly.
  3024. SDValue N = getValue(I.getOperand(0));
  3025. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  3026. I.getType());
  3027. setValue(&I, DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT));
  3028. }
  3029. void SelectionDAGBuilder::visitBitCast(const User &I) {
  3030. SDValue N = getValue(I.getOperand(0));
  3031. SDLoc dl = getCurSDLoc();
  3032. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  3033. I.getType());
  3034. // BitCast assures us that source and destination are the same size so this is
  3035. // either a BITCAST or a no-op.
  3036. if (DestVT != N.getValueType())
  3037. setValue(&I, DAG.getNode(ISD::BITCAST, dl,
  3038. DestVT, N)); // convert types.
  3039. // Check if the original LLVM IR Operand was a ConstantInt, because getValue()
  3040. // might fold any kind of constant expression to an integer constant and that
  3041. // is not what we are looking for. Only recognize a bitcast of a genuine
  3042. // constant integer as an opaque constant.
  3043. else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0)))
  3044. setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false,
  3045. /*isOpaque*/true));
  3046. else
  3047. setValue(&I, N); // noop cast.
  3048. }
  3049. void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) {
  3050. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3051. const Value *SV = I.getOperand(0);
  3052. SDValue N = getValue(SV);
  3053. EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  3054. unsigned SrcAS = SV->getType()->getPointerAddressSpace();
  3055. unsigned DestAS = I.getType()->getPointerAddressSpace();
  3056. if (!TLI.isNoopAddrSpaceCast(SrcAS, DestAS))
  3057. N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS);
  3058. setValue(&I, N);
  3059. }
  3060. void SelectionDAGBuilder::visitInsertElement(const User &I) {
  3061. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3062. SDValue InVec = getValue(I.getOperand(0));
  3063. SDValue InVal = getValue(I.getOperand(1));
  3064. SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(),
  3065. TLI.getVectorIdxTy(DAG.getDataLayout()));
  3066. setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(),
  3067. TLI.getValueType(DAG.getDataLayout(), I.getType()),
  3068. InVec, InVal, InIdx));
  3069. }
  3070. void SelectionDAGBuilder::visitExtractElement(const User &I) {
  3071. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3072. SDValue InVec = getValue(I.getOperand(0));
  3073. SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(),
  3074. TLI.getVectorIdxTy(DAG.getDataLayout()));
  3075. setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(),
  3076. TLI.getValueType(DAG.getDataLayout(), I.getType()),
  3077. InVec, InIdx));
  3078. }
  3079. void SelectionDAGBuilder::visitShuffleVector(const User &I) {
  3080. SDValue Src1 = getValue(I.getOperand(0));
  3081. SDValue Src2 = getValue(I.getOperand(1));
  3082. SDLoc DL = getCurSDLoc();
  3083. SmallVector<int, 8> Mask;
  3084. ShuffleVectorInst::getShuffleMask(cast<Constant>(I.getOperand(2)), Mask);
  3085. unsigned MaskNumElts = Mask.size();
  3086. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3087. EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  3088. EVT SrcVT = Src1.getValueType();
  3089. unsigned SrcNumElts = SrcVT.getVectorNumElements();
  3090. if (SrcNumElts == MaskNumElts) {
  3091. setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask));
  3092. return;
  3093. }
  3094. // Normalize the shuffle vector since mask and vector length don't match.
  3095. if (SrcNumElts < MaskNumElts) {
  3096. // Mask is longer than the source vectors. We can use concatenate vector to
  3097. // make the mask and vectors lengths match.
  3098. if (MaskNumElts % SrcNumElts == 0) {
  3099. // Mask length is a multiple of the source vector length.
  3100. // Check if the shuffle is some kind of concatenation of the input
  3101. // vectors.
  3102. unsigned NumConcat = MaskNumElts / SrcNumElts;
  3103. bool IsConcat = true;
  3104. SmallVector<int, 8> ConcatSrcs(NumConcat, -1);
  3105. for (unsigned i = 0; i != MaskNumElts; ++i) {
  3106. int Idx = Mask[i];
  3107. if (Idx < 0)
  3108. continue;
  3109. // Ensure the indices in each SrcVT sized piece are sequential and that
  3110. // the same source is used for the whole piece.
  3111. if ((Idx % SrcNumElts != (i % SrcNumElts)) ||
  3112. (ConcatSrcs[i / SrcNumElts] >= 0 &&
  3113. ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) {
  3114. IsConcat = false;
  3115. break;
  3116. }
  3117. // Remember which source this index came from.
  3118. ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts;
  3119. }
  3120. // The shuffle is concatenating multiple vectors together. Just emit
  3121. // a CONCAT_VECTORS operation.
  3122. if (IsConcat) {
  3123. SmallVector<SDValue, 8> ConcatOps;
  3124. for (auto Src : ConcatSrcs) {
  3125. if (Src < 0)
  3126. ConcatOps.push_back(DAG.getUNDEF(SrcVT));
  3127. else if (Src == 0)
  3128. ConcatOps.push_back(Src1);
  3129. else
  3130. ConcatOps.push_back(Src2);
  3131. }
  3132. setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps));
  3133. return;
  3134. }
  3135. }
  3136. unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts);
  3137. unsigned NumConcat = PaddedMaskNumElts / SrcNumElts;
  3138. EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
  3139. PaddedMaskNumElts);
  3140. // Pad both vectors with undefs to make them the same length as the mask.
  3141. SDValue UndefVal = DAG.getUNDEF(SrcVT);
  3142. SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
  3143. SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
  3144. MOps1[0] = Src1;
  3145. MOps2[0] = Src2;
  3146. Src1 = Src1.isUndef()
  3147. ? DAG.getUNDEF(PaddedVT)
  3148. : DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1);
  3149. Src2 = Src2.isUndef()
  3150. ? DAG.getUNDEF(PaddedVT)
  3151. : DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2);
  3152. // Readjust mask for new input vector length.
  3153. SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1);
  3154. for (unsigned i = 0; i != MaskNumElts; ++i) {
  3155. int Idx = Mask[i];
  3156. if (Idx >= (int)SrcNumElts)
  3157. Idx -= SrcNumElts - PaddedMaskNumElts;
  3158. MappedOps[i] = Idx;
  3159. }
  3160. SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps);
  3161. // If the concatenated vector was padded, extract a subvector with the
  3162. // correct number of elements.
  3163. if (MaskNumElts != PaddedMaskNumElts)
  3164. Result = DAG.getNode(
  3165. ISD::EXTRACT_SUBVECTOR, DL, VT, Result,
  3166. DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
  3167. setValue(&I, Result);
  3168. return;
  3169. }
  3170. if (SrcNumElts > MaskNumElts) {
  3171. // Analyze the access pattern of the vector to see if we can extract
  3172. // two subvectors and do the shuffle.
  3173. int StartIdx[2] = { -1, -1 }; // StartIdx to extract from
  3174. bool CanExtract = true;
  3175. for (int Idx : Mask) {
  3176. unsigned Input = 0;
  3177. if (Idx < 0)
  3178. continue;
  3179. if (Idx >= (int)SrcNumElts) {
  3180. Input = 1;
  3181. Idx -= SrcNumElts;
  3182. }
  3183. // If all the indices come from the same MaskNumElts sized portion of
  3184. // the sources we can use extract. Also make sure the extract wouldn't
  3185. // extract past the end of the source.
  3186. int NewStartIdx = alignDown(Idx, MaskNumElts);
  3187. if (NewStartIdx + MaskNumElts > SrcNumElts ||
  3188. (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx))
  3189. CanExtract = false;
  3190. // Make sure we always update StartIdx as we use it to track if all
  3191. // elements are undef.
  3192. StartIdx[Input] = NewStartIdx;
  3193. }
  3194. if (StartIdx[0] < 0 && StartIdx[1] < 0) {
  3195. setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
  3196. return;
  3197. }
  3198. if (CanExtract) {
  3199. // Extract appropriate subvector and generate a vector shuffle
  3200. for (unsigned Input = 0; Input < 2; ++Input) {
  3201. SDValue &Src = Input == 0 ? Src1 : Src2;
  3202. if (StartIdx[Input] < 0)
  3203. Src = DAG.getUNDEF(VT);
  3204. else {
  3205. Src = DAG.getNode(
  3206. ISD::EXTRACT_SUBVECTOR, DL, VT, Src,
  3207. DAG.getConstant(StartIdx[Input], DL,
  3208. TLI.getVectorIdxTy(DAG.getDataLayout())));
  3209. }
  3210. }
  3211. // Calculate new mask.
  3212. SmallVector<int, 8> MappedOps(Mask.begin(), Mask.end());
  3213. for (int &Idx : MappedOps) {
  3214. if (Idx >= (int)SrcNumElts)
  3215. Idx -= SrcNumElts + StartIdx[1] - MaskNumElts;
  3216. else if (Idx >= 0)
  3217. Idx -= StartIdx[0];
  3218. }
  3219. setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps));
  3220. return;
  3221. }
  3222. }
  3223. // We can't use either concat vectors or extract subvectors so fall back to
  3224. // replacing the shuffle with extract and build vector.
  3225. // to insert and build vector.
  3226. EVT EltVT = VT.getVectorElementType();
  3227. EVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout());
  3228. SmallVector<SDValue,8> Ops;
  3229. for (int Idx : Mask) {
  3230. SDValue Res;
  3231. if (Idx < 0) {
  3232. Res = DAG.getUNDEF(EltVT);
  3233. } else {
  3234. SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2;
  3235. if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts;
  3236. Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
  3237. EltVT, Src, DAG.getConstant(Idx, DL, IdxVT));
  3238. }
  3239. Ops.push_back(Res);
  3240. }
  3241. setValue(&I, DAG.getBuildVector(VT, DL, Ops));
  3242. }
  3243. void SelectionDAGBuilder::visitInsertValue(const User &I) {
  3244. ArrayRef<unsigned> Indices;
  3245. if (const InsertValueInst *IV = dyn_cast<InsertValueInst>(&I))
  3246. Indices = IV->getIndices();
  3247. else
  3248. Indices = cast<ConstantExpr>(&I)->getIndices();
  3249. const Value *Op0 = I.getOperand(0);
  3250. const Value *Op1 = I.getOperand(1);
  3251. Type *AggTy = I.getType();
  3252. Type *ValTy = Op1->getType();
  3253. bool IntoUndef = isa<UndefValue>(Op0);
  3254. bool FromUndef = isa<UndefValue>(Op1);
  3255. unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
  3256. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3257. SmallVector<EVT, 4> AggValueVTs;
  3258. ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs);
  3259. SmallVector<EVT, 4> ValValueVTs;
  3260. ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
  3261. unsigned NumAggValues = AggValueVTs.size();
  3262. unsigned NumValValues = ValValueVTs.size();
  3263. SmallVector<SDValue, 4> Values(NumAggValues);
  3264. // Ignore an insertvalue that produces an empty object
  3265. if (!NumAggValues) {
  3266. setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
  3267. return;
  3268. }
  3269. SDValue Agg = getValue(Op0);
  3270. unsigned i = 0;
  3271. // Copy the beginning value(s) from the original aggregate.
  3272. for (; i != LinearIndex; ++i)
  3273. Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
  3274. SDValue(Agg.getNode(), Agg.getResNo() + i);
  3275. // Copy values from the inserted value(s).
  3276. if (NumValValues) {
  3277. SDValue Val = getValue(Op1);
  3278. for (; i != LinearIndex + NumValValues; ++i)
  3279. Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
  3280. SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
  3281. }
  3282. // Copy remaining value(s) from the original aggregate.
  3283. for (; i != NumAggValues; ++i)
  3284. Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
  3285. SDValue(Agg.getNode(), Agg.getResNo() + i);
  3286. setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
  3287. DAG.getVTList(AggValueVTs), Values));
  3288. }
  3289. void SelectionDAGBuilder::visitExtractValue(const User &I) {
  3290. ArrayRef<unsigned> Indices;
  3291. if (const ExtractValueInst *EV = dyn_cast<ExtractValueInst>(&I))
  3292. Indices = EV->getIndices();
  3293. else
  3294. Indices = cast<ConstantExpr>(&I)->getIndices();
  3295. const Value *Op0 = I.getOperand(0);
  3296. Type *AggTy = Op0->getType();
  3297. Type *ValTy = I.getType();
  3298. bool OutOfUndef = isa<UndefValue>(Op0);
  3299. unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
  3300. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3301. SmallVector<EVT, 4> ValValueVTs;
  3302. ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
  3303. unsigned NumValValues = ValValueVTs.size();
  3304. // Ignore a extractvalue that produces an empty object
  3305. if (!NumValValues) {
  3306. setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
  3307. return;
  3308. }
  3309. SmallVector<SDValue, 4> Values(NumValValues);
  3310. SDValue Agg = getValue(Op0);
  3311. // Copy out the selected value(s).
  3312. for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
  3313. Values[i - LinearIndex] =
  3314. OutOfUndef ?
  3315. DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
  3316. SDValue(Agg.getNode(), Agg.getResNo() + i);
  3317. setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
  3318. DAG.getVTList(ValValueVTs), Values));
  3319. }
  3320. void SelectionDAGBuilder::visitGetElementPtr(const User &I) {
  3321. Value *Op0 = I.getOperand(0);
  3322. // Note that the pointer operand may be a vector of pointers. Take the scalar
  3323. // element which holds a pointer.
  3324. unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace();
  3325. SDValue N = getValue(Op0);
  3326. SDLoc dl = getCurSDLoc();
  3327. // Normalize Vector GEP - all scalar operands should be converted to the
  3328. // splat vector.
  3329. unsigned VectorWidth = I.getType()->isVectorTy() ?
  3330. cast<VectorType>(I.getType())->getVectorNumElements() : 0;
  3331. if (VectorWidth && !N.getValueType().isVector()) {
  3332. LLVMContext &Context = *DAG.getContext();
  3333. EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorWidth);
  3334. N = DAG.getSplatBuildVector(VT, dl, N);
  3335. }
  3336. for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I);
  3337. GTI != E; ++GTI) {
  3338. const Value *Idx = GTI.getOperand();
  3339. if (StructType *StTy = GTI.getStructTypeOrNull()) {
  3340. unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
  3341. if (Field) {
  3342. // N = N + Offset
  3343. uint64_t Offset = DL->getStructLayout(StTy)->getElementOffset(Field);
  3344. // In an inbounds GEP with an offset that is nonnegative even when
  3345. // interpreted as signed, assume there is no unsigned overflow.
  3346. SDNodeFlags Flags;
  3347. if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds())
  3348. Flags.setNoUnsignedWrap(true);
  3349. N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N,
  3350. DAG.getConstant(Offset, dl, N.getValueType()), Flags);
  3351. }
  3352. } else {
  3353. unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS);
  3354. MVT IdxTy = MVT::getIntegerVT(IdxSize);
  3355. APInt ElementSize(IdxSize, DL->getTypeAllocSize(GTI.getIndexedType()));
  3356. // If this is a scalar constant or a splat vector of constants,
  3357. // handle it quickly.
  3358. const auto *CI = dyn_cast<ConstantInt>(Idx);
  3359. if (!CI && isa<ConstantDataVector>(Idx) &&
  3360. cast<ConstantDataVector>(Idx)->getSplatValue())
  3361. CI = cast<ConstantInt>(cast<ConstantDataVector>(Idx)->getSplatValue());
  3362. if (CI) {
  3363. if (CI->isZero())
  3364. continue;
  3365. APInt Offs = ElementSize * CI->getValue().sextOrTrunc(IdxSize);
  3366. LLVMContext &Context = *DAG.getContext();
  3367. SDValue OffsVal = VectorWidth ?
  3368. DAG.getConstant(Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorWidth)) :
  3369. DAG.getConstant(Offs, dl, IdxTy);
  3370. // In an inbouds GEP with an offset that is nonnegative even when
  3371. // interpreted as signed, assume there is no unsigned overflow.
  3372. SDNodeFlags Flags;
  3373. if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds())
  3374. Flags.setNoUnsignedWrap(true);
  3375. N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags);
  3376. continue;
  3377. }
  3378. // N = N + Idx * ElementSize;
  3379. SDValue IdxN = getValue(Idx);
  3380. if (!IdxN.getValueType().isVector() && VectorWidth) {
  3381. EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(), VectorWidth);
  3382. IdxN = DAG.getSplatBuildVector(VT, dl, IdxN);
  3383. }
  3384. // If the index is smaller or larger than intptr_t, truncate or extend
  3385. // it.
  3386. IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType());
  3387. // If this is a multiply by a power of two, turn it into a shl
  3388. // immediately. This is a very common case.
  3389. if (ElementSize != 1) {
  3390. if (ElementSize.isPowerOf2()) {
  3391. unsigned Amt = ElementSize.logBase2();
  3392. IdxN = DAG.getNode(ISD::SHL, dl,
  3393. N.getValueType(), IdxN,
  3394. DAG.getConstant(Amt, dl, IdxN.getValueType()));
  3395. } else {
  3396. SDValue Scale = DAG.getConstant(ElementSize, dl, IdxN.getValueType());
  3397. IdxN = DAG.getNode(ISD::MUL, dl,
  3398. N.getValueType(), IdxN, Scale);
  3399. }
  3400. }
  3401. N = DAG.getNode(ISD::ADD, dl,
  3402. N.getValueType(), N, IdxN);
  3403. }
  3404. }
  3405. setValue(&I, N);
  3406. }
  3407. void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) {
  3408. // If this is a fixed sized alloca in the entry block of the function,
  3409. // allocate it statically on the stack.
  3410. if (FuncInfo.StaticAllocaMap.count(&I))
  3411. return; // getValue will auto-populate this.
  3412. SDLoc dl = getCurSDLoc();
  3413. Type *Ty = I.getAllocatedType();
  3414. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3415. auto &DL = DAG.getDataLayout();
  3416. uint64_t TySize = DL.getTypeAllocSize(Ty);
  3417. unsigned Align =
  3418. std::max((unsigned)DL.getPrefTypeAlignment(Ty), I.getAlignment());
  3419. SDValue AllocSize = getValue(I.getArraySize());
  3420. EVT IntPtr = TLI.getPointerTy(DAG.getDataLayout(), DL.getAllocaAddrSpace());
  3421. if (AllocSize.getValueType() != IntPtr)
  3422. AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr);
  3423. AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr,
  3424. AllocSize,
  3425. DAG.getConstant(TySize, dl, IntPtr));
  3426. // Handle alignment. If the requested alignment is less than or equal to
  3427. // the stack alignment, ignore it. If the size is greater than or equal to
  3428. // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
  3429. unsigned StackAlign =
  3430. DAG.getSubtarget().getFrameLowering()->getStackAlignment();
  3431. if (Align <= StackAlign)
  3432. Align = 0;
  3433. // Round the size of the allocation up to the stack alignment size
  3434. // by add SA-1 to the size. This doesn't overflow because we're computing
  3435. // an address inside an alloca.
  3436. SDNodeFlags Flags;
  3437. Flags.setNoUnsignedWrap(true);
  3438. AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize,
  3439. DAG.getConstant(StackAlign - 1, dl, IntPtr), Flags);
  3440. // Mask out the low bits for alignment purposes.
  3441. AllocSize =
  3442. DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize,
  3443. DAG.getConstant(~(uint64_t)(StackAlign - 1), dl, IntPtr));
  3444. SDValue Ops[] = {getRoot(), AllocSize, DAG.getConstant(Align, dl, IntPtr)};
  3445. SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
  3446. SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops);
  3447. setValue(&I, DSA);
  3448. DAG.setRoot(DSA.getValue(1));
  3449. assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects());
  3450. }
  3451. void SelectionDAGBuilder::visitLoad(const LoadInst &I) {
  3452. if (I.isAtomic())
  3453. return visitAtomicLoad(I);
  3454. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3455. const Value *SV = I.getOperand(0);
  3456. if (TLI.supportSwiftError()) {
  3457. // Swifterror values can come from either a function parameter with
  3458. // swifterror attribute or an alloca with swifterror attribute.
  3459. if (const Argument *Arg = dyn_cast<Argument>(SV)) {
  3460. if (Arg->hasSwiftErrorAttr())
  3461. return visitLoadFromSwiftError(I);
  3462. }
  3463. if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) {
  3464. if (Alloca->isSwiftError())
  3465. return visitLoadFromSwiftError(I);
  3466. }
  3467. }
  3468. SDValue Ptr = getValue(SV);
  3469. Type *Ty = I.getType();
  3470. bool isVolatile = I.isVolatile();
  3471. bool isNonTemporal = I.getMetadata(LLVMContext::MD_nontemporal) != nullptr;
  3472. bool isInvariant = I.getMetadata(LLVMContext::MD_invariant_load) != nullptr;
  3473. bool isDereferenceable = isDereferenceablePointer(SV, DAG.getDataLayout());
  3474. unsigned Alignment = I.getAlignment();
  3475. AAMDNodes AAInfo;
  3476. I.getAAMetadata(AAInfo);
  3477. const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
  3478. SmallVector<EVT, 4> ValueVTs;
  3479. SmallVector<uint64_t, 4> Offsets;
  3480. ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &Offsets);
  3481. unsigned NumValues = ValueVTs.size();
  3482. if (NumValues == 0)
  3483. return;
  3484. SDValue Root;
  3485. bool ConstantMemory = false;
  3486. if (isVolatile || NumValues > MaxParallelChains)
  3487. // Serialize volatile loads with other side effects.
  3488. Root = getRoot();
  3489. else if (AA &&
  3490. AA->pointsToConstantMemory(MemoryLocation(
  3491. SV,
  3492. LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
  3493. AAInfo))) {
  3494. // Do not serialize (non-volatile) loads of constant memory with anything.
  3495. Root = DAG.getEntryNode();
  3496. ConstantMemory = true;
  3497. } else {
  3498. // Do not serialize non-volatile loads against each other.
  3499. Root = DAG.getRoot();
  3500. }
  3501. SDLoc dl = getCurSDLoc();
  3502. if (isVolatile)
  3503. Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG);
  3504. // An aggregate load cannot wrap around the address space, so offsets to its
  3505. // parts don't wrap either.
  3506. SDNodeFlags Flags;
  3507. Flags.setNoUnsignedWrap(true);
  3508. SmallVector<SDValue, 4> Values(NumValues);
  3509. SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
  3510. EVT PtrVT = Ptr.getValueType();
  3511. unsigned ChainI = 0;
  3512. for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
  3513. // Serializing loads here may result in excessive register pressure, and
  3514. // TokenFactor places arbitrary choke points on the scheduler. SD scheduling
  3515. // could recover a bit by hoisting nodes upward in the chain by recognizing
  3516. // they are side-effect free or do not alias. The optimizer should really
  3517. // avoid this case by converting large object/array copies to llvm.memcpy
  3518. // (MaxParallelChains should always remain as failsafe).
  3519. if (ChainI == MaxParallelChains) {
  3520. assert(PendingLoads.empty() && "PendingLoads must be serialized first");
  3521. SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
  3522. makeArrayRef(Chains.data(), ChainI));
  3523. Root = Chain;
  3524. ChainI = 0;
  3525. }
  3526. SDValue A = DAG.getNode(ISD::ADD, dl,
  3527. PtrVT, Ptr,
  3528. DAG.getConstant(Offsets[i], dl, PtrVT),
  3529. Flags);
  3530. auto MMOFlags = MachineMemOperand::MONone;
  3531. if (isVolatile)
  3532. MMOFlags |= MachineMemOperand::MOVolatile;
  3533. if (isNonTemporal)
  3534. MMOFlags |= MachineMemOperand::MONonTemporal;
  3535. if (isInvariant)
  3536. MMOFlags |= MachineMemOperand::MOInvariant;
  3537. if (isDereferenceable)
  3538. MMOFlags |= MachineMemOperand::MODereferenceable;
  3539. MMOFlags |= TLI.getMMOFlags(I);
  3540. SDValue L = DAG.getLoad(ValueVTs[i], dl, Root, A,
  3541. MachinePointerInfo(SV, Offsets[i]), Alignment,
  3542. MMOFlags, AAInfo, Ranges);
  3543. Values[i] = L;
  3544. Chains[ChainI] = L.getValue(1);
  3545. }
  3546. if (!ConstantMemory) {
  3547. SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
  3548. makeArrayRef(Chains.data(), ChainI));
  3549. if (isVolatile)
  3550. DAG.setRoot(Chain);
  3551. else
  3552. PendingLoads.push_back(Chain);
  3553. }
  3554. setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl,
  3555. DAG.getVTList(ValueVTs), Values));
  3556. }
  3557. void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) {
  3558. assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
  3559. "call visitStoreToSwiftError when backend supports swifterror");
  3560. SmallVector<EVT, 4> ValueVTs;
  3561. SmallVector<uint64_t, 4> Offsets;
  3562. const Value *SrcV = I.getOperand(0);
  3563. ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
  3564. SrcV->getType(), ValueVTs, &Offsets);
  3565. assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
  3566. "expect a single EVT for swifterror");
  3567. SDValue Src = getValue(SrcV);
  3568. // Create a virtual register, then update the virtual register.
  3569. unsigned VReg; bool CreatedVReg;
  3570. std::tie(VReg, CreatedVReg) = FuncInfo.getOrCreateSwiftErrorVRegDefAt(&I);
  3571. // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue
  3572. // Chain can be getRoot or getControlRoot.
  3573. SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg,
  3574. SDValue(Src.getNode(), Src.getResNo()));
  3575. DAG.setRoot(CopyNode);
  3576. if (CreatedVReg)
  3577. FuncInfo.setCurrentSwiftErrorVReg(FuncInfo.MBB, I.getOperand(1), VReg);
  3578. }
  3579. void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) {
  3580. assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
  3581. "call visitLoadFromSwiftError when backend supports swifterror");
  3582. assert(!I.isVolatile() &&
  3583. I.getMetadata(LLVMContext::MD_nontemporal) == nullptr &&
  3584. I.getMetadata(LLVMContext::MD_invariant_load) == nullptr &&
  3585. "Support volatile, non temporal, invariant for load_from_swift_error");
  3586. const Value *SV = I.getOperand(0);
  3587. Type *Ty = I.getType();
  3588. AAMDNodes AAInfo;
  3589. I.getAAMetadata(AAInfo);
  3590. assert(
  3591. (!AA ||
  3592. !AA->pointsToConstantMemory(MemoryLocation(
  3593. SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
  3594. AAInfo))) &&
  3595. "load_from_swift_error should not be constant memory");
  3596. SmallVector<EVT, 4> ValueVTs;
  3597. SmallVector<uint64_t, 4> Offsets;
  3598. ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty,
  3599. ValueVTs, &Offsets);
  3600. assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
  3601. "expect a single EVT for swifterror");
  3602. // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT
  3603. SDValue L = DAG.getCopyFromReg(
  3604. getRoot(), getCurSDLoc(),
  3605. FuncInfo.getOrCreateSwiftErrorVRegUseAt(&I, FuncInfo.MBB, SV).first,
  3606. ValueVTs[0]);
  3607. setValue(&I, L);
  3608. }
  3609. void SelectionDAGBuilder::visitStore(const StoreInst &I) {
  3610. if (I.isAtomic())
  3611. return visitAtomicStore(I);
  3612. const Value *SrcV = I.getOperand(0);
  3613. const Value *PtrV = I.getOperand(1);
  3614. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3615. if (TLI.supportSwiftError()) {
  3616. // Swifterror values can come from either a function parameter with
  3617. // swifterror attribute or an alloca with swifterror attribute.
  3618. if (const Argument *Arg = dyn_cast<Argument>(PtrV)) {
  3619. if (Arg->hasSwiftErrorAttr())
  3620. return visitStoreToSwiftError(I);
  3621. }
  3622. if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) {
  3623. if (Alloca->isSwiftError())
  3624. return visitStoreToSwiftError(I);
  3625. }
  3626. }
  3627. SmallVector<EVT, 4> ValueVTs;
  3628. SmallVector<uint64_t, 4> Offsets;
  3629. ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
  3630. SrcV->getType(), ValueVTs, &Offsets);
  3631. unsigned NumValues = ValueVTs.size();
  3632. if (NumValues == 0)
  3633. return;
  3634. // Get the lowered operands. Note that we do this after
  3635. // checking if NumResults is zero, because with zero results
  3636. // the operands won't have values in the map.
  3637. SDValue Src = getValue(SrcV);
  3638. SDValue Ptr = getValue(PtrV);
  3639. SDValue Root = getRoot();
  3640. SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
  3641. SDLoc dl = getCurSDLoc();
  3642. EVT PtrVT = Ptr.getValueType();
  3643. unsigned Alignment = I.getAlignment();
  3644. AAMDNodes AAInfo;
  3645. I.getAAMetadata(AAInfo);
  3646. auto MMOFlags = MachineMemOperand::MONone;
  3647. if (I.isVolatile())
  3648. MMOFlags |= MachineMemOperand::MOVolatile;
  3649. if (I.getMetadata(LLVMContext::MD_nontemporal) != nullptr)
  3650. MMOFlags |= MachineMemOperand::MONonTemporal;
  3651. MMOFlags |= TLI.getMMOFlags(I);
  3652. // An aggregate load cannot wrap around the address space, so offsets to its
  3653. // parts don't wrap either.
  3654. SDNodeFlags Flags;
  3655. Flags.setNoUnsignedWrap(true);
  3656. unsigned ChainI = 0;
  3657. for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
  3658. // See visitLoad comments.
  3659. if (ChainI == MaxParallelChains) {
  3660. SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
  3661. makeArrayRef(Chains.data(), ChainI));
  3662. Root = Chain;
  3663. ChainI = 0;
  3664. }
  3665. SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, Ptr,
  3666. DAG.getConstant(Offsets[i], dl, PtrVT), Flags);
  3667. SDValue St = DAG.getStore(
  3668. Root, dl, SDValue(Src.getNode(), Src.getResNo() + i), Add,
  3669. MachinePointerInfo(PtrV, Offsets[i]), Alignment, MMOFlags, AAInfo);
  3670. Chains[ChainI] = St;
  3671. }
  3672. SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
  3673. makeArrayRef(Chains.data(), ChainI));
  3674. DAG.setRoot(StoreNode);
  3675. }
  3676. void SelectionDAGBuilder::visitMaskedStore(const CallInst &I,
  3677. bool IsCompressing) {
  3678. SDLoc sdl = getCurSDLoc();
  3679. auto getMaskedStoreOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
  3680. unsigned& Alignment) {
  3681. // llvm.masked.store.*(Src0, Ptr, alignment, Mask)
  3682. Src0 = I.getArgOperand(0);
  3683. Ptr = I.getArgOperand(1);
  3684. Alignment = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue();
  3685. Mask = I.getArgOperand(3);
  3686. };
  3687. auto getCompressingStoreOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
  3688. unsigned& Alignment) {
  3689. // llvm.masked.compressstore.*(Src0, Ptr, Mask)
  3690. Src0 = I.getArgOperand(0);
  3691. Ptr = I.getArgOperand(1);
  3692. Mask = I.getArgOperand(2);
  3693. Alignment = 0;
  3694. };
  3695. Value *PtrOperand, *MaskOperand, *Src0Operand;
  3696. unsigned Alignment;
  3697. if (IsCompressing)
  3698. getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
  3699. else
  3700. getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
  3701. SDValue Ptr = getValue(PtrOperand);
  3702. SDValue Src0 = getValue(Src0Operand);
  3703. SDValue Mask = getValue(MaskOperand);
  3704. EVT VT = Src0.getValueType();
  3705. if (!Alignment)
  3706. Alignment = DAG.getEVTAlignment(VT);
  3707. AAMDNodes AAInfo;
  3708. I.getAAMetadata(AAInfo);
  3709. MachineMemOperand *MMO =
  3710. DAG.getMachineFunction().
  3711. getMachineMemOperand(MachinePointerInfo(PtrOperand),
  3712. MachineMemOperand::MOStore, VT.getStoreSize(),
  3713. Alignment, AAInfo);
  3714. SDValue StoreNode = DAG.getMaskedStore(getRoot(), sdl, Src0, Ptr, Mask, VT,
  3715. MMO, false /* Truncating */,
  3716. IsCompressing);
  3717. DAG.setRoot(StoreNode);
  3718. setValue(&I, StoreNode);
  3719. }
  3720. // Get a uniform base for the Gather/Scatter intrinsic.
  3721. // The first argument of the Gather/Scatter intrinsic is a vector of pointers.
  3722. // We try to represent it as a base pointer + vector of indices.
  3723. // Usually, the vector of pointers comes from a 'getelementptr' instruction.
  3724. // The first operand of the GEP may be a single pointer or a vector of pointers
  3725. // Example:
  3726. // %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind
  3727. // or
  3728. // %gep.ptr = getelementptr i32, i32* %ptr, <8 x i32> %ind
  3729. // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, ..
  3730. //
  3731. // When the first GEP operand is a single pointer - it is the uniform base we
  3732. // are looking for. If first operand of the GEP is a splat vector - we
  3733. // extract the splat value and use it as a uniform base.
  3734. // In all other cases the function returns 'false'.
  3735. static bool getUniformBase(const Value* &Ptr, SDValue& Base, SDValue& Index,
  3736. SDValue &Scale, SelectionDAGBuilder* SDB) {
  3737. SelectionDAG& DAG = SDB->DAG;
  3738. LLVMContext &Context = *DAG.getContext();
  3739. assert(Ptr->getType()->isVectorTy() && "Uexpected pointer type");
  3740. const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr);
  3741. if (!GEP)
  3742. return false;
  3743. const Value *GEPPtr = GEP->getPointerOperand();
  3744. if (!GEPPtr->getType()->isVectorTy())
  3745. Ptr = GEPPtr;
  3746. else if (!(Ptr = getSplatValue(GEPPtr)))
  3747. return false;
  3748. unsigned FinalIndex = GEP->getNumOperands() - 1;
  3749. Value *IndexVal = GEP->getOperand(FinalIndex);
  3750. // Ensure all the other indices are 0.
  3751. for (unsigned i = 1; i < FinalIndex; ++i) {
  3752. auto *C = dyn_cast<ConstantInt>(GEP->getOperand(i));
  3753. if (!C || !C->isZero())
  3754. return false;
  3755. }
  3756. // The operands of the GEP may be defined in another basic block.
  3757. // In this case we'll not find nodes for the operands.
  3758. if (!SDB->findValue(Ptr) || !SDB->findValue(IndexVal))
  3759. return false;
  3760. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3761. const DataLayout &DL = DAG.getDataLayout();
  3762. Scale = DAG.getTargetConstant(DL.getTypeAllocSize(GEP->getResultElementType()),
  3763. SDB->getCurSDLoc(), TLI.getPointerTy(DL));
  3764. Base = SDB->getValue(Ptr);
  3765. Index = SDB->getValue(IndexVal);
  3766. if (!Index.getValueType().isVector()) {
  3767. unsigned GEPWidth = GEP->getType()->getVectorNumElements();
  3768. EVT VT = EVT::getVectorVT(Context, Index.getValueType(), GEPWidth);
  3769. Index = DAG.getSplatBuildVector(VT, SDLoc(Index), Index);
  3770. }
  3771. return true;
  3772. }
  3773. void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) {
  3774. SDLoc sdl = getCurSDLoc();
  3775. // llvm.masked.scatter.*(Src0, Ptrs, alignemt, Mask)
  3776. const Value *Ptr = I.getArgOperand(1);
  3777. SDValue Src0 = getValue(I.getArgOperand(0));
  3778. SDValue Mask = getValue(I.getArgOperand(3));
  3779. EVT VT = Src0.getValueType();
  3780. unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(2)))->getZExtValue();
  3781. if (!Alignment)
  3782. Alignment = DAG.getEVTAlignment(VT);
  3783. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3784. AAMDNodes AAInfo;
  3785. I.getAAMetadata(AAInfo);
  3786. SDValue Base;
  3787. SDValue Index;
  3788. SDValue Scale;
  3789. const Value *BasePtr = Ptr;
  3790. bool UniformBase = getUniformBase(BasePtr, Base, Index, Scale, this);
  3791. const Value *MemOpBasePtr = UniformBase ? BasePtr : nullptr;
  3792. MachineMemOperand *MMO = DAG.getMachineFunction().
  3793. getMachineMemOperand(MachinePointerInfo(MemOpBasePtr),
  3794. MachineMemOperand::MOStore, VT.getStoreSize(),
  3795. Alignment, AAInfo);
  3796. if (!UniformBase) {
  3797. Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
  3798. Index = getValue(Ptr);
  3799. Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
  3800. }
  3801. SDValue Ops[] = { getRoot(), Src0, Mask, Base, Index, Scale };
  3802. SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl,
  3803. Ops, MMO);
  3804. DAG.setRoot(Scatter);
  3805. setValue(&I, Scatter);
  3806. }
  3807. void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) {
  3808. SDLoc sdl = getCurSDLoc();
  3809. auto getMaskedLoadOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
  3810. unsigned& Alignment) {
  3811. // @llvm.masked.load.*(Ptr, alignment, Mask, Src0)
  3812. Ptr = I.getArgOperand(0);
  3813. Alignment = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
  3814. Mask = I.getArgOperand(2);
  3815. Src0 = I.getArgOperand(3);
  3816. };
  3817. auto getExpandingLoadOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
  3818. unsigned& Alignment) {
  3819. // @llvm.masked.expandload.*(Ptr, Mask, Src0)
  3820. Ptr = I.getArgOperand(0);
  3821. Alignment = 0;
  3822. Mask = I.getArgOperand(1);
  3823. Src0 = I.getArgOperand(2);
  3824. };
  3825. Value *PtrOperand, *MaskOperand, *Src0Operand;
  3826. unsigned Alignment;
  3827. if (IsExpanding)
  3828. getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
  3829. else
  3830. getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
  3831. SDValue Ptr = getValue(PtrOperand);
  3832. SDValue Src0 = getValue(Src0Operand);
  3833. SDValue Mask = getValue(MaskOperand);
  3834. EVT VT = Src0.getValueType();
  3835. if (!Alignment)
  3836. Alignment = DAG.getEVTAlignment(VT);
  3837. AAMDNodes AAInfo;
  3838. I.getAAMetadata(AAInfo);
  3839. const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
  3840. // Do not serialize masked loads of constant memory with anything.
  3841. bool AddToChain =
  3842. !AA || !AA->pointsToConstantMemory(MemoryLocation(
  3843. PtrOperand,
  3844. LocationSize::precise(
  3845. DAG.getDataLayout().getTypeStoreSize(I.getType())),
  3846. AAInfo));
  3847. SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
  3848. MachineMemOperand *MMO =
  3849. DAG.getMachineFunction().
  3850. getMachineMemOperand(MachinePointerInfo(PtrOperand),
  3851. MachineMemOperand::MOLoad, VT.getStoreSize(),
  3852. Alignment, AAInfo, Ranges);
  3853. SDValue Load = DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Mask, Src0, VT, MMO,
  3854. ISD::NON_EXTLOAD, IsExpanding);
  3855. if (AddToChain)
  3856. PendingLoads.push_back(Load.getValue(1));
  3857. setValue(&I, Load);
  3858. }
  3859. void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) {
  3860. SDLoc sdl = getCurSDLoc();
  3861. // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0)
  3862. const Value *Ptr = I.getArgOperand(0);
  3863. SDValue Src0 = getValue(I.getArgOperand(3));
  3864. SDValue Mask = getValue(I.getArgOperand(2));
  3865. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3866. EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  3867. unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(1)))->getZExtValue();
  3868. if (!Alignment)
  3869. Alignment = DAG.getEVTAlignment(VT);
  3870. AAMDNodes AAInfo;
  3871. I.getAAMetadata(AAInfo);
  3872. const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
  3873. SDValue Root = DAG.getRoot();
  3874. SDValue Base;
  3875. SDValue Index;
  3876. SDValue Scale;
  3877. const Value *BasePtr = Ptr;
  3878. bool UniformBase = getUniformBase(BasePtr, Base, Index, Scale, this);
  3879. bool ConstantMemory = false;
  3880. if (UniformBase && AA &&
  3881. AA->pointsToConstantMemory(
  3882. MemoryLocation(BasePtr,
  3883. LocationSize::precise(
  3884. DAG.getDataLayout().getTypeStoreSize(I.getType())),
  3885. AAInfo))) {
  3886. // Do not serialize (non-volatile) loads of constant memory with anything.
  3887. Root = DAG.getEntryNode();
  3888. ConstantMemory = true;
  3889. }
  3890. MachineMemOperand *MMO =
  3891. DAG.getMachineFunction().
  3892. getMachineMemOperand(MachinePointerInfo(UniformBase ? BasePtr : nullptr),
  3893. MachineMemOperand::MOLoad, VT.getStoreSize(),
  3894. Alignment, AAInfo, Ranges);
  3895. if (!UniformBase) {
  3896. Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
  3897. Index = getValue(Ptr);
  3898. Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
  3899. }
  3900. SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale };
  3901. SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl,
  3902. Ops, MMO);
  3903. SDValue OutChain = Gather.getValue(1);
  3904. if (!ConstantMemory)
  3905. PendingLoads.push_back(OutChain);
  3906. setValue(&I, Gather);
  3907. }
  3908. void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) {
  3909. SDLoc dl = getCurSDLoc();
  3910. AtomicOrdering SuccessOrdering = I.getSuccessOrdering();
  3911. AtomicOrdering FailureOrdering = I.getFailureOrdering();
  3912. SyncScope::ID SSID = I.getSyncScopeID();
  3913. SDValue InChain = getRoot();
  3914. MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType();
  3915. SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other);
  3916. auto Alignment = DAG.getEVTAlignment(MemVT);
  3917. auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
  3918. if (I.isVolatile())
  3919. Flags |= MachineMemOperand::MOVolatile;
  3920. Flags |= DAG.getTargetLoweringInfo().getMMOFlags(I);
  3921. MachineFunction &MF = DAG.getMachineFunction();
  3922. MachineMemOperand *MMO =
  3923. MF.getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()),
  3924. Flags, MemVT.getStoreSize(), Alignment,
  3925. AAMDNodes(), nullptr, SSID, SuccessOrdering,
  3926. FailureOrdering);
  3927. SDValue L = DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS,
  3928. dl, MemVT, VTs, InChain,
  3929. getValue(I.getPointerOperand()),
  3930. getValue(I.getCompareOperand()),
  3931. getValue(I.getNewValOperand()), MMO);
  3932. SDValue OutChain = L.getValue(2);
  3933. setValue(&I, L);
  3934. DAG.setRoot(OutChain);
  3935. }
  3936. void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) {
  3937. SDLoc dl = getCurSDLoc();
  3938. ISD::NodeType NT;
  3939. switch (I.getOperation()) {
  3940. default: llvm_unreachable("Unknown atomicrmw operation");
  3941. case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break;
  3942. case AtomicRMWInst::Add: NT = ISD::ATOMIC_LOAD_ADD; break;
  3943. case AtomicRMWInst::Sub: NT = ISD::ATOMIC_LOAD_SUB; break;
  3944. case AtomicRMWInst::And: NT = ISD::ATOMIC_LOAD_AND; break;
  3945. case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break;
  3946. case AtomicRMWInst::Or: NT = ISD::ATOMIC_LOAD_OR; break;
  3947. case AtomicRMWInst::Xor: NT = ISD::ATOMIC_LOAD_XOR; break;
  3948. case AtomicRMWInst::Max: NT = ISD::ATOMIC_LOAD_MAX; break;
  3949. case AtomicRMWInst::Min: NT = ISD::ATOMIC_LOAD_MIN; break;
  3950. case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break;
  3951. case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break;
  3952. case AtomicRMWInst::FAdd: NT = ISD::ATOMIC_LOAD_FADD; break;
  3953. case AtomicRMWInst::FSub: NT = ISD::ATOMIC_LOAD_FSUB; break;
  3954. }
  3955. AtomicOrdering Ordering = I.getOrdering();
  3956. SyncScope::ID SSID = I.getSyncScopeID();
  3957. SDValue InChain = getRoot();
  3958. auto MemVT = getValue(I.getValOperand()).getSimpleValueType();
  3959. auto Alignment = DAG.getEVTAlignment(MemVT);
  3960. auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
  3961. if (I.isVolatile())
  3962. Flags |= MachineMemOperand::MOVolatile;
  3963. Flags |= DAG.getTargetLoweringInfo().getMMOFlags(I);
  3964. MachineFunction &MF = DAG.getMachineFunction();
  3965. MachineMemOperand *MMO =
  3966. MF.getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()), Flags,
  3967. MemVT.getStoreSize(), Alignment, AAMDNodes(),
  3968. nullptr, SSID, Ordering);
  3969. SDValue L =
  3970. DAG.getAtomic(NT, dl, MemVT, InChain,
  3971. getValue(I.getPointerOperand()), getValue(I.getValOperand()),
  3972. MMO);
  3973. SDValue OutChain = L.getValue(1);
  3974. setValue(&I, L);
  3975. DAG.setRoot(OutChain);
  3976. }
  3977. void SelectionDAGBuilder::visitFence(const FenceInst &I) {
  3978. SDLoc dl = getCurSDLoc();
  3979. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3980. SDValue Ops[3];
  3981. Ops[0] = getRoot();
  3982. Ops[1] = DAG.getConstant((unsigned)I.getOrdering(), dl,
  3983. TLI.getFenceOperandTy(DAG.getDataLayout()));
  3984. Ops[2] = DAG.getConstant(I.getSyncScopeID(), dl,
  3985. TLI.getFenceOperandTy(DAG.getDataLayout()));
  3986. DAG.setRoot(DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops));
  3987. }
  3988. void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) {
  3989. SDLoc dl = getCurSDLoc();
  3990. AtomicOrdering Order = I.getOrdering();
  3991. SyncScope::ID SSID = I.getSyncScopeID();
  3992. SDValue InChain = getRoot();
  3993. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3994. EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  3995. if (!TLI.supportsUnalignedAtomics() &&
  3996. I.getAlignment() < VT.getStoreSize())
  3997. report_fatal_error("Cannot generate unaligned atomic load");
  3998. auto Flags = MachineMemOperand::MOLoad;
  3999. if (I.isVolatile())
  4000. Flags |= MachineMemOperand::MOVolatile;
  4001. if (I.getMetadata(LLVMContext::MD_invariant_load) != nullptr)
  4002. Flags |= MachineMemOperand::MOInvariant;
  4003. if (isDereferenceablePointer(I.getPointerOperand(), DAG.getDataLayout()))
  4004. Flags |= MachineMemOperand::MODereferenceable;
  4005. Flags |= TLI.getMMOFlags(I);
  4006. MachineMemOperand *MMO =
  4007. DAG.getMachineFunction().
  4008. getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()),
  4009. Flags, VT.getStoreSize(),
  4010. I.getAlignment() ? I.getAlignment() :
  4011. DAG.getEVTAlignment(VT),
  4012. AAMDNodes(), nullptr, SSID, Order);
  4013. InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG);
  4014. SDValue L =
  4015. DAG.getAtomic(ISD::ATOMIC_LOAD, dl, VT, VT, InChain,
  4016. getValue(I.getPointerOperand()), MMO);
  4017. SDValue OutChain = L.getValue(1);
  4018. setValue(&I, L);
  4019. DAG.setRoot(OutChain);
  4020. }
  4021. void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) {
  4022. SDLoc dl = getCurSDLoc();
  4023. AtomicOrdering Ordering = I.getOrdering();
  4024. SyncScope::ID SSID = I.getSyncScopeID();
  4025. SDValue InChain = getRoot();
  4026. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  4027. EVT VT =
  4028. TLI.getValueType(DAG.getDataLayout(), I.getValueOperand()->getType());
  4029. if (I.getAlignment() < VT.getStoreSize())
  4030. report_fatal_error("Cannot generate unaligned atomic store");
  4031. auto Flags = MachineMemOperand::MOStore;
  4032. if (I.isVolatile())
  4033. Flags |= MachineMemOperand::MOVolatile;
  4034. Flags |= TLI.getMMOFlags(I);
  4035. MachineFunction &MF = DAG.getMachineFunction();
  4036. MachineMemOperand *MMO =
  4037. MF.getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()), Flags,
  4038. VT.getStoreSize(), I.getAlignment(), AAMDNodes(),
  4039. nullptr, SSID, Ordering);
  4040. SDValue OutChain =
  4041. DAG.getAtomic(ISD::ATOMIC_STORE, dl, VT, InChain,
  4042. getValue(I.getPointerOperand()), getValue(I.getValueOperand()),
  4043. MMO);
  4044. DAG.setRoot(OutChain);
  4045. }
  4046. /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
  4047. /// node.
  4048. void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I,
  4049. unsigned Intrinsic) {
  4050. // Ignore the callsite's attributes. A specific call site may be marked with
  4051. // readnone, but the lowering code will expect the chain based on the
  4052. // definition.
  4053. const Function *F = I.getCalledFunction();
  4054. bool HasChain = !F->doesNotAccessMemory();
  4055. bool OnlyLoad = HasChain && F->onlyReadsMemory();
  4056. // Build the operand list.
  4057. SmallVector<SDValue, 8> Ops;
  4058. if (HasChain) { // If this intrinsic has side-effects, chainify it.
  4059. if (OnlyLoad) {
  4060. // We don't need to serialize loads against other loads.
  4061. Ops.push_back(DAG.getRoot());
  4062. } else {
  4063. Ops.push_back(getRoot());
  4064. }
  4065. }
  4066. // Info is set by getTgtMemInstrinsic
  4067. TargetLowering::IntrinsicInfo Info;
  4068. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  4069. bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I,
  4070. DAG.getMachineFunction(),
  4071. Intrinsic);
  4072. // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
  4073. if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID ||
  4074. Info.opc == ISD::INTRINSIC_W_CHAIN)
  4075. Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(),
  4076. TLI.getPointerTy(DAG.getDataLayout())));
  4077. // Add all operands of the call to the operand list.
  4078. for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) {
  4079. SDValue Op = getValue(I.getArgOperand(i));
  4080. Ops.push_back(Op);
  4081. }
  4082. SmallVector<EVT, 4> ValueVTs;
  4083. ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs);
  4084. if (HasChain)
  4085. ValueVTs.push_back(MVT::Other);
  4086. SDVTList VTs = DAG.getVTList(ValueVTs);
  4087. // Create the node.
  4088. SDValue Result;
  4089. if (IsTgtIntrinsic) {
  4090. // This is target intrinsic that touches memory
  4091. Result = DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(), VTs,
  4092. Ops, Info.memVT,
  4093. MachinePointerInfo(Info.ptrVal, Info.offset), Info.align,
  4094. Info.flags, Info.size);
  4095. } else if (!HasChain) {
  4096. Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops);
  4097. } else if (!I.getType()->isVoidTy()) {
  4098. Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops);
  4099. } else {
  4100. Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops);
  4101. }
  4102. if (HasChain) {
  4103. SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
  4104. if (OnlyLoad)
  4105. PendingLoads.push_back(Chain);
  4106. else
  4107. DAG.setRoot(Chain);
  4108. }
  4109. if (!I.getType()->isVoidTy()) {
  4110. if (VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
  4111. EVT VT = TLI.getValueType(DAG.getDataLayout(), PTy);
  4112. Result = DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT, Result);
  4113. } else
  4114. Result = lowerRangeToAssertZExt(DAG, I, Result);
  4115. setValue(&I, Result);
  4116. }
  4117. }
  4118. /// GetSignificand - Get the significand and build it into a floating-point
  4119. /// number with exponent of 1:
  4120. ///
  4121. /// Op = (Op & 0x007fffff) | 0x3f800000;
  4122. ///
  4123. /// where Op is the hexadecimal representation of floating point value.
  4124. static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) {
  4125. SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
  4126. DAG.getConstant(0x007fffff, dl, MVT::i32));
  4127. SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
  4128. DAG.getConstant(0x3f800000, dl, MVT::i32));
  4129. return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2);
  4130. }
  4131. /// GetExponent - Get the exponent:
  4132. ///
  4133. /// (float)(int)(((Op & 0x7f800000) >> 23) - 127);
  4134. ///
  4135. /// where Op is the hexadecimal representation of floating point value.
  4136. static SDValue GetExponent(SelectionDAG &DAG, SDValue Op,
  4137. const TargetLowering &TLI, const SDLoc &dl) {
  4138. SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
  4139. DAG.getConstant(0x7f800000, dl, MVT::i32));
  4140. SDValue t1 = DAG.getNode(
  4141. ISD::SRL, dl, MVT::i32, t0,
  4142. DAG.getConstant(23, dl, TLI.getPointerTy(DAG.getDataLayout())));
  4143. SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
  4144. DAG.getConstant(127, dl, MVT::i32));
  4145. return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
  4146. }
  4147. /// getF32Constant - Get 32-bit floating point constant.
  4148. static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt,
  4149. const SDLoc &dl) {
  4150. return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl,
  4151. MVT::f32);
  4152. }
  4153. static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl,
  4154. SelectionDAG &DAG) {
  4155. // TODO: What fast-math-flags should be set on the floating-point nodes?
  4156. // IntegerPartOfX = ((int32_t)(t0);
  4157. SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
  4158. // FractionalPartOfX = t0 - (float)IntegerPartOfX;
  4159. SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
  4160. SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
  4161. // IntegerPartOfX <<= 23;
  4162. IntegerPartOfX = DAG.getNode(
  4163. ISD::SHL, dl, MVT::i32, IntegerPartOfX,
  4164. DAG.getConstant(23, dl, DAG.getTargetLoweringInfo().getPointerTy(
  4165. DAG.getDataLayout())));
  4166. SDValue TwoToFractionalPartOfX;
  4167. if (LimitFloatPrecision <= 6) {
  4168. // For floating-point precision of 6:
  4169. //
  4170. // TwoToFractionalPartOfX =
  4171. // 0.997535578f +
  4172. // (0.735607626f + 0.252464424f * x) * x;
  4173. //
  4174. // error 0.0144103317, which is 6 bits
  4175. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  4176. getF32Constant(DAG, 0x3e814304, dl));
  4177. SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
  4178. getF32Constant(DAG, 0x3f3c50c8, dl));
  4179. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  4180. TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  4181. getF32Constant(DAG, 0x3f7f5e7e, dl));
  4182. } else if (LimitFloatPrecision <= 12) {
  4183. // For floating-point precision of 12:
  4184. //
  4185. // TwoToFractionalPartOfX =
  4186. // 0.999892986f +
  4187. // (0.696457318f +
  4188. // (0.224338339f + 0.792043434e-1f * x) * x) * x;
  4189. //
  4190. // error 0.000107046256, which is 13 to 14 bits
  4191. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  4192. getF32Constant(DAG, 0x3da235e3, dl));
  4193. SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
  4194. getF32Constant(DAG, 0x3e65b8f3, dl));
  4195. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  4196. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  4197. getF32Constant(DAG, 0x3f324b07, dl));
  4198. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  4199. TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
  4200. getF32Constant(DAG, 0x3f7ff8fd, dl));
  4201. } else { // LimitFloatPrecision <= 18
  4202. // For floating-point precision of 18:
  4203. //
  4204. // TwoToFractionalPartOfX =
  4205. // 0.999999982f +
  4206. // (0.693148872f +
  4207. // (0.240227044f +
  4208. // (0.554906021e-1f +
  4209. // (0.961591928e-2f +
  4210. // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
  4211. // error 2.47208000*10^(-7), which is better than 18 bits
  4212. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  4213. getF32Constant(DAG, 0x3924b03e, dl));
  4214. SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
  4215. getF32Constant(DAG, 0x3ab24b87, dl));
  4216. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  4217. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  4218. getF32Constant(DAG, 0x3c1d8c17, dl));
  4219. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  4220. SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
  4221. getF32Constant(DAG, 0x3d634a1d, dl));
  4222. SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
  4223. SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
  4224. getF32Constant(DAG, 0x3e75fe14, dl));
  4225. SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
  4226. SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
  4227. getF32Constant(DAG, 0x3f317234, dl));
  4228. SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
  4229. TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
  4230. getF32Constant(DAG, 0x3f800000, dl));
  4231. }
  4232. // Add the exponent into the result in integer domain.
  4233. SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX);
  4234. return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
  4235. DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX));
  4236. }
  4237. /// expandExp - Lower an exp intrinsic. Handles the special sequences for
  4238. /// limited-precision mode.
  4239. static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
  4240. const TargetLowering &TLI) {
  4241. if (Op.getValueType() == MVT::f32 &&
  4242. LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
  4243. // Put the exponent in the right bit position for later addition to the
  4244. // final result:
  4245. //
  4246. // #define LOG2OFe 1.4426950f
  4247. // t0 = Op * LOG2OFe
  4248. // TODO: What fast-math-flags should be set here?
  4249. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
  4250. getF32Constant(DAG, 0x3fb8aa3b, dl));
  4251. return getLimitedPrecisionExp2(t0, dl, DAG);
  4252. }
  4253. // No special expansion.
  4254. return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op);
  4255. }
  4256. /// expandLog - Lower a log intrinsic. Handles the special sequences for
  4257. /// limited-precision mode.
  4258. static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
  4259. const TargetLowering &TLI) {
  4260. // TODO: What fast-math-flags should be set on the floating-point nodes?
  4261. if (Op.getValueType() == MVT::f32 &&
  4262. LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
  4263. SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
  4264. // Scale the exponent by log(2) [0.69314718f].
  4265. SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
  4266. SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
  4267. getF32Constant(DAG, 0x3f317218, dl));
  4268. // Get the significand and build it into a floating-point number with
  4269. // exponent of 1.
  4270. SDValue X = GetSignificand(DAG, Op1, dl);
  4271. SDValue LogOfMantissa;
  4272. if (LimitFloatPrecision <= 6) {
  4273. // For floating-point precision of 6:
  4274. //
  4275. // LogofMantissa =
  4276. // -1.1609546f +
  4277. // (1.4034025f - 0.23903021f * x) * x;
  4278. //
  4279. // error 0.0034276066, which is better than 8 bits
  4280. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  4281. getF32Constant(DAG, 0xbe74c456, dl));
  4282. SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
  4283. getF32Constant(DAG, 0x3fb3a2b1, dl));
  4284. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  4285. LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
  4286. getF32Constant(DAG, 0x3f949a29, dl));
  4287. } else if (LimitFloatPrecision <= 12) {
  4288. // For floating-point precision of 12:
  4289. //
  4290. // LogOfMantissa =
  4291. // -1.7417939f +
  4292. // (2.8212026f +
  4293. // (-1.4699568f +
  4294. // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
  4295. //
  4296. // error 0.000061011436, which is 14 bits
  4297. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  4298. getF32Constant(DAG, 0xbd67b6d6, dl));
  4299. SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
  4300. getF32Constant(DAG, 0x3ee4f4b8, dl));
  4301. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  4302. SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
  4303. getF32Constant(DAG, 0x3fbc278b, dl));
  4304. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  4305. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  4306. getF32Constant(DAG, 0x40348e95, dl));
  4307. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  4308. LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
  4309. getF32Constant(DAG, 0x3fdef31a, dl));
  4310. } else { // LimitFloatPrecision <= 18
  4311. // For floating-point precision of 18:
  4312. //
  4313. // LogOfMantissa =
  4314. // -2.1072184f +
  4315. // (4.2372794f +
  4316. // (-3.7029485f +
  4317. // (2.2781945f +
  4318. // (-0.87823314f +
  4319. // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
  4320. //
  4321. // error 0.0000023660568, which is better than 18 bits
  4322. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  4323. getF32Constant(DAG, 0xbc91e5ac, dl));
  4324. SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
  4325. getF32Constant(DAG, 0x3e4350aa, dl));
  4326. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  4327. SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
  4328. getF32Constant(DAG, 0x3f60d3e3, dl));
  4329. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  4330. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  4331. getF32Constant(DAG, 0x4011cdf0, dl));
  4332. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  4333. SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
  4334. getF32Constant(DAG, 0x406cfd1c, dl));
  4335. SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
  4336. SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
  4337. getF32Constant(DAG, 0x408797cb, dl));
  4338. SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
  4339. LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
  4340. getF32Constant(DAG, 0x4006dcab, dl));
  4341. }
  4342. return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa);
  4343. }
  4344. // No special expansion.
  4345. return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op);
  4346. }
  4347. /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for
  4348. /// limited-precision mode.
  4349. static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
  4350. const TargetLowering &TLI) {
  4351. // TODO: What fast-math-flags should be set on the floating-point nodes?
  4352. if (Op.getValueType() == MVT::f32 &&
  4353. LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
  4354. SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
  4355. // Get the exponent.
  4356. SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
  4357. // Get the significand and build it into a floating-point number with
  4358. // exponent of 1.
  4359. SDValue X = GetSignificand(DAG, Op1, dl);
  4360. // Different possible minimax approximations of significand in
  4361. // floating-point for various degrees of accuracy over [1,2].
  4362. SDValue Log2ofMantissa;
  4363. if (LimitFloatPrecision <= 6) {
  4364. // For floating-point precision of 6:
  4365. //
  4366. // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
  4367. //
  4368. // error 0.0049451742, which is more than 7 bits
  4369. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  4370. getF32Constant(DAG, 0xbeb08fe0, dl));
  4371. SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
  4372. getF32Constant(DAG, 0x40019463, dl));
  4373. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  4374. Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
  4375. getF32Constant(DAG, 0x3fd6633d, dl));
  4376. } else if (LimitFloatPrecision <= 12) {
  4377. // For floating-point precision of 12:
  4378. //
  4379. // Log2ofMantissa =
  4380. // -2.51285454f +
  4381. // (4.07009056f +
  4382. // (-2.12067489f +
  4383. // (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
  4384. //
  4385. // error 0.0000876136000, which is better than 13 bits
  4386. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  4387. getF32Constant(DAG, 0xbda7262e, dl));
  4388. SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
  4389. getF32Constant(DAG, 0x3f25280b, dl));
  4390. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  4391. SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
  4392. getF32Constant(DAG, 0x4007b923, dl));
  4393. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  4394. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  4395. getF32Constant(DAG, 0x40823e2f, dl));
  4396. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  4397. Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
  4398. getF32Constant(DAG, 0x4020d29c, dl));
  4399. } else { // LimitFloatPrecision <= 18
  4400. // For floating-point precision of 18:
  4401. //
  4402. // Log2ofMantissa =
  4403. // -3.0400495f +
  4404. // (6.1129976f +
  4405. // (-5.3420409f +
  4406. // (3.2865683f +
  4407. // (-1.2669343f +
  4408. // (0.27515199f -
  4409. // 0.25691327e-1f * x) * x) * x) * x) * x) * x;
  4410. //
  4411. // error 0.0000018516, which is better than 18 bits
  4412. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  4413. getF32Constant(DAG, 0xbcd2769e, dl));
  4414. SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
  4415. getF32Constant(DAG, 0x3e8ce0b9, dl));
  4416. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  4417. SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
  4418. getF32Constant(DAG, 0x3fa22ae7, dl));
  4419. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  4420. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  4421. getF32Constant(DAG, 0x40525723, dl));
  4422. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  4423. SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
  4424. getF32Constant(DAG, 0x40aaf200, dl));
  4425. SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
  4426. SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
  4427. getF32Constant(DAG, 0x40c39dad, dl));
  4428. SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
  4429. Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
  4430. getF32Constant(DAG, 0x4042902c, dl));
  4431. }
  4432. return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa);
  4433. }
  4434. // No special expansion.
  4435. return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op);
  4436. }
  4437. /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for
  4438. /// limited-precision mode.
  4439. static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
  4440. const TargetLowering &TLI) {
  4441. // TODO: What fast-math-flags should be set on the floating-point nodes?
  4442. if (Op.getValueType() == MVT::f32 &&
  4443. LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
  4444. SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
  4445. // Scale the exponent by log10(2) [0.30102999f].
  4446. SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
  4447. SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
  4448. getF32Constant(DAG, 0x3e9a209a, dl));
  4449. // Get the significand and build it into a floating-point number with
  4450. // exponent of 1.
  4451. SDValue X = GetSignificand(DAG, Op1, dl);
  4452. SDValue Log10ofMantissa;
  4453. if (LimitFloatPrecision <= 6) {
  4454. // For floating-point precision of 6:
  4455. //
  4456. // Log10ofMantissa =
  4457. // -0.50419619f +
  4458. // (0.60948995f - 0.10380950f * x) * x;
  4459. //
  4460. // error 0.0014886165, which is 6 bits
  4461. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  4462. getF32Constant(DAG, 0xbdd49a13, dl));
  4463. SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
  4464. getF32Constant(DAG, 0x3f1c0789, dl));
  4465. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  4466. Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
  4467. getF32Constant(DAG, 0x3f011300, dl));
  4468. } else if (LimitFloatPrecision <= 12) {
  4469. // For floating-point precision of 12:
  4470. //
  4471. // Log10ofMantissa =
  4472. // -0.64831180f +
  4473. // (0.91751397f +
  4474. // (-0.31664806f + 0.47637168e-1f * x) * x) * x;
  4475. //
  4476. // error 0.00019228036, which is better than 12 bits
  4477. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  4478. getF32Constant(DAG, 0x3d431f31, dl));
  4479. SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
  4480. getF32Constant(DAG, 0x3ea21fb2, dl));
  4481. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  4482. SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
  4483. getF32Constant(DAG, 0x3f6ae232, dl));
  4484. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  4485. Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
  4486. getF32Constant(DAG, 0x3f25f7c3, dl));
  4487. } else { // LimitFloatPrecision <= 18
  4488. // For floating-point precision of 18:
  4489. //
  4490. // Log10ofMantissa =
  4491. // -0.84299375f +
  4492. // (1.5327582f +
  4493. // (-1.0688956f +
  4494. // (0.49102474f +
  4495. // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
  4496. //
  4497. // error 0.0000037995730, which is better than 18 bits
  4498. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  4499. getF32Constant(DAG, 0x3c5d51ce, dl));
  4500. SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
  4501. getF32Constant(DAG, 0x3e00685a, dl));
  4502. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  4503. SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
  4504. getF32Constant(DAG, 0x3efb6798, dl));
  4505. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  4506. SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
  4507. getF32Constant(DAG, 0x3f88d192, dl));
  4508. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  4509. SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
  4510. getF32Constant(DAG, 0x3fc4316c, dl));
  4511. SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
  4512. Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
  4513. getF32Constant(DAG, 0x3f57ce70, dl));
  4514. }
  4515. return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa);
  4516. }
  4517. // No special expansion.
  4518. return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op);
  4519. }
  4520. /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for
  4521. /// limited-precision mode.
  4522. static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
  4523. const TargetLowering &TLI) {
  4524. if (Op.getValueType() == MVT::f32 &&
  4525. LimitFloatPrecision > 0 && LimitFloatPrecision <= 18)
  4526. return getLimitedPrecisionExp2(Op, dl, DAG);
  4527. // No special expansion.
  4528. return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op);
  4529. }
  4530. /// visitPow - Lower a pow intrinsic. Handles the special sequences for
  4531. /// limited-precision mode with x == 10.0f.
  4532. static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS,
  4533. SelectionDAG &DAG, const TargetLowering &TLI) {
  4534. bool IsExp10 = false;
  4535. if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 &&
  4536. LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
  4537. if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) {
  4538. APFloat Ten(10.0f);
  4539. IsExp10 = LHSC->isExactlyValue(Ten);
  4540. }
  4541. }
  4542. // TODO: What fast-math-flags should be set on the FMUL node?
  4543. if (IsExp10) {
  4544. // Put the exponent in the right bit position for later addition to the
  4545. // final result:
  4546. //
  4547. // #define LOG2OF10 3.3219281f
  4548. // t0 = Op * LOG2OF10;
  4549. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS,
  4550. getF32Constant(DAG, 0x40549a78, dl));
  4551. return getLimitedPrecisionExp2(t0, dl, DAG);
  4552. }
  4553. // No special expansion.
  4554. return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS);
  4555. }
  4556. /// ExpandPowI - Expand a llvm.powi intrinsic.
  4557. static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS,
  4558. SelectionDAG &DAG) {
  4559. // If RHS is a constant, we can expand this out to a multiplication tree,
  4560. // otherwise we end up lowering to a call to __powidf2 (for example). When
  4561. // optimizing for size, we only want to do this if the expansion would produce
  4562. // a small number of multiplies, otherwise we do the full expansion.
  4563. if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
  4564. // Get the exponent as a positive value.
  4565. unsigned Val = RHSC->getSExtValue();
  4566. if ((int)Val < 0) Val = -Val;
  4567. // powi(x, 0) -> 1.0
  4568. if (Val == 0)
  4569. return DAG.getConstantFP(1.0, DL, LHS.getValueType());
  4570. const Function &F = DAG.getMachineFunction().getFunction();
  4571. if (!F.hasOptSize() ||
  4572. // If optimizing for size, don't insert too many multiplies.
  4573. // This inserts up to 5 multiplies.
  4574. countPopulation(Val) + Log2_32(Val) < 7) {
  4575. // We use the simple binary decomposition method to generate the multiply
  4576. // sequence. There are more optimal ways to do this (for example,
  4577. // powi(x,15) generates one more multiply than it should), but this has
  4578. // the benefit of being both really simple and much better than a libcall.
  4579. SDValue Res; // Logically starts equal to 1.0
  4580. SDValue CurSquare = LHS;
  4581. // TODO: Intrinsics should have fast-math-flags that propagate to these
  4582. // nodes.
  4583. while (Val) {
  4584. if (Val & 1) {
  4585. if (Res.getNode())
  4586. Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare);
  4587. else
  4588. Res = CurSquare; // 1.0*CurSquare.
  4589. }
  4590. CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(),
  4591. CurSquare, CurSquare);
  4592. Val >>= 1;
  4593. }
  4594. // If the original was negative, invert the result, producing 1/(x*x*x).
  4595. if (RHSC->getSExtValue() < 0)
  4596. Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(),
  4597. DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res);
  4598. return Res;
  4599. }
  4600. }
  4601. // Otherwise, expand to a libcall.
  4602. return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS);
  4603. }
  4604. // getUnderlyingArgReg - Find underlying register used for a truncated or
  4605. // bitcasted argument.
  4606. static unsigned getUnderlyingArgReg(const SDValue &N) {
  4607. switch (N.getOpcode()) {
  4608. case ISD::CopyFromReg:
  4609. return cast<RegisterSDNode>(N.getOperand(1))->getReg();
  4610. case ISD::BITCAST:
  4611. case ISD::AssertZext:
  4612. case ISD::AssertSext:
  4613. case ISD::TRUNCATE:
  4614. return getUnderlyingArgReg(N.getOperand(0));
  4615. default:
  4616. return 0;
  4617. }
  4618. }
  4619. /// If the DbgValueInst is a dbg_value of a function argument, create the
  4620. /// corresponding DBG_VALUE machine instruction for it now. At the end of
  4621. /// instruction selection, they will be inserted to the entry BB.
  4622. bool SelectionDAGBuilder::EmitFuncArgumentDbgValue(
  4623. const Value *V, DILocalVariable *Variable, DIExpression *Expr,
  4624. DILocation *DL, bool IsDbgDeclare, const SDValue &N) {
  4625. const Argument *Arg = dyn_cast<Argument>(V);
  4626. if (!Arg)
  4627. return false;
  4628. if (!IsDbgDeclare) {
  4629. // ArgDbgValues are hoisted to the beginning of the entry block. So we
  4630. // should only emit as ArgDbgValue if the dbg.value intrinsic is found in
  4631. // the entry block.
  4632. bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front();
  4633. if (!IsInEntryBlock)
  4634. return false;
  4635. // ArgDbgValues are hoisted to the beginning of the entry block. So we
  4636. // should only emit as ArgDbgValue if the dbg.value intrinsic describes a
  4637. // variable that also is a param.
  4638. //
  4639. // Although, if we are at the top of the entry block already, we can still
  4640. // emit using ArgDbgValue. This might catch some situations when the
  4641. // dbg.value refers to an argument that isn't used in the entry block, so
  4642. // any CopyToReg node would be optimized out and the only way to express
  4643. // this DBG_VALUE is by using the physical reg (or FI) as done in this
  4644. // method. ArgDbgValues are hoisted to the beginning of the entry block. So
  4645. // we should only emit as ArgDbgValue if the Variable is an argument to the
  4646. // current function, and the dbg.value intrinsic is found in the entry
  4647. // block.
  4648. bool VariableIsFunctionInputArg = Variable->isParameter() &&
  4649. !DL->getInlinedAt();
  4650. bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder;
  4651. if (!IsInPrologue && !VariableIsFunctionInputArg)
  4652. return false;
  4653. // Here we assume that a function argument on IR level only can be used to
  4654. // describe one input parameter on source level. If we for example have
  4655. // source code like this
  4656. //
  4657. // struct A { long x, y; };
  4658. // void foo(struct A a, long b) {
  4659. // ...
  4660. // b = a.x;
  4661. // ...
  4662. // }
  4663. //
  4664. // and IR like this
  4665. //
  4666. // define void @foo(i32 %a1, i32 %a2, i32 %b) {
  4667. // entry:
  4668. // call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment
  4669. // call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment
  4670. // call void @llvm.dbg.value(metadata i32 %b, "b",
  4671. // ...
  4672. // call void @llvm.dbg.value(metadata i32 %a1, "b"
  4673. // ...
  4674. //
  4675. // then the last dbg.value is describing a parameter "b" using a value that
  4676. // is an argument. But since we already has used %a1 to describe a parameter
  4677. // we should not handle that last dbg.value here (that would result in an
  4678. // incorrect hoisting of the DBG_VALUE to the function entry).
  4679. // Notice that we allow one dbg.value per IR level argument, to accomodate
  4680. // for the situation with fragments above.
  4681. if (VariableIsFunctionInputArg) {
  4682. unsigned ArgNo = Arg->getArgNo();
  4683. if (ArgNo >= FuncInfo.DescribedArgs.size())
  4684. FuncInfo.DescribedArgs.resize(ArgNo + 1, false);
  4685. else if (!IsInPrologue && FuncInfo.DescribedArgs.test(ArgNo))
  4686. return false;
  4687. FuncInfo.DescribedArgs.set(ArgNo);
  4688. }
  4689. }
  4690. MachineFunction &MF = DAG.getMachineFunction();
  4691. const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
  4692. bool IsIndirect = false;
  4693. Optional<MachineOperand> Op;
  4694. // Some arguments' frame index is recorded during argument lowering.
  4695. int FI = FuncInfo.getArgumentFrameIndex(Arg);
  4696. if (FI != std::numeric_limits<int>::max())
  4697. Op = MachineOperand::CreateFI(FI);
  4698. if (!Op && N.getNode()) {
  4699. unsigned Reg = getUnderlyingArgReg(N);
  4700. if (Reg && TargetRegisterInfo::isVirtualRegister(Reg)) {
  4701. MachineRegisterInfo &RegInfo = MF.getRegInfo();
  4702. unsigned PR = RegInfo.getLiveInPhysReg(Reg);
  4703. if (PR)
  4704. Reg = PR;
  4705. }
  4706. if (Reg) {
  4707. Op = MachineOperand::CreateReg(Reg, false);
  4708. IsIndirect = IsDbgDeclare;
  4709. }
  4710. }
  4711. if (!Op && N.getNode()) {
  4712. // Check if frame index is available.
  4713. SDValue LCandidate = peekThroughBitcasts(N);
  4714. if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(LCandidate.getNode()))
  4715. if (FrameIndexSDNode *FINode =
  4716. dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
  4717. Op = MachineOperand::CreateFI(FINode->getIndex());
  4718. }
  4719. if (!Op) {
  4720. // Check if ValueMap has reg number.
  4721. DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
  4722. if (VMI != FuncInfo.ValueMap.end()) {
  4723. const auto &TLI = DAG.getTargetLoweringInfo();
  4724. RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second,
  4725. V->getType(), getABIRegCopyCC(V));
  4726. if (RFV.occupiesMultipleRegs()) {
  4727. unsigned Offset = 0;
  4728. for (auto RegAndSize : RFV.getRegsAndSizes()) {
  4729. Op = MachineOperand::CreateReg(RegAndSize.first, false);
  4730. auto FragmentExpr = DIExpression::createFragmentExpression(
  4731. Expr, Offset, RegAndSize.second);
  4732. if (!FragmentExpr)
  4733. continue;
  4734. FuncInfo.ArgDbgValues.push_back(
  4735. BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsDbgDeclare,
  4736. Op->getReg(), Variable, *FragmentExpr));
  4737. Offset += RegAndSize.second;
  4738. }
  4739. return true;
  4740. }
  4741. Op = MachineOperand::CreateReg(VMI->second, false);
  4742. IsIndirect = IsDbgDeclare;
  4743. }
  4744. }
  4745. if (!Op)
  4746. return false;
  4747. assert(Variable->isValidLocationForIntrinsic(DL) &&
  4748. "Expected inlined-at fields to agree");
  4749. IsIndirect = (Op->isReg()) ? IsIndirect : true;
  4750. FuncInfo.ArgDbgValues.push_back(
  4751. BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsIndirect,
  4752. *Op, Variable, Expr));
  4753. return true;
  4754. }
  4755. /// Return the appropriate SDDbgValue based on N.
  4756. SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N,
  4757. DILocalVariable *Variable,
  4758. DIExpression *Expr,
  4759. const DebugLoc &dl,
  4760. unsigned DbgSDNodeOrder) {
  4761. if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) {
  4762. // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe
  4763. // stack slot locations.
  4764. //
  4765. // Consider "int x = 0; int *px = &x;". There are two kinds of interesting
  4766. // debug values here after optimization:
  4767. //
  4768. // dbg.value(i32* %px, !"int *px", !DIExpression()), and
  4769. // dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref))
  4770. //
  4771. // Both describe the direct values of their associated variables.
  4772. return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(),
  4773. /*IsIndirect*/ false, dl, DbgSDNodeOrder);
  4774. }
  4775. return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(),
  4776. /*IsIndirect*/ false, dl, DbgSDNodeOrder);
  4777. }
  4778. // VisualStudio defines setjmp as _setjmp
  4779. #if defined(_MSC_VER) && defined(setjmp) && \
  4780. !defined(setjmp_undefined_for_msvc)
  4781. # pragma push_macro("setjmp")
  4782. # undef setjmp
  4783. # define setjmp_undefined_for_msvc
  4784. #endif
  4785. static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) {
  4786. switch (Intrinsic) {
  4787. case Intrinsic::smul_fix:
  4788. return ISD::SMULFIX;
  4789. case Intrinsic::umul_fix:
  4790. return ISD::UMULFIX;
  4791. default:
  4792. llvm_unreachable("Unhandled fixed point intrinsic");
  4793. }
  4794. }
  4795. /// Lower the call to the specified intrinsic function. If we want to emit this
  4796. /// as a call to a named external function, return the name. Otherwise, lower it
  4797. /// and return null.
  4798. const char *
  4799. SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I, unsigned Intrinsic) {
  4800. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  4801. SDLoc sdl = getCurSDLoc();
  4802. DebugLoc dl = getCurDebugLoc();
  4803. SDValue Res;
  4804. switch (Intrinsic) {
  4805. default:
  4806. // By default, turn this into a target intrinsic node.
  4807. visitTargetIntrinsic(I, Intrinsic);
  4808. return nullptr;
  4809. case Intrinsic::vastart: visitVAStart(I); return nullptr;
  4810. case Intrinsic::vaend: visitVAEnd(I); return nullptr;
  4811. case Intrinsic::vacopy: visitVACopy(I); return nullptr;
  4812. case Intrinsic::returnaddress:
  4813. setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl,
  4814. TLI.getPointerTy(DAG.getDataLayout()),
  4815. getValue(I.getArgOperand(0))));
  4816. return nullptr;
  4817. case Intrinsic::addressofreturnaddress:
  4818. setValue(&I, DAG.getNode(ISD::ADDROFRETURNADDR, sdl,
  4819. TLI.getPointerTy(DAG.getDataLayout())));
  4820. return nullptr;
  4821. case Intrinsic::sponentry:
  4822. setValue(&I, DAG.getNode(ISD::SPONENTRY, sdl,
  4823. TLI.getPointerTy(DAG.getDataLayout())));
  4824. return nullptr;
  4825. case Intrinsic::frameaddress:
  4826. setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl,
  4827. TLI.getPointerTy(DAG.getDataLayout()),
  4828. getValue(I.getArgOperand(0))));
  4829. return nullptr;
  4830. case Intrinsic::read_register: {
  4831. Value *Reg = I.getArgOperand(0);
  4832. SDValue Chain = getRoot();
  4833. SDValue RegName =
  4834. DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
  4835. EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  4836. Res = DAG.getNode(ISD::READ_REGISTER, sdl,
  4837. DAG.getVTList(VT, MVT::Other), Chain, RegName);
  4838. setValue(&I, Res);
  4839. DAG.setRoot(Res.getValue(1));
  4840. return nullptr;
  4841. }
  4842. case Intrinsic::write_register: {
  4843. Value *Reg = I.getArgOperand(0);
  4844. Value *RegValue = I.getArgOperand(1);
  4845. SDValue Chain = getRoot();
  4846. SDValue RegName =
  4847. DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
  4848. DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain,
  4849. RegName, getValue(RegValue)));
  4850. return nullptr;
  4851. }
  4852. case Intrinsic::setjmp:
  4853. return &"_setjmp"[!TLI.usesUnderscoreSetJmp()];
  4854. case Intrinsic::longjmp:
  4855. return &"_longjmp"[!TLI.usesUnderscoreLongJmp()];
  4856. case Intrinsic::memcpy: {
  4857. const auto &MCI = cast<MemCpyInst>(I);
  4858. SDValue Op1 = getValue(I.getArgOperand(0));
  4859. SDValue Op2 = getValue(I.getArgOperand(1));
  4860. SDValue Op3 = getValue(I.getArgOperand(2));
  4861. // @llvm.memcpy defines 0 and 1 to both mean no alignment.
  4862. unsigned DstAlign = std::max<unsigned>(MCI.getDestAlignment(), 1);
  4863. unsigned SrcAlign = std::max<unsigned>(MCI.getSourceAlignment(), 1);
  4864. unsigned Align = MinAlign(DstAlign, SrcAlign);
  4865. bool isVol = MCI.isVolatile();
  4866. bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
  4867. // FIXME: Support passing different dest/src alignments to the memcpy DAG
  4868. // node.
  4869. SDValue MC = DAG.getMemcpy(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
  4870. false, isTC,
  4871. MachinePointerInfo(I.getArgOperand(0)),
  4872. MachinePointerInfo(I.getArgOperand(1)));
  4873. updateDAGForMaybeTailCall(MC);
  4874. return nullptr;
  4875. }
  4876. case Intrinsic::memset: {
  4877. const auto &MSI = cast<MemSetInst>(I);
  4878. SDValue Op1 = getValue(I.getArgOperand(0));
  4879. SDValue Op2 = getValue(I.getArgOperand(1));
  4880. SDValue Op3 = getValue(I.getArgOperand(2));
  4881. // @llvm.memset defines 0 and 1 to both mean no alignment.
  4882. unsigned Align = std::max<unsigned>(MSI.getDestAlignment(), 1);
  4883. bool isVol = MSI.isVolatile();
  4884. bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
  4885. SDValue MS = DAG.getMemset(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
  4886. isTC, MachinePointerInfo(I.getArgOperand(0)));
  4887. updateDAGForMaybeTailCall(MS);
  4888. return nullptr;
  4889. }
  4890. case Intrinsic::memmove: {
  4891. const auto &MMI = cast<MemMoveInst>(I);
  4892. SDValue Op1 = getValue(I.getArgOperand(0));
  4893. SDValue Op2 = getValue(I.getArgOperand(1));
  4894. SDValue Op3 = getValue(I.getArgOperand(2));
  4895. // @llvm.memmove defines 0 and 1 to both mean no alignment.
  4896. unsigned DstAlign = std::max<unsigned>(MMI.getDestAlignment(), 1);
  4897. unsigned SrcAlign = std::max<unsigned>(MMI.getSourceAlignment(), 1);
  4898. unsigned Align = MinAlign(DstAlign, SrcAlign);
  4899. bool isVol = MMI.isVolatile();
  4900. bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
  4901. // FIXME: Support passing different dest/src alignments to the memmove DAG
  4902. // node.
  4903. SDValue MM = DAG.getMemmove(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
  4904. isTC, MachinePointerInfo(I.getArgOperand(0)),
  4905. MachinePointerInfo(I.getArgOperand(1)));
  4906. updateDAGForMaybeTailCall(MM);
  4907. return nullptr;
  4908. }
  4909. case Intrinsic::memcpy_element_unordered_atomic: {
  4910. const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I);
  4911. SDValue Dst = getValue(MI.getRawDest());
  4912. SDValue Src = getValue(MI.getRawSource());
  4913. SDValue Length = getValue(MI.getLength());
  4914. unsigned DstAlign = MI.getDestAlignment();
  4915. unsigned SrcAlign = MI.getSourceAlignment();
  4916. Type *LengthTy = MI.getLength()->getType();
  4917. unsigned ElemSz = MI.getElementSizeInBytes();
  4918. bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
  4919. SDValue MC = DAG.getAtomicMemcpy(getRoot(), sdl, Dst, DstAlign, Src,
  4920. SrcAlign, Length, LengthTy, ElemSz, isTC,
  4921. MachinePointerInfo(MI.getRawDest()),
  4922. MachinePointerInfo(MI.getRawSource()));
  4923. updateDAGForMaybeTailCall(MC);
  4924. return nullptr;
  4925. }
  4926. case Intrinsic::memmove_element_unordered_atomic: {
  4927. auto &MI = cast<AtomicMemMoveInst>(I);
  4928. SDValue Dst = getValue(MI.getRawDest());
  4929. SDValue Src = getValue(MI.getRawSource());
  4930. SDValue Length = getValue(MI.getLength());
  4931. unsigned DstAlign = MI.getDestAlignment();
  4932. unsigned SrcAlign = MI.getSourceAlignment();
  4933. Type *LengthTy = MI.getLength()->getType();
  4934. unsigned ElemSz = MI.getElementSizeInBytes();
  4935. bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
  4936. SDValue MC = DAG.getAtomicMemmove(getRoot(), sdl, Dst, DstAlign, Src,
  4937. SrcAlign, Length, LengthTy, ElemSz, isTC,
  4938. MachinePointerInfo(MI.getRawDest()),
  4939. MachinePointerInfo(MI.getRawSource()));
  4940. updateDAGForMaybeTailCall(MC);
  4941. return nullptr;
  4942. }
  4943. case Intrinsic::memset_element_unordered_atomic: {
  4944. auto &MI = cast<AtomicMemSetInst>(I);
  4945. SDValue Dst = getValue(MI.getRawDest());
  4946. SDValue Val = getValue(MI.getValue());
  4947. SDValue Length = getValue(MI.getLength());
  4948. unsigned DstAlign = MI.getDestAlignment();
  4949. Type *LengthTy = MI.getLength()->getType();
  4950. unsigned ElemSz = MI.getElementSizeInBytes();
  4951. bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
  4952. SDValue MC = DAG.getAtomicMemset(getRoot(), sdl, Dst, DstAlign, Val, Length,
  4953. LengthTy, ElemSz, isTC,
  4954. MachinePointerInfo(MI.getRawDest()));
  4955. updateDAGForMaybeTailCall(MC);
  4956. return nullptr;
  4957. }
  4958. case Intrinsic::dbg_addr:
  4959. case Intrinsic::dbg_declare: {
  4960. const auto &DI = cast<DbgVariableIntrinsic>(I);
  4961. DILocalVariable *Variable = DI.getVariable();
  4962. DIExpression *Expression = DI.getExpression();
  4963. dropDanglingDebugInfo(Variable, Expression);
  4964. assert(Variable && "Missing variable");
  4965. // Check if address has undef value.
  4966. const Value *Address = DI.getVariableLocation();
  4967. if (!Address || isa<UndefValue>(Address) ||
  4968. (Address->use_empty() && !isa<Argument>(Address))) {
  4969. LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
  4970. return nullptr;
  4971. }
  4972. bool isParameter = Variable->isParameter() || isa<Argument>(Address);
  4973. // Check if this variable can be described by a frame index, typically
  4974. // either as a static alloca or a byval parameter.
  4975. int FI = std::numeric_limits<int>::max();
  4976. if (const auto *AI =
  4977. dyn_cast<AllocaInst>(Address->stripInBoundsConstantOffsets())) {
  4978. if (AI->isStaticAlloca()) {
  4979. auto I = FuncInfo.StaticAllocaMap.find(AI);
  4980. if (I != FuncInfo.StaticAllocaMap.end())
  4981. FI = I->second;
  4982. }
  4983. } else if (const auto *Arg = dyn_cast<Argument>(
  4984. Address->stripInBoundsConstantOffsets())) {
  4985. FI = FuncInfo.getArgumentFrameIndex(Arg);
  4986. }
  4987. // llvm.dbg.addr is control dependent and always generates indirect
  4988. // DBG_VALUE instructions. llvm.dbg.declare is handled as a frame index in
  4989. // the MachineFunction variable table.
  4990. if (FI != std::numeric_limits<int>::max()) {
  4991. if (Intrinsic == Intrinsic::dbg_addr) {
  4992. SDDbgValue *SDV = DAG.getFrameIndexDbgValue(
  4993. Variable, Expression, FI, /*IsIndirect*/ true, dl, SDNodeOrder);
  4994. DAG.AddDbgValue(SDV, getRoot().getNode(), isParameter);
  4995. }
  4996. return nullptr;
  4997. }
  4998. SDValue &N = NodeMap[Address];
  4999. if (!N.getNode() && isa<Argument>(Address))
  5000. // Check unused arguments map.
  5001. N = UnusedArgNodeMap[Address];
  5002. SDDbgValue *SDV;
  5003. if (N.getNode()) {
  5004. if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
  5005. Address = BCI->getOperand(0);
  5006. // Parameters are handled specially.
  5007. auto FINode = dyn_cast<FrameIndexSDNode>(N.getNode());
  5008. if (isParameter && FINode) {
  5009. // Byval parameter. We have a frame index at this point.
  5010. SDV =
  5011. DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(),
  5012. /*IsIndirect*/ true, dl, SDNodeOrder);
  5013. } else if (isa<Argument>(Address)) {
  5014. // Address is an argument, so try to emit its dbg value using
  5015. // virtual register info from the FuncInfo.ValueMap.
  5016. EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, N);
  5017. return nullptr;
  5018. } else {
  5019. SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(),
  5020. true, dl, SDNodeOrder);
  5021. }
  5022. DAG.AddDbgValue(SDV, N.getNode(), isParameter);
  5023. } else {
  5024. // If Address is an argument then try to emit its dbg value using
  5025. // virtual register info from the FuncInfo.ValueMap.
  5026. if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true,
  5027. N)) {
  5028. LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
  5029. }
  5030. }
  5031. return nullptr;
  5032. }
  5033. case Intrinsic::dbg_label: {
  5034. const DbgLabelInst &DI = cast<DbgLabelInst>(I);
  5035. DILabel *Label = DI.getLabel();
  5036. assert(Label && "Missing label");
  5037. SDDbgLabel *SDV;
  5038. SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder);
  5039. DAG.AddDbgLabel(SDV);
  5040. return nullptr;
  5041. }
  5042. case Intrinsic::dbg_value: {
  5043. const DbgValueInst &DI = cast<DbgValueInst>(I);
  5044. assert(DI.getVariable() && "Missing variable");
  5045. DILocalVariable *Variable = DI.getVariable();
  5046. DIExpression *Expression = DI.getExpression();
  5047. dropDanglingDebugInfo(Variable, Expression);
  5048. const Value *V = DI.getValue();
  5049. if (!V)
  5050. return nullptr;
  5051. if (handleDebugValue(V, Variable, Expression, dl, DI.getDebugLoc(),
  5052. SDNodeOrder))
  5053. return nullptr;
  5054. // TODO: Dangling debug info will eventually either be resolved or produce
  5055. // an Undef DBG_VALUE. However in the resolution case, a gap may appear
  5056. // between the original dbg.value location and its resolved DBG_VALUE, which
  5057. // we should ideally fill with an extra Undef DBG_VALUE.
  5058. DanglingDebugInfoMap[V].emplace_back(&DI, dl, SDNodeOrder);
  5059. return nullptr;
  5060. }
  5061. case Intrinsic::eh_typeid_for: {
  5062. // Find the type id for the given typeinfo.
  5063. GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0));
  5064. unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV);
  5065. Res = DAG.getConstant(TypeID, sdl, MVT::i32);
  5066. setValue(&I, Res);
  5067. return nullptr;
  5068. }
  5069. case Intrinsic::eh_return_i32:
  5070. case Intrinsic::eh_return_i64:
  5071. DAG.getMachineFunction().setCallsEHReturn(true);
  5072. DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl,
  5073. MVT::Other,
  5074. getControlRoot(),
  5075. getValue(I.getArgOperand(0)),
  5076. getValue(I.getArgOperand(1))));
  5077. return nullptr;
  5078. case Intrinsic::eh_unwind_init:
  5079. DAG.getMachineFunction().setCallsUnwindInit(true);
  5080. return nullptr;
  5081. case Intrinsic::eh_dwarf_cfa:
  5082. setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl,
  5083. TLI.getPointerTy(DAG.getDataLayout()),
  5084. getValue(I.getArgOperand(0))));
  5085. return nullptr;
  5086. case Intrinsic::eh_sjlj_callsite: {
  5087. MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
  5088. ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0));
  5089. assert(CI && "Non-constant call site value in eh.sjlj.callsite!");
  5090. assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!");
  5091. MMI.setCurrentCallSite(CI->getZExtValue());
  5092. return nullptr;
  5093. }
  5094. case Intrinsic::eh_sjlj_functioncontext: {
  5095. // Get and store the index of the function context.
  5096. MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
  5097. AllocaInst *FnCtx =
  5098. cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts());
  5099. int FI = FuncInfo.StaticAllocaMap[FnCtx];
  5100. MFI.setFunctionContextIndex(FI);
  5101. return nullptr;
  5102. }
  5103. case Intrinsic::eh_sjlj_setjmp: {
  5104. SDValue Ops[2];
  5105. Ops[0] = getRoot();
  5106. Ops[1] = getValue(I.getArgOperand(0));
  5107. SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl,
  5108. DAG.getVTList(MVT::i32, MVT::Other), Ops);
  5109. setValue(&I, Op.getValue(0));
  5110. DAG.setRoot(Op.getValue(1));
  5111. return nullptr;
  5112. }
  5113. case Intrinsic::eh_sjlj_longjmp:
  5114. DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other,
  5115. getRoot(), getValue(I.getArgOperand(0))));
  5116. return nullptr;
  5117. case Intrinsic::eh_sjlj_setup_dispatch:
  5118. DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other,
  5119. getRoot()));
  5120. return nullptr;
  5121. case Intrinsic::masked_gather:
  5122. visitMaskedGather(I);
  5123. return nullptr;
  5124. case Intrinsic::masked_load:
  5125. visitMaskedLoad(I);
  5126. return nullptr;
  5127. case Intrinsic::masked_scatter:
  5128. visitMaskedScatter(I);
  5129. return nullptr;
  5130. case Intrinsic::masked_store:
  5131. visitMaskedStore(I);
  5132. return nullptr;
  5133. case Intrinsic::masked_expandload:
  5134. visitMaskedLoad(I, true /* IsExpanding */);
  5135. return nullptr;
  5136. case Intrinsic::masked_compressstore:
  5137. visitMaskedStore(I, true /* IsCompressing */);
  5138. return nullptr;
  5139. case Intrinsic::x86_mmx_pslli_w:
  5140. case Intrinsic::x86_mmx_pslli_d:
  5141. case Intrinsic::x86_mmx_pslli_q:
  5142. case Intrinsic::x86_mmx_psrli_w:
  5143. case Intrinsic::x86_mmx_psrli_d:
  5144. case Intrinsic::x86_mmx_psrli_q:
  5145. case Intrinsic::x86_mmx_psrai_w:
  5146. case Intrinsic::x86_mmx_psrai_d: {
  5147. SDValue ShAmt = getValue(I.getArgOperand(1));
  5148. if (isa<ConstantSDNode>(ShAmt)) {
  5149. visitTargetIntrinsic(I, Intrinsic);
  5150. return nullptr;
  5151. }
  5152. unsigned NewIntrinsic = 0;
  5153. EVT ShAmtVT = MVT::v2i32;
  5154. switch (Intrinsic) {
  5155. case Intrinsic::x86_mmx_pslli_w:
  5156. NewIntrinsic = Intrinsic::x86_mmx_psll_w;
  5157. break;
  5158. case Intrinsic::x86_mmx_pslli_d:
  5159. NewIntrinsic = Intrinsic::x86_mmx_psll_d;
  5160. break;
  5161. case Intrinsic::x86_mmx_pslli_q:
  5162. NewIntrinsic = Intrinsic::x86_mmx_psll_q;
  5163. break;
  5164. case Intrinsic::x86_mmx_psrli_w:
  5165. NewIntrinsic = Intrinsic::x86_mmx_psrl_w;
  5166. break;
  5167. case Intrinsic::x86_mmx_psrli_d:
  5168. NewIntrinsic = Intrinsic::x86_mmx_psrl_d;
  5169. break;
  5170. case Intrinsic::x86_mmx_psrli_q:
  5171. NewIntrinsic = Intrinsic::x86_mmx_psrl_q;
  5172. break;
  5173. case Intrinsic::x86_mmx_psrai_w:
  5174. NewIntrinsic = Intrinsic::x86_mmx_psra_w;
  5175. break;
  5176. case Intrinsic::x86_mmx_psrai_d:
  5177. NewIntrinsic = Intrinsic::x86_mmx_psra_d;
  5178. break;
  5179. default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
  5180. }
  5181. // The vector shift intrinsics with scalars uses 32b shift amounts but
  5182. // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
  5183. // to be zero.
  5184. // We must do this early because v2i32 is not a legal type.
  5185. SDValue ShOps[2];
  5186. ShOps[0] = ShAmt;
  5187. ShOps[1] = DAG.getConstant(0, sdl, MVT::i32);
  5188. ShAmt = DAG.getBuildVector(ShAmtVT, sdl, ShOps);
  5189. EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  5190. ShAmt = DAG.getNode(ISD::BITCAST, sdl, DestVT, ShAmt);
  5191. Res = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, sdl, DestVT,
  5192. DAG.getConstant(NewIntrinsic, sdl, MVT::i32),
  5193. getValue(I.getArgOperand(0)), ShAmt);
  5194. setValue(&I, Res);
  5195. return nullptr;
  5196. }
  5197. case Intrinsic::powi:
  5198. setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)),
  5199. getValue(I.getArgOperand(1)), DAG));
  5200. return nullptr;
  5201. case Intrinsic::log:
  5202. setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
  5203. return nullptr;
  5204. case Intrinsic::log2:
  5205. setValue(&I, expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
  5206. return nullptr;
  5207. case Intrinsic::log10:
  5208. setValue(&I, expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
  5209. return nullptr;
  5210. case Intrinsic::exp:
  5211. setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
  5212. return nullptr;
  5213. case Intrinsic::exp2:
  5214. setValue(&I, expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
  5215. return nullptr;
  5216. case Intrinsic::pow:
  5217. setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)),
  5218. getValue(I.getArgOperand(1)), DAG, TLI));
  5219. return nullptr;
  5220. case Intrinsic::sqrt:
  5221. case Intrinsic::fabs:
  5222. case Intrinsic::sin:
  5223. case Intrinsic::cos:
  5224. case Intrinsic::floor:
  5225. case Intrinsic::ceil:
  5226. case Intrinsic::trunc:
  5227. case Intrinsic::rint:
  5228. case Intrinsic::nearbyint:
  5229. case Intrinsic::round:
  5230. case Intrinsic::canonicalize: {
  5231. unsigned Opcode;
  5232. switch (Intrinsic) {
  5233. default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
  5234. case Intrinsic::sqrt: Opcode = ISD::FSQRT; break;
  5235. case Intrinsic::fabs: Opcode = ISD::FABS; break;
  5236. case Intrinsic::sin: Opcode = ISD::FSIN; break;
  5237. case Intrinsic::cos: Opcode = ISD::FCOS; break;
  5238. case Intrinsic::floor: Opcode = ISD::FFLOOR; break;
  5239. case Intrinsic::ceil: Opcode = ISD::FCEIL; break;
  5240. case Intrinsic::trunc: Opcode = ISD::FTRUNC; break;
  5241. case Intrinsic::rint: Opcode = ISD::FRINT; break;
  5242. case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break;
  5243. case Intrinsic::round: Opcode = ISD::FROUND; break;
  5244. case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break;
  5245. }
  5246. setValue(&I, DAG.getNode(Opcode, sdl,
  5247. getValue(I.getArgOperand(0)).getValueType(),
  5248. getValue(I.getArgOperand(0))));
  5249. return nullptr;
  5250. }
  5251. case Intrinsic::minnum: {
  5252. auto VT = getValue(I.getArgOperand(0)).getValueType();
  5253. unsigned Opc =
  5254. I.hasNoNaNs() && TLI.isOperationLegalOrCustom(ISD::FMINIMUM, VT)
  5255. ? ISD::FMINIMUM
  5256. : ISD::FMINNUM;
  5257. setValue(&I, DAG.getNode(Opc, sdl, VT,
  5258. getValue(I.getArgOperand(0)),
  5259. getValue(I.getArgOperand(1))));
  5260. return nullptr;
  5261. }
  5262. case Intrinsic::maxnum: {
  5263. auto VT = getValue(I.getArgOperand(0)).getValueType();
  5264. unsigned Opc =
  5265. I.hasNoNaNs() && TLI.isOperationLegalOrCustom(ISD::FMAXIMUM, VT)
  5266. ? ISD::FMAXIMUM
  5267. : ISD::FMAXNUM;
  5268. setValue(&I, DAG.getNode(Opc, sdl, VT,
  5269. getValue(I.getArgOperand(0)),
  5270. getValue(I.getArgOperand(1))));
  5271. return nullptr;
  5272. }
  5273. case Intrinsic::minimum:
  5274. setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl,
  5275. getValue(I.getArgOperand(0)).getValueType(),
  5276. getValue(I.getArgOperand(0)),
  5277. getValue(I.getArgOperand(1))));
  5278. return nullptr;
  5279. case Intrinsic::maximum:
  5280. setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl,
  5281. getValue(I.getArgOperand(0)).getValueType(),
  5282. getValue(I.getArgOperand(0)),
  5283. getValue(I.getArgOperand(1))));
  5284. return nullptr;
  5285. case Intrinsic::copysign:
  5286. setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl,
  5287. getValue(I.getArgOperand(0)).getValueType(),
  5288. getValue(I.getArgOperand(0)),
  5289. getValue(I.getArgOperand(1))));
  5290. return nullptr;
  5291. case Intrinsic::fma:
  5292. setValue(&I, DAG.getNode(ISD::FMA, sdl,
  5293. getValue(I.getArgOperand(0)).getValueType(),
  5294. getValue(I.getArgOperand(0)),
  5295. getValue(I.getArgOperand(1)),
  5296. getValue(I.getArgOperand(2))));
  5297. return nullptr;
  5298. case Intrinsic::experimental_constrained_fadd:
  5299. case Intrinsic::experimental_constrained_fsub:
  5300. case Intrinsic::experimental_constrained_fmul:
  5301. case Intrinsic::experimental_constrained_fdiv:
  5302. case Intrinsic::experimental_constrained_frem:
  5303. case Intrinsic::experimental_constrained_fma:
  5304. case Intrinsic::experimental_constrained_sqrt:
  5305. case Intrinsic::experimental_constrained_pow:
  5306. case Intrinsic::experimental_constrained_powi:
  5307. case Intrinsic::experimental_constrained_sin:
  5308. case Intrinsic::experimental_constrained_cos:
  5309. case Intrinsic::experimental_constrained_exp:
  5310. case Intrinsic::experimental_constrained_exp2:
  5311. case Intrinsic::experimental_constrained_log:
  5312. case Intrinsic::experimental_constrained_log10:
  5313. case Intrinsic::experimental_constrained_log2:
  5314. case Intrinsic::experimental_constrained_rint:
  5315. case Intrinsic::experimental_constrained_nearbyint:
  5316. case Intrinsic::experimental_constrained_maxnum:
  5317. case Intrinsic::experimental_constrained_minnum:
  5318. case Intrinsic::experimental_constrained_ceil:
  5319. case Intrinsic::experimental_constrained_floor:
  5320. case Intrinsic::experimental_constrained_round:
  5321. case Intrinsic::experimental_constrained_trunc:
  5322. visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I));
  5323. return nullptr;
  5324. case Intrinsic::fmuladd: {
  5325. EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  5326. if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
  5327. TLI.isFMAFasterThanFMulAndFAdd(VT)) {
  5328. setValue(&I, DAG.getNode(ISD::FMA, sdl,
  5329. getValue(I.getArgOperand(0)).getValueType(),
  5330. getValue(I.getArgOperand(0)),
  5331. getValue(I.getArgOperand(1)),
  5332. getValue(I.getArgOperand(2))));
  5333. } else {
  5334. // TODO: Intrinsic calls should have fast-math-flags.
  5335. SDValue Mul = DAG.getNode(ISD::FMUL, sdl,
  5336. getValue(I.getArgOperand(0)).getValueType(),
  5337. getValue(I.getArgOperand(0)),
  5338. getValue(I.getArgOperand(1)));
  5339. SDValue Add = DAG.getNode(ISD::FADD, sdl,
  5340. getValue(I.getArgOperand(0)).getValueType(),
  5341. Mul,
  5342. getValue(I.getArgOperand(2)));
  5343. setValue(&I, Add);
  5344. }
  5345. return nullptr;
  5346. }
  5347. case Intrinsic::convert_to_fp16:
  5348. setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16,
  5349. DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16,
  5350. getValue(I.getArgOperand(0)),
  5351. DAG.getTargetConstant(0, sdl,
  5352. MVT::i32))));
  5353. return nullptr;
  5354. case Intrinsic::convert_from_fp16:
  5355. setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl,
  5356. TLI.getValueType(DAG.getDataLayout(), I.getType()),
  5357. DAG.getNode(ISD::BITCAST, sdl, MVT::f16,
  5358. getValue(I.getArgOperand(0)))));
  5359. return nullptr;
  5360. case Intrinsic::pcmarker: {
  5361. SDValue Tmp = getValue(I.getArgOperand(0));
  5362. DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp));
  5363. return nullptr;
  5364. }
  5365. case Intrinsic::readcyclecounter: {
  5366. SDValue Op = getRoot();
  5367. Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl,
  5368. DAG.getVTList(MVT::i64, MVT::Other), Op);
  5369. setValue(&I, Res);
  5370. DAG.setRoot(Res.getValue(1));
  5371. return nullptr;
  5372. }
  5373. case Intrinsic::bitreverse:
  5374. setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl,
  5375. getValue(I.getArgOperand(0)).getValueType(),
  5376. getValue(I.getArgOperand(0))));
  5377. return nullptr;
  5378. case Intrinsic::bswap:
  5379. setValue(&I, DAG.getNode(ISD::BSWAP, sdl,
  5380. getValue(I.getArgOperand(0)).getValueType(),
  5381. getValue(I.getArgOperand(0))));
  5382. return nullptr;
  5383. case Intrinsic::cttz: {
  5384. SDValue Arg = getValue(I.getArgOperand(0));
  5385. ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
  5386. EVT Ty = Arg.getValueType();
  5387. setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF,
  5388. sdl, Ty, Arg));
  5389. return nullptr;
  5390. }
  5391. case Intrinsic::ctlz: {
  5392. SDValue Arg = getValue(I.getArgOperand(0));
  5393. ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
  5394. EVT Ty = Arg.getValueType();
  5395. setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF,
  5396. sdl, Ty, Arg));
  5397. return nullptr;
  5398. }
  5399. case Intrinsic::ctpop: {
  5400. SDValue Arg = getValue(I.getArgOperand(0));
  5401. EVT Ty = Arg.getValueType();
  5402. setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg));
  5403. return nullptr;
  5404. }
  5405. case Intrinsic::fshl:
  5406. case Intrinsic::fshr: {
  5407. bool IsFSHL = Intrinsic == Intrinsic::fshl;
  5408. SDValue X = getValue(I.getArgOperand(0));
  5409. SDValue Y = getValue(I.getArgOperand(1));
  5410. SDValue Z = getValue(I.getArgOperand(2));
  5411. EVT VT = X.getValueType();
  5412. SDValue BitWidthC = DAG.getConstant(VT.getScalarSizeInBits(), sdl, VT);
  5413. SDValue Zero = DAG.getConstant(0, sdl, VT);
  5414. SDValue ShAmt = DAG.getNode(ISD::UREM, sdl, VT, Z, BitWidthC);
  5415. auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR;
  5416. if (TLI.isOperationLegalOrCustom(FunnelOpcode, VT)) {
  5417. setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z));
  5418. return nullptr;
  5419. }
  5420. // When X == Y, this is rotate. If the data type has a power-of-2 size, we
  5421. // avoid the select that is necessary in the general case to filter out
  5422. // the 0-shift possibility that leads to UB.
  5423. if (X == Y && isPowerOf2_32(VT.getScalarSizeInBits())) {
  5424. auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR;
  5425. if (TLI.isOperationLegalOrCustom(RotateOpcode, VT)) {
  5426. setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z));
  5427. return nullptr;
  5428. }
  5429. // Some targets only rotate one way. Try the opposite direction.
  5430. RotateOpcode = IsFSHL ? ISD::ROTR : ISD::ROTL;
  5431. if (TLI.isOperationLegalOrCustom(RotateOpcode, VT)) {
  5432. // Negate the shift amount because it is safe to ignore the high bits.
  5433. SDValue NegShAmt = DAG.getNode(ISD::SUB, sdl, VT, Zero, Z);
  5434. setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, NegShAmt));
  5435. return nullptr;
  5436. }
  5437. // fshl (rotl): (X << (Z % BW)) | (X >> ((0 - Z) % BW))
  5438. // fshr (rotr): (X << ((0 - Z) % BW)) | (X >> (Z % BW))
  5439. SDValue NegZ = DAG.getNode(ISD::SUB, sdl, VT, Zero, Z);
  5440. SDValue NShAmt = DAG.getNode(ISD::UREM, sdl, VT, NegZ, BitWidthC);
  5441. SDValue ShX = DAG.getNode(ISD::SHL, sdl, VT, X, IsFSHL ? ShAmt : NShAmt);
  5442. SDValue ShY = DAG.getNode(ISD::SRL, sdl, VT, X, IsFSHL ? NShAmt : ShAmt);
  5443. setValue(&I, DAG.getNode(ISD::OR, sdl, VT, ShX, ShY));
  5444. return nullptr;
  5445. }
  5446. // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW)))
  5447. // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW))
  5448. SDValue InvShAmt = DAG.getNode(ISD::SUB, sdl, VT, BitWidthC, ShAmt);
  5449. SDValue ShX = DAG.getNode(ISD::SHL, sdl, VT, X, IsFSHL ? ShAmt : InvShAmt);
  5450. SDValue ShY = DAG.getNode(ISD::SRL, sdl, VT, Y, IsFSHL ? InvShAmt : ShAmt);
  5451. SDValue Or = DAG.getNode(ISD::OR, sdl, VT, ShX, ShY);
  5452. // If (Z % BW == 0), then the opposite direction shift is shift-by-bitwidth,
  5453. // and that is undefined. We must compare and select to avoid UB.
  5454. EVT CCVT = MVT::i1;
  5455. if (VT.isVector())
  5456. CCVT = EVT::getVectorVT(*Context, CCVT, VT.getVectorNumElements());
  5457. // For fshl, 0-shift returns the 1st arg (X).
  5458. // For fshr, 0-shift returns the 2nd arg (Y).
  5459. SDValue IsZeroShift = DAG.getSetCC(sdl, CCVT, ShAmt, Zero, ISD::SETEQ);
  5460. setValue(&I, DAG.getSelect(sdl, VT, IsZeroShift, IsFSHL ? X : Y, Or));
  5461. return nullptr;
  5462. }
  5463. case Intrinsic::sadd_sat: {
  5464. SDValue Op1 = getValue(I.getArgOperand(0));
  5465. SDValue Op2 = getValue(I.getArgOperand(1));
  5466. setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2));
  5467. return nullptr;
  5468. }
  5469. case Intrinsic::uadd_sat: {
  5470. SDValue Op1 = getValue(I.getArgOperand(0));
  5471. SDValue Op2 = getValue(I.getArgOperand(1));
  5472. setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2));
  5473. return nullptr;
  5474. }
  5475. case Intrinsic::ssub_sat: {
  5476. SDValue Op1 = getValue(I.getArgOperand(0));
  5477. SDValue Op2 = getValue(I.getArgOperand(1));
  5478. setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2));
  5479. return nullptr;
  5480. }
  5481. case Intrinsic::usub_sat: {
  5482. SDValue Op1 = getValue(I.getArgOperand(0));
  5483. SDValue Op2 = getValue(I.getArgOperand(1));
  5484. setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2));
  5485. return nullptr;
  5486. }
  5487. case Intrinsic::smul_fix:
  5488. case Intrinsic::umul_fix: {
  5489. SDValue Op1 = getValue(I.getArgOperand(0));
  5490. SDValue Op2 = getValue(I.getArgOperand(1));
  5491. SDValue Op3 = getValue(I.getArgOperand(2));
  5492. setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl,
  5493. Op1.getValueType(), Op1, Op2, Op3));
  5494. return nullptr;
  5495. }
  5496. case Intrinsic::stacksave: {
  5497. SDValue Op = getRoot();
  5498. Res = DAG.getNode(
  5499. ISD::STACKSAVE, sdl,
  5500. DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Op);
  5501. setValue(&I, Res);
  5502. DAG.setRoot(Res.getValue(1));
  5503. return nullptr;
  5504. }
  5505. case Intrinsic::stackrestore:
  5506. Res = getValue(I.getArgOperand(0));
  5507. DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res));
  5508. return nullptr;
  5509. case Intrinsic::get_dynamic_area_offset: {
  5510. SDValue Op = getRoot();
  5511. EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
  5512. EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
  5513. // Result type for @llvm.get.dynamic.area.offset should match PtrTy for
  5514. // target.
  5515. if (PtrTy != ResTy)
  5516. report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset"
  5517. " intrinsic!");
  5518. Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy),
  5519. Op);
  5520. DAG.setRoot(Op);
  5521. setValue(&I, Res);
  5522. return nullptr;
  5523. }
  5524. case Intrinsic::stackguard: {
  5525. EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
  5526. MachineFunction &MF = DAG.getMachineFunction();
  5527. const Module &M = *MF.getFunction().getParent();
  5528. SDValue Chain = getRoot();
  5529. if (TLI.useLoadStackGuardNode()) {
  5530. Res = getLoadStackGuard(DAG, sdl, Chain);
  5531. } else {
  5532. const Value *Global = TLI.getSDagStackGuard(M);
  5533. unsigned Align = DL->getPrefTypeAlignment(Global->getType());
  5534. Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global),
  5535. MachinePointerInfo(Global, 0), Align,
  5536. MachineMemOperand::MOVolatile);
  5537. }
  5538. if (TLI.useStackGuardXorFP())
  5539. Res = TLI.emitStackGuardXorFP(DAG, Res, sdl);
  5540. DAG.setRoot(Chain);
  5541. setValue(&I, Res);
  5542. return nullptr;
  5543. }
  5544. case Intrinsic::stackprotector: {
  5545. // Emit code into the DAG to store the stack guard onto the stack.
  5546. MachineFunction &MF = DAG.getMachineFunction();
  5547. MachineFrameInfo &MFI = MF.getFrameInfo();
  5548. EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
  5549. SDValue Src, Chain = getRoot();
  5550. if (TLI.useLoadStackGuardNode())
  5551. Src = getLoadStackGuard(DAG, sdl, Chain);
  5552. else
  5553. Src = getValue(I.getArgOperand(0)); // The guard's value.
  5554. AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
  5555. int FI = FuncInfo.StaticAllocaMap[Slot];
  5556. MFI.setStackProtectorIndex(FI);
  5557. SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
  5558. // Store the stack protector onto the stack.
  5559. Res = DAG.getStore(Chain, sdl, Src, FIN, MachinePointerInfo::getFixedStack(
  5560. DAG.getMachineFunction(), FI),
  5561. /* Alignment = */ 0, MachineMemOperand::MOVolatile);
  5562. setValue(&I, Res);
  5563. DAG.setRoot(Res);
  5564. return nullptr;
  5565. }
  5566. case Intrinsic::objectsize: {
  5567. // If we don't know by now, we're never going to know.
  5568. ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(1));
  5569. assert(CI && "Non-constant type in __builtin_object_size?");
  5570. SDValue Arg = getValue(I.getCalledValue());
  5571. EVT Ty = Arg.getValueType();
  5572. if (CI->isZero())
  5573. Res = DAG.getConstant(-1ULL, sdl, Ty);
  5574. else
  5575. Res = DAG.getConstant(0, sdl, Ty);
  5576. setValue(&I, Res);
  5577. return nullptr;
  5578. }
  5579. case Intrinsic::is_constant:
  5580. // If this wasn't constant-folded away by now, then it's not a
  5581. // constant.
  5582. setValue(&I, DAG.getConstant(0, sdl, MVT::i1));
  5583. return nullptr;
  5584. case Intrinsic::annotation:
  5585. case Intrinsic::ptr_annotation:
  5586. case Intrinsic::launder_invariant_group:
  5587. case Intrinsic::strip_invariant_group:
  5588. // Drop the intrinsic, but forward the value
  5589. setValue(&I, getValue(I.getOperand(0)));
  5590. return nullptr;
  5591. case Intrinsic::assume:
  5592. case Intrinsic::var_annotation:
  5593. case Intrinsic::sideeffect:
  5594. // Discard annotate attributes, assumptions, and artificial side-effects.
  5595. return nullptr;
  5596. case Intrinsic::codeview_annotation: {
  5597. // Emit a label associated with this metadata.
  5598. MachineFunction &MF = DAG.getMachineFunction();
  5599. MCSymbol *Label =
  5600. MF.getMMI().getContext().createTempSymbol("annotation", true);
  5601. Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata();
  5602. MF.addCodeViewAnnotation(Label, cast<MDNode>(MD));
  5603. Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label);
  5604. DAG.setRoot(Res);
  5605. return nullptr;
  5606. }
  5607. case Intrinsic::init_trampoline: {
  5608. const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts());
  5609. SDValue Ops[6];
  5610. Ops[0] = getRoot();
  5611. Ops[1] = getValue(I.getArgOperand(0));
  5612. Ops[2] = getValue(I.getArgOperand(1));
  5613. Ops[3] = getValue(I.getArgOperand(2));
  5614. Ops[4] = DAG.getSrcValue(I.getArgOperand(0));
  5615. Ops[5] = DAG.getSrcValue(F);
  5616. Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops);
  5617. DAG.setRoot(Res);
  5618. return nullptr;
  5619. }
  5620. case Intrinsic::adjust_trampoline:
  5621. setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl,
  5622. TLI.getPointerTy(DAG.getDataLayout()),
  5623. getValue(I.getArgOperand(0))));
  5624. return nullptr;
  5625. case Intrinsic::gcroot: {
  5626. assert(DAG.getMachineFunction().getFunction().hasGC() &&
  5627. "only valid in functions with gc specified, enforced by Verifier");
  5628. assert(GFI && "implied by previous");
  5629. const Value *Alloca = I.getArgOperand(0)->stripPointerCasts();
  5630. const Constant *TypeMap = cast<Constant>(I.getArgOperand(1));
  5631. FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
  5632. GFI->addStackRoot(FI->getIndex(), TypeMap);
  5633. return nullptr;
  5634. }
  5635. case Intrinsic::gcread:
  5636. case Intrinsic::gcwrite:
  5637. llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
  5638. case Intrinsic::flt_rounds:
  5639. setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, sdl, MVT::i32));
  5640. return nullptr;
  5641. case Intrinsic::expect:
  5642. // Just replace __builtin_expect(exp, c) with EXP.
  5643. setValue(&I, getValue(I.getArgOperand(0)));
  5644. return nullptr;
  5645. case Intrinsic::debugtrap:
  5646. case Intrinsic::trap: {
  5647. StringRef TrapFuncName =
  5648. I.getAttributes()
  5649. .getAttribute(AttributeList::FunctionIndex, "trap-func-name")
  5650. .getValueAsString();
  5651. if (TrapFuncName.empty()) {
  5652. ISD::NodeType Op = (Intrinsic == Intrinsic::trap) ?
  5653. ISD::TRAP : ISD::DEBUGTRAP;
  5654. DAG.setRoot(DAG.getNode(Op, sdl,MVT::Other, getRoot()));
  5655. return nullptr;
  5656. }
  5657. TargetLowering::ArgListTy Args;
  5658. TargetLowering::CallLoweringInfo CLI(DAG);
  5659. CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee(
  5660. CallingConv::C, I.getType(),
  5661. DAG.getExternalSymbol(TrapFuncName.data(),
  5662. TLI.getPointerTy(DAG.getDataLayout())),
  5663. std::move(Args));
  5664. std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
  5665. DAG.setRoot(Result.second);
  5666. return nullptr;
  5667. }
  5668. case Intrinsic::uadd_with_overflow:
  5669. case Intrinsic::sadd_with_overflow:
  5670. case Intrinsic::usub_with_overflow:
  5671. case Intrinsic::ssub_with_overflow:
  5672. case Intrinsic::umul_with_overflow:
  5673. case Intrinsic::smul_with_overflow: {
  5674. ISD::NodeType Op;
  5675. switch (Intrinsic) {
  5676. default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
  5677. case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break;
  5678. case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break;
  5679. case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break;
  5680. case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break;
  5681. case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break;
  5682. case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break;
  5683. }
  5684. SDValue Op1 = getValue(I.getArgOperand(0));
  5685. SDValue Op2 = getValue(I.getArgOperand(1));
  5686. EVT ResultVT = Op1.getValueType();
  5687. EVT OverflowVT = MVT::i1;
  5688. if (ResultVT.isVector())
  5689. OverflowVT = EVT::getVectorVT(
  5690. *Context, OverflowVT, ResultVT.getVectorNumElements());
  5691. SDVTList VTs = DAG.getVTList(ResultVT, OverflowVT);
  5692. setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2));
  5693. return nullptr;
  5694. }
  5695. case Intrinsic::prefetch: {
  5696. SDValue Ops[5];
  5697. unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
  5698. auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore;
  5699. Ops[0] = DAG.getRoot();
  5700. Ops[1] = getValue(I.getArgOperand(0));
  5701. Ops[2] = getValue(I.getArgOperand(1));
  5702. Ops[3] = getValue(I.getArgOperand(2));
  5703. Ops[4] = getValue(I.getArgOperand(3));
  5704. SDValue Result = DAG.getMemIntrinsicNode(ISD::PREFETCH, sdl,
  5705. DAG.getVTList(MVT::Other), Ops,
  5706. EVT::getIntegerVT(*Context, 8),
  5707. MachinePointerInfo(I.getArgOperand(0)),
  5708. 0, /* align */
  5709. Flags);
  5710. // Chain the prefetch in parallell with any pending loads, to stay out of
  5711. // the way of later optimizations.
  5712. PendingLoads.push_back(Result);
  5713. Result = getRoot();
  5714. DAG.setRoot(Result);
  5715. return nullptr;
  5716. }
  5717. case Intrinsic::lifetime_start:
  5718. case Intrinsic::lifetime_end: {
  5719. bool IsStart = (Intrinsic == Intrinsic::lifetime_start);
  5720. // Stack coloring is not enabled in O0, discard region information.
  5721. if (TM.getOptLevel() == CodeGenOpt::None)
  5722. return nullptr;
  5723. const int64_t ObjectSize =
  5724. cast<ConstantInt>(I.getArgOperand(0))->getSExtValue();
  5725. Value *const ObjectPtr = I.getArgOperand(1);
  5726. SmallVector<const Value *, 4> Allocas;
  5727. GetUnderlyingObjects(ObjectPtr, Allocas, *DL);
  5728. for (SmallVectorImpl<const Value*>::iterator Object = Allocas.begin(),
  5729. E = Allocas.end(); Object != E; ++Object) {
  5730. const AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(*Object);
  5731. // Could not find an Alloca.
  5732. if (!LifetimeObject)
  5733. continue;
  5734. // First check that the Alloca is static, otherwise it won't have a
  5735. // valid frame index.
  5736. auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject);
  5737. if (SI == FuncInfo.StaticAllocaMap.end())
  5738. return nullptr;
  5739. const int FrameIndex = SI->second;
  5740. int64_t Offset;
  5741. if (GetPointerBaseWithConstantOffset(
  5742. ObjectPtr, Offset, DAG.getDataLayout()) != LifetimeObject)
  5743. Offset = -1; // Cannot determine offset from alloca to lifetime object.
  5744. Res = DAG.getLifetimeNode(IsStart, sdl, getRoot(), FrameIndex, ObjectSize,
  5745. Offset);
  5746. DAG.setRoot(Res);
  5747. }
  5748. return nullptr;
  5749. }
  5750. case Intrinsic::invariant_start:
  5751. // Discard region information.
  5752. setValue(&I, DAG.getUNDEF(TLI.getPointerTy(DAG.getDataLayout())));
  5753. return nullptr;
  5754. case Intrinsic::invariant_end:
  5755. // Discard region information.
  5756. return nullptr;
  5757. case Intrinsic::clear_cache:
  5758. return TLI.getClearCacheBuiltinName();
  5759. case Intrinsic::donothing:
  5760. // ignore
  5761. return nullptr;
  5762. case Intrinsic::experimental_stackmap:
  5763. visitStackmap(I);
  5764. return nullptr;
  5765. case Intrinsic::experimental_patchpoint_void:
  5766. case Intrinsic::experimental_patchpoint_i64:
  5767. visitPatchpoint(&I);
  5768. return nullptr;
  5769. case Intrinsic::experimental_gc_statepoint:
  5770. LowerStatepoint(ImmutableStatepoint(&I));
  5771. return nullptr;
  5772. case Intrinsic::experimental_gc_result:
  5773. visitGCResult(cast<GCResultInst>(I));
  5774. return nullptr;
  5775. case Intrinsic::experimental_gc_relocate:
  5776. visitGCRelocate(cast<GCRelocateInst>(I));
  5777. return nullptr;
  5778. case Intrinsic::instrprof_increment:
  5779. llvm_unreachable("instrprof failed to lower an increment");
  5780. case Intrinsic::instrprof_value_profile:
  5781. llvm_unreachable("instrprof failed to lower a value profiling call");
  5782. case Intrinsic::localescape: {
  5783. MachineFunction &MF = DAG.getMachineFunction();
  5784. const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
  5785. // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission
  5786. // is the same on all targets.
  5787. for (unsigned Idx = 0, E = I.getNumArgOperands(); Idx < E; ++Idx) {
  5788. Value *Arg = I.getArgOperand(Idx)->stripPointerCasts();
  5789. if (isa<ConstantPointerNull>(Arg))
  5790. continue; // Skip null pointers. They represent a hole in index space.
  5791. AllocaInst *Slot = cast<AllocaInst>(Arg);
  5792. assert(FuncInfo.StaticAllocaMap.count(Slot) &&
  5793. "can only escape static allocas");
  5794. int FI = FuncInfo.StaticAllocaMap[Slot];
  5795. MCSymbol *FrameAllocSym =
  5796. MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
  5797. GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx);
  5798. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl,
  5799. TII->get(TargetOpcode::LOCAL_ESCAPE))
  5800. .addSym(FrameAllocSym)
  5801. .addFrameIndex(FI);
  5802. }
  5803. return nullptr;
  5804. }
  5805. case Intrinsic::localrecover: {
  5806. // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx)
  5807. MachineFunction &MF = DAG.getMachineFunction();
  5808. MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout(), 0);
  5809. // Get the symbol that defines the frame offset.
  5810. auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts());
  5811. auto *Idx = cast<ConstantInt>(I.getArgOperand(2));
  5812. unsigned IdxVal =
  5813. unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max()));
  5814. MCSymbol *FrameAllocSym =
  5815. MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
  5816. GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal);
  5817. // Create a MCSymbol for the label to avoid any target lowering
  5818. // that would make this PC relative.
  5819. SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT);
  5820. SDValue OffsetVal =
  5821. DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym);
  5822. // Add the offset to the FP.
  5823. Value *FP = I.getArgOperand(1);
  5824. SDValue FPVal = getValue(FP);
  5825. SDValue Add = DAG.getNode(ISD::ADD, sdl, PtrVT, FPVal, OffsetVal);
  5826. setValue(&I, Add);
  5827. return nullptr;
  5828. }
  5829. case Intrinsic::eh_exceptionpointer:
  5830. case Intrinsic::eh_exceptioncode: {
  5831. // Get the exception pointer vreg, copy from it, and resize it to fit.
  5832. const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0));
  5833. MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
  5834. const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT);
  5835. unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC);
  5836. SDValue N =
  5837. DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), VReg, PtrVT);
  5838. if (Intrinsic == Intrinsic::eh_exceptioncode)
  5839. N = DAG.getZExtOrTrunc(N, getCurSDLoc(), MVT::i32);
  5840. setValue(&I, N);
  5841. return nullptr;
  5842. }
  5843. case Intrinsic::xray_customevent: {
  5844. // Here we want to make sure that the intrinsic behaves as if it has a
  5845. // specific calling convention, and only for x86_64.
  5846. // FIXME: Support other platforms later.
  5847. const auto &Triple = DAG.getTarget().getTargetTriple();
  5848. if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux())
  5849. return nullptr;
  5850. SDLoc DL = getCurSDLoc();
  5851. SmallVector<SDValue, 8> Ops;
  5852. // We want to say that we always want the arguments in registers.
  5853. SDValue LogEntryVal = getValue(I.getArgOperand(0));
  5854. SDValue StrSizeVal = getValue(I.getArgOperand(1));
  5855. SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
  5856. SDValue Chain = getRoot();
  5857. Ops.push_back(LogEntryVal);
  5858. Ops.push_back(StrSizeVal);
  5859. Ops.push_back(Chain);
  5860. // We need to enforce the calling convention for the callsite, so that
  5861. // argument ordering is enforced correctly, and that register allocation can
  5862. // see that some registers may be assumed clobbered and have to preserve
  5863. // them across calls to the intrinsic.
  5864. MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL,
  5865. DL, NodeTys, Ops);
  5866. SDValue patchableNode = SDValue(MN, 0);
  5867. DAG.setRoot(patchableNode);
  5868. setValue(&I, patchableNode);
  5869. return nullptr;
  5870. }
  5871. case Intrinsic::xray_typedevent: {
  5872. // Here we want to make sure that the intrinsic behaves as if it has a
  5873. // specific calling convention, and only for x86_64.
  5874. // FIXME: Support other platforms later.
  5875. const auto &Triple = DAG.getTarget().getTargetTriple();
  5876. if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux())
  5877. return nullptr;
  5878. SDLoc DL = getCurSDLoc();
  5879. SmallVector<SDValue, 8> Ops;
  5880. // We want to say that we always want the arguments in registers.
  5881. // It's unclear to me how manipulating the selection DAG here forces callers
  5882. // to provide arguments in registers instead of on the stack.
  5883. SDValue LogTypeId = getValue(I.getArgOperand(0));
  5884. SDValue LogEntryVal = getValue(I.getArgOperand(1));
  5885. SDValue StrSizeVal = getValue(I.getArgOperand(2));
  5886. SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
  5887. SDValue Chain = getRoot();
  5888. Ops.push_back(LogTypeId);
  5889. Ops.push_back(LogEntryVal);
  5890. Ops.push_back(StrSizeVal);
  5891. Ops.push_back(Chain);
  5892. // We need to enforce the calling convention for the callsite, so that
  5893. // argument ordering is enforced correctly, and that register allocation can
  5894. // see that some registers may be assumed clobbered and have to preserve
  5895. // them across calls to the intrinsic.
  5896. MachineSDNode *MN = DAG.getMachineNode(
  5897. TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, DL, NodeTys, Ops);
  5898. SDValue patchableNode = SDValue(MN, 0);
  5899. DAG.setRoot(patchableNode);
  5900. setValue(&I, patchableNode);
  5901. return nullptr;
  5902. }
  5903. case Intrinsic::experimental_deoptimize:
  5904. LowerDeoptimizeCall(&I);
  5905. return nullptr;
  5906. case Intrinsic::experimental_vector_reduce_fadd:
  5907. case Intrinsic::experimental_vector_reduce_fmul:
  5908. case Intrinsic::experimental_vector_reduce_add:
  5909. case Intrinsic::experimental_vector_reduce_mul:
  5910. case Intrinsic::experimental_vector_reduce_and:
  5911. case Intrinsic::experimental_vector_reduce_or:
  5912. case Intrinsic::experimental_vector_reduce_xor:
  5913. case Intrinsic::experimental_vector_reduce_smax:
  5914. case Intrinsic::experimental_vector_reduce_smin:
  5915. case Intrinsic::experimental_vector_reduce_umax:
  5916. case Intrinsic::experimental_vector_reduce_umin:
  5917. case Intrinsic::experimental_vector_reduce_fmax:
  5918. case Intrinsic::experimental_vector_reduce_fmin:
  5919. visitVectorReduce(I, Intrinsic);
  5920. return nullptr;
  5921. case Intrinsic::icall_branch_funnel: {
  5922. SmallVector<SDValue, 16> Ops;
  5923. Ops.push_back(DAG.getRoot());
  5924. Ops.push_back(getValue(I.getArgOperand(0)));
  5925. int64_t Offset;
  5926. auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
  5927. I.getArgOperand(1), Offset, DAG.getDataLayout()));
  5928. if (!Base)
  5929. report_fatal_error(
  5930. "llvm.icall.branch.funnel operand must be a GlobalValue");
  5931. Ops.push_back(DAG.getTargetGlobalAddress(Base, getCurSDLoc(), MVT::i64, 0));
  5932. struct BranchFunnelTarget {
  5933. int64_t Offset;
  5934. SDValue Target;
  5935. };
  5936. SmallVector<BranchFunnelTarget, 8> Targets;
  5937. for (unsigned Op = 1, N = I.getNumArgOperands(); Op != N; Op += 2) {
  5938. auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
  5939. I.getArgOperand(Op), Offset, DAG.getDataLayout()));
  5940. if (ElemBase != Base)
  5941. report_fatal_error("all llvm.icall.branch.funnel operands must refer "
  5942. "to the same GlobalValue");
  5943. SDValue Val = getValue(I.getArgOperand(Op + 1));
  5944. auto *GA = dyn_cast<GlobalAddressSDNode>(Val);
  5945. if (!GA)
  5946. report_fatal_error(
  5947. "llvm.icall.branch.funnel operand must be a GlobalValue");
  5948. Targets.push_back({Offset, DAG.getTargetGlobalAddress(
  5949. GA->getGlobal(), getCurSDLoc(),
  5950. Val.getValueType(), GA->getOffset())});
  5951. }
  5952. llvm::sort(Targets,
  5953. [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) {
  5954. return T1.Offset < T2.Offset;
  5955. });
  5956. for (auto &T : Targets) {
  5957. Ops.push_back(DAG.getTargetConstant(T.Offset, getCurSDLoc(), MVT::i32));
  5958. Ops.push_back(T.Target);
  5959. }
  5960. SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL,
  5961. getCurSDLoc(), MVT::Other, Ops),
  5962. 0);
  5963. DAG.setRoot(N);
  5964. setValue(&I, N);
  5965. HasTailCall = true;
  5966. return nullptr;
  5967. }
  5968. case Intrinsic::wasm_landingpad_index:
  5969. // Information this intrinsic contained has been transferred to
  5970. // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely
  5971. // delete it now.
  5972. return nullptr;
  5973. }
  5974. }
  5975. void SelectionDAGBuilder::visitConstrainedFPIntrinsic(
  5976. const ConstrainedFPIntrinsic &FPI) {
  5977. SDLoc sdl = getCurSDLoc();
  5978. unsigned Opcode;
  5979. switch (FPI.getIntrinsicID()) {
  5980. default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
  5981. case Intrinsic::experimental_constrained_fadd:
  5982. Opcode = ISD::STRICT_FADD;
  5983. break;
  5984. case Intrinsic::experimental_constrained_fsub:
  5985. Opcode = ISD::STRICT_FSUB;
  5986. break;
  5987. case Intrinsic::experimental_constrained_fmul:
  5988. Opcode = ISD::STRICT_FMUL;
  5989. break;
  5990. case Intrinsic::experimental_constrained_fdiv:
  5991. Opcode = ISD::STRICT_FDIV;
  5992. break;
  5993. case Intrinsic::experimental_constrained_frem:
  5994. Opcode = ISD::STRICT_FREM;
  5995. break;
  5996. case Intrinsic::experimental_constrained_fma:
  5997. Opcode = ISD::STRICT_FMA;
  5998. break;
  5999. case Intrinsic::experimental_constrained_sqrt:
  6000. Opcode = ISD::STRICT_FSQRT;
  6001. break;
  6002. case Intrinsic::experimental_constrained_pow:
  6003. Opcode = ISD::STRICT_FPOW;
  6004. break;
  6005. case Intrinsic::experimental_constrained_powi:
  6006. Opcode = ISD::STRICT_FPOWI;
  6007. break;
  6008. case Intrinsic::experimental_constrained_sin:
  6009. Opcode = ISD::STRICT_FSIN;
  6010. break;
  6011. case Intrinsic::experimental_constrained_cos:
  6012. Opcode = ISD::STRICT_FCOS;
  6013. break;
  6014. case Intrinsic::experimental_constrained_exp:
  6015. Opcode = ISD::STRICT_FEXP;
  6016. break;
  6017. case Intrinsic::experimental_constrained_exp2:
  6018. Opcode = ISD::STRICT_FEXP2;
  6019. break;
  6020. case Intrinsic::experimental_constrained_log:
  6021. Opcode = ISD::STRICT_FLOG;
  6022. break;
  6023. case Intrinsic::experimental_constrained_log10:
  6024. Opcode = ISD::STRICT_FLOG10;
  6025. break;
  6026. case Intrinsic::experimental_constrained_log2:
  6027. Opcode = ISD::STRICT_FLOG2;
  6028. break;
  6029. case Intrinsic::experimental_constrained_rint:
  6030. Opcode = ISD::STRICT_FRINT;
  6031. break;
  6032. case Intrinsic::experimental_constrained_nearbyint:
  6033. Opcode = ISD::STRICT_FNEARBYINT;
  6034. break;
  6035. case Intrinsic::experimental_constrained_maxnum:
  6036. Opcode = ISD::STRICT_FMAXNUM;
  6037. break;
  6038. case Intrinsic::experimental_constrained_minnum:
  6039. Opcode = ISD::STRICT_FMINNUM;
  6040. break;
  6041. case Intrinsic::experimental_constrained_ceil:
  6042. Opcode = ISD::STRICT_FCEIL;
  6043. break;
  6044. case Intrinsic::experimental_constrained_floor:
  6045. Opcode = ISD::STRICT_FFLOOR;
  6046. break;
  6047. case Intrinsic::experimental_constrained_round:
  6048. Opcode = ISD::STRICT_FROUND;
  6049. break;
  6050. case Intrinsic::experimental_constrained_trunc:
  6051. Opcode = ISD::STRICT_FTRUNC;
  6052. break;
  6053. }
  6054. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  6055. SDValue Chain = getRoot();
  6056. SmallVector<EVT, 4> ValueVTs;
  6057. ComputeValueVTs(TLI, DAG.getDataLayout(), FPI.getType(), ValueVTs);
  6058. ValueVTs.push_back(MVT::Other); // Out chain
  6059. SDVTList VTs = DAG.getVTList(ValueVTs);
  6060. SDValue Result;
  6061. if (FPI.isUnaryOp())
  6062. Result = DAG.getNode(Opcode, sdl, VTs,
  6063. { Chain, getValue(FPI.getArgOperand(0)) });
  6064. else if (FPI.isTernaryOp())
  6065. Result = DAG.getNode(Opcode, sdl, VTs,
  6066. { Chain, getValue(FPI.getArgOperand(0)),
  6067. getValue(FPI.getArgOperand(1)),
  6068. getValue(FPI.getArgOperand(2)) });
  6069. else
  6070. Result = DAG.getNode(Opcode, sdl, VTs,
  6071. { Chain, getValue(FPI.getArgOperand(0)),
  6072. getValue(FPI.getArgOperand(1)) });
  6073. assert(Result.getNode()->getNumValues() == 2);
  6074. SDValue OutChain = Result.getValue(1);
  6075. DAG.setRoot(OutChain);
  6076. SDValue FPResult = Result.getValue(0);
  6077. setValue(&FPI, FPResult);
  6078. }
  6079. std::pair<SDValue, SDValue>
  6080. SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI,
  6081. const BasicBlock *EHPadBB) {
  6082. MachineFunction &MF = DAG.getMachineFunction();
  6083. MachineModuleInfo &MMI = MF.getMMI();
  6084. MCSymbol *BeginLabel = nullptr;
  6085. if (EHPadBB) {
  6086. // Insert a label before the invoke call to mark the try range. This can be
  6087. // used to detect deletion of the invoke via the MachineModuleInfo.
  6088. BeginLabel = MMI.getContext().createTempSymbol();
  6089. // For SjLj, keep track of which landing pads go with which invokes
  6090. // so as to maintain the ordering of pads in the LSDA.
  6091. unsigned CallSiteIndex = MMI.getCurrentCallSite();
  6092. if (CallSiteIndex) {
  6093. MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex);
  6094. LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex);
  6095. // Now that the call site is handled, stop tracking it.
  6096. MMI.setCurrentCallSite(0);
  6097. }
  6098. // Both PendingLoads and PendingExports must be flushed here;
  6099. // this call might not return.
  6100. (void)getRoot();
  6101. DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getControlRoot(), BeginLabel));
  6102. CLI.setChain(getRoot());
  6103. }
  6104. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  6105. std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
  6106. assert((CLI.IsTailCall || Result.second.getNode()) &&
  6107. "Non-null chain expected with non-tail call!");
  6108. assert((Result.second.getNode() || !Result.first.getNode()) &&
  6109. "Null value expected with tail call!");
  6110. if (!Result.second.getNode()) {
  6111. // As a special case, a null chain means that a tail call has been emitted
  6112. // and the DAG root is already updated.
  6113. HasTailCall = true;
  6114. // Since there's no actual continuation from this block, nothing can be
  6115. // relying on us setting vregs for them.
  6116. PendingExports.clear();
  6117. } else {
  6118. DAG.setRoot(Result.second);
  6119. }
  6120. if (EHPadBB) {
  6121. // Insert a label at the end of the invoke call to mark the try range. This
  6122. // can be used to detect deletion of the invoke via the MachineModuleInfo.
  6123. MCSymbol *EndLabel = MMI.getContext().createTempSymbol();
  6124. DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getRoot(), EndLabel));
  6125. // Inform MachineModuleInfo of range.
  6126. auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
  6127. // There is a platform (e.g. wasm) that uses funclet style IR but does not
  6128. // actually use outlined funclets and their LSDA info style.
  6129. if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) {
  6130. assert(CLI.CS);
  6131. WinEHFuncInfo *EHInfo = DAG.getMachineFunction().getWinEHFuncInfo();
  6132. EHInfo->addIPToStateRange(cast<InvokeInst>(CLI.CS.getInstruction()),
  6133. BeginLabel, EndLabel);
  6134. } else if (!isScopedEHPersonality(Pers)) {
  6135. MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel);
  6136. }
  6137. }
  6138. return Result;
  6139. }
  6140. void SelectionDAGBuilder::LowerCallTo(ImmutableCallSite CS, SDValue Callee,
  6141. bool isTailCall,
  6142. const BasicBlock *EHPadBB) {
  6143. auto &DL = DAG.getDataLayout();
  6144. FunctionType *FTy = CS.getFunctionType();
  6145. Type *RetTy = CS.getType();
  6146. TargetLowering::ArgListTy Args;
  6147. Args.reserve(CS.arg_size());
  6148. const Value *SwiftErrorVal = nullptr;
  6149. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  6150. // We can't tail call inside a function with a swifterror argument. Lowering
  6151. // does not support this yet. It would have to move into the swifterror
  6152. // register before the call.
  6153. auto *Caller = CS.getInstruction()->getParent()->getParent();
  6154. if (TLI.supportSwiftError() &&
  6155. Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError))
  6156. isTailCall = false;
  6157. for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
  6158. i != e; ++i) {
  6159. TargetLowering::ArgListEntry Entry;
  6160. const Value *V = *i;
  6161. // Skip empty types
  6162. if (V->getType()->isEmptyTy())
  6163. continue;
  6164. SDValue ArgNode = getValue(V);
  6165. Entry.Node = ArgNode; Entry.Ty = V->getType();
  6166. Entry.setAttributes(&CS, i - CS.arg_begin());
  6167. // Use swifterror virtual register as input to the call.
  6168. if (Entry.IsSwiftError && TLI.supportSwiftError()) {
  6169. SwiftErrorVal = V;
  6170. // We find the virtual register for the actual swifterror argument.
  6171. // Instead of using the Value, we use the virtual register instead.
  6172. Entry.Node = DAG.getRegister(FuncInfo
  6173. .getOrCreateSwiftErrorVRegUseAt(
  6174. CS.getInstruction(), FuncInfo.MBB, V)
  6175. .first,
  6176. EVT(TLI.getPointerTy(DL)));
  6177. }
  6178. Args.push_back(Entry);
  6179. // If we have an explicit sret argument that is an Instruction, (i.e., it
  6180. // might point to function-local memory), we can't meaningfully tail-call.
  6181. if (Entry.IsSRet && isa<Instruction>(V))
  6182. isTailCall = false;
  6183. }
  6184. // Check if target-independent constraints permit a tail call here.
  6185. // Target-dependent constraints are checked within TLI->LowerCallTo.
  6186. if (isTailCall && !isInTailCallPosition(CS, DAG.getTarget()))
  6187. isTailCall = false;
  6188. // Disable tail calls if there is an swifterror argument. Targets have not
  6189. // been updated to support tail calls.
  6190. if (TLI.supportSwiftError() && SwiftErrorVal)
  6191. isTailCall = false;
  6192. TargetLowering::CallLoweringInfo CLI(DAG);
  6193. CLI.setDebugLoc(getCurSDLoc())
  6194. .setChain(getRoot())
  6195. .setCallee(RetTy, FTy, Callee, std::move(Args), CS)
  6196. .setTailCall(isTailCall)
  6197. .setConvergent(CS.isConvergent());
  6198. std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
  6199. if (Result.first.getNode()) {
  6200. const Instruction *Inst = CS.getInstruction();
  6201. Result.first = lowerRangeToAssertZExt(DAG, *Inst, Result.first);
  6202. setValue(Inst, Result.first);
  6203. }
  6204. // The last element of CLI.InVals has the SDValue for swifterror return.
  6205. // Here we copy it to a virtual register and update SwiftErrorMap for
  6206. // book-keeping.
  6207. if (SwiftErrorVal && TLI.supportSwiftError()) {
  6208. // Get the last element of InVals.
  6209. SDValue Src = CLI.InVals.back();
  6210. unsigned VReg; bool CreatedVReg;
  6211. std::tie(VReg, CreatedVReg) =
  6212. FuncInfo.getOrCreateSwiftErrorVRegDefAt(CS.getInstruction());
  6213. SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src);
  6214. // We update the virtual register for the actual swifterror argument.
  6215. if (CreatedVReg)
  6216. FuncInfo.setCurrentSwiftErrorVReg(FuncInfo.MBB, SwiftErrorVal, VReg);
  6217. DAG.setRoot(CopyNode);
  6218. }
  6219. }
  6220. static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT,
  6221. SelectionDAGBuilder &Builder) {
  6222. // Check to see if this load can be trivially constant folded, e.g. if the
  6223. // input is from a string literal.
  6224. if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) {
  6225. // Cast pointer to the type we really want to load.
  6226. Type *LoadTy =
  6227. Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits());
  6228. if (LoadVT.isVector())
  6229. LoadTy = VectorType::get(LoadTy, LoadVT.getVectorNumElements());
  6230. LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput),
  6231. PointerType::getUnqual(LoadTy));
  6232. if (const Constant *LoadCst = ConstantFoldLoadFromConstPtr(
  6233. const_cast<Constant *>(LoadInput), LoadTy, *Builder.DL))
  6234. return Builder.getValue(LoadCst);
  6235. }
  6236. // Otherwise, we have to emit the load. If the pointer is to unfoldable but
  6237. // still constant memory, the input chain can be the entry node.
  6238. SDValue Root;
  6239. bool ConstantMemory = false;
  6240. // Do not serialize (non-volatile) loads of constant memory with anything.
  6241. if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) {
  6242. Root = Builder.DAG.getEntryNode();
  6243. ConstantMemory = true;
  6244. } else {
  6245. // Do not serialize non-volatile loads against each other.
  6246. Root = Builder.DAG.getRoot();
  6247. }
  6248. SDValue Ptr = Builder.getValue(PtrVal);
  6249. SDValue LoadVal = Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root,
  6250. Ptr, MachinePointerInfo(PtrVal),
  6251. /* Alignment = */ 1);
  6252. if (!ConstantMemory)
  6253. Builder.PendingLoads.push_back(LoadVal.getValue(1));
  6254. return LoadVal;
  6255. }
  6256. /// Record the value for an instruction that produces an integer result,
  6257. /// converting the type where necessary.
  6258. void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I,
  6259. SDValue Value,
  6260. bool IsSigned) {
  6261. EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  6262. I.getType(), true);
  6263. if (IsSigned)
  6264. Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT);
  6265. else
  6266. Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT);
  6267. setValue(&I, Value);
  6268. }
  6269. /// See if we can lower a memcmp call into an optimized form. If so, return
  6270. /// true and lower it. Otherwise return false, and it will be lowered like a
  6271. /// normal call.
  6272. /// The caller already checked that \p I calls the appropriate LibFunc with a
  6273. /// correct prototype.
  6274. bool SelectionDAGBuilder::visitMemCmpCall(const CallInst &I) {
  6275. const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1);
  6276. const Value *Size = I.getArgOperand(2);
  6277. const ConstantInt *CSize = dyn_cast<ConstantInt>(Size);
  6278. if (CSize && CSize->getZExtValue() == 0) {
  6279. EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  6280. I.getType(), true);
  6281. setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT));
  6282. return true;
  6283. }
  6284. const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
  6285. std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp(
  6286. DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS),
  6287. getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS));
  6288. if (Res.first.getNode()) {
  6289. processIntegerCallValue(I, Res.first, true);
  6290. PendingLoads.push_back(Res.second);
  6291. return true;
  6292. }
  6293. // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS) != 0
  6294. // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS) != 0
  6295. if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I))
  6296. return false;
  6297. // If the target has a fast compare for the given size, it will return a
  6298. // preferred load type for that size. Require that the load VT is legal and
  6299. // that the target supports unaligned loads of that type. Otherwise, return
  6300. // INVALID.
  6301. auto hasFastLoadsAndCompare = [&](unsigned NumBits) {
  6302. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  6303. MVT LVT = TLI.hasFastEqualityCompare(NumBits);
  6304. if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) {
  6305. // TODO: Handle 5 byte compare as 4-byte + 1 byte.
  6306. // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
  6307. // TODO: Check alignment of src and dest ptrs.
  6308. unsigned DstAS = LHS->getType()->getPointerAddressSpace();
  6309. unsigned SrcAS = RHS->getType()->getPointerAddressSpace();
  6310. if (!TLI.isTypeLegal(LVT) ||
  6311. !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) ||
  6312. !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS))
  6313. LVT = MVT::INVALID_SIMPLE_VALUE_TYPE;
  6314. }
  6315. return LVT;
  6316. };
  6317. // This turns into unaligned loads. We only do this if the target natively
  6318. // supports the MVT we'll be loading or if it is small enough (<= 4) that
  6319. // we'll only produce a small number of byte loads.
  6320. MVT LoadVT;
  6321. unsigned NumBitsToCompare = CSize->getZExtValue() * 8;
  6322. switch (NumBitsToCompare) {
  6323. default:
  6324. return false;
  6325. case 16:
  6326. LoadVT = MVT::i16;
  6327. break;
  6328. case 32:
  6329. LoadVT = MVT::i32;
  6330. break;
  6331. case 64:
  6332. case 128:
  6333. case 256:
  6334. LoadVT = hasFastLoadsAndCompare(NumBitsToCompare);
  6335. break;
  6336. }
  6337. if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE)
  6338. return false;
  6339. SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this);
  6340. SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this);
  6341. // Bitcast to a wide integer type if the loads are vectors.
  6342. if (LoadVT.isVector()) {
  6343. EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits());
  6344. LoadL = DAG.getBitcast(CmpVT, LoadL);
  6345. LoadR = DAG.getBitcast(CmpVT, LoadR);
  6346. }
  6347. SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE);
  6348. processIntegerCallValue(I, Cmp, false);
  6349. return true;
  6350. }
  6351. /// See if we can lower a memchr call into an optimized form. If so, return
  6352. /// true and lower it. Otherwise return false, and it will be lowered like a
  6353. /// normal call.
  6354. /// The caller already checked that \p I calls the appropriate LibFunc with a
  6355. /// correct prototype.
  6356. bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) {
  6357. const Value *Src = I.getArgOperand(0);
  6358. const Value *Char = I.getArgOperand(1);
  6359. const Value *Length = I.getArgOperand(2);
  6360. const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
  6361. std::pair<SDValue, SDValue> Res =
  6362. TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(),
  6363. getValue(Src), getValue(Char), getValue(Length),
  6364. MachinePointerInfo(Src));
  6365. if (Res.first.getNode()) {
  6366. setValue(&I, Res.first);
  6367. PendingLoads.push_back(Res.second);
  6368. return true;
  6369. }
  6370. return false;
  6371. }
  6372. /// See if we can lower a mempcpy call into an optimized form. If so, return
  6373. /// true and lower it. Otherwise return false, and it will be lowered like a
  6374. /// normal call.
  6375. /// The caller already checked that \p I calls the appropriate LibFunc with a
  6376. /// correct prototype.
  6377. bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) {
  6378. SDValue Dst = getValue(I.getArgOperand(0));
  6379. SDValue Src = getValue(I.getArgOperand(1));
  6380. SDValue Size = getValue(I.getArgOperand(2));
  6381. unsigned DstAlign = DAG.InferPtrAlignment(Dst);
  6382. unsigned SrcAlign = DAG.InferPtrAlignment(Src);
  6383. unsigned Align = std::min(DstAlign, SrcAlign);
  6384. if (Align == 0) // Alignment of one or both could not be inferred.
  6385. Align = 1; // 0 and 1 both specify no alignment, but 0 is reserved.
  6386. bool isVol = false;
  6387. SDLoc sdl = getCurSDLoc();
  6388. // In the mempcpy context we need to pass in a false value for isTailCall
  6389. // because the return pointer needs to be adjusted by the size of
  6390. // the copied memory.
  6391. SDValue MC = DAG.getMemcpy(getRoot(), sdl, Dst, Src, Size, Align, isVol,
  6392. false, /*isTailCall=*/false,
  6393. MachinePointerInfo(I.getArgOperand(0)),
  6394. MachinePointerInfo(I.getArgOperand(1)));
  6395. assert(MC.getNode() != nullptr &&
  6396. "** memcpy should not be lowered as TailCall in mempcpy context **");
  6397. DAG.setRoot(MC);
  6398. // Check if Size needs to be truncated or extended.
  6399. Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType());
  6400. // Adjust return pointer to point just past the last dst byte.
  6401. SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(),
  6402. Dst, Size);
  6403. setValue(&I, DstPlusSize);
  6404. return true;
  6405. }
  6406. /// See if we can lower a strcpy call into an optimized form. If so, return
  6407. /// true and lower it, otherwise return false and it will be lowered like a
  6408. /// normal call.
  6409. /// The caller already checked that \p I calls the appropriate LibFunc with a
  6410. /// correct prototype.
  6411. bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) {
  6412. const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
  6413. const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
  6414. std::pair<SDValue, SDValue> Res =
  6415. TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(),
  6416. getValue(Arg0), getValue(Arg1),
  6417. MachinePointerInfo(Arg0),
  6418. MachinePointerInfo(Arg1), isStpcpy);
  6419. if (Res.first.getNode()) {
  6420. setValue(&I, Res.first);
  6421. DAG.setRoot(Res.second);
  6422. return true;
  6423. }
  6424. return false;
  6425. }
  6426. /// See if we can lower a strcmp call into an optimized form. If so, return
  6427. /// true and lower it, otherwise return false and it will be lowered like a
  6428. /// normal call.
  6429. /// The caller already checked that \p I calls the appropriate LibFunc with a
  6430. /// correct prototype.
  6431. bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) {
  6432. const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
  6433. const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
  6434. std::pair<SDValue, SDValue> Res =
  6435. TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(),
  6436. getValue(Arg0), getValue(Arg1),
  6437. MachinePointerInfo(Arg0),
  6438. MachinePointerInfo(Arg1));
  6439. if (Res.first.getNode()) {
  6440. processIntegerCallValue(I, Res.first, true);
  6441. PendingLoads.push_back(Res.second);
  6442. return true;
  6443. }
  6444. return false;
  6445. }
  6446. /// See if we can lower a strlen call into an optimized form. If so, return
  6447. /// true and lower it, otherwise return false and it will be lowered like a
  6448. /// normal call.
  6449. /// The caller already checked that \p I calls the appropriate LibFunc with a
  6450. /// correct prototype.
  6451. bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) {
  6452. const Value *Arg0 = I.getArgOperand(0);
  6453. const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
  6454. std::pair<SDValue, SDValue> Res =
  6455. TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(),
  6456. getValue(Arg0), MachinePointerInfo(Arg0));
  6457. if (Res.first.getNode()) {
  6458. processIntegerCallValue(I, Res.first, false);
  6459. PendingLoads.push_back(Res.second);
  6460. return true;
  6461. }
  6462. return false;
  6463. }
  6464. /// See if we can lower a strnlen call into an optimized form. If so, return
  6465. /// true and lower it, otherwise return false and it will be lowered like a
  6466. /// normal call.
  6467. /// The caller already checked that \p I calls the appropriate LibFunc with a
  6468. /// correct prototype.
  6469. bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) {
  6470. const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
  6471. const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
  6472. std::pair<SDValue, SDValue> Res =
  6473. TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(),
  6474. getValue(Arg0), getValue(Arg1),
  6475. MachinePointerInfo(Arg0));
  6476. if (Res.first.getNode()) {
  6477. processIntegerCallValue(I, Res.first, false);
  6478. PendingLoads.push_back(Res.second);
  6479. return true;
  6480. }
  6481. return false;
  6482. }
  6483. /// See if we can lower a unary floating-point operation into an SDNode with
  6484. /// the specified Opcode. If so, return true and lower it, otherwise return
  6485. /// false and it will be lowered like a normal call.
  6486. /// The caller already checked that \p I calls the appropriate LibFunc with a
  6487. /// correct prototype.
  6488. bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I,
  6489. unsigned Opcode) {
  6490. // We already checked this call's prototype; verify it doesn't modify errno.
  6491. if (!I.onlyReadsMemory())
  6492. return false;
  6493. SDValue Tmp = getValue(I.getArgOperand(0));
  6494. setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp));
  6495. return true;
  6496. }
  6497. /// See if we can lower a binary floating-point operation into an SDNode with
  6498. /// the specified Opcode. If so, return true and lower it. Otherwise return
  6499. /// false, and it will be lowered like a normal call.
  6500. /// The caller already checked that \p I calls the appropriate LibFunc with a
  6501. /// correct prototype.
  6502. bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I,
  6503. unsigned Opcode) {
  6504. // We already checked this call's prototype; verify it doesn't modify errno.
  6505. if (!I.onlyReadsMemory())
  6506. return false;
  6507. SDValue Tmp0 = getValue(I.getArgOperand(0));
  6508. SDValue Tmp1 = getValue(I.getArgOperand(1));
  6509. EVT VT = Tmp0.getValueType();
  6510. setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1));
  6511. return true;
  6512. }
  6513. void SelectionDAGBuilder::visitCall(const CallInst &I) {
  6514. // Handle inline assembly differently.
  6515. if (isa<InlineAsm>(I.getCalledValue())) {
  6516. visitInlineAsm(&I);
  6517. return;
  6518. }
  6519. const char *RenameFn = nullptr;
  6520. if (Function *F = I.getCalledFunction()) {
  6521. if (F->isDeclaration()) {
  6522. // Is this an LLVM intrinsic or a target-specific intrinsic?
  6523. unsigned IID = F->getIntrinsicID();
  6524. if (!IID)
  6525. if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo())
  6526. IID = II->getIntrinsicID(F);
  6527. if (IID) {
  6528. RenameFn = visitIntrinsicCall(I, IID);
  6529. if (!RenameFn)
  6530. return;
  6531. }
  6532. }
  6533. // Check for well-known libc/libm calls. If the function is internal, it
  6534. // can't be a library call. Don't do the check if marked as nobuiltin for
  6535. // some reason or the call site requires strict floating point semantics.
  6536. LibFunc Func;
  6537. if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() &&
  6538. F->hasName() && LibInfo->getLibFunc(*F, Func) &&
  6539. LibInfo->hasOptimizedCodeGen(Func)) {
  6540. switch (Func) {
  6541. default: break;
  6542. case LibFunc_copysign:
  6543. case LibFunc_copysignf:
  6544. case LibFunc_copysignl:
  6545. // We already checked this call's prototype; verify it doesn't modify
  6546. // errno.
  6547. if (I.onlyReadsMemory()) {
  6548. SDValue LHS = getValue(I.getArgOperand(0));
  6549. SDValue RHS = getValue(I.getArgOperand(1));
  6550. setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(),
  6551. LHS.getValueType(), LHS, RHS));
  6552. return;
  6553. }
  6554. break;
  6555. case LibFunc_fabs:
  6556. case LibFunc_fabsf:
  6557. case LibFunc_fabsl:
  6558. if (visitUnaryFloatCall(I, ISD::FABS))
  6559. return;
  6560. break;
  6561. case LibFunc_fmin:
  6562. case LibFunc_fminf:
  6563. case LibFunc_fminl:
  6564. if (visitBinaryFloatCall(I, ISD::FMINNUM))
  6565. return;
  6566. break;
  6567. case LibFunc_fmax:
  6568. case LibFunc_fmaxf:
  6569. case LibFunc_fmaxl:
  6570. if (visitBinaryFloatCall(I, ISD::FMAXNUM))
  6571. return;
  6572. break;
  6573. case LibFunc_sin:
  6574. case LibFunc_sinf:
  6575. case LibFunc_sinl:
  6576. if (visitUnaryFloatCall(I, ISD::FSIN))
  6577. return;
  6578. break;
  6579. case LibFunc_cos:
  6580. case LibFunc_cosf:
  6581. case LibFunc_cosl:
  6582. if (visitUnaryFloatCall(I, ISD::FCOS))
  6583. return;
  6584. break;
  6585. case LibFunc_sqrt:
  6586. case LibFunc_sqrtf:
  6587. case LibFunc_sqrtl:
  6588. case LibFunc_sqrt_finite:
  6589. case LibFunc_sqrtf_finite:
  6590. case LibFunc_sqrtl_finite:
  6591. if (visitUnaryFloatCall(I, ISD::FSQRT))
  6592. return;
  6593. break;
  6594. case LibFunc_floor:
  6595. case LibFunc_floorf:
  6596. case LibFunc_floorl:
  6597. if (visitUnaryFloatCall(I, ISD::FFLOOR))
  6598. return;
  6599. break;
  6600. case LibFunc_nearbyint:
  6601. case LibFunc_nearbyintf:
  6602. case LibFunc_nearbyintl:
  6603. if (visitUnaryFloatCall(I, ISD::FNEARBYINT))
  6604. return;
  6605. break;
  6606. case LibFunc_ceil:
  6607. case LibFunc_ceilf:
  6608. case LibFunc_ceill:
  6609. if (visitUnaryFloatCall(I, ISD::FCEIL))
  6610. return;
  6611. break;
  6612. case LibFunc_rint:
  6613. case LibFunc_rintf:
  6614. case LibFunc_rintl:
  6615. if (visitUnaryFloatCall(I, ISD::FRINT))
  6616. return;
  6617. break;
  6618. case LibFunc_round:
  6619. case LibFunc_roundf:
  6620. case LibFunc_roundl:
  6621. if (visitUnaryFloatCall(I, ISD::FROUND))
  6622. return;
  6623. break;
  6624. case LibFunc_trunc:
  6625. case LibFunc_truncf:
  6626. case LibFunc_truncl:
  6627. if (visitUnaryFloatCall(I, ISD::FTRUNC))
  6628. return;
  6629. break;
  6630. case LibFunc_log2:
  6631. case LibFunc_log2f:
  6632. case LibFunc_log2l:
  6633. if (visitUnaryFloatCall(I, ISD::FLOG2))
  6634. return;
  6635. break;
  6636. case LibFunc_exp2:
  6637. case LibFunc_exp2f:
  6638. case LibFunc_exp2l:
  6639. if (visitUnaryFloatCall(I, ISD::FEXP2))
  6640. return;
  6641. break;
  6642. case LibFunc_memcmp:
  6643. if (visitMemCmpCall(I))
  6644. return;
  6645. break;
  6646. case LibFunc_mempcpy:
  6647. if (visitMemPCpyCall(I))
  6648. return;
  6649. break;
  6650. case LibFunc_memchr:
  6651. if (visitMemChrCall(I))
  6652. return;
  6653. break;
  6654. case LibFunc_strcpy:
  6655. if (visitStrCpyCall(I, false))
  6656. return;
  6657. break;
  6658. case LibFunc_stpcpy:
  6659. if (visitStrCpyCall(I, true))
  6660. return;
  6661. break;
  6662. case LibFunc_strcmp:
  6663. if (visitStrCmpCall(I))
  6664. return;
  6665. break;
  6666. case LibFunc_strlen:
  6667. if (visitStrLenCall(I))
  6668. return;
  6669. break;
  6670. case LibFunc_strnlen:
  6671. if (visitStrNLenCall(I))
  6672. return;
  6673. break;
  6674. }
  6675. }
  6676. }
  6677. SDValue Callee;
  6678. if (!RenameFn)
  6679. Callee = getValue(I.getCalledValue());
  6680. else
  6681. Callee = DAG.getExternalSymbol(
  6682. RenameFn,
  6683. DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()));
  6684. // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
  6685. // have to do anything here to lower funclet bundles.
  6686. assert(!I.hasOperandBundlesOtherThan(
  6687. {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) &&
  6688. "Cannot lower calls with arbitrary operand bundles!");
  6689. if (I.countOperandBundlesOfType(LLVMContext::OB_deopt))
  6690. LowerCallSiteWithDeoptBundle(&I, Callee, nullptr);
  6691. else
  6692. // Check if we can potentially perform a tail call. More detailed checking
  6693. // is be done within LowerCallTo, after more information about the call is
  6694. // known.
  6695. LowerCallTo(&I, Callee, I.isTailCall());
  6696. }
  6697. namespace {
  6698. /// AsmOperandInfo - This contains information for each constraint that we are
  6699. /// lowering.
  6700. class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
  6701. public:
  6702. /// CallOperand - If this is the result output operand or a clobber
  6703. /// this is null, otherwise it is the incoming operand to the CallInst.
  6704. /// This gets modified as the asm is processed.
  6705. SDValue CallOperand;
  6706. /// AssignedRegs - If this is a register or register class operand, this
  6707. /// contains the set of register corresponding to the operand.
  6708. RegsForValue AssignedRegs;
  6709. explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info)
  6710. : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) {
  6711. }
  6712. /// Whether or not this operand accesses memory
  6713. bool hasMemory(const TargetLowering &TLI) const {
  6714. // Indirect operand accesses access memory.
  6715. if (isIndirect)
  6716. return true;
  6717. for (const auto &Code : Codes)
  6718. if (TLI.getConstraintType(Code) == TargetLowering::C_Memory)
  6719. return true;
  6720. return false;
  6721. }
  6722. /// getCallOperandValEVT - Return the EVT of the Value* that this operand
  6723. /// corresponds to. If there is no Value* for this operand, it returns
  6724. /// MVT::Other.
  6725. EVT getCallOperandValEVT(LLVMContext &Context, const TargetLowering &TLI,
  6726. const DataLayout &DL) const {
  6727. if (!CallOperandVal) return MVT::Other;
  6728. if (isa<BasicBlock>(CallOperandVal))
  6729. return TLI.getPointerTy(DL);
  6730. llvm::Type *OpTy = CallOperandVal->getType();
  6731. // FIXME: code duplicated from TargetLowering::ParseConstraints().
  6732. // If this is an indirect operand, the operand is a pointer to the
  6733. // accessed type.
  6734. if (isIndirect) {
  6735. PointerType *PtrTy = dyn_cast<PointerType>(OpTy);
  6736. if (!PtrTy)
  6737. report_fatal_error("Indirect operand for inline asm not a pointer!");
  6738. OpTy = PtrTy->getElementType();
  6739. }
  6740. // Look for vector wrapped in a struct. e.g. { <16 x i8> }.
  6741. if (StructType *STy = dyn_cast<StructType>(OpTy))
  6742. if (STy->getNumElements() == 1)
  6743. OpTy = STy->getElementType(0);
  6744. // If OpTy is not a single value, it may be a struct/union that we
  6745. // can tile with integers.
  6746. if (!OpTy->isSingleValueType() && OpTy->isSized()) {
  6747. unsigned BitSize = DL.getTypeSizeInBits(OpTy);
  6748. switch (BitSize) {
  6749. default: break;
  6750. case 1:
  6751. case 8:
  6752. case 16:
  6753. case 32:
  6754. case 64:
  6755. case 128:
  6756. OpTy = IntegerType::get(Context, BitSize);
  6757. break;
  6758. }
  6759. }
  6760. return TLI.getValueType(DL, OpTy, true);
  6761. }
  6762. };
  6763. using SDISelAsmOperandInfoVector = SmallVector<SDISelAsmOperandInfo, 16>;
  6764. } // end anonymous namespace
  6765. /// Make sure that the output operand \p OpInfo and its corresponding input
  6766. /// operand \p MatchingOpInfo have compatible constraint types (otherwise error
  6767. /// out).
  6768. static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo,
  6769. SDISelAsmOperandInfo &MatchingOpInfo,
  6770. SelectionDAG &DAG) {
  6771. if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT)
  6772. return;
  6773. const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
  6774. const auto &TLI = DAG.getTargetLoweringInfo();
  6775. std::pair<unsigned, const TargetRegisterClass *> MatchRC =
  6776. TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode,
  6777. OpInfo.ConstraintVT);
  6778. std::pair<unsigned, const TargetRegisterClass *> InputRC =
  6779. TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode,
  6780. MatchingOpInfo.ConstraintVT);
  6781. if ((OpInfo.ConstraintVT.isInteger() !=
  6782. MatchingOpInfo.ConstraintVT.isInteger()) ||
  6783. (MatchRC.second != InputRC.second)) {
  6784. // FIXME: error out in a more elegant fashion
  6785. report_fatal_error("Unsupported asm: input constraint"
  6786. " with a matching output constraint of"
  6787. " incompatible type!");
  6788. }
  6789. MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT;
  6790. }
  6791. /// Get a direct memory input to behave well as an indirect operand.
  6792. /// This may introduce stores, hence the need for a \p Chain.
  6793. /// \return The (possibly updated) chain.
  6794. static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location,
  6795. SDISelAsmOperandInfo &OpInfo,
  6796. SelectionDAG &DAG) {
  6797. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  6798. // If we don't have an indirect input, put it in the constpool if we can,
  6799. // otherwise spill it to a stack slot.
  6800. // TODO: This isn't quite right. We need to handle these according to
  6801. // the addressing mode that the constraint wants. Also, this may take
  6802. // an additional register for the computation and we don't want that
  6803. // either.
  6804. // If the operand is a float, integer, or vector constant, spill to a
  6805. // constant pool entry to get its address.
  6806. const Value *OpVal = OpInfo.CallOperandVal;
  6807. if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
  6808. isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) {
  6809. OpInfo.CallOperand = DAG.getConstantPool(
  6810. cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout()));
  6811. return Chain;
  6812. }
  6813. // Otherwise, create a stack slot and emit a store to it before the asm.
  6814. Type *Ty = OpVal->getType();
  6815. auto &DL = DAG.getDataLayout();
  6816. uint64_t TySize = DL.getTypeAllocSize(Ty);
  6817. unsigned Align = DL.getPrefTypeAlignment(Ty);
  6818. MachineFunction &MF = DAG.getMachineFunction();
  6819. int SSFI = MF.getFrameInfo().CreateStackObject(TySize, Align, false);
  6820. SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL));
  6821. Chain = DAG.getStore(Chain, Location, OpInfo.CallOperand, StackSlot,
  6822. MachinePointerInfo::getFixedStack(MF, SSFI));
  6823. OpInfo.CallOperand = StackSlot;
  6824. return Chain;
  6825. }
  6826. /// GetRegistersForValue - Assign registers (virtual or physical) for the
  6827. /// specified operand. We prefer to assign virtual registers, to allow the
  6828. /// register allocator to handle the assignment process. However, if the asm
  6829. /// uses features that we can't model on machineinstrs, we have SDISel do the
  6830. /// allocation. This produces generally horrible, but correct, code.
  6831. ///
  6832. /// OpInfo describes the operand
  6833. /// RefOpInfo describes the matching operand if any, the operand otherwise
  6834. static void GetRegistersForValue(SelectionDAG &DAG, const SDLoc &DL,
  6835. SDISelAsmOperandInfo &OpInfo,
  6836. SDISelAsmOperandInfo &RefOpInfo) {
  6837. LLVMContext &Context = *DAG.getContext();
  6838. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  6839. MachineFunction &MF = DAG.getMachineFunction();
  6840. SmallVector<unsigned, 4> Regs;
  6841. const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
  6842. // No work to do for memory operations.
  6843. if (OpInfo.ConstraintType == TargetLowering::C_Memory)
  6844. return;
  6845. // If this is a constraint for a single physreg, or a constraint for a
  6846. // register class, find it.
  6847. unsigned AssignedReg;
  6848. const TargetRegisterClass *RC;
  6849. std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint(
  6850. &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT);
  6851. // RC is unset only on failure. Return immediately.
  6852. if (!RC)
  6853. return;
  6854. // Get the actual register value type. This is important, because the user
  6855. // may have asked for (e.g.) the AX register in i32 type. We need to
  6856. // remember that AX is actually i16 to get the right extension.
  6857. const MVT RegVT = *TRI.legalclasstypes_begin(*RC);
  6858. if (OpInfo.ConstraintVT != MVT::Other) {
  6859. // If this is an FP operand in an integer register (or visa versa), or more
  6860. // generally if the operand value disagrees with the register class we plan
  6861. // to stick it in, fix the operand type.
  6862. //
  6863. // If this is an input value, the bitcast to the new type is done now.
  6864. // Bitcast for output value is done at the end of visitInlineAsm().
  6865. if ((OpInfo.Type == InlineAsm::isOutput ||
  6866. OpInfo.Type == InlineAsm::isInput) &&
  6867. !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) {
  6868. // Try to convert to the first EVT that the reg class contains. If the
  6869. // types are identical size, use a bitcast to convert (e.g. two differing
  6870. // vector types). Note: output bitcast is done at the end of
  6871. // visitInlineAsm().
  6872. if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
  6873. // Exclude indirect inputs while they are unsupported because the code
  6874. // to perform the load is missing and thus OpInfo.CallOperand still
  6875. // refers to the input address rather than the pointed-to value.
  6876. if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect)
  6877. OpInfo.CallOperand =
  6878. DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand);
  6879. OpInfo.ConstraintVT = RegVT;
  6880. // If the operand is an FP value and we want it in integer registers,
  6881. // use the corresponding integer type. This turns an f64 value into
  6882. // i64, which can be passed with two i32 values on a 32-bit machine.
  6883. } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
  6884. MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
  6885. if (OpInfo.Type == InlineAsm::isInput)
  6886. OpInfo.CallOperand =
  6887. DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand);
  6888. OpInfo.ConstraintVT = VT;
  6889. }
  6890. }
  6891. }
  6892. // No need to allocate a matching input constraint since the constraint it's
  6893. // matching to has already been allocated.
  6894. if (OpInfo.isMatchingInputConstraint())
  6895. return;
  6896. EVT ValueVT = OpInfo.ConstraintVT;
  6897. if (OpInfo.ConstraintVT == MVT::Other)
  6898. ValueVT = RegVT;
  6899. // Initialize NumRegs.
  6900. unsigned NumRegs = 1;
  6901. if (OpInfo.ConstraintVT != MVT::Other)
  6902. NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT);
  6903. // If this is a constraint for a specific physical register, like {r17},
  6904. // assign it now.
  6905. // If this associated to a specific register, initialize iterator to correct
  6906. // place. If virtual, make sure we have enough registers
  6907. // Initialize iterator if necessary
  6908. TargetRegisterClass::iterator I = RC->begin();
  6909. MachineRegisterInfo &RegInfo = MF.getRegInfo();
  6910. // Do not check for single registers.
  6911. if (AssignedReg) {
  6912. for (; *I != AssignedReg; ++I)
  6913. assert(I != RC->end() && "AssignedReg should be member of RC");
  6914. }
  6915. for (; NumRegs; --NumRegs, ++I) {
  6916. assert(I != RC->end() && "Ran out of registers to allocate!");
  6917. auto R = (AssignedReg) ? *I : RegInfo.createVirtualRegister(RC);
  6918. Regs.push_back(R);
  6919. }
  6920. OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
  6921. }
  6922. static unsigned
  6923. findMatchingInlineAsmOperand(unsigned OperandNo,
  6924. const std::vector<SDValue> &AsmNodeOperands) {
  6925. // Scan until we find the definition we already emitted of this operand.
  6926. unsigned CurOp = InlineAsm::Op_FirstOperand;
  6927. for (; OperandNo; --OperandNo) {
  6928. // Advance to the next operand.
  6929. unsigned OpFlag =
  6930. cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
  6931. assert((InlineAsm::isRegDefKind(OpFlag) ||
  6932. InlineAsm::isRegDefEarlyClobberKind(OpFlag) ||
  6933. InlineAsm::isMemKind(OpFlag)) &&
  6934. "Skipped past definitions?");
  6935. CurOp += InlineAsm::getNumOperandRegisters(OpFlag) + 1;
  6936. }
  6937. return CurOp;
  6938. }
  6939. namespace {
  6940. class ExtraFlags {
  6941. unsigned Flags = 0;
  6942. public:
  6943. explicit ExtraFlags(ImmutableCallSite CS) {
  6944. const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
  6945. if (IA->hasSideEffects())
  6946. Flags |= InlineAsm::Extra_HasSideEffects;
  6947. if (IA->isAlignStack())
  6948. Flags |= InlineAsm::Extra_IsAlignStack;
  6949. if (CS.isConvergent())
  6950. Flags |= InlineAsm::Extra_IsConvergent;
  6951. Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect;
  6952. }
  6953. void update(const TargetLowering::AsmOperandInfo &OpInfo) {
  6954. // Ideally, we would only check against memory constraints. However, the
  6955. // meaning of an Other constraint can be target-specific and we can't easily
  6956. // reason about it. Therefore, be conservative and set MayLoad/MayStore
  6957. // for Other constraints as well.
  6958. if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
  6959. OpInfo.ConstraintType == TargetLowering::C_Other) {
  6960. if (OpInfo.Type == InlineAsm::isInput)
  6961. Flags |= InlineAsm::Extra_MayLoad;
  6962. else if (OpInfo.Type == InlineAsm::isOutput)
  6963. Flags |= InlineAsm::Extra_MayStore;
  6964. else if (OpInfo.Type == InlineAsm::isClobber)
  6965. Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore);
  6966. }
  6967. }
  6968. unsigned get() const { return Flags; }
  6969. };
  6970. } // end anonymous namespace
  6971. /// visitInlineAsm - Handle a call to an InlineAsm object.
  6972. void SelectionDAGBuilder::visitInlineAsm(ImmutableCallSite CS) {
  6973. const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
  6974. /// ConstraintOperands - Information about all of the constraints.
  6975. SDISelAsmOperandInfoVector ConstraintOperands;
  6976. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  6977. TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints(
  6978. DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), CS);
  6979. // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack,
  6980. // AsmDialect, MayLoad, MayStore).
  6981. bool HasSideEffect = IA->hasSideEffects();
  6982. ExtraFlags ExtraInfo(CS);
  6983. unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
  6984. unsigned ResNo = 0; // ResNo - The result number of the next output.
  6985. for (auto &T : TargetConstraints) {
  6986. ConstraintOperands.push_back(SDISelAsmOperandInfo(T));
  6987. SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
  6988. // Compute the value type for each operand.
  6989. if (OpInfo.Type == InlineAsm::isInput ||
  6990. (OpInfo.Type == InlineAsm::isOutput && OpInfo.isIndirect)) {
  6991. OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
  6992. // Process the call argument. BasicBlocks are labels, currently appearing
  6993. // only in asm's.
  6994. const Instruction *I = CS.getInstruction();
  6995. if (isa<CallBrInst>(I) &&
  6996. (ArgNo - 1) >= (cast<CallBrInst>(I)->getNumArgOperands() -
  6997. cast<CallBrInst>(I)->getNumIndirectDests())) {
  6998. const auto *BA = cast<BlockAddress>(OpInfo.CallOperandVal);
  6999. EVT VT = TLI.getValueType(DAG.getDataLayout(), BA->getType(), true);
  7000. OpInfo.CallOperand = DAG.getTargetBlockAddress(BA, VT);
  7001. } else if (const auto *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) {
  7002. OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
  7003. } else {
  7004. OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
  7005. }
  7006. OpInfo.ConstraintVT =
  7007. OpInfo
  7008. .getCallOperandValEVT(*DAG.getContext(), TLI, DAG.getDataLayout())
  7009. .getSimpleVT();
  7010. } else if (OpInfo.Type == InlineAsm::isOutput && !OpInfo.isIndirect) {
  7011. // The return value of the call is this value. As such, there is no
  7012. // corresponding argument.
  7013. assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
  7014. if (StructType *STy = dyn_cast<StructType>(CS.getType())) {
  7015. OpInfo.ConstraintVT = TLI.getSimpleValueType(
  7016. DAG.getDataLayout(), STy->getElementType(ResNo));
  7017. } else {
  7018. assert(ResNo == 0 && "Asm only has one result!");
  7019. OpInfo.ConstraintVT =
  7020. TLI.getSimpleValueType(DAG.getDataLayout(), CS.getType());
  7021. }
  7022. ++ResNo;
  7023. } else {
  7024. OpInfo.ConstraintVT = MVT::Other;
  7025. }
  7026. if (!HasSideEffect)
  7027. HasSideEffect = OpInfo.hasMemory(TLI);
  7028. // Determine if this InlineAsm MayLoad or MayStore based on the constraints.
  7029. // FIXME: Could we compute this on OpInfo rather than T?
  7030. // Compute the constraint code and ConstraintType to use.
  7031. TLI.ComputeConstraintToUse(T, SDValue());
  7032. ExtraInfo.update(T);
  7033. }
  7034. // We won't need to flush pending loads if this asm doesn't touch
  7035. // memory and is nonvolatile.
  7036. SDValue Flag, Chain = (HasSideEffect) ? getRoot() : DAG.getRoot();
  7037. // Second pass over the constraints: compute which constraint option to use.
  7038. for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
  7039. // If this is an output operand with a matching input operand, look up the
  7040. // matching input. If their types mismatch, e.g. one is an integer, the
  7041. // other is floating point, or their sizes are different, flag it as an
  7042. // error.
  7043. if (OpInfo.hasMatchingInput()) {
  7044. SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
  7045. patchMatchingInput(OpInfo, Input, DAG);
  7046. }
  7047. // Compute the constraint code and ConstraintType to use.
  7048. TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
  7049. if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
  7050. OpInfo.Type == InlineAsm::isClobber)
  7051. continue;
  7052. // If this is a memory input, and if the operand is not indirect, do what we
  7053. // need to provide an address for the memory input.
  7054. if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
  7055. !OpInfo.isIndirect) {
  7056. assert((OpInfo.isMultipleAlternative ||
  7057. (OpInfo.Type == InlineAsm::isInput)) &&
  7058. "Can only indirectify direct input operands!");
  7059. // Memory operands really want the address of the value.
  7060. Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG);
  7061. // There is no longer a Value* corresponding to this operand.
  7062. OpInfo.CallOperandVal = nullptr;
  7063. // It is now an indirect operand.
  7064. OpInfo.isIndirect = true;
  7065. }
  7066. }
  7067. // AsmNodeOperands - The operands for the ISD::INLINEASM node.
  7068. std::vector<SDValue> AsmNodeOperands;
  7069. AsmNodeOperands.push_back(SDValue()); // reserve space for input chain
  7070. AsmNodeOperands.push_back(DAG.getTargetExternalSymbol(
  7071. IA->getAsmString().c_str(), TLI.getPointerTy(DAG.getDataLayout())));
  7072. // If we have a !srcloc metadata node associated with it, we want to attach
  7073. // this to the ultimately generated inline asm machineinstr. To do this, we
  7074. // pass in the third operand as this (potentially null) inline asm MDNode.
  7075. const MDNode *SrcLoc = CS.getInstruction()->getMetadata("srcloc");
  7076. AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc));
  7077. // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore
  7078. // bits as operand 3.
  7079. AsmNodeOperands.push_back(DAG.getTargetConstant(
  7080. ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
  7081. // Third pass: Loop over operands to prepare DAG-level operands.. As part of
  7082. // this, assign virtual and physical registers for inputs and otput.
  7083. for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
  7084. // Assign Registers.
  7085. SDISelAsmOperandInfo &RefOpInfo =
  7086. OpInfo.isMatchingInputConstraint()
  7087. ? ConstraintOperands[OpInfo.getMatchedOperand()]
  7088. : OpInfo;
  7089. GetRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo);
  7090. switch (OpInfo.Type) {
  7091. case InlineAsm::isOutput:
  7092. if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
  7093. (OpInfo.ConstraintType == TargetLowering::C_Other &&
  7094. OpInfo.isIndirect)) {
  7095. unsigned ConstraintID =
  7096. TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
  7097. assert(ConstraintID != InlineAsm::Constraint_Unknown &&
  7098. "Failed to convert memory constraint code to constraint id.");
  7099. // Add information to the INLINEASM node to know about this output.
  7100. unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
  7101. OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID);
  7102. AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(),
  7103. MVT::i32));
  7104. AsmNodeOperands.push_back(OpInfo.CallOperand);
  7105. break;
  7106. } else if ((OpInfo.ConstraintType == TargetLowering::C_Other &&
  7107. !OpInfo.isIndirect) ||
  7108. OpInfo.ConstraintType == TargetLowering::C_Register ||
  7109. OpInfo.ConstraintType == TargetLowering::C_RegisterClass) {
  7110. // Otherwise, this outputs to a register (directly for C_Register /
  7111. // C_RegisterClass, and a target-defined fashion for C_Other). Find a
  7112. // register that we can use.
  7113. if (OpInfo.AssignedRegs.Regs.empty()) {
  7114. emitInlineAsmError(
  7115. CS, "couldn't allocate output register for constraint '" +
  7116. Twine(OpInfo.ConstraintCode) + "'");
  7117. return;
  7118. }
  7119. // Add information to the INLINEASM node to know that this register is
  7120. // set.
  7121. OpInfo.AssignedRegs.AddInlineAsmOperands(
  7122. OpInfo.isEarlyClobber ? InlineAsm::Kind_RegDefEarlyClobber
  7123. : InlineAsm::Kind_RegDef,
  7124. false, 0, getCurSDLoc(), DAG, AsmNodeOperands);
  7125. }
  7126. break;
  7127. case InlineAsm::isInput: {
  7128. SDValue InOperandVal = OpInfo.CallOperand;
  7129. if (OpInfo.isMatchingInputConstraint()) {
  7130. // If this is required to match an output register we have already set,
  7131. // just use its register.
  7132. auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(),
  7133. AsmNodeOperands);
  7134. unsigned OpFlag =
  7135. cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
  7136. if (InlineAsm::isRegDefKind(OpFlag) ||
  7137. InlineAsm::isRegDefEarlyClobberKind(OpFlag)) {
  7138. // Add (OpFlag&0xffff)>>3 registers to MatchedRegs.
  7139. if (OpInfo.isIndirect) {
  7140. // This happens on gcc/testsuite/gcc.dg/pr8788-1.c
  7141. emitInlineAsmError(CS, "inline asm not supported yet:"
  7142. " don't know how to handle tied "
  7143. "indirect register inputs");
  7144. return;
  7145. }
  7146. MVT RegVT = AsmNodeOperands[CurOp+1].getSimpleValueType();
  7147. SmallVector<unsigned, 4> Regs;
  7148. if (const TargetRegisterClass *RC = TLI.getRegClassFor(RegVT)) {
  7149. unsigned NumRegs = InlineAsm::getNumOperandRegisters(OpFlag);
  7150. MachineRegisterInfo &RegInfo =
  7151. DAG.getMachineFunction().getRegInfo();
  7152. for (unsigned i = 0; i != NumRegs; ++i)
  7153. Regs.push_back(RegInfo.createVirtualRegister(RC));
  7154. } else {
  7155. emitInlineAsmError(CS, "inline asm error: This value type register "
  7156. "class is not natively supported!");
  7157. return;
  7158. }
  7159. RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType());
  7160. SDLoc dl = getCurSDLoc();
  7161. // Use the produced MatchedRegs object to
  7162. MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag,
  7163. CS.getInstruction());
  7164. MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse,
  7165. true, OpInfo.getMatchedOperand(), dl,
  7166. DAG, AsmNodeOperands);
  7167. break;
  7168. }
  7169. assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!");
  7170. assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 &&
  7171. "Unexpected number of operands");
  7172. // Add information to the INLINEASM node to know about this input.
  7173. // See InlineAsm.h isUseOperandTiedToDef.
  7174. OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag);
  7175. OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag,
  7176. OpInfo.getMatchedOperand());
  7177. AsmNodeOperands.push_back(DAG.getTargetConstant(
  7178. OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
  7179. AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
  7180. break;
  7181. }
  7182. // Treat indirect 'X' constraint as memory.
  7183. if (OpInfo.ConstraintType == TargetLowering::C_Other &&
  7184. OpInfo.isIndirect)
  7185. OpInfo.ConstraintType = TargetLowering::C_Memory;
  7186. if (OpInfo.ConstraintType == TargetLowering::C_Other) {
  7187. std::vector<SDValue> Ops;
  7188. TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode,
  7189. Ops, DAG);
  7190. if (Ops.empty()) {
  7191. emitInlineAsmError(CS, "invalid operand for inline asm constraint '" +
  7192. Twine(OpInfo.ConstraintCode) + "'");
  7193. return;
  7194. }
  7195. // Add information to the INLINEASM node to know about this input.
  7196. unsigned ResOpType =
  7197. InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size());
  7198. AsmNodeOperands.push_back(DAG.getTargetConstant(
  7199. ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
  7200. AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
  7201. break;
  7202. }
  7203. if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
  7204. assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
  7205. assert(InOperandVal.getValueType() ==
  7206. TLI.getPointerTy(DAG.getDataLayout()) &&
  7207. "Memory operands expect pointer values");
  7208. unsigned ConstraintID =
  7209. TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
  7210. assert(ConstraintID != InlineAsm::Constraint_Unknown &&
  7211. "Failed to convert memory constraint code to constraint id.");
  7212. // Add information to the INLINEASM node to know about this input.
  7213. unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
  7214. ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID);
  7215. AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
  7216. getCurSDLoc(),
  7217. MVT::i32));
  7218. AsmNodeOperands.push_back(InOperandVal);
  7219. break;
  7220. }
  7221. assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
  7222. OpInfo.ConstraintType == TargetLowering::C_Register) &&
  7223. "Unknown constraint type!");
  7224. // TODO: Support this.
  7225. if (OpInfo.isIndirect) {
  7226. emitInlineAsmError(
  7227. CS, "Don't know how to handle indirect register inputs yet "
  7228. "for constraint '" +
  7229. Twine(OpInfo.ConstraintCode) + "'");
  7230. return;
  7231. }
  7232. // Copy the input into the appropriate registers.
  7233. if (OpInfo.AssignedRegs.Regs.empty()) {
  7234. emitInlineAsmError(CS, "couldn't allocate input reg for constraint '" +
  7235. Twine(OpInfo.ConstraintCode) + "'");
  7236. return;
  7237. }
  7238. SDLoc dl = getCurSDLoc();
  7239. OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl,
  7240. Chain, &Flag, CS.getInstruction());
  7241. OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0,
  7242. dl, DAG, AsmNodeOperands);
  7243. break;
  7244. }
  7245. case InlineAsm::isClobber:
  7246. // Add the clobbered value to the operand list, so that the register
  7247. // allocator is aware that the physreg got clobbered.
  7248. if (!OpInfo.AssignedRegs.Regs.empty())
  7249. OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber,
  7250. false, 0, getCurSDLoc(), DAG,
  7251. AsmNodeOperands);
  7252. break;
  7253. }
  7254. }
  7255. // Finish up input operands. Set the input chain and add the flag last.
  7256. AsmNodeOperands[InlineAsm::Op_InputChain] = Chain;
  7257. if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
  7258. unsigned ISDOpc = isa<CallBrInst>(CS.getInstruction()) ? ISD::INLINEASM_BR
  7259. : ISD::INLINEASM;
  7260. Chain = DAG.getNode(ISDOpc, getCurSDLoc(),
  7261. DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands);
  7262. Flag = Chain.getValue(1);
  7263. // Do additional work to generate outputs.
  7264. SmallVector<EVT, 1> ResultVTs;
  7265. SmallVector<SDValue, 1> ResultValues;
  7266. SmallVector<SDValue, 8> OutChains;
  7267. llvm::Type *CSResultType = CS.getType();
  7268. ArrayRef<Type *> ResultTypes;
  7269. if (StructType *StructResult = dyn_cast<StructType>(CSResultType))
  7270. ResultTypes = StructResult->elements();
  7271. else if (!CSResultType->isVoidTy())
  7272. ResultTypes = makeArrayRef(CSResultType);
  7273. auto CurResultType = ResultTypes.begin();
  7274. auto handleRegAssign = [&](SDValue V) {
  7275. assert(CurResultType != ResultTypes.end() && "Unexpected value");
  7276. assert((*CurResultType)->isSized() && "Unexpected unsized type");
  7277. EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType);
  7278. ++CurResultType;
  7279. // If the type of the inline asm call site return value is different but has
  7280. // same size as the type of the asm output bitcast it. One example of this
  7281. // is for vectors with different width / number of elements. This can
  7282. // happen for register classes that can contain multiple different value
  7283. // types. The preg or vreg allocated may not have the same VT as was
  7284. // expected.
  7285. //
  7286. // This can also happen for a return value that disagrees with the register
  7287. // class it is put in, eg. a double in a general-purpose register on a
  7288. // 32-bit machine.
  7289. if (ResultVT != V.getValueType() &&
  7290. ResultVT.getSizeInBits() == V.getValueSizeInBits())
  7291. V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V);
  7292. else if (ResultVT != V.getValueType() && ResultVT.isInteger() &&
  7293. V.getValueType().isInteger()) {
  7294. // If a result value was tied to an input value, the computed result
  7295. // may have a wider width than the expected result. Extract the
  7296. // relevant portion.
  7297. V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V);
  7298. }
  7299. assert(ResultVT == V.getValueType() && "Asm result value mismatch!");
  7300. ResultVTs.push_back(ResultVT);
  7301. ResultValues.push_back(V);
  7302. };
  7303. // Deal with output operands.
  7304. for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
  7305. if (OpInfo.Type == InlineAsm::isOutput) {
  7306. SDValue Val;
  7307. // Skip trivial output operands.
  7308. if (OpInfo.AssignedRegs.Regs.empty())
  7309. continue;
  7310. switch (OpInfo.ConstraintType) {
  7311. case TargetLowering::C_Register:
  7312. case TargetLowering::C_RegisterClass:
  7313. Val = OpInfo.AssignedRegs.getCopyFromRegs(
  7314. DAG, FuncInfo, getCurSDLoc(), Chain, &Flag, CS.getInstruction());
  7315. break;
  7316. case TargetLowering::C_Other:
  7317. Val = TLI.LowerAsmOutputForConstraint(Chain, Flag, getCurSDLoc(),
  7318. OpInfo, DAG);
  7319. break;
  7320. case TargetLowering::C_Memory:
  7321. break; // Already handled.
  7322. case TargetLowering::C_Unknown:
  7323. assert(false && "Unexpected unknown constraint");
  7324. }
  7325. // Indirect output manifest as stores. Record output chains.
  7326. if (OpInfo.isIndirect) {
  7327. const Value *Ptr = OpInfo.CallOperandVal;
  7328. assert(Ptr && "Expected value CallOperandVal for indirect asm operand");
  7329. SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr),
  7330. MachinePointerInfo(Ptr));
  7331. OutChains.push_back(Store);
  7332. } else {
  7333. // generate CopyFromRegs to associated registers.
  7334. assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
  7335. if (Val.getOpcode() == ISD::MERGE_VALUES) {
  7336. for (const SDValue &V : Val->op_values())
  7337. handleRegAssign(V);
  7338. } else
  7339. handleRegAssign(Val);
  7340. }
  7341. }
  7342. }
  7343. // Set results.
  7344. if (!ResultValues.empty()) {
  7345. assert(CurResultType == ResultTypes.end() &&
  7346. "Mismatch in number of ResultTypes");
  7347. assert(ResultValues.size() == ResultTypes.size() &&
  7348. "Mismatch in number of output operands in asm result");
  7349. SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
  7350. DAG.getVTList(ResultVTs), ResultValues);
  7351. setValue(CS.getInstruction(), V);
  7352. }
  7353. // Collect store chains.
  7354. if (!OutChains.empty())
  7355. Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains);
  7356. // Only Update Root if inline assembly has a memory effect.
  7357. if (ResultValues.empty() || HasSideEffect || !OutChains.empty())
  7358. DAG.setRoot(Chain);
  7359. }
  7360. void SelectionDAGBuilder::emitInlineAsmError(ImmutableCallSite CS,
  7361. const Twine &Message) {
  7362. LLVMContext &Ctx = *DAG.getContext();
  7363. Ctx.emitError(CS.getInstruction(), Message);
  7364. // Make sure we leave the DAG in a valid state
  7365. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  7366. SmallVector<EVT, 1> ValueVTs;
  7367. ComputeValueVTs(TLI, DAG.getDataLayout(), CS->getType(), ValueVTs);
  7368. if (ValueVTs.empty())
  7369. return;
  7370. SmallVector<SDValue, 1> Ops;
  7371. for (unsigned i = 0, e = ValueVTs.size(); i != e; ++i)
  7372. Ops.push_back(DAG.getUNDEF(ValueVTs[i]));
  7373. setValue(CS.getInstruction(), DAG.getMergeValues(Ops, getCurSDLoc()));
  7374. }
  7375. void SelectionDAGBuilder::visitVAStart(const CallInst &I) {
  7376. DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(),
  7377. MVT::Other, getRoot(),
  7378. getValue(I.getArgOperand(0)),
  7379. DAG.getSrcValue(I.getArgOperand(0))));
  7380. }
  7381. void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) {
  7382. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  7383. const DataLayout &DL = DAG.getDataLayout();
  7384. SDValue V = DAG.getVAArg(TLI.getValueType(DAG.getDataLayout(), I.getType()),
  7385. getCurSDLoc(), getRoot(), getValue(I.getOperand(0)),
  7386. DAG.getSrcValue(I.getOperand(0)),
  7387. DL.getABITypeAlignment(I.getType()));
  7388. setValue(&I, V);
  7389. DAG.setRoot(V.getValue(1));
  7390. }
  7391. void SelectionDAGBuilder::visitVAEnd(const CallInst &I) {
  7392. DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(),
  7393. MVT::Other, getRoot(),
  7394. getValue(I.getArgOperand(0)),
  7395. DAG.getSrcValue(I.getArgOperand(0))));
  7396. }
  7397. void SelectionDAGBuilder::visitVACopy(const CallInst &I) {
  7398. DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(),
  7399. MVT::Other, getRoot(),
  7400. getValue(I.getArgOperand(0)),
  7401. getValue(I.getArgOperand(1)),
  7402. DAG.getSrcValue(I.getArgOperand(0)),
  7403. DAG.getSrcValue(I.getArgOperand(1))));
  7404. }
  7405. SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG,
  7406. const Instruction &I,
  7407. SDValue Op) {
  7408. const MDNode *Range = I.getMetadata(LLVMContext::MD_range);
  7409. if (!Range)
  7410. return Op;
  7411. ConstantRange CR = getConstantRangeFromMetadata(*Range);
  7412. if (CR.isFullSet() || CR.isEmptySet() || CR.isUpperWrapped())
  7413. return Op;
  7414. APInt Lo = CR.getUnsignedMin();
  7415. if (!Lo.isMinValue())
  7416. return Op;
  7417. APInt Hi = CR.getUnsignedMax();
  7418. unsigned Bits = std::max(Hi.getActiveBits(),
  7419. static_cast<unsigned>(IntegerType::MIN_INT_BITS));
  7420. EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
  7421. SDLoc SL = getCurSDLoc();
  7422. SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op,
  7423. DAG.getValueType(SmallVT));
  7424. unsigned NumVals = Op.getNode()->getNumValues();
  7425. if (NumVals == 1)
  7426. return ZExt;
  7427. SmallVector<SDValue, 4> Ops;
  7428. Ops.push_back(ZExt);
  7429. for (unsigned I = 1; I != NumVals; ++I)
  7430. Ops.push_back(Op.getValue(I));
  7431. return DAG.getMergeValues(Ops, SL);
  7432. }
  7433. /// Populate a CallLowerinInfo (into \p CLI) based on the properties of
  7434. /// the call being lowered.
  7435. ///
  7436. /// This is a helper for lowering intrinsics that follow a target calling
  7437. /// convention or require stack pointer adjustment. Only a subset of the
  7438. /// intrinsic's operands need to participate in the calling convention.
  7439. void SelectionDAGBuilder::populateCallLoweringInfo(
  7440. TargetLowering::CallLoweringInfo &CLI, const CallBase *Call,
  7441. unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy,
  7442. bool IsPatchPoint) {
  7443. TargetLowering::ArgListTy Args;
  7444. Args.reserve(NumArgs);
  7445. // Populate the argument list.
  7446. // Attributes for args start at offset 1, after the return attribute.
  7447. for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs;
  7448. ArgI != ArgE; ++ArgI) {
  7449. const Value *V = Call->getOperand(ArgI);
  7450. assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic.");
  7451. TargetLowering::ArgListEntry Entry;
  7452. Entry.Node = getValue(V);
  7453. Entry.Ty = V->getType();
  7454. Entry.setAttributes(Call, ArgI);
  7455. Args.push_back(Entry);
  7456. }
  7457. CLI.setDebugLoc(getCurSDLoc())
  7458. .setChain(getRoot())
  7459. .setCallee(Call->getCallingConv(), ReturnTy, Callee, std::move(Args))
  7460. .setDiscardResult(Call->use_empty())
  7461. .setIsPatchPoint(IsPatchPoint);
  7462. }
  7463. /// Add a stack map intrinsic call's live variable operands to a stackmap
  7464. /// or patchpoint target node's operand list.
  7465. ///
  7466. /// Constants are converted to TargetConstants purely as an optimization to
  7467. /// avoid constant materialization and register allocation.
  7468. ///
  7469. /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not
  7470. /// generate addess computation nodes, and so ExpandISelPseudo can convert the
  7471. /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids
  7472. /// address materialization and register allocation, but may also be required
  7473. /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an
  7474. /// alloca in the entry block, then the runtime may assume that the alloca's
  7475. /// StackMap location can be read immediately after compilation and that the
  7476. /// location is valid at any point during execution (this is similar to the
  7477. /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were
  7478. /// only available in a register, then the runtime would need to trap when
  7479. /// execution reaches the StackMap in order to read the alloca's location.
  7480. static void addStackMapLiveVars(ImmutableCallSite CS, unsigned StartIdx,
  7481. const SDLoc &DL, SmallVectorImpl<SDValue> &Ops,
  7482. SelectionDAGBuilder &Builder) {
  7483. for (unsigned i = StartIdx, e = CS.arg_size(); i != e; ++i) {
  7484. SDValue OpVal = Builder.getValue(CS.getArgument(i));
  7485. if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(OpVal)) {
  7486. Ops.push_back(
  7487. Builder.DAG.getTargetConstant(StackMaps::ConstantOp, DL, MVT::i64));
  7488. Ops.push_back(
  7489. Builder.DAG.getTargetConstant(C->getSExtValue(), DL, MVT::i64));
  7490. } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(OpVal)) {
  7491. const TargetLowering &TLI = Builder.DAG.getTargetLoweringInfo();
  7492. Ops.push_back(Builder.DAG.getTargetFrameIndex(
  7493. FI->getIndex(), TLI.getFrameIndexTy(Builder.DAG.getDataLayout())));
  7494. } else
  7495. Ops.push_back(OpVal);
  7496. }
  7497. }
  7498. /// Lower llvm.experimental.stackmap directly to its target opcode.
  7499. void SelectionDAGBuilder::visitStackmap(const CallInst &CI) {
  7500. // void @llvm.experimental.stackmap(i32 <id>, i32 <numShadowBytes>,
  7501. // [live variables...])
  7502. assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value.");
  7503. SDValue Chain, InFlag, Callee, NullPtr;
  7504. SmallVector<SDValue, 32> Ops;
  7505. SDLoc DL = getCurSDLoc();
  7506. Callee = getValue(CI.getCalledValue());
  7507. NullPtr = DAG.getIntPtrConstant(0, DL, true);
  7508. // The stackmap intrinsic only records the live variables (the arguemnts
  7509. // passed to it) and emits NOPS (if requested). Unlike the patchpoint
  7510. // intrinsic, this won't be lowered to a function call. This means we don't
  7511. // have to worry about calling conventions and target specific lowering code.
  7512. // Instead we perform the call lowering right here.
  7513. //
  7514. // chain, flag = CALLSEQ_START(chain, 0, 0)
  7515. // chain, flag = STACKMAP(id, nbytes, ..., chain, flag)
  7516. // chain, flag = CALLSEQ_END(chain, 0, 0, flag)
  7517. //
  7518. Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL);
  7519. InFlag = Chain.getValue(1);
  7520. // Add the <id> and <numBytes> constants.
  7521. SDValue IDVal = getValue(CI.getOperand(PatchPointOpers::IDPos));
  7522. Ops.push_back(DAG.getTargetConstant(
  7523. cast<ConstantSDNode>(IDVal)->getZExtValue(), DL, MVT::i64));
  7524. SDValue NBytesVal = getValue(CI.getOperand(PatchPointOpers::NBytesPos));
  7525. Ops.push_back(DAG.getTargetConstant(
  7526. cast<ConstantSDNode>(NBytesVal)->getZExtValue(), DL,
  7527. MVT::i32));
  7528. // Push live variables for the stack map.
  7529. addStackMapLiveVars(&CI, 2, DL, Ops, *this);
  7530. // We are not pushing any register mask info here on the operands list,
  7531. // because the stackmap doesn't clobber anything.
  7532. // Push the chain and the glue flag.
  7533. Ops.push_back(Chain);
  7534. Ops.push_back(InFlag);
  7535. // Create the STACKMAP node.
  7536. SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
  7537. SDNode *SM = DAG.getMachineNode(TargetOpcode::STACKMAP, DL, NodeTys, Ops);
  7538. Chain = SDValue(SM, 0);
  7539. InFlag = Chain.getValue(1);
  7540. Chain = DAG.getCALLSEQ_END(Chain, NullPtr, NullPtr, InFlag, DL);
  7541. // Stackmaps don't generate values, so nothing goes into the NodeMap.
  7542. // Set the root to the target-lowered call chain.
  7543. DAG.setRoot(Chain);
  7544. // Inform the Frame Information that we have a stackmap in this function.
  7545. FuncInfo.MF->getFrameInfo().setHasStackMap();
  7546. }
  7547. /// Lower llvm.experimental.patchpoint directly to its target opcode.
  7548. void SelectionDAGBuilder::visitPatchpoint(ImmutableCallSite CS,
  7549. const BasicBlock *EHPadBB) {
  7550. // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>,
  7551. // i32 <numBytes>,
  7552. // i8* <target>,
  7553. // i32 <numArgs>,
  7554. // [Args...],
  7555. // [live variables...])
  7556. CallingConv::ID CC = CS.getCallingConv();
  7557. bool IsAnyRegCC = CC == CallingConv::AnyReg;
  7558. bool HasDef = !CS->getType()->isVoidTy();
  7559. SDLoc dl = getCurSDLoc();
  7560. SDValue Callee = getValue(CS->getOperand(PatchPointOpers::TargetPos));
  7561. // Handle immediate and symbolic callees.
  7562. if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee))
  7563. Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl,
  7564. /*isTarget=*/true);
  7565. else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee))
  7566. Callee = DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(),
  7567. SDLoc(SymbolicCallee),
  7568. SymbolicCallee->getValueType(0));
  7569. // Get the real number of arguments participating in the call <numArgs>
  7570. SDValue NArgVal = getValue(CS.getArgument(PatchPointOpers::NArgPos));
  7571. unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue();
  7572. // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs>
  7573. // Intrinsics include all meta-operands up to but not including CC.
  7574. unsigned NumMetaOpers = PatchPointOpers::CCPos;
  7575. assert(CS.arg_size() >= NumMetaOpers + NumArgs &&
  7576. "Not enough arguments provided to the patchpoint intrinsic");
  7577. // For AnyRegCC the arguments are lowered later on manually.
  7578. unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs;
  7579. Type *ReturnTy =
  7580. IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CS->getType();
  7581. TargetLowering::CallLoweringInfo CLI(DAG);
  7582. populateCallLoweringInfo(CLI, cast<CallBase>(CS.getInstruction()),
  7583. NumMetaOpers, NumCallArgs, Callee, ReturnTy, true);
  7584. std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
  7585. SDNode *CallEnd = Result.second.getNode();
  7586. if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg))
  7587. CallEnd = CallEnd->getOperand(0).getNode();
  7588. /// Get a call instruction from the call sequence chain.
  7589. /// Tail calls are not allowed.
  7590. assert(CallEnd->getOpcode() == ISD::CALLSEQ_END &&
  7591. "Expected a callseq node.");
  7592. SDNode *Call = CallEnd->getOperand(0).getNode();
  7593. bool HasGlue = Call->getGluedNode();
  7594. // Replace the target specific call node with the patchable intrinsic.
  7595. SmallVector<SDValue, 8> Ops;
  7596. // Add the <id> and <numBytes> constants.
  7597. SDValue IDVal = getValue(CS->getOperand(PatchPointOpers::IDPos));
  7598. Ops.push_back(DAG.getTargetConstant(
  7599. cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64));
  7600. SDValue NBytesVal = getValue(CS->getOperand(PatchPointOpers::NBytesPos));
  7601. Ops.push_back(DAG.getTargetConstant(
  7602. cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl,
  7603. MVT::i32));
  7604. // Add the callee.
  7605. Ops.push_back(Callee);
  7606. // Adjust <numArgs> to account for any arguments that have been passed on the
  7607. // stack instead.
  7608. // Call Node: Chain, Target, {Args}, RegMask, [Glue]
  7609. unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3);
  7610. NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs;
  7611. Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32));
  7612. // Add the calling convention
  7613. Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32));
  7614. // Add the arguments we omitted previously. The register allocator should
  7615. // place these in any free register.
  7616. if (IsAnyRegCC)
  7617. for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i)
  7618. Ops.push_back(getValue(CS.getArgument(i)));
  7619. // Push the arguments from the call instruction up to the register mask.
  7620. SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1;
  7621. Ops.append(Call->op_begin() + 2, e);
  7622. // Push live variables for the stack map.
  7623. addStackMapLiveVars(CS, NumMetaOpers + NumArgs, dl, Ops, *this);
  7624. // Push the register mask info.
  7625. if (HasGlue)
  7626. Ops.push_back(*(Call->op_end()-2));
  7627. else
  7628. Ops.push_back(*(Call->op_end()-1));
  7629. // Push the chain (this is originally the first operand of the call, but
  7630. // becomes now the last or second to last operand).
  7631. Ops.push_back(*(Call->op_begin()));
  7632. // Push the glue flag (last operand).
  7633. if (HasGlue)
  7634. Ops.push_back(*(Call->op_end()-1));
  7635. SDVTList NodeTys;
  7636. if (IsAnyRegCC && HasDef) {
  7637. // Create the return types based on the intrinsic definition
  7638. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  7639. SmallVector<EVT, 3> ValueVTs;
  7640. ComputeValueVTs(TLI, DAG.getDataLayout(), CS->getType(), ValueVTs);
  7641. assert(ValueVTs.size() == 1 && "Expected only one return value type.");
  7642. // There is always a chain and a glue type at the end
  7643. ValueVTs.push_back(MVT::Other);
  7644. ValueVTs.push_back(MVT::Glue);
  7645. NodeTys = DAG.getVTList(ValueVTs);
  7646. } else
  7647. NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
  7648. // Replace the target specific call node with a PATCHPOINT node.
  7649. MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHPOINT,
  7650. dl, NodeTys, Ops);
  7651. // Update the NodeMap.
  7652. if (HasDef) {
  7653. if (IsAnyRegCC)
  7654. setValue(CS.getInstruction(), SDValue(MN, 0));
  7655. else
  7656. setValue(CS.getInstruction(), Result.first);
  7657. }
  7658. // Fixup the consumers of the intrinsic. The chain and glue may be used in the
  7659. // call sequence. Furthermore the location of the chain and glue can change
  7660. // when the AnyReg calling convention is used and the intrinsic returns a
  7661. // value.
  7662. if (IsAnyRegCC && HasDef) {
  7663. SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)};
  7664. SDValue To[] = {SDValue(MN, 1), SDValue(MN, 2)};
  7665. DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
  7666. } else
  7667. DAG.ReplaceAllUsesWith(Call, MN);
  7668. DAG.DeleteNode(Call);
  7669. // Inform the Frame Information that we have a patchpoint in this function.
  7670. FuncInfo.MF->getFrameInfo().setHasPatchPoint();
  7671. }
  7672. void SelectionDAGBuilder::visitVectorReduce(const CallInst &I,
  7673. unsigned Intrinsic) {
  7674. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  7675. SDValue Op1 = getValue(I.getArgOperand(0));
  7676. SDValue Op2;
  7677. if (I.getNumArgOperands() > 1)
  7678. Op2 = getValue(I.getArgOperand(1));
  7679. SDLoc dl = getCurSDLoc();
  7680. EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  7681. SDValue Res;
  7682. FastMathFlags FMF;
  7683. if (isa<FPMathOperator>(I))
  7684. FMF = I.getFastMathFlags();
  7685. switch (Intrinsic) {
  7686. case Intrinsic::experimental_vector_reduce_fadd:
  7687. if (FMF.isFast())
  7688. Res = DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2);
  7689. else
  7690. Res = DAG.getNode(ISD::VECREDUCE_STRICT_FADD, dl, VT, Op1, Op2);
  7691. break;
  7692. case Intrinsic::experimental_vector_reduce_fmul:
  7693. if (FMF.isFast())
  7694. Res = DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2);
  7695. else
  7696. Res = DAG.getNode(ISD::VECREDUCE_STRICT_FMUL, dl, VT, Op1, Op2);
  7697. break;
  7698. case Intrinsic::experimental_vector_reduce_add:
  7699. Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1);
  7700. break;
  7701. case Intrinsic::experimental_vector_reduce_mul:
  7702. Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1);
  7703. break;
  7704. case Intrinsic::experimental_vector_reduce_and:
  7705. Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1);
  7706. break;
  7707. case Intrinsic::experimental_vector_reduce_or:
  7708. Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1);
  7709. break;
  7710. case Intrinsic::experimental_vector_reduce_xor:
  7711. Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1);
  7712. break;
  7713. case Intrinsic::experimental_vector_reduce_smax:
  7714. Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1);
  7715. break;
  7716. case Intrinsic::experimental_vector_reduce_smin:
  7717. Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1);
  7718. break;
  7719. case Intrinsic::experimental_vector_reduce_umax:
  7720. Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1);
  7721. break;
  7722. case Intrinsic::experimental_vector_reduce_umin:
  7723. Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1);
  7724. break;
  7725. case Intrinsic::experimental_vector_reduce_fmax:
  7726. Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1);
  7727. break;
  7728. case Intrinsic::experimental_vector_reduce_fmin:
  7729. Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1);
  7730. break;
  7731. default:
  7732. llvm_unreachable("Unhandled vector reduce intrinsic");
  7733. }
  7734. setValue(&I, Res);
  7735. }
  7736. /// Returns an AttributeList representing the attributes applied to the return
  7737. /// value of the given call.
  7738. static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) {
  7739. SmallVector<Attribute::AttrKind, 2> Attrs;
  7740. if (CLI.RetSExt)
  7741. Attrs.push_back(Attribute::SExt);
  7742. if (CLI.RetZExt)
  7743. Attrs.push_back(Attribute::ZExt);
  7744. if (CLI.IsInReg)
  7745. Attrs.push_back(Attribute::InReg);
  7746. return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex,
  7747. Attrs);
  7748. }
  7749. /// TargetLowering::LowerCallTo - This is the default LowerCallTo
  7750. /// implementation, which just calls LowerCall.
  7751. /// FIXME: When all targets are
  7752. /// migrated to using LowerCall, this hook should be integrated into SDISel.
  7753. std::pair<SDValue, SDValue>
  7754. TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const {
  7755. // Handle the incoming return values from the call.
  7756. CLI.Ins.clear();
  7757. Type *OrigRetTy = CLI.RetTy;
  7758. SmallVector<EVT, 4> RetTys;
  7759. SmallVector<uint64_t, 4> Offsets;
  7760. auto &DL = CLI.DAG.getDataLayout();
  7761. ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets);
  7762. if (CLI.IsPostTypeLegalization) {
  7763. // If we are lowering a libcall after legalization, split the return type.
  7764. SmallVector<EVT, 4> OldRetTys = std::move(RetTys);
  7765. SmallVector<uint64_t, 4> OldOffsets = std::move(Offsets);
  7766. for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) {
  7767. EVT RetVT = OldRetTys[i];
  7768. uint64_t Offset = OldOffsets[i];
  7769. MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT);
  7770. unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT);
  7771. unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8;
  7772. RetTys.append(NumRegs, RegisterVT);
  7773. for (unsigned j = 0; j != NumRegs; ++j)
  7774. Offsets.push_back(Offset + j * RegisterVTByteSZ);
  7775. }
  7776. }
  7777. SmallVector<ISD::OutputArg, 4> Outs;
  7778. GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL);
  7779. bool CanLowerReturn =
  7780. this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(),
  7781. CLI.IsVarArg, Outs, CLI.RetTy->getContext());
  7782. SDValue DemoteStackSlot;
  7783. int DemoteStackIdx = -100;
  7784. if (!CanLowerReturn) {
  7785. // FIXME: equivalent assert?
  7786. // assert(!CS.hasInAllocaArgument() &&
  7787. // "sret demotion is incompatible with inalloca");
  7788. uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy);
  7789. unsigned Align = DL.getPrefTypeAlignment(CLI.RetTy);
  7790. MachineFunction &MF = CLI.DAG.getMachineFunction();
  7791. DemoteStackIdx = MF.getFrameInfo().CreateStackObject(TySize, Align, false);
  7792. Type *StackSlotPtrType = PointerType::get(CLI.RetTy,
  7793. DL.getAllocaAddrSpace());
  7794. DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL));
  7795. ArgListEntry Entry;
  7796. Entry.Node = DemoteStackSlot;
  7797. Entry.Ty = StackSlotPtrType;
  7798. Entry.IsSExt = false;
  7799. Entry.IsZExt = false;
  7800. Entry.IsInReg = false;
  7801. Entry.IsSRet = true;
  7802. Entry.IsNest = false;
  7803. Entry.IsByVal = false;
  7804. Entry.IsReturned = false;
  7805. Entry.IsSwiftSelf = false;
  7806. Entry.IsSwiftError = false;
  7807. Entry.Alignment = Align;
  7808. CLI.getArgs().insert(CLI.getArgs().begin(), Entry);
  7809. CLI.NumFixedArgs += 1;
  7810. CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext());
  7811. // sret demotion isn't compatible with tail-calls, since the sret argument
  7812. // points into the callers stack frame.
  7813. CLI.IsTailCall = false;
  7814. } else {
  7815. bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
  7816. CLI.RetTy, CLI.CallConv, CLI.IsVarArg);
  7817. for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
  7818. ISD::ArgFlagsTy Flags;
  7819. if (NeedsRegBlock) {
  7820. Flags.setInConsecutiveRegs();
  7821. if (I == RetTys.size() - 1)
  7822. Flags.setInConsecutiveRegsLast();
  7823. }
  7824. EVT VT = RetTys[I];
  7825. MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
  7826. CLI.CallConv, VT);
  7827. unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
  7828. CLI.CallConv, VT);
  7829. for (unsigned i = 0; i != NumRegs; ++i) {
  7830. ISD::InputArg MyFlags;
  7831. MyFlags.Flags = Flags;
  7832. MyFlags.VT = RegisterVT;
  7833. MyFlags.ArgVT = VT;
  7834. MyFlags.Used = CLI.IsReturnValueUsed;
  7835. if (CLI.RetTy->isPointerTy()) {
  7836. MyFlags.Flags.setPointer();
  7837. MyFlags.Flags.setPointerAddrSpace(
  7838. cast<PointerType>(CLI.RetTy)->getAddressSpace());
  7839. }
  7840. if (CLI.RetSExt)
  7841. MyFlags.Flags.setSExt();
  7842. if (CLI.RetZExt)
  7843. MyFlags.Flags.setZExt();
  7844. if (CLI.IsInReg)
  7845. MyFlags.Flags.setInReg();
  7846. CLI.Ins.push_back(MyFlags);
  7847. }
  7848. }
  7849. }
  7850. // We push in swifterror return as the last element of CLI.Ins.
  7851. ArgListTy &Args = CLI.getArgs();
  7852. if (supportSwiftError()) {
  7853. for (unsigned i = 0, e = Args.size(); i != e; ++i) {
  7854. if (Args[i].IsSwiftError) {
  7855. ISD::InputArg MyFlags;
  7856. MyFlags.VT = getPointerTy(DL);
  7857. MyFlags.ArgVT = EVT(getPointerTy(DL));
  7858. MyFlags.Flags.setSwiftError();
  7859. CLI.Ins.push_back(MyFlags);
  7860. }
  7861. }
  7862. }
  7863. // Handle all of the outgoing arguments.
  7864. CLI.Outs.clear();
  7865. CLI.OutVals.clear();
  7866. for (unsigned i = 0, e = Args.size(); i != e; ++i) {
  7867. SmallVector<EVT, 4> ValueVTs;
  7868. ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs);
  7869. // FIXME: Split arguments if CLI.IsPostTypeLegalization
  7870. Type *FinalType = Args[i].Ty;
  7871. if (Args[i].IsByVal)
  7872. FinalType = cast<PointerType>(Args[i].Ty)->getElementType();
  7873. bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
  7874. FinalType, CLI.CallConv, CLI.IsVarArg);
  7875. for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues;
  7876. ++Value) {
  7877. EVT VT = ValueVTs[Value];
  7878. Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext());
  7879. SDValue Op = SDValue(Args[i].Node.getNode(),
  7880. Args[i].Node.getResNo() + Value);
  7881. ISD::ArgFlagsTy Flags;
  7882. // Certain targets (such as MIPS), may have a different ABI alignment
  7883. // for a type depending on the context. Give the target a chance to
  7884. // specify the alignment it wants.
  7885. unsigned OriginalAlignment = getABIAlignmentForCallingConv(ArgTy, DL);
  7886. if (Args[i].Ty->isPointerTy()) {
  7887. Flags.setPointer();
  7888. Flags.setPointerAddrSpace(
  7889. cast<PointerType>(Args[i].Ty)->getAddressSpace());
  7890. }
  7891. if (Args[i].IsZExt)
  7892. Flags.setZExt();
  7893. if (Args[i].IsSExt)
  7894. Flags.setSExt();
  7895. if (Args[i].IsInReg) {
  7896. // If we are using vectorcall calling convention, a structure that is
  7897. // passed InReg - is surely an HVA
  7898. if (CLI.CallConv == CallingConv::X86_VectorCall &&
  7899. isa<StructType>(FinalType)) {
  7900. // The first value of a structure is marked
  7901. if (0 == Value)
  7902. Flags.setHvaStart();
  7903. Flags.setHva();
  7904. }
  7905. // Set InReg Flag
  7906. Flags.setInReg();
  7907. }
  7908. if (Args[i].IsSRet)
  7909. Flags.setSRet();
  7910. if (Args[i].IsSwiftSelf)
  7911. Flags.setSwiftSelf();
  7912. if (Args[i].IsSwiftError)
  7913. Flags.setSwiftError();
  7914. if (Args[i].IsByVal)
  7915. Flags.setByVal();
  7916. if (Args[i].IsInAlloca) {
  7917. Flags.setInAlloca();
  7918. // Set the byval flag for CCAssignFn callbacks that don't know about
  7919. // inalloca. This way we can know how many bytes we should've allocated
  7920. // and how many bytes a callee cleanup function will pop. If we port
  7921. // inalloca to more targets, we'll have to add custom inalloca handling
  7922. // in the various CC lowering callbacks.
  7923. Flags.setByVal();
  7924. }
  7925. if (Args[i].IsByVal || Args[i].IsInAlloca) {
  7926. PointerType *Ty = cast<PointerType>(Args[i].Ty);
  7927. Type *ElementTy = Ty->getElementType();
  7928. Flags.setByValSize(DL.getTypeAllocSize(ElementTy));
  7929. // For ByVal, alignment should come from FE. BE will guess if this
  7930. // info is not there but there are cases it cannot get right.
  7931. unsigned FrameAlign;
  7932. if (Args[i].Alignment)
  7933. FrameAlign = Args[i].Alignment;
  7934. else
  7935. FrameAlign = getByValTypeAlignment(ElementTy, DL);
  7936. Flags.setByValAlign(FrameAlign);
  7937. }
  7938. if (Args[i].IsNest)
  7939. Flags.setNest();
  7940. if (NeedsRegBlock)
  7941. Flags.setInConsecutiveRegs();
  7942. Flags.setOrigAlign(OriginalAlignment);
  7943. MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
  7944. CLI.CallConv, VT);
  7945. unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
  7946. CLI.CallConv, VT);
  7947. SmallVector<SDValue, 4> Parts(NumParts);
  7948. ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
  7949. if (Args[i].IsSExt)
  7950. ExtendKind = ISD::SIGN_EXTEND;
  7951. else if (Args[i].IsZExt)
  7952. ExtendKind = ISD::ZERO_EXTEND;
  7953. // Conservatively only handle 'returned' on non-vectors that can be lowered,
  7954. // for now.
  7955. if (Args[i].IsReturned && !Op.getValueType().isVector() &&
  7956. CanLowerReturn) {
  7957. assert(CLI.RetTy == Args[i].Ty && RetTys.size() == NumValues &&
  7958. "unexpected use of 'returned'");
  7959. // Before passing 'returned' to the target lowering code, ensure that
  7960. // either the register MVT and the actual EVT are the same size or that
  7961. // the return value and argument are extended in the same way; in these
  7962. // cases it's safe to pass the argument register value unchanged as the
  7963. // return register value (although it's at the target's option whether
  7964. // to do so)
  7965. // TODO: allow code generation to take advantage of partially preserved
  7966. // registers rather than clobbering the entire register when the
  7967. // parameter extension method is not compatible with the return
  7968. // extension method
  7969. if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) ||
  7970. (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt &&
  7971. CLI.RetZExt == Args[i].IsZExt))
  7972. Flags.setReturned();
  7973. }
  7974. getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT,
  7975. CLI.CS.getInstruction(), CLI.CallConv, ExtendKind);
  7976. for (unsigned j = 0; j != NumParts; ++j) {
  7977. // if it isn't first piece, alignment must be 1
  7978. ISD::OutputArg MyFlags(Flags, Parts[j].getValueType(), VT,
  7979. i < CLI.NumFixedArgs,
  7980. i, j*Parts[j].getValueType().getStoreSize());
  7981. if (NumParts > 1 && j == 0)
  7982. MyFlags.Flags.setSplit();
  7983. else if (j != 0) {
  7984. MyFlags.Flags.setOrigAlign(1);
  7985. if (j == NumParts - 1)
  7986. MyFlags.Flags.setSplitEnd();
  7987. }
  7988. CLI.Outs.push_back(MyFlags);
  7989. CLI.OutVals.push_back(Parts[j]);
  7990. }
  7991. if (NeedsRegBlock && Value == NumValues - 1)
  7992. CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast();
  7993. }
  7994. }
  7995. SmallVector<SDValue, 4> InVals;
  7996. CLI.Chain = LowerCall(CLI, InVals);
  7997. // Update CLI.InVals to use outside of this function.
  7998. CLI.InVals = InVals;
  7999. // Verify that the target's LowerCall behaved as expected.
  8000. assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other &&
  8001. "LowerCall didn't return a valid chain!");
  8002. assert((!CLI.IsTailCall || InVals.empty()) &&
  8003. "LowerCall emitted a return value for a tail call!");
  8004. assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) &&
  8005. "LowerCall didn't emit the correct number of values!");
  8006. // For a tail call, the return value is merely live-out and there aren't
  8007. // any nodes in the DAG representing it. Return a special value to
  8008. // indicate that a tail call has been emitted and no more Instructions
  8009. // should be processed in the current block.
  8010. if (CLI.IsTailCall) {
  8011. CLI.DAG.setRoot(CLI.Chain);
  8012. return std::make_pair(SDValue(), SDValue());
  8013. }
  8014. #ifndef NDEBUG
  8015. for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) {
  8016. assert(InVals[i].getNode() && "LowerCall emitted a null value!");
  8017. assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() &&
  8018. "LowerCall emitted a value with the wrong type!");
  8019. }
  8020. #endif
  8021. SmallVector<SDValue, 4> ReturnValues;
  8022. if (!CanLowerReturn) {
  8023. // The instruction result is the result of loading from the
  8024. // hidden sret parameter.
  8025. SmallVector<EVT, 1> PVTs;
  8026. Type *PtrRetTy = OrigRetTy->getPointerTo(DL.getAllocaAddrSpace());
  8027. ComputeValueVTs(*this, DL, PtrRetTy, PVTs);
  8028. assert(PVTs.size() == 1 && "Pointers should fit in one register");
  8029. EVT PtrVT = PVTs[0];
  8030. unsigned NumValues = RetTys.size();
  8031. ReturnValues.resize(NumValues);
  8032. SmallVector<SDValue, 4> Chains(NumValues);
  8033. // An aggregate return value cannot wrap around the address space, so
  8034. // offsets to its parts don't wrap either.
  8035. SDNodeFlags Flags;
  8036. Flags.setNoUnsignedWrap(true);
  8037. for (unsigned i = 0; i < NumValues; ++i) {
  8038. SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot,
  8039. CLI.DAG.getConstant(Offsets[i], CLI.DL,
  8040. PtrVT), Flags);
  8041. SDValue L = CLI.DAG.getLoad(
  8042. RetTys[i], CLI.DL, CLI.Chain, Add,
  8043. MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(),
  8044. DemoteStackIdx, Offsets[i]),
  8045. /* Alignment = */ 1);
  8046. ReturnValues[i] = L;
  8047. Chains[i] = L.getValue(1);
  8048. }
  8049. CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains);
  8050. } else {
  8051. // Collect the legal value parts into potentially illegal values
  8052. // that correspond to the original function's return values.
  8053. Optional<ISD::NodeType> AssertOp;
  8054. if (CLI.RetSExt)
  8055. AssertOp = ISD::AssertSext;
  8056. else if (CLI.RetZExt)
  8057. AssertOp = ISD::AssertZext;
  8058. unsigned CurReg = 0;
  8059. for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
  8060. EVT VT = RetTys[I];
  8061. MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
  8062. CLI.CallConv, VT);
  8063. unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
  8064. CLI.CallConv, VT);
  8065. ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg],
  8066. NumRegs, RegisterVT, VT, nullptr,
  8067. CLI.CallConv, AssertOp));
  8068. CurReg += NumRegs;
  8069. }
  8070. // For a function returning void, there is no return value. We can't create
  8071. // such a node, so we just return a null return value in that case. In
  8072. // that case, nothing will actually look at the value.
  8073. if (ReturnValues.empty())
  8074. return std::make_pair(SDValue(), CLI.Chain);
  8075. }
  8076. SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL,
  8077. CLI.DAG.getVTList(RetTys), ReturnValues);
  8078. return std::make_pair(Res, CLI.Chain);
  8079. }
  8080. void TargetLowering::LowerOperationWrapper(SDNode *N,
  8081. SmallVectorImpl<SDValue> &Results,
  8082. SelectionDAG &DAG) const {
  8083. if (SDValue Res = LowerOperation(SDValue(N, 0), DAG))
  8084. Results.push_back(Res);
  8085. }
  8086. SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
  8087. llvm_unreachable("LowerOperation not implemented for this target!");
  8088. }
  8089. void
  8090. SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) {
  8091. SDValue Op = getNonRegisterValue(V);
  8092. assert((Op.getOpcode() != ISD::CopyFromReg ||
  8093. cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
  8094. "Copy from a reg to the same reg!");
  8095. assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg");
  8096. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  8097. // If this is an InlineAsm we have to match the registers required, not the
  8098. // notional registers required by the type.
  8099. RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(),
  8100. None); // This is not an ABI copy.
  8101. SDValue Chain = DAG.getEntryNode();
  8102. ISD::NodeType ExtendType = (FuncInfo.PreferredExtendType.find(V) ==
  8103. FuncInfo.PreferredExtendType.end())
  8104. ? ISD::ANY_EXTEND
  8105. : FuncInfo.PreferredExtendType[V];
  8106. RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType);
  8107. PendingExports.push_back(Chain);
  8108. }
  8109. #include "llvm/CodeGen/SelectionDAGISel.h"
  8110. /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
  8111. /// entry block, return true. This includes arguments used by switches, since
  8112. /// the switch may expand into multiple basic blocks.
  8113. static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) {
  8114. // With FastISel active, we may be splitting blocks, so force creation
  8115. // of virtual registers for all non-dead arguments.
  8116. if (FastISel)
  8117. return A->use_empty();
  8118. const BasicBlock &Entry = A->getParent()->front();
  8119. for (const User *U : A->users())
  8120. if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U))
  8121. return false; // Use not in entry block.
  8122. return true;
  8123. }
  8124. using ArgCopyElisionMapTy =
  8125. DenseMap<const Argument *,
  8126. std::pair<const AllocaInst *, const StoreInst *>>;
  8127. /// Scan the entry block of the function in FuncInfo for arguments that look
  8128. /// like copies into a local alloca. Record any copied arguments in
  8129. /// ArgCopyElisionCandidates.
  8130. static void
  8131. findArgumentCopyElisionCandidates(const DataLayout &DL,
  8132. FunctionLoweringInfo *FuncInfo,
  8133. ArgCopyElisionMapTy &ArgCopyElisionCandidates) {
  8134. // Record the state of every static alloca used in the entry block. Argument
  8135. // allocas are all used in the entry block, so we need approximately as many
  8136. // entries as we have arguments.
  8137. enum StaticAllocaInfo { Unknown, Clobbered, Elidable };
  8138. SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas;
  8139. unsigned NumArgs = FuncInfo->Fn->arg_size();
  8140. StaticAllocas.reserve(NumArgs * 2);
  8141. auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * {
  8142. if (!V)
  8143. return nullptr;
  8144. V = V->stripPointerCasts();
  8145. const auto *AI = dyn_cast<AllocaInst>(V);
  8146. if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI))
  8147. return nullptr;
  8148. auto Iter = StaticAllocas.insert({AI, Unknown});
  8149. return &Iter.first->second;
  8150. };
  8151. // Look for stores of arguments to static allocas. Look through bitcasts and
  8152. // GEPs to handle type coercions, as long as the alloca is fully initialized
  8153. // by the store. Any non-store use of an alloca escapes it and any subsequent
  8154. // unanalyzed store might write it.
  8155. // FIXME: Handle structs initialized with multiple stores.
  8156. for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) {
  8157. // Look for stores, and handle non-store uses conservatively.
  8158. const auto *SI = dyn_cast<StoreInst>(&I);
  8159. if (!SI) {
  8160. // We will look through cast uses, so ignore them completely.
  8161. if (I.isCast())
  8162. continue;
  8163. // Ignore debug info intrinsics, they don't escape or store to allocas.
  8164. if (isa<DbgInfoIntrinsic>(I))
  8165. continue;
  8166. // This is an unknown instruction. Assume it escapes or writes to all
  8167. // static alloca operands.
  8168. for (const Use &U : I.operands()) {
  8169. if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U))
  8170. *Info = StaticAllocaInfo::Clobbered;
  8171. }
  8172. continue;
  8173. }
  8174. // If the stored value is a static alloca, mark it as escaped.
  8175. if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand()))
  8176. *Info = StaticAllocaInfo::Clobbered;
  8177. // Check if the destination is a static alloca.
  8178. const Value *Dst = SI->getPointerOperand()->stripPointerCasts();
  8179. StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst);
  8180. if (!Info)
  8181. continue;
  8182. const AllocaInst *AI = cast<AllocaInst>(Dst);
  8183. // Skip allocas that have been initialized or clobbered.
  8184. if (*Info != StaticAllocaInfo::Unknown)
  8185. continue;
  8186. // Check if the stored value is an argument, and that this store fully
  8187. // initializes the alloca. Don't elide copies from the same argument twice.
  8188. const Value *Val = SI->getValueOperand()->stripPointerCasts();
  8189. const auto *Arg = dyn_cast<Argument>(Val);
  8190. if (!Arg || Arg->hasInAllocaAttr() || Arg->hasByValAttr() ||
  8191. Arg->getType()->isEmptyTy() ||
  8192. DL.getTypeStoreSize(Arg->getType()) !=
  8193. DL.getTypeAllocSize(AI->getAllocatedType()) ||
  8194. ArgCopyElisionCandidates.count(Arg)) {
  8195. *Info = StaticAllocaInfo::Clobbered;
  8196. continue;
  8197. }
  8198. LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI
  8199. << '\n');
  8200. // Mark this alloca and store for argument copy elision.
  8201. *Info = StaticAllocaInfo::Elidable;
  8202. ArgCopyElisionCandidates.insert({Arg, {AI, SI}});
  8203. // Stop scanning if we've seen all arguments. This will happen early in -O0
  8204. // builds, which is useful, because -O0 builds have large entry blocks and
  8205. // many allocas.
  8206. if (ArgCopyElisionCandidates.size() == NumArgs)
  8207. break;
  8208. }
  8209. }
  8210. /// Try to elide argument copies from memory into a local alloca. Succeeds if
  8211. /// ArgVal is a load from a suitable fixed stack object.
  8212. static void tryToElideArgumentCopy(
  8213. FunctionLoweringInfo *FuncInfo, SmallVectorImpl<SDValue> &Chains,
  8214. DenseMap<int, int> &ArgCopyElisionFrameIndexMap,
  8215. SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs,
  8216. ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg,
  8217. SDValue ArgVal, bool &ArgHasUses) {
  8218. // Check if this is a load from a fixed stack object.
  8219. auto *LNode = dyn_cast<LoadSDNode>(ArgVal);
  8220. if (!LNode)
  8221. return;
  8222. auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode());
  8223. if (!FINode)
  8224. return;
  8225. // Check that the fixed stack object is the right size and alignment.
  8226. // Look at the alignment that the user wrote on the alloca instead of looking
  8227. // at the stack object.
  8228. auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg);
  8229. assert(ArgCopyIter != ArgCopyElisionCandidates.end());
  8230. const AllocaInst *AI = ArgCopyIter->second.first;
  8231. int FixedIndex = FINode->getIndex();
  8232. int &AllocaIndex = FuncInfo->StaticAllocaMap[AI];
  8233. int OldIndex = AllocaIndex;
  8234. MachineFrameInfo &MFI = FuncInfo->MF->getFrameInfo();
  8235. if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) {
  8236. LLVM_DEBUG(
  8237. dbgs() << " argument copy elision failed due to bad fixed stack "
  8238. "object size\n");
  8239. return;
  8240. }
  8241. unsigned RequiredAlignment = AI->getAlignment();
  8242. if (!RequiredAlignment) {
  8243. RequiredAlignment = FuncInfo->MF->getDataLayout().getABITypeAlignment(
  8244. AI->getAllocatedType());
  8245. }
  8246. if (MFI.getObjectAlignment(FixedIndex) < RequiredAlignment) {
  8247. LLVM_DEBUG(dbgs() << " argument copy elision failed: alignment of alloca "
  8248. "greater than stack argument alignment ("
  8249. << RequiredAlignment << " vs "
  8250. << MFI.getObjectAlignment(FixedIndex) << ")\n");
  8251. return;
  8252. }
  8253. // Perform the elision. Delete the old stack object and replace its only use
  8254. // in the variable info map. Mark the stack object as mutable.
  8255. LLVM_DEBUG({
  8256. dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n'
  8257. << " Replacing frame index " << OldIndex << " with " << FixedIndex
  8258. << '\n';
  8259. });
  8260. MFI.RemoveStackObject(OldIndex);
  8261. MFI.setIsImmutableObjectIndex(FixedIndex, false);
  8262. AllocaIndex = FixedIndex;
  8263. ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex});
  8264. Chains.push_back(ArgVal.getValue(1));
  8265. // Avoid emitting code for the store implementing the copy.
  8266. const StoreInst *SI = ArgCopyIter->second.second;
  8267. ElidedArgCopyInstrs.insert(SI);
  8268. // Check for uses of the argument again so that we can avoid exporting ArgVal
  8269. // if it is't used by anything other than the store.
  8270. for (const Value *U : Arg.users()) {
  8271. if (U != SI) {
  8272. ArgHasUses = true;
  8273. break;
  8274. }
  8275. }
  8276. }
  8277. void SelectionDAGISel::LowerArguments(const Function &F) {
  8278. SelectionDAG &DAG = SDB->DAG;
  8279. SDLoc dl = SDB->getCurSDLoc();
  8280. const DataLayout &DL = DAG.getDataLayout();
  8281. SmallVector<ISD::InputArg, 16> Ins;
  8282. if (!FuncInfo->CanLowerReturn) {
  8283. // Put in an sret pointer parameter before all the other parameters.
  8284. SmallVector<EVT, 1> ValueVTs;
  8285. ComputeValueVTs(*TLI, DAG.getDataLayout(),
  8286. F.getReturnType()->getPointerTo(
  8287. DAG.getDataLayout().getAllocaAddrSpace()),
  8288. ValueVTs);
  8289. // NOTE: Assuming that a pointer will never break down to more than one VT
  8290. // or one register.
  8291. ISD::ArgFlagsTy Flags;
  8292. Flags.setSRet();
  8293. MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]);
  8294. ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true,
  8295. ISD::InputArg::NoArgIndex, 0);
  8296. Ins.push_back(RetArg);
  8297. }
  8298. // Look for stores of arguments to static allocas. Mark such arguments with a
  8299. // flag to ask the target to give us the memory location of that argument if
  8300. // available.
  8301. ArgCopyElisionMapTy ArgCopyElisionCandidates;
  8302. findArgumentCopyElisionCandidates(DL, FuncInfo, ArgCopyElisionCandidates);
  8303. // Set up the incoming argument description vector.
  8304. for (const Argument &Arg : F.args()) {
  8305. unsigned ArgNo = Arg.getArgNo();
  8306. SmallVector<EVT, 4> ValueVTs;
  8307. ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
  8308. bool isArgValueUsed = !Arg.use_empty();
  8309. unsigned PartBase = 0;
  8310. Type *FinalType = Arg.getType();
  8311. if (Arg.hasAttribute(Attribute::ByVal))
  8312. FinalType = cast<PointerType>(FinalType)->getElementType();
  8313. bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters(
  8314. FinalType, F.getCallingConv(), F.isVarArg());
  8315. for (unsigned Value = 0, NumValues = ValueVTs.size();
  8316. Value != NumValues; ++Value) {
  8317. EVT VT = ValueVTs[Value];
  8318. Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
  8319. ISD::ArgFlagsTy Flags;
  8320. // Certain targets (such as MIPS), may have a different ABI alignment
  8321. // for a type depending on the context. Give the target a chance to
  8322. // specify the alignment it wants.
  8323. unsigned OriginalAlignment =
  8324. TLI->getABIAlignmentForCallingConv(ArgTy, DL);
  8325. if (Arg.getType()->isPointerTy()) {
  8326. Flags.setPointer();
  8327. Flags.setPointerAddrSpace(
  8328. cast<PointerType>(Arg.getType())->getAddressSpace());
  8329. }
  8330. if (Arg.hasAttribute(Attribute::ZExt))
  8331. Flags.setZExt();
  8332. if (Arg.hasAttribute(Attribute::SExt))
  8333. Flags.setSExt();
  8334. if (Arg.hasAttribute(Attribute::InReg)) {
  8335. // If we are using vectorcall calling convention, a structure that is
  8336. // passed InReg - is surely an HVA
  8337. if (F.getCallingConv() == CallingConv::X86_VectorCall &&
  8338. isa<StructType>(Arg.getType())) {
  8339. // The first value of a structure is marked
  8340. if (0 == Value)
  8341. Flags.setHvaStart();
  8342. Flags.setHva();
  8343. }
  8344. // Set InReg Flag
  8345. Flags.setInReg();
  8346. }
  8347. if (Arg.hasAttribute(Attribute::StructRet))
  8348. Flags.setSRet();
  8349. if (Arg.hasAttribute(Attribute::SwiftSelf))
  8350. Flags.setSwiftSelf();
  8351. if (Arg.hasAttribute(Attribute::SwiftError))
  8352. Flags.setSwiftError();
  8353. if (Arg.hasAttribute(Attribute::ByVal))
  8354. Flags.setByVal();
  8355. if (Arg.hasAttribute(Attribute::InAlloca)) {
  8356. Flags.setInAlloca();
  8357. // Set the byval flag for CCAssignFn callbacks that don't know about
  8358. // inalloca. This way we can know how many bytes we should've allocated
  8359. // and how many bytes a callee cleanup function will pop. If we port
  8360. // inalloca to more targets, we'll have to add custom inalloca handling
  8361. // in the various CC lowering callbacks.
  8362. Flags.setByVal();
  8363. }
  8364. if (F.getCallingConv() == CallingConv::X86_INTR) {
  8365. // IA Interrupt passes frame (1st parameter) by value in the stack.
  8366. if (ArgNo == 0)
  8367. Flags.setByVal();
  8368. }
  8369. if (Flags.isByVal() || Flags.isInAlloca()) {
  8370. PointerType *Ty = cast<PointerType>(Arg.getType());
  8371. Type *ElementTy = Ty->getElementType();
  8372. Flags.setByValSize(DL.getTypeAllocSize(ElementTy));
  8373. // For ByVal, alignment should be passed from FE. BE will guess if
  8374. // this info is not there but there are cases it cannot get right.
  8375. unsigned FrameAlign;
  8376. if (Arg.getParamAlignment())
  8377. FrameAlign = Arg.getParamAlignment();
  8378. else
  8379. FrameAlign = TLI->getByValTypeAlignment(ElementTy, DL);
  8380. Flags.setByValAlign(FrameAlign);
  8381. }
  8382. if (Arg.hasAttribute(Attribute::Nest))
  8383. Flags.setNest();
  8384. if (NeedsRegBlock)
  8385. Flags.setInConsecutiveRegs();
  8386. Flags.setOrigAlign(OriginalAlignment);
  8387. if (ArgCopyElisionCandidates.count(&Arg))
  8388. Flags.setCopyElisionCandidate();
  8389. MVT RegisterVT = TLI->getRegisterTypeForCallingConv(
  8390. *CurDAG->getContext(), F.getCallingConv(), VT);
  8391. unsigned NumRegs = TLI->getNumRegistersForCallingConv(
  8392. *CurDAG->getContext(), F.getCallingConv(), VT);
  8393. for (unsigned i = 0; i != NumRegs; ++i) {
  8394. ISD::InputArg MyFlags(Flags, RegisterVT, VT, isArgValueUsed,
  8395. ArgNo, PartBase+i*RegisterVT.getStoreSize());
  8396. if (NumRegs > 1 && i == 0)
  8397. MyFlags.Flags.setSplit();
  8398. // if it isn't first piece, alignment must be 1
  8399. else if (i > 0) {
  8400. MyFlags.Flags.setOrigAlign(1);
  8401. if (i == NumRegs - 1)
  8402. MyFlags.Flags.setSplitEnd();
  8403. }
  8404. Ins.push_back(MyFlags);
  8405. }
  8406. if (NeedsRegBlock && Value == NumValues - 1)
  8407. Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast();
  8408. PartBase += VT.getStoreSize();
  8409. }
  8410. }
  8411. // Call the target to set up the argument values.
  8412. SmallVector<SDValue, 8> InVals;
  8413. SDValue NewRoot = TLI->LowerFormalArguments(
  8414. DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals);
  8415. // Verify that the target's LowerFormalArguments behaved as expected.
  8416. assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
  8417. "LowerFormalArguments didn't return a valid chain!");
  8418. assert(InVals.size() == Ins.size() &&
  8419. "LowerFormalArguments didn't emit the correct number of values!");
  8420. LLVM_DEBUG({
  8421. for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
  8422. assert(InVals[i].getNode() &&
  8423. "LowerFormalArguments emitted a null value!");
  8424. assert(EVT(Ins[i].VT) == InVals[i].getValueType() &&
  8425. "LowerFormalArguments emitted a value with the wrong type!");
  8426. }
  8427. });
  8428. // Update the DAG with the new chain value resulting from argument lowering.
  8429. DAG.setRoot(NewRoot);
  8430. // Set up the argument values.
  8431. unsigned i = 0;
  8432. if (!FuncInfo->CanLowerReturn) {
  8433. // Create a virtual register for the sret pointer, and put in a copy
  8434. // from the sret argument into it.
  8435. SmallVector<EVT, 1> ValueVTs;
  8436. ComputeValueVTs(*TLI, DAG.getDataLayout(),
  8437. F.getReturnType()->getPointerTo(
  8438. DAG.getDataLayout().getAllocaAddrSpace()),
  8439. ValueVTs);
  8440. MVT VT = ValueVTs[0].getSimpleVT();
  8441. MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
  8442. Optional<ISD::NodeType> AssertOp = None;
  8443. SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT,
  8444. nullptr, F.getCallingConv(), AssertOp);
  8445. MachineFunction& MF = SDB->DAG.getMachineFunction();
  8446. MachineRegisterInfo& RegInfo = MF.getRegInfo();
  8447. unsigned SRetReg = RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT));
  8448. FuncInfo->DemoteRegister = SRetReg;
  8449. NewRoot =
  8450. SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue);
  8451. DAG.setRoot(NewRoot);
  8452. // i indexes lowered arguments. Bump it past the hidden sret argument.
  8453. ++i;
  8454. }
  8455. SmallVector<SDValue, 4> Chains;
  8456. DenseMap<int, int> ArgCopyElisionFrameIndexMap;
  8457. for (const Argument &Arg : F.args()) {
  8458. SmallVector<SDValue, 4> ArgValues;
  8459. SmallVector<EVT, 4> ValueVTs;
  8460. ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
  8461. unsigned NumValues = ValueVTs.size();
  8462. if (NumValues == 0)
  8463. continue;
  8464. bool ArgHasUses = !Arg.use_empty();
  8465. // Elide the copying store if the target loaded this argument from a
  8466. // suitable fixed stack object.
  8467. if (Ins[i].Flags.isCopyElisionCandidate()) {
  8468. tryToElideArgumentCopy(FuncInfo, Chains, ArgCopyElisionFrameIndexMap,
  8469. ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg,
  8470. InVals[i], ArgHasUses);
  8471. }
  8472. // If this argument is unused then remember its value. It is used to generate
  8473. // debugging information.
  8474. bool isSwiftErrorArg =
  8475. TLI->supportSwiftError() &&
  8476. Arg.hasAttribute(Attribute::SwiftError);
  8477. if (!ArgHasUses && !isSwiftErrorArg) {
  8478. SDB->setUnusedArgValue(&Arg, InVals[i]);
  8479. // Also remember any frame index for use in FastISel.
  8480. if (FrameIndexSDNode *FI =
  8481. dyn_cast<FrameIndexSDNode>(InVals[i].getNode()))
  8482. FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
  8483. }
  8484. for (unsigned Val = 0; Val != NumValues; ++Val) {
  8485. EVT VT = ValueVTs[Val];
  8486. MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(),
  8487. F.getCallingConv(), VT);
  8488. unsigned NumParts = TLI->getNumRegistersForCallingConv(
  8489. *CurDAG->getContext(), F.getCallingConv(), VT);
  8490. // Even an apparant 'unused' swifterror argument needs to be returned. So
  8491. // we do generate a copy for it that can be used on return from the
  8492. // function.
  8493. if (ArgHasUses || isSwiftErrorArg) {
  8494. Optional<ISD::NodeType> AssertOp;
  8495. if (Arg.hasAttribute(Attribute::SExt))
  8496. AssertOp = ISD::AssertSext;
  8497. else if (Arg.hasAttribute(Attribute::ZExt))
  8498. AssertOp = ISD::AssertZext;
  8499. ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts,
  8500. PartVT, VT, nullptr,
  8501. F.getCallingConv(), AssertOp));
  8502. }
  8503. i += NumParts;
  8504. }
  8505. // We don't need to do anything else for unused arguments.
  8506. if (ArgValues.empty())
  8507. continue;
  8508. // Note down frame index.
  8509. if (FrameIndexSDNode *FI =
  8510. dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode()))
  8511. FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
  8512. SDValue Res = DAG.getMergeValues(makeArrayRef(ArgValues.data(), NumValues),
  8513. SDB->getCurSDLoc());
  8514. SDB->setValue(&Arg, Res);
  8515. if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) {
  8516. // We want to associate the argument with the frame index, among
  8517. // involved operands, that correspond to the lowest address. The
  8518. // getCopyFromParts function, called earlier, is swapping the order of
  8519. // the operands to BUILD_PAIR depending on endianness. The result of
  8520. // that swapping is that the least significant bits of the argument will
  8521. // be in the first operand of the BUILD_PAIR node, and the most
  8522. // significant bits will be in the second operand.
  8523. unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0;
  8524. if (LoadSDNode *LNode =
  8525. dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode()))
  8526. if (FrameIndexSDNode *FI =
  8527. dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
  8528. FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
  8529. }
  8530. // Update the SwiftErrorVRegDefMap.
  8531. if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) {
  8532. unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
  8533. if (TargetRegisterInfo::isVirtualRegister(Reg))
  8534. FuncInfo->setCurrentSwiftErrorVReg(FuncInfo->MBB,
  8535. FuncInfo->SwiftErrorArg, Reg);
  8536. }
  8537. // If this argument is live outside of the entry block, insert a copy from
  8538. // wherever we got it to the vreg that other BB's will reference it as.
  8539. if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::CopyFromReg) {
  8540. // If we can, though, try to skip creating an unnecessary vreg.
  8541. // FIXME: This isn't very clean... it would be nice to make this more
  8542. // general. It's also subtly incompatible with the hacks FastISel
  8543. // uses with vregs.
  8544. unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
  8545. if (TargetRegisterInfo::isVirtualRegister(Reg)) {
  8546. FuncInfo->ValueMap[&Arg] = Reg;
  8547. continue;
  8548. }
  8549. }
  8550. if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) {
  8551. FuncInfo->InitializeRegForValue(&Arg);
  8552. SDB->CopyToExportRegsIfNeeded(&Arg);
  8553. }
  8554. }
  8555. if (!Chains.empty()) {
  8556. Chains.push_back(NewRoot);
  8557. NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
  8558. }
  8559. DAG.setRoot(NewRoot);
  8560. assert(i == InVals.size() && "Argument register count mismatch!");
  8561. // If any argument copy elisions occurred and we have debug info, update the
  8562. // stale frame indices used in the dbg.declare variable info table.
  8563. MachineFunction::VariableDbgInfoMapTy &DbgDeclareInfo = MF->getVariableDbgInfo();
  8564. if (!DbgDeclareInfo.empty() && !ArgCopyElisionFrameIndexMap.empty()) {
  8565. for (MachineFunction::VariableDbgInfo &VI : DbgDeclareInfo) {
  8566. auto I = ArgCopyElisionFrameIndexMap.find(VI.Slot);
  8567. if (I != ArgCopyElisionFrameIndexMap.end())
  8568. VI.Slot = I->second;
  8569. }
  8570. }
  8571. // Finally, if the target has anything special to do, allow it to do so.
  8572. EmitFunctionEntryCode();
  8573. }
  8574. /// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
  8575. /// ensure constants are generated when needed. Remember the virtual registers
  8576. /// that need to be added to the Machine PHI nodes as input. We cannot just
  8577. /// directly add them, because expansion might result in multiple MBB's for one
  8578. /// BB. As such, the start of the BB might correspond to a different MBB than
  8579. /// the end.
  8580. void
  8581. SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
  8582. const Instruction *TI = LLVMBB->getTerminator();
  8583. SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
  8584. // Check PHI nodes in successors that expect a value to be available from this
  8585. // block.
  8586. for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
  8587. const BasicBlock *SuccBB = TI->getSuccessor(succ);
  8588. if (!isa<PHINode>(SuccBB->begin())) continue;
  8589. MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
  8590. // If this terminator has multiple identical successors (common for
  8591. // switches), only handle each succ once.
  8592. if (!SuccsHandled.insert(SuccMBB).second)
  8593. continue;
  8594. MachineBasicBlock::iterator MBBI = SuccMBB->begin();
  8595. // At this point we know that there is a 1-1 correspondence between LLVM PHI
  8596. // nodes and Machine PHI nodes, but the incoming operands have not been
  8597. // emitted yet.
  8598. for (const PHINode &PN : SuccBB->phis()) {
  8599. // Ignore dead phi's.
  8600. if (PN.use_empty())
  8601. continue;
  8602. // Skip empty types
  8603. if (PN.getType()->isEmptyTy())
  8604. continue;
  8605. unsigned Reg;
  8606. const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB);
  8607. if (const Constant *C = dyn_cast<Constant>(PHIOp)) {
  8608. unsigned &RegOut = ConstantsOut[C];
  8609. if (RegOut == 0) {
  8610. RegOut = FuncInfo.CreateRegs(C->getType());
  8611. CopyValueToVirtualRegister(C, RegOut);
  8612. }
  8613. Reg = RegOut;
  8614. } else {
  8615. DenseMap<const Value *, unsigned>::iterator I =
  8616. FuncInfo.ValueMap.find(PHIOp);
  8617. if (I != FuncInfo.ValueMap.end())
  8618. Reg = I->second;
  8619. else {
  8620. assert(isa<AllocaInst>(PHIOp) &&
  8621. FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
  8622. "Didn't codegen value into a register!??");
  8623. Reg = FuncInfo.CreateRegs(PHIOp->getType());
  8624. CopyValueToVirtualRegister(PHIOp, Reg);
  8625. }
  8626. }
  8627. // Remember that this register needs to added to the machine PHI node as
  8628. // the input for this MBB.
  8629. SmallVector<EVT, 4> ValueVTs;
  8630. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  8631. ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs);
  8632. for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
  8633. EVT VT = ValueVTs[vti];
  8634. unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT);
  8635. for (unsigned i = 0, e = NumRegisters; i != e; ++i)
  8636. FuncInfo.PHINodesToUpdate.push_back(
  8637. std::make_pair(&*MBBI++, Reg + i));
  8638. Reg += NumRegisters;
  8639. }
  8640. }
  8641. }
  8642. ConstantsOut.clear();
  8643. }
  8644. /// Add a successor MBB to ParentMBB< creating a new MachineBB for BB if SuccMBB
  8645. /// is 0.
  8646. MachineBasicBlock *
  8647. SelectionDAGBuilder::StackProtectorDescriptor::
  8648. AddSuccessorMBB(const BasicBlock *BB,
  8649. MachineBasicBlock *ParentMBB,
  8650. bool IsLikely,
  8651. MachineBasicBlock *SuccMBB) {
  8652. // If SuccBB has not been created yet, create it.
  8653. if (!SuccMBB) {
  8654. MachineFunction *MF = ParentMBB->getParent();
  8655. MachineFunction::iterator BBI(ParentMBB);
  8656. SuccMBB = MF->CreateMachineBasicBlock(BB);
  8657. MF->insert(++BBI, SuccMBB);
  8658. }
  8659. // Add it as a successor of ParentMBB.
  8660. ParentMBB->addSuccessor(
  8661. SuccMBB, BranchProbabilityInfo::getBranchProbStackProtector(IsLikely));
  8662. return SuccMBB;
  8663. }
  8664. MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) {
  8665. MachineFunction::iterator I(MBB);
  8666. if (++I == FuncInfo.MF->end())
  8667. return nullptr;
  8668. return &*I;
  8669. }
  8670. /// During lowering new call nodes can be created (such as memset, etc.).
  8671. /// Those will become new roots of the current DAG, but complications arise
  8672. /// when they are tail calls. In such cases, the call lowering will update
  8673. /// the root, but the builder still needs to know that a tail call has been
  8674. /// lowered in order to avoid generating an additional return.
  8675. void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) {
  8676. // If the node is null, we do have a tail call.
  8677. if (MaybeTC.getNode() != nullptr)
  8678. DAG.setRoot(MaybeTC);
  8679. else
  8680. HasTailCall = true;
  8681. }
  8682. uint64_t
  8683. SelectionDAGBuilder::getJumpTableRange(const CaseClusterVector &Clusters,
  8684. unsigned First, unsigned Last) const {
  8685. assert(Last >= First);
  8686. const APInt &LowCase = Clusters[First].Low->getValue();
  8687. const APInt &HighCase = Clusters[Last].High->getValue();
  8688. assert(LowCase.getBitWidth() == HighCase.getBitWidth());
  8689. // FIXME: A range of consecutive cases has 100% density, but only requires one
  8690. // comparison to lower. We should discriminate against such consecutive ranges
  8691. // in jump tables.
  8692. return (HighCase - LowCase).getLimitedValue((UINT64_MAX - 1) / 100) + 1;
  8693. }
  8694. uint64_t SelectionDAGBuilder::getJumpTableNumCases(
  8695. const SmallVectorImpl<unsigned> &TotalCases, unsigned First,
  8696. unsigned Last) const {
  8697. assert(Last >= First);
  8698. assert(TotalCases[Last] >= TotalCases[First]);
  8699. uint64_t NumCases =
  8700. TotalCases[Last] - (First == 0 ? 0 : TotalCases[First - 1]);
  8701. return NumCases;
  8702. }
  8703. bool SelectionDAGBuilder::buildJumpTable(const CaseClusterVector &Clusters,
  8704. unsigned First, unsigned Last,
  8705. const SwitchInst *SI,
  8706. MachineBasicBlock *DefaultMBB,
  8707. CaseCluster &JTCluster) {
  8708. assert(First <= Last);
  8709. auto Prob = BranchProbability::getZero();
  8710. unsigned NumCmps = 0;
  8711. std::vector<MachineBasicBlock*> Table;
  8712. DenseMap<MachineBasicBlock*, BranchProbability> JTProbs;
  8713. // Initialize probabilities in JTProbs.
  8714. for (unsigned I = First; I <= Last; ++I)
  8715. JTProbs[Clusters[I].MBB] = BranchProbability::getZero();
  8716. for (unsigned I = First; I <= Last; ++I) {
  8717. assert(Clusters[I].Kind == CC_Range);
  8718. Prob += Clusters[I].Prob;
  8719. const APInt &Low = Clusters[I].Low->getValue();
  8720. const APInt &High = Clusters[I].High->getValue();
  8721. NumCmps += (Low == High) ? 1 : 2;
  8722. if (I != First) {
  8723. // Fill the gap between this and the previous cluster.
  8724. const APInt &PreviousHigh = Clusters[I - 1].High->getValue();
  8725. assert(PreviousHigh.slt(Low));
  8726. uint64_t Gap = (Low - PreviousHigh).getLimitedValue() - 1;
  8727. for (uint64_t J = 0; J < Gap; J++)
  8728. Table.push_back(DefaultMBB);
  8729. }
  8730. uint64_t ClusterSize = (High - Low).getLimitedValue() + 1;
  8731. for (uint64_t J = 0; J < ClusterSize; ++J)
  8732. Table.push_back(Clusters[I].MBB);
  8733. JTProbs[Clusters[I].MBB] += Clusters[I].Prob;
  8734. }
  8735. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  8736. unsigned NumDests = JTProbs.size();
  8737. if (TLI.isSuitableForBitTests(
  8738. NumDests, NumCmps, Clusters[First].Low->getValue(),
  8739. Clusters[Last].High->getValue(), DAG.getDataLayout())) {
  8740. // Clusters[First..Last] should be lowered as bit tests instead.
  8741. return false;
  8742. }
  8743. // Create the MBB that will load from and jump through the table.
  8744. // Note: We create it here, but it's not inserted into the function yet.
  8745. MachineFunction *CurMF = FuncInfo.MF;
  8746. MachineBasicBlock *JumpTableMBB =
  8747. CurMF->CreateMachineBasicBlock(SI->getParent());
  8748. // Add successors. Note: use table order for determinism.
  8749. SmallPtrSet<MachineBasicBlock *, 8> Done;
  8750. for (MachineBasicBlock *Succ : Table) {
  8751. if (Done.count(Succ))
  8752. continue;
  8753. addSuccessorWithProb(JumpTableMBB, Succ, JTProbs[Succ]);
  8754. Done.insert(Succ);
  8755. }
  8756. JumpTableMBB->normalizeSuccProbs();
  8757. unsigned JTI = CurMF->getOrCreateJumpTableInfo(TLI.getJumpTableEncoding())
  8758. ->createJumpTableIndex(Table);
  8759. // Set up the jump table info.
  8760. JumpTable JT(-1U, JTI, JumpTableMBB, nullptr);
  8761. JumpTableHeader JTH(Clusters[First].Low->getValue(),
  8762. Clusters[Last].High->getValue(), SI->getCondition(),
  8763. nullptr, false);
  8764. JTCases.emplace_back(std::move(JTH), std::move(JT));
  8765. JTCluster = CaseCluster::jumpTable(Clusters[First].Low, Clusters[Last].High,
  8766. JTCases.size() - 1, Prob);
  8767. return true;
  8768. }
  8769. void SelectionDAGBuilder::findJumpTables(CaseClusterVector &Clusters,
  8770. const SwitchInst *SI,
  8771. MachineBasicBlock *DefaultMBB) {
  8772. #ifndef NDEBUG
  8773. // Clusters must be non-empty, sorted, and only contain Range clusters.
  8774. assert(!Clusters.empty());
  8775. for (CaseCluster &C : Clusters)
  8776. assert(C.Kind == CC_Range);
  8777. for (unsigned i = 1, e = Clusters.size(); i < e; ++i)
  8778. assert(Clusters[i - 1].High->getValue().slt(Clusters[i].Low->getValue()));
  8779. #endif
  8780. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  8781. if (!TLI.areJTsAllowed(SI->getParent()->getParent()))
  8782. return;
  8783. const int64_t N = Clusters.size();
  8784. const unsigned MinJumpTableEntries = TLI.getMinimumJumpTableEntries();
  8785. const unsigned SmallNumberOfEntries = MinJumpTableEntries / 2;
  8786. if (N < 2 || N < MinJumpTableEntries)
  8787. return;
  8788. // TotalCases[i]: Total nbr of cases in Clusters[0..i].
  8789. SmallVector<unsigned, 8> TotalCases(N);
  8790. for (unsigned i = 0; i < N; ++i) {
  8791. const APInt &Hi = Clusters[i].High->getValue();
  8792. const APInt &Lo = Clusters[i].Low->getValue();
  8793. TotalCases[i] = (Hi - Lo).getLimitedValue() + 1;
  8794. if (i != 0)
  8795. TotalCases[i] += TotalCases[i - 1];
  8796. }
  8797. // Cheap case: the whole range may be suitable for jump table.
  8798. uint64_t Range = getJumpTableRange(Clusters,0, N - 1);
  8799. uint64_t NumCases = getJumpTableNumCases(TotalCases, 0, N - 1);
  8800. assert(NumCases < UINT64_MAX / 100);
  8801. assert(Range >= NumCases);
  8802. if (TLI.isSuitableForJumpTable(SI, NumCases, Range)) {
  8803. CaseCluster JTCluster;
  8804. if (buildJumpTable(Clusters, 0, N - 1, SI, DefaultMBB, JTCluster)) {
  8805. Clusters[0] = JTCluster;
  8806. Clusters.resize(1);
  8807. return;
  8808. }
  8809. }
  8810. // The algorithm below is not suitable for -O0.
  8811. if (TM.getOptLevel() == CodeGenOpt::None)
  8812. return;
  8813. // Split Clusters into minimum number of dense partitions. The algorithm uses
  8814. // the same idea as Kannan & Proebsting "Correction to 'Producing Good Code
  8815. // for the Case Statement'" (1994), but builds the MinPartitions array in
  8816. // reverse order to make it easier to reconstruct the partitions in ascending
  8817. // order. In the choice between two optimal partitionings, it picks the one
  8818. // which yields more jump tables.
  8819. // MinPartitions[i] is the minimum nbr of partitions of Clusters[i..N-1].
  8820. SmallVector<unsigned, 8> MinPartitions(N);
  8821. // LastElement[i] is the last element of the partition starting at i.
  8822. SmallVector<unsigned, 8> LastElement(N);
  8823. // PartitionsScore[i] is used to break ties when choosing between two
  8824. // partitionings resulting in the same number of partitions.
  8825. SmallVector<unsigned, 8> PartitionsScore(N);
  8826. // For PartitionsScore, a small number of comparisons is considered as good as
  8827. // a jump table and a single comparison is considered better than a jump
  8828. // table.
  8829. enum PartitionScores : unsigned {
  8830. NoTable = 0,
  8831. Table = 1,
  8832. FewCases = 1,
  8833. SingleCase = 2
  8834. };
  8835. // Base case: There is only one way to partition Clusters[N-1].
  8836. MinPartitions[N - 1] = 1;
  8837. LastElement[N - 1] = N - 1;
  8838. PartitionsScore[N - 1] = PartitionScores::SingleCase;
  8839. // Note: loop indexes are signed to avoid underflow.
  8840. for (int64_t i = N - 2; i >= 0; i--) {
  8841. // Find optimal partitioning of Clusters[i..N-1].
  8842. // Baseline: Put Clusters[i] into a partition on its own.
  8843. MinPartitions[i] = MinPartitions[i + 1] + 1;
  8844. LastElement[i] = i;
  8845. PartitionsScore[i] = PartitionsScore[i + 1] + PartitionScores::SingleCase;
  8846. // Search for a solution that results in fewer partitions.
  8847. for (int64_t j = N - 1; j > i; j--) {
  8848. // Try building a partition from Clusters[i..j].
  8849. uint64_t Range = getJumpTableRange(Clusters, i, j);
  8850. uint64_t NumCases = getJumpTableNumCases(TotalCases, i, j);
  8851. assert(NumCases < UINT64_MAX / 100);
  8852. assert(Range >= NumCases);
  8853. if (TLI.isSuitableForJumpTable(SI, NumCases, Range)) {
  8854. unsigned NumPartitions = 1 + (j == N - 1 ? 0 : MinPartitions[j + 1]);
  8855. unsigned Score = j == N - 1 ? 0 : PartitionsScore[j + 1];
  8856. int64_t NumEntries = j - i + 1;
  8857. if (NumEntries == 1)
  8858. Score += PartitionScores::SingleCase;
  8859. else if (NumEntries <= SmallNumberOfEntries)
  8860. Score += PartitionScores::FewCases;
  8861. else if (NumEntries >= MinJumpTableEntries)
  8862. Score += PartitionScores::Table;
  8863. // If this leads to fewer partitions, or to the same number of
  8864. // partitions with better score, it is a better partitioning.
  8865. if (NumPartitions < MinPartitions[i] ||
  8866. (NumPartitions == MinPartitions[i] && Score > PartitionsScore[i])) {
  8867. MinPartitions[i] = NumPartitions;
  8868. LastElement[i] = j;
  8869. PartitionsScore[i] = Score;
  8870. }
  8871. }
  8872. }
  8873. }
  8874. // Iterate over the partitions, replacing some with jump tables in-place.
  8875. unsigned DstIndex = 0;
  8876. for (unsigned First = 0, Last; First < N; First = Last + 1) {
  8877. Last = LastElement[First];
  8878. assert(Last >= First);
  8879. assert(DstIndex <= First);
  8880. unsigned NumClusters = Last - First + 1;
  8881. CaseCluster JTCluster;
  8882. if (NumClusters >= MinJumpTableEntries &&
  8883. buildJumpTable(Clusters, First, Last, SI, DefaultMBB, JTCluster)) {
  8884. Clusters[DstIndex++] = JTCluster;
  8885. } else {
  8886. for (unsigned I = First; I <= Last; ++I)
  8887. std::memmove(&Clusters[DstIndex++], &Clusters[I], sizeof(Clusters[I]));
  8888. }
  8889. }
  8890. Clusters.resize(DstIndex);
  8891. }
  8892. bool SelectionDAGBuilder::buildBitTests(CaseClusterVector &Clusters,
  8893. unsigned First, unsigned Last,
  8894. const SwitchInst *SI,
  8895. CaseCluster &BTCluster) {
  8896. assert(First <= Last);
  8897. if (First == Last)
  8898. return false;
  8899. BitVector Dests(FuncInfo.MF->getNumBlockIDs());
  8900. unsigned NumCmps = 0;
  8901. for (int64_t I = First; I <= Last; ++I) {
  8902. assert(Clusters[I].Kind == CC_Range);
  8903. Dests.set(Clusters[I].MBB->getNumber());
  8904. NumCmps += (Clusters[I].Low == Clusters[I].High) ? 1 : 2;
  8905. }
  8906. unsigned NumDests = Dests.count();
  8907. APInt Low = Clusters[First].Low->getValue();
  8908. APInt High = Clusters[Last].High->getValue();
  8909. assert(Low.slt(High));
  8910. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  8911. const DataLayout &DL = DAG.getDataLayout();
  8912. if (!TLI.isSuitableForBitTests(NumDests, NumCmps, Low, High, DL))
  8913. return false;
  8914. APInt LowBound;
  8915. APInt CmpRange;
  8916. const int BitWidth = TLI.getPointerTy(DL).getSizeInBits();
  8917. assert(TLI.rangeFitsInWord(Low, High, DL) &&
  8918. "Case range must fit in bit mask!");
  8919. // Check if the clusters cover a contiguous range such that no value in the
  8920. // range will jump to the default statement.
  8921. bool ContiguousRange = true;
  8922. for (int64_t I = First + 1; I <= Last; ++I) {
  8923. if (Clusters[I].Low->getValue() != Clusters[I - 1].High->getValue() + 1) {
  8924. ContiguousRange = false;
  8925. break;
  8926. }
  8927. }
  8928. if (Low.isStrictlyPositive() && High.slt(BitWidth)) {
  8929. // Optimize the case where all the case values fit in a word without having
  8930. // to subtract minValue. In this case, we can optimize away the subtraction.
  8931. LowBound = APInt::getNullValue(Low.getBitWidth());
  8932. CmpRange = High;
  8933. ContiguousRange = false;
  8934. } else {
  8935. LowBound = Low;
  8936. CmpRange = High - Low;
  8937. }
  8938. CaseBitsVector CBV;
  8939. auto TotalProb = BranchProbability::getZero();
  8940. for (unsigned i = First; i <= Last; ++i) {
  8941. // Find the CaseBits for this destination.
  8942. unsigned j;
  8943. for (j = 0; j < CBV.size(); ++j)
  8944. if (CBV[j].BB == Clusters[i].MBB)
  8945. break;
  8946. if (j == CBV.size())
  8947. CBV.push_back(
  8948. CaseBits(0, Clusters[i].MBB, 0, BranchProbability::getZero()));
  8949. CaseBits *CB = &CBV[j];
  8950. // Update Mask, Bits and ExtraProb.
  8951. uint64_t Lo = (Clusters[i].Low->getValue() - LowBound).getZExtValue();
  8952. uint64_t Hi = (Clusters[i].High->getValue() - LowBound).getZExtValue();
  8953. assert(Hi >= Lo && Hi < 64 && "Invalid bit case!");
  8954. CB->Mask |= (-1ULL >> (63 - (Hi - Lo))) << Lo;
  8955. CB->Bits += Hi - Lo + 1;
  8956. CB->ExtraProb += Clusters[i].Prob;
  8957. TotalProb += Clusters[i].Prob;
  8958. }
  8959. BitTestInfo BTI;
  8960. llvm::sort(CBV, [](const CaseBits &a, const CaseBits &b) {
  8961. // Sort by probability first, number of bits second, bit mask third.
  8962. if (a.ExtraProb != b.ExtraProb)
  8963. return a.ExtraProb > b.ExtraProb;
  8964. if (a.Bits != b.Bits)
  8965. return a.Bits > b.Bits;
  8966. return a.Mask < b.Mask;
  8967. });
  8968. for (auto &CB : CBV) {
  8969. MachineBasicBlock *BitTestBB =
  8970. FuncInfo.MF->CreateMachineBasicBlock(SI->getParent());
  8971. BTI.push_back(BitTestCase(CB.Mask, BitTestBB, CB.BB, CB.ExtraProb));
  8972. }
  8973. BitTestCases.emplace_back(std::move(LowBound), std::move(CmpRange),
  8974. SI->getCondition(), -1U, MVT::Other, false,
  8975. ContiguousRange, nullptr, nullptr, std::move(BTI),
  8976. TotalProb);
  8977. BTCluster = CaseCluster::bitTests(Clusters[First].Low, Clusters[Last].High,
  8978. BitTestCases.size() - 1, TotalProb);
  8979. return true;
  8980. }
  8981. void SelectionDAGBuilder::findBitTestClusters(CaseClusterVector &Clusters,
  8982. const SwitchInst *SI) {
  8983. // Partition Clusters into as few subsets as possible, where each subset has a
  8984. // range that fits in a machine word and has <= 3 unique destinations.
  8985. #ifndef NDEBUG
  8986. // Clusters must be sorted and contain Range or JumpTable clusters.
  8987. assert(!Clusters.empty());
  8988. assert(Clusters[0].Kind == CC_Range || Clusters[0].Kind == CC_JumpTable);
  8989. for (const CaseCluster &C : Clusters)
  8990. assert(C.Kind == CC_Range || C.Kind == CC_JumpTable);
  8991. for (unsigned i = 1; i < Clusters.size(); ++i)
  8992. assert(Clusters[i-1].High->getValue().slt(Clusters[i].Low->getValue()));
  8993. #endif
  8994. // The algorithm below is not suitable for -O0.
  8995. if (TM.getOptLevel() == CodeGenOpt::None)
  8996. return;
  8997. // If target does not have legal shift left, do not emit bit tests at all.
  8998. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  8999. const DataLayout &DL = DAG.getDataLayout();
  9000. EVT PTy = TLI.getPointerTy(DL);
  9001. if (!TLI.isOperationLegal(ISD::SHL, PTy))
  9002. return;
  9003. int BitWidth = PTy.getSizeInBits();
  9004. const int64_t N = Clusters.size();
  9005. // MinPartitions[i] is the minimum nbr of partitions of Clusters[i..N-1].
  9006. SmallVector<unsigned, 8> MinPartitions(N);
  9007. // LastElement[i] is the last element of the partition starting at i.
  9008. SmallVector<unsigned, 8> LastElement(N);
  9009. // FIXME: This might not be the best algorithm for finding bit test clusters.
  9010. // Base case: There is only one way to partition Clusters[N-1].
  9011. MinPartitions[N - 1] = 1;
  9012. LastElement[N - 1] = N - 1;
  9013. // Note: loop indexes are signed to avoid underflow.
  9014. for (int64_t i = N - 2; i >= 0; --i) {
  9015. // Find optimal partitioning of Clusters[i..N-1].
  9016. // Baseline: Put Clusters[i] into a partition on its own.
  9017. MinPartitions[i] = MinPartitions[i + 1] + 1;
  9018. LastElement[i] = i;
  9019. // Search for a solution that results in fewer partitions.
  9020. // Note: the search is limited by BitWidth, reducing time complexity.
  9021. for (int64_t j = std::min(N - 1, i + BitWidth - 1); j > i; --j) {
  9022. // Try building a partition from Clusters[i..j].
  9023. // Check the range.
  9024. if (!TLI.rangeFitsInWord(Clusters[i].Low->getValue(),
  9025. Clusters[j].High->getValue(), DL))
  9026. continue;
  9027. // Check nbr of destinations and cluster types.
  9028. // FIXME: This works, but doesn't seem very efficient.
  9029. bool RangesOnly = true;
  9030. BitVector Dests(FuncInfo.MF->getNumBlockIDs());
  9031. for (int64_t k = i; k <= j; k++) {
  9032. if (Clusters[k].Kind != CC_Range) {
  9033. RangesOnly = false;
  9034. break;
  9035. }
  9036. Dests.set(Clusters[k].MBB->getNumber());
  9037. }
  9038. if (!RangesOnly || Dests.count() > 3)
  9039. break;
  9040. // Check if it's a better partition.
  9041. unsigned NumPartitions = 1 + (j == N - 1 ? 0 : MinPartitions[j + 1]);
  9042. if (NumPartitions < MinPartitions[i]) {
  9043. // Found a better partition.
  9044. MinPartitions[i] = NumPartitions;
  9045. LastElement[i] = j;
  9046. }
  9047. }
  9048. }
  9049. // Iterate over the partitions, replacing with bit-test clusters in-place.
  9050. unsigned DstIndex = 0;
  9051. for (unsigned First = 0, Last; First < N; First = Last + 1) {
  9052. Last = LastElement[First];
  9053. assert(First <= Last);
  9054. assert(DstIndex <= First);
  9055. CaseCluster BitTestCluster;
  9056. if (buildBitTests(Clusters, First, Last, SI, BitTestCluster)) {
  9057. Clusters[DstIndex++] = BitTestCluster;
  9058. } else {
  9059. size_t NumClusters = Last - First + 1;
  9060. std::memmove(&Clusters[DstIndex], &Clusters[First],
  9061. sizeof(Clusters[0]) * NumClusters);
  9062. DstIndex += NumClusters;
  9063. }
  9064. }
  9065. Clusters.resize(DstIndex);
  9066. }
  9067. void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond,
  9068. MachineBasicBlock *SwitchMBB,
  9069. MachineBasicBlock *DefaultMBB) {
  9070. MachineFunction *CurMF = FuncInfo.MF;
  9071. MachineBasicBlock *NextMBB = nullptr;
  9072. MachineFunction::iterator BBI(W.MBB);
  9073. if (++BBI != FuncInfo.MF->end())
  9074. NextMBB = &*BBI;
  9075. unsigned Size = W.LastCluster - W.FirstCluster + 1;
  9076. BranchProbabilityInfo *BPI = FuncInfo.BPI;
  9077. if (Size == 2 && W.MBB == SwitchMBB) {
  9078. // If any two of the cases has the same destination, and if one value
  9079. // is the same as the other, but has one bit unset that the other has set,
  9080. // use bit manipulation to do two compares at once. For example:
  9081. // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
  9082. // TODO: This could be extended to merge any 2 cases in switches with 3
  9083. // cases.
  9084. // TODO: Handle cases where W.CaseBB != SwitchBB.
  9085. CaseCluster &Small = *W.FirstCluster;
  9086. CaseCluster &Big = *W.LastCluster;
  9087. if (Small.Low == Small.High && Big.Low == Big.High &&
  9088. Small.MBB == Big.MBB) {
  9089. const APInt &SmallValue = Small.Low->getValue();
  9090. const APInt &BigValue = Big.Low->getValue();
  9091. // Check that there is only one bit different.
  9092. APInt CommonBit = BigValue ^ SmallValue;
  9093. if (CommonBit.isPowerOf2()) {
  9094. SDValue CondLHS = getValue(Cond);
  9095. EVT VT = CondLHS.getValueType();
  9096. SDLoc DL = getCurSDLoc();
  9097. SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS,
  9098. DAG.getConstant(CommonBit, DL, VT));
  9099. SDValue Cond = DAG.getSetCC(
  9100. DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT),
  9101. ISD::SETEQ);
  9102. // Update successor info.
  9103. // Both Small and Big will jump to Small.BB, so we sum up the
  9104. // probabilities.
  9105. addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob);
  9106. if (BPI)
  9107. addSuccessorWithProb(
  9108. SwitchMBB, DefaultMBB,
  9109. // The default destination is the first successor in IR.
  9110. BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0));
  9111. else
  9112. addSuccessorWithProb(SwitchMBB, DefaultMBB);
  9113. // Insert the true branch.
  9114. SDValue BrCond =
  9115. DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond,
  9116. DAG.getBasicBlock(Small.MBB));
  9117. // Insert the false branch.
  9118. BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond,
  9119. DAG.getBasicBlock(DefaultMBB));
  9120. DAG.setRoot(BrCond);
  9121. return;
  9122. }
  9123. }
  9124. }
  9125. if (TM.getOptLevel() != CodeGenOpt::None) {
  9126. // Here, we order cases by probability so the most likely case will be
  9127. // checked first. However, two clusters can have the same probability in
  9128. // which case their relative ordering is non-deterministic. So we use Low
  9129. // as a tie-breaker as clusters are guaranteed to never overlap.
  9130. llvm::sort(W.FirstCluster, W.LastCluster + 1,
  9131. [](const CaseCluster &a, const CaseCluster &b) {
  9132. return a.Prob != b.Prob ?
  9133. a.Prob > b.Prob :
  9134. a.Low->getValue().slt(b.Low->getValue());
  9135. });
  9136. // Rearrange the case blocks so that the last one falls through if possible
  9137. // without changing the order of probabilities.
  9138. for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) {
  9139. --I;
  9140. if (I->Prob > W.LastCluster->Prob)
  9141. break;
  9142. if (I->Kind == CC_Range && I->MBB == NextMBB) {
  9143. std::swap(*I, *W.LastCluster);
  9144. break;
  9145. }
  9146. }
  9147. }
  9148. // Compute total probability.
  9149. BranchProbability DefaultProb = W.DefaultProb;
  9150. BranchProbability UnhandledProbs = DefaultProb;
  9151. for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I)
  9152. UnhandledProbs += I->Prob;
  9153. MachineBasicBlock *CurMBB = W.MBB;
  9154. for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) {
  9155. bool FallthroughUnreachable = false;
  9156. MachineBasicBlock *Fallthrough;
  9157. if (I == W.LastCluster) {
  9158. // For the last cluster, fall through to the default destination.
  9159. Fallthrough = DefaultMBB;
  9160. FallthroughUnreachable = isa<UnreachableInst>(
  9161. DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg());
  9162. } else {
  9163. Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock());
  9164. CurMF->insert(BBI, Fallthrough);
  9165. // Put Cond in a virtual register to make it available from the new blocks.
  9166. ExportFromCurrentBlock(Cond);
  9167. }
  9168. UnhandledProbs -= I->Prob;
  9169. switch (I->Kind) {
  9170. case CC_JumpTable: {
  9171. // FIXME: Optimize away range check based on pivot comparisons.
  9172. JumpTableHeader *JTH = &JTCases[I->JTCasesIndex].first;
  9173. JumpTable *JT = &JTCases[I->JTCasesIndex].second;
  9174. // The jump block hasn't been inserted yet; insert it here.
  9175. MachineBasicBlock *JumpMBB = JT->MBB;
  9176. CurMF->insert(BBI, JumpMBB);
  9177. auto JumpProb = I->Prob;
  9178. auto FallthroughProb = UnhandledProbs;
  9179. // If the default statement is a target of the jump table, we evenly
  9180. // distribute the default probability to successors of CurMBB. Also
  9181. // update the probability on the edge from JumpMBB to Fallthrough.
  9182. for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(),
  9183. SE = JumpMBB->succ_end();
  9184. SI != SE; ++SI) {
  9185. if (*SI == DefaultMBB) {
  9186. JumpProb += DefaultProb / 2;
  9187. FallthroughProb -= DefaultProb / 2;
  9188. JumpMBB->setSuccProbability(SI, DefaultProb / 2);
  9189. JumpMBB->normalizeSuccProbs();
  9190. break;
  9191. }
  9192. }
  9193. if (FallthroughUnreachable) {
  9194. // Skip the range check if the fallthrough block is unreachable.
  9195. JTH->OmitRangeCheck = true;
  9196. }
  9197. if (!JTH->OmitRangeCheck)
  9198. addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb);
  9199. addSuccessorWithProb(CurMBB, JumpMBB, JumpProb);
  9200. CurMBB->normalizeSuccProbs();
  9201. // The jump table header will be inserted in our current block, do the
  9202. // range check, and fall through to our fallthrough block.
  9203. JTH->HeaderBB = CurMBB;
  9204. JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader.
  9205. // If we're in the right place, emit the jump table header right now.
  9206. if (CurMBB == SwitchMBB) {
  9207. visitJumpTableHeader(*JT, *JTH, SwitchMBB);
  9208. JTH->Emitted = true;
  9209. }
  9210. break;
  9211. }
  9212. case CC_BitTests: {
  9213. // FIXME: If Fallthrough is unreachable, skip the range check.
  9214. // FIXME: Optimize away range check based on pivot comparisons.
  9215. BitTestBlock *BTB = &BitTestCases[I->BTCasesIndex];
  9216. // The bit test blocks haven't been inserted yet; insert them here.
  9217. for (BitTestCase &BTC : BTB->Cases)
  9218. CurMF->insert(BBI, BTC.ThisBB);
  9219. // Fill in fields of the BitTestBlock.
  9220. BTB->Parent = CurMBB;
  9221. BTB->Default = Fallthrough;
  9222. BTB->DefaultProb = UnhandledProbs;
  9223. // If the cases in bit test don't form a contiguous range, we evenly
  9224. // distribute the probability on the edge to Fallthrough to two
  9225. // successors of CurMBB.
  9226. if (!BTB->ContiguousRange) {
  9227. BTB->Prob += DefaultProb / 2;
  9228. BTB->DefaultProb -= DefaultProb / 2;
  9229. }
  9230. // If we're in the right place, emit the bit test header right now.
  9231. if (CurMBB == SwitchMBB) {
  9232. visitBitTestHeader(*BTB, SwitchMBB);
  9233. BTB->Emitted = true;
  9234. }
  9235. break;
  9236. }
  9237. case CC_Range: {
  9238. const Value *RHS, *LHS, *MHS;
  9239. ISD::CondCode CC;
  9240. if (I->Low == I->High) {
  9241. // Check Cond == I->Low.
  9242. CC = ISD::SETEQ;
  9243. LHS = Cond;
  9244. RHS=I->Low;
  9245. MHS = nullptr;
  9246. } else {
  9247. // Check I->Low <= Cond <= I->High.
  9248. CC = ISD::SETLE;
  9249. LHS = I->Low;
  9250. MHS = Cond;
  9251. RHS = I->High;
  9252. }
  9253. // If Fallthrough is unreachable, fold away the comparison.
  9254. if (FallthroughUnreachable)
  9255. CC = ISD::SETTRUE;
  9256. // The false probability is the sum of all unhandled cases.
  9257. CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB,
  9258. getCurSDLoc(), I->Prob, UnhandledProbs);
  9259. if (CurMBB == SwitchMBB)
  9260. visitSwitchCase(CB, SwitchMBB);
  9261. else
  9262. SwitchCases.push_back(CB);
  9263. break;
  9264. }
  9265. }
  9266. CurMBB = Fallthrough;
  9267. }
  9268. }
  9269. unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC,
  9270. CaseClusterIt First,
  9271. CaseClusterIt Last) {
  9272. return std::count_if(First, Last + 1, [&](const CaseCluster &X) {
  9273. if (X.Prob != CC.Prob)
  9274. return X.Prob > CC.Prob;
  9275. // Ties are broken by comparing the case value.
  9276. return X.Low->getValue().slt(CC.Low->getValue());
  9277. });
  9278. }
  9279. void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList,
  9280. const SwitchWorkListItem &W,
  9281. Value *Cond,
  9282. MachineBasicBlock *SwitchMBB) {
  9283. assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) &&
  9284. "Clusters not sorted?");
  9285. assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!");
  9286. // Balance the tree based on branch probabilities to create a near-optimal (in
  9287. // terms of search time given key frequency) binary search tree. See e.g. Kurt
  9288. // Mehlhorn "Nearly Optimal Binary Search Trees" (1975).
  9289. CaseClusterIt LastLeft = W.FirstCluster;
  9290. CaseClusterIt FirstRight = W.LastCluster;
  9291. auto LeftProb = LastLeft->Prob + W.DefaultProb / 2;
  9292. auto RightProb = FirstRight->Prob + W.DefaultProb / 2;
  9293. // Move LastLeft and FirstRight towards each other from opposite directions to
  9294. // find a partitioning of the clusters which balances the probability on both
  9295. // sides. If LeftProb and RightProb are equal, alternate which side is
  9296. // taken to ensure 0-probability nodes are distributed evenly.
  9297. unsigned I = 0;
  9298. while (LastLeft + 1 < FirstRight) {
  9299. if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1)))
  9300. LeftProb += (++LastLeft)->Prob;
  9301. else
  9302. RightProb += (--FirstRight)->Prob;
  9303. I++;
  9304. }
  9305. while (true) {
  9306. // Our binary search tree differs from a typical BST in that ours can have up
  9307. // to three values in each leaf. The pivot selection above doesn't take that
  9308. // into account, which means the tree might require more nodes and be less
  9309. // efficient. We compensate for this here.
  9310. unsigned NumLeft = LastLeft - W.FirstCluster + 1;
  9311. unsigned NumRight = W.LastCluster - FirstRight + 1;
  9312. if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) {
  9313. // If one side has less than 3 clusters, and the other has more than 3,
  9314. // consider taking a cluster from the other side.
  9315. if (NumLeft < NumRight) {
  9316. // Consider moving the first cluster on the right to the left side.
  9317. CaseCluster &CC = *FirstRight;
  9318. unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
  9319. unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
  9320. if (LeftSideRank <= RightSideRank) {
  9321. // Moving the cluster to the left does not demote it.
  9322. ++LastLeft;
  9323. ++FirstRight;
  9324. continue;
  9325. }
  9326. } else {
  9327. assert(NumRight < NumLeft);
  9328. // Consider moving the last element on the left to the right side.
  9329. CaseCluster &CC = *LastLeft;
  9330. unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
  9331. unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
  9332. if (RightSideRank <= LeftSideRank) {
  9333. // Moving the cluster to the right does not demot it.
  9334. --LastLeft;
  9335. --FirstRight;
  9336. continue;
  9337. }
  9338. }
  9339. }
  9340. break;
  9341. }
  9342. assert(LastLeft + 1 == FirstRight);
  9343. assert(LastLeft >= W.FirstCluster);
  9344. assert(FirstRight <= W.LastCluster);
  9345. // Use the first element on the right as pivot since we will make less-than
  9346. // comparisons against it.
  9347. CaseClusterIt PivotCluster = FirstRight;
  9348. assert(PivotCluster > W.FirstCluster);
  9349. assert(PivotCluster <= W.LastCluster);
  9350. CaseClusterIt FirstLeft = W.FirstCluster;
  9351. CaseClusterIt LastRight = W.LastCluster;
  9352. const ConstantInt *Pivot = PivotCluster->Low;
  9353. // New blocks will be inserted immediately after the current one.
  9354. MachineFunction::iterator BBI(W.MBB);
  9355. ++BBI;
  9356. // We will branch to the LHS if Value < Pivot. If LHS is a single cluster,
  9357. // we can branch to its destination directly if it's squeezed exactly in
  9358. // between the known lower bound and Pivot - 1.
  9359. MachineBasicBlock *LeftMBB;
  9360. if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range &&
  9361. FirstLeft->Low == W.GE &&
  9362. (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) {
  9363. LeftMBB = FirstLeft->MBB;
  9364. } else {
  9365. LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
  9366. FuncInfo.MF->insert(BBI, LeftMBB);
  9367. WorkList.push_back(
  9368. {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2});
  9369. // Put Cond in a virtual register to make it available from the new blocks.
  9370. ExportFromCurrentBlock(Cond);
  9371. }
  9372. // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a
  9373. // single cluster, RHS.Low == Pivot, and we can branch to its destination
  9374. // directly if RHS.High equals the current upper bound.
  9375. MachineBasicBlock *RightMBB;
  9376. if (FirstRight == LastRight && FirstRight->Kind == CC_Range &&
  9377. W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) {
  9378. RightMBB = FirstRight->MBB;
  9379. } else {
  9380. RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
  9381. FuncInfo.MF->insert(BBI, RightMBB);
  9382. WorkList.push_back(
  9383. {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2});
  9384. // Put Cond in a virtual register to make it available from the new blocks.
  9385. ExportFromCurrentBlock(Cond);
  9386. }
  9387. // Create the CaseBlock record that will be used to lower the branch.
  9388. CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB,
  9389. getCurSDLoc(), LeftProb, RightProb);
  9390. if (W.MBB == SwitchMBB)
  9391. visitSwitchCase(CB, SwitchMBB);
  9392. else
  9393. SwitchCases.push_back(CB);
  9394. }
  9395. // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb
  9396. // from the swith statement.
  9397. static BranchProbability scaleCaseProbality(BranchProbability CaseProb,
  9398. BranchProbability PeeledCaseProb) {
  9399. if (PeeledCaseProb == BranchProbability::getOne())
  9400. return BranchProbability::getZero();
  9401. BranchProbability SwitchProb = PeeledCaseProb.getCompl();
  9402. uint32_t Numerator = CaseProb.getNumerator();
  9403. uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator());
  9404. return BranchProbability(Numerator, std::max(Numerator, Denominator));
  9405. }
  9406. // Try to peel the top probability case if it exceeds the threshold.
  9407. // Return current MachineBasicBlock for the switch statement if the peeling
  9408. // does not occur.
  9409. // If the peeling is performed, return the newly created MachineBasicBlock
  9410. // for the peeled switch statement. Also update Clusters to remove the peeled
  9411. // case. PeeledCaseProb is the BranchProbability for the peeled case.
  9412. MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster(
  9413. const SwitchInst &SI, CaseClusterVector &Clusters,
  9414. BranchProbability &PeeledCaseProb) {
  9415. MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
  9416. // Don't perform if there is only one cluster or optimizing for size.
  9417. if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 ||
  9418. TM.getOptLevel() == CodeGenOpt::None ||
  9419. SwitchMBB->getParent()->getFunction().hasMinSize())
  9420. return SwitchMBB;
  9421. BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100);
  9422. unsigned PeeledCaseIndex = 0;
  9423. bool SwitchPeeled = false;
  9424. for (unsigned Index = 0; Index < Clusters.size(); ++Index) {
  9425. CaseCluster &CC = Clusters[Index];
  9426. if (CC.Prob < TopCaseProb)
  9427. continue;
  9428. TopCaseProb = CC.Prob;
  9429. PeeledCaseIndex = Index;
  9430. SwitchPeeled = true;
  9431. }
  9432. if (!SwitchPeeled)
  9433. return SwitchMBB;
  9434. LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: "
  9435. << TopCaseProb << "\n");
  9436. // Record the MBB for the peeled switch statement.
  9437. MachineFunction::iterator BBI(SwitchMBB);
  9438. ++BBI;
  9439. MachineBasicBlock *PeeledSwitchMBB =
  9440. FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock());
  9441. FuncInfo.MF->insert(BBI, PeeledSwitchMBB);
  9442. ExportFromCurrentBlock(SI.getCondition());
  9443. auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex;
  9444. SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt,
  9445. nullptr, nullptr, TopCaseProb.getCompl()};
  9446. lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB);
  9447. Clusters.erase(PeeledCaseIt);
  9448. for (CaseCluster &CC : Clusters) {
  9449. LLVM_DEBUG(
  9450. dbgs() << "Scale the probablity for one cluster, before scaling: "
  9451. << CC.Prob << "\n");
  9452. CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb);
  9453. LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n");
  9454. }
  9455. PeeledCaseProb = TopCaseProb;
  9456. return PeeledSwitchMBB;
  9457. }
  9458. void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) {
  9459. // Extract cases from the switch.
  9460. BranchProbabilityInfo *BPI = FuncInfo.BPI;
  9461. CaseClusterVector Clusters;
  9462. Clusters.reserve(SI.getNumCases());
  9463. for (auto I : SI.cases()) {
  9464. MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()];
  9465. const ConstantInt *CaseVal = I.getCaseValue();
  9466. BranchProbability Prob =
  9467. BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex())
  9468. : BranchProbability(1, SI.getNumCases() + 1);
  9469. Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob));
  9470. }
  9471. MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()];
  9472. // Cluster adjacent cases with the same destination. We do this at all
  9473. // optimization levels because it's cheap to do and will make codegen faster
  9474. // if there are many clusters.
  9475. sortAndRangeify(Clusters);
  9476. // The branch probablity of the peeled case.
  9477. BranchProbability PeeledCaseProb = BranchProbability::getZero();
  9478. MachineBasicBlock *PeeledSwitchMBB =
  9479. peelDominantCaseCluster(SI, Clusters, PeeledCaseProb);
  9480. // If there is only the default destination, jump there directly.
  9481. MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
  9482. if (Clusters.empty()) {
  9483. assert(PeeledSwitchMBB == SwitchMBB);
  9484. SwitchMBB->addSuccessor(DefaultMBB);
  9485. if (DefaultMBB != NextBlock(SwitchMBB)) {
  9486. DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
  9487. getControlRoot(), DAG.getBasicBlock(DefaultMBB)));
  9488. }
  9489. return;
  9490. }
  9491. findJumpTables(Clusters, &SI, DefaultMBB);
  9492. findBitTestClusters(Clusters, &SI);
  9493. LLVM_DEBUG({
  9494. dbgs() << "Case clusters: ";
  9495. for (const CaseCluster &C : Clusters) {
  9496. if (C.Kind == CC_JumpTable)
  9497. dbgs() << "JT:";
  9498. if (C.Kind == CC_BitTests)
  9499. dbgs() << "BT:";
  9500. C.Low->getValue().print(dbgs(), true);
  9501. if (C.Low != C.High) {
  9502. dbgs() << '-';
  9503. C.High->getValue().print(dbgs(), true);
  9504. }
  9505. dbgs() << ' ';
  9506. }
  9507. dbgs() << '\n';
  9508. });
  9509. assert(!Clusters.empty());
  9510. SwitchWorkList WorkList;
  9511. CaseClusterIt First = Clusters.begin();
  9512. CaseClusterIt Last = Clusters.end() - 1;
  9513. auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB);
  9514. // Scale the branchprobability for DefaultMBB if the peel occurs and
  9515. // DefaultMBB is not replaced.
  9516. if (PeeledCaseProb != BranchProbability::getZero() &&
  9517. DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()])
  9518. DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb);
  9519. WorkList.push_back(
  9520. {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb});
  9521. while (!WorkList.empty()) {
  9522. SwitchWorkListItem W = WorkList.back();
  9523. WorkList.pop_back();
  9524. unsigned NumClusters = W.LastCluster - W.FirstCluster + 1;
  9525. if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None &&
  9526. !DefaultMBB->getParent()->getFunction().hasMinSize()) {
  9527. // For optimized builds, lower large range as a balanced binary tree.
  9528. splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB);
  9529. continue;
  9530. }
  9531. lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB);
  9532. }
  9533. }