SelectionDAGBuilder.cpp 395 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179
  1. //===- SelectionDAGBuilder.cpp - Selection-DAG building -------------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This implements routines for translating from LLVM IR into SelectionDAG IR.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "SelectionDAGBuilder.h"
  14. #include "SDNodeDbgValue.h"
  15. #include "llvm/ADT/APFloat.h"
  16. #include "llvm/ADT/APInt.h"
  17. #include "llvm/ADT/ArrayRef.h"
  18. #include "llvm/ADT/BitVector.h"
  19. #include "llvm/ADT/DenseMap.h"
  20. #include "llvm/ADT/None.h"
  21. #include "llvm/ADT/Optional.h"
  22. #include "llvm/ADT/STLExtras.h"
  23. #include "llvm/ADT/SmallPtrSet.h"
  24. #include "llvm/ADT/SmallSet.h"
  25. #include "llvm/ADT/SmallVector.h"
  26. #include "llvm/ADT/StringRef.h"
  27. #include "llvm/ADT/Triple.h"
  28. #include "llvm/ADT/Twine.h"
  29. #include "llvm/Analysis/AliasAnalysis.h"
  30. #include "llvm/Analysis/BranchProbabilityInfo.h"
  31. #include "llvm/Analysis/ConstantFolding.h"
  32. #include "llvm/Analysis/EHPersonalities.h"
  33. #include "llvm/Analysis/Loads.h"
  34. #include "llvm/Analysis/MemoryLocation.h"
  35. #include "llvm/Analysis/TargetLibraryInfo.h"
  36. #include "llvm/Analysis/ValueTracking.h"
  37. #include "llvm/Analysis/VectorUtils.h"
  38. #include "llvm/CodeGen/Analysis.h"
  39. #include "llvm/CodeGen/FunctionLoweringInfo.h"
  40. #include "llvm/CodeGen/GCMetadata.h"
  41. #include "llvm/CodeGen/ISDOpcodes.h"
  42. #include "llvm/CodeGen/MachineBasicBlock.h"
  43. #include "llvm/CodeGen/MachineFrameInfo.h"
  44. #include "llvm/CodeGen/MachineFunction.h"
  45. #include "llvm/CodeGen/MachineInstr.h"
  46. #include "llvm/CodeGen/MachineInstrBuilder.h"
  47. #include "llvm/CodeGen/MachineJumpTableInfo.h"
  48. #include "llvm/CodeGen/MachineMemOperand.h"
  49. #include "llvm/CodeGen/MachineModuleInfo.h"
  50. #include "llvm/CodeGen/MachineOperand.h"
  51. #include "llvm/CodeGen/MachineRegisterInfo.h"
  52. #include "llvm/CodeGen/RuntimeLibcalls.h"
  53. #include "llvm/CodeGen/SelectionDAG.h"
  54. #include "llvm/CodeGen/SelectionDAGNodes.h"
  55. #include "llvm/CodeGen/SelectionDAGTargetInfo.h"
  56. #include "llvm/CodeGen/StackMaps.h"
  57. #include "llvm/CodeGen/TargetFrameLowering.h"
  58. #include "llvm/CodeGen/TargetInstrInfo.h"
  59. #include "llvm/CodeGen/TargetLowering.h"
  60. #include "llvm/CodeGen/TargetOpcodes.h"
  61. #include "llvm/CodeGen/TargetRegisterInfo.h"
  62. #include "llvm/CodeGen/TargetSubtargetInfo.h"
  63. #include "llvm/CodeGen/ValueTypes.h"
  64. #include "llvm/CodeGen/WinEHFuncInfo.h"
  65. #include "llvm/IR/Argument.h"
  66. #include "llvm/IR/Attributes.h"
  67. #include "llvm/IR/BasicBlock.h"
  68. #include "llvm/IR/CFG.h"
  69. #include "llvm/IR/CallSite.h"
  70. #include "llvm/IR/CallingConv.h"
  71. #include "llvm/IR/Constant.h"
  72. #include "llvm/IR/ConstantRange.h"
  73. #include "llvm/IR/Constants.h"
  74. #include "llvm/IR/DataLayout.h"
  75. #include "llvm/IR/DebugInfoMetadata.h"
  76. #include "llvm/IR/DebugLoc.h"
  77. #include "llvm/IR/DerivedTypes.h"
  78. #include "llvm/IR/Function.h"
  79. #include "llvm/IR/GetElementPtrTypeIterator.h"
  80. #include "llvm/IR/InlineAsm.h"
  81. #include "llvm/IR/InstrTypes.h"
  82. #include "llvm/IR/Instruction.h"
  83. #include "llvm/IR/Instructions.h"
  84. #include "llvm/IR/IntrinsicInst.h"
  85. #include "llvm/IR/Intrinsics.h"
  86. #include "llvm/IR/LLVMContext.h"
  87. #include "llvm/IR/Metadata.h"
  88. #include "llvm/IR/Module.h"
  89. #include "llvm/IR/Operator.h"
  90. #include "llvm/IR/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 <algorithm>
  111. #include <cassert>
  112. #include <cstddef>
  113. #include <cstdint>
  114. #include <cstring>
  115. #include <iterator>
  116. #include <limits>
  117. #include <numeric>
  118. #include <tuple>
  119. #include <utility>
  120. #include <vector>
  121. using namespace llvm;
  122. #define DEBUG_TYPE "isel"
  123. /// LimitFloatPrecision - Generate low-precision inline sequences for
  124. /// some float libcalls (6, 8 or 12 bits).
  125. static unsigned LimitFloatPrecision;
  126. static cl::opt<unsigned, true>
  127. LimitFPPrecision("limit-float-precision",
  128. cl::desc("Generate low-precision inline sequences "
  129. "for some float libcalls"),
  130. cl::location(LimitFloatPrecision), cl::Hidden,
  131. cl::init(0));
  132. static cl::opt<unsigned> SwitchPeelThreshold(
  133. "switch-peel-threshold", cl::Hidden, cl::init(66),
  134. cl::desc("Set the case probability threshold for peeling the case from a "
  135. "switch statement. A value greater than 100 will void this "
  136. "optimization"));
  137. // Limit the width of DAG chains. This is important in general to prevent
  138. // DAG-based analysis from blowing up. For example, alias analysis and
  139. // load clustering may not complete in reasonable time. It is difficult to
  140. // recognize and avoid this situation within each individual analysis, and
  141. // future analyses are likely to have the same behavior. Limiting DAG width is
  142. // the safe approach and will be especially important with global DAGs.
  143. //
  144. // MaxParallelChains default is arbitrarily high to avoid affecting
  145. // optimization, but could be lowered to improve compile time. Any ld-ld-st-st
  146. // sequence over this should have been converted to llvm.memcpy by the
  147. // frontend. It is easy to induce this behavior with .ll code such as:
  148. // %buffer = alloca [4096 x i8]
  149. // %data = load [4096 x i8]* %argPtr
  150. // store [4096 x i8] %data, [4096 x i8]* %buffer
  151. static const unsigned MaxParallelChains = 64;
  152. // True if the Value passed requires ABI mangling as it is a parameter to a
  153. // function or a return value from a function which is not an intrinsic.
  154. static bool isABIRegCopy(const Value *V) {
  155. const bool IsRetInst = V && isa<ReturnInst>(V);
  156. const bool IsCallInst = V && isa<CallInst>(V);
  157. const bool IsInLineAsm =
  158. IsCallInst && static_cast<const CallInst *>(V)->isInlineAsm();
  159. const bool IsIndirectFunctionCall =
  160. IsCallInst && !IsInLineAsm &&
  161. !static_cast<const CallInst *>(V)->getCalledFunction();
  162. // It is possible that the call instruction is an inline asm statement or an
  163. // indirect function call in which case the return value of
  164. // getCalledFunction() would be nullptr.
  165. const bool IsInstrinsicCall =
  166. IsCallInst && !IsInLineAsm && !IsIndirectFunctionCall &&
  167. static_cast<const CallInst *>(V)->getCalledFunction()->getIntrinsicID() !=
  168. Intrinsic::not_intrinsic;
  169. return IsRetInst || (IsCallInst && (!IsInLineAsm && !IsInstrinsicCall));
  170. }
  171. static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
  172. const SDValue *Parts, unsigned NumParts,
  173. MVT PartVT, EVT ValueVT, const Value *V,
  174. bool IsABIRegCopy);
  175. /// getCopyFromParts - Create a value that contains the specified legal parts
  176. /// combined into the value they represent. If the parts combine to a type
  177. /// larger than ValueVT then AssertOp can be used to specify whether the extra
  178. /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
  179. /// (ISD::AssertSext).
  180. static SDValue getCopyFromParts(SelectionDAG &DAG, const SDLoc &DL,
  181. const SDValue *Parts, unsigned NumParts,
  182. MVT PartVT, EVT ValueVT, const Value *V,
  183. Optional<ISD::NodeType> AssertOp = None,
  184. bool IsABIRegCopy = false) {
  185. if (ValueVT.isVector())
  186. return getCopyFromPartsVector(DAG, DL, Parts, NumParts,
  187. PartVT, ValueVT, V, IsABIRegCopy);
  188. assert(NumParts > 0 && "No parts to assemble!");
  189. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  190. SDValue Val = Parts[0];
  191. if (NumParts > 1) {
  192. // Assemble the value from multiple parts.
  193. if (ValueVT.isInteger()) {
  194. unsigned PartBits = PartVT.getSizeInBits();
  195. unsigned ValueBits = ValueVT.getSizeInBits();
  196. // Assemble the power of 2 part.
  197. unsigned RoundParts = NumParts & (NumParts - 1) ?
  198. 1 << Log2_32(NumParts) : NumParts;
  199. unsigned RoundBits = PartBits * RoundParts;
  200. EVT RoundVT = RoundBits == ValueBits ?
  201. ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits);
  202. SDValue Lo, Hi;
  203. EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2);
  204. if (RoundParts > 2) {
  205. Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2,
  206. PartVT, HalfVT, V);
  207. Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2,
  208. RoundParts / 2, PartVT, HalfVT, V);
  209. } else {
  210. Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]);
  211. Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]);
  212. }
  213. if (DAG.getDataLayout().isBigEndian())
  214. std::swap(Lo, Hi);
  215. Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi);
  216. if (RoundParts < NumParts) {
  217. // Assemble the trailing non-power-of-2 part.
  218. unsigned OddParts = NumParts - RoundParts;
  219. EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits);
  220. Hi = getCopyFromParts(DAG, DL,
  221. Parts + RoundParts, OddParts, PartVT, OddVT, V);
  222. // Combine the round and odd parts.
  223. Lo = Val;
  224. if (DAG.getDataLayout().isBigEndian())
  225. std::swap(Lo, Hi);
  226. EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
  227. Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi);
  228. Hi =
  229. DAG.getNode(ISD::SHL, DL, TotalVT, Hi,
  230. DAG.getConstant(Lo.getValueSizeInBits(), DL,
  231. TLI.getPointerTy(DAG.getDataLayout())));
  232. Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo);
  233. Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi);
  234. }
  235. } else if (PartVT.isFloatingPoint()) {
  236. // FP split into multiple FP parts (for ppcf128)
  237. assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 &&
  238. "Unexpected split");
  239. SDValue Lo, Hi;
  240. Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]);
  241. Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]);
  242. if (TLI.hasBigEndianPartOrdering(ValueVT, DAG.getDataLayout()))
  243. std::swap(Lo, Hi);
  244. Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi);
  245. } else {
  246. // FP split into integer parts (soft fp)
  247. assert(ValueVT.isFloatingPoint() && PartVT.isInteger() &&
  248. !PartVT.isVector() && "Unexpected split");
  249. EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
  250. Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V);
  251. }
  252. }
  253. // There is now one part, held in Val. Correct it to match ValueVT.
  254. // PartEVT is the type of the register class that holds the value.
  255. // ValueVT is the type of the inline asm operation.
  256. EVT PartEVT = Val.getValueType();
  257. if (PartEVT == ValueVT)
  258. return Val;
  259. if (PartEVT.isInteger() && ValueVT.isFloatingPoint() &&
  260. ValueVT.bitsLT(PartEVT)) {
  261. // For an FP value in an integer part, we need to truncate to the right
  262. // width first.
  263. PartEVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
  264. Val = DAG.getNode(ISD::TRUNCATE, DL, PartEVT, Val);
  265. }
  266. // Handle types that have the same size.
  267. if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits())
  268. return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
  269. // Handle types with different sizes.
  270. if (PartEVT.isInteger() && ValueVT.isInteger()) {
  271. if (ValueVT.bitsLT(PartEVT)) {
  272. // For a truncate, see if we have any information to
  273. // indicate whether the truncated bits will always be
  274. // zero or sign-extension.
  275. if (AssertOp.hasValue())
  276. Val = DAG.getNode(*AssertOp, DL, PartEVT, Val,
  277. DAG.getValueType(ValueVT));
  278. return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
  279. }
  280. return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val);
  281. }
  282. if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
  283. // FP_ROUND's are always exact here.
  284. if (ValueVT.bitsLT(Val.getValueType()))
  285. return DAG.getNode(
  286. ISD::FP_ROUND, DL, ValueVT, Val,
  287. DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout())));
  288. return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val);
  289. }
  290. llvm_unreachable("Unknown mismatch!");
  291. }
  292. static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V,
  293. const Twine &ErrMsg) {
  294. const Instruction *I = dyn_cast_or_null<Instruction>(V);
  295. if (!V)
  296. return Ctx.emitError(ErrMsg);
  297. const char *AsmError = ", possible invalid constraint for vector type";
  298. if (const CallInst *CI = dyn_cast<CallInst>(I))
  299. if (isa<InlineAsm>(CI->getCalledValue()))
  300. return Ctx.emitError(I, ErrMsg + AsmError);
  301. return Ctx.emitError(I, ErrMsg);
  302. }
  303. /// getCopyFromPartsVector - Create a value that contains the specified legal
  304. /// parts combined into the value they represent. If the parts combine to a
  305. /// type larger than ValueVT then AssertOp can be used to specify whether the
  306. /// extra bits are known to be zero (ISD::AssertZext) or sign extended from
  307. /// ValueVT (ISD::AssertSext).
  308. static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
  309. const SDValue *Parts, unsigned NumParts,
  310. MVT PartVT, EVT ValueVT, const Value *V,
  311. bool IsABIRegCopy) {
  312. assert(ValueVT.isVector() && "Not a vector value");
  313. assert(NumParts > 0 && "No parts to assemble!");
  314. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  315. SDValue Val = Parts[0];
  316. // Handle a multi-element vector.
  317. if (NumParts > 1) {
  318. EVT IntermediateVT;
  319. MVT RegisterVT;
  320. unsigned NumIntermediates;
  321. unsigned NumRegs;
  322. if (IsABIRegCopy) {
  323. NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
  324. *DAG.getContext(), ValueVT, IntermediateVT, NumIntermediates,
  325. RegisterVT);
  326. } else {
  327. NumRegs =
  328. TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
  329. NumIntermediates, RegisterVT);
  330. }
  331. assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
  332. NumParts = NumRegs; // Silence a compiler warning.
  333. assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
  334. assert(RegisterVT.getSizeInBits() ==
  335. Parts[0].getSimpleValueType().getSizeInBits() &&
  336. "Part type sizes don't match!");
  337. // Assemble the parts into intermediate operands.
  338. SmallVector<SDValue, 8> Ops(NumIntermediates);
  339. if (NumIntermediates == NumParts) {
  340. // If the register was not expanded, truncate or copy the value,
  341. // as appropriate.
  342. for (unsigned i = 0; i != NumParts; ++i)
  343. Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1,
  344. PartVT, IntermediateVT, V);
  345. } else if (NumParts > 0) {
  346. // If the intermediate type was expanded, build the intermediate
  347. // operands from the parts.
  348. assert(NumParts % NumIntermediates == 0 &&
  349. "Must expand into a divisible number of parts!");
  350. unsigned Factor = NumParts / NumIntermediates;
  351. for (unsigned i = 0; i != NumIntermediates; ++i)
  352. Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor,
  353. PartVT, IntermediateVT, V);
  354. }
  355. // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the
  356. // intermediate operands.
  357. EVT BuiltVectorTy =
  358. EVT::getVectorVT(*DAG.getContext(), IntermediateVT.getScalarType(),
  359. (IntermediateVT.isVector()
  360. ? IntermediateVT.getVectorNumElements() * NumParts
  361. : NumIntermediates));
  362. Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS
  363. : ISD::BUILD_VECTOR,
  364. DL, BuiltVectorTy, Ops);
  365. }
  366. // There is now one part, held in Val. Correct it to match ValueVT.
  367. EVT PartEVT = Val.getValueType();
  368. if (PartEVT == ValueVT)
  369. return Val;
  370. if (PartEVT.isVector()) {
  371. // If the element type of the source/dest vectors are the same, but the
  372. // parts vector has more elements than the value vector, then we have a
  373. // vector widening case (e.g. <2 x float> -> <4 x float>). Extract the
  374. // elements we want.
  375. if (PartEVT.getVectorElementType() == ValueVT.getVectorElementType()) {
  376. assert(PartEVT.getVectorNumElements() > ValueVT.getVectorNumElements() &&
  377. "Cannot narrow, it would be a lossy transformation");
  378. return DAG.getNode(
  379. ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
  380. DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
  381. }
  382. // Vector/Vector bitcast.
  383. if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits())
  384. return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
  385. assert(PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements() &&
  386. "Cannot handle this kind of promotion");
  387. // Promoted vector extract
  388. return DAG.getAnyExtOrTrunc(Val, DL, ValueVT);
  389. }
  390. // Trivial bitcast if the types are the same size and the destination
  391. // vector type is legal.
  392. if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() &&
  393. TLI.isTypeLegal(ValueVT))
  394. return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
  395. if (ValueVT.getVectorNumElements() != 1) {
  396. // Certain ABIs require that vectors are passed as integers. For vectors
  397. // are the same size, this is an obvious bitcast.
  398. if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) {
  399. return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
  400. } else if (ValueVT.getSizeInBits() < PartEVT.getSizeInBits()) {
  401. // Bitcast Val back the original type and extract the corresponding
  402. // vector we want.
  403. unsigned Elts = PartEVT.getSizeInBits() / ValueVT.getScalarSizeInBits();
  404. EVT WiderVecType = EVT::getVectorVT(*DAG.getContext(),
  405. ValueVT.getVectorElementType(), Elts);
  406. Val = DAG.getBitcast(WiderVecType, Val);
  407. return DAG.getNode(
  408. ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
  409. DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
  410. }
  411. diagnosePossiblyInvalidConstraint(
  412. *DAG.getContext(), V, "non-trivial scalar-to-vector conversion");
  413. return DAG.getUNDEF(ValueVT);
  414. }
  415. // Handle cases such as i8 -> <1 x i1>
  416. EVT ValueSVT = ValueVT.getVectorElementType();
  417. if (ValueVT.getVectorNumElements() == 1 && ValueSVT != PartEVT)
  418. Val = ValueVT.isFloatingPoint() ? DAG.getFPExtendOrRound(Val, DL, ValueSVT)
  419. : DAG.getAnyExtOrTrunc(Val, DL, ValueSVT);
  420. return DAG.getBuildVector(ValueVT, DL, Val);
  421. }
  422. static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl,
  423. SDValue Val, SDValue *Parts, unsigned NumParts,
  424. MVT PartVT, const Value *V, bool IsABIRegCopy);
  425. /// getCopyToParts - Create a series of nodes that contain the specified value
  426. /// split into legal parts. If the parts contain more bits than Val, then, for
  427. /// integers, ExtendKind can be used to specify how to generate the extra bits.
  428. static void getCopyToParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val,
  429. SDValue *Parts, unsigned NumParts, MVT PartVT,
  430. const Value *V,
  431. ISD::NodeType ExtendKind = ISD::ANY_EXTEND,
  432. bool IsABIRegCopy = false) {
  433. EVT ValueVT = Val.getValueType();
  434. // Handle the vector case separately.
  435. if (ValueVT.isVector())
  436. return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V,
  437. IsABIRegCopy);
  438. unsigned PartBits = PartVT.getSizeInBits();
  439. unsigned OrigNumParts = NumParts;
  440. assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) &&
  441. "Copying to an illegal type!");
  442. if (NumParts == 0)
  443. return;
  444. assert(!ValueVT.isVector() && "Vector case handled elsewhere");
  445. EVT PartEVT = PartVT;
  446. if (PartEVT == ValueVT) {
  447. assert(NumParts == 1 && "No-op copy with multiple parts!");
  448. Parts[0] = Val;
  449. return;
  450. }
  451. if (NumParts * PartBits > ValueVT.getSizeInBits()) {
  452. // If the parts cover more bits than the value has, promote the value.
  453. if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
  454. assert(NumParts == 1 && "Do not know what to promote to!");
  455. Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val);
  456. } else {
  457. if (ValueVT.isFloatingPoint()) {
  458. // FP values need to be bitcast, then extended if they are being put
  459. // into a larger container.
  460. ValueVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
  461. Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
  462. }
  463. assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
  464. ValueVT.isInteger() &&
  465. "Unknown mismatch!");
  466. ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
  467. Val = DAG.getNode(ExtendKind, DL, ValueVT, Val);
  468. if (PartVT == MVT::x86mmx)
  469. Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
  470. }
  471. } else if (PartBits == ValueVT.getSizeInBits()) {
  472. // Different types of the same size.
  473. assert(NumParts == 1 && PartEVT != ValueVT);
  474. Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
  475. } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
  476. // If the parts cover less bits than value has, truncate the value.
  477. assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
  478. ValueVT.isInteger() &&
  479. "Unknown mismatch!");
  480. ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
  481. Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
  482. if (PartVT == MVT::x86mmx)
  483. Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
  484. }
  485. // The value may have changed - recompute ValueVT.
  486. ValueVT = Val.getValueType();
  487. assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
  488. "Failed to tile the value with PartVT!");
  489. if (NumParts == 1) {
  490. if (PartEVT != ValueVT) {
  491. diagnosePossiblyInvalidConstraint(*DAG.getContext(), V,
  492. "scalar-to-vector conversion failed");
  493. Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
  494. }
  495. Parts[0] = Val;
  496. return;
  497. }
  498. // Expand the value into multiple parts.
  499. if (NumParts & (NumParts - 1)) {
  500. // The number of parts is not a power of 2. Split off and copy the tail.
  501. assert(PartVT.isInteger() && ValueVT.isInteger() &&
  502. "Do not know what to expand to!");
  503. unsigned RoundParts = 1 << Log2_32(NumParts);
  504. unsigned RoundBits = RoundParts * PartBits;
  505. unsigned OddParts = NumParts - RoundParts;
  506. SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val,
  507. DAG.getIntPtrConstant(RoundBits, DL));
  508. getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V);
  509. if (DAG.getDataLayout().isBigEndian())
  510. // The odd parts were reversed by getCopyToParts - unreverse them.
  511. std::reverse(Parts + RoundParts, Parts + NumParts);
  512. NumParts = RoundParts;
  513. ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
  514. Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
  515. }
  516. // The number of parts is a power of 2. Repeatedly bisect the value using
  517. // EXTRACT_ELEMENT.
  518. Parts[0] = DAG.getNode(ISD::BITCAST, DL,
  519. EVT::getIntegerVT(*DAG.getContext(),
  520. ValueVT.getSizeInBits()),
  521. Val);
  522. for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
  523. for (unsigned i = 0; i < NumParts; i += StepSize) {
  524. unsigned ThisBits = StepSize * PartBits / 2;
  525. EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits);
  526. SDValue &Part0 = Parts[i];
  527. SDValue &Part1 = Parts[i+StepSize/2];
  528. Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
  529. ThisVT, Part0, DAG.getIntPtrConstant(1, DL));
  530. Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
  531. ThisVT, Part0, DAG.getIntPtrConstant(0, DL));
  532. if (ThisBits == PartBits && ThisVT != PartVT) {
  533. Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0);
  534. Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1);
  535. }
  536. }
  537. }
  538. if (DAG.getDataLayout().isBigEndian())
  539. std::reverse(Parts, Parts + OrigNumParts);
  540. }
  541. /// getCopyToPartsVector - Create a series of nodes that contain the specified
  542. /// value split into legal parts.
  543. static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL,
  544. SDValue Val, SDValue *Parts, unsigned NumParts,
  545. MVT PartVT, const Value *V,
  546. bool IsABIRegCopy) {
  547. EVT ValueVT = Val.getValueType();
  548. assert(ValueVT.isVector() && "Not a vector");
  549. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  550. if (NumParts == 1) {
  551. EVT PartEVT = PartVT;
  552. if (PartEVT == ValueVT) {
  553. // Nothing to do.
  554. } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) {
  555. // Bitconvert vector->vector case.
  556. Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
  557. } else if (PartVT.isVector() &&
  558. PartEVT.getVectorElementType() == ValueVT.getVectorElementType() &&
  559. PartEVT.getVectorNumElements() > ValueVT.getVectorNumElements()) {
  560. EVT ElementVT = PartVT.getVectorElementType();
  561. // Vector widening case, e.g. <2 x float> -> <4 x float>. Shuffle in
  562. // undef elements.
  563. SmallVector<SDValue, 16> Ops;
  564. for (unsigned i = 0, e = ValueVT.getVectorNumElements(); i != e; ++i)
  565. Ops.push_back(DAG.getNode(
  566. ISD::EXTRACT_VECTOR_ELT, DL, ElementVT, Val,
  567. DAG.getConstant(i, DL, TLI.getVectorIdxTy(DAG.getDataLayout()))));
  568. for (unsigned i = ValueVT.getVectorNumElements(),
  569. e = PartVT.getVectorNumElements(); i != e; ++i)
  570. Ops.push_back(DAG.getUNDEF(ElementVT));
  571. Val = DAG.getBuildVector(PartVT, DL, Ops);
  572. // FIXME: Use CONCAT for 2x -> 4x.
  573. //SDValue UndefElts = DAG.getUNDEF(VectorTy);
  574. //Val = DAG.getNode(ISD::CONCAT_VECTORS, DL, PartVT, Val, UndefElts);
  575. } else if (PartVT.isVector() &&
  576. PartEVT.getVectorElementType().bitsGE(
  577. ValueVT.getVectorElementType()) &&
  578. PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements()) {
  579. // Promoted vector extract
  580. Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
  581. } else {
  582. if (ValueVT.getVectorNumElements() == 1) {
  583. Val = DAG.getNode(
  584. ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val,
  585. DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
  586. } else {
  587. assert(PartVT.getSizeInBits() > ValueVT.getSizeInBits() &&
  588. "lossy conversion of vector to scalar type");
  589. EVT IntermediateType =
  590. EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
  591. Val = DAG.getBitcast(IntermediateType, Val);
  592. Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
  593. }
  594. }
  595. assert(Val.getValueType() == PartVT && "Unexpected vector part value type");
  596. Parts[0] = Val;
  597. return;
  598. }
  599. // Handle a multi-element vector.
  600. EVT IntermediateVT;
  601. MVT RegisterVT;
  602. unsigned NumIntermediates;
  603. unsigned NumRegs;
  604. if (IsABIRegCopy) {
  605. NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
  606. *DAG.getContext(), ValueVT, IntermediateVT, NumIntermediates,
  607. RegisterVT);
  608. } else {
  609. NumRegs =
  610. TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
  611. NumIntermediates, RegisterVT);
  612. }
  613. unsigned NumElements = ValueVT.getVectorNumElements();
  614. assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
  615. NumParts = NumRegs; // Silence a compiler warning.
  616. assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
  617. // Convert the vector to the appropiate type if necessary.
  618. unsigned DestVectorNoElts =
  619. NumIntermediates *
  620. (IntermediateVT.isVector() ? IntermediateVT.getVectorNumElements() : 1);
  621. EVT BuiltVectorTy = EVT::getVectorVT(
  622. *DAG.getContext(), IntermediateVT.getScalarType(), DestVectorNoElts);
  623. if (Val.getValueType() != BuiltVectorTy)
  624. Val = DAG.getNode(ISD::BITCAST, DL, BuiltVectorTy, Val);
  625. // Split the vector into intermediate operands.
  626. SmallVector<SDValue, 8> Ops(NumIntermediates);
  627. for (unsigned i = 0; i != NumIntermediates; ++i) {
  628. if (IntermediateVT.isVector())
  629. Ops[i] =
  630. DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val,
  631. DAG.getConstant(i * (NumElements / NumIntermediates), DL,
  632. TLI.getVectorIdxTy(DAG.getDataLayout())));
  633. else
  634. Ops[i] = DAG.getNode(
  635. ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val,
  636. DAG.getConstant(i, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
  637. }
  638. // Split the intermediate operands into legal parts.
  639. if (NumParts == NumIntermediates) {
  640. // If the register was not expanded, promote or copy the value,
  641. // as appropriate.
  642. for (unsigned i = 0; i != NumParts; ++i)
  643. getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V);
  644. } else if (NumParts > 0) {
  645. // If the intermediate type was expanded, split each the value into
  646. // legal parts.
  647. assert(NumIntermediates != 0 && "division by zero");
  648. assert(NumParts % NumIntermediates == 0 &&
  649. "Must expand into a divisible number of parts!");
  650. unsigned Factor = NumParts / NumIntermediates;
  651. for (unsigned i = 0; i != NumIntermediates; ++i)
  652. getCopyToParts(DAG, DL, Ops[i], &Parts[i*Factor], Factor, PartVT, V);
  653. }
  654. }
  655. RegsForValue::RegsForValue(const SmallVector<unsigned, 4> &regs, MVT regvt,
  656. EVT valuevt, bool IsABIMangledValue)
  657. : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs),
  658. RegCount(1, regs.size()), IsABIMangled(IsABIMangledValue) {}
  659. RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI,
  660. const DataLayout &DL, unsigned Reg, Type *Ty,
  661. bool IsABIMangledValue) {
  662. ComputeValueVTs(TLI, DL, Ty, ValueVTs);
  663. IsABIMangled = IsABIMangledValue;
  664. for (EVT ValueVT : ValueVTs) {
  665. unsigned NumRegs = IsABIMangledValue
  666. ? TLI.getNumRegistersForCallingConv(Context, ValueVT)
  667. : TLI.getNumRegisters(Context, ValueVT);
  668. MVT RegisterVT = IsABIMangledValue
  669. ? TLI.getRegisterTypeForCallingConv(Context, ValueVT)
  670. : TLI.getRegisterType(Context, ValueVT);
  671. for (unsigned i = 0; i != NumRegs; ++i)
  672. Regs.push_back(Reg + i);
  673. RegVTs.push_back(RegisterVT);
  674. RegCount.push_back(NumRegs);
  675. Reg += NumRegs;
  676. }
  677. }
  678. SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
  679. FunctionLoweringInfo &FuncInfo,
  680. const SDLoc &dl, SDValue &Chain,
  681. SDValue *Flag, const Value *V) const {
  682. // A Value with type {} or [0 x %t] needs no registers.
  683. if (ValueVTs.empty())
  684. return SDValue();
  685. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  686. // Assemble the legal parts into the final values.
  687. SmallVector<SDValue, 4> Values(ValueVTs.size());
  688. SmallVector<SDValue, 8> Parts;
  689. for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
  690. // Copy the legal parts from the registers.
  691. EVT ValueVT = ValueVTs[Value];
  692. unsigned NumRegs = RegCount[Value];
  693. MVT RegisterVT = IsABIMangled
  694. ? TLI.getRegisterTypeForCallingConv(RegVTs[Value])
  695. : RegVTs[Value];
  696. Parts.resize(NumRegs);
  697. for (unsigned i = 0; i != NumRegs; ++i) {
  698. SDValue P;
  699. if (!Flag) {
  700. P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT);
  701. } else {
  702. P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag);
  703. *Flag = P.getValue(2);
  704. }
  705. Chain = P.getValue(1);
  706. Parts[i] = P;
  707. // If the source register was virtual and if we know something about it,
  708. // add an assert node.
  709. if (!TargetRegisterInfo::isVirtualRegister(Regs[Part+i]) ||
  710. !RegisterVT.isInteger() || RegisterVT.isVector())
  711. continue;
  712. const FunctionLoweringInfo::LiveOutInfo *LOI =
  713. FuncInfo.GetLiveOutRegInfo(Regs[Part+i]);
  714. if (!LOI)
  715. continue;
  716. unsigned RegSize = RegisterVT.getSizeInBits();
  717. unsigned NumSignBits = LOI->NumSignBits;
  718. unsigned NumZeroBits = LOI->Known.countMinLeadingZeros();
  719. if (NumZeroBits == RegSize) {
  720. // The current value is a zero.
  721. // Explicitly express that as it would be easier for
  722. // optimizations to kick in.
  723. Parts[i] = DAG.getConstant(0, dl, RegisterVT);
  724. continue;
  725. }
  726. // FIXME: We capture more information than the dag can represent. For
  727. // now, just use the tightest assertzext/assertsext possible.
  728. bool isSExt = true;
  729. EVT FromVT(MVT::Other);
  730. if (NumSignBits == RegSize) {
  731. isSExt = true; // ASSERT SEXT 1
  732. FromVT = MVT::i1;
  733. } else if (NumZeroBits >= RegSize - 1) {
  734. isSExt = false; // ASSERT ZEXT 1
  735. FromVT = MVT::i1;
  736. } else if (NumSignBits > RegSize - 8) {
  737. isSExt = true; // ASSERT SEXT 8
  738. FromVT = MVT::i8;
  739. } else if (NumZeroBits >= RegSize - 8) {
  740. isSExt = false; // ASSERT ZEXT 8
  741. FromVT = MVT::i8;
  742. } else if (NumSignBits > RegSize - 16) {
  743. isSExt = true; // ASSERT SEXT 16
  744. FromVT = MVT::i16;
  745. } else if (NumZeroBits >= RegSize - 16) {
  746. isSExt = false; // ASSERT ZEXT 16
  747. FromVT = MVT::i16;
  748. } else if (NumSignBits > RegSize - 32) {
  749. isSExt = true; // ASSERT SEXT 32
  750. FromVT = MVT::i32;
  751. } else if (NumZeroBits >= RegSize - 32) {
  752. isSExt = false; // ASSERT ZEXT 32
  753. FromVT = MVT::i32;
  754. } else {
  755. continue;
  756. }
  757. // Add an assertion node.
  758. assert(FromVT != MVT::Other);
  759. Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl,
  760. RegisterVT, P, DAG.getValueType(FromVT));
  761. }
  762. Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(),
  763. NumRegs, RegisterVT, ValueVT, V);
  764. Part += NumRegs;
  765. Parts.clear();
  766. }
  767. return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values);
  768. }
  769. void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG,
  770. const SDLoc &dl, SDValue &Chain, SDValue *Flag,
  771. const Value *V,
  772. ISD::NodeType PreferredExtendType) const {
  773. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  774. ISD::NodeType ExtendKind = PreferredExtendType;
  775. // Get the list of the values's legal parts.
  776. unsigned NumRegs = Regs.size();
  777. SmallVector<SDValue, 8> Parts(NumRegs);
  778. for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
  779. unsigned NumParts = RegCount[Value];
  780. MVT RegisterVT = IsABIMangled
  781. ? TLI.getRegisterTypeForCallingConv(RegVTs[Value])
  782. : RegVTs[Value];
  783. if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT))
  784. ExtendKind = ISD::ZERO_EXTEND;
  785. getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value),
  786. &Parts[Part], NumParts, RegisterVT, V, ExtendKind);
  787. Part += NumParts;
  788. }
  789. // Copy the parts into the registers.
  790. SmallVector<SDValue, 8> Chains(NumRegs);
  791. for (unsigned i = 0; i != NumRegs; ++i) {
  792. SDValue Part;
  793. if (!Flag) {
  794. Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]);
  795. } else {
  796. Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag);
  797. *Flag = Part.getValue(1);
  798. }
  799. Chains[i] = Part.getValue(0);
  800. }
  801. if (NumRegs == 1 || Flag)
  802. // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
  803. // flagged to it. That is the CopyToReg nodes and the user are considered
  804. // a single scheduling unit. If we create a TokenFactor and return it as
  805. // chain, then the TokenFactor is both a predecessor (operand) of the
  806. // user as well as a successor (the TF operands are flagged to the user).
  807. // c1, f1 = CopyToReg
  808. // c2, f2 = CopyToReg
  809. // c3 = TokenFactor c1, c2
  810. // ...
  811. // = op c3, ..., f2
  812. Chain = Chains[NumRegs-1];
  813. else
  814. Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
  815. }
  816. void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching,
  817. unsigned MatchingIdx, const SDLoc &dl,
  818. SelectionDAG &DAG,
  819. std::vector<SDValue> &Ops) const {
  820. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  821. unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size());
  822. if (HasMatching)
  823. Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx);
  824. else if (!Regs.empty() &&
  825. TargetRegisterInfo::isVirtualRegister(Regs.front())) {
  826. // Put the register class of the virtual registers in the flag word. That
  827. // way, later passes can recompute register class constraints for inline
  828. // assembly as well as normal instructions.
  829. // Don't do this for tied operands that can use the regclass information
  830. // from the def.
  831. const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
  832. const TargetRegisterClass *RC = MRI.getRegClass(Regs.front());
  833. Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID());
  834. }
  835. SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32);
  836. Ops.push_back(Res);
  837. if (Code == InlineAsm::Kind_Clobber) {
  838. // Clobbers should always have a 1:1 mapping with registers, and may
  839. // reference registers that have illegal (e.g. vector) types. Hence, we
  840. // shouldn't try to apply any sort of splitting logic to them.
  841. assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() &&
  842. "No 1:1 mapping from clobbers to regs?");
  843. unsigned SP = TLI.getStackPointerRegisterToSaveRestore();
  844. (void)SP;
  845. for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) {
  846. Ops.push_back(DAG.getRegister(Regs[I], RegVTs[I]));
  847. assert(
  848. (Regs[I] != SP ||
  849. DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment()) &&
  850. "If we clobbered the stack pointer, MFI should know about it.");
  851. }
  852. return;
  853. }
  854. for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
  855. unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value]);
  856. MVT RegisterVT = RegVTs[Value];
  857. for (unsigned i = 0; i != NumRegs; ++i) {
  858. assert(Reg < Regs.size() && "Mismatch in # registers expected");
  859. unsigned TheReg = Regs[Reg++];
  860. Ops.push_back(DAG.getRegister(TheReg, RegisterVT));
  861. }
  862. }
  863. }
  864. SmallVector<std::pair<unsigned, unsigned>, 4>
  865. RegsForValue::getRegsAndSizes() const {
  866. SmallVector<std::pair<unsigned, unsigned>, 4> OutVec;
  867. unsigned I = 0;
  868. for (auto CountAndVT : zip_first(RegCount, RegVTs)) {
  869. unsigned RegCount = std::get<0>(CountAndVT);
  870. MVT RegisterVT = std::get<1>(CountAndVT);
  871. unsigned RegisterSize = RegisterVT.getSizeInBits();
  872. for (unsigned E = I + RegCount; I != E; ++I)
  873. OutVec.push_back(std::make_pair(Regs[I], RegisterSize));
  874. }
  875. return OutVec;
  876. }
  877. void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis *aa,
  878. const TargetLibraryInfo *li) {
  879. AA = aa;
  880. GFI = gfi;
  881. LibInfo = li;
  882. DL = &DAG.getDataLayout();
  883. Context = DAG.getContext();
  884. LPadToCallSiteMap.clear();
  885. }
  886. void SelectionDAGBuilder::clear() {
  887. NodeMap.clear();
  888. UnusedArgNodeMap.clear();
  889. PendingLoads.clear();
  890. PendingExports.clear();
  891. CurInst = nullptr;
  892. HasTailCall = false;
  893. SDNodeOrder = LowestSDNodeOrder;
  894. StatepointLowering.clear();
  895. }
  896. void SelectionDAGBuilder::clearDanglingDebugInfo() {
  897. DanglingDebugInfoMap.clear();
  898. }
  899. SDValue SelectionDAGBuilder::getRoot() {
  900. if (PendingLoads.empty())
  901. return DAG.getRoot();
  902. if (PendingLoads.size() == 1) {
  903. SDValue Root = PendingLoads[0];
  904. DAG.setRoot(Root);
  905. PendingLoads.clear();
  906. return Root;
  907. }
  908. // Otherwise, we have to make a token factor node.
  909. SDValue Root = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other,
  910. PendingLoads);
  911. PendingLoads.clear();
  912. DAG.setRoot(Root);
  913. return Root;
  914. }
  915. SDValue SelectionDAGBuilder::getControlRoot() {
  916. SDValue Root = DAG.getRoot();
  917. if (PendingExports.empty())
  918. return Root;
  919. // Turn all of the CopyToReg chains into one factored node.
  920. if (Root.getOpcode() != ISD::EntryToken) {
  921. unsigned i = 0, e = PendingExports.size();
  922. for (; i != e; ++i) {
  923. assert(PendingExports[i].getNode()->getNumOperands() > 1);
  924. if (PendingExports[i].getNode()->getOperand(0) == Root)
  925. break; // Don't add the root if we already indirectly depend on it.
  926. }
  927. if (i == e)
  928. PendingExports.push_back(Root);
  929. }
  930. Root = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other,
  931. PendingExports);
  932. PendingExports.clear();
  933. DAG.setRoot(Root);
  934. return Root;
  935. }
  936. void SelectionDAGBuilder::visit(const Instruction &I) {
  937. // Set up outgoing PHI node register values before emitting the terminator.
  938. if (isa<TerminatorInst>(&I)) {
  939. HandlePHINodesInSuccessorBlocks(I.getParent());
  940. }
  941. // Increase the SDNodeOrder if dealing with a non-debug instruction.
  942. if (!isa<DbgInfoIntrinsic>(I))
  943. ++SDNodeOrder;
  944. CurInst = &I;
  945. visit(I.getOpcode(), I);
  946. if (!isa<TerminatorInst>(&I) && !HasTailCall &&
  947. !isStatepoint(&I)) // statepoints handle their exports internally
  948. CopyToExportRegsIfNeeded(&I);
  949. CurInst = nullptr;
  950. }
  951. void SelectionDAGBuilder::visitPHI(const PHINode &) {
  952. llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!");
  953. }
  954. void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) {
  955. // Note: this doesn't use InstVisitor, because it has to work with
  956. // ConstantExpr's in addition to instructions.
  957. switch (Opcode) {
  958. default: llvm_unreachable("Unknown instruction type encountered!");
  959. // Build the switch statement using the Instruction.def file.
  960. #define HANDLE_INST(NUM, OPCODE, CLASS) \
  961. case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break;
  962. #include "llvm/IR/Instruction.def"
  963. }
  964. }
  965. void SelectionDAGBuilder::dropDanglingDebugInfo(const DILocalVariable *Variable,
  966. const DIExpression *Expr) {
  967. for (auto &DDIMI : DanglingDebugInfoMap)
  968. for (auto &DDI : DDIMI.second)
  969. if (DDI.getDI()) {
  970. const DbgValueInst *DI = DDI.getDI();
  971. DIVariable *DanglingVariable = DI->getVariable();
  972. DIExpression *DanglingExpr = DI->getExpression();
  973. if (DanglingVariable == Variable &&
  974. Expr->fragmentsOverlap(DanglingExpr)) {
  975. DEBUG(dbgs() << "Dropping dangling debug info for " << *DI << "\n");
  976. DDI = DanglingDebugInfo();
  977. }
  978. }
  979. }
  980. // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V,
  981. // generate the debug data structures now that we've seen its definition.
  982. void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V,
  983. SDValue Val) {
  984. DanglingDebugInfoVector &DDIV = DanglingDebugInfoMap[V];
  985. for (auto &DDI : DDIV) {
  986. if (!DDI.getDI())
  987. continue;
  988. const DbgValueInst *DI = DDI.getDI();
  989. DebugLoc dl = DDI.getdl();
  990. unsigned ValSDNodeOrder = Val.getNode()->getIROrder();
  991. unsigned DbgSDNodeOrder = DDI.getSDNodeOrder();
  992. DILocalVariable *Variable = DI->getVariable();
  993. DIExpression *Expr = DI->getExpression();
  994. assert(Variable->isValidLocationForIntrinsic(dl) &&
  995. "Expected inlined-at fields to agree");
  996. SDDbgValue *SDV;
  997. if (Val.getNode()) {
  998. if (!EmitFuncArgumentDbgValue(V, Variable, Expr, dl, false, Val)) {
  999. DEBUG(dbgs() << "Resolve dangling debug info [order=" << DbgSDNodeOrder
  1000. << "] for:\n " << *DI << "\n");
  1001. DEBUG(dbgs() << " By mapping to:\n "; Val.dump());
  1002. // Increase the SDNodeOrder for the DbgValue here to make sure it is
  1003. // inserted after the definition of Val when emitting the instructions
  1004. // after ISel. An alternative could be to teach
  1005. // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly.
  1006. DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder)
  1007. dbgs() << "changing SDNodeOrder from " << DbgSDNodeOrder
  1008. << " to " << ValSDNodeOrder << "\n");
  1009. SDV = getDbgValue(Val, Variable, Expr, dl,
  1010. std::max(DbgSDNodeOrder, ValSDNodeOrder));
  1011. DAG.AddDbgValue(SDV, Val.getNode(), false);
  1012. } else
  1013. DEBUG(dbgs() << "Resolved dangling debug info for " << *DI
  1014. << "in EmitFuncArgumentDbgValue\n");
  1015. } else
  1016. DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
  1017. }
  1018. DanglingDebugInfoMap[V].clear();
  1019. }
  1020. /// getCopyFromRegs - If there was virtual register allocated for the value V
  1021. /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise.
  1022. SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) {
  1023. DenseMap<const Value *, unsigned>::iterator It = FuncInfo.ValueMap.find(V);
  1024. SDValue Result;
  1025. if (It != FuncInfo.ValueMap.end()) {
  1026. unsigned InReg = It->second;
  1027. RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(),
  1028. DAG.getDataLayout(), InReg, Ty, isABIRegCopy(V));
  1029. SDValue Chain = DAG.getEntryNode();
  1030. Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr,
  1031. V);
  1032. resolveDanglingDebugInfo(V, Result);
  1033. }
  1034. return Result;
  1035. }
  1036. /// getValue - Return an SDValue for the given Value.
  1037. SDValue SelectionDAGBuilder::getValue(const Value *V) {
  1038. // If we already have an SDValue for this value, use it. It's important
  1039. // to do this first, so that we don't create a CopyFromReg if we already
  1040. // have a regular SDValue.
  1041. SDValue &N = NodeMap[V];
  1042. if (N.getNode()) return N;
  1043. // If there's a virtual register allocated and initialized for this
  1044. // value, use it.
  1045. if (SDValue copyFromReg = getCopyFromRegs(V, V->getType()))
  1046. return copyFromReg;
  1047. // Otherwise create a new SDValue and remember it.
  1048. SDValue Val = getValueImpl(V);
  1049. NodeMap[V] = Val;
  1050. resolveDanglingDebugInfo(V, Val);
  1051. return Val;
  1052. }
  1053. // Return true if SDValue exists for the given Value
  1054. bool SelectionDAGBuilder::findValue(const Value *V) const {
  1055. return (NodeMap.find(V) != NodeMap.end()) ||
  1056. (FuncInfo.ValueMap.find(V) != FuncInfo.ValueMap.end());
  1057. }
  1058. /// getNonRegisterValue - Return an SDValue for the given Value, but
  1059. /// don't look in FuncInfo.ValueMap for a virtual register.
  1060. SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) {
  1061. // If we already have an SDValue for this value, use it.
  1062. SDValue &N = NodeMap[V];
  1063. if (N.getNode()) {
  1064. if (isa<ConstantSDNode>(N) || isa<ConstantFPSDNode>(N)) {
  1065. // Remove the debug location from the node as the node is about to be used
  1066. // in a location which may differ from the original debug location. This
  1067. // is relevant to Constant and ConstantFP nodes because they can appear
  1068. // as constant expressions inside PHI nodes.
  1069. N->setDebugLoc(DebugLoc());
  1070. }
  1071. return N;
  1072. }
  1073. // Otherwise create a new SDValue and remember it.
  1074. SDValue Val = getValueImpl(V);
  1075. NodeMap[V] = Val;
  1076. resolveDanglingDebugInfo(V, Val);
  1077. return Val;
  1078. }
  1079. /// getValueImpl - Helper function for getValue and getNonRegisterValue.
  1080. /// Create an SDValue for the given value.
  1081. SDValue SelectionDAGBuilder::getValueImpl(const Value *V) {
  1082. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  1083. if (const Constant *C = dyn_cast<Constant>(V)) {
  1084. EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true);
  1085. if (const ConstantInt *CI = dyn_cast<ConstantInt>(C))
  1086. return DAG.getConstant(*CI, getCurSDLoc(), VT);
  1087. if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
  1088. return DAG.getGlobalAddress(GV, getCurSDLoc(), VT);
  1089. if (isa<ConstantPointerNull>(C)) {
  1090. unsigned AS = V->getType()->getPointerAddressSpace();
  1091. return DAG.getConstant(0, getCurSDLoc(),
  1092. TLI.getPointerTy(DAG.getDataLayout(), AS));
  1093. }
  1094. if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
  1095. return DAG.getConstantFP(*CFP, getCurSDLoc(), VT);
  1096. if (isa<UndefValue>(C) && !V->getType()->isAggregateType())
  1097. return DAG.getUNDEF(VT);
  1098. if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
  1099. visit(CE->getOpcode(), *CE);
  1100. SDValue N1 = NodeMap[V];
  1101. assert(N1.getNode() && "visit didn't populate the NodeMap!");
  1102. return N1;
  1103. }
  1104. if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
  1105. SmallVector<SDValue, 4> Constants;
  1106. for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end();
  1107. OI != OE; ++OI) {
  1108. SDNode *Val = getValue(*OI).getNode();
  1109. // If the operand is an empty aggregate, there are no values.
  1110. if (!Val) continue;
  1111. // Add each leaf value from the operand to the Constants list
  1112. // to form a flattened list of all the values.
  1113. for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
  1114. Constants.push_back(SDValue(Val, i));
  1115. }
  1116. return DAG.getMergeValues(Constants, getCurSDLoc());
  1117. }
  1118. if (const ConstantDataSequential *CDS =
  1119. dyn_cast<ConstantDataSequential>(C)) {
  1120. SmallVector<SDValue, 4> Ops;
  1121. for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
  1122. SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode();
  1123. // Add each leaf value from the operand to the Constants list
  1124. // to form a flattened list of all the values.
  1125. for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
  1126. Ops.push_back(SDValue(Val, i));
  1127. }
  1128. if (isa<ArrayType>(CDS->getType()))
  1129. return DAG.getMergeValues(Ops, getCurSDLoc());
  1130. return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
  1131. }
  1132. if (C->getType()->isStructTy() || C->getType()->isArrayTy()) {
  1133. assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
  1134. "Unknown struct or array constant!");
  1135. SmallVector<EVT, 4> ValueVTs;
  1136. ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs);
  1137. unsigned NumElts = ValueVTs.size();
  1138. if (NumElts == 0)
  1139. return SDValue(); // empty struct
  1140. SmallVector<SDValue, 4> Constants(NumElts);
  1141. for (unsigned i = 0; i != NumElts; ++i) {
  1142. EVT EltVT = ValueVTs[i];
  1143. if (isa<UndefValue>(C))
  1144. Constants[i] = DAG.getUNDEF(EltVT);
  1145. else if (EltVT.isFloatingPoint())
  1146. Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
  1147. else
  1148. Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT);
  1149. }
  1150. return DAG.getMergeValues(Constants, getCurSDLoc());
  1151. }
  1152. if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
  1153. return DAG.getBlockAddress(BA, VT);
  1154. VectorType *VecTy = cast<VectorType>(V->getType());
  1155. unsigned NumElements = VecTy->getNumElements();
  1156. // Now that we know the number and type of the elements, get that number of
  1157. // elements into the Ops array based on what kind of constant it is.
  1158. SmallVector<SDValue, 16> Ops;
  1159. if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) {
  1160. for (unsigned i = 0; i != NumElements; ++i)
  1161. Ops.push_back(getValue(CV->getOperand(i)));
  1162. } else {
  1163. assert(isa<ConstantAggregateZero>(C) && "Unknown vector constant!");
  1164. EVT EltVT =
  1165. TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType());
  1166. SDValue Op;
  1167. if (EltVT.isFloatingPoint())
  1168. Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
  1169. else
  1170. Op = DAG.getConstant(0, getCurSDLoc(), EltVT);
  1171. Ops.assign(NumElements, Op);
  1172. }
  1173. // Create a BUILD_VECTOR node.
  1174. return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
  1175. }
  1176. // If this is a static alloca, generate it as the frameindex instead of
  1177. // computation.
  1178. if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
  1179. DenseMap<const AllocaInst*, int>::iterator SI =
  1180. FuncInfo.StaticAllocaMap.find(AI);
  1181. if (SI != FuncInfo.StaticAllocaMap.end())
  1182. return DAG.getFrameIndex(SI->second,
  1183. TLI.getFrameIndexTy(DAG.getDataLayout()));
  1184. }
  1185. // If this is an instruction which fast-isel has deferred, select it now.
  1186. if (const Instruction *Inst = dyn_cast<Instruction>(V)) {
  1187. unsigned InReg = FuncInfo.InitializeRegForValue(Inst);
  1188. RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg,
  1189. Inst->getType(), isABIRegCopy(V));
  1190. SDValue Chain = DAG.getEntryNode();
  1191. return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V);
  1192. }
  1193. llvm_unreachable("Can't get register for value!");
  1194. }
  1195. void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) {
  1196. auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
  1197. bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX;
  1198. bool IsCoreCLR = Pers == EHPersonality::CoreCLR;
  1199. MachineBasicBlock *CatchPadMBB = FuncInfo.MBB;
  1200. // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues.
  1201. if (IsMSVCCXX || IsCoreCLR)
  1202. CatchPadMBB->setIsEHFuncletEntry();
  1203. DAG.setRoot(DAG.getNode(ISD::CATCHPAD, getCurSDLoc(), MVT::Other, getControlRoot()));
  1204. }
  1205. void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) {
  1206. // Update machine-CFG edge.
  1207. MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()];
  1208. FuncInfo.MBB->addSuccessor(TargetMBB);
  1209. auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
  1210. bool IsSEH = isAsynchronousEHPersonality(Pers);
  1211. if (IsSEH) {
  1212. // If this is not a fall-through branch or optimizations are switched off,
  1213. // emit the branch.
  1214. if (TargetMBB != NextBlock(FuncInfo.MBB) ||
  1215. TM.getOptLevel() == CodeGenOpt::None)
  1216. DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
  1217. getControlRoot(), DAG.getBasicBlock(TargetMBB)));
  1218. return;
  1219. }
  1220. // Figure out the funclet membership for the catchret's successor.
  1221. // This will be used by the FuncletLayout pass to determine how to order the
  1222. // BB's.
  1223. // A 'catchret' returns to the outer scope's color.
  1224. Value *ParentPad = I.getCatchSwitchParentPad();
  1225. const BasicBlock *SuccessorColor;
  1226. if (isa<ConstantTokenNone>(ParentPad))
  1227. SuccessorColor = &FuncInfo.Fn->getEntryBlock();
  1228. else
  1229. SuccessorColor = cast<Instruction>(ParentPad)->getParent();
  1230. assert(SuccessorColor && "No parent funclet for catchret!");
  1231. MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor];
  1232. assert(SuccessorColorMBB && "No MBB for SuccessorColor!");
  1233. // Create the terminator node.
  1234. SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other,
  1235. getControlRoot(), DAG.getBasicBlock(TargetMBB),
  1236. DAG.getBasicBlock(SuccessorColorMBB));
  1237. DAG.setRoot(Ret);
  1238. }
  1239. void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) {
  1240. // Don't emit any special code for the cleanuppad instruction. It just marks
  1241. // the start of a funclet.
  1242. FuncInfo.MBB->setIsEHFuncletEntry();
  1243. FuncInfo.MBB->setIsCleanupFuncletEntry();
  1244. }
  1245. /// When an invoke or a cleanupret unwinds to the next EH pad, there are
  1246. /// many places it could ultimately go. In the IR, we have a single unwind
  1247. /// destination, but in the machine CFG, we enumerate all the possible blocks.
  1248. /// This function skips over imaginary basic blocks that hold catchswitch
  1249. /// instructions, and finds all the "real" machine
  1250. /// basic block destinations. As those destinations may not be successors of
  1251. /// EHPadBB, here we also calculate the edge probability to those destinations.
  1252. /// The passed-in Prob is the edge probability to EHPadBB.
  1253. static void findUnwindDestinations(
  1254. FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
  1255. BranchProbability Prob,
  1256. SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
  1257. &UnwindDests) {
  1258. EHPersonality Personality =
  1259. classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
  1260. bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX;
  1261. bool IsCoreCLR = Personality == EHPersonality::CoreCLR;
  1262. while (EHPadBB) {
  1263. const Instruction *Pad = EHPadBB->getFirstNonPHI();
  1264. BasicBlock *NewEHPadBB = nullptr;
  1265. if (isa<LandingPadInst>(Pad)) {
  1266. // Stop on landingpads. They are not funclets.
  1267. UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
  1268. break;
  1269. } else if (isa<CleanupPadInst>(Pad)) {
  1270. // Stop on cleanup pads. Cleanups are always funclet entries for all known
  1271. // personalities.
  1272. UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
  1273. UnwindDests.back().first->setIsEHFuncletEntry();
  1274. break;
  1275. } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
  1276. // Add the catchpad handlers to the possible destinations.
  1277. for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
  1278. UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
  1279. // For MSVC++ and the CLR, catchblocks are funclets and need prologues.
  1280. if (IsMSVCCXX || IsCoreCLR)
  1281. UnwindDests.back().first->setIsEHFuncletEntry();
  1282. }
  1283. NewEHPadBB = CatchSwitch->getUnwindDest();
  1284. } else {
  1285. continue;
  1286. }
  1287. BranchProbabilityInfo *BPI = FuncInfo.BPI;
  1288. if (BPI && NewEHPadBB)
  1289. Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB);
  1290. EHPadBB = NewEHPadBB;
  1291. }
  1292. }
  1293. void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) {
  1294. // Update successor info.
  1295. SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
  1296. auto UnwindDest = I.getUnwindDest();
  1297. BranchProbabilityInfo *BPI = FuncInfo.BPI;
  1298. BranchProbability UnwindDestProb =
  1299. (BPI && UnwindDest)
  1300. ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest)
  1301. : BranchProbability::getZero();
  1302. findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests);
  1303. for (auto &UnwindDest : UnwindDests) {
  1304. UnwindDest.first->setIsEHPad();
  1305. addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second);
  1306. }
  1307. FuncInfo.MBB->normalizeSuccProbs();
  1308. // Create the terminator node.
  1309. SDValue Ret =
  1310. DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot());
  1311. DAG.setRoot(Ret);
  1312. }
  1313. void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) {
  1314. report_fatal_error("visitCatchSwitch not yet implemented!");
  1315. }
  1316. void SelectionDAGBuilder::visitRet(const ReturnInst &I) {
  1317. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  1318. auto &DL = DAG.getDataLayout();
  1319. SDValue Chain = getControlRoot();
  1320. SmallVector<ISD::OutputArg, 8> Outs;
  1321. SmallVector<SDValue, 8> OutVals;
  1322. // Calls to @llvm.experimental.deoptimize don't generate a return value, so
  1323. // lower
  1324. //
  1325. // %val = call <ty> @llvm.experimental.deoptimize()
  1326. // ret <ty> %val
  1327. //
  1328. // differently.
  1329. if (I.getParent()->getTerminatingDeoptimizeCall()) {
  1330. LowerDeoptimizingReturn();
  1331. return;
  1332. }
  1333. if (!FuncInfo.CanLowerReturn) {
  1334. unsigned DemoteReg = FuncInfo.DemoteRegister;
  1335. const Function *F = I.getParent()->getParent();
  1336. // Emit a store of the return value through the virtual register.
  1337. // Leave Outs empty so that LowerReturn won't try to load return
  1338. // registers the usual way.
  1339. SmallVector<EVT, 1> PtrValueVTs;
  1340. ComputeValueVTs(TLI, DL,
  1341. F->getReturnType()->getPointerTo(
  1342. DAG.getDataLayout().getAllocaAddrSpace()),
  1343. PtrValueVTs);
  1344. SDValue RetPtr = DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(),
  1345. DemoteReg, PtrValueVTs[0]);
  1346. SDValue RetOp = getValue(I.getOperand(0));
  1347. SmallVector<EVT, 4> ValueVTs;
  1348. SmallVector<uint64_t, 4> Offsets;
  1349. ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &Offsets);
  1350. unsigned NumValues = ValueVTs.size();
  1351. SmallVector<SDValue, 4> Chains(NumValues);
  1352. for (unsigned i = 0; i != NumValues; ++i) {
  1353. // An aggregate return value cannot wrap around the address space, so
  1354. // offsets to its parts don't wrap either.
  1355. SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr, Offsets[i]);
  1356. Chains[i] = DAG.getStore(
  1357. Chain, getCurSDLoc(), SDValue(RetOp.getNode(), RetOp.getResNo() + i),
  1358. // FIXME: better loc info would be nice.
  1359. Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction()));
  1360. }
  1361. Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
  1362. MVT::Other, Chains);
  1363. } else if (I.getNumOperands() != 0) {
  1364. SmallVector<EVT, 4> ValueVTs;
  1365. ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs);
  1366. unsigned NumValues = ValueVTs.size();
  1367. if (NumValues) {
  1368. SDValue RetOp = getValue(I.getOperand(0));
  1369. const Function *F = I.getParent()->getParent();
  1370. ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
  1371. if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex,
  1372. Attribute::SExt))
  1373. ExtendKind = ISD::SIGN_EXTEND;
  1374. else if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex,
  1375. Attribute::ZExt))
  1376. ExtendKind = ISD::ZERO_EXTEND;
  1377. LLVMContext &Context = F->getContext();
  1378. bool RetInReg = F->getAttributes().hasAttribute(
  1379. AttributeList::ReturnIndex, Attribute::InReg);
  1380. for (unsigned j = 0; j != NumValues; ++j) {
  1381. EVT VT = ValueVTs[j];
  1382. if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger())
  1383. VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind);
  1384. unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, VT);
  1385. MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, VT);
  1386. SmallVector<SDValue, 4> Parts(NumParts);
  1387. getCopyToParts(DAG, getCurSDLoc(),
  1388. SDValue(RetOp.getNode(), RetOp.getResNo() + j),
  1389. &Parts[0], NumParts, PartVT, &I, ExtendKind, true);
  1390. // 'inreg' on function refers to return value
  1391. ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
  1392. if (RetInReg)
  1393. Flags.setInReg();
  1394. // Propagate extension type if any
  1395. if (ExtendKind == ISD::SIGN_EXTEND)
  1396. Flags.setSExt();
  1397. else if (ExtendKind == ISD::ZERO_EXTEND)
  1398. Flags.setZExt();
  1399. for (unsigned i = 0; i < NumParts; ++i) {
  1400. Outs.push_back(ISD::OutputArg(Flags, Parts[i].getValueType(),
  1401. VT, /*isfixed=*/true, 0, 0));
  1402. OutVals.push_back(Parts[i]);
  1403. }
  1404. }
  1405. }
  1406. }
  1407. // Push in swifterror virtual register as the last element of Outs. This makes
  1408. // sure swifterror virtual register will be returned in the swifterror
  1409. // physical register.
  1410. const Function *F = I.getParent()->getParent();
  1411. if (TLI.supportSwiftError() &&
  1412. F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) {
  1413. assert(FuncInfo.SwiftErrorArg && "Need a swift error argument");
  1414. ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
  1415. Flags.setSwiftError();
  1416. Outs.push_back(ISD::OutputArg(Flags, EVT(TLI.getPointerTy(DL)) /*vt*/,
  1417. EVT(TLI.getPointerTy(DL)) /*argvt*/,
  1418. true /*isfixed*/, 1 /*origidx*/,
  1419. 0 /*partOffs*/));
  1420. // Create SDNode for the swifterror virtual register.
  1421. OutVals.push_back(
  1422. DAG.getRegister(FuncInfo.getOrCreateSwiftErrorVRegUseAt(
  1423. &I, FuncInfo.MBB, FuncInfo.SwiftErrorArg).first,
  1424. EVT(TLI.getPointerTy(DL))));
  1425. }
  1426. bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg();
  1427. CallingConv::ID CallConv =
  1428. DAG.getMachineFunction().getFunction().getCallingConv();
  1429. Chain = DAG.getTargetLoweringInfo().LowerReturn(
  1430. Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG);
  1431. // Verify that the target's LowerReturn behaved as expected.
  1432. assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
  1433. "LowerReturn didn't return a valid chain!");
  1434. // Update the DAG with the new chain value resulting from return lowering.
  1435. DAG.setRoot(Chain);
  1436. }
  1437. /// CopyToExportRegsIfNeeded - If the given value has virtual registers
  1438. /// created for it, emit nodes to copy the value into the virtual
  1439. /// registers.
  1440. void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) {
  1441. // Skip empty types
  1442. if (V->getType()->isEmptyTy())
  1443. return;
  1444. DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
  1445. if (VMI != FuncInfo.ValueMap.end()) {
  1446. assert(!V->use_empty() && "Unused value assigned virtual registers!");
  1447. CopyValueToVirtualRegister(V, VMI->second);
  1448. }
  1449. }
  1450. /// ExportFromCurrentBlock - If this condition isn't known to be exported from
  1451. /// the current basic block, add it to ValueMap now so that we'll get a
  1452. /// CopyTo/FromReg.
  1453. void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) {
  1454. // No need to export constants.
  1455. if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
  1456. // Already exported?
  1457. if (FuncInfo.isExportedInst(V)) return;
  1458. unsigned Reg = FuncInfo.InitializeRegForValue(V);
  1459. CopyValueToVirtualRegister(V, Reg);
  1460. }
  1461. bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V,
  1462. const BasicBlock *FromBB) {
  1463. // The operands of the setcc have to be in this block. We don't know
  1464. // how to export them from some other block.
  1465. if (const Instruction *VI = dyn_cast<Instruction>(V)) {
  1466. // Can export from current BB.
  1467. if (VI->getParent() == FromBB)
  1468. return true;
  1469. // Is already exported, noop.
  1470. return FuncInfo.isExportedInst(V);
  1471. }
  1472. // If this is an argument, we can export it if the BB is the entry block or
  1473. // if it is already exported.
  1474. if (isa<Argument>(V)) {
  1475. if (FromBB == &FromBB->getParent()->getEntryBlock())
  1476. return true;
  1477. // Otherwise, can only export this if it is already exported.
  1478. return FuncInfo.isExportedInst(V);
  1479. }
  1480. // Otherwise, constants can always be exported.
  1481. return true;
  1482. }
  1483. /// Return branch probability calculated by BranchProbabilityInfo for IR blocks.
  1484. BranchProbability
  1485. SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src,
  1486. const MachineBasicBlock *Dst) const {
  1487. BranchProbabilityInfo *BPI = FuncInfo.BPI;
  1488. const BasicBlock *SrcBB = Src->getBasicBlock();
  1489. const BasicBlock *DstBB = Dst->getBasicBlock();
  1490. if (!BPI) {
  1491. // If BPI is not available, set the default probability as 1 / N, where N is
  1492. // the number of successors.
  1493. auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1);
  1494. return BranchProbability(1, SuccSize);
  1495. }
  1496. return BPI->getEdgeProbability(SrcBB, DstBB);
  1497. }
  1498. void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src,
  1499. MachineBasicBlock *Dst,
  1500. BranchProbability Prob) {
  1501. if (!FuncInfo.BPI)
  1502. Src->addSuccessorWithoutProb(Dst);
  1503. else {
  1504. if (Prob.isUnknown())
  1505. Prob = getEdgeProbability(Src, Dst);
  1506. Src->addSuccessor(Dst, Prob);
  1507. }
  1508. }
  1509. static bool InBlock(const Value *V, const BasicBlock *BB) {
  1510. if (const Instruction *I = dyn_cast<Instruction>(V))
  1511. return I->getParent() == BB;
  1512. return true;
  1513. }
  1514. /// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
  1515. /// This function emits a branch and is used at the leaves of an OR or an
  1516. /// AND operator tree.
  1517. void
  1518. SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond,
  1519. MachineBasicBlock *TBB,
  1520. MachineBasicBlock *FBB,
  1521. MachineBasicBlock *CurBB,
  1522. MachineBasicBlock *SwitchBB,
  1523. BranchProbability TProb,
  1524. BranchProbability FProb,
  1525. bool InvertCond) {
  1526. const BasicBlock *BB = CurBB->getBasicBlock();
  1527. // If the leaf of the tree is a comparison, merge the condition into
  1528. // the caseblock.
  1529. if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
  1530. // The operands of the cmp have to be in this block. We don't know
  1531. // how to export them from some other block. If this is the first block
  1532. // of the sequence, no exporting is needed.
  1533. if (CurBB == SwitchBB ||
  1534. (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
  1535. isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
  1536. ISD::CondCode Condition;
  1537. if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
  1538. ICmpInst::Predicate Pred =
  1539. InvertCond ? IC->getInversePredicate() : IC->getPredicate();
  1540. Condition = getICmpCondCode(Pred);
  1541. } else {
  1542. const FCmpInst *FC = cast<FCmpInst>(Cond);
  1543. FCmpInst::Predicate Pred =
  1544. InvertCond ? FC->getInversePredicate() : FC->getPredicate();
  1545. Condition = getFCmpCondCode(Pred);
  1546. if (TM.Options.NoNaNsFPMath)
  1547. Condition = getFCmpCodeWithoutNaN(Condition);
  1548. }
  1549. CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr,
  1550. TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
  1551. SwitchCases.push_back(CB);
  1552. return;
  1553. }
  1554. }
  1555. // Create a CaseBlock record representing this branch.
  1556. ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ;
  1557. CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()),
  1558. nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
  1559. SwitchCases.push_back(CB);
  1560. }
  1561. /// FindMergedConditions - If Cond is an expression like
  1562. void SelectionDAGBuilder::FindMergedConditions(const Value *Cond,
  1563. MachineBasicBlock *TBB,
  1564. MachineBasicBlock *FBB,
  1565. MachineBasicBlock *CurBB,
  1566. MachineBasicBlock *SwitchBB,
  1567. Instruction::BinaryOps Opc,
  1568. BranchProbability TProb,
  1569. BranchProbability FProb,
  1570. bool InvertCond) {
  1571. // Skip over not part of the tree and remember to invert op and operands at
  1572. // next level.
  1573. if (BinaryOperator::isNot(Cond) && Cond->hasOneUse()) {
  1574. const Value *CondOp = BinaryOperator::getNotArgument(Cond);
  1575. if (InBlock(CondOp, CurBB->getBasicBlock())) {
  1576. FindMergedConditions(CondOp, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb,
  1577. !InvertCond);
  1578. return;
  1579. }
  1580. }
  1581. const Instruction *BOp = dyn_cast<Instruction>(Cond);
  1582. // Compute the effective opcode for Cond, taking into account whether it needs
  1583. // to be inverted, e.g.
  1584. // and (not (or A, B)), C
  1585. // gets lowered as
  1586. // and (and (not A, not B), C)
  1587. unsigned BOpc = 0;
  1588. if (BOp) {
  1589. BOpc = BOp->getOpcode();
  1590. if (InvertCond) {
  1591. if (BOpc == Instruction::And)
  1592. BOpc = Instruction::Or;
  1593. else if (BOpc == Instruction::Or)
  1594. BOpc = Instruction::And;
  1595. }
  1596. }
  1597. // If this node is not part of the or/and tree, emit it as a branch.
  1598. if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
  1599. BOpc != unsigned(Opc) || !BOp->hasOneUse() ||
  1600. BOp->getParent() != CurBB->getBasicBlock() ||
  1601. !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
  1602. !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
  1603. EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB,
  1604. TProb, FProb, InvertCond);
  1605. return;
  1606. }
  1607. // Create TmpBB after CurBB.
  1608. MachineFunction::iterator BBI(CurBB);
  1609. MachineFunction &MF = DAG.getMachineFunction();
  1610. MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
  1611. CurBB->getParent()->insert(++BBI, TmpBB);
  1612. if (Opc == Instruction::Or) {
  1613. // Codegen X | Y as:
  1614. // BB1:
  1615. // jmp_if_X TBB
  1616. // jmp TmpBB
  1617. // TmpBB:
  1618. // jmp_if_Y TBB
  1619. // jmp FBB
  1620. //
  1621. // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
  1622. // The requirement is that
  1623. // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
  1624. // = TrueProb for original BB.
  1625. // Assuming the original probabilities are A and B, one choice is to set
  1626. // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to
  1627. // A/(1+B) and 2B/(1+B). This choice assumes that
  1628. // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
  1629. // Another choice is to assume TrueProb for BB1 equals to TrueProb for
  1630. // TmpBB, but the math is more complicated.
  1631. auto NewTrueProb = TProb / 2;
  1632. auto NewFalseProb = TProb / 2 + FProb;
  1633. // Emit the LHS condition.
  1634. FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, SwitchBB, Opc,
  1635. NewTrueProb, NewFalseProb, InvertCond);
  1636. // Normalize A/2 and B to get A/(1+B) and 2B/(1+B).
  1637. SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb};
  1638. BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
  1639. // Emit the RHS condition into TmpBB.
  1640. FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc,
  1641. Probs[0], Probs[1], InvertCond);
  1642. } else {
  1643. assert(Opc == Instruction::And && "Unknown merge op!");
  1644. // Codegen X & Y as:
  1645. // BB1:
  1646. // jmp_if_X TmpBB
  1647. // jmp FBB
  1648. // TmpBB:
  1649. // jmp_if_Y TBB
  1650. // jmp FBB
  1651. //
  1652. // This requires creation of TmpBB after CurBB.
  1653. // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
  1654. // The requirement is that
  1655. // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
  1656. // = FalseProb for original BB.
  1657. // Assuming the original probabilities are A and B, one choice is to set
  1658. // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to
  1659. // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 ==
  1660. // TrueProb for BB1 * FalseProb for TmpBB.
  1661. auto NewTrueProb = TProb + FProb / 2;
  1662. auto NewFalseProb = FProb / 2;
  1663. // Emit the LHS condition.
  1664. FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, SwitchBB, Opc,
  1665. NewTrueProb, NewFalseProb, InvertCond);
  1666. // Normalize A and B/2 to get 2A/(1+A) and B/(1+A).
  1667. SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2};
  1668. BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
  1669. // Emit the RHS condition into TmpBB.
  1670. FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc,
  1671. Probs[0], Probs[1], InvertCond);
  1672. }
  1673. }
  1674. /// If the set of cases should be emitted as a series of branches, return true.
  1675. /// If we should emit this as a bunch of and/or'd together conditions, return
  1676. /// false.
  1677. bool
  1678. SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) {
  1679. if (Cases.size() != 2) return true;
  1680. // If this is two comparisons of the same values or'd or and'd together, they
  1681. // will get folded into a single comparison, so don't emit two blocks.
  1682. if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
  1683. Cases[0].CmpRHS == Cases[1].CmpRHS) ||
  1684. (Cases[0].CmpRHS == Cases[1].CmpLHS &&
  1685. Cases[0].CmpLHS == Cases[1].CmpRHS)) {
  1686. return false;
  1687. }
  1688. // Handle: (X != null) | (Y != null) --> (X|Y) != 0
  1689. // Handle: (X == null) & (Y == null) --> (X|Y) == 0
  1690. if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
  1691. Cases[0].CC == Cases[1].CC &&
  1692. isa<Constant>(Cases[0].CmpRHS) &&
  1693. cast<Constant>(Cases[0].CmpRHS)->isNullValue()) {
  1694. if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB)
  1695. return false;
  1696. if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB)
  1697. return false;
  1698. }
  1699. return true;
  1700. }
  1701. void SelectionDAGBuilder::visitBr(const BranchInst &I) {
  1702. MachineBasicBlock *BrMBB = FuncInfo.MBB;
  1703. // Update machine-CFG edges.
  1704. MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
  1705. if (I.isUnconditional()) {
  1706. // Update machine-CFG edges.
  1707. BrMBB->addSuccessor(Succ0MBB);
  1708. // If this is not a fall-through branch or optimizations are switched off,
  1709. // emit the branch.
  1710. if (Succ0MBB != NextBlock(BrMBB) || TM.getOptLevel() == CodeGenOpt::None)
  1711. DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
  1712. MVT::Other, getControlRoot(),
  1713. DAG.getBasicBlock(Succ0MBB)));
  1714. return;
  1715. }
  1716. // If this condition is one of the special cases we handle, do special stuff
  1717. // now.
  1718. const Value *CondVal = I.getCondition();
  1719. MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
  1720. // If this is a series of conditions that are or'd or and'd together, emit
  1721. // this as a sequence of branches instead of setcc's with and/or operations.
  1722. // As long as jumps are not expensive, this should improve performance.
  1723. // For example, instead of something like:
  1724. // cmp A, B
  1725. // C = seteq
  1726. // cmp D, E
  1727. // F = setle
  1728. // or C, F
  1729. // jnz foo
  1730. // Emit:
  1731. // cmp A, B
  1732. // je foo
  1733. // cmp D, E
  1734. // jle foo
  1735. if (const BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
  1736. Instruction::BinaryOps Opcode = BOp->getOpcode();
  1737. if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp->hasOneUse() &&
  1738. !I.getMetadata(LLVMContext::MD_unpredictable) &&
  1739. (Opcode == Instruction::And || Opcode == Instruction::Or)) {
  1740. FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB,
  1741. Opcode,
  1742. getEdgeProbability(BrMBB, Succ0MBB),
  1743. getEdgeProbability(BrMBB, Succ1MBB),
  1744. /*InvertCond=*/false);
  1745. // If the compares in later blocks need to use values not currently
  1746. // exported from this block, export them now. This block should always
  1747. // be the first entry.
  1748. assert(SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!");
  1749. // Allow some cases to be rejected.
  1750. if (ShouldEmitAsBranches(SwitchCases)) {
  1751. for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
  1752. ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
  1753. ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
  1754. }
  1755. // Emit the branch for this block.
  1756. visitSwitchCase(SwitchCases[0], BrMBB);
  1757. SwitchCases.erase(SwitchCases.begin());
  1758. return;
  1759. }
  1760. // Okay, we decided not to do this, remove any inserted MBB's and clear
  1761. // SwitchCases.
  1762. for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
  1763. FuncInfo.MF->erase(SwitchCases[i].ThisBB);
  1764. SwitchCases.clear();
  1765. }
  1766. }
  1767. // Create a CaseBlock record representing this branch.
  1768. CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
  1769. nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc());
  1770. // Use visitSwitchCase to actually insert the fast branch sequence for this
  1771. // cond branch.
  1772. visitSwitchCase(CB, BrMBB);
  1773. }
  1774. /// visitSwitchCase - Emits the necessary code to represent a single node in
  1775. /// the binary search tree resulting from lowering a switch instruction.
  1776. void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB,
  1777. MachineBasicBlock *SwitchBB) {
  1778. SDValue Cond;
  1779. SDValue CondLHS = getValue(CB.CmpLHS);
  1780. SDLoc dl = CB.DL;
  1781. // Build the setcc now.
  1782. if (!CB.CmpMHS) {
  1783. // Fold "(X == true)" to X and "(X == false)" to !X to
  1784. // handle common cases produced by branch lowering.
  1785. if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
  1786. CB.CC == ISD::SETEQ)
  1787. Cond = CondLHS;
  1788. else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
  1789. CB.CC == ISD::SETEQ) {
  1790. SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType());
  1791. Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
  1792. } else
  1793. Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
  1794. } else {
  1795. assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
  1796. const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
  1797. const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
  1798. SDValue CmpOp = getValue(CB.CmpMHS);
  1799. EVT VT = CmpOp.getValueType();
  1800. if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
  1801. Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT),
  1802. ISD::SETLE);
  1803. } else {
  1804. SDValue SUB = DAG.getNode(ISD::SUB, dl,
  1805. VT, CmpOp, DAG.getConstant(Low, dl, VT));
  1806. Cond = DAG.getSetCC(dl, MVT::i1, SUB,
  1807. DAG.getConstant(High-Low, dl, VT), ISD::SETULE);
  1808. }
  1809. }
  1810. // Update successor info
  1811. addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
  1812. // TrueBB and FalseBB are always different unless the incoming IR is
  1813. // degenerate. This only happens when running llc on weird IR.
  1814. if (CB.TrueBB != CB.FalseBB)
  1815. addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb);
  1816. SwitchBB->normalizeSuccProbs();
  1817. // If the lhs block is the next block, invert the condition so that we can
  1818. // fall through to the lhs instead of the rhs block.
  1819. if (CB.TrueBB == NextBlock(SwitchBB)) {
  1820. std::swap(CB.TrueBB, CB.FalseBB);
  1821. SDValue True = DAG.getConstant(1, dl, Cond.getValueType());
  1822. Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
  1823. }
  1824. SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
  1825. MVT::Other, getControlRoot(), Cond,
  1826. DAG.getBasicBlock(CB.TrueBB));
  1827. // Insert the false branch. Do this even if it's a fall through branch,
  1828. // this makes it easier to do DAG optimizations which require inverting
  1829. // the branch condition.
  1830. BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
  1831. DAG.getBasicBlock(CB.FalseBB));
  1832. DAG.setRoot(BrCond);
  1833. }
  1834. /// visitJumpTable - Emit JumpTable node in the current MBB
  1835. void SelectionDAGBuilder::visitJumpTable(JumpTable &JT) {
  1836. // Emit the code for the jump table
  1837. assert(JT.Reg != -1U && "Should lower JT Header first!");
  1838. EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
  1839. SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(),
  1840. JT.Reg, PTy);
  1841. SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
  1842. SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(),
  1843. MVT::Other, Index.getValue(1),
  1844. Table, Index);
  1845. DAG.setRoot(BrJumpTable);
  1846. }
  1847. /// visitJumpTableHeader - This function emits necessary code to produce index
  1848. /// in the JumpTable from switch case.
  1849. void SelectionDAGBuilder::visitJumpTableHeader(JumpTable &JT,
  1850. JumpTableHeader &JTH,
  1851. MachineBasicBlock *SwitchBB) {
  1852. SDLoc dl = getCurSDLoc();
  1853. // Subtract the lowest switch case value from the value being switched on and
  1854. // conditional branch to default mbb if the result is greater than the
  1855. // difference between smallest and largest cases.
  1856. SDValue SwitchOp = getValue(JTH.SValue);
  1857. EVT VT = SwitchOp.getValueType();
  1858. SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp,
  1859. DAG.getConstant(JTH.First, dl, VT));
  1860. // The SDNode we just created, which holds the value being switched on minus
  1861. // the smallest case value, needs to be copied to a virtual register so it
  1862. // can be used as an index into the jump table in a subsequent basic block.
  1863. // This value may be smaller or larger than the target's pointer type, and
  1864. // therefore require extension or truncating.
  1865. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  1866. SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout()));
  1867. unsigned JumpTableReg =
  1868. FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout()));
  1869. SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl,
  1870. JumpTableReg, SwitchOp);
  1871. JT.Reg = JumpTableReg;
  1872. // Emit the range check for the jump table, and branch to the default block
  1873. // for the switch statement if the value being switched on exceeds the largest
  1874. // case in the switch.
  1875. SDValue CMP = DAG.getSetCC(
  1876. dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
  1877. Sub.getValueType()),
  1878. Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT);
  1879. SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
  1880. MVT::Other, CopyTo, CMP,
  1881. DAG.getBasicBlock(JT.Default));
  1882. // Avoid emitting unnecessary branches to the next block.
  1883. if (JT.MBB != NextBlock(SwitchBB))
  1884. BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
  1885. DAG.getBasicBlock(JT.MBB));
  1886. DAG.setRoot(BrCond);
  1887. }
  1888. /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global
  1889. /// variable if there exists one.
  1890. static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL,
  1891. SDValue &Chain) {
  1892. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  1893. EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
  1894. MachineFunction &MF = DAG.getMachineFunction();
  1895. Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent());
  1896. MachineSDNode *Node =
  1897. DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain);
  1898. if (Global) {
  1899. MachinePointerInfo MPInfo(Global);
  1900. MachineInstr::mmo_iterator MemRefs = MF.allocateMemRefsArray(1);
  1901. auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant |
  1902. MachineMemOperand::MODereferenceable;
  1903. *MemRefs = MF.getMachineMemOperand(MPInfo, Flags, PtrTy.getSizeInBits() / 8,
  1904. DAG.getEVTAlignment(PtrTy));
  1905. Node->setMemRefs(MemRefs, MemRefs + 1);
  1906. }
  1907. return SDValue(Node, 0);
  1908. }
  1909. /// Codegen a new tail for a stack protector check ParentMBB which has had its
  1910. /// tail spliced into a stack protector check success bb.
  1911. ///
  1912. /// For a high level explanation of how this fits into the stack protector
  1913. /// generation see the comment on the declaration of class
  1914. /// StackProtectorDescriptor.
  1915. void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD,
  1916. MachineBasicBlock *ParentBB) {
  1917. // First create the loads to the guard/stack slot for the comparison.
  1918. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  1919. EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
  1920. MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo();
  1921. int FI = MFI.getStackProtectorIndex();
  1922. SDValue Guard;
  1923. SDLoc dl = getCurSDLoc();
  1924. SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy);
  1925. const Module &M = *ParentBB->getParent()->getFunction().getParent();
  1926. unsigned Align = DL->getPrefTypeAlignment(Type::getInt8PtrTy(M.getContext()));
  1927. // Generate code to load the content of the guard slot.
  1928. SDValue GuardVal = DAG.getLoad(
  1929. PtrTy, dl, DAG.getEntryNode(), StackSlotPtr,
  1930. MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align,
  1931. MachineMemOperand::MOVolatile);
  1932. if (TLI.useStackGuardXorFP())
  1933. GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl);
  1934. // Retrieve guard check function, nullptr if instrumentation is inlined.
  1935. if (const Value *GuardCheck = TLI.getSSPStackGuardCheck(M)) {
  1936. // The target provides a guard check function to validate the guard value.
  1937. // Generate a call to that function with the content of the guard slot as
  1938. // argument.
  1939. auto *Fn = cast<Function>(GuardCheck);
  1940. FunctionType *FnTy = Fn->getFunctionType();
  1941. assert(FnTy->getNumParams() == 1 && "Invalid function signature");
  1942. TargetLowering::ArgListTy Args;
  1943. TargetLowering::ArgListEntry Entry;
  1944. Entry.Node = GuardVal;
  1945. Entry.Ty = FnTy->getParamType(0);
  1946. if (Fn->hasAttribute(1, Attribute::AttrKind::InReg))
  1947. Entry.IsInReg = true;
  1948. Args.push_back(Entry);
  1949. TargetLowering::CallLoweringInfo CLI(DAG);
  1950. CLI.setDebugLoc(getCurSDLoc())
  1951. .setChain(DAG.getEntryNode())
  1952. .setCallee(Fn->getCallingConv(), FnTy->getReturnType(),
  1953. getValue(GuardCheck), std::move(Args));
  1954. std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
  1955. DAG.setRoot(Result.second);
  1956. return;
  1957. }
  1958. // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD.
  1959. // Otherwise, emit a volatile load to retrieve the stack guard value.
  1960. SDValue Chain = DAG.getEntryNode();
  1961. if (TLI.useLoadStackGuardNode()) {
  1962. Guard = getLoadStackGuard(DAG, dl, Chain);
  1963. } else {
  1964. const Value *IRGuard = TLI.getSDagStackGuard(M);
  1965. SDValue GuardPtr = getValue(IRGuard);
  1966. Guard =
  1967. DAG.getLoad(PtrTy, dl, Chain, GuardPtr, MachinePointerInfo(IRGuard, 0),
  1968. Align, MachineMemOperand::MOVolatile);
  1969. }
  1970. // Perform the comparison via a subtract/getsetcc.
  1971. EVT VT = Guard.getValueType();
  1972. SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, Guard, GuardVal);
  1973. SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(),
  1974. *DAG.getContext(),
  1975. Sub.getValueType()),
  1976. Sub, DAG.getConstant(0, dl, VT), ISD::SETNE);
  1977. // If the sub is not 0, then we know the guard/stackslot do not equal, so
  1978. // branch to failure MBB.
  1979. SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
  1980. MVT::Other, GuardVal.getOperand(0),
  1981. Cmp, DAG.getBasicBlock(SPD.getFailureMBB()));
  1982. // Otherwise branch to success MBB.
  1983. SDValue Br = DAG.getNode(ISD::BR, dl,
  1984. MVT::Other, BrCond,
  1985. DAG.getBasicBlock(SPD.getSuccessMBB()));
  1986. DAG.setRoot(Br);
  1987. }
  1988. /// Codegen the failure basic block for a stack protector check.
  1989. ///
  1990. /// A failure stack protector machine basic block consists simply of a call to
  1991. /// __stack_chk_fail().
  1992. ///
  1993. /// For a high level explanation of how this fits into the stack protector
  1994. /// generation see the comment on the declaration of class
  1995. /// StackProtectorDescriptor.
  1996. void
  1997. SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) {
  1998. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  1999. SDValue Chain =
  2000. TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid,
  2001. None, false, getCurSDLoc(), false, false).second;
  2002. DAG.setRoot(Chain);
  2003. }
  2004. /// visitBitTestHeader - This function emits necessary code to produce value
  2005. /// suitable for "bit tests"
  2006. void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B,
  2007. MachineBasicBlock *SwitchBB) {
  2008. SDLoc dl = getCurSDLoc();
  2009. // Subtract the minimum value
  2010. SDValue SwitchOp = getValue(B.SValue);
  2011. EVT VT = SwitchOp.getValueType();
  2012. SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp,
  2013. DAG.getConstant(B.First, dl, VT));
  2014. // Check range
  2015. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2016. SDValue RangeCmp = DAG.getSetCC(
  2017. dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
  2018. Sub.getValueType()),
  2019. Sub, DAG.getConstant(B.Range, dl, VT), ISD::SETUGT);
  2020. // Determine the type of the test operands.
  2021. bool UsePtrType = false;
  2022. if (!TLI.isTypeLegal(VT))
  2023. UsePtrType = true;
  2024. else {
  2025. for (unsigned i = 0, e = B.Cases.size(); i != e; ++i)
  2026. if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) {
  2027. // Switch table case range are encoded into series of masks.
  2028. // Just use pointer type, it's guaranteed to fit.
  2029. UsePtrType = true;
  2030. break;
  2031. }
  2032. }
  2033. if (UsePtrType) {
  2034. VT = TLI.getPointerTy(DAG.getDataLayout());
  2035. Sub = DAG.getZExtOrTrunc(Sub, dl, VT);
  2036. }
  2037. B.RegVT = VT.getSimpleVT();
  2038. B.Reg = FuncInfo.CreateReg(B.RegVT);
  2039. SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub);
  2040. MachineBasicBlock* MBB = B.Cases[0].ThisBB;
  2041. addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb);
  2042. addSuccessorWithProb(SwitchBB, MBB, B.Prob);
  2043. SwitchBB->normalizeSuccProbs();
  2044. SDValue BrRange = DAG.getNode(ISD::BRCOND, dl,
  2045. MVT::Other, CopyTo, RangeCmp,
  2046. DAG.getBasicBlock(B.Default));
  2047. // Avoid emitting unnecessary branches to the next block.
  2048. if (MBB != NextBlock(SwitchBB))
  2049. BrRange = DAG.getNode(ISD::BR, dl, MVT::Other, BrRange,
  2050. DAG.getBasicBlock(MBB));
  2051. DAG.setRoot(BrRange);
  2052. }
  2053. /// visitBitTestCase - this function produces one "bit test"
  2054. void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB,
  2055. MachineBasicBlock* NextMBB,
  2056. BranchProbability BranchProbToNext,
  2057. unsigned Reg,
  2058. BitTestCase &B,
  2059. MachineBasicBlock *SwitchBB) {
  2060. SDLoc dl = getCurSDLoc();
  2061. MVT VT = BB.RegVT;
  2062. SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT);
  2063. SDValue Cmp;
  2064. unsigned PopCount = countPopulation(B.Mask);
  2065. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2066. if (PopCount == 1) {
  2067. // Testing for a single bit; just compare the shift count with what it
  2068. // would need to be to shift a 1 bit in that position.
  2069. Cmp = DAG.getSetCC(
  2070. dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
  2071. ShiftOp, DAG.getConstant(countTrailingZeros(B.Mask), dl, VT),
  2072. ISD::SETEQ);
  2073. } else if (PopCount == BB.Range) {
  2074. // There is only one zero bit in the range, test for it directly.
  2075. Cmp = DAG.getSetCC(
  2076. dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
  2077. ShiftOp, DAG.getConstant(countTrailingOnes(B.Mask), dl, VT),
  2078. ISD::SETNE);
  2079. } else {
  2080. // Make desired shift
  2081. SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT,
  2082. DAG.getConstant(1, dl, VT), ShiftOp);
  2083. // Emit bit tests and jumps
  2084. SDValue AndOp = DAG.getNode(ISD::AND, dl,
  2085. VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT));
  2086. Cmp = DAG.getSetCC(
  2087. dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
  2088. AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE);
  2089. }
  2090. // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb.
  2091. addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb);
  2092. // The branch probability from SwitchBB to NextMBB is BranchProbToNext.
  2093. addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext);
  2094. // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is
  2095. // one as they are relative probabilities (and thus work more like weights),
  2096. // and hence we need to normalize them to let the sum of them become one.
  2097. SwitchBB->normalizeSuccProbs();
  2098. SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl,
  2099. MVT::Other, getControlRoot(),
  2100. Cmp, DAG.getBasicBlock(B.TargetBB));
  2101. // Avoid emitting unnecessary branches to the next block.
  2102. if (NextMBB != NextBlock(SwitchBB))
  2103. BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd,
  2104. DAG.getBasicBlock(NextMBB));
  2105. DAG.setRoot(BrAnd);
  2106. }
  2107. void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) {
  2108. MachineBasicBlock *InvokeMBB = FuncInfo.MBB;
  2109. // Retrieve successors. Look through artificial IR level blocks like
  2110. // catchswitch for successors.
  2111. MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
  2112. const BasicBlock *EHPadBB = I.getSuccessor(1);
  2113. // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
  2114. // have to do anything here to lower funclet bundles.
  2115. assert(!I.hasOperandBundlesOtherThan(
  2116. {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) &&
  2117. "Cannot lower invokes with arbitrary operand bundles yet!");
  2118. const Value *Callee(I.getCalledValue());
  2119. const Function *Fn = dyn_cast<Function>(Callee);
  2120. if (isa<InlineAsm>(Callee))
  2121. visitInlineAsm(&I);
  2122. else if (Fn && Fn->isIntrinsic()) {
  2123. switch (Fn->getIntrinsicID()) {
  2124. default:
  2125. llvm_unreachable("Cannot invoke this intrinsic");
  2126. case Intrinsic::donothing:
  2127. // Ignore invokes to @llvm.donothing: jump directly to the next BB.
  2128. break;
  2129. case Intrinsic::experimental_patchpoint_void:
  2130. case Intrinsic::experimental_patchpoint_i64:
  2131. visitPatchpoint(&I, EHPadBB);
  2132. break;
  2133. case Intrinsic::experimental_gc_statepoint:
  2134. LowerStatepoint(ImmutableStatepoint(&I), EHPadBB);
  2135. break;
  2136. }
  2137. } else if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) {
  2138. // Currently we do not lower any intrinsic calls with deopt operand bundles.
  2139. // Eventually we will support lowering the @llvm.experimental.deoptimize
  2140. // intrinsic, and right now there are no plans to support other intrinsics
  2141. // with deopt state.
  2142. LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB);
  2143. } else {
  2144. LowerCallTo(&I, getValue(Callee), false, EHPadBB);
  2145. }
  2146. // If the value of the invoke is used outside of its defining block, make it
  2147. // available as a virtual register.
  2148. // We already took care of the exported value for the statepoint instruction
  2149. // during call to the LowerStatepoint.
  2150. if (!isStatepoint(I)) {
  2151. CopyToExportRegsIfNeeded(&I);
  2152. }
  2153. SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
  2154. BranchProbabilityInfo *BPI = FuncInfo.BPI;
  2155. BranchProbability EHPadBBProb =
  2156. BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB)
  2157. : BranchProbability::getZero();
  2158. findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests);
  2159. // Update successor info.
  2160. addSuccessorWithProb(InvokeMBB, Return);
  2161. for (auto &UnwindDest : UnwindDests) {
  2162. UnwindDest.first->setIsEHPad();
  2163. addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second);
  2164. }
  2165. InvokeMBB->normalizeSuccProbs();
  2166. // Drop into normal successor.
  2167. DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
  2168. MVT::Other, getControlRoot(),
  2169. DAG.getBasicBlock(Return)));
  2170. }
  2171. void SelectionDAGBuilder::visitResume(const ResumeInst &RI) {
  2172. llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!");
  2173. }
  2174. void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) {
  2175. assert(FuncInfo.MBB->isEHPad() &&
  2176. "Call to landingpad not in landing pad!");
  2177. MachineBasicBlock *MBB = FuncInfo.MBB;
  2178. addLandingPadInfo(LP, *MBB);
  2179. // If there aren't registers to copy the values into (e.g., during SjLj
  2180. // exceptions), then don't bother to create these DAG nodes.
  2181. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2182. const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn();
  2183. if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 &&
  2184. TLI.getExceptionSelectorRegister(PersonalityFn) == 0)
  2185. return;
  2186. // If landingpad's return type is token type, we don't create DAG nodes
  2187. // for its exception pointer and selector value. The extraction of exception
  2188. // pointer or selector value from token type landingpads is not currently
  2189. // supported.
  2190. if (LP.getType()->isTokenTy())
  2191. return;
  2192. SmallVector<EVT, 2> ValueVTs;
  2193. SDLoc dl = getCurSDLoc();
  2194. ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs);
  2195. assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported");
  2196. // Get the two live-in registers as SDValues. The physregs have already been
  2197. // copied into virtual registers.
  2198. SDValue Ops[2];
  2199. if (FuncInfo.ExceptionPointerVirtReg) {
  2200. Ops[0] = DAG.getZExtOrTrunc(
  2201. DAG.getCopyFromReg(DAG.getEntryNode(), dl,
  2202. FuncInfo.ExceptionPointerVirtReg,
  2203. TLI.getPointerTy(DAG.getDataLayout())),
  2204. dl, ValueVTs[0]);
  2205. } else {
  2206. Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout()));
  2207. }
  2208. Ops[1] = DAG.getZExtOrTrunc(
  2209. DAG.getCopyFromReg(DAG.getEntryNode(), dl,
  2210. FuncInfo.ExceptionSelectorVirtReg,
  2211. TLI.getPointerTy(DAG.getDataLayout())),
  2212. dl, ValueVTs[1]);
  2213. // Merge into one.
  2214. SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl,
  2215. DAG.getVTList(ValueVTs), Ops);
  2216. setValue(&LP, Res);
  2217. }
  2218. void SelectionDAGBuilder::sortAndRangeify(CaseClusterVector &Clusters) {
  2219. #ifndef NDEBUG
  2220. for (const CaseCluster &CC : Clusters)
  2221. assert(CC.Low == CC.High && "Input clusters must be single-case");
  2222. #endif
  2223. llvm::sort(Clusters.begin(), Clusters.end(),
  2224. [](const CaseCluster &a, const CaseCluster &b) {
  2225. return a.Low->getValue().slt(b.Low->getValue());
  2226. });
  2227. // Merge adjacent clusters with the same destination.
  2228. const unsigned N = Clusters.size();
  2229. unsigned DstIndex = 0;
  2230. for (unsigned SrcIndex = 0; SrcIndex < N; ++SrcIndex) {
  2231. CaseCluster &CC = Clusters[SrcIndex];
  2232. const ConstantInt *CaseVal = CC.Low;
  2233. MachineBasicBlock *Succ = CC.MBB;
  2234. if (DstIndex != 0 && Clusters[DstIndex - 1].MBB == Succ &&
  2235. (CaseVal->getValue() - Clusters[DstIndex - 1].High->getValue()) == 1) {
  2236. // If this case has the same successor and is a neighbour, merge it into
  2237. // the previous cluster.
  2238. Clusters[DstIndex - 1].High = CaseVal;
  2239. Clusters[DstIndex - 1].Prob += CC.Prob;
  2240. } else {
  2241. std::memmove(&Clusters[DstIndex++], &Clusters[SrcIndex],
  2242. sizeof(Clusters[SrcIndex]));
  2243. }
  2244. }
  2245. Clusters.resize(DstIndex);
  2246. }
  2247. void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First,
  2248. MachineBasicBlock *Last) {
  2249. // Update JTCases.
  2250. for (unsigned i = 0, e = JTCases.size(); i != e; ++i)
  2251. if (JTCases[i].first.HeaderBB == First)
  2252. JTCases[i].first.HeaderBB = Last;
  2253. // Update BitTestCases.
  2254. for (unsigned i = 0, e = BitTestCases.size(); i != e; ++i)
  2255. if (BitTestCases[i].Parent == First)
  2256. BitTestCases[i].Parent = Last;
  2257. }
  2258. void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) {
  2259. MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB;
  2260. // Update machine-CFG edges with unique successors.
  2261. SmallSet<BasicBlock*, 32> Done;
  2262. for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) {
  2263. BasicBlock *BB = I.getSuccessor(i);
  2264. bool Inserted = Done.insert(BB).second;
  2265. if (!Inserted)
  2266. continue;
  2267. MachineBasicBlock *Succ = FuncInfo.MBBMap[BB];
  2268. addSuccessorWithProb(IndirectBrMBB, Succ);
  2269. }
  2270. IndirectBrMBB->normalizeSuccProbs();
  2271. DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(),
  2272. MVT::Other, getControlRoot(),
  2273. getValue(I.getAddress())));
  2274. }
  2275. void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) {
  2276. if (DAG.getTarget().Options.TrapUnreachable)
  2277. DAG.setRoot(
  2278. DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot()));
  2279. }
  2280. void SelectionDAGBuilder::visitFSub(const User &I) {
  2281. // -0.0 - X --> fneg
  2282. Type *Ty = I.getType();
  2283. if (isa<Constant>(I.getOperand(0)) &&
  2284. I.getOperand(0) == ConstantFP::getZeroValueForNegation(Ty)) {
  2285. SDValue Op2 = getValue(I.getOperand(1));
  2286. setValue(&I, DAG.getNode(ISD::FNEG, getCurSDLoc(),
  2287. Op2.getValueType(), Op2));
  2288. return;
  2289. }
  2290. visitBinary(I, ISD::FSUB);
  2291. }
  2292. /// Checks if the given instruction performs a vector reduction, in which case
  2293. /// we have the freedom to alter the elements in the result as long as the
  2294. /// reduction of them stays unchanged.
  2295. static bool isVectorReductionOp(const User *I) {
  2296. const Instruction *Inst = dyn_cast<Instruction>(I);
  2297. if (!Inst || !Inst->getType()->isVectorTy())
  2298. return false;
  2299. auto OpCode = Inst->getOpcode();
  2300. switch (OpCode) {
  2301. case Instruction::Add:
  2302. case Instruction::Mul:
  2303. case Instruction::And:
  2304. case Instruction::Or:
  2305. case Instruction::Xor:
  2306. break;
  2307. case Instruction::FAdd:
  2308. case Instruction::FMul:
  2309. if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(Inst))
  2310. if (FPOp->getFastMathFlags().isFast())
  2311. break;
  2312. LLVM_FALLTHROUGH;
  2313. default:
  2314. return false;
  2315. }
  2316. unsigned ElemNum = Inst->getType()->getVectorNumElements();
  2317. unsigned ElemNumToReduce = ElemNum;
  2318. // Do DFS search on the def-use chain from the given instruction. We only
  2319. // allow four kinds of operations during the search until we reach the
  2320. // instruction that extracts the first element from the vector:
  2321. //
  2322. // 1. The reduction operation of the same opcode as the given instruction.
  2323. //
  2324. // 2. PHI node.
  2325. //
  2326. // 3. ShuffleVector instruction together with a reduction operation that
  2327. // does a partial reduction.
  2328. //
  2329. // 4. ExtractElement that extracts the first element from the vector, and we
  2330. // stop searching the def-use chain here.
  2331. //
  2332. // 3 & 4 above perform a reduction on all elements of the vector. We push defs
  2333. // from 1-3 to the stack to continue the DFS. The given instruction is not
  2334. // a reduction operation if we meet any other instructions other than those
  2335. // listed above.
  2336. SmallVector<const User *, 16> UsersToVisit{Inst};
  2337. SmallPtrSet<const User *, 16> Visited;
  2338. bool ReduxExtracted = false;
  2339. while (!UsersToVisit.empty()) {
  2340. auto User = UsersToVisit.back();
  2341. UsersToVisit.pop_back();
  2342. if (!Visited.insert(User).second)
  2343. continue;
  2344. for (const auto &U : User->users()) {
  2345. auto Inst = dyn_cast<Instruction>(U);
  2346. if (!Inst)
  2347. return false;
  2348. if (Inst->getOpcode() == OpCode || isa<PHINode>(U)) {
  2349. if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(Inst))
  2350. if (!isa<PHINode>(FPOp) && !FPOp->getFastMathFlags().isFast())
  2351. return false;
  2352. UsersToVisit.push_back(U);
  2353. } else if (const ShuffleVectorInst *ShufInst =
  2354. dyn_cast<ShuffleVectorInst>(U)) {
  2355. // Detect the following pattern: A ShuffleVector instruction together
  2356. // with a reduction that do partial reduction on the first and second
  2357. // ElemNumToReduce / 2 elements, and store the result in
  2358. // ElemNumToReduce / 2 elements in another vector.
  2359. unsigned ResultElements = ShufInst->getType()->getVectorNumElements();
  2360. if (ResultElements < ElemNum)
  2361. return false;
  2362. if (ElemNumToReduce == 1)
  2363. return false;
  2364. if (!isa<UndefValue>(U->getOperand(1)))
  2365. return false;
  2366. for (unsigned i = 0; i < ElemNumToReduce / 2; ++i)
  2367. if (ShufInst->getMaskValue(i) != int(i + ElemNumToReduce / 2))
  2368. return false;
  2369. for (unsigned i = ElemNumToReduce / 2; i < ElemNum; ++i)
  2370. if (ShufInst->getMaskValue(i) != -1)
  2371. return false;
  2372. // There is only one user of this ShuffleVector instruction, which
  2373. // must be a reduction operation.
  2374. if (!U->hasOneUse())
  2375. return false;
  2376. auto U2 = dyn_cast<Instruction>(*U->user_begin());
  2377. if (!U2 || U2->getOpcode() != OpCode)
  2378. return false;
  2379. // Check operands of the reduction operation.
  2380. if ((U2->getOperand(0) == U->getOperand(0) && U2->getOperand(1) == U) ||
  2381. (U2->getOperand(1) == U->getOperand(0) && U2->getOperand(0) == U)) {
  2382. UsersToVisit.push_back(U2);
  2383. ElemNumToReduce /= 2;
  2384. } else
  2385. return false;
  2386. } else if (isa<ExtractElementInst>(U)) {
  2387. // At this moment we should have reduced all elements in the vector.
  2388. if (ElemNumToReduce != 1)
  2389. return false;
  2390. const ConstantInt *Val = dyn_cast<ConstantInt>(U->getOperand(1));
  2391. if (!Val || Val->getZExtValue() != 0)
  2392. return false;
  2393. ReduxExtracted = true;
  2394. } else
  2395. return false;
  2396. }
  2397. }
  2398. return ReduxExtracted;
  2399. }
  2400. void SelectionDAGBuilder::visitBinary(const User &I, unsigned OpCode) {
  2401. SDValue Op1 = getValue(I.getOperand(0));
  2402. SDValue Op2 = getValue(I.getOperand(1));
  2403. bool nuw = false;
  2404. bool nsw = false;
  2405. bool exact = false;
  2406. bool vec_redux = false;
  2407. FastMathFlags FMF;
  2408. if (const OverflowingBinaryOperator *OFBinOp =
  2409. dyn_cast<const OverflowingBinaryOperator>(&I)) {
  2410. nuw = OFBinOp->hasNoUnsignedWrap();
  2411. nsw = OFBinOp->hasNoSignedWrap();
  2412. }
  2413. if (const PossiblyExactOperator *ExactOp =
  2414. dyn_cast<const PossiblyExactOperator>(&I))
  2415. exact = ExactOp->isExact();
  2416. if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(&I))
  2417. FMF = FPOp->getFastMathFlags();
  2418. if (isVectorReductionOp(&I)) {
  2419. vec_redux = true;
  2420. DEBUG(dbgs() << "Detected a reduction operation:" << I << "\n");
  2421. }
  2422. SDNodeFlags Flags;
  2423. Flags.setExact(exact);
  2424. Flags.setNoSignedWrap(nsw);
  2425. Flags.setNoUnsignedWrap(nuw);
  2426. Flags.setVectorReduction(vec_redux);
  2427. Flags.setAllowReciprocal(FMF.allowReciprocal());
  2428. Flags.setAllowContract(FMF.allowContract());
  2429. Flags.setNoInfs(FMF.noInfs());
  2430. Flags.setNoNaNs(FMF.noNaNs());
  2431. Flags.setNoSignedZeros(FMF.noSignedZeros());
  2432. Flags.setApproximateFuncs(FMF.approxFunc());
  2433. Flags.setAllowReassociation(FMF.allowReassoc());
  2434. SDValue BinNodeValue = DAG.getNode(OpCode, getCurSDLoc(), Op1.getValueType(),
  2435. Op1, Op2, Flags);
  2436. setValue(&I, BinNodeValue);
  2437. }
  2438. void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) {
  2439. SDValue Op1 = getValue(I.getOperand(0));
  2440. SDValue Op2 = getValue(I.getOperand(1));
  2441. EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy(
  2442. Op2.getValueType(), DAG.getDataLayout());
  2443. // Coerce the shift amount to the right type if we can.
  2444. if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) {
  2445. unsigned ShiftSize = ShiftTy.getSizeInBits();
  2446. unsigned Op2Size = Op2.getValueSizeInBits();
  2447. SDLoc DL = getCurSDLoc();
  2448. // If the operand is smaller than the shift count type, promote it.
  2449. if (ShiftSize > Op2Size)
  2450. Op2 = DAG.getNode(ISD::ZERO_EXTEND, DL, ShiftTy, Op2);
  2451. // If the operand is larger than the shift count type but the shift
  2452. // count type has enough bits to represent any shift value, truncate
  2453. // it now. This is a common case and it exposes the truncate to
  2454. // optimization early.
  2455. else if (ShiftSize >= Log2_32_Ceil(Op2.getValueSizeInBits()))
  2456. Op2 = DAG.getNode(ISD::TRUNCATE, DL, ShiftTy, Op2);
  2457. // Otherwise we'll need to temporarily settle for some other convenient
  2458. // type. Type legalization will make adjustments once the shiftee is split.
  2459. else
  2460. Op2 = DAG.getZExtOrTrunc(Op2, DL, MVT::i32);
  2461. }
  2462. bool nuw = false;
  2463. bool nsw = false;
  2464. bool exact = false;
  2465. if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) {
  2466. if (const OverflowingBinaryOperator *OFBinOp =
  2467. dyn_cast<const OverflowingBinaryOperator>(&I)) {
  2468. nuw = OFBinOp->hasNoUnsignedWrap();
  2469. nsw = OFBinOp->hasNoSignedWrap();
  2470. }
  2471. if (const PossiblyExactOperator *ExactOp =
  2472. dyn_cast<const PossiblyExactOperator>(&I))
  2473. exact = ExactOp->isExact();
  2474. }
  2475. SDNodeFlags Flags;
  2476. Flags.setExact(exact);
  2477. Flags.setNoSignedWrap(nsw);
  2478. Flags.setNoUnsignedWrap(nuw);
  2479. SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2,
  2480. Flags);
  2481. setValue(&I, Res);
  2482. }
  2483. void SelectionDAGBuilder::visitSDiv(const User &I) {
  2484. SDValue Op1 = getValue(I.getOperand(0));
  2485. SDValue Op2 = getValue(I.getOperand(1));
  2486. SDNodeFlags Flags;
  2487. Flags.setExact(isa<PossiblyExactOperator>(&I) &&
  2488. cast<PossiblyExactOperator>(&I)->isExact());
  2489. setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1,
  2490. Op2, Flags));
  2491. }
  2492. void SelectionDAGBuilder::visitICmp(const User &I) {
  2493. ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
  2494. if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I))
  2495. predicate = IC->getPredicate();
  2496. else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
  2497. predicate = ICmpInst::Predicate(IC->getPredicate());
  2498. SDValue Op1 = getValue(I.getOperand(0));
  2499. SDValue Op2 = getValue(I.getOperand(1));
  2500. ISD::CondCode Opcode = getICmpCondCode(predicate);
  2501. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  2502. I.getType());
  2503. setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode));
  2504. }
  2505. void SelectionDAGBuilder::visitFCmp(const User &I) {
  2506. FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
  2507. if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I))
  2508. predicate = FC->getPredicate();
  2509. else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
  2510. predicate = FCmpInst::Predicate(FC->getPredicate());
  2511. SDValue Op1 = getValue(I.getOperand(0));
  2512. SDValue Op2 = getValue(I.getOperand(1));
  2513. ISD::CondCode Condition = getFCmpCondCode(predicate);
  2514. // FIXME: Fcmp instructions have fast-math-flags in IR, so we should use them.
  2515. // FIXME: We should propagate the fast-math-flags to the DAG node itself for
  2516. // further optimization, but currently FMF is only applicable to binary nodes.
  2517. if (TM.Options.NoNaNsFPMath)
  2518. Condition = getFCmpCodeWithoutNaN(Condition);
  2519. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  2520. I.getType());
  2521. setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition));
  2522. }
  2523. // Check if the condition of the select has one use or two users that are both
  2524. // selects with the same condition.
  2525. static bool hasOnlySelectUsers(const Value *Cond) {
  2526. return llvm::all_of(Cond->users(), [](const Value *V) {
  2527. return isa<SelectInst>(V);
  2528. });
  2529. }
  2530. void SelectionDAGBuilder::visitSelect(const User &I) {
  2531. SmallVector<EVT, 4> ValueVTs;
  2532. ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
  2533. ValueVTs);
  2534. unsigned NumValues = ValueVTs.size();
  2535. if (NumValues == 0) return;
  2536. SmallVector<SDValue, 4> Values(NumValues);
  2537. SDValue Cond = getValue(I.getOperand(0));
  2538. SDValue LHSVal = getValue(I.getOperand(1));
  2539. SDValue RHSVal = getValue(I.getOperand(2));
  2540. auto BaseOps = {Cond};
  2541. ISD::NodeType OpCode = Cond.getValueType().isVector() ?
  2542. ISD::VSELECT : ISD::SELECT;
  2543. // Min/max matching is only viable if all output VTs are the same.
  2544. if (std::equal(ValueVTs.begin(), ValueVTs.end(), ValueVTs.begin())) {
  2545. EVT VT = ValueVTs[0];
  2546. LLVMContext &Ctx = *DAG.getContext();
  2547. auto &TLI = DAG.getTargetLoweringInfo();
  2548. // We care about the legality of the operation after it has been type
  2549. // legalized.
  2550. while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal &&
  2551. VT != TLI.getTypeToTransformTo(Ctx, VT))
  2552. VT = TLI.getTypeToTransformTo(Ctx, VT);
  2553. // If the vselect is legal, assume we want to leave this as a vector setcc +
  2554. // vselect. Otherwise, if this is going to be scalarized, we want to see if
  2555. // min/max is legal on the scalar type.
  2556. bool UseScalarMinMax = VT.isVector() &&
  2557. !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT);
  2558. Value *LHS, *RHS;
  2559. auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS);
  2560. ISD::NodeType Opc = ISD::DELETED_NODE;
  2561. switch (SPR.Flavor) {
  2562. case SPF_UMAX: Opc = ISD::UMAX; break;
  2563. case SPF_UMIN: Opc = ISD::UMIN; break;
  2564. case SPF_SMAX: Opc = ISD::SMAX; break;
  2565. case SPF_SMIN: Opc = ISD::SMIN; break;
  2566. case SPF_FMINNUM:
  2567. switch (SPR.NaNBehavior) {
  2568. case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
  2569. case SPNB_RETURNS_NAN: Opc = ISD::FMINNAN; break;
  2570. case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break;
  2571. case SPNB_RETURNS_ANY: {
  2572. if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT))
  2573. Opc = ISD::FMINNUM;
  2574. else if (TLI.isOperationLegalOrCustom(ISD::FMINNAN, VT))
  2575. Opc = ISD::FMINNAN;
  2576. else if (UseScalarMinMax)
  2577. Opc = TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType()) ?
  2578. ISD::FMINNUM : ISD::FMINNAN;
  2579. break;
  2580. }
  2581. }
  2582. break;
  2583. case SPF_FMAXNUM:
  2584. switch (SPR.NaNBehavior) {
  2585. case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
  2586. case SPNB_RETURNS_NAN: Opc = ISD::FMAXNAN; break;
  2587. case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break;
  2588. case SPNB_RETURNS_ANY:
  2589. if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT))
  2590. Opc = ISD::FMAXNUM;
  2591. else if (TLI.isOperationLegalOrCustom(ISD::FMAXNAN, VT))
  2592. Opc = ISD::FMAXNAN;
  2593. else if (UseScalarMinMax)
  2594. Opc = TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType()) ?
  2595. ISD::FMAXNUM : ISD::FMAXNAN;
  2596. break;
  2597. }
  2598. break;
  2599. default: break;
  2600. }
  2601. if (Opc != ISD::DELETED_NODE &&
  2602. (TLI.isOperationLegalOrCustom(Opc, VT) ||
  2603. (UseScalarMinMax &&
  2604. TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) &&
  2605. // If the underlying comparison instruction is used by any other
  2606. // instruction, the consumed instructions won't be destroyed, so it is
  2607. // not profitable to convert to a min/max.
  2608. hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) {
  2609. OpCode = Opc;
  2610. LHSVal = getValue(LHS);
  2611. RHSVal = getValue(RHS);
  2612. BaseOps = {};
  2613. }
  2614. }
  2615. for (unsigned i = 0; i != NumValues; ++i) {
  2616. SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end());
  2617. Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i));
  2618. Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i));
  2619. Values[i] = DAG.getNode(OpCode, getCurSDLoc(),
  2620. LHSVal.getNode()->getValueType(LHSVal.getResNo()+i),
  2621. Ops);
  2622. }
  2623. setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
  2624. DAG.getVTList(ValueVTs), Values));
  2625. }
  2626. void SelectionDAGBuilder::visitTrunc(const User &I) {
  2627. // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
  2628. SDValue N = getValue(I.getOperand(0));
  2629. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  2630. I.getType());
  2631. setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N));
  2632. }
  2633. void SelectionDAGBuilder::visitZExt(const User &I) {
  2634. // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
  2635. // ZExt also can't be a cast to bool for same reason. So, nothing much to do
  2636. SDValue N = getValue(I.getOperand(0));
  2637. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  2638. I.getType());
  2639. setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N));
  2640. }
  2641. void SelectionDAGBuilder::visitSExt(const User &I) {
  2642. // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
  2643. // SExt also can't be a cast to bool for same reason. So, nothing much to do
  2644. SDValue N = getValue(I.getOperand(0));
  2645. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  2646. I.getType());
  2647. setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
  2648. }
  2649. void SelectionDAGBuilder::visitFPTrunc(const User &I) {
  2650. // FPTrunc is never a no-op cast, no need to check
  2651. SDValue N = getValue(I.getOperand(0));
  2652. SDLoc dl = getCurSDLoc();
  2653. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2654. EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  2655. setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N,
  2656. DAG.getTargetConstant(
  2657. 0, dl, TLI.getPointerTy(DAG.getDataLayout()))));
  2658. }
  2659. void SelectionDAGBuilder::visitFPExt(const User &I) {
  2660. // FPExt is never a no-op cast, no need to check
  2661. SDValue N = getValue(I.getOperand(0));
  2662. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  2663. I.getType());
  2664. setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N));
  2665. }
  2666. void SelectionDAGBuilder::visitFPToUI(const User &I) {
  2667. // FPToUI is never a no-op cast, no need to check
  2668. SDValue N = getValue(I.getOperand(0));
  2669. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  2670. I.getType());
  2671. setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N));
  2672. }
  2673. void SelectionDAGBuilder::visitFPToSI(const User &I) {
  2674. // FPToSI is never a no-op cast, no need to check
  2675. SDValue N = getValue(I.getOperand(0));
  2676. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  2677. I.getType());
  2678. setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N));
  2679. }
  2680. void SelectionDAGBuilder::visitUIToFP(const User &I) {
  2681. // UIToFP is never a no-op cast, no need to check
  2682. SDValue N = getValue(I.getOperand(0));
  2683. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  2684. I.getType());
  2685. setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N));
  2686. }
  2687. void SelectionDAGBuilder::visitSIToFP(const User &I) {
  2688. // SIToFP is never a no-op cast, no need to check
  2689. SDValue N = getValue(I.getOperand(0));
  2690. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  2691. I.getType());
  2692. setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N));
  2693. }
  2694. void SelectionDAGBuilder::visitPtrToInt(const User &I) {
  2695. // What to do depends on the size of the integer and the size of the pointer.
  2696. // We can either truncate, zero extend, or no-op, accordingly.
  2697. SDValue N = getValue(I.getOperand(0));
  2698. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  2699. I.getType());
  2700. setValue(&I, DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT));
  2701. }
  2702. void SelectionDAGBuilder::visitIntToPtr(const User &I) {
  2703. // What to do depends on the size of the integer and the size of the pointer.
  2704. // We can either truncate, zero extend, or no-op, accordingly.
  2705. SDValue N = getValue(I.getOperand(0));
  2706. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  2707. I.getType());
  2708. setValue(&I, DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT));
  2709. }
  2710. void SelectionDAGBuilder::visitBitCast(const User &I) {
  2711. SDValue N = getValue(I.getOperand(0));
  2712. SDLoc dl = getCurSDLoc();
  2713. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  2714. I.getType());
  2715. // BitCast assures us that source and destination are the same size so this is
  2716. // either a BITCAST or a no-op.
  2717. if (DestVT != N.getValueType())
  2718. setValue(&I, DAG.getNode(ISD::BITCAST, dl,
  2719. DestVT, N)); // convert types.
  2720. // Check if the original LLVM IR Operand was a ConstantInt, because getValue()
  2721. // might fold any kind of constant expression to an integer constant and that
  2722. // is not what we are looking for. Only recognize a bitcast of a genuine
  2723. // constant integer as an opaque constant.
  2724. else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0)))
  2725. setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false,
  2726. /*isOpaque*/true));
  2727. else
  2728. setValue(&I, N); // noop cast.
  2729. }
  2730. void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) {
  2731. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2732. const Value *SV = I.getOperand(0);
  2733. SDValue N = getValue(SV);
  2734. EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  2735. unsigned SrcAS = SV->getType()->getPointerAddressSpace();
  2736. unsigned DestAS = I.getType()->getPointerAddressSpace();
  2737. if (!TLI.isNoopAddrSpaceCast(SrcAS, DestAS))
  2738. N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS);
  2739. setValue(&I, N);
  2740. }
  2741. void SelectionDAGBuilder::visitInsertElement(const User &I) {
  2742. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2743. SDValue InVec = getValue(I.getOperand(0));
  2744. SDValue InVal = getValue(I.getOperand(1));
  2745. SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(),
  2746. TLI.getVectorIdxTy(DAG.getDataLayout()));
  2747. setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(),
  2748. TLI.getValueType(DAG.getDataLayout(), I.getType()),
  2749. InVec, InVal, InIdx));
  2750. }
  2751. void SelectionDAGBuilder::visitExtractElement(const User &I) {
  2752. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2753. SDValue InVec = getValue(I.getOperand(0));
  2754. SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(),
  2755. TLI.getVectorIdxTy(DAG.getDataLayout()));
  2756. setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(),
  2757. TLI.getValueType(DAG.getDataLayout(), I.getType()),
  2758. InVec, InIdx));
  2759. }
  2760. void SelectionDAGBuilder::visitShuffleVector(const User &I) {
  2761. SDValue Src1 = getValue(I.getOperand(0));
  2762. SDValue Src2 = getValue(I.getOperand(1));
  2763. SDLoc DL = getCurSDLoc();
  2764. SmallVector<int, 8> Mask;
  2765. ShuffleVectorInst::getShuffleMask(cast<Constant>(I.getOperand(2)), Mask);
  2766. unsigned MaskNumElts = Mask.size();
  2767. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2768. EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  2769. EVT SrcVT = Src1.getValueType();
  2770. unsigned SrcNumElts = SrcVT.getVectorNumElements();
  2771. if (SrcNumElts == MaskNumElts) {
  2772. setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask));
  2773. return;
  2774. }
  2775. // Normalize the shuffle vector since mask and vector length don't match.
  2776. if (SrcNumElts < MaskNumElts) {
  2777. // Mask is longer than the source vectors. We can use concatenate vector to
  2778. // make the mask and vectors lengths match.
  2779. if (MaskNumElts % SrcNumElts == 0) {
  2780. // Mask length is a multiple of the source vector length.
  2781. // Check if the shuffle is some kind of concatenation of the input
  2782. // vectors.
  2783. unsigned NumConcat = MaskNumElts / SrcNumElts;
  2784. bool IsConcat = true;
  2785. SmallVector<int, 8> ConcatSrcs(NumConcat, -1);
  2786. for (unsigned i = 0; i != MaskNumElts; ++i) {
  2787. int Idx = Mask[i];
  2788. if (Idx < 0)
  2789. continue;
  2790. // Ensure the indices in each SrcVT sized piece are sequential and that
  2791. // the same source is used for the whole piece.
  2792. if ((Idx % SrcNumElts != (i % SrcNumElts)) ||
  2793. (ConcatSrcs[i / SrcNumElts] >= 0 &&
  2794. ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) {
  2795. IsConcat = false;
  2796. break;
  2797. }
  2798. // Remember which source this index came from.
  2799. ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts;
  2800. }
  2801. // The shuffle is concatenating multiple vectors together. Just emit
  2802. // a CONCAT_VECTORS operation.
  2803. if (IsConcat) {
  2804. SmallVector<SDValue, 8> ConcatOps;
  2805. for (auto Src : ConcatSrcs) {
  2806. if (Src < 0)
  2807. ConcatOps.push_back(DAG.getUNDEF(SrcVT));
  2808. else if (Src == 0)
  2809. ConcatOps.push_back(Src1);
  2810. else
  2811. ConcatOps.push_back(Src2);
  2812. }
  2813. setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps));
  2814. return;
  2815. }
  2816. }
  2817. unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts);
  2818. unsigned NumConcat = PaddedMaskNumElts / SrcNumElts;
  2819. EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
  2820. PaddedMaskNumElts);
  2821. // Pad both vectors with undefs to make them the same length as the mask.
  2822. SDValue UndefVal = DAG.getUNDEF(SrcVT);
  2823. SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
  2824. SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
  2825. MOps1[0] = Src1;
  2826. MOps2[0] = Src2;
  2827. Src1 = Src1.isUndef()
  2828. ? DAG.getUNDEF(PaddedVT)
  2829. : DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1);
  2830. Src2 = Src2.isUndef()
  2831. ? DAG.getUNDEF(PaddedVT)
  2832. : DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2);
  2833. // Readjust mask for new input vector length.
  2834. SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1);
  2835. for (unsigned i = 0; i != MaskNumElts; ++i) {
  2836. int Idx = Mask[i];
  2837. if (Idx >= (int)SrcNumElts)
  2838. Idx -= SrcNumElts - PaddedMaskNumElts;
  2839. MappedOps[i] = Idx;
  2840. }
  2841. SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps);
  2842. // If the concatenated vector was padded, extract a subvector with the
  2843. // correct number of elements.
  2844. if (MaskNumElts != PaddedMaskNumElts)
  2845. Result = DAG.getNode(
  2846. ISD::EXTRACT_SUBVECTOR, DL, VT, Result,
  2847. DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
  2848. setValue(&I, Result);
  2849. return;
  2850. }
  2851. if (SrcNumElts > MaskNumElts) {
  2852. // Analyze the access pattern of the vector to see if we can extract
  2853. // two subvectors and do the shuffle.
  2854. int StartIdx[2] = { -1, -1 }; // StartIdx to extract from
  2855. bool CanExtract = true;
  2856. for (int Idx : Mask) {
  2857. unsigned Input = 0;
  2858. if (Idx < 0)
  2859. continue;
  2860. if (Idx >= (int)SrcNumElts) {
  2861. Input = 1;
  2862. Idx -= SrcNumElts;
  2863. }
  2864. // If all the indices come from the same MaskNumElts sized portion of
  2865. // the sources we can use extract. Also make sure the extract wouldn't
  2866. // extract past the end of the source.
  2867. int NewStartIdx = alignDown(Idx, MaskNumElts);
  2868. if (NewStartIdx + MaskNumElts > SrcNumElts ||
  2869. (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx))
  2870. CanExtract = false;
  2871. // Make sure we always update StartIdx as we use it to track if all
  2872. // elements are undef.
  2873. StartIdx[Input] = NewStartIdx;
  2874. }
  2875. if (StartIdx[0] < 0 && StartIdx[1] < 0) {
  2876. setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
  2877. return;
  2878. }
  2879. if (CanExtract) {
  2880. // Extract appropriate subvector and generate a vector shuffle
  2881. for (unsigned Input = 0; Input < 2; ++Input) {
  2882. SDValue &Src = Input == 0 ? Src1 : Src2;
  2883. if (StartIdx[Input] < 0)
  2884. Src = DAG.getUNDEF(VT);
  2885. else {
  2886. Src = DAG.getNode(
  2887. ISD::EXTRACT_SUBVECTOR, DL, VT, Src,
  2888. DAG.getConstant(StartIdx[Input], DL,
  2889. TLI.getVectorIdxTy(DAG.getDataLayout())));
  2890. }
  2891. }
  2892. // Calculate new mask.
  2893. SmallVector<int, 8> MappedOps(Mask.begin(), Mask.end());
  2894. for (int &Idx : MappedOps) {
  2895. if (Idx >= (int)SrcNumElts)
  2896. Idx -= SrcNumElts + StartIdx[1] - MaskNumElts;
  2897. else if (Idx >= 0)
  2898. Idx -= StartIdx[0];
  2899. }
  2900. setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps));
  2901. return;
  2902. }
  2903. }
  2904. // We can't use either concat vectors or extract subvectors so fall back to
  2905. // replacing the shuffle with extract and build vector.
  2906. // to insert and build vector.
  2907. EVT EltVT = VT.getVectorElementType();
  2908. EVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout());
  2909. SmallVector<SDValue,8> Ops;
  2910. for (int Idx : Mask) {
  2911. SDValue Res;
  2912. if (Idx < 0) {
  2913. Res = DAG.getUNDEF(EltVT);
  2914. } else {
  2915. SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2;
  2916. if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts;
  2917. Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
  2918. EltVT, Src, DAG.getConstant(Idx, DL, IdxVT));
  2919. }
  2920. Ops.push_back(Res);
  2921. }
  2922. setValue(&I, DAG.getBuildVector(VT, DL, Ops));
  2923. }
  2924. void SelectionDAGBuilder::visitInsertValue(const User &I) {
  2925. ArrayRef<unsigned> Indices;
  2926. if (const InsertValueInst *IV = dyn_cast<InsertValueInst>(&I))
  2927. Indices = IV->getIndices();
  2928. else
  2929. Indices = cast<ConstantExpr>(&I)->getIndices();
  2930. const Value *Op0 = I.getOperand(0);
  2931. const Value *Op1 = I.getOperand(1);
  2932. Type *AggTy = I.getType();
  2933. Type *ValTy = Op1->getType();
  2934. bool IntoUndef = isa<UndefValue>(Op0);
  2935. bool FromUndef = isa<UndefValue>(Op1);
  2936. unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
  2937. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2938. SmallVector<EVT, 4> AggValueVTs;
  2939. ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs);
  2940. SmallVector<EVT, 4> ValValueVTs;
  2941. ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
  2942. unsigned NumAggValues = AggValueVTs.size();
  2943. unsigned NumValValues = ValValueVTs.size();
  2944. SmallVector<SDValue, 4> Values(NumAggValues);
  2945. // Ignore an insertvalue that produces an empty object
  2946. if (!NumAggValues) {
  2947. setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
  2948. return;
  2949. }
  2950. SDValue Agg = getValue(Op0);
  2951. unsigned i = 0;
  2952. // Copy the beginning value(s) from the original aggregate.
  2953. for (; i != LinearIndex; ++i)
  2954. Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
  2955. SDValue(Agg.getNode(), Agg.getResNo() + i);
  2956. // Copy values from the inserted value(s).
  2957. if (NumValValues) {
  2958. SDValue Val = getValue(Op1);
  2959. for (; i != LinearIndex + NumValValues; ++i)
  2960. Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
  2961. SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
  2962. }
  2963. // Copy remaining value(s) from the original aggregate.
  2964. for (; i != NumAggValues; ++i)
  2965. Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
  2966. SDValue(Agg.getNode(), Agg.getResNo() + i);
  2967. setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
  2968. DAG.getVTList(AggValueVTs), Values));
  2969. }
  2970. void SelectionDAGBuilder::visitExtractValue(const User &I) {
  2971. ArrayRef<unsigned> Indices;
  2972. if (const ExtractValueInst *EV = dyn_cast<ExtractValueInst>(&I))
  2973. Indices = EV->getIndices();
  2974. else
  2975. Indices = cast<ConstantExpr>(&I)->getIndices();
  2976. const Value *Op0 = I.getOperand(0);
  2977. Type *AggTy = Op0->getType();
  2978. Type *ValTy = I.getType();
  2979. bool OutOfUndef = isa<UndefValue>(Op0);
  2980. unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
  2981. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2982. SmallVector<EVT, 4> ValValueVTs;
  2983. ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
  2984. unsigned NumValValues = ValValueVTs.size();
  2985. // Ignore a extractvalue that produces an empty object
  2986. if (!NumValValues) {
  2987. setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
  2988. return;
  2989. }
  2990. SmallVector<SDValue, 4> Values(NumValValues);
  2991. SDValue Agg = getValue(Op0);
  2992. // Copy out the selected value(s).
  2993. for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
  2994. Values[i - LinearIndex] =
  2995. OutOfUndef ?
  2996. DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
  2997. SDValue(Agg.getNode(), Agg.getResNo() + i);
  2998. setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
  2999. DAG.getVTList(ValValueVTs), Values));
  3000. }
  3001. void SelectionDAGBuilder::visitGetElementPtr(const User &I) {
  3002. Value *Op0 = I.getOperand(0);
  3003. // Note that the pointer operand may be a vector of pointers. Take the scalar
  3004. // element which holds a pointer.
  3005. unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace();
  3006. SDValue N = getValue(Op0);
  3007. SDLoc dl = getCurSDLoc();
  3008. // Normalize Vector GEP - all scalar operands should be converted to the
  3009. // splat vector.
  3010. unsigned VectorWidth = I.getType()->isVectorTy() ?
  3011. cast<VectorType>(I.getType())->getVectorNumElements() : 0;
  3012. if (VectorWidth && !N.getValueType().isVector()) {
  3013. LLVMContext &Context = *DAG.getContext();
  3014. EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorWidth);
  3015. N = DAG.getSplatBuildVector(VT, dl, N);
  3016. }
  3017. for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I);
  3018. GTI != E; ++GTI) {
  3019. const Value *Idx = GTI.getOperand();
  3020. if (StructType *StTy = GTI.getStructTypeOrNull()) {
  3021. unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
  3022. if (Field) {
  3023. // N = N + Offset
  3024. uint64_t Offset = DL->getStructLayout(StTy)->getElementOffset(Field);
  3025. // In an inbounds GEP with an offset that is nonnegative even when
  3026. // interpreted as signed, assume there is no unsigned overflow.
  3027. SDNodeFlags Flags;
  3028. if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds())
  3029. Flags.setNoUnsignedWrap(true);
  3030. N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N,
  3031. DAG.getConstant(Offset, dl, N.getValueType()), Flags);
  3032. }
  3033. } else {
  3034. unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS);
  3035. MVT IdxTy = MVT::getIntegerVT(IdxSize);
  3036. APInt ElementSize(IdxSize, DL->getTypeAllocSize(GTI.getIndexedType()));
  3037. // If this is a scalar constant or a splat vector of constants,
  3038. // handle it quickly.
  3039. const auto *CI = dyn_cast<ConstantInt>(Idx);
  3040. if (!CI && isa<ConstantDataVector>(Idx) &&
  3041. cast<ConstantDataVector>(Idx)->getSplatValue())
  3042. CI = cast<ConstantInt>(cast<ConstantDataVector>(Idx)->getSplatValue());
  3043. if (CI) {
  3044. if (CI->isZero())
  3045. continue;
  3046. APInt Offs = ElementSize * CI->getValue().sextOrTrunc(IdxSize);
  3047. LLVMContext &Context = *DAG.getContext();
  3048. SDValue OffsVal = VectorWidth ?
  3049. DAG.getConstant(Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorWidth)) :
  3050. DAG.getConstant(Offs, dl, IdxTy);
  3051. // In an inbouds GEP with an offset that is nonnegative even when
  3052. // interpreted as signed, assume there is no unsigned overflow.
  3053. SDNodeFlags Flags;
  3054. if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds())
  3055. Flags.setNoUnsignedWrap(true);
  3056. N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags);
  3057. continue;
  3058. }
  3059. // N = N + Idx * ElementSize;
  3060. SDValue IdxN = getValue(Idx);
  3061. if (!IdxN.getValueType().isVector() && VectorWidth) {
  3062. EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(), VectorWidth);
  3063. IdxN = DAG.getSplatBuildVector(VT, dl, IdxN);
  3064. }
  3065. // If the index is smaller or larger than intptr_t, truncate or extend
  3066. // it.
  3067. IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType());
  3068. // If this is a multiply by a power of two, turn it into a shl
  3069. // immediately. This is a very common case.
  3070. if (ElementSize != 1) {
  3071. if (ElementSize.isPowerOf2()) {
  3072. unsigned Amt = ElementSize.logBase2();
  3073. IdxN = DAG.getNode(ISD::SHL, dl,
  3074. N.getValueType(), IdxN,
  3075. DAG.getConstant(Amt, dl, IdxN.getValueType()));
  3076. } else {
  3077. SDValue Scale = DAG.getConstant(ElementSize, dl, IdxN.getValueType());
  3078. IdxN = DAG.getNode(ISD::MUL, dl,
  3079. N.getValueType(), IdxN, Scale);
  3080. }
  3081. }
  3082. N = DAG.getNode(ISD::ADD, dl,
  3083. N.getValueType(), N, IdxN);
  3084. }
  3085. }
  3086. setValue(&I, N);
  3087. }
  3088. void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) {
  3089. // If this is a fixed sized alloca in the entry block of the function,
  3090. // allocate it statically on the stack.
  3091. if (FuncInfo.StaticAllocaMap.count(&I))
  3092. return; // getValue will auto-populate this.
  3093. SDLoc dl = getCurSDLoc();
  3094. Type *Ty = I.getAllocatedType();
  3095. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3096. auto &DL = DAG.getDataLayout();
  3097. uint64_t TySize = DL.getTypeAllocSize(Ty);
  3098. unsigned Align =
  3099. std::max((unsigned)DL.getPrefTypeAlignment(Ty), I.getAlignment());
  3100. SDValue AllocSize = getValue(I.getArraySize());
  3101. EVT IntPtr = TLI.getPointerTy(DAG.getDataLayout(), DL.getAllocaAddrSpace());
  3102. if (AllocSize.getValueType() != IntPtr)
  3103. AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr);
  3104. AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr,
  3105. AllocSize,
  3106. DAG.getConstant(TySize, dl, IntPtr));
  3107. // Handle alignment. If the requested alignment is less than or equal to
  3108. // the stack alignment, ignore it. If the size is greater than or equal to
  3109. // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
  3110. unsigned StackAlign =
  3111. DAG.getSubtarget().getFrameLowering()->getStackAlignment();
  3112. if (Align <= StackAlign)
  3113. Align = 0;
  3114. // Round the size of the allocation up to the stack alignment size
  3115. // by add SA-1 to the size. This doesn't overflow because we're computing
  3116. // an address inside an alloca.
  3117. SDNodeFlags Flags;
  3118. Flags.setNoUnsignedWrap(true);
  3119. AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize,
  3120. DAG.getConstant(StackAlign - 1, dl, IntPtr), Flags);
  3121. // Mask out the low bits for alignment purposes.
  3122. AllocSize =
  3123. DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize,
  3124. DAG.getConstant(~(uint64_t)(StackAlign - 1), dl, IntPtr));
  3125. SDValue Ops[] = {getRoot(), AllocSize, DAG.getConstant(Align, dl, IntPtr)};
  3126. SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
  3127. SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops);
  3128. setValue(&I, DSA);
  3129. DAG.setRoot(DSA.getValue(1));
  3130. assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects());
  3131. }
  3132. void SelectionDAGBuilder::visitLoad(const LoadInst &I) {
  3133. if (I.isAtomic())
  3134. return visitAtomicLoad(I);
  3135. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3136. const Value *SV = I.getOperand(0);
  3137. if (TLI.supportSwiftError()) {
  3138. // Swifterror values can come from either a function parameter with
  3139. // swifterror attribute or an alloca with swifterror attribute.
  3140. if (const Argument *Arg = dyn_cast<Argument>(SV)) {
  3141. if (Arg->hasSwiftErrorAttr())
  3142. return visitLoadFromSwiftError(I);
  3143. }
  3144. if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) {
  3145. if (Alloca->isSwiftError())
  3146. return visitLoadFromSwiftError(I);
  3147. }
  3148. }
  3149. SDValue Ptr = getValue(SV);
  3150. Type *Ty = I.getType();
  3151. bool isVolatile = I.isVolatile();
  3152. bool isNonTemporal = I.getMetadata(LLVMContext::MD_nontemporal) != nullptr;
  3153. bool isInvariant = I.getMetadata(LLVMContext::MD_invariant_load) != nullptr;
  3154. bool isDereferenceable = isDereferenceablePointer(SV, DAG.getDataLayout());
  3155. unsigned Alignment = I.getAlignment();
  3156. AAMDNodes AAInfo;
  3157. I.getAAMetadata(AAInfo);
  3158. const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
  3159. SmallVector<EVT, 4> ValueVTs;
  3160. SmallVector<uint64_t, 4> Offsets;
  3161. ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &Offsets);
  3162. unsigned NumValues = ValueVTs.size();
  3163. if (NumValues == 0)
  3164. return;
  3165. SDValue Root;
  3166. bool ConstantMemory = false;
  3167. if (isVolatile || NumValues > MaxParallelChains)
  3168. // Serialize volatile loads with other side effects.
  3169. Root = getRoot();
  3170. else if (AA && AA->pointsToConstantMemory(MemoryLocation(
  3171. SV, DAG.getDataLayout().getTypeStoreSize(Ty), AAInfo))) {
  3172. // Do not serialize (non-volatile) loads of constant memory with anything.
  3173. Root = DAG.getEntryNode();
  3174. ConstantMemory = true;
  3175. } else {
  3176. // Do not serialize non-volatile loads against each other.
  3177. Root = DAG.getRoot();
  3178. }
  3179. SDLoc dl = getCurSDLoc();
  3180. if (isVolatile)
  3181. Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG);
  3182. // An aggregate load cannot wrap around the address space, so offsets to its
  3183. // parts don't wrap either.
  3184. SDNodeFlags Flags;
  3185. Flags.setNoUnsignedWrap(true);
  3186. SmallVector<SDValue, 4> Values(NumValues);
  3187. SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
  3188. EVT PtrVT = Ptr.getValueType();
  3189. unsigned ChainI = 0;
  3190. for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
  3191. // Serializing loads here may result in excessive register pressure, and
  3192. // TokenFactor places arbitrary choke points on the scheduler. SD scheduling
  3193. // could recover a bit by hoisting nodes upward in the chain by recognizing
  3194. // they are side-effect free or do not alias. The optimizer should really
  3195. // avoid this case by converting large object/array copies to llvm.memcpy
  3196. // (MaxParallelChains should always remain as failsafe).
  3197. if (ChainI == MaxParallelChains) {
  3198. assert(PendingLoads.empty() && "PendingLoads must be serialized first");
  3199. SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
  3200. makeArrayRef(Chains.data(), ChainI));
  3201. Root = Chain;
  3202. ChainI = 0;
  3203. }
  3204. SDValue A = DAG.getNode(ISD::ADD, dl,
  3205. PtrVT, Ptr,
  3206. DAG.getConstant(Offsets[i], dl, PtrVT),
  3207. Flags);
  3208. auto MMOFlags = MachineMemOperand::MONone;
  3209. if (isVolatile)
  3210. MMOFlags |= MachineMemOperand::MOVolatile;
  3211. if (isNonTemporal)
  3212. MMOFlags |= MachineMemOperand::MONonTemporal;
  3213. if (isInvariant)
  3214. MMOFlags |= MachineMemOperand::MOInvariant;
  3215. if (isDereferenceable)
  3216. MMOFlags |= MachineMemOperand::MODereferenceable;
  3217. MMOFlags |= TLI.getMMOFlags(I);
  3218. SDValue L = DAG.getLoad(ValueVTs[i], dl, Root, A,
  3219. MachinePointerInfo(SV, Offsets[i]), Alignment,
  3220. MMOFlags, AAInfo, Ranges);
  3221. Values[i] = L;
  3222. Chains[ChainI] = L.getValue(1);
  3223. }
  3224. if (!ConstantMemory) {
  3225. SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
  3226. makeArrayRef(Chains.data(), ChainI));
  3227. if (isVolatile)
  3228. DAG.setRoot(Chain);
  3229. else
  3230. PendingLoads.push_back(Chain);
  3231. }
  3232. setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl,
  3233. DAG.getVTList(ValueVTs), Values));
  3234. }
  3235. void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) {
  3236. assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
  3237. "call visitStoreToSwiftError when backend supports swifterror");
  3238. SmallVector<EVT, 4> ValueVTs;
  3239. SmallVector<uint64_t, 4> Offsets;
  3240. const Value *SrcV = I.getOperand(0);
  3241. ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
  3242. SrcV->getType(), ValueVTs, &Offsets);
  3243. assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
  3244. "expect a single EVT for swifterror");
  3245. SDValue Src = getValue(SrcV);
  3246. // Create a virtual register, then update the virtual register.
  3247. unsigned VReg; bool CreatedVReg;
  3248. std::tie(VReg, CreatedVReg) = FuncInfo.getOrCreateSwiftErrorVRegDefAt(&I);
  3249. // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue
  3250. // Chain can be getRoot or getControlRoot.
  3251. SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg,
  3252. SDValue(Src.getNode(), Src.getResNo()));
  3253. DAG.setRoot(CopyNode);
  3254. if (CreatedVReg)
  3255. FuncInfo.setCurrentSwiftErrorVReg(FuncInfo.MBB, I.getOperand(1), VReg);
  3256. }
  3257. void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) {
  3258. assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
  3259. "call visitLoadFromSwiftError when backend supports swifterror");
  3260. assert(!I.isVolatile() &&
  3261. I.getMetadata(LLVMContext::MD_nontemporal) == nullptr &&
  3262. I.getMetadata(LLVMContext::MD_invariant_load) == nullptr &&
  3263. "Support volatile, non temporal, invariant for load_from_swift_error");
  3264. const Value *SV = I.getOperand(0);
  3265. Type *Ty = I.getType();
  3266. AAMDNodes AAInfo;
  3267. I.getAAMetadata(AAInfo);
  3268. assert((!AA || !AA->pointsToConstantMemory(MemoryLocation(
  3269. SV, DAG.getDataLayout().getTypeStoreSize(Ty), AAInfo))) &&
  3270. "load_from_swift_error should not be constant memory");
  3271. SmallVector<EVT, 4> ValueVTs;
  3272. SmallVector<uint64_t, 4> Offsets;
  3273. ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty,
  3274. ValueVTs, &Offsets);
  3275. assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
  3276. "expect a single EVT for swifterror");
  3277. // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT
  3278. SDValue L = DAG.getCopyFromReg(
  3279. getRoot(), getCurSDLoc(),
  3280. FuncInfo.getOrCreateSwiftErrorVRegUseAt(&I, FuncInfo.MBB, SV).first,
  3281. ValueVTs[0]);
  3282. setValue(&I, L);
  3283. }
  3284. void SelectionDAGBuilder::visitStore(const StoreInst &I) {
  3285. if (I.isAtomic())
  3286. return visitAtomicStore(I);
  3287. const Value *SrcV = I.getOperand(0);
  3288. const Value *PtrV = I.getOperand(1);
  3289. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3290. if (TLI.supportSwiftError()) {
  3291. // Swifterror values can come from either a function parameter with
  3292. // swifterror attribute or an alloca with swifterror attribute.
  3293. if (const Argument *Arg = dyn_cast<Argument>(PtrV)) {
  3294. if (Arg->hasSwiftErrorAttr())
  3295. return visitStoreToSwiftError(I);
  3296. }
  3297. if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) {
  3298. if (Alloca->isSwiftError())
  3299. return visitStoreToSwiftError(I);
  3300. }
  3301. }
  3302. SmallVector<EVT, 4> ValueVTs;
  3303. SmallVector<uint64_t, 4> Offsets;
  3304. ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
  3305. SrcV->getType(), ValueVTs, &Offsets);
  3306. unsigned NumValues = ValueVTs.size();
  3307. if (NumValues == 0)
  3308. return;
  3309. // Get the lowered operands. Note that we do this after
  3310. // checking if NumResults is zero, because with zero results
  3311. // the operands won't have values in the map.
  3312. SDValue Src = getValue(SrcV);
  3313. SDValue Ptr = getValue(PtrV);
  3314. SDValue Root = getRoot();
  3315. SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
  3316. SDLoc dl = getCurSDLoc();
  3317. EVT PtrVT = Ptr.getValueType();
  3318. unsigned Alignment = I.getAlignment();
  3319. AAMDNodes AAInfo;
  3320. I.getAAMetadata(AAInfo);
  3321. auto MMOFlags = MachineMemOperand::MONone;
  3322. if (I.isVolatile())
  3323. MMOFlags |= MachineMemOperand::MOVolatile;
  3324. if (I.getMetadata(LLVMContext::MD_nontemporal) != nullptr)
  3325. MMOFlags |= MachineMemOperand::MONonTemporal;
  3326. MMOFlags |= TLI.getMMOFlags(I);
  3327. // An aggregate load cannot wrap around the address space, so offsets to its
  3328. // parts don't wrap either.
  3329. SDNodeFlags Flags;
  3330. Flags.setNoUnsignedWrap(true);
  3331. unsigned ChainI = 0;
  3332. for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
  3333. // See visitLoad comments.
  3334. if (ChainI == MaxParallelChains) {
  3335. SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
  3336. makeArrayRef(Chains.data(), ChainI));
  3337. Root = Chain;
  3338. ChainI = 0;
  3339. }
  3340. SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, Ptr,
  3341. DAG.getConstant(Offsets[i], dl, PtrVT), Flags);
  3342. SDValue St = DAG.getStore(
  3343. Root, dl, SDValue(Src.getNode(), Src.getResNo() + i), Add,
  3344. MachinePointerInfo(PtrV, Offsets[i]), Alignment, MMOFlags, AAInfo);
  3345. Chains[ChainI] = St;
  3346. }
  3347. SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
  3348. makeArrayRef(Chains.data(), ChainI));
  3349. DAG.setRoot(StoreNode);
  3350. }
  3351. void SelectionDAGBuilder::visitMaskedStore(const CallInst &I,
  3352. bool IsCompressing) {
  3353. SDLoc sdl = getCurSDLoc();
  3354. auto getMaskedStoreOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
  3355. unsigned& Alignment) {
  3356. // llvm.masked.store.*(Src0, Ptr, alignment, Mask)
  3357. Src0 = I.getArgOperand(0);
  3358. Ptr = I.getArgOperand(1);
  3359. Alignment = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue();
  3360. Mask = I.getArgOperand(3);
  3361. };
  3362. auto getCompressingStoreOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
  3363. unsigned& Alignment) {
  3364. // llvm.masked.compressstore.*(Src0, Ptr, Mask)
  3365. Src0 = I.getArgOperand(0);
  3366. Ptr = I.getArgOperand(1);
  3367. Mask = I.getArgOperand(2);
  3368. Alignment = 0;
  3369. };
  3370. Value *PtrOperand, *MaskOperand, *Src0Operand;
  3371. unsigned Alignment;
  3372. if (IsCompressing)
  3373. getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
  3374. else
  3375. getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
  3376. SDValue Ptr = getValue(PtrOperand);
  3377. SDValue Src0 = getValue(Src0Operand);
  3378. SDValue Mask = getValue(MaskOperand);
  3379. EVT VT = Src0.getValueType();
  3380. if (!Alignment)
  3381. Alignment = DAG.getEVTAlignment(VT);
  3382. AAMDNodes AAInfo;
  3383. I.getAAMetadata(AAInfo);
  3384. MachineMemOperand *MMO =
  3385. DAG.getMachineFunction().
  3386. getMachineMemOperand(MachinePointerInfo(PtrOperand),
  3387. MachineMemOperand::MOStore, VT.getStoreSize(),
  3388. Alignment, AAInfo);
  3389. SDValue StoreNode = DAG.getMaskedStore(getRoot(), sdl, Src0, Ptr, Mask, VT,
  3390. MMO, false /* Truncating */,
  3391. IsCompressing);
  3392. DAG.setRoot(StoreNode);
  3393. setValue(&I, StoreNode);
  3394. }
  3395. // Get a uniform base for the Gather/Scatter intrinsic.
  3396. // The first argument of the Gather/Scatter intrinsic is a vector of pointers.
  3397. // We try to represent it as a base pointer + vector of indices.
  3398. // Usually, the vector of pointers comes from a 'getelementptr' instruction.
  3399. // The first operand of the GEP may be a single pointer or a vector of pointers
  3400. // Example:
  3401. // %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind
  3402. // or
  3403. // %gep.ptr = getelementptr i32, i32* %ptr, <8 x i32> %ind
  3404. // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, ..
  3405. //
  3406. // When the first GEP operand is a single pointer - it is the uniform base we
  3407. // are looking for. If first operand of the GEP is a splat vector - we
  3408. // extract the splat value and use it as a uniform base.
  3409. // In all other cases the function returns 'false'.
  3410. static bool getUniformBase(const Value* &Ptr, SDValue& Base, SDValue& Index,
  3411. SDValue &Scale, SelectionDAGBuilder* SDB) {
  3412. SelectionDAG& DAG = SDB->DAG;
  3413. LLVMContext &Context = *DAG.getContext();
  3414. assert(Ptr->getType()->isVectorTy() && "Uexpected pointer type");
  3415. const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr);
  3416. if (!GEP)
  3417. return false;
  3418. const Value *GEPPtr = GEP->getPointerOperand();
  3419. if (!GEPPtr->getType()->isVectorTy())
  3420. Ptr = GEPPtr;
  3421. else if (!(Ptr = getSplatValue(GEPPtr)))
  3422. return false;
  3423. unsigned FinalIndex = GEP->getNumOperands() - 1;
  3424. Value *IndexVal = GEP->getOperand(FinalIndex);
  3425. // Ensure all the other indices are 0.
  3426. for (unsigned i = 1; i < FinalIndex; ++i) {
  3427. auto *C = dyn_cast<ConstantInt>(GEP->getOperand(i));
  3428. if (!C || !C->isZero())
  3429. return false;
  3430. }
  3431. // The operands of the GEP may be defined in another basic block.
  3432. // In this case we'll not find nodes for the operands.
  3433. if (!SDB->findValue(Ptr) || !SDB->findValue(IndexVal))
  3434. return false;
  3435. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3436. const DataLayout &DL = DAG.getDataLayout();
  3437. Scale = DAG.getTargetConstant(DL.getTypeAllocSize(GEP->getResultElementType()),
  3438. SDB->getCurSDLoc(), TLI.getPointerTy(DL));
  3439. Base = SDB->getValue(Ptr);
  3440. Index = SDB->getValue(IndexVal);
  3441. if (!Index.getValueType().isVector()) {
  3442. unsigned GEPWidth = GEP->getType()->getVectorNumElements();
  3443. EVT VT = EVT::getVectorVT(Context, Index.getValueType(), GEPWidth);
  3444. Index = DAG.getSplatBuildVector(VT, SDLoc(Index), Index);
  3445. }
  3446. return true;
  3447. }
  3448. void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) {
  3449. SDLoc sdl = getCurSDLoc();
  3450. // llvm.masked.scatter.*(Src0, Ptrs, alignemt, Mask)
  3451. const Value *Ptr = I.getArgOperand(1);
  3452. SDValue Src0 = getValue(I.getArgOperand(0));
  3453. SDValue Mask = getValue(I.getArgOperand(3));
  3454. EVT VT = Src0.getValueType();
  3455. unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(2)))->getZExtValue();
  3456. if (!Alignment)
  3457. Alignment = DAG.getEVTAlignment(VT);
  3458. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3459. AAMDNodes AAInfo;
  3460. I.getAAMetadata(AAInfo);
  3461. SDValue Base;
  3462. SDValue Index;
  3463. SDValue Scale;
  3464. const Value *BasePtr = Ptr;
  3465. bool UniformBase = getUniformBase(BasePtr, Base, Index, Scale, this);
  3466. const Value *MemOpBasePtr = UniformBase ? BasePtr : nullptr;
  3467. MachineMemOperand *MMO = DAG.getMachineFunction().
  3468. getMachineMemOperand(MachinePointerInfo(MemOpBasePtr),
  3469. MachineMemOperand::MOStore, VT.getStoreSize(),
  3470. Alignment, AAInfo);
  3471. if (!UniformBase) {
  3472. Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
  3473. Index = getValue(Ptr);
  3474. Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
  3475. }
  3476. SDValue Ops[] = { getRoot(), Src0, Mask, Base, Index, Scale };
  3477. SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl,
  3478. Ops, MMO);
  3479. DAG.setRoot(Scatter);
  3480. setValue(&I, Scatter);
  3481. }
  3482. void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) {
  3483. SDLoc sdl = getCurSDLoc();
  3484. auto getMaskedLoadOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
  3485. unsigned& Alignment) {
  3486. // @llvm.masked.load.*(Ptr, alignment, Mask, Src0)
  3487. Ptr = I.getArgOperand(0);
  3488. Alignment = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
  3489. Mask = I.getArgOperand(2);
  3490. Src0 = I.getArgOperand(3);
  3491. };
  3492. auto getExpandingLoadOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
  3493. unsigned& Alignment) {
  3494. // @llvm.masked.expandload.*(Ptr, Mask, Src0)
  3495. Ptr = I.getArgOperand(0);
  3496. Alignment = 0;
  3497. Mask = I.getArgOperand(1);
  3498. Src0 = I.getArgOperand(2);
  3499. };
  3500. Value *PtrOperand, *MaskOperand, *Src0Operand;
  3501. unsigned Alignment;
  3502. if (IsExpanding)
  3503. getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
  3504. else
  3505. getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
  3506. SDValue Ptr = getValue(PtrOperand);
  3507. SDValue Src0 = getValue(Src0Operand);
  3508. SDValue Mask = getValue(MaskOperand);
  3509. EVT VT = Src0.getValueType();
  3510. if (!Alignment)
  3511. Alignment = DAG.getEVTAlignment(VT);
  3512. AAMDNodes AAInfo;
  3513. I.getAAMetadata(AAInfo);
  3514. const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
  3515. // Do not serialize masked loads of constant memory with anything.
  3516. bool AddToChain = !AA || !AA->pointsToConstantMemory(MemoryLocation(
  3517. PtrOperand, DAG.getDataLayout().getTypeStoreSize(I.getType()), AAInfo));
  3518. SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
  3519. MachineMemOperand *MMO =
  3520. DAG.getMachineFunction().
  3521. getMachineMemOperand(MachinePointerInfo(PtrOperand),
  3522. MachineMemOperand::MOLoad, VT.getStoreSize(),
  3523. Alignment, AAInfo, Ranges);
  3524. SDValue Load = DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Mask, Src0, VT, MMO,
  3525. ISD::NON_EXTLOAD, IsExpanding);
  3526. if (AddToChain) {
  3527. SDValue OutChain = Load.getValue(1);
  3528. DAG.setRoot(OutChain);
  3529. }
  3530. setValue(&I, Load);
  3531. }
  3532. void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) {
  3533. SDLoc sdl = getCurSDLoc();
  3534. // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0)
  3535. const Value *Ptr = I.getArgOperand(0);
  3536. SDValue Src0 = getValue(I.getArgOperand(3));
  3537. SDValue Mask = getValue(I.getArgOperand(2));
  3538. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3539. EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  3540. unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(1)))->getZExtValue();
  3541. if (!Alignment)
  3542. Alignment = DAG.getEVTAlignment(VT);
  3543. AAMDNodes AAInfo;
  3544. I.getAAMetadata(AAInfo);
  3545. const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
  3546. SDValue Root = DAG.getRoot();
  3547. SDValue Base;
  3548. SDValue Index;
  3549. SDValue Scale;
  3550. const Value *BasePtr = Ptr;
  3551. bool UniformBase = getUniformBase(BasePtr, Base, Index, Scale, this);
  3552. bool ConstantMemory = false;
  3553. if (UniformBase &&
  3554. AA && AA->pointsToConstantMemory(MemoryLocation(
  3555. BasePtr, DAG.getDataLayout().getTypeStoreSize(I.getType()),
  3556. AAInfo))) {
  3557. // Do not serialize (non-volatile) loads of constant memory with anything.
  3558. Root = DAG.getEntryNode();
  3559. ConstantMemory = true;
  3560. }
  3561. MachineMemOperand *MMO =
  3562. DAG.getMachineFunction().
  3563. getMachineMemOperand(MachinePointerInfo(UniformBase ? BasePtr : nullptr),
  3564. MachineMemOperand::MOLoad, VT.getStoreSize(),
  3565. Alignment, AAInfo, Ranges);
  3566. if (!UniformBase) {
  3567. Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
  3568. Index = getValue(Ptr);
  3569. Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
  3570. }
  3571. SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale };
  3572. SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl,
  3573. Ops, MMO);
  3574. SDValue OutChain = Gather.getValue(1);
  3575. if (!ConstantMemory)
  3576. PendingLoads.push_back(OutChain);
  3577. setValue(&I, Gather);
  3578. }
  3579. void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) {
  3580. SDLoc dl = getCurSDLoc();
  3581. AtomicOrdering SuccessOrder = I.getSuccessOrdering();
  3582. AtomicOrdering FailureOrder = I.getFailureOrdering();
  3583. SyncScope::ID SSID = I.getSyncScopeID();
  3584. SDValue InChain = getRoot();
  3585. MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType();
  3586. SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other);
  3587. SDValue L = DAG.getAtomicCmpSwap(
  3588. ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, dl, MemVT, VTs, InChain,
  3589. getValue(I.getPointerOperand()), getValue(I.getCompareOperand()),
  3590. getValue(I.getNewValOperand()), MachinePointerInfo(I.getPointerOperand()),
  3591. /*Alignment=*/ 0, SuccessOrder, FailureOrder, SSID);
  3592. SDValue OutChain = L.getValue(2);
  3593. setValue(&I, L);
  3594. DAG.setRoot(OutChain);
  3595. }
  3596. void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) {
  3597. SDLoc dl = getCurSDLoc();
  3598. ISD::NodeType NT;
  3599. switch (I.getOperation()) {
  3600. default: llvm_unreachable("Unknown atomicrmw operation");
  3601. case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break;
  3602. case AtomicRMWInst::Add: NT = ISD::ATOMIC_LOAD_ADD; break;
  3603. case AtomicRMWInst::Sub: NT = ISD::ATOMIC_LOAD_SUB; break;
  3604. case AtomicRMWInst::And: NT = ISD::ATOMIC_LOAD_AND; break;
  3605. case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break;
  3606. case AtomicRMWInst::Or: NT = ISD::ATOMIC_LOAD_OR; break;
  3607. case AtomicRMWInst::Xor: NT = ISD::ATOMIC_LOAD_XOR; break;
  3608. case AtomicRMWInst::Max: NT = ISD::ATOMIC_LOAD_MAX; break;
  3609. case AtomicRMWInst::Min: NT = ISD::ATOMIC_LOAD_MIN; break;
  3610. case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break;
  3611. case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break;
  3612. }
  3613. AtomicOrdering Order = I.getOrdering();
  3614. SyncScope::ID SSID = I.getSyncScopeID();
  3615. SDValue InChain = getRoot();
  3616. SDValue L =
  3617. DAG.getAtomic(NT, dl,
  3618. getValue(I.getValOperand()).getSimpleValueType(),
  3619. InChain,
  3620. getValue(I.getPointerOperand()),
  3621. getValue(I.getValOperand()),
  3622. I.getPointerOperand(),
  3623. /* Alignment=*/ 0, Order, SSID);
  3624. SDValue OutChain = L.getValue(1);
  3625. setValue(&I, L);
  3626. DAG.setRoot(OutChain);
  3627. }
  3628. void SelectionDAGBuilder::visitFence(const FenceInst &I) {
  3629. SDLoc dl = getCurSDLoc();
  3630. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3631. SDValue Ops[3];
  3632. Ops[0] = getRoot();
  3633. Ops[1] = DAG.getConstant((unsigned)I.getOrdering(), dl,
  3634. TLI.getFenceOperandTy(DAG.getDataLayout()));
  3635. Ops[2] = DAG.getConstant(I.getSyncScopeID(), dl,
  3636. TLI.getFenceOperandTy(DAG.getDataLayout()));
  3637. DAG.setRoot(DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops));
  3638. }
  3639. void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) {
  3640. SDLoc dl = getCurSDLoc();
  3641. AtomicOrdering Order = I.getOrdering();
  3642. SyncScope::ID SSID = I.getSyncScopeID();
  3643. SDValue InChain = getRoot();
  3644. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3645. EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  3646. if (!TLI.supportsUnalignedAtomics() &&
  3647. I.getAlignment() < VT.getStoreSize())
  3648. report_fatal_error("Cannot generate unaligned atomic load");
  3649. MachineMemOperand *MMO =
  3650. DAG.getMachineFunction().
  3651. getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()),
  3652. MachineMemOperand::MOVolatile |
  3653. MachineMemOperand::MOLoad,
  3654. VT.getStoreSize(),
  3655. I.getAlignment() ? I.getAlignment() :
  3656. DAG.getEVTAlignment(VT),
  3657. AAMDNodes(), nullptr, SSID, Order);
  3658. InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG);
  3659. SDValue L =
  3660. DAG.getAtomic(ISD::ATOMIC_LOAD, dl, VT, VT, InChain,
  3661. getValue(I.getPointerOperand()), MMO);
  3662. SDValue OutChain = L.getValue(1);
  3663. setValue(&I, L);
  3664. DAG.setRoot(OutChain);
  3665. }
  3666. void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) {
  3667. SDLoc dl = getCurSDLoc();
  3668. AtomicOrdering Order = I.getOrdering();
  3669. SyncScope::ID SSID = I.getSyncScopeID();
  3670. SDValue InChain = getRoot();
  3671. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3672. EVT VT =
  3673. TLI.getValueType(DAG.getDataLayout(), I.getValueOperand()->getType());
  3674. if (I.getAlignment() < VT.getStoreSize())
  3675. report_fatal_error("Cannot generate unaligned atomic store");
  3676. SDValue OutChain =
  3677. DAG.getAtomic(ISD::ATOMIC_STORE, dl, VT,
  3678. InChain,
  3679. getValue(I.getPointerOperand()),
  3680. getValue(I.getValueOperand()),
  3681. I.getPointerOperand(), I.getAlignment(),
  3682. Order, SSID);
  3683. DAG.setRoot(OutChain);
  3684. }
  3685. /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
  3686. /// node.
  3687. void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I,
  3688. unsigned Intrinsic) {
  3689. // Ignore the callsite's attributes. A specific call site may be marked with
  3690. // readnone, but the lowering code will expect the chain based on the
  3691. // definition.
  3692. const Function *F = I.getCalledFunction();
  3693. bool HasChain = !F->doesNotAccessMemory();
  3694. bool OnlyLoad = HasChain && F->onlyReadsMemory();
  3695. // Build the operand list.
  3696. SmallVector<SDValue, 8> Ops;
  3697. if (HasChain) { // If this intrinsic has side-effects, chainify it.
  3698. if (OnlyLoad) {
  3699. // We don't need to serialize loads against other loads.
  3700. Ops.push_back(DAG.getRoot());
  3701. } else {
  3702. Ops.push_back(getRoot());
  3703. }
  3704. }
  3705. // Info is set by getTgtMemInstrinsic
  3706. TargetLowering::IntrinsicInfo Info;
  3707. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3708. bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I,
  3709. DAG.getMachineFunction(),
  3710. Intrinsic);
  3711. // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
  3712. if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID ||
  3713. Info.opc == ISD::INTRINSIC_W_CHAIN)
  3714. Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(),
  3715. TLI.getPointerTy(DAG.getDataLayout())));
  3716. // Add all operands of the call to the operand list.
  3717. for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) {
  3718. SDValue Op = getValue(I.getArgOperand(i));
  3719. Ops.push_back(Op);
  3720. }
  3721. SmallVector<EVT, 4> ValueVTs;
  3722. ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs);
  3723. if (HasChain)
  3724. ValueVTs.push_back(MVT::Other);
  3725. SDVTList VTs = DAG.getVTList(ValueVTs);
  3726. // Create the node.
  3727. SDValue Result;
  3728. if (IsTgtIntrinsic) {
  3729. // This is target intrinsic that touches memory
  3730. Result = DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(), VTs,
  3731. Ops, Info.memVT,
  3732. MachinePointerInfo(Info.ptrVal, Info.offset), Info.align,
  3733. Info.flags, Info.size);
  3734. } else if (!HasChain) {
  3735. Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops);
  3736. } else if (!I.getType()->isVoidTy()) {
  3737. Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops);
  3738. } else {
  3739. Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops);
  3740. }
  3741. if (HasChain) {
  3742. SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
  3743. if (OnlyLoad)
  3744. PendingLoads.push_back(Chain);
  3745. else
  3746. DAG.setRoot(Chain);
  3747. }
  3748. if (!I.getType()->isVoidTy()) {
  3749. if (VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
  3750. EVT VT = TLI.getValueType(DAG.getDataLayout(), PTy);
  3751. Result = DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT, Result);
  3752. } else
  3753. Result = lowerRangeToAssertZExt(DAG, I, Result);
  3754. setValue(&I, Result);
  3755. }
  3756. }
  3757. /// GetSignificand - Get the significand and build it into a floating-point
  3758. /// number with exponent of 1:
  3759. ///
  3760. /// Op = (Op & 0x007fffff) | 0x3f800000;
  3761. ///
  3762. /// where Op is the hexadecimal representation of floating point value.
  3763. static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) {
  3764. SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
  3765. DAG.getConstant(0x007fffff, dl, MVT::i32));
  3766. SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
  3767. DAG.getConstant(0x3f800000, dl, MVT::i32));
  3768. return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2);
  3769. }
  3770. /// GetExponent - Get the exponent:
  3771. ///
  3772. /// (float)(int)(((Op & 0x7f800000) >> 23) - 127);
  3773. ///
  3774. /// where Op is the hexadecimal representation of floating point value.
  3775. static SDValue GetExponent(SelectionDAG &DAG, SDValue Op,
  3776. const TargetLowering &TLI, const SDLoc &dl) {
  3777. SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
  3778. DAG.getConstant(0x7f800000, dl, MVT::i32));
  3779. SDValue t1 = DAG.getNode(
  3780. ISD::SRL, dl, MVT::i32, t0,
  3781. DAG.getConstant(23, dl, TLI.getPointerTy(DAG.getDataLayout())));
  3782. SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
  3783. DAG.getConstant(127, dl, MVT::i32));
  3784. return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
  3785. }
  3786. /// getF32Constant - Get 32-bit floating point constant.
  3787. static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt,
  3788. const SDLoc &dl) {
  3789. return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl,
  3790. MVT::f32);
  3791. }
  3792. static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl,
  3793. SelectionDAG &DAG) {
  3794. // TODO: What fast-math-flags should be set on the floating-point nodes?
  3795. // IntegerPartOfX = ((int32_t)(t0);
  3796. SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
  3797. // FractionalPartOfX = t0 - (float)IntegerPartOfX;
  3798. SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
  3799. SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
  3800. // IntegerPartOfX <<= 23;
  3801. IntegerPartOfX = DAG.getNode(
  3802. ISD::SHL, dl, MVT::i32, IntegerPartOfX,
  3803. DAG.getConstant(23, dl, DAG.getTargetLoweringInfo().getPointerTy(
  3804. DAG.getDataLayout())));
  3805. SDValue TwoToFractionalPartOfX;
  3806. if (LimitFloatPrecision <= 6) {
  3807. // For floating-point precision of 6:
  3808. //
  3809. // TwoToFractionalPartOfX =
  3810. // 0.997535578f +
  3811. // (0.735607626f + 0.252464424f * x) * x;
  3812. //
  3813. // error 0.0144103317, which is 6 bits
  3814. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  3815. getF32Constant(DAG, 0x3e814304, dl));
  3816. SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
  3817. getF32Constant(DAG, 0x3f3c50c8, dl));
  3818. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  3819. TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  3820. getF32Constant(DAG, 0x3f7f5e7e, dl));
  3821. } else if (LimitFloatPrecision <= 12) {
  3822. // For floating-point precision of 12:
  3823. //
  3824. // TwoToFractionalPartOfX =
  3825. // 0.999892986f +
  3826. // (0.696457318f +
  3827. // (0.224338339f + 0.792043434e-1f * x) * x) * x;
  3828. //
  3829. // error 0.000107046256, which is 13 to 14 bits
  3830. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  3831. getF32Constant(DAG, 0x3da235e3, dl));
  3832. SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
  3833. getF32Constant(DAG, 0x3e65b8f3, dl));
  3834. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  3835. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  3836. getF32Constant(DAG, 0x3f324b07, dl));
  3837. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  3838. TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
  3839. getF32Constant(DAG, 0x3f7ff8fd, dl));
  3840. } else { // LimitFloatPrecision <= 18
  3841. // For floating-point precision of 18:
  3842. //
  3843. // TwoToFractionalPartOfX =
  3844. // 0.999999982f +
  3845. // (0.693148872f +
  3846. // (0.240227044f +
  3847. // (0.554906021e-1f +
  3848. // (0.961591928e-2f +
  3849. // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
  3850. // error 2.47208000*10^(-7), which is better than 18 bits
  3851. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  3852. getF32Constant(DAG, 0x3924b03e, dl));
  3853. SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
  3854. getF32Constant(DAG, 0x3ab24b87, dl));
  3855. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  3856. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  3857. getF32Constant(DAG, 0x3c1d8c17, dl));
  3858. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  3859. SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
  3860. getF32Constant(DAG, 0x3d634a1d, dl));
  3861. SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
  3862. SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
  3863. getF32Constant(DAG, 0x3e75fe14, dl));
  3864. SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
  3865. SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
  3866. getF32Constant(DAG, 0x3f317234, dl));
  3867. SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
  3868. TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
  3869. getF32Constant(DAG, 0x3f800000, dl));
  3870. }
  3871. // Add the exponent into the result in integer domain.
  3872. SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX);
  3873. return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
  3874. DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX));
  3875. }
  3876. /// expandExp - Lower an exp intrinsic. Handles the special sequences for
  3877. /// limited-precision mode.
  3878. static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
  3879. const TargetLowering &TLI) {
  3880. if (Op.getValueType() == MVT::f32 &&
  3881. LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
  3882. // Put the exponent in the right bit position for later addition to the
  3883. // final result:
  3884. //
  3885. // #define LOG2OFe 1.4426950f
  3886. // t0 = Op * LOG2OFe
  3887. // TODO: What fast-math-flags should be set here?
  3888. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
  3889. getF32Constant(DAG, 0x3fb8aa3b, dl));
  3890. return getLimitedPrecisionExp2(t0, dl, DAG);
  3891. }
  3892. // No special expansion.
  3893. return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op);
  3894. }
  3895. /// expandLog - Lower a log intrinsic. Handles the special sequences for
  3896. /// limited-precision mode.
  3897. static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
  3898. const TargetLowering &TLI) {
  3899. // TODO: What fast-math-flags should be set on the floating-point nodes?
  3900. if (Op.getValueType() == MVT::f32 &&
  3901. LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
  3902. SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
  3903. // Scale the exponent by log(2) [0.69314718f].
  3904. SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
  3905. SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
  3906. getF32Constant(DAG, 0x3f317218, dl));
  3907. // Get the significand and build it into a floating-point number with
  3908. // exponent of 1.
  3909. SDValue X = GetSignificand(DAG, Op1, dl);
  3910. SDValue LogOfMantissa;
  3911. if (LimitFloatPrecision <= 6) {
  3912. // For floating-point precision of 6:
  3913. //
  3914. // LogofMantissa =
  3915. // -1.1609546f +
  3916. // (1.4034025f - 0.23903021f * x) * x;
  3917. //
  3918. // error 0.0034276066, which is better than 8 bits
  3919. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  3920. getF32Constant(DAG, 0xbe74c456, dl));
  3921. SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
  3922. getF32Constant(DAG, 0x3fb3a2b1, dl));
  3923. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  3924. LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
  3925. getF32Constant(DAG, 0x3f949a29, dl));
  3926. } else if (LimitFloatPrecision <= 12) {
  3927. // For floating-point precision of 12:
  3928. //
  3929. // LogOfMantissa =
  3930. // -1.7417939f +
  3931. // (2.8212026f +
  3932. // (-1.4699568f +
  3933. // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
  3934. //
  3935. // error 0.000061011436, which is 14 bits
  3936. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  3937. getF32Constant(DAG, 0xbd67b6d6, dl));
  3938. SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
  3939. getF32Constant(DAG, 0x3ee4f4b8, dl));
  3940. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  3941. SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
  3942. getF32Constant(DAG, 0x3fbc278b, dl));
  3943. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  3944. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  3945. getF32Constant(DAG, 0x40348e95, dl));
  3946. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  3947. LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
  3948. getF32Constant(DAG, 0x3fdef31a, dl));
  3949. } else { // LimitFloatPrecision <= 18
  3950. // For floating-point precision of 18:
  3951. //
  3952. // LogOfMantissa =
  3953. // -2.1072184f +
  3954. // (4.2372794f +
  3955. // (-3.7029485f +
  3956. // (2.2781945f +
  3957. // (-0.87823314f +
  3958. // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
  3959. //
  3960. // error 0.0000023660568, which is better than 18 bits
  3961. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  3962. getF32Constant(DAG, 0xbc91e5ac, dl));
  3963. SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
  3964. getF32Constant(DAG, 0x3e4350aa, dl));
  3965. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  3966. SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
  3967. getF32Constant(DAG, 0x3f60d3e3, dl));
  3968. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  3969. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  3970. getF32Constant(DAG, 0x4011cdf0, dl));
  3971. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  3972. SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
  3973. getF32Constant(DAG, 0x406cfd1c, dl));
  3974. SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
  3975. SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
  3976. getF32Constant(DAG, 0x408797cb, dl));
  3977. SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
  3978. LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
  3979. getF32Constant(DAG, 0x4006dcab, dl));
  3980. }
  3981. return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa);
  3982. }
  3983. // No special expansion.
  3984. return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op);
  3985. }
  3986. /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for
  3987. /// limited-precision mode.
  3988. static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
  3989. const TargetLowering &TLI) {
  3990. // TODO: What fast-math-flags should be set on the floating-point nodes?
  3991. if (Op.getValueType() == MVT::f32 &&
  3992. LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
  3993. SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
  3994. // Get the exponent.
  3995. SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
  3996. // Get the significand and build it into a floating-point number with
  3997. // exponent of 1.
  3998. SDValue X = GetSignificand(DAG, Op1, dl);
  3999. // Different possible minimax approximations of significand in
  4000. // floating-point for various degrees of accuracy over [1,2].
  4001. SDValue Log2ofMantissa;
  4002. if (LimitFloatPrecision <= 6) {
  4003. // For floating-point precision of 6:
  4004. //
  4005. // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
  4006. //
  4007. // error 0.0049451742, which is more than 7 bits
  4008. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  4009. getF32Constant(DAG, 0xbeb08fe0, dl));
  4010. SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
  4011. getF32Constant(DAG, 0x40019463, dl));
  4012. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  4013. Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
  4014. getF32Constant(DAG, 0x3fd6633d, dl));
  4015. } else if (LimitFloatPrecision <= 12) {
  4016. // For floating-point precision of 12:
  4017. //
  4018. // Log2ofMantissa =
  4019. // -2.51285454f +
  4020. // (4.07009056f +
  4021. // (-2.12067489f +
  4022. // (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
  4023. //
  4024. // error 0.0000876136000, which is better than 13 bits
  4025. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  4026. getF32Constant(DAG, 0xbda7262e, dl));
  4027. SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
  4028. getF32Constant(DAG, 0x3f25280b, dl));
  4029. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  4030. SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
  4031. getF32Constant(DAG, 0x4007b923, dl));
  4032. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  4033. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  4034. getF32Constant(DAG, 0x40823e2f, dl));
  4035. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  4036. Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
  4037. getF32Constant(DAG, 0x4020d29c, dl));
  4038. } else { // LimitFloatPrecision <= 18
  4039. // For floating-point precision of 18:
  4040. //
  4041. // Log2ofMantissa =
  4042. // -3.0400495f +
  4043. // (6.1129976f +
  4044. // (-5.3420409f +
  4045. // (3.2865683f +
  4046. // (-1.2669343f +
  4047. // (0.27515199f -
  4048. // 0.25691327e-1f * x) * x) * x) * x) * x) * x;
  4049. //
  4050. // error 0.0000018516, which is better than 18 bits
  4051. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  4052. getF32Constant(DAG, 0xbcd2769e, dl));
  4053. SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
  4054. getF32Constant(DAG, 0x3e8ce0b9, dl));
  4055. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  4056. SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
  4057. getF32Constant(DAG, 0x3fa22ae7, dl));
  4058. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  4059. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  4060. getF32Constant(DAG, 0x40525723, dl));
  4061. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  4062. SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
  4063. getF32Constant(DAG, 0x40aaf200, dl));
  4064. SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
  4065. SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
  4066. getF32Constant(DAG, 0x40c39dad, dl));
  4067. SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
  4068. Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
  4069. getF32Constant(DAG, 0x4042902c, dl));
  4070. }
  4071. return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa);
  4072. }
  4073. // No special expansion.
  4074. return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op);
  4075. }
  4076. /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for
  4077. /// limited-precision mode.
  4078. static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
  4079. const TargetLowering &TLI) {
  4080. // TODO: What fast-math-flags should be set on the floating-point nodes?
  4081. if (Op.getValueType() == MVT::f32 &&
  4082. LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
  4083. SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
  4084. // Scale the exponent by log10(2) [0.30102999f].
  4085. SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
  4086. SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
  4087. getF32Constant(DAG, 0x3e9a209a, dl));
  4088. // Get the significand and build it into a floating-point number with
  4089. // exponent of 1.
  4090. SDValue X = GetSignificand(DAG, Op1, dl);
  4091. SDValue Log10ofMantissa;
  4092. if (LimitFloatPrecision <= 6) {
  4093. // For floating-point precision of 6:
  4094. //
  4095. // Log10ofMantissa =
  4096. // -0.50419619f +
  4097. // (0.60948995f - 0.10380950f * x) * x;
  4098. //
  4099. // error 0.0014886165, which is 6 bits
  4100. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  4101. getF32Constant(DAG, 0xbdd49a13, dl));
  4102. SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
  4103. getF32Constant(DAG, 0x3f1c0789, dl));
  4104. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  4105. Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
  4106. getF32Constant(DAG, 0x3f011300, dl));
  4107. } else if (LimitFloatPrecision <= 12) {
  4108. // For floating-point precision of 12:
  4109. //
  4110. // Log10ofMantissa =
  4111. // -0.64831180f +
  4112. // (0.91751397f +
  4113. // (-0.31664806f + 0.47637168e-1f * x) * x) * x;
  4114. //
  4115. // error 0.00019228036, which is better than 12 bits
  4116. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  4117. getF32Constant(DAG, 0x3d431f31, dl));
  4118. SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
  4119. getF32Constant(DAG, 0x3ea21fb2, dl));
  4120. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  4121. SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
  4122. getF32Constant(DAG, 0x3f6ae232, dl));
  4123. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  4124. Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
  4125. getF32Constant(DAG, 0x3f25f7c3, dl));
  4126. } else { // LimitFloatPrecision <= 18
  4127. // For floating-point precision of 18:
  4128. //
  4129. // Log10ofMantissa =
  4130. // -0.84299375f +
  4131. // (1.5327582f +
  4132. // (-1.0688956f +
  4133. // (0.49102474f +
  4134. // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
  4135. //
  4136. // error 0.0000037995730, which is better than 18 bits
  4137. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  4138. getF32Constant(DAG, 0x3c5d51ce, dl));
  4139. SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
  4140. getF32Constant(DAG, 0x3e00685a, dl));
  4141. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  4142. SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
  4143. getF32Constant(DAG, 0x3efb6798, dl));
  4144. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  4145. SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
  4146. getF32Constant(DAG, 0x3f88d192, dl));
  4147. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  4148. SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
  4149. getF32Constant(DAG, 0x3fc4316c, dl));
  4150. SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
  4151. Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
  4152. getF32Constant(DAG, 0x3f57ce70, dl));
  4153. }
  4154. return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa);
  4155. }
  4156. // No special expansion.
  4157. return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op);
  4158. }
  4159. /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for
  4160. /// limited-precision mode.
  4161. static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
  4162. const TargetLowering &TLI) {
  4163. if (Op.getValueType() == MVT::f32 &&
  4164. LimitFloatPrecision > 0 && LimitFloatPrecision <= 18)
  4165. return getLimitedPrecisionExp2(Op, dl, DAG);
  4166. // No special expansion.
  4167. return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op);
  4168. }
  4169. /// visitPow - Lower a pow intrinsic. Handles the special sequences for
  4170. /// limited-precision mode with x == 10.0f.
  4171. static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS,
  4172. SelectionDAG &DAG, const TargetLowering &TLI) {
  4173. bool IsExp10 = false;
  4174. if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 &&
  4175. LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
  4176. if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) {
  4177. APFloat Ten(10.0f);
  4178. IsExp10 = LHSC->isExactlyValue(Ten);
  4179. }
  4180. }
  4181. // TODO: What fast-math-flags should be set on the FMUL node?
  4182. if (IsExp10) {
  4183. // Put the exponent in the right bit position for later addition to the
  4184. // final result:
  4185. //
  4186. // #define LOG2OF10 3.3219281f
  4187. // t0 = Op * LOG2OF10;
  4188. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS,
  4189. getF32Constant(DAG, 0x40549a78, dl));
  4190. return getLimitedPrecisionExp2(t0, dl, DAG);
  4191. }
  4192. // No special expansion.
  4193. return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS);
  4194. }
  4195. /// ExpandPowI - Expand a llvm.powi intrinsic.
  4196. static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS,
  4197. SelectionDAG &DAG) {
  4198. // If RHS is a constant, we can expand this out to a multiplication tree,
  4199. // otherwise we end up lowering to a call to __powidf2 (for example). When
  4200. // optimizing for size, we only want to do this if the expansion would produce
  4201. // a small number of multiplies, otherwise we do the full expansion.
  4202. if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
  4203. // Get the exponent as a positive value.
  4204. unsigned Val = RHSC->getSExtValue();
  4205. if ((int)Val < 0) Val = -Val;
  4206. // powi(x, 0) -> 1.0
  4207. if (Val == 0)
  4208. return DAG.getConstantFP(1.0, DL, LHS.getValueType());
  4209. const Function &F = DAG.getMachineFunction().getFunction();
  4210. if (!F.optForSize() ||
  4211. // If optimizing for size, don't insert too many multiplies.
  4212. // This inserts up to 5 multiplies.
  4213. countPopulation(Val) + Log2_32(Val) < 7) {
  4214. // We use the simple binary decomposition method to generate the multiply
  4215. // sequence. There are more optimal ways to do this (for example,
  4216. // powi(x,15) generates one more multiply than it should), but this has
  4217. // the benefit of being both really simple and much better than a libcall.
  4218. SDValue Res; // Logically starts equal to 1.0
  4219. SDValue CurSquare = LHS;
  4220. // TODO: Intrinsics should have fast-math-flags that propagate to these
  4221. // nodes.
  4222. while (Val) {
  4223. if (Val & 1) {
  4224. if (Res.getNode())
  4225. Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare);
  4226. else
  4227. Res = CurSquare; // 1.0*CurSquare.
  4228. }
  4229. CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(),
  4230. CurSquare, CurSquare);
  4231. Val >>= 1;
  4232. }
  4233. // If the original was negative, invert the result, producing 1/(x*x*x).
  4234. if (RHSC->getSExtValue() < 0)
  4235. Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(),
  4236. DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res);
  4237. return Res;
  4238. }
  4239. }
  4240. // Otherwise, expand to a libcall.
  4241. return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS);
  4242. }
  4243. // getUnderlyingArgReg - Find underlying register used for a truncated or
  4244. // bitcasted argument.
  4245. static unsigned getUnderlyingArgReg(const SDValue &N) {
  4246. switch (N.getOpcode()) {
  4247. case ISD::CopyFromReg:
  4248. return cast<RegisterSDNode>(N.getOperand(1))->getReg();
  4249. case ISD::BITCAST:
  4250. case ISD::AssertZext:
  4251. case ISD::AssertSext:
  4252. case ISD::TRUNCATE:
  4253. return getUnderlyingArgReg(N.getOperand(0));
  4254. default:
  4255. return 0;
  4256. }
  4257. }
  4258. /// If the DbgValueInst is a dbg_value of a function argument, create the
  4259. /// corresponding DBG_VALUE machine instruction for it now. At the end of
  4260. /// instruction selection, they will be inserted to the entry BB.
  4261. bool SelectionDAGBuilder::EmitFuncArgumentDbgValue(
  4262. const Value *V, DILocalVariable *Variable, DIExpression *Expr,
  4263. DILocation *DL, bool IsDbgDeclare, const SDValue &N) {
  4264. const Argument *Arg = dyn_cast<Argument>(V);
  4265. if (!Arg)
  4266. return false;
  4267. MachineFunction &MF = DAG.getMachineFunction();
  4268. const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
  4269. bool IsIndirect = false;
  4270. Optional<MachineOperand> Op;
  4271. // Some arguments' frame index is recorded during argument lowering.
  4272. int FI = FuncInfo.getArgumentFrameIndex(Arg);
  4273. if (FI != std::numeric_limits<int>::max())
  4274. Op = MachineOperand::CreateFI(FI);
  4275. if (!Op && N.getNode()) {
  4276. unsigned Reg = getUnderlyingArgReg(N);
  4277. if (Reg && TargetRegisterInfo::isVirtualRegister(Reg)) {
  4278. MachineRegisterInfo &RegInfo = MF.getRegInfo();
  4279. unsigned PR = RegInfo.getLiveInPhysReg(Reg);
  4280. if (PR)
  4281. Reg = PR;
  4282. }
  4283. if (Reg) {
  4284. Op = MachineOperand::CreateReg(Reg, false);
  4285. IsIndirect = IsDbgDeclare;
  4286. }
  4287. }
  4288. if (!Op && N.getNode())
  4289. // Check if frame index is available.
  4290. if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(N.getNode()))
  4291. if (FrameIndexSDNode *FINode =
  4292. dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
  4293. Op = MachineOperand::CreateFI(FINode->getIndex());
  4294. if (!Op) {
  4295. // Check if ValueMap has reg number.
  4296. DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
  4297. if (VMI != FuncInfo.ValueMap.end()) {
  4298. const auto &TLI = DAG.getTargetLoweringInfo();
  4299. RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second,
  4300. V->getType(), isABIRegCopy(V));
  4301. if (RFV.occupiesMultipleRegs()) {
  4302. unsigned Offset = 0;
  4303. for (auto RegAndSize : RFV.getRegsAndSizes()) {
  4304. Op = MachineOperand::CreateReg(RegAndSize.first, false);
  4305. auto FragmentExpr = DIExpression::createFragmentExpression(
  4306. Expr, Offset, RegAndSize.second);
  4307. if (!FragmentExpr)
  4308. continue;
  4309. FuncInfo.ArgDbgValues.push_back(
  4310. BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsDbgDeclare,
  4311. Op->getReg(), Variable, *FragmentExpr));
  4312. Offset += RegAndSize.second;
  4313. }
  4314. return true;
  4315. }
  4316. Op = MachineOperand::CreateReg(VMI->second, false);
  4317. IsIndirect = IsDbgDeclare;
  4318. }
  4319. }
  4320. if (!Op)
  4321. return false;
  4322. assert(Variable->isValidLocationForIntrinsic(DL) &&
  4323. "Expected inlined-at fields to agree");
  4324. if (Op->isReg())
  4325. FuncInfo.ArgDbgValues.push_back(
  4326. BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsIndirect,
  4327. Op->getReg(), Variable, Expr));
  4328. else
  4329. FuncInfo.ArgDbgValues.push_back(
  4330. BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE))
  4331. .add(*Op)
  4332. .addImm(0)
  4333. .addMetadata(Variable)
  4334. .addMetadata(Expr));
  4335. return true;
  4336. }
  4337. /// Return the appropriate SDDbgValue based on N.
  4338. SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N,
  4339. DILocalVariable *Variable,
  4340. DIExpression *Expr,
  4341. const DebugLoc &dl,
  4342. unsigned DbgSDNodeOrder) {
  4343. if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) {
  4344. // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe
  4345. // stack slot locations as such instead of as indirectly addressed
  4346. // locations.
  4347. return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(), dl,
  4348. DbgSDNodeOrder);
  4349. }
  4350. return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(), false, dl,
  4351. DbgSDNodeOrder);
  4352. }
  4353. // VisualStudio defines setjmp as _setjmp
  4354. #if defined(_MSC_VER) && defined(setjmp) && \
  4355. !defined(setjmp_undefined_for_msvc)
  4356. # pragma push_macro("setjmp")
  4357. # undef setjmp
  4358. # define setjmp_undefined_for_msvc
  4359. #endif
  4360. /// Lower the call to the specified intrinsic function. If we want to emit this
  4361. /// as a call to a named external function, return the name. Otherwise, lower it
  4362. /// and return null.
  4363. const char *
  4364. SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I, unsigned Intrinsic) {
  4365. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  4366. SDLoc sdl = getCurSDLoc();
  4367. DebugLoc dl = getCurDebugLoc();
  4368. SDValue Res;
  4369. switch (Intrinsic) {
  4370. default:
  4371. // By default, turn this into a target intrinsic node.
  4372. visitTargetIntrinsic(I, Intrinsic);
  4373. return nullptr;
  4374. case Intrinsic::vastart: visitVAStart(I); return nullptr;
  4375. case Intrinsic::vaend: visitVAEnd(I); return nullptr;
  4376. case Intrinsic::vacopy: visitVACopy(I); return nullptr;
  4377. case Intrinsic::returnaddress:
  4378. setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl,
  4379. TLI.getPointerTy(DAG.getDataLayout()),
  4380. getValue(I.getArgOperand(0))));
  4381. return nullptr;
  4382. case Intrinsic::addressofreturnaddress:
  4383. setValue(&I, DAG.getNode(ISD::ADDROFRETURNADDR, sdl,
  4384. TLI.getPointerTy(DAG.getDataLayout())));
  4385. return nullptr;
  4386. case Intrinsic::frameaddress:
  4387. setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl,
  4388. TLI.getPointerTy(DAG.getDataLayout()),
  4389. getValue(I.getArgOperand(0))));
  4390. return nullptr;
  4391. case Intrinsic::read_register: {
  4392. Value *Reg = I.getArgOperand(0);
  4393. SDValue Chain = getRoot();
  4394. SDValue RegName =
  4395. DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
  4396. EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  4397. Res = DAG.getNode(ISD::READ_REGISTER, sdl,
  4398. DAG.getVTList(VT, MVT::Other), Chain, RegName);
  4399. setValue(&I, Res);
  4400. DAG.setRoot(Res.getValue(1));
  4401. return nullptr;
  4402. }
  4403. case Intrinsic::write_register: {
  4404. Value *Reg = I.getArgOperand(0);
  4405. Value *RegValue = I.getArgOperand(1);
  4406. SDValue Chain = getRoot();
  4407. SDValue RegName =
  4408. DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
  4409. DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain,
  4410. RegName, getValue(RegValue)));
  4411. return nullptr;
  4412. }
  4413. case Intrinsic::setjmp:
  4414. return &"_setjmp"[!TLI.usesUnderscoreSetJmp()];
  4415. case Intrinsic::longjmp:
  4416. return &"_longjmp"[!TLI.usesUnderscoreLongJmp()];
  4417. case Intrinsic::memcpy: {
  4418. const auto &MCI = cast<MemCpyInst>(I);
  4419. SDValue Op1 = getValue(I.getArgOperand(0));
  4420. SDValue Op2 = getValue(I.getArgOperand(1));
  4421. SDValue Op3 = getValue(I.getArgOperand(2));
  4422. // @llvm.memcpy defines 0 and 1 to both mean no alignment.
  4423. unsigned DstAlign = std::max<unsigned>(MCI.getDestAlignment(), 1);
  4424. unsigned SrcAlign = std::max<unsigned>(MCI.getSourceAlignment(), 1);
  4425. unsigned Align = MinAlign(DstAlign, SrcAlign);
  4426. bool isVol = MCI.isVolatile();
  4427. bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
  4428. // FIXME: Support passing different dest/src alignments to the memcpy DAG
  4429. // node.
  4430. SDValue MC = DAG.getMemcpy(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
  4431. false, isTC,
  4432. MachinePointerInfo(I.getArgOperand(0)),
  4433. MachinePointerInfo(I.getArgOperand(1)));
  4434. updateDAGForMaybeTailCall(MC);
  4435. return nullptr;
  4436. }
  4437. case Intrinsic::memset: {
  4438. const auto &MSI = cast<MemSetInst>(I);
  4439. SDValue Op1 = getValue(I.getArgOperand(0));
  4440. SDValue Op2 = getValue(I.getArgOperand(1));
  4441. SDValue Op3 = getValue(I.getArgOperand(2));
  4442. // @llvm.memset defines 0 and 1 to both mean no alignment.
  4443. unsigned Align = std::max<unsigned>(MSI.getDestAlignment(), 1);
  4444. bool isVol = MSI.isVolatile();
  4445. bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
  4446. SDValue MS = DAG.getMemset(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
  4447. isTC, MachinePointerInfo(I.getArgOperand(0)));
  4448. updateDAGForMaybeTailCall(MS);
  4449. return nullptr;
  4450. }
  4451. case Intrinsic::memmove: {
  4452. const auto &MMI = cast<MemMoveInst>(I);
  4453. SDValue Op1 = getValue(I.getArgOperand(0));
  4454. SDValue Op2 = getValue(I.getArgOperand(1));
  4455. SDValue Op3 = getValue(I.getArgOperand(2));
  4456. // @llvm.memmove defines 0 and 1 to both mean no alignment.
  4457. unsigned DstAlign = std::max<unsigned>(MMI.getDestAlignment(), 1);
  4458. unsigned SrcAlign = std::max<unsigned>(MMI.getSourceAlignment(), 1);
  4459. unsigned Align = MinAlign(DstAlign, SrcAlign);
  4460. bool isVol = MMI.isVolatile();
  4461. bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
  4462. // FIXME: Support passing different dest/src alignments to the memmove DAG
  4463. // node.
  4464. SDValue MM = DAG.getMemmove(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
  4465. isTC, MachinePointerInfo(I.getArgOperand(0)),
  4466. MachinePointerInfo(I.getArgOperand(1)));
  4467. updateDAGForMaybeTailCall(MM);
  4468. return nullptr;
  4469. }
  4470. case Intrinsic::memcpy_element_unordered_atomic: {
  4471. const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I);
  4472. SDValue Dst = getValue(MI.getRawDest());
  4473. SDValue Src = getValue(MI.getRawSource());
  4474. SDValue Length = getValue(MI.getLength());
  4475. unsigned DstAlign = MI.getDestAlignment();
  4476. unsigned SrcAlign = MI.getSourceAlignment();
  4477. Type *LengthTy = MI.getLength()->getType();
  4478. unsigned ElemSz = MI.getElementSizeInBytes();
  4479. bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
  4480. SDValue MC = DAG.getAtomicMemcpy(getRoot(), sdl, Dst, DstAlign, Src,
  4481. SrcAlign, Length, LengthTy, ElemSz, isTC,
  4482. MachinePointerInfo(MI.getRawDest()),
  4483. MachinePointerInfo(MI.getRawSource()));
  4484. updateDAGForMaybeTailCall(MC);
  4485. return nullptr;
  4486. }
  4487. case Intrinsic::memmove_element_unordered_atomic: {
  4488. auto &MI = cast<AtomicMemMoveInst>(I);
  4489. SDValue Dst = getValue(MI.getRawDest());
  4490. SDValue Src = getValue(MI.getRawSource());
  4491. SDValue Length = getValue(MI.getLength());
  4492. unsigned DstAlign = MI.getDestAlignment();
  4493. unsigned SrcAlign = MI.getSourceAlignment();
  4494. Type *LengthTy = MI.getLength()->getType();
  4495. unsigned ElemSz = MI.getElementSizeInBytes();
  4496. bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
  4497. SDValue MC = DAG.getAtomicMemmove(getRoot(), sdl, Dst, DstAlign, Src,
  4498. SrcAlign, Length, LengthTy, ElemSz, isTC,
  4499. MachinePointerInfo(MI.getRawDest()),
  4500. MachinePointerInfo(MI.getRawSource()));
  4501. updateDAGForMaybeTailCall(MC);
  4502. return nullptr;
  4503. }
  4504. case Intrinsic::memset_element_unordered_atomic: {
  4505. auto &MI = cast<AtomicMemSetInst>(I);
  4506. SDValue Dst = getValue(MI.getRawDest());
  4507. SDValue Val = getValue(MI.getValue());
  4508. SDValue Length = getValue(MI.getLength());
  4509. unsigned DstAlign = MI.getDestAlignment();
  4510. Type *LengthTy = MI.getLength()->getType();
  4511. unsigned ElemSz = MI.getElementSizeInBytes();
  4512. bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
  4513. SDValue MC = DAG.getAtomicMemset(getRoot(), sdl, Dst, DstAlign, Val, Length,
  4514. LengthTy, ElemSz, isTC,
  4515. MachinePointerInfo(MI.getRawDest()));
  4516. updateDAGForMaybeTailCall(MC);
  4517. return nullptr;
  4518. }
  4519. case Intrinsic::dbg_addr:
  4520. case Intrinsic::dbg_declare: {
  4521. const DbgInfoIntrinsic &DI = cast<DbgInfoIntrinsic>(I);
  4522. DILocalVariable *Variable = DI.getVariable();
  4523. DIExpression *Expression = DI.getExpression();
  4524. dropDanglingDebugInfo(Variable, Expression);
  4525. assert(Variable && "Missing variable");
  4526. // Check if address has undef value.
  4527. const Value *Address = DI.getVariableLocation();
  4528. if (!Address || isa<UndefValue>(Address) ||
  4529. (Address->use_empty() && !isa<Argument>(Address))) {
  4530. DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
  4531. return nullptr;
  4532. }
  4533. bool isParameter = Variable->isParameter() || isa<Argument>(Address);
  4534. // Check if this variable can be described by a frame index, typically
  4535. // either as a static alloca or a byval parameter.
  4536. int FI = std::numeric_limits<int>::max();
  4537. if (const auto *AI =
  4538. dyn_cast<AllocaInst>(Address->stripInBoundsConstantOffsets())) {
  4539. if (AI->isStaticAlloca()) {
  4540. auto I = FuncInfo.StaticAllocaMap.find(AI);
  4541. if (I != FuncInfo.StaticAllocaMap.end())
  4542. FI = I->second;
  4543. }
  4544. } else if (const auto *Arg = dyn_cast<Argument>(
  4545. Address->stripInBoundsConstantOffsets())) {
  4546. FI = FuncInfo.getArgumentFrameIndex(Arg);
  4547. }
  4548. // llvm.dbg.addr is control dependent and always generates indirect
  4549. // DBG_VALUE instructions. llvm.dbg.declare is handled as a frame index in
  4550. // the MachineFunction variable table.
  4551. if (FI != std::numeric_limits<int>::max()) {
  4552. if (Intrinsic == Intrinsic::dbg_addr) {
  4553. SDDbgValue *SDV = DAG.getFrameIndexDbgValue(Variable, Expression,
  4554. FI, dl, SDNodeOrder);
  4555. DAG.AddDbgValue(SDV, getRoot().getNode(), isParameter);
  4556. }
  4557. return nullptr;
  4558. }
  4559. SDValue &N = NodeMap[Address];
  4560. if (!N.getNode() && isa<Argument>(Address))
  4561. // Check unused arguments map.
  4562. N = UnusedArgNodeMap[Address];
  4563. SDDbgValue *SDV;
  4564. if (N.getNode()) {
  4565. if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
  4566. Address = BCI->getOperand(0);
  4567. // Parameters are handled specially.
  4568. auto FINode = dyn_cast<FrameIndexSDNode>(N.getNode());
  4569. if (isParameter && FINode) {
  4570. // Byval parameter. We have a frame index at this point.
  4571. SDV = DAG.getFrameIndexDbgValue(Variable, Expression,
  4572. FINode->getIndex(), dl, SDNodeOrder);
  4573. } else if (isa<Argument>(Address)) {
  4574. // Address is an argument, so try to emit its dbg value using
  4575. // virtual register info from the FuncInfo.ValueMap.
  4576. EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, N);
  4577. return nullptr;
  4578. } else {
  4579. SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(),
  4580. true, dl, SDNodeOrder);
  4581. }
  4582. DAG.AddDbgValue(SDV, N.getNode(), isParameter);
  4583. } else {
  4584. // If Address is an argument then try to emit its dbg value using
  4585. // virtual register info from the FuncInfo.ValueMap.
  4586. if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true,
  4587. N)) {
  4588. DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
  4589. }
  4590. }
  4591. return nullptr;
  4592. }
  4593. case Intrinsic::dbg_label: {
  4594. const DbgLabelInst &DI = cast<DbgLabelInst>(I);
  4595. DILabel *Label = DI.getLabel();
  4596. assert(Label && "Missing label");
  4597. SDDbgLabel *SDV;
  4598. SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder);
  4599. DAG.AddDbgLabel(SDV);
  4600. return nullptr;
  4601. }
  4602. case Intrinsic::dbg_value: {
  4603. const DbgValueInst &DI = cast<DbgValueInst>(I);
  4604. assert(DI.getVariable() && "Missing variable");
  4605. DILocalVariable *Variable = DI.getVariable();
  4606. DIExpression *Expression = DI.getExpression();
  4607. dropDanglingDebugInfo(Variable, Expression);
  4608. const Value *V = DI.getValue();
  4609. if (!V)
  4610. return nullptr;
  4611. SDDbgValue *SDV;
  4612. if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V)) {
  4613. SDV = DAG.getConstantDbgValue(Variable, Expression, V, dl, SDNodeOrder);
  4614. DAG.AddDbgValue(SDV, nullptr, false);
  4615. return nullptr;
  4616. }
  4617. // Do not use getValue() in here; we don't want to generate code at
  4618. // this point if it hasn't been done yet.
  4619. SDValue N = NodeMap[V];
  4620. if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map.
  4621. N = UnusedArgNodeMap[V];
  4622. if (N.getNode()) {
  4623. if (EmitFuncArgumentDbgValue(V, Variable, Expression, dl, false, N))
  4624. return nullptr;
  4625. SDV = getDbgValue(N, Variable, Expression, dl, SDNodeOrder);
  4626. DAG.AddDbgValue(SDV, N.getNode(), false);
  4627. return nullptr;
  4628. }
  4629. // PHI nodes have already been selected, so we should know which VReg that
  4630. // is assigns to already.
  4631. if (isa<PHINode>(V)) {
  4632. auto VMI = FuncInfo.ValueMap.find(V);
  4633. if (VMI != FuncInfo.ValueMap.end()) {
  4634. unsigned Reg = VMI->second;
  4635. // The PHI node may be split up into several MI PHI nodes (in
  4636. // FunctionLoweringInfo::set).
  4637. RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg,
  4638. V->getType(), false);
  4639. if (RFV.occupiesMultipleRegs()) {
  4640. unsigned Offset = 0;
  4641. unsigned BitsToDescribe = 0;
  4642. if (auto VarSize = Variable->getSizeInBits())
  4643. BitsToDescribe = *VarSize;
  4644. if (auto Fragment = Expression->getFragmentInfo())
  4645. BitsToDescribe = Fragment->SizeInBits;
  4646. for (auto RegAndSize : RFV.getRegsAndSizes()) {
  4647. unsigned RegisterSize = RegAndSize.second;
  4648. // Bail out if all bits are described already.
  4649. if (Offset >= BitsToDescribe)
  4650. break;
  4651. unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe)
  4652. ? BitsToDescribe - Offset
  4653. : RegisterSize;
  4654. auto FragmentExpr = DIExpression::createFragmentExpression(
  4655. Expression, Offset, FragmentSize);
  4656. if (!FragmentExpr)
  4657. continue;
  4658. SDV = DAG.getVRegDbgValue(Variable, *FragmentExpr, RegAndSize.first,
  4659. false, dl, SDNodeOrder);
  4660. DAG.AddDbgValue(SDV, nullptr, false);
  4661. Offset += RegisterSize;
  4662. }
  4663. } else {
  4664. SDV = DAG.getVRegDbgValue(Variable, Expression, Reg, false, dl,
  4665. SDNodeOrder);
  4666. DAG.AddDbgValue(SDV, nullptr, false);
  4667. }
  4668. return nullptr;
  4669. }
  4670. }
  4671. // TODO: When we get here we will either drop the dbg.value completely, or
  4672. // we try to move it forward by letting it dangle for awhile. So we should
  4673. // probably add an extra DbgValue to the DAG here, with a reference to
  4674. // "noreg", to indicate that we have lost the debug location for the
  4675. // variable.
  4676. if (!V->use_empty() ) {
  4677. // Do not call getValue(V) yet, as we don't want to generate code.
  4678. // Remember it for later.
  4679. DanglingDebugInfo DDI(&DI, dl, SDNodeOrder);
  4680. DanglingDebugInfoMap[V].push_back(DDI);
  4681. return nullptr;
  4682. }
  4683. DEBUG(dbgs() << "Dropping debug location info for:\n " << DI << "\n");
  4684. DEBUG(dbgs() << " Last seen at:\n " << *V << "\n");
  4685. return nullptr;
  4686. }
  4687. case Intrinsic::eh_typeid_for: {
  4688. // Find the type id for the given typeinfo.
  4689. GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0));
  4690. unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV);
  4691. Res = DAG.getConstant(TypeID, sdl, MVT::i32);
  4692. setValue(&I, Res);
  4693. return nullptr;
  4694. }
  4695. case Intrinsic::eh_return_i32:
  4696. case Intrinsic::eh_return_i64:
  4697. DAG.getMachineFunction().setCallsEHReturn(true);
  4698. DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl,
  4699. MVT::Other,
  4700. getControlRoot(),
  4701. getValue(I.getArgOperand(0)),
  4702. getValue(I.getArgOperand(1))));
  4703. return nullptr;
  4704. case Intrinsic::eh_unwind_init:
  4705. DAG.getMachineFunction().setCallsUnwindInit(true);
  4706. return nullptr;
  4707. case Intrinsic::eh_dwarf_cfa:
  4708. setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl,
  4709. TLI.getPointerTy(DAG.getDataLayout()),
  4710. getValue(I.getArgOperand(0))));
  4711. return nullptr;
  4712. case Intrinsic::eh_sjlj_callsite: {
  4713. MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
  4714. ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0));
  4715. assert(CI && "Non-constant call site value in eh.sjlj.callsite!");
  4716. assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!");
  4717. MMI.setCurrentCallSite(CI->getZExtValue());
  4718. return nullptr;
  4719. }
  4720. case Intrinsic::eh_sjlj_functioncontext: {
  4721. // Get and store the index of the function context.
  4722. MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
  4723. AllocaInst *FnCtx =
  4724. cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts());
  4725. int FI = FuncInfo.StaticAllocaMap[FnCtx];
  4726. MFI.setFunctionContextIndex(FI);
  4727. return nullptr;
  4728. }
  4729. case Intrinsic::eh_sjlj_setjmp: {
  4730. SDValue Ops[2];
  4731. Ops[0] = getRoot();
  4732. Ops[1] = getValue(I.getArgOperand(0));
  4733. SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl,
  4734. DAG.getVTList(MVT::i32, MVT::Other), Ops);
  4735. setValue(&I, Op.getValue(0));
  4736. DAG.setRoot(Op.getValue(1));
  4737. return nullptr;
  4738. }
  4739. case Intrinsic::eh_sjlj_longjmp:
  4740. DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other,
  4741. getRoot(), getValue(I.getArgOperand(0))));
  4742. return nullptr;
  4743. case Intrinsic::eh_sjlj_setup_dispatch:
  4744. DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other,
  4745. getRoot()));
  4746. return nullptr;
  4747. case Intrinsic::masked_gather:
  4748. visitMaskedGather(I);
  4749. return nullptr;
  4750. case Intrinsic::masked_load:
  4751. visitMaskedLoad(I);
  4752. return nullptr;
  4753. case Intrinsic::masked_scatter:
  4754. visitMaskedScatter(I);
  4755. return nullptr;
  4756. case Intrinsic::masked_store:
  4757. visitMaskedStore(I);
  4758. return nullptr;
  4759. case Intrinsic::masked_expandload:
  4760. visitMaskedLoad(I, true /* IsExpanding */);
  4761. return nullptr;
  4762. case Intrinsic::masked_compressstore:
  4763. visitMaskedStore(I, true /* IsCompressing */);
  4764. return nullptr;
  4765. case Intrinsic::x86_mmx_pslli_w:
  4766. case Intrinsic::x86_mmx_pslli_d:
  4767. case Intrinsic::x86_mmx_pslli_q:
  4768. case Intrinsic::x86_mmx_psrli_w:
  4769. case Intrinsic::x86_mmx_psrli_d:
  4770. case Intrinsic::x86_mmx_psrli_q:
  4771. case Intrinsic::x86_mmx_psrai_w:
  4772. case Intrinsic::x86_mmx_psrai_d: {
  4773. SDValue ShAmt = getValue(I.getArgOperand(1));
  4774. if (isa<ConstantSDNode>(ShAmt)) {
  4775. visitTargetIntrinsic(I, Intrinsic);
  4776. return nullptr;
  4777. }
  4778. unsigned NewIntrinsic = 0;
  4779. EVT ShAmtVT = MVT::v2i32;
  4780. switch (Intrinsic) {
  4781. case Intrinsic::x86_mmx_pslli_w:
  4782. NewIntrinsic = Intrinsic::x86_mmx_psll_w;
  4783. break;
  4784. case Intrinsic::x86_mmx_pslli_d:
  4785. NewIntrinsic = Intrinsic::x86_mmx_psll_d;
  4786. break;
  4787. case Intrinsic::x86_mmx_pslli_q:
  4788. NewIntrinsic = Intrinsic::x86_mmx_psll_q;
  4789. break;
  4790. case Intrinsic::x86_mmx_psrli_w:
  4791. NewIntrinsic = Intrinsic::x86_mmx_psrl_w;
  4792. break;
  4793. case Intrinsic::x86_mmx_psrli_d:
  4794. NewIntrinsic = Intrinsic::x86_mmx_psrl_d;
  4795. break;
  4796. case Intrinsic::x86_mmx_psrli_q:
  4797. NewIntrinsic = Intrinsic::x86_mmx_psrl_q;
  4798. break;
  4799. case Intrinsic::x86_mmx_psrai_w:
  4800. NewIntrinsic = Intrinsic::x86_mmx_psra_w;
  4801. break;
  4802. case Intrinsic::x86_mmx_psrai_d:
  4803. NewIntrinsic = Intrinsic::x86_mmx_psra_d;
  4804. break;
  4805. default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
  4806. }
  4807. // The vector shift intrinsics with scalars uses 32b shift amounts but
  4808. // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
  4809. // to be zero.
  4810. // We must do this early because v2i32 is not a legal type.
  4811. SDValue ShOps[2];
  4812. ShOps[0] = ShAmt;
  4813. ShOps[1] = DAG.getConstant(0, sdl, MVT::i32);
  4814. ShAmt = DAG.getBuildVector(ShAmtVT, sdl, ShOps);
  4815. EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  4816. ShAmt = DAG.getNode(ISD::BITCAST, sdl, DestVT, ShAmt);
  4817. Res = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, sdl, DestVT,
  4818. DAG.getConstant(NewIntrinsic, sdl, MVT::i32),
  4819. getValue(I.getArgOperand(0)), ShAmt);
  4820. setValue(&I, Res);
  4821. return nullptr;
  4822. }
  4823. case Intrinsic::powi:
  4824. setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)),
  4825. getValue(I.getArgOperand(1)), DAG));
  4826. return nullptr;
  4827. case Intrinsic::log:
  4828. setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
  4829. return nullptr;
  4830. case Intrinsic::log2:
  4831. setValue(&I, expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
  4832. return nullptr;
  4833. case Intrinsic::log10:
  4834. setValue(&I, expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
  4835. return nullptr;
  4836. case Intrinsic::exp:
  4837. setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
  4838. return nullptr;
  4839. case Intrinsic::exp2:
  4840. setValue(&I, expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
  4841. return nullptr;
  4842. case Intrinsic::pow:
  4843. setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)),
  4844. getValue(I.getArgOperand(1)), DAG, TLI));
  4845. return nullptr;
  4846. case Intrinsic::sqrt:
  4847. case Intrinsic::fabs:
  4848. case Intrinsic::sin:
  4849. case Intrinsic::cos:
  4850. case Intrinsic::floor:
  4851. case Intrinsic::ceil:
  4852. case Intrinsic::trunc:
  4853. case Intrinsic::rint:
  4854. case Intrinsic::nearbyint:
  4855. case Intrinsic::round:
  4856. case Intrinsic::canonicalize: {
  4857. unsigned Opcode;
  4858. switch (Intrinsic) {
  4859. default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
  4860. case Intrinsic::sqrt: Opcode = ISD::FSQRT; break;
  4861. case Intrinsic::fabs: Opcode = ISD::FABS; break;
  4862. case Intrinsic::sin: Opcode = ISD::FSIN; break;
  4863. case Intrinsic::cos: Opcode = ISD::FCOS; break;
  4864. case Intrinsic::floor: Opcode = ISD::FFLOOR; break;
  4865. case Intrinsic::ceil: Opcode = ISD::FCEIL; break;
  4866. case Intrinsic::trunc: Opcode = ISD::FTRUNC; break;
  4867. case Intrinsic::rint: Opcode = ISD::FRINT; break;
  4868. case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break;
  4869. case Intrinsic::round: Opcode = ISD::FROUND; break;
  4870. case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break;
  4871. }
  4872. setValue(&I, DAG.getNode(Opcode, sdl,
  4873. getValue(I.getArgOperand(0)).getValueType(),
  4874. getValue(I.getArgOperand(0))));
  4875. return nullptr;
  4876. }
  4877. case Intrinsic::minnum: {
  4878. auto VT = getValue(I.getArgOperand(0)).getValueType();
  4879. unsigned Opc =
  4880. I.hasNoNaNs() && TLI.isOperationLegalOrCustom(ISD::FMINNAN, VT)
  4881. ? ISD::FMINNAN
  4882. : ISD::FMINNUM;
  4883. setValue(&I, DAG.getNode(Opc, sdl, VT,
  4884. getValue(I.getArgOperand(0)),
  4885. getValue(I.getArgOperand(1))));
  4886. return nullptr;
  4887. }
  4888. case Intrinsic::maxnum: {
  4889. auto VT = getValue(I.getArgOperand(0)).getValueType();
  4890. unsigned Opc =
  4891. I.hasNoNaNs() && TLI.isOperationLegalOrCustom(ISD::FMAXNAN, VT)
  4892. ? ISD::FMAXNAN
  4893. : ISD::FMAXNUM;
  4894. setValue(&I, DAG.getNode(Opc, sdl, VT,
  4895. getValue(I.getArgOperand(0)),
  4896. getValue(I.getArgOperand(1))));
  4897. return nullptr;
  4898. }
  4899. case Intrinsic::copysign:
  4900. setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl,
  4901. getValue(I.getArgOperand(0)).getValueType(),
  4902. getValue(I.getArgOperand(0)),
  4903. getValue(I.getArgOperand(1))));
  4904. return nullptr;
  4905. case Intrinsic::fma:
  4906. setValue(&I, DAG.getNode(ISD::FMA, sdl,
  4907. getValue(I.getArgOperand(0)).getValueType(),
  4908. getValue(I.getArgOperand(0)),
  4909. getValue(I.getArgOperand(1)),
  4910. getValue(I.getArgOperand(2))));
  4911. return nullptr;
  4912. case Intrinsic::experimental_constrained_fadd:
  4913. case Intrinsic::experimental_constrained_fsub:
  4914. case Intrinsic::experimental_constrained_fmul:
  4915. case Intrinsic::experimental_constrained_fdiv:
  4916. case Intrinsic::experimental_constrained_frem:
  4917. case Intrinsic::experimental_constrained_fma:
  4918. case Intrinsic::experimental_constrained_sqrt:
  4919. case Intrinsic::experimental_constrained_pow:
  4920. case Intrinsic::experimental_constrained_powi:
  4921. case Intrinsic::experimental_constrained_sin:
  4922. case Intrinsic::experimental_constrained_cos:
  4923. case Intrinsic::experimental_constrained_exp:
  4924. case Intrinsic::experimental_constrained_exp2:
  4925. case Intrinsic::experimental_constrained_log:
  4926. case Intrinsic::experimental_constrained_log10:
  4927. case Intrinsic::experimental_constrained_log2:
  4928. case Intrinsic::experimental_constrained_rint:
  4929. case Intrinsic::experimental_constrained_nearbyint:
  4930. visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I));
  4931. return nullptr;
  4932. case Intrinsic::fmuladd: {
  4933. EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  4934. if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
  4935. TLI.isFMAFasterThanFMulAndFAdd(VT)) {
  4936. setValue(&I, DAG.getNode(ISD::FMA, sdl,
  4937. getValue(I.getArgOperand(0)).getValueType(),
  4938. getValue(I.getArgOperand(0)),
  4939. getValue(I.getArgOperand(1)),
  4940. getValue(I.getArgOperand(2))));
  4941. } else {
  4942. // TODO: Intrinsic calls should have fast-math-flags.
  4943. SDValue Mul = DAG.getNode(ISD::FMUL, sdl,
  4944. getValue(I.getArgOperand(0)).getValueType(),
  4945. getValue(I.getArgOperand(0)),
  4946. getValue(I.getArgOperand(1)));
  4947. SDValue Add = DAG.getNode(ISD::FADD, sdl,
  4948. getValue(I.getArgOperand(0)).getValueType(),
  4949. Mul,
  4950. getValue(I.getArgOperand(2)));
  4951. setValue(&I, Add);
  4952. }
  4953. return nullptr;
  4954. }
  4955. case Intrinsic::convert_to_fp16:
  4956. setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16,
  4957. DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16,
  4958. getValue(I.getArgOperand(0)),
  4959. DAG.getTargetConstant(0, sdl,
  4960. MVT::i32))));
  4961. return nullptr;
  4962. case Intrinsic::convert_from_fp16:
  4963. setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl,
  4964. TLI.getValueType(DAG.getDataLayout(), I.getType()),
  4965. DAG.getNode(ISD::BITCAST, sdl, MVT::f16,
  4966. getValue(I.getArgOperand(0)))));
  4967. return nullptr;
  4968. case Intrinsic::pcmarker: {
  4969. SDValue Tmp = getValue(I.getArgOperand(0));
  4970. DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp));
  4971. return nullptr;
  4972. }
  4973. case Intrinsic::readcyclecounter: {
  4974. SDValue Op = getRoot();
  4975. Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl,
  4976. DAG.getVTList(MVT::i64, MVT::Other), Op);
  4977. setValue(&I, Res);
  4978. DAG.setRoot(Res.getValue(1));
  4979. return nullptr;
  4980. }
  4981. case Intrinsic::bitreverse:
  4982. setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl,
  4983. getValue(I.getArgOperand(0)).getValueType(),
  4984. getValue(I.getArgOperand(0))));
  4985. return nullptr;
  4986. case Intrinsic::bswap:
  4987. setValue(&I, DAG.getNode(ISD::BSWAP, sdl,
  4988. getValue(I.getArgOperand(0)).getValueType(),
  4989. getValue(I.getArgOperand(0))));
  4990. return nullptr;
  4991. case Intrinsic::cttz: {
  4992. SDValue Arg = getValue(I.getArgOperand(0));
  4993. ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
  4994. EVT Ty = Arg.getValueType();
  4995. setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF,
  4996. sdl, Ty, Arg));
  4997. return nullptr;
  4998. }
  4999. case Intrinsic::ctlz: {
  5000. SDValue Arg = getValue(I.getArgOperand(0));
  5001. ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
  5002. EVT Ty = Arg.getValueType();
  5003. setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF,
  5004. sdl, Ty, Arg));
  5005. return nullptr;
  5006. }
  5007. case Intrinsic::ctpop: {
  5008. SDValue Arg = getValue(I.getArgOperand(0));
  5009. EVT Ty = Arg.getValueType();
  5010. setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg));
  5011. return nullptr;
  5012. }
  5013. case Intrinsic::stacksave: {
  5014. SDValue Op = getRoot();
  5015. Res = DAG.getNode(
  5016. ISD::STACKSAVE, sdl,
  5017. DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Op);
  5018. setValue(&I, Res);
  5019. DAG.setRoot(Res.getValue(1));
  5020. return nullptr;
  5021. }
  5022. case Intrinsic::stackrestore:
  5023. Res = getValue(I.getArgOperand(0));
  5024. DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res));
  5025. return nullptr;
  5026. case Intrinsic::get_dynamic_area_offset: {
  5027. SDValue Op = getRoot();
  5028. EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
  5029. EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
  5030. // Result type for @llvm.get.dynamic.area.offset should match PtrTy for
  5031. // target.
  5032. if (PtrTy != ResTy)
  5033. report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset"
  5034. " intrinsic!");
  5035. Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy),
  5036. Op);
  5037. DAG.setRoot(Op);
  5038. setValue(&I, Res);
  5039. return nullptr;
  5040. }
  5041. case Intrinsic::stackguard: {
  5042. EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
  5043. MachineFunction &MF = DAG.getMachineFunction();
  5044. const Module &M = *MF.getFunction().getParent();
  5045. SDValue Chain = getRoot();
  5046. if (TLI.useLoadStackGuardNode()) {
  5047. Res = getLoadStackGuard(DAG, sdl, Chain);
  5048. } else {
  5049. const Value *Global = TLI.getSDagStackGuard(M);
  5050. unsigned Align = DL->getPrefTypeAlignment(Global->getType());
  5051. Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global),
  5052. MachinePointerInfo(Global, 0), Align,
  5053. MachineMemOperand::MOVolatile);
  5054. }
  5055. if (TLI.useStackGuardXorFP())
  5056. Res = TLI.emitStackGuardXorFP(DAG, Res, sdl);
  5057. DAG.setRoot(Chain);
  5058. setValue(&I, Res);
  5059. return nullptr;
  5060. }
  5061. case Intrinsic::stackprotector: {
  5062. // Emit code into the DAG to store the stack guard onto the stack.
  5063. MachineFunction &MF = DAG.getMachineFunction();
  5064. MachineFrameInfo &MFI = MF.getFrameInfo();
  5065. EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
  5066. SDValue Src, Chain = getRoot();
  5067. if (TLI.useLoadStackGuardNode())
  5068. Src = getLoadStackGuard(DAG, sdl, Chain);
  5069. else
  5070. Src = getValue(I.getArgOperand(0)); // The guard's value.
  5071. AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
  5072. int FI = FuncInfo.StaticAllocaMap[Slot];
  5073. MFI.setStackProtectorIndex(FI);
  5074. SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
  5075. // Store the stack protector onto the stack.
  5076. Res = DAG.getStore(Chain, sdl, Src, FIN, MachinePointerInfo::getFixedStack(
  5077. DAG.getMachineFunction(), FI),
  5078. /* Alignment = */ 0, MachineMemOperand::MOVolatile);
  5079. setValue(&I, Res);
  5080. DAG.setRoot(Res);
  5081. return nullptr;
  5082. }
  5083. case Intrinsic::objectsize: {
  5084. // If we don't know by now, we're never going to know.
  5085. ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(1));
  5086. assert(CI && "Non-constant type in __builtin_object_size?");
  5087. SDValue Arg = getValue(I.getCalledValue());
  5088. EVT Ty = Arg.getValueType();
  5089. if (CI->isZero())
  5090. Res = DAG.getConstant(-1ULL, sdl, Ty);
  5091. else
  5092. Res = DAG.getConstant(0, sdl, Ty);
  5093. setValue(&I, Res);
  5094. return nullptr;
  5095. }
  5096. case Intrinsic::annotation:
  5097. case Intrinsic::ptr_annotation:
  5098. case Intrinsic::launder_invariant_group:
  5099. // Drop the intrinsic, but forward the value
  5100. setValue(&I, getValue(I.getOperand(0)));
  5101. return nullptr;
  5102. case Intrinsic::assume:
  5103. case Intrinsic::var_annotation:
  5104. case Intrinsic::sideeffect:
  5105. // Discard annotate attributes, assumptions, and artificial side-effects.
  5106. return nullptr;
  5107. case Intrinsic::codeview_annotation: {
  5108. // Emit a label associated with this metadata.
  5109. MachineFunction &MF = DAG.getMachineFunction();
  5110. MCSymbol *Label =
  5111. MF.getMMI().getContext().createTempSymbol("annotation", true);
  5112. Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata();
  5113. MF.addCodeViewAnnotation(Label, cast<MDNode>(MD));
  5114. Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label);
  5115. DAG.setRoot(Res);
  5116. return nullptr;
  5117. }
  5118. case Intrinsic::init_trampoline: {
  5119. const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts());
  5120. SDValue Ops[6];
  5121. Ops[0] = getRoot();
  5122. Ops[1] = getValue(I.getArgOperand(0));
  5123. Ops[2] = getValue(I.getArgOperand(1));
  5124. Ops[3] = getValue(I.getArgOperand(2));
  5125. Ops[4] = DAG.getSrcValue(I.getArgOperand(0));
  5126. Ops[5] = DAG.getSrcValue(F);
  5127. Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops);
  5128. DAG.setRoot(Res);
  5129. return nullptr;
  5130. }
  5131. case Intrinsic::adjust_trampoline:
  5132. setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl,
  5133. TLI.getPointerTy(DAG.getDataLayout()),
  5134. getValue(I.getArgOperand(0))));
  5135. return nullptr;
  5136. case Intrinsic::gcroot: {
  5137. assert(DAG.getMachineFunction().getFunction().hasGC() &&
  5138. "only valid in functions with gc specified, enforced by Verifier");
  5139. assert(GFI && "implied by previous");
  5140. const Value *Alloca = I.getArgOperand(0)->stripPointerCasts();
  5141. const Constant *TypeMap = cast<Constant>(I.getArgOperand(1));
  5142. FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
  5143. GFI->addStackRoot(FI->getIndex(), TypeMap);
  5144. return nullptr;
  5145. }
  5146. case Intrinsic::gcread:
  5147. case Intrinsic::gcwrite:
  5148. llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
  5149. case Intrinsic::flt_rounds:
  5150. setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, sdl, MVT::i32));
  5151. return nullptr;
  5152. case Intrinsic::expect:
  5153. // Just replace __builtin_expect(exp, c) with EXP.
  5154. setValue(&I, getValue(I.getArgOperand(0)));
  5155. return nullptr;
  5156. case Intrinsic::debugtrap:
  5157. case Intrinsic::trap: {
  5158. StringRef TrapFuncName =
  5159. I.getAttributes()
  5160. .getAttribute(AttributeList::FunctionIndex, "trap-func-name")
  5161. .getValueAsString();
  5162. if (TrapFuncName.empty()) {
  5163. ISD::NodeType Op = (Intrinsic == Intrinsic::trap) ?
  5164. ISD::TRAP : ISD::DEBUGTRAP;
  5165. DAG.setRoot(DAG.getNode(Op, sdl,MVT::Other, getRoot()));
  5166. return nullptr;
  5167. }
  5168. TargetLowering::ArgListTy Args;
  5169. TargetLowering::CallLoweringInfo CLI(DAG);
  5170. CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee(
  5171. CallingConv::C, I.getType(),
  5172. DAG.getExternalSymbol(TrapFuncName.data(),
  5173. TLI.getPointerTy(DAG.getDataLayout())),
  5174. std::move(Args));
  5175. std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
  5176. DAG.setRoot(Result.second);
  5177. return nullptr;
  5178. }
  5179. case Intrinsic::uadd_with_overflow:
  5180. case Intrinsic::sadd_with_overflow:
  5181. case Intrinsic::usub_with_overflow:
  5182. case Intrinsic::ssub_with_overflow:
  5183. case Intrinsic::umul_with_overflow:
  5184. case Intrinsic::smul_with_overflow: {
  5185. ISD::NodeType Op;
  5186. switch (Intrinsic) {
  5187. default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
  5188. case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break;
  5189. case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break;
  5190. case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break;
  5191. case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break;
  5192. case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break;
  5193. case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break;
  5194. }
  5195. SDValue Op1 = getValue(I.getArgOperand(0));
  5196. SDValue Op2 = getValue(I.getArgOperand(1));
  5197. SDVTList VTs = DAG.getVTList(Op1.getValueType(), MVT::i1);
  5198. setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2));
  5199. return nullptr;
  5200. }
  5201. case Intrinsic::prefetch: {
  5202. SDValue Ops[5];
  5203. unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
  5204. auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore;
  5205. Ops[0] = DAG.getRoot();
  5206. Ops[1] = getValue(I.getArgOperand(0));
  5207. Ops[2] = getValue(I.getArgOperand(1));
  5208. Ops[3] = getValue(I.getArgOperand(2));
  5209. Ops[4] = getValue(I.getArgOperand(3));
  5210. SDValue Result = DAG.getMemIntrinsicNode(ISD::PREFETCH, sdl,
  5211. DAG.getVTList(MVT::Other), Ops,
  5212. EVT::getIntegerVT(*Context, 8),
  5213. MachinePointerInfo(I.getArgOperand(0)),
  5214. 0, /* align */
  5215. Flags);
  5216. // Chain the prefetch in parallell with any pending loads, to stay out of
  5217. // the way of later optimizations.
  5218. PendingLoads.push_back(Result);
  5219. Result = getRoot();
  5220. DAG.setRoot(Result);
  5221. return nullptr;
  5222. }
  5223. case Intrinsic::lifetime_start:
  5224. case Intrinsic::lifetime_end: {
  5225. bool IsStart = (Intrinsic == Intrinsic::lifetime_start);
  5226. // Stack coloring is not enabled in O0, discard region information.
  5227. if (TM.getOptLevel() == CodeGenOpt::None)
  5228. return nullptr;
  5229. SmallVector<Value *, 4> Allocas;
  5230. GetUnderlyingObjects(I.getArgOperand(1), Allocas, *DL);
  5231. for (SmallVectorImpl<Value*>::iterator Object = Allocas.begin(),
  5232. E = Allocas.end(); Object != E; ++Object) {
  5233. AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(*Object);
  5234. // Could not find an Alloca.
  5235. if (!LifetimeObject)
  5236. continue;
  5237. // First check that the Alloca is static, otherwise it won't have a
  5238. // valid frame index.
  5239. auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject);
  5240. if (SI == FuncInfo.StaticAllocaMap.end())
  5241. return nullptr;
  5242. int FI = SI->second;
  5243. SDValue Ops[2];
  5244. Ops[0] = getRoot();
  5245. Ops[1] =
  5246. DAG.getFrameIndex(FI, TLI.getFrameIndexTy(DAG.getDataLayout()), true);
  5247. unsigned Opcode = (IsStart ? ISD::LIFETIME_START : ISD::LIFETIME_END);
  5248. Res = DAG.getNode(Opcode, sdl, MVT::Other, Ops);
  5249. DAG.setRoot(Res);
  5250. }
  5251. return nullptr;
  5252. }
  5253. case Intrinsic::invariant_start:
  5254. // Discard region information.
  5255. setValue(&I, DAG.getUNDEF(TLI.getPointerTy(DAG.getDataLayout())));
  5256. return nullptr;
  5257. case Intrinsic::invariant_end:
  5258. // Discard region information.
  5259. return nullptr;
  5260. case Intrinsic::clear_cache:
  5261. return TLI.getClearCacheBuiltinName();
  5262. case Intrinsic::donothing:
  5263. // ignore
  5264. return nullptr;
  5265. case Intrinsic::experimental_stackmap:
  5266. visitStackmap(I);
  5267. return nullptr;
  5268. case Intrinsic::experimental_patchpoint_void:
  5269. case Intrinsic::experimental_patchpoint_i64:
  5270. visitPatchpoint(&I);
  5271. return nullptr;
  5272. case Intrinsic::experimental_gc_statepoint:
  5273. LowerStatepoint(ImmutableStatepoint(&I));
  5274. return nullptr;
  5275. case Intrinsic::experimental_gc_result:
  5276. visitGCResult(cast<GCResultInst>(I));
  5277. return nullptr;
  5278. case Intrinsic::experimental_gc_relocate:
  5279. visitGCRelocate(cast<GCRelocateInst>(I));
  5280. return nullptr;
  5281. case Intrinsic::instrprof_increment:
  5282. llvm_unreachable("instrprof failed to lower an increment");
  5283. case Intrinsic::instrprof_value_profile:
  5284. llvm_unreachable("instrprof failed to lower a value profiling call");
  5285. case Intrinsic::localescape: {
  5286. MachineFunction &MF = DAG.getMachineFunction();
  5287. const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
  5288. // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission
  5289. // is the same on all targets.
  5290. for (unsigned Idx = 0, E = I.getNumArgOperands(); Idx < E; ++Idx) {
  5291. Value *Arg = I.getArgOperand(Idx)->stripPointerCasts();
  5292. if (isa<ConstantPointerNull>(Arg))
  5293. continue; // Skip null pointers. They represent a hole in index space.
  5294. AllocaInst *Slot = cast<AllocaInst>(Arg);
  5295. assert(FuncInfo.StaticAllocaMap.count(Slot) &&
  5296. "can only escape static allocas");
  5297. int FI = FuncInfo.StaticAllocaMap[Slot];
  5298. MCSymbol *FrameAllocSym =
  5299. MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
  5300. GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx);
  5301. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl,
  5302. TII->get(TargetOpcode::LOCAL_ESCAPE))
  5303. .addSym(FrameAllocSym)
  5304. .addFrameIndex(FI);
  5305. }
  5306. return nullptr;
  5307. }
  5308. case Intrinsic::localrecover: {
  5309. // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx)
  5310. MachineFunction &MF = DAG.getMachineFunction();
  5311. MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout(), 0);
  5312. // Get the symbol that defines the frame offset.
  5313. auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts());
  5314. auto *Idx = cast<ConstantInt>(I.getArgOperand(2));
  5315. unsigned IdxVal =
  5316. unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max()));
  5317. MCSymbol *FrameAllocSym =
  5318. MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
  5319. GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal);
  5320. // Create a MCSymbol for the label to avoid any target lowering
  5321. // that would make this PC relative.
  5322. SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT);
  5323. SDValue OffsetVal =
  5324. DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym);
  5325. // Add the offset to the FP.
  5326. Value *FP = I.getArgOperand(1);
  5327. SDValue FPVal = getValue(FP);
  5328. SDValue Add = DAG.getNode(ISD::ADD, sdl, PtrVT, FPVal, OffsetVal);
  5329. setValue(&I, Add);
  5330. return nullptr;
  5331. }
  5332. case Intrinsic::eh_exceptionpointer:
  5333. case Intrinsic::eh_exceptioncode: {
  5334. // Get the exception pointer vreg, copy from it, and resize it to fit.
  5335. const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0));
  5336. MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
  5337. const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT);
  5338. unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC);
  5339. SDValue N =
  5340. DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), VReg, PtrVT);
  5341. if (Intrinsic == Intrinsic::eh_exceptioncode)
  5342. N = DAG.getZExtOrTrunc(N, getCurSDLoc(), MVT::i32);
  5343. setValue(&I, N);
  5344. return nullptr;
  5345. }
  5346. case Intrinsic::xray_customevent: {
  5347. // Here we want to make sure that the intrinsic behaves as if it has a
  5348. // specific calling convention, and only for x86_64.
  5349. // FIXME: Support other platforms later.
  5350. const auto &Triple = DAG.getTarget().getTargetTriple();
  5351. if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux())
  5352. return nullptr;
  5353. SDLoc DL = getCurSDLoc();
  5354. SmallVector<SDValue, 8> Ops;
  5355. // We want to say that we always want the arguments in registers.
  5356. SDValue LogEntryVal = getValue(I.getArgOperand(0));
  5357. SDValue StrSizeVal = getValue(I.getArgOperand(1));
  5358. SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
  5359. SDValue Chain = getRoot();
  5360. Ops.push_back(LogEntryVal);
  5361. Ops.push_back(StrSizeVal);
  5362. Ops.push_back(Chain);
  5363. // We need to enforce the calling convention for the callsite, so that
  5364. // argument ordering is enforced correctly, and that register allocation can
  5365. // see that some registers may be assumed clobbered and have to preserve
  5366. // them across calls to the intrinsic.
  5367. MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL,
  5368. DL, NodeTys, Ops);
  5369. SDValue patchableNode = SDValue(MN, 0);
  5370. DAG.setRoot(patchableNode);
  5371. setValue(&I, patchableNode);
  5372. return nullptr;
  5373. }
  5374. case Intrinsic::xray_typedevent: {
  5375. // Here we want to make sure that the intrinsic behaves as if it has a
  5376. // specific calling convention, and only for x86_64.
  5377. // FIXME: Support other platforms later.
  5378. const auto &Triple = DAG.getTarget().getTargetTriple();
  5379. if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux())
  5380. return nullptr;
  5381. SDLoc DL = getCurSDLoc();
  5382. SmallVector<SDValue, 8> Ops;
  5383. // We want to say that we always want the arguments in registers.
  5384. // It's unclear to me how manipulating the selection DAG here forces callers
  5385. // to provide arguments in registers instead of on the stack.
  5386. SDValue LogTypeId = getValue(I.getArgOperand(0));
  5387. SDValue LogEntryVal = getValue(I.getArgOperand(1));
  5388. SDValue StrSizeVal = getValue(I.getArgOperand(2));
  5389. SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
  5390. SDValue Chain = getRoot();
  5391. Ops.push_back(LogTypeId);
  5392. Ops.push_back(LogEntryVal);
  5393. Ops.push_back(StrSizeVal);
  5394. Ops.push_back(Chain);
  5395. // We need to enforce the calling convention for the callsite, so that
  5396. // argument ordering is enforced correctly, and that register allocation can
  5397. // see that some registers may be assumed clobbered and have to preserve
  5398. // them across calls to the intrinsic.
  5399. MachineSDNode *MN = DAG.getMachineNode(
  5400. TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, DL, NodeTys, Ops);
  5401. SDValue patchableNode = SDValue(MN, 0);
  5402. DAG.setRoot(patchableNode);
  5403. setValue(&I, patchableNode);
  5404. return nullptr;
  5405. }
  5406. case Intrinsic::experimental_deoptimize:
  5407. LowerDeoptimizeCall(&I);
  5408. return nullptr;
  5409. case Intrinsic::experimental_vector_reduce_fadd:
  5410. case Intrinsic::experimental_vector_reduce_fmul:
  5411. case Intrinsic::experimental_vector_reduce_add:
  5412. case Intrinsic::experimental_vector_reduce_mul:
  5413. case Intrinsic::experimental_vector_reduce_and:
  5414. case Intrinsic::experimental_vector_reduce_or:
  5415. case Intrinsic::experimental_vector_reduce_xor:
  5416. case Intrinsic::experimental_vector_reduce_smax:
  5417. case Intrinsic::experimental_vector_reduce_smin:
  5418. case Intrinsic::experimental_vector_reduce_umax:
  5419. case Intrinsic::experimental_vector_reduce_umin:
  5420. case Intrinsic::experimental_vector_reduce_fmax:
  5421. case Intrinsic::experimental_vector_reduce_fmin:
  5422. visitVectorReduce(I, Intrinsic);
  5423. return nullptr;
  5424. case Intrinsic::icall_branch_funnel: {
  5425. SmallVector<SDValue, 16> Ops;
  5426. Ops.push_back(DAG.getRoot());
  5427. Ops.push_back(getValue(I.getArgOperand(0)));
  5428. int64_t Offset;
  5429. auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
  5430. I.getArgOperand(1), Offset, DAG.getDataLayout()));
  5431. if (!Base)
  5432. report_fatal_error(
  5433. "llvm.icall.branch.funnel operand must be a GlobalValue");
  5434. Ops.push_back(DAG.getTargetGlobalAddress(Base, getCurSDLoc(), MVT::i64, 0));
  5435. struct BranchFunnelTarget {
  5436. int64_t Offset;
  5437. SDValue Target;
  5438. };
  5439. SmallVector<BranchFunnelTarget, 8> Targets;
  5440. for (unsigned Op = 1, N = I.getNumArgOperands(); Op != N; Op += 2) {
  5441. auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
  5442. I.getArgOperand(Op), Offset, DAG.getDataLayout()));
  5443. if (ElemBase != Base)
  5444. report_fatal_error("all llvm.icall.branch.funnel operands must refer "
  5445. "to the same GlobalValue");
  5446. SDValue Val = getValue(I.getArgOperand(Op + 1));
  5447. auto *GA = dyn_cast<GlobalAddressSDNode>(Val);
  5448. if (!GA)
  5449. report_fatal_error(
  5450. "llvm.icall.branch.funnel operand must be a GlobalValue");
  5451. Targets.push_back({Offset, DAG.getTargetGlobalAddress(
  5452. GA->getGlobal(), getCurSDLoc(),
  5453. Val.getValueType(), GA->getOffset())});
  5454. }
  5455. llvm::sort(Targets.begin(), Targets.end(),
  5456. [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) {
  5457. return T1.Offset < T2.Offset;
  5458. });
  5459. for (auto &T : Targets) {
  5460. Ops.push_back(DAG.getTargetConstant(T.Offset, getCurSDLoc(), MVT::i32));
  5461. Ops.push_back(T.Target);
  5462. }
  5463. SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL,
  5464. getCurSDLoc(), MVT::Other, Ops),
  5465. 0);
  5466. DAG.setRoot(N);
  5467. setValue(&I, N);
  5468. HasTailCall = true;
  5469. return nullptr;
  5470. }
  5471. }
  5472. }
  5473. void SelectionDAGBuilder::visitConstrainedFPIntrinsic(
  5474. const ConstrainedFPIntrinsic &FPI) {
  5475. SDLoc sdl = getCurSDLoc();
  5476. unsigned Opcode;
  5477. switch (FPI.getIntrinsicID()) {
  5478. default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
  5479. case Intrinsic::experimental_constrained_fadd:
  5480. Opcode = ISD::STRICT_FADD;
  5481. break;
  5482. case Intrinsic::experimental_constrained_fsub:
  5483. Opcode = ISD::STRICT_FSUB;
  5484. break;
  5485. case Intrinsic::experimental_constrained_fmul:
  5486. Opcode = ISD::STRICT_FMUL;
  5487. break;
  5488. case Intrinsic::experimental_constrained_fdiv:
  5489. Opcode = ISD::STRICT_FDIV;
  5490. break;
  5491. case Intrinsic::experimental_constrained_frem:
  5492. Opcode = ISD::STRICT_FREM;
  5493. break;
  5494. case Intrinsic::experimental_constrained_fma:
  5495. Opcode = ISD::STRICT_FMA;
  5496. break;
  5497. case Intrinsic::experimental_constrained_sqrt:
  5498. Opcode = ISD::STRICT_FSQRT;
  5499. break;
  5500. case Intrinsic::experimental_constrained_pow:
  5501. Opcode = ISD::STRICT_FPOW;
  5502. break;
  5503. case Intrinsic::experimental_constrained_powi:
  5504. Opcode = ISD::STRICT_FPOWI;
  5505. break;
  5506. case Intrinsic::experimental_constrained_sin:
  5507. Opcode = ISD::STRICT_FSIN;
  5508. break;
  5509. case Intrinsic::experimental_constrained_cos:
  5510. Opcode = ISD::STRICT_FCOS;
  5511. break;
  5512. case Intrinsic::experimental_constrained_exp:
  5513. Opcode = ISD::STRICT_FEXP;
  5514. break;
  5515. case Intrinsic::experimental_constrained_exp2:
  5516. Opcode = ISD::STRICT_FEXP2;
  5517. break;
  5518. case Intrinsic::experimental_constrained_log:
  5519. Opcode = ISD::STRICT_FLOG;
  5520. break;
  5521. case Intrinsic::experimental_constrained_log10:
  5522. Opcode = ISD::STRICT_FLOG10;
  5523. break;
  5524. case Intrinsic::experimental_constrained_log2:
  5525. Opcode = ISD::STRICT_FLOG2;
  5526. break;
  5527. case Intrinsic::experimental_constrained_rint:
  5528. Opcode = ISD::STRICT_FRINT;
  5529. break;
  5530. case Intrinsic::experimental_constrained_nearbyint:
  5531. Opcode = ISD::STRICT_FNEARBYINT;
  5532. break;
  5533. }
  5534. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  5535. SDValue Chain = getRoot();
  5536. SmallVector<EVT, 4> ValueVTs;
  5537. ComputeValueVTs(TLI, DAG.getDataLayout(), FPI.getType(), ValueVTs);
  5538. ValueVTs.push_back(MVT::Other); // Out chain
  5539. SDVTList VTs = DAG.getVTList(ValueVTs);
  5540. SDValue Result;
  5541. if (FPI.isUnaryOp())
  5542. Result = DAG.getNode(Opcode, sdl, VTs,
  5543. { Chain, getValue(FPI.getArgOperand(0)) });
  5544. else if (FPI.isTernaryOp())
  5545. Result = DAG.getNode(Opcode, sdl, VTs,
  5546. { Chain, getValue(FPI.getArgOperand(0)),
  5547. getValue(FPI.getArgOperand(1)),
  5548. getValue(FPI.getArgOperand(2)) });
  5549. else
  5550. Result = DAG.getNode(Opcode, sdl, VTs,
  5551. { Chain, getValue(FPI.getArgOperand(0)),
  5552. getValue(FPI.getArgOperand(1)) });
  5553. assert(Result.getNode()->getNumValues() == 2);
  5554. SDValue OutChain = Result.getValue(1);
  5555. DAG.setRoot(OutChain);
  5556. SDValue FPResult = Result.getValue(0);
  5557. setValue(&FPI, FPResult);
  5558. }
  5559. std::pair<SDValue, SDValue>
  5560. SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI,
  5561. const BasicBlock *EHPadBB) {
  5562. MachineFunction &MF = DAG.getMachineFunction();
  5563. MachineModuleInfo &MMI = MF.getMMI();
  5564. MCSymbol *BeginLabel = nullptr;
  5565. if (EHPadBB) {
  5566. // Insert a label before the invoke call to mark the try range. This can be
  5567. // used to detect deletion of the invoke via the MachineModuleInfo.
  5568. BeginLabel = MMI.getContext().createTempSymbol();
  5569. // For SjLj, keep track of which landing pads go with which invokes
  5570. // so as to maintain the ordering of pads in the LSDA.
  5571. unsigned CallSiteIndex = MMI.getCurrentCallSite();
  5572. if (CallSiteIndex) {
  5573. MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex);
  5574. LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex);
  5575. // Now that the call site is handled, stop tracking it.
  5576. MMI.setCurrentCallSite(0);
  5577. }
  5578. // Both PendingLoads and PendingExports must be flushed here;
  5579. // this call might not return.
  5580. (void)getRoot();
  5581. DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getControlRoot(), BeginLabel));
  5582. CLI.setChain(getRoot());
  5583. }
  5584. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  5585. std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
  5586. assert((CLI.IsTailCall || Result.second.getNode()) &&
  5587. "Non-null chain expected with non-tail call!");
  5588. assert((Result.second.getNode() || !Result.first.getNode()) &&
  5589. "Null value expected with tail call!");
  5590. if (!Result.second.getNode()) {
  5591. // As a special case, a null chain means that a tail call has been emitted
  5592. // and the DAG root is already updated.
  5593. HasTailCall = true;
  5594. // Since there's no actual continuation from this block, nothing can be
  5595. // relying on us setting vregs for them.
  5596. PendingExports.clear();
  5597. } else {
  5598. DAG.setRoot(Result.second);
  5599. }
  5600. if (EHPadBB) {
  5601. // Insert a label at the end of the invoke call to mark the try range. This
  5602. // can be used to detect deletion of the invoke via the MachineModuleInfo.
  5603. MCSymbol *EndLabel = MMI.getContext().createTempSymbol();
  5604. DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getRoot(), EndLabel));
  5605. // Inform MachineModuleInfo of range.
  5606. if (MF.hasEHFunclets()) {
  5607. assert(CLI.CS);
  5608. WinEHFuncInfo *EHInfo = DAG.getMachineFunction().getWinEHFuncInfo();
  5609. EHInfo->addIPToStateRange(cast<InvokeInst>(CLI.CS.getInstruction()),
  5610. BeginLabel, EndLabel);
  5611. } else {
  5612. MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel);
  5613. }
  5614. }
  5615. return Result;
  5616. }
  5617. void SelectionDAGBuilder::LowerCallTo(ImmutableCallSite CS, SDValue Callee,
  5618. bool isTailCall,
  5619. const BasicBlock *EHPadBB) {
  5620. auto &DL = DAG.getDataLayout();
  5621. FunctionType *FTy = CS.getFunctionType();
  5622. Type *RetTy = CS.getType();
  5623. TargetLowering::ArgListTy Args;
  5624. Args.reserve(CS.arg_size());
  5625. const Value *SwiftErrorVal = nullptr;
  5626. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  5627. // We can't tail call inside a function with a swifterror argument. Lowering
  5628. // does not support this yet. It would have to move into the swifterror
  5629. // register before the call.
  5630. auto *Caller = CS.getInstruction()->getParent()->getParent();
  5631. if (TLI.supportSwiftError() &&
  5632. Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError))
  5633. isTailCall = false;
  5634. for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
  5635. i != e; ++i) {
  5636. TargetLowering::ArgListEntry Entry;
  5637. const Value *V = *i;
  5638. // Skip empty types
  5639. if (V->getType()->isEmptyTy())
  5640. continue;
  5641. SDValue ArgNode = getValue(V);
  5642. Entry.Node = ArgNode; Entry.Ty = V->getType();
  5643. Entry.setAttributes(&CS, i - CS.arg_begin());
  5644. // Use swifterror virtual register as input to the call.
  5645. if (Entry.IsSwiftError && TLI.supportSwiftError()) {
  5646. SwiftErrorVal = V;
  5647. // We find the virtual register for the actual swifterror argument.
  5648. // Instead of using the Value, we use the virtual register instead.
  5649. Entry.Node = DAG.getRegister(FuncInfo
  5650. .getOrCreateSwiftErrorVRegUseAt(
  5651. CS.getInstruction(), FuncInfo.MBB, V)
  5652. .first,
  5653. EVT(TLI.getPointerTy(DL)));
  5654. }
  5655. Args.push_back(Entry);
  5656. // If we have an explicit sret argument that is an Instruction, (i.e., it
  5657. // might point to function-local memory), we can't meaningfully tail-call.
  5658. if (Entry.IsSRet && isa<Instruction>(V))
  5659. isTailCall = false;
  5660. }
  5661. // Check if target-independent constraints permit a tail call here.
  5662. // Target-dependent constraints are checked within TLI->LowerCallTo.
  5663. if (isTailCall && !isInTailCallPosition(CS, DAG.getTarget()))
  5664. isTailCall = false;
  5665. // Disable tail calls if there is an swifterror argument. Targets have not
  5666. // been updated to support tail calls.
  5667. if (TLI.supportSwiftError() && SwiftErrorVal)
  5668. isTailCall = false;
  5669. TargetLowering::CallLoweringInfo CLI(DAG);
  5670. CLI.setDebugLoc(getCurSDLoc())
  5671. .setChain(getRoot())
  5672. .setCallee(RetTy, FTy, Callee, std::move(Args), CS)
  5673. .setTailCall(isTailCall)
  5674. .setConvergent(CS.isConvergent());
  5675. std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
  5676. if (Result.first.getNode()) {
  5677. const Instruction *Inst = CS.getInstruction();
  5678. Result.first = lowerRangeToAssertZExt(DAG, *Inst, Result.first);
  5679. setValue(Inst, Result.first);
  5680. }
  5681. // The last element of CLI.InVals has the SDValue for swifterror return.
  5682. // Here we copy it to a virtual register and update SwiftErrorMap for
  5683. // book-keeping.
  5684. if (SwiftErrorVal && TLI.supportSwiftError()) {
  5685. // Get the last element of InVals.
  5686. SDValue Src = CLI.InVals.back();
  5687. unsigned VReg; bool CreatedVReg;
  5688. std::tie(VReg, CreatedVReg) =
  5689. FuncInfo.getOrCreateSwiftErrorVRegDefAt(CS.getInstruction());
  5690. SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src);
  5691. // We update the virtual register for the actual swifterror argument.
  5692. if (CreatedVReg)
  5693. FuncInfo.setCurrentSwiftErrorVReg(FuncInfo.MBB, SwiftErrorVal, VReg);
  5694. DAG.setRoot(CopyNode);
  5695. }
  5696. }
  5697. static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT,
  5698. SelectionDAGBuilder &Builder) {
  5699. // Check to see if this load can be trivially constant folded, e.g. if the
  5700. // input is from a string literal.
  5701. if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) {
  5702. // Cast pointer to the type we really want to load.
  5703. Type *LoadTy =
  5704. Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits());
  5705. if (LoadVT.isVector())
  5706. LoadTy = VectorType::get(LoadTy, LoadVT.getVectorNumElements());
  5707. LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput),
  5708. PointerType::getUnqual(LoadTy));
  5709. if (const Constant *LoadCst = ConstantFoldLoadFromConstPtr(
  5710. const_cast<Constant *>(LoadInput), LoadTy, *Builder.DL))
  5711. return Builder.getValue(LoadCst);
  5712. }
  5713. // Otherwise, we have to emit the load. If the pointer is to unfoldable but
  5714. // still constant memory, the input chain can be the entry node.
  5715. SDValue Root;
  5716. bool ConstantMemory = false;
  5717. // Do not serialize (non-volatile) loads of constant memory with anything.
  5718. if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) {
  5719. Root = Builder.DAG.getEntryNode();
  5720. ConstantMemory = true;
  5721. } else {
  5722. // Do not serialize non-volatile loads against each other.
  5723. Root = Builder.DAG.getRoot();
  5724. }
  5725. SDValue Ptr = Builder.getValue(PtrVal);
  5726. SDValue LoadVal = Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root,
  5727. Ptr, MachinePointerInfo(PtrVal),
  5728. /* Alignment = */ 1);
  5729. if (!ConstantMemory)
  5730. Builder.PendingLoads.push_back(LoadVal.getValue(1));
  5731. return LoadVal;
  5732. }
  5733. /// Record the value for an instruction that produces an integer result,
  5734. /// converting the type where necessary.
  5735. void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I,
  5736. SDValue Value,
  5737. bool IsSigned) {
  5738. EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  5739. I.getType(), true);
  5740. if (IsSigned)
  5741. Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT);
  5742. else
  5743. Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT);
  5744. setValue(&I, Value);
  5745. }
  5746. /// See if we can lower a memcmp call into an optimized form. If so, return
  5747. /// true and lower it. Otherwise return false, and it will be lowered like a
  5748. /// normal call.
  5749. /// The caller already checked that \p I calls the appropriate LibFunc with a
  5750. /// correct prototype.
  5751. bool SelectionDAGBuilder::visitMemCmpCall(const CallInst &I) {
  5752. const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1);
  5753. const Value *Size = I.getArgOperand(2);
  5754. const ConstantInt *CSize = dyn_cast<ConstantInt>(Size);
  5755. if (CSize && CSize->getZExtValue() == 0) {
  5756. EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  5757. I.getType(), true);
  5758. setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT));
  5759. return true;
  5760. }
  5761. const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
  5762. std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp(
  5763. DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS),
  5764. getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS));
  5765. if (Res.first.getNode()) {
  5766. processIntegerCallValue(I, Res.first, true);
  5767. PendingLoads.push_back(Res.second);
  5768. return true;
  5769. }
  5770. // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS) != 0
  5771. // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS) != 0
  5772. if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I))
  5773. return false;
  5774. // If the target has a fast compare for the given size, it will return a
  5775. // preferred load type for that size. Require that the load VT is legal and
  5776. // that the target supports unaligned loads of that type. Otherwise, return
  5777. // INVALID.
  5778. auto hasFastLoadsAndCompare = [&](unsigned NumBits) {
  5779. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  5780. MVT LVT = TLI.hasFastEqualityCompare(NumBits);
  5781. if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) {
  5782. // TODO: Handle 5 byte compare as 4-byte + 1 byte.
  5783. // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
  5784. // TODO: Check alignment of src and dest ptrs.
  5785. unsigned DstAS = LHS->getType()->getPointerAddressSpace();
  5786. unsigned SrcAS = RHS->getType()->getPointerAddressSpace();
  5787. if (!TLI.isTypeLegal(LVT) ||
  5788. !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) ||
  5789. !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS))
  5790. LVT = MVT::INVALID_SIMPLE_VALUE_TYPE;
  5791. }
  5792. return LVT;
  5793. };
  5794. // This turns into unaligned loads. We only do this if the target natively
  5795. // supports the MVT we'll be loading or if it is small enough (<= 4) that
  5796. // we'll only produce a small number of byte loads.
  5797. MVT LoadVT;
  5798. unsigned NumBitsToCompare = CSize->getZExtValue() * 8;
  5799. switch (NumBitsToCompare) {
  5800. default:
  5801. return false;
  5802. case 16:
  5803. LoadVT = MVT::i16;
  5804. break;
  5805. case 32:
  5806. LoadVT = MVT::i32;
  5807. break;
  5808. case 64:
  5809. case 128:
  5810. case 256:
  5811. LoadVT = hasFastLoadsAndCompare(NumBitsToCompare);
  5812. break;
  5813. }
  5814. if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE)
  5815. return false;
  5816. SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this);
  5817. SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this);
  5818. // Bitcast to a wide integer type if the loads are vectors.
  5819. if (LoadVT.isVector()) {
  5820. EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits());
  5821. LoadL = DAG.getBitcast(CmpVT, LoadL);
  5822. LoadR = DAG.getBitcast(CmpVT, LoadR);
  5823. }
  5824. SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE);
  5825. processIntegerCallValue(I, Cmp, false);
  5826. return true;
  5827. }
  5828. /// See if we can lower a memchr call into an optimized form. If so, return
  5829. /// true and lower it. Otherwise return false, and it will be lowered like a
  5830. /// normal call.
  5831. /// The caller already checked that \p I calls the appropriate LibFunc with a
  5832. /// correct prototype.
  5833. bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) {
  5834. const Value *Src = I.getArgOperand(0);
  5835. const Value *Char = I.getArgOperand(1);
  5836. const Value *Length = I.getArgOperand(2);
  5837. const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
  5838. std::pair<SDValue, SDValue> Res =
  5839. TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(),
  5840. getValue(Src), getValue(Char), getValue(Length),
  5841. MachinePointerInfo(Src));
  5842. if (Res.first.getNode()) {
  5843. setValue(&I, Res.first);
  5844. PendingLoads.push_back(Res.second);
  5845. return true;
  5846. }
  5847. return false;
  5848. }
  5849. /// See if we can lower a mempcpy call into an optimized form. If so, return
  5850. /// true and lower it. Otherwise return false, and it will be lowered like a
  5851. /// normal call.
  5852. /// The caller already checked that \p I calls the appropriate LibFunc with a
  5853. /// correct prototype.
  5854. bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) {
  5855. SDValue Dst = getValue(I.getArgOperand(0));
  5856. SDValue Src = getValue(I.getArgOperand(1));
  5857. SDValue Size = getValue(I.getArgOperand(2));
  5858. unsigned DstAlign = DAG.InferPtrAlignment(Dst);
  5859. unsigned SrcAlign = DAG.InferPtrAlignment(Src);
  5860. unsigned Align = std::min(DstAlign, SrcAlign);
  5861. if (Align == 0) // Alignment of one or both could not be inferred.
  5862. Align = 1; // 0 and 1 both specify no alignment, but 0 is reserved.
  5863. bool isVol = false;
  5864. SDLoc sdl = getCurSDLoc();
  5865. // In the mempcpy context we need to pass in a false value for isTailCall
  5866. // because the return pointer needs to be adjusted by the size of
  5867. // the copied memory.
  5868. SDValue MC = DAG.getMemcpy(getRoot(), sdl, Dst, Src, Size, Align, isVol,
  5869. false, /*isTailCall=*/false,
  5870. MachinePointerInfo(I.getArgOperand(0)),
  5871. MachinePointerInfo(I.getArgOperand(1)));
  5872. assert(MC.getNode() != nullptr &&
  5873. "** memcpy should not be lowered as TailCall in mempcpy context **");
  5874. DAG.setRoot(MC);
  5875. // Check if Size needs to be truncated or extended.
  5876. Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType());
  5877. // Adjust return pointer to point just past the last dst byte.
  5878. SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(),
  5879. Dst, Size);
  5880. setValue(&I, DstPlusSize);
  5881. return true;
  5882. }
  5883. /// See if we can lower a strcpy call into an optimized form. If so, return
  5884. /// true and lower it, otherwise return false and it will be lowered like a
  5885. /// normal call.
  5886. /// The caller already checked that \p I calls the appropriate LibFunc with a
  5887. /// correct prototype.
  5888. bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) {
  5889. const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
  5890. const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
  5891. std::pair<SDValue, SDValue> Res =
  5892. TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(),
  5893. getValue(Arg0), getValue(Arg1),
  5894. MachinePointerInfo(Arg0),
  5895. MachinePointerInfo(Arg1), isStpcpy);
  5896. if (Res.first.getNode()) {
  5897. setValue(&I, Res.first);
  5898. DAG.setRoot(Res.second);
  5899. return true;
  5900. }
  5901. return false;
  5902. }
  5903. /// See if we can lower a strcmp call into an optimized form. If so, return
  5904. /// true and lower it, otherwise return false and it will be lowered like a
  5905. /// normal call.
  5906. /// The caller already checked that \p I calls the appropriate LibFunc with a
  5907. /// correct prototype.
  5908. bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) {
  5909. const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
  5910. const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
  5911. std::pair<SDValue, SDValue> Res =
  5912. TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(),
  5913. getValue(Arg0), getValue(Arg1),
  5914. MachinePointerInfo(Arg0),
  5915. MachinePointerInfo(Arg1));
  5916. if (Res.first.getNode()) {
  5917. processIntegerCallValue(I, Res.first, true);
  5918. PendingLoads.push_back(Res.second);
  5919. return true;
  5920. }
  5921. return false;
  5922. }
  5923. /// See if we can lower a strlen call into an optimized form. If so, return
  5924. /// true and lower it, otherwise return false and it will be lowered like a
  5925. /// normal call.
  5926. /// The caller already checked that \p I calls the appropriate LibFunc with a
  5927. /// correct prototype.
  5928. bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) {
  5929. const Value *Arg0 = I.getArgOperand(0);
  5930. const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
  5931. std::pair<SDValue, SDValue> Res =
  5932. TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(),
  5933. getValue(Arg0), MachinePointerInfo(Arg0));
  5934. if (Res.first.getNode()) {
  5935. processIntegerCallValue(I, Res.first, false);
  5936. PendingLoads.push_back(Res.second);
  5937. return true;
  5938. }
  5939. return false;
  5940. }
  5941. /// See if we can lower a strnlen call into an optimized form. If so, return
  5942. /// true and lower it, otherwise return false and it will be lowered like a
  5943. /// normal call.
  5944. /// The caller already checked that \p I calls the appropriate LibFunc with a
  5945. /// correct prototype.
  5946. bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) {
  5947. const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
  5948. const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
  5949. std::pair<SDValue, SDValue> Res =
  5950. TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(),
  5951. getValue(Arg0), getValue(Arg1),
  5952. MachinePointerInfo(Arg0));
  5953. if (Res.first.getNode()) {
  5954. processIntegerCallValue(I, Res.first, false);
  5955. PendingLoads.push_back(Res.second);
  5956. return true;
  5957. }
  5958. return false;
  5959. }
  5960. /// See if we can lower a unary floating-point operation into an SDNode with
  5961. /// the specified Opcode. If so, return true and lower it, otherwise return
  5962. /// false and it will be lowered like a normal call.
  5963. /// The caller already checked that \p I calls the appropriate LibFunc with a
  5964. /// correct prototype.
  5965. bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I,
  5966. unsigned Opcode) {
  5967. // We already checked this call's prototype; verify it doesn't modify errno.
  5968. if (!I.onlyReadsMemory())
  5969. return false;
  5970. SDValue Tmp = getValue(I.getArgOperand(0));
  5971. setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp));
  5972. return true;
  5973. }
  5974. /// See if we can lower a binary floating-point operation into an SDNode with
  5975. /// the specified Opcode. If so, return true and lower it. Otherwise return
  5976. /// false, and it will be lowered like a normal call.
  5977. /// The caller already checked that \p I calls the appropriate LibFunc with a
  5978. /// correct prototype.
  5979. bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I,
  5980. unsigned Opcode) {
  5981. // We already checked this call's prototype; verify it doesn't modify errno.
  5982. if (!I.onlyReadsMemory())
  5983. return false;
  5984. SDValue Tmp0 = getValue(I.getArgOperand(0));
  5985. SDValue Tmp1 = getValue(I.getArgOperand(1));
  5986. EVT VT = Tmp0.getValueType();
  5987. setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1));
  5988. return true;
  5989. }
  5990. void SelectionDAGBuilder::visitCall(const CallInst &I) {
  5991. // Handle inline assembly differently.
  5992. if (isa<InlineAsm>(I.getCalledValue())) {
  5993. visitInlineAsm(&I);
  5994. return;
  5995. }
  5996. MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
  5997. computeUsesVAFloatArgument(I, MMI);
  5998. const char *RenameFn = nullptr;
  5999. if (Function *F = I.getCalledFunction()) {
  6000. if (F->isDeclaration()) {
  6001. if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo()) {
  6002. if (unsigned IID = II->getIntrinsicID(F)) {
  6003. RenameFn = visitIntrinsicCall(I, IID);
  6004. if (!RenameFn)
  6005. return;
  6006. }
  6007. }
  6008. if (Intrinsic::ID IID = F->getIntrinsicID()) {
  6009. RenameFn = visitIntrinsicCall(I, IID);
  6010. if (!RenameFn)
  6011. return;
  6012. }
  6013. }
  6014. // Check for well-known libc/libm calls. If the function is internal, it
  6015. // can't be a library call. Don't do the check if marked as nobuiltin for
  6016. // some reason or the call site requires strict floating point semantics.
  6017. LibFunc Func;
  6018. if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() &&
  6019. F->hasName() && LibInfo->getLibFunc(*F, Func) &&
  6020. LibInfo->hasOptimizedCodeGen(Func)) {
  6021. switch (Func) {
  6022. default: break;
  6023. case LibFunc_copysign:
  6024. case LibFunc_copysignf:
  6025. case LibFunc_copysignl:
  6026. // We already checked this call's prototype; verify it doesn't modify
  6027. // errno.
  6028. if (I.onlyReadsMemory()) {
  6029. SDValue LHS = getValue(I.getArgOperand(0));
  6030. SDValue RHS = getValue(I.getArgOperand(1));
  6031. setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(),
  6032. LHS.getValueType(), LHS, RHS));
  6033. return;
  6034. }
  6035. break;
  6036. case LibFunc_fabs:
  6037. case LibFunc_fabsf:
  6038. case LibFunc_fabsl:
  6039. if (visitUnaryFloatCall(I, ISD::FABS))
  6040. return;
  6041. break;
  6042. case LibFunc_fmin:
  6043. case LibFunc_fminf:
  6044. case LibFunc_fminl:
  6045. if (visitBinaryFloatCall(I, ISD::FMINNUM))
  6046. return;
  6047. break;
  6048. case LibFunc_fmax:
  6049. case LibFunc_fmaxf:
  6050. case LibFunc_fmaxl:
  6051. if (visitBinaryFloatCall(I, ISD::FMAXNUM))
  6052. return;
  6053. break;
  6054. case LibFunc_sin:
  6055. case LibFunc_sinf:
  6056. case LibFunc_sinl:
  6057. if (visitUnaryFloatCall(I, ISD::FSIN))
  6058. return;
  6059. break;
  6060. case LibFunc_cos:
  6061. case LibFunc_cosf:
  6062. case LibFunc_cosl:
  6063. if (visitUnaryFloatCall(I, ISD::FCOS))
  6064. return;
  6065. break;
  6066. case LibFunc_sqrt:
  6067. case LibFunc_sqrtf:
  6068. case LibFunc_sqrtl:
  6069. case LibFunc_sqrt_finite:
  6070. case LibFunc_sqrtf_finite:
  6071. case LibFunc_sqrtl_finite:
  6072. if (visitUnaryFloatCall(I, ISD::FSQRT))
  6073. return;
  6074. break;
  6075. case LibFunc_floor:
  6076. case LibFunc_floorf:
  6077. case LibFunc_floorl:
  6078. if (visitUnaryFloatCall(I, ISD::FFLOOR))
  6079. return;
  6080. break;
  6081. case LibFunc_nearbyint:
  6082. case LibFunc_nearbyintf:
  6083. case LibFunc_nearbyintl:
  6084. if (visitUnaryFloatCall(I, ISD::FNEARBYINT))
  6085. return;
  6086. break;
  6087. case LibFunc_ceil:
  6088. case LibFunc_ceilf:
  6089. case LibFunc_ceill:
  6090. if (visitUnaryFloatCall(I, ISD::FCEIL))
  6091. return;
  6092. break;
  6093. case LibFunc_rint:
  6094. case LibFunc_rintf:
  6095. case LibFunc_rintl:
  6096. if (visitUnaryFloatCall(I, ISD::FRINT))
  6097. return;
  6098. break;
  6099. case LibFunc_round:
  6100. case LibFunc_roundf:
  6101. case LibFunc_roundl:
  6102. if (visitUnaryFloatCall(I, ISD::FROUND))
  6103. return;
  6104. break;
  6105. case LibFunc_trunc:
  6106. case LibFunc_truncf:
  6107. case LibFunc_truncl:
  6108. if (visitUnaryFloatCall(I, ISD::FTRUNC))
  6109. return;
  6110. break;
  6111. case LibFunc_log2:
  6112. case LibFunc_log2f:
  6113. case LibFunc_log2l:
  6114. if (visitUnaryFloatCall(I, ISD::FLOG2))
  6115. return;
  6116. break;
  6117. case LibFunc_exp2:
  6118. case LibFunc_exp2f:
  6119. case LibFunc_exp2l:
  6120. if (visitUnaryFloatCall(I, ISD::FEXP2))
  6121. return;
  6122. break;
  6123. case LibFunc_memcmp:
  6124. if (visitMemCmpCall(I))
  6125. return;
  6126. break;
  6127. case LibFunc_mempcpy:
  6128. if (visitMemPCpyCall(I))
  6129. return;
  6130. break;
  6131. case LibFunc_memchr:
  6132. if (visitMemChrCall(I))
  6133. return;
  6134. break;
  6135. case LibFunc_strcpy:
  6136. if (visitStrCpyCall(I, false))
  6137. return;
  6138. break;
  6139. case LibFunc_stpcpy:
  6140. if (visitStrCpyCall(I, true))
  6141. return;
  6142. break;
  6143. case LibFunc_strcmp:
  6144. if (visitStrCmpCall(I))
  6145. return;
  6146. break;
  6147. case LibFunc_strlen:
  6148. if (visitStrLenCall(I))
  6149. return;
  6150. break;
  6151. case LibFunc_strnlen:
  6152. if (visitStrNLenCall(I))
  6153. return;
  6154. break;
  6155. }
  6156. }
  6157. }
  6158. SDValue Callee;
  6159. if (!RenameFn)
  6160. Callee = getValue(I.getCalledValue());
  6161. else
  6162. Callee = DAG.getExternalSymbol(
  6163. RenameFn,
  6164. DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()));
  6165. // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
  6166. // have to do anything here to lower funclet bundles.
  6167. assert(!I.hasOperandBundlesOtherThan(
  6168. {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) &&
  6169. "Cannot lower calls with arbitrary operand bundles!");
  6170. if (I.countOperandBundlesOfType(LLVMContext::OB_deopt))
  6171. LowerCallSiteWithDeoptBundle(&I, Callee, nullptr);
  6172. else
  6173. // Check if we can potentially perform a tail call. More detailed checking
  6174. // is be done within LowerCallTo, after more information about the call is
  6175. // known.
  6176. LowerCallTo(&I, Callee, I.isTailCall());
  6177. }
  6178. namespace {
  6179. /// AsmOperandInfo - This contains information for each constraint that we are
  6180. /// lowering.
  6181. class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
  6182. public:
  6183. /// CallOperand - If this is the result output operand or a clobber
  6184. /// this is null, otherwise it is the incoming operand to the CallInst.
  6185. /// This gets modified as the asm is processed.
  6186. SDValue CallOperand;
  6187. /// AssignedRegs - If this is a register or register class operand, this
  6188. /// contains the set of register corresponding to the operand.
  6189. RegsForValue AssignedRegs;
  6190. explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info)
  6191. : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) {
  6192. }
  6193. /// Whether or not this operand accesses memory
  6194. bool hasMemory(const TargetLowering &TLI) const {
  6195. // Indirect operand accesses access memory.
  6196. if (isIndirect)
  6197. return true;
  6198. for (const auto &Code : Codes)
  6199. if (TLI.getConstraintType(Code) == TargetLowering::C_Memory)
  6200. return true;
  6201. return false;
  6202. }
  6203. /// getCallOperandValEVT - Return the EVT of the Value* that this operand
  6204. /// corresponds to. If there is no Value* for this operand, it returns
  6205. /// MVT::Other.
  6206. EVT getCallOperandValEVT(LLVMContext &Context, const TargetLowering &TLI,
  6207. const DataLayout &DL) const {
  6208. if (!CallOperandVal) return MVT::Other;
  6209. if (isa<BasicBlock>(CallOperandVal))
  6210. return TLI.getPointerTy(DL);
  6211. llvm::Type *OpTy = CallOperandVal->getType();
  6212. // FIXME: code duplicated from TargetLowering::ParseConstraints().
  6213. // If this is an indirect operand, the operand is a pointer to the
  6214. // accessed type.
  6215. if (isIndirect) {
  6216. PointerType *PtrTy = dyn_cast<PointerType>(OpTy);
  6217. if (!PtrTy)
  6218. report_fatal_error("Indirect operand for inline asm not a pointer!");
  6219. OpTy = PtrTy->getElementType();
  6220. }
  6221. // Look for vector wrapped in a struct. e.g. { <16 x i8> }.
  6222. if (StructType *STy = dyn_cast<StructType>(OpTy))
  6223. if (STy->getNumElements() == 1)
  6224. OpTy = STy->getElementType(0);
  6225. // If OpTy is not a single value, it may be a struct/union that we
  6226. // can tile with integers.
  6227. if (!OpTy->isSingleValueType() && OpTy->isSized()) {
  6228. unsigned BitSize = DL.getTypeSizeInBits(OpTy);
  6229. switch (BitSize) {
  6230. default: break;
  6231. case 1:
  6232. case 8:
  6233. case 16:
  6234. case 32:
  6235. case 64:
  6236. case 128:
  6237. OpTy = IntegerType::get(Context, BitSize);
  6238. break;
  6239. }
  6240. }
  6241. return TLI.getValueType(DL, OpTy, true);
  6242. }
  6243. };
  6244. using SDISelAsmOperandInfoVector = SmallVector<SDISelAsmOperandInfo, 16>;
  6245. } // end anonymous namespace
  6246. /// Make sure that the output operand \p OpInfo and its corresponding input
  6247. /// operand \p MatchingOpInfo have compatible constraint types (otherwise error
  6248. /// out).
  6249. static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo,
  6250. SDISelAsmOperandInfo &MatchingOpInfo,
  6251. SelectionDAG &DAG) {
  6252. if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT)
  6253. return;
  6254. const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
  6255. const auto &TLI = DAG.getTargetLoweringInfo();
  6256. std::pair<unsigned, const TargetRegisterClass *> MatchRC =
  6257. TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode,
  6258. OpInfo.ConstraintVT);
  6259. std::pair<unsigned, const TargetRegisterClass *> InputRC =
  6260. TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode,
  6261. MatchingOpInfo.ConstraintVT);
  6262. if ((OpInfo.ConstraintVT.isInteger() !=
  6263. MatchingOpInfo.ConstraintVT.isInteger()) ||
  6264. (MatchRC.second != InputRC.second)) {
  6265. // FIXME: error out in a more elegant fashion
  6266. report_fatal_error("Unsupported asm: input constraint"
  6267. " with a matching output constraint of"
  6268. " incompatible type!");
  6269. }
  6270. MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT;
  6271. }
  6272. /// Get a direct memory input to behave well as an indirect operand.
  6273. /// This may introduce stores, hence the need for a \p Chain.
  6274. /// \return The (possibly updated) chain.
  6275. static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location,
  6276. SDISelAsmOperandInfo &OpInfo,
  6277. SelectionDAG &DAG) {
  6278. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  6279. // If we don't have an indirect input, put it in the constpool if we can,
  6280. // otherwise spill it to a stack slot.
  6281. // TODO: This isn't quite right. We need to handle these according to
  6282. // the addressing mode that the constraint wants. Also, this may take
  6283. // an additional register for the computation and we don't want that
  6284. // either.
  6285. // If the operand is a float, integer, or vector constant, spill to a
  6286. // constant pool entry to get its address.
  6287. const Value *OpVal = OpInfo.CallOperandVal;
  6288. if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
  6289. isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) {
  6290. OpInfo.CallOperand = DAG.getConstantPool(
  6291. cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout()));
  6292. return Chain;
  6293. }
  6294. // Otherwise, create a stack slot and emit a store to it before the asm.
  6295. Type *Ty = OpVal->getType();
  6296. auto &DL = DAG.getDataLayout();
  6297. uint64_t TySize = DL.getTypeAllocSize(Ty);
  6298. unsigned Align = DL.getPrefTypeAlignment(Ty);
  6299. MachineFunction &MF = DAG.getMachineFunction();
  6300. int SSFI = MF.getFrameInfo().CreateStackObject(TySize, Align, false);
  6301. SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL));
  6302. Chain = DAG.getStore(Chain, Location, OpInfo.CallOperand, StackSlot,
  6303. MachinePointerInfo::getFixedStack(MF, SSFI));
  6304. OpInfo.CallOperand = StackSlot;
  6305. return Chain;
  6306. }
  6307. /// GetRegistersForValue - Assign registers (virtual or physical) for the
  6308. /// specified operand. We prefer to assign virtual registers, to allow the
  6309. /// register allocator to handle the assignment process. However, if the asm
  6310. /// uses features that we can't model on machineinstrs, we have SDISel do the
  6311. /// allocation. This produces generally horrible, but correct, code.
  6312. ///
  6313. /// OpInfo describes the operand.
  6314. static void GetRegistersForValue(SelectionDAG &DAG, const TargetLowering &TLI,
  6315. const SDLoc &DL,
  6316. SDISelAsmOperandInfo &OpInfo) {
  6317. LLVMContext &Context = *DAG.getContext();
  6318. MachineFunction &MF = DAG.getMachineFunction();
  6319. SmallVector<unsigned, 4> Regs;
  6320. const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
  6321. // If this is a constraint for a single physreg, or a constraint for a
  6322. // register class, find it.
  6323. std::pair<unsigned, const TargetRegisterClass *> PhysReg =
  6324. TLI.getRegForInlineAsmConstraint(&TRI, OpInfo.ConstraintCode,
  6325. OpInfo.ConstraintVT);
  6326. unsigned NumRegs = 1;
  6327. if (OpInfo.ConstraintVT != MVT::Other) {
  6328. // If this is a FP input in an integer register (or visa versa) insert a bit
  6329. // cast of the input value. More generally, handle any case where the input
  6330. // value disagrees with the register class we plan to stick this in.
  6331. if (OpInfo.Type == InlineAsm::isInput && PhysReg.second &&
  6332. !TRI.isTypeLegalForClass(*PhysReg.second, OpInfo.ConstraintVT)) {
  6333. // Try to convert to the first EVT that the reg class contains. If the
  6334. // types are identical size, use a bitcast to convert (e.g. two differing
  6335. // vector types).
  6336. MVT RegVT = *TRI.legalclasstypes_begin(*PhysReg.second);
  6337. if (RegVT.getSizeInBits() == OpInfo.CallOperand.getValueSizeInBits()) {
  6338. OpInfo.CallOperand = DAG.getNode(ISD::BITCAST, DL,
  6339. RegVT, OpInfo.CallOperand);
  6340. OpInfo.ConstraintVT = RegVT;
  6341. } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
  6342. // If the input is a FP value and we want it in FP registers, do a
  6343. // bitcast to the corresponding integer type. This turns an f64 value
  6344. // into i64, which can be passed with two i32 values on a 32-bit
  6345. // machine.
  6346. RegVT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
  6347. OpInfo.CallOperand = DAG.getNode(ISD::BITCAST, DL,
  6348. RegVT, OpInfo.CallOperand);
  6349. OpInfo.ConstraintVT = RegVT;
  6350. }
  6351. }
  6352. NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT);
  6353. }
  6354. MVT RegVT;
  6355. EVT ValueVT = OpInfo.ConstraintVT;
  6356. // If this is a constraint for a specific physical register, like {r17},
  6357. // assign it now.
  6358. if (unsigned AssignedReg = PhysReg.first) {
  6359. const TargetRegisterClass *RC = PhysReg.second;
  6360. if (OpInfo.ConstraintVT == MVT::Other)
  6361. ValueVT = *TRI.legalclasstypes_begin(*RC);
  6362. // Get the actual register value type. This is important, because the user
  6363. // may have asked for (e.g.) the AX register in i32 type. We need to
  6364. // remember that AX is actually i16 to get the right extension.
  6365. RegVT = *TRI.legalclasstypes_begin(*RC);
  6366. // This is a explicit reference to a physical register.
  6367. Regs.push_back(AssignedReg);
  6368. // If this is an expanded reference, add the rest of the regs to Regs.
  6369. if (NumRegs != 1) {
  6370. TargetRegisterClass::iterator I = RC->begin();
  6371. for (; *I != AssignedReg; ++I)
  6372. assert(I != RC->end() && "Didn't find reg!");
  6373. // Already added the first reg.
  6374. --NumRegs; ++I;
  6375. for (; NumRegs; --NumRegs, ++I) {
  6376. assert(I != RC->end() && "Ran out of registers to allocate!");
  6377. Regs.push_back(*I);
  6378. }
  6379. }
  6380. OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
  6381. return;
  6382. }
  6383. // Otherwise, if this was a reference to an LLVM register class, create vregs
  6384. // for this reference.
  6385. if (const TargetRegisterClass *RC = PhysReg.second) {
  6386. RegVT = *TRI.legalclasstypes_begin(*RC);
  6387. if (OpInfo.ConstraintVT == MVT::Other)
  6388. ValueVT = RegVT;
  6389. // Create the appropriate number of virtual registers.
  6390. MachineRegisterInfo &RegInfo = MF.getRegInfo();
  6391. for (; NumRegs; --NumRegs)
  6392. Regs.push_back(RegInfo.createVirtualRegister(RC));
  6393. OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
  6394. return;
  6395. }
  6396. // Otherwise, we couldn't allocate enough registers for this.
  6397. }
  6398. static unsigned
  6399. findMatchingInlineAsmOperand(unsigned OperandNo,
  6400. const std::vector<SDValue> &AsmNodeOperands) {
  6401. // Scan until we find the definition we already emitted of this operand.
  6402. unsigned CurOp = InlineAsm::Op_FirstOperand;
  6403. for (; OperandNo; --OperandNo) {
  6404. // Advance to the next operand.
  6405. unsigned OpFlag =
  6406. cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
  6407. assert((InlineAsm::isRegDefKind(OpFlag) ||
  6408. InlineAsm::isRegDefEarlyClobberKind(OpFlag) ||
  6409. InlineAsm::isMemKind(OpFlag)) &&
  6410. "Skipped past definitions?");
  6411. CurOp += InlineAsm::getNumOperandRegisters(OpFlag) + 1;
  6412. }
  6413. return CurOp;
  6414. }
  6415. /// Fill \p Regs with \p NumRegs new virtual registers of type \p RegVT
  6416. /// \return true if it has succeeded, false otherwise
  6417. static bool createVirtualRegs(SmallVector<unsigned, 4> &Regs, unsigned NumRegs,
  6418. MVT RegVT, SelectionDAG &DAG) {
  6419. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  6420. MachineRegisterInfo &RegInfo = DAG.getMachineFunction().getRegInfo();
  6421. for (unsigned i = 0, e = NumRegs; i != e; ++i) {
  6422. if (const TargetRegisterClass *RC = TLI.getRegClassFor(RegVT))
  6423. Regs.push_back(RegInfo.createVirtualRegister(RC));
  6424. else
  6425. return false;
  6426. }
  6427. return true;
  6428. }
  6429. namespace {
  6430. class ExtraFlags {
  6431. unsigned Flags = 0;
  6432. public:
  6433. explicit ExtraFlags(ImmutableCallSite CS) {
  6434. const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
  6435. if (IA->hasSideEffects())
  6436. Flags |= InlineAsm::Extra_HasSideEffects;
  6437. if (IA->isAlignStack())
  6438. Flags |= InlineAsm::Extra_IsAlignStack;
  6439. if (CS.isConvergent())
  6440. Flags |= InlineAsm::Extra_IsConvergent;
  6441. Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect;
  6442. }
  6443. void update(const TargetLowering::AsmOperandInfo &OpInfo) {
  6444. // Ideally, we would only check against memory constraints. However, the
  6445. // meaning of an Other constraint can be target-specific and we can't easily
  6446. // reason about it. Therefore, be conservative and set MayLoad/MayStore
  6447. // for Other constraints as well.
  6448. if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
  6449. OpInfo.ConstraintType == TargetLowering::C_Other) {
  6450. if (OpInfo.Type == InlineAsm::isInput)
  6451. Flags |= InlineAsm::Extra_MayLoad;
  6452. else if (OpInfo.Type == InlineAsm::isOutput)
  6453. Flags |= InlineAsm::Extra_MayStore;
  6454. else if (OpInfo.Type == InlineAsm::isClobber)
  6455. Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore);
  6456. }
  6457. }
  6458. unsigned get() const { return Flags; }
  6459. };
  6460. } // end anonymous namespace
  6461. /// visitInlineAsm - Handle a call to an InlineAsm object.
  6462. void SelectionDAGBuilder::visitInlineAsm(ImmutableCallSite CS) {
  6463. const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
  6464. /// ConstraintOperands - Information about all of the constraints.
  6465. SDISelAsmOperandInfoVector ConstraintOperands;
  6466. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  6467. TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints(
  6468. DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), CS);
  6469. bool hasMemory = false;
  6470. // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore
  6471. ExtraFlags ExtraInfo(CS);
  6472. unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
  6473. unsigned ResNo = 0; // ResNo - The result number of the next output.
  6474. for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
  6475. ConstraintOperands.push_back(SDISelAsmOperandInfo(TargetConstraints[i]));
  6476. SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
  6477. MVT OpVT = MVT::Other;
  6478. // Compute the value type for each operand.
  6479. if (OpInfo.Type == InlineAsm::isInput ||
  6480. (OpInfo.Type == InlineAsm::isOutput && OpInfo.isIndirect)) {
  6481. OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
  6482. // Process the call argument. BasicBlocks are labels, currently appearing
  6483. // only in asm's.
  6484. if (const BasicBlock *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) {
  6485. OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
  6486. } else {
  6487. OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
  6488. }
  6489. OpVT =
  6490. OpInfo
  6491. .getCallOperandValEVT(*DAG.getContext(), TLI, DAG.getDataLayout())
  6492. .getSimpleVT();
  6493. }
  6494. if (OpInfo.Type == InlineAsm::isOutput && !OpInfo.isIndirect) {
  6495. // The return value of the call is this value. As such, there is no
  6496. // corresponding argument.
  6497. assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
  6498. if (StructType *STy = dyn_cast<StructType>(CS.getType())) {
  6499. OpVT = TLI.getSimpleValueType(DAG.getDataLayout(),
  6500. STy->getElementType(ResNo));
  6501. } else {
  6502. assert(ResNo == 0 && "Asm only has one result!");
  6503. OpVT = TLI.getSimpleValueType(DAG.getDataLayout(), CS.getType());
  6504. }
  6505. ++ResNo;
  6506. }
  6507. OpInfo.ConstraintVT = OpVT;
  6508. if (!hasMemory)
  6509. hasMemory = OpInfo.hasMemory(TLI);
  6510. // Determine if this InlineAsm MayLoad or MayStore based on the constraints.
  6511. // FIXME: Could we compute this on OpInfo rather than TargetConstraints[i]?
  6512. auto TargetConstraint = TargetConstraints[i];
  6513. // Compute the constraint code and ConstraintType to use.
  6514. TLI.ComputeConstraintToUse(TargetConstraint, SDValue());
  6515. ExtraInfo.update(TargetConstraint);
  6516. }
  6517. SDValue Chain, Flag;
  6518. // We won't need to flush pending loads if this asm doesn't touch
  6519. // memory and is nonvolatile.
  6520. if (hasMemory || IA->hasSideEffects())
  6521. Chain = getRoot();
  6522. else
  6523. Chain = DAG.getRoot();
  6524. // Second pass over the constraints: compute which constraint option to use
  6525. // and assign registers to constraints that want a specific physreg.
  6526. for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
  6527. SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
  6528. // If this is an output operand with a matching input operand, look up the
  6529. // matching input. If their types mismatch, e.g. one is an integer, the
  6530. // other is floating point, or their sizes are different, flag it as an
  6531. // error.
  6532. if (OpInfo.hasMatchingInput()) {
  6533. SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
  6534. patchMatchingInput(OpInfo, Input, DAG);
  6535. }
  6536. // Compute the constraint code and ConstraintType to use.
  6537. TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
  6538. if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
  6539. OpInfo.Type == InlineAsm::isClobber)
  6540. continue;
  6541. // If this is a memory input, and if the operand is not indirect, do what we
  6542. // need to provide an address for the memory input.
  6543. if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
  6544. !OpInfo.isIndirect) {
  6545. assert((OpInfo.isMultipleAlternative ||
  6546. (OpInfo.Type == InlineAsm::isInput)) &&
  6547. "Can only indirectify direct input operands!");
  6548. // Memory operands really want the address of the value.
  6549. Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG);
  6550. // There is no longer a Value* corresponding to this operand.
  6551. OpInfo.CallOperandVal = nullptr;
  6552. // It is now an indirect operand.
  6553. OpInfo.isIndirect = true;
  6554. }
  6555. // If this constraint is for a specific register, allocate it before
  6556. // anything else.
  6557. if (OpInfo.ConstraintType == TargetLowering::C_Register)
  6558. GetRegistersForValue(DAG, TLI, getCurSDLoc(), OpInfo);
  6559. }
  6560. // Third pass - Loop over all of the operands, assigning virtual or physregs
  6561. // to register class operands.
  6562. for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
  6563. SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
  6564. // C_Register operands have already been allocated, Other/Memory don't need
  6565. // to be.
  6566. if (OpInfo.ConstraintType == TargetLowering::C_RegisterClass)
  6567. GetRegistersForValue(DAG, TLI, getCurSDLoc(), OpInfo);
  6568. }
  6569. // AsmNodeOperands - The operands for the ISD::INLINEASM node.
  6570. std::vector<SDValue> AsmNodeOperands;
  6571. AsmNodeOperands.push_back(SDValue()); // reserve space for input chain
  6572. AsmNodeOperands.push_back(DAG.getTargetExternalSymbol(
  6573. IA->getAsmString().c_str(), TLI.getPointerTy(DAG.getDataLayout())));
  6574. // If we have a !srcloc metadata node associated with it, we want to attach
  6575. // this to the ultimately generated inline asm machineinstr. To do this, we
  6576. // pass in the third operand as this (potentially null) inline asm MDNode.
  6577. const MDNode *SrcLoc = CS.getInstruction()->getMetadata("srcloc");
  6578. AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc));
  6579. // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore
  6580. // bits as operand 3.
  6581. AsmNodeOperands.push_back(DAG.getTargetConstant(
  6582. ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
  6583. // Loop over all of the inputs, copying the operand values into the
  6584. // appropriate registers and processing the output regs.
  6585. RegsForValue RetValRegs;
  6586. // IndirectStoresToEmit - The set of stores to emit after the inline asm node.
  6587. std::vector<std::pair<RegsForValue, Value *>> IndirectStoresToEmit;
  6588. for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
  6589. SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
  6590. switch (OpInfo.Type) {
  6591. case InlineAsm::isOutput:
  6592. if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
  6593. OpInfo.ConstraintType != TargetLowering::C_Register) {
  6594. // Memory output, or 'other' output (e.g. 'X' constraint).
  6595. assert(OpInfo.isIndirect && "Memory output must be indirect operand");
  6596. unsigned ConstraintID =
  6597. TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
  6598. assert(ConstraintID != InlineAsm::Constraint_Unknown &&
  6599. "Failed to convert memory constraint code to constraint id.");
  6600. // Add information to the INLINEASM node to know about this output.
  6601. unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
  6602. OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID);
  6603. AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(),
  6604. MVT::i32));
  6605. AsmNodeOperands.push_back(OpInfo.CallOperand);
  6606. break;
  6607. }
  6608. // Otherwise, this is a register or register class output.
  6609. // Copy the output from the appropriate register. Find a register that
  6610. // we can use.
  6611. if (OpInfo.AssignedRegs.Regs.empty()) {
  6612. emitInlineAsmError(
  6613. CS, "couldn't allocate output register for constraint '" +
  6614. Twine(OpInfo.ConstraintCode) + "'");
  6615. return;
  6616. }
  6617. // If this is an indirect operand, store through the pointer after the
  6618. // asm.
  6619. if (OpInfo.isIndirect) {
  6620. IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs,
  6621. OpInfo.CallOperandVal));
  6622. } else {
  6623. // This is the result value of the call.
  6624. assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
  6625. // Concatenate this output onto the outputs list.
  6626. RetValRegs.append(OpInfo.AssignedRegs);
  6627. }
  6628. // Add information to the INLINEASM node to know that this register is
  6629. // set.
  6630. OpInfo.AssignedRegs
  6631. .AddInlineAsmOperands(OpInfo.isEarlyClobber
  6632. ? InlineAsm::Kind_RegDefEarlyClobber
  6633. : InlineAsm::Kind_RegDef,
  6634. false, 0, getCurSDLoc(), DAG, AsmNodeOperands);
  6635. break;
  6636. case InlineAsm::isInput: {
  6637. SDValue InOperandVal = OpInfo.CallOperand;
  6638. if (OpInfo.isMatchingInputConstraint()) {
  6639. // If this is required to match an output register we have already set,
  6640. // just use its register.
  6641. auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(),
  6642. AsmNodeOperands);
  6643. unsigned OpFlag =
  6644. cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
  6645. if (InlineAsm::isRegDefKind(OpFlag) ||
  6646. InlineAsm::isRegDefEarlyClobberKind(OpFlag)) {
  6647. // Add (OpFlag&0xffff)>>3 registers to MatchedRegs.
  6648. if (OpInfo.isIndirect) {
  6649. // This happens on gcc/testsuite/gcc.dg/pr8788-1.c
  6650. emitInlineAsmError(CS, "inline asm not supported yet:"
  6651. " don't know how to handle tied "
  6652. "indirect register inputs");
  6653. return;
  6654. }
  6655. MVT RegVT = AsmNodeOperands[CurOp+1].getSimpleValueType();
  6656. SmallVector<unsigned, 4> Regs;
  6657. if (!createVirtualRegs(Regs,
  6658. InlineAsm::getNumOperandRegisters(OpFlag),
  6659. RegVT, DAG)) {
  6660. emitInlineAsmError(CS, "inline asm error: This value type register "
  6661. "class is not natively supported!");
  6662. return;
  6663. }
  6664. RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType());
  6665. SDLoc dl = getCurSDLoc();
  6666. // Use the produced MatchedRegs object to
  6667. MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag,
  6668. CS.getInstruction());
  6669. MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse,
  6670. true, OpInfo.getMatchedOperand(), dl,
  6671. DAG, AsmNodeOperands);
  6672. break;
  6673. }
  6674. assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!");
  6675. assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 &&
  6676. "Unexpected number of operands");
  6677. // Add information to the INLINEASM node to know about this input.
  6678. // See InlineAsm.h isUseOperandTiedToDef.
  6679. OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag);
  6680. OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag,
  6681. OpInfo.getMatchedOperand());
  6682. AsmNodeOperands.push_back(DAG.getTargetConstant(
  6683. OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
  6684. AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
  6685. break;
  6686. }
  6687. // Treat indirect 'X' constraint as memory.
  6688. if (OpInfo.ConstraintType == TargetLowering::C_Other &&
  6689. OpInfo.isIndirect)
  6690. OpInfo.ConstraintType = TargetLowering::C_Memory;
  6691. if (OpInfo.ConstraintType == TargetLowering::C_Other) {
  6692. std::vector<SDValue> Ops;
  6693. TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode,
  6694. Ops, DAG);
  6695. if (Ops.empty()) {
  6696. emitInlineAsmError(CS, "invalid operand for inline asm constraint '" +
  6697. Twine(OpInfo.ConstraintCode) + "'");
  6698. return;
  6699. }
  6700. // Add information to the INLINEASM node to know about this input.
  6701. unsigned ResOpType =
  6702. InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size());
  6703. AsmNodeOperands.push_back(DAG.getTargetConstant(
  6704. ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
  6705. AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
  6706. break;
  6707. }
  6708. if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
  6709. assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
  6710. assert(InOperandVal.getValueType() ==
  6711. TLI.getPointerTy(DAG.getDataLayout()) &&
  6712. "Memory operands expect pointer values");
  6713. unsigned ConstraintID =
  6714. TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
  6715. assert(ConstraintID != InlineAsm::Constraint_Unknown &&
  6716. "Failed to convert memory constraint code to constraint id.");
  6717. // Add information to the INLINEASM node to know about this input.
  6718. unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
  6719. ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID);
  6720. AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
  6721. getCurSDLoc(),
  6722. MVT::i32));
  6723. AsmNodeOperands.push_back(InOperandVal);
  6724. break;
  6725. }
  6726. assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
  6727. OpInfo.ConstraintType == TargetLowering::C_Register) &&
  6728. "Unknown constraint type!");
  6729. // TODO: Support this.
  6730. if (OpInfo.isIndirect) {
  6731. emitInlineAsmError(
  6732. CS, "Don't know how to handle indirect register inputs yet "
  6733. "for constraint '" +
  6734. Twine(OpInfo.ConstraintCode) + "'");
  6735. return;
  6736. }
  6737. // Copy the input into the appropriate registers.
  6738. if (OpInfo.AssignedRegs.Regs.empty()) {
  6739. emitInlineAsmError(CS, "couldn't allocate input reg for constraint '" +
  6740. Twine(OpInfo.ConstraintCode) + "'");
  6741. return;
  6742. }
  6743. SDLoc dl = getCurSDLoc();
  6744. OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl,
  6745. Chain, &Flag, CS.getInstruction());
  6746. OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0,
  6747. dl, DAG, AsmNodeOperands);
  6748. break;
  6749. }
  6750. case InlineAsm::isClobber:
  6751. // Add the clobbered value to the operand list, so that the register
  6752. // allocator is aware that the physreg got clobbered.
  6753. if (!OpInfo.AssignedRegs.Regs.empty())
  6754. OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber,
  6755. false, 0, getCurSDLoc(), DAG,
  6756. AsmNodeOperands);
  6757. break;
  6758. }
  6759. }
  6760. // Finish up input operands. Set the input chain and add the flag last.
  6761. AsmNodeOperands[InlineAsm::Op_InputChain] = Chain;
  6762. if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
  6763. Chain = DAG.getNode(ISD::INLINEASM, getCurSDLoc(),
  6764. DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands);
  6765. Flag = Chain.getValue(1);
  6766. // If this asm returns a register value, copy the result from that register
  6767. // and set it as the value of the call.
  6768. if (!RetValRegs.Regs.empty()) {
  6769. SDValue Val = RetValRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(),
  6770. Chain, &Flag, CS.getInstruction());
  6771. // FIXME: Why don't we do this for inline asms with MRVs?
  6772. if (CS.getType()->isSingleValueType() && CS.getType()->isSized()) {
  6773. EVT ResultType = TLI.getValueType(DAG.getDataLayout(), CS.getType());
  6774. // If any of the results of the inline asm is a vector, it may have the
  6775. // wrong width/num elts. This can happen for register classes that can
  6776. // contain multiple different value types. The preg or vreg allocated may
  6777. // not have the same VT as was expected. Convert it to the right type
  6778. // with bit_convert.
  6779. if (ResultType != Val.getValueType() && Val.getValueType().isVector()) {
  6780. Val = DAG.getNode(ISD::BITCAST, getCurSDLoc(),
  6781. ResultType, Val);
  6782. } else if (ResultType != Val.getValueType() &&
  6783. ResultType.isInteger() && Val.getValueType().isInteger()) {
  6784. // If a result value was tied to an input value, the computed result may
  6785. // have a wider width than the expected result. Extract the relevant
  6786. // portion.
  6787. Val = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultType, Val);
  6788. }
  6789. assert(ResultType == Val.getValueType() && "Asm result value mismatch!");
  6790. }
  6791. setValue(CS.getInstruction(), Val);
  6792. // Don't need to use this as a chain in this case.
  6793. if (!IA->hasSideEffects() && !hasMemory && IndirectStoresToEmit.empty())
  6794. return;
  6795. }
  6796. std::vector<std::pair<SDValue, const Value *>> StoresToEmit;
  6797. // Process indirect outputs, first output all of the flagged copies out of
  6798. // physregs.
  6799. for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
  6800. RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
  6801. const Value *Ptr = IndirectStoresToEmit[i].second;
  6802. SDValue OutVal = OutRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(),
  6803. Chain, &Flag, IA);
  6804. StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
  6805. }
  6806. // Emit the non-flagged stores from the physregs.
  6807. SmallVector<SDValue, 8> OutChains;
  6808. for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i) {
  6809. SDValue Val = DAG.getStore(Chain, getCurSDLoc(), StoresToEmit[i].first,
  6810. getValue(StoresToEmit[i].second),
  6811. MachinePointerInfo(StoresToEmit[i].second));
  6812. OutChains.push_back(Val);
  6813. }
  6814. if (!OutChains.empty())
  6815. Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains);
  6816. DAG.setRoot(Chain);
  6817. }
  6818. void SelectionDAGBuilder::emitInlineAsmError(ImmutableCallSite CS,
  6819. const Twine &Message) {
  6820. LLVMContext &Ctx = *DAG.getContext();
  6821. Ctx.emitError(CS.getInstruction(), Message);
  6822. // Make sure we leave the DAG in a valid state
  6823. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  6824. auto VT = TLI.getValueType(DAG.getDataLayout(), CS.getType());
  6825. setValue(CS.getInstruction(), DAG.getUNDEF(VT));
  6826. }
  6827. void SelectionDAGBuilder::visitVAStart(const CallInst &I) {
  6828. DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(),
  6829. MVT::Other, getRoot(),
  6830. getValue(I.getArgOperand(0)),
  6831. DAG.getSrcValue(I.getArgOperand(0))));
  6832. }
  6833. void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) {
  6834. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  6835. const DataLayout &DL = DAG.getDataLayout();
  6836. SDValue V = DAG.getVAArg(TLI.getValueType(DAG.getDataLayout(), I.getType()),
  6837. getCurSDLoc(), getRoot(), getValue(I.getOperand(0)),
  6838. DAG.getSrcValue(I.getOperand(0)),
  6839. DL.getABITypeAlignment(I.getType()));
  6840. setValue(&I, V);
  6841. DAG.setRoot(V.getValue(1));
  6842. }
  6843. void SelectionDAGBuilder::visitVAEnd(const CallInst &I) {
  6844. DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(),
  6845. MVT::Other, getRoot(),
  6846. getValue(I.getArgOperand(0)),
  6847. DAG.getSrcValue(I.getArgOperand(0))));
  6848. }
  6849. void SelectionDAGBuilder::visitVACopy(const CallInst &I) {
  6850. DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(),
  6851. MVT::Other, getRoot(),
  6852. getValue(I.getArgOperand(0)),
  6853. getValue(I.getArgOperand(1)),
  6854. DAG.getSrcValue(I.getArgOperand(0)),
  6855. DAG.getSrcValue(I.getArgOperand(1))));
  6856. }
  6857. SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG,
  6858. const Instruction &I,
  6859. SDValue Op) {
  6860. const MDNode *Range = I.getMetadata(LLVMContext::MD_range);
  6861. if (!Range)
  6862. return Op;
  6863. ConstantRange CR = getConstantRangeFromMetadata(*Range);
  6864. if (CR.isFullSet() || CR.isEmptySet() || CR.isWrappedSet())
  6865. return Op;
  6866. APInt Lo = CR.getUnsignedMin();
  6867. if (!Lo.isMinValue())
  6868. return Op;
  6869. APInt Hi = CR.getUnsignedMax();
  6870. unsigned Bits = Hi.getActiveBits();
  6871. EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
  6872. SDLoc SL = getCurSDLoc();
  6873. SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op,
  6874. DAG.getValueType(SmallVT));
  6875. unsigned NumVals = Op.getNode()->getNumValues();
  6876. if (NumVals == 1)
  6877. return ZExt;
  6878. SmallVector<SDValue, 4> Ops;
  6879. Ops.push_back(ZExt);
  6880. for (unsigned I = 1; I != NumVals; ++I)
  6881. Ops.push_back(Op.getValue(I));
  6882. return DAG.getMergeValues(Ops, SL);
  6883. }
  6884. /// Populate a CallLowerinInfo (into \p CLI) based on the properties of
  6885. /// the call being lowered.
  6886. ///
  6887. /// This is a helper for lowering intrinsics that follow a target calling
  6888. /// convention or require stack pointer adjustment. Only a subset of the
  6889. /// intrinsic's operands need to participate in the calling convention.
  6890. void SelectionDAGBuilder::populateCallLoweringInfo(
  6891. TargetLowering::CallLoweringInfo &CLI, ImmutableCallSite CS,
  6892. unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy,
  6893. bool IsPatchPoint) {
  6894. TargetLowering::ArgListTy Args;
  6895. Args.reserve(NumArgs);
  6896. // Populate the argument list.
  6897. // Attributes for args start at offset 1, after the return attribute.
  6898. for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs;
  6899. ArgI != ArgE; ++ArgI) {
  6900. const Value *V = CS->getOperand(ArgI);
  6901. assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic.");
  6902. TargetLowering::ArgListEntry Entry;
  6903. Entry.Node = getValue(V);
  6904. Entry.Ty = V->getType();
  6905. Entry.setAttributes(&CS, ArgI);
  6906. Args.push_back(Entry);
  6907. }
  6908. CLI.setDebugLoc(getCurSDLoc())
  6909. .setChain(getRoot())
  6910. .setCallee(CS.getCallingConv(), ReturnTy, Callee, std::move(Args))
  6911. .setDiscardResult(CS->use_empty())
  6912. .setIsPatchPoint(IsPatchPoint);
  6913. }
  6914. /// Add a stack map intrinsic call's live variable operands to a stackmap
  6915. /// or patchpoint target node's operand list.
  6916. ///
  6917. /// Constants are converted to TargetConstants purely as an optimization to
  6918. /// avoid constant materialization and register allocation.
  6919. ///
  6920. /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not
  6921. /// generate addess computation nodes, and so ExpandISelPseudo can convert the
  6922. /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids
  6923. /// address materialization and register allocation, but may also be required
  6924. /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an
  6925. /// alloca in the entry block, then the runtime may assume that the alloca's
  6926. /// StackMap location can be read immediately after compilation and that the
  6927. /// location is valid at any point during execution (this is similar to the
  6928. /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were
  6929. /// only available in a register, then the runtime would need to trap when
  6930. /// execution reaches the StackMap in order to read the alloca's location.
  6931. static void addStackMapLiveVars(ImmutableCallSite CS, unsigned StartIdx,
  6932. const SDLoc &DL, SmallVectorImpl<SDValue> &Ops,
  6933. SelectionDAGBuilder &Builder) {
  6934. for (unsigned i = StartIdx, e = CS.arg_size(); i != e; ++i) {
  6935. SDValue OpVal = Builder.getValue(CS.getArgument(i));
  6936. if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(OpVal)) {
  6937. Ops.push_back(
  6938. Builder.DAG.getTargetConstant(StackMaps::ConstantOp, DL, MVT::i64));
  6939. Ops.push_back(
  6940. Builder.DAG.getTargetConstant(C->getSExtValue(), DL, MVT::i64));
  6941. } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(OpVal)) {
  6942. const TargetLowering &TLI = Builder.DAG.getTargetLoweringInfo();
  6943. Ops.push_back(Builder.DAG.getTargetFrameIndex(
  6944. FI->getIndex(), TLI.getFrameIndexTy(Builder.DAG.getDataLayout())));
  6945. } else
  6946. Ops.push_back(OpVal);
  6947. }
  6948. }
  6949. /// Lower llvm.experimental.stackmap directly to its target opcode.
  6950. void SelectionDAGBuilder::visitStackmap(const CallInst &CI) {
  6951. // void @llvm.experimental.stackmap(i32 <id>, i32 <numShadowBytes>,
  6952. // [live variables...])
  6953. assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value.");
  6954. SDValue Chain, InFlag, Callee, NullPtr;
  6955. SmallVector<SDValue, 32> Ops;
  6956. SDLoc DL = getCurSDLoc();
  6957. Callee = getValue(CI.getCalledValue());
  6958. NullPtr = DAG.getIntPtrConstant(0, DL, true);
  6959. // The stackmap intrinsic only records the live variables (the arguemnts
  6960. // passed to it) and emits NOPS (if requested). Unlike the patchpoint
  6961. // intrinsic, this won't be lowered to a function call. This means we don't
  6962. // have to worry about calling conventions and target specific lowering code.
  6963. // Instead we perform the call lowering right here.
  6964. //
  6965. // chain, flag = CALLSEQ_START(chain, 0, 0)
  6966. // chain, flag = STACKMAP(id, nbytes, ..., chain, flag)
  6967. // chain, flag = CALLSEQ_END(chain, 0, 0, flag)
  6968. //
  6969. Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL);
  6970. InFlag = Chain.getValue(1);
  6971. // Add the <id> and <numBytes> constants.
  6972. SDValue IDVal = getValue(CI.getOperand(PatchPointOpers::IDPos));
  6973. Ops.push_back(DAG.getTargetConstant(
  6974. cast<ConstantSDNode>(IDVal)->getZExtValue(), DL, MVT::i64));
  6975. SDValue NBytesVal = getValue(CI.getOperand(PatchPointOpers::NBytesPos));
  6976. Ops.push_back(DAG.getTargetConstant(
  6977. cast<ConstantSDNode>(NBytesVal)->getZExtValue(), DL,
  6978. MVT::i32));
  6979. // Push live variables for the stack map.
  6980. addStackMapLiveVars(&CI, 2, DL, Ops, *this);
  6981. // We are not pushing any register mask info here on the operands list,
  6982. // because the stackmap doesn't clobber anything.
  6983. // Push the chain and the glue flag.
  6984. Ops.push_back(Chain);
  6985. Ops.push_back(InFlag);
  6986. // Create the STACKMAP node.
  6987. SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
  6988. SDNode *SM = DAG.getMachineNode(TargetOpcode::STACKMAP, DL, NodeTys, Ops);
  6989. Chain = SDValue(SM, 0);
  6990. InFlag = Chain.getValue(1);
  6991. Chain = DAG.getCALLSEQ_END(Chain, NullPtr, NullPtr, InFlag, DL);
  6992. // Stackmaps don't generate values, so nothing goes into the NodeMap.
  6993. // Set the root to the target-lowered call chain.
  6994. DAG.setRoot(Chain);
  6995. // Inform the Frame Information that we have a stackmap in this function.
  6996. FuncInfo.MF->getFrameInfo().setHasStackMap();
  6997. }
  6998. /// Lower llvm.experimental.patchpoint directly to its target opcode.
  6999. void SelectionDAGBuilder::visitPatchpoint(ImmutableCallSite CS,
  7000. const BasicBlock *EHPadBB) {
  7001. // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>,
  7002. // i32 <numBytes>,
  7003. // i8* <target>,
  7004. // i32 <numArgs>,
  7005. // [Args...],
  7006. // [live variables...])
  7007. CallingConv::ID CC = CS.getCallingConv();
  7008. bool IsAnyRegCC = CC == CallingConv::AnyReg;
  7009. bool HasDef = !CS->getType()->isVoidTy();
  7010. SDLoc dl = getCurSDLoc();
  7011. SDValue Callee = getValue(CS->getOperand(PatchPointOpers::TargetPos));
  7012. // Handle immediate and symbolic callees.
  7013. if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee))
  7014. Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl,
  7015. /*isTarget=*/true);
  7016. else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee))
  7017. Callee = DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(),
  7018. SDLoc(SymbolicCallee),
  7019. SymbolicCallee->getValueType(0));
  7020. // Get the real number of arguments participating in the call <numArgs>
  7021. SDValue NArgVal = getValue(CS.getArgument(PatchPointOpers::NArgPos));
  7022. unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue();
  7023. // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs>
  7024. // Intrinsics include all meta-operands up to but not including CC.
  7025. unsigned NumMetaOpers = PatchPointOpers::CCPos;
  7026. assert(CS.arg_size() >= NumMetaOpers + NumArgs &&
  7027. "Not enough arguments provided to the patchpoint intrinsic");
  7028. // For AnyRegCC the arguments are lowered later on manually.
  7029. unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs;
  7030. Type *ReturnTy =
  7031. IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CS->getType();
  7032. TargetLowering::CallLoweringInfo CLI(DAG);
  7033. populateCallLoweringInfo(CLI, CS, NumMetaOpers, NumCallArgs, Callee, ReturnTy,
  7034. true);
  7035. std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
  7036. SDNode *CallEnd = Result.second.getNode();
  7037. if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg))
  7038. CallEnd = CallEnd->getOperand(0).getNode();
  7039. /// Get a call instruction from the call sequence chain.
  7040. /// Tail calls are not allowed.
  7041. assert(CallEnd->getOpcode() == ISD::CALLSEQ_END &&
  7042. "Expected a callseq node.");
  7043. SDNode *Call = CallEnd->getOperand(0).getNode();
  7044. bool HasGlue = Call->getGluedNode();
  7045. // Replace the target specific call node with the patchable intrinsic.
  7046. SmallVector<SDValue, 8> Ops;
  7047. // Add the <id> and <numBytes> constants.
  7048. SDValue IDVal = getValue(CS->getOperand(PatchPointOpers::IDPos));
  7049. Ops.push_back(DAG.getTargetConstant(
  7050. cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64));
  7051. SDValue NBytesVal = getValue(CS->getOperand(PatchPointOpers::NBytesPos));
  7052. Ops.push_back(DAG.getTargetConstant(
  7053. cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl,
  7054. MVT::i32));
  7055. // Add the callee.
  7056. Ops.push_back(Callee);
  7057. // Adjust <numArgs> to account for any arguments that have been passed on the
  7058. // stack instead.
  7059. // Call Node: Chain, Target, {Args}, RegMask, [Glue]
  7060. unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3);
  7061. NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs;
  7062. Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32));
  7063. // Add the calling convention
  7064. Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32));
  7065. // Add the arguments we omitted previously. The register allocator should
  7066. // place these in any free register.
  7067. if (IsAnyRegCC)
  7068. for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i)
  7069. Ops.push_back(getValue(CS.getArgument(i)));
  7070. // Push the arguments from the call instruction up to the register mask.
  7071. SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1;
  7072. Ops.append(Call->op_begin() + 2, e);
  7073. // Push live variables for the stack map.
  7074. addStackMapLiveVars(CS, NumMetaOpers + NumArgs, dl, Ops, *this);
  7075. // Push the register mask info.
  7076. if (HasGlue)
  7077. Ops.push_back(*(Call->op_end()-2));
  7078. else
  7079. Ops.push_back(*(Call->op_end()-1));
  7080. // Push the chain (this is originally the first operand of the call, but
  7081. // becomes now the last or second to last operand).
  7082. Ops.push_back(*(Call->op_begin()));
  7083. // Push the glue flag (last operand).
  7084. if (HasGlue)
  7085. Ops.push_back(*(Call->op_end()-1));
  7086. SDVTList NodeTys;
  7087. if (IsAnyRegCC && HasDef) {
  7088. // Create the return types based on the intrinsic definition
  7089. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  7090. SmallVector<EVT, 3> ValueVTs;
  7091. ComputeValueVTs(TLI, DAG.getDataLayout(), CS->getType(), ValueVTs);
  7092. assert(ValueVTs.size() == 1 && "Expected only one return value type.");
  7093. // There is always a chain and a glue type at the end
  7094. ValueVTs.push_back(MVT::Other);
  7095. ValueVTs.push_back(MVT::Glue);
  7096. NodeTys = DAG.getVTList(ValueVTs);
  7097. } else
  7098. NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
  7099. // Replace the target specific call node with a PATCHPOINT node.
  7100. MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHPOINT,
  7101. dl, NodeTys, Ops);
  7102. // Update the NodeMap.
  7103. if (HasDef) {
  7104. if (IsAnyRegCC)
  7105. setValue(CS.getInstruction(), SDValue(MN, 0));
  7106. else
  7107. setValue(CS.getInstruction(), Result.first);
  7108. }
  7109. // Fixup the consumers of the intrinsic. The chain and glue may be used in the
  7110. // call sequence. Furthermore the location of the chain and glue can change
  7111. // when the AnyReg calling convention is used and the intrinsic returns a
  7112. // value.
  7113. if (IsAnyRegCC && HasDef) {
  7114. SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)};
  7115. SDValue To[] = {SDValue(MN, 1), SDValue(MN, 2)};
  7116. DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
  7117. } else
  7118. DAG.ReplaceAllUsesWith(Call, MN);
  7119. DAG.DeleteNode(Call);
  7120. // Inform the Frame Information that we have a patchpoint in this function.
  7121. FuncInfo.MF->getFrameInfo().setHasPatchPoint();
  7122. }
  7123. void SelectionDAGBuilder::visitVectorReduce(const CallInst &I,
  7124. unsigned Intrinsic) {
  7125. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  7126. SDValue Op1 = getValue(I.getArgOperand(0));
  7127. SDValue Op2;
  7128. if (I.getNumArgOperands() > 1)
  7129. Op2 = getValue(I.getArgOperand(1));
  7130. SDLoc dl = getCurSDLoc();
  7131. EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  7132. SDValue Res;
  7133. FastMathFlags FMF;
  7134. if (isa<FPMathOperator>(I))
  7135. FMF = I.getFastMathFlags();
  7136. SDNodeFlags SDFlags;
  7137. SDFlags.setNoNaNs(FMF.noNaNs());
  7138. switch (Intrinsic) {
  7139. case Intrinsic::experimental_vector_reduce_fadd:
  7140. if (FMF.isFast())
  7141. Res = DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2);
  7142. else
  7143. Res = DAG.getNode(ISD::VECREDUCE_STRICT_FADD, dl, VT, Op1, Op2);
  7144. break;
  7145. case Intrinsic::experimental_vector_reduce_fmul:
  7146. if (FMF.isFast())
  7147. Res = DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2);
  7148. else
  7149. Res = DAG.getNode(ISD::VECREDUCE_STRICT_FMUL, dl, VT, Op1, Op2);
  7150. break;
  7151. case Intrinsic::experimental_vector_reduce_add:
  7152. Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1);
  7153. break;
  7154. case Intrinsic::experimental_vector_reduce_mul:
  7155. Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1);
  7156. break;
  7157. case Intrinsic::experimental_vector_reduce_and:
  7158. Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1);
  7159. break;
  7160. case Intrinsic::experimental_vector_reduce_or:
  7161. Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1);
  7162. break;
  7163. case Intrinsic::experimental_vector_reduce_xor:
  7164. Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1);
  7165. break;
  7166. case Intrinsic::experimental_vector_reduce_smax:
  7167. Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1);
  7168. break;
  7169. case Intrinsic::experimental_vector_reduce_smin:
  7170. Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1);
  7171. break;
  7172. case Intrinsic::experimental_vector_reduce_umax:
  7173. Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1);
  7174. break;
  7175. case Intrinsic::experimental_vector_reduce_umin:
  7176. Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1);
  7177. break;
  7178. case Intrinsic::experimental_vector_reduce_fmax:
  7179. Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1, SDFlags);
  7180. break;
  7181. case Intrinsic::experimental_vector_reduce_fmin:
  7182. Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1, SDFlags);
  7183. break;
  7184. default:
  7185. llvm_unreachable("Unhandled vector reduce intrinsic");
  7186. }
  7187. setValue(&I, Res);
  7188. }
  7189. /// Returns an AttributeList representing the attributes applied to the return
  7190. /// value of the given call.
  7191. static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) {
  7192. SmallVector<Attribute::AttrKind, 2> Attrs;
  7193. if (CLI.RetSExt)
  7194. Attrs.push_back(Attribute::SExt);
  7195. if (CLI.RetZExt)
  7196. Attrs.push_back(Attribute::ZExt);
  7197. if (CLI.IsInReg)
  7198. Attrs.push_back(Attribute::InReg);
  7199. return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex,
  7200. Attrs);
  7201. }
  7202. /// TargetLowering::LowerCallTo - This is the default LowerCallTo
  7203. /// implementation, which just calls LowerCall.
  7204. /// FIXME: When all targets are
  7205. /// migrated to using LowerCall, this hook should be integrated into SDISel.
  7206. std::pair<SDValue, SDValue>
  7207. TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const {
  7208. // Handle the incoming return values from the call.
  7209. CLI.Ins.clear();
  7210. Type *OrigRetTy = CLI.RetTy;
  7211. SmallVector<EVT, 4> RetTys;
  7212. SmallVector<uint64_t, 4> Offsets;
  7213. auto &DL = CLI.DAG.getDataLayout();
  7214. ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets);
  7215. if (CLI.IsPostTypeLegalization) {
  7216. // If we are lowering a libcall after legalization, split the return type.
  7217. SmallVector<EVT, 4> OldRetTys = std::move(RetTys);
  7218. SmallVector<uint64_t, 4> OldOffsets = std::move(Offsets);
  7219. for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) {
  7220. EVT RetVT = OldRetTys[i];
  7221. uint64_t Offset = OldOffsets[i];
  7222. MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT);
  7223. unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT);
  7224. unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8;
  7225. RetTys.append(NumRegs, RegisterVT);
  7226. for (unsigned j = 0; j != NumRegs; ++j)
  7227. Offsets.push_back(Offset + j * RegisterVTByteSZ);
  7228. }
  7229. }
  7230. SmallVector<ISD::OutputArg, 4> Outs;
  7231. GetReturnInfo(CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL);
  7232. bool CanLowerReturn =
  7233. this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(),
  7234. CLI.IsVarArg, Outs, CLI.RetTy->getContext());
  7235. SDValue DemoteStackSlot;
  7236. int DemoteStackIdx = -100;
  7237. if (!CanLowerReturn) {
  7238. // FIXME: equivalent assert?
  7239. // assert(!CS.hasInAllocaArgument() &&
  7240. // "sret demotion is incompatible with inalloca");
  7241. uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy);
  7242. unsigned Align = DL.getPrefTypeAlignment(CLI.RetTy);
  7243. MachineFunction &MF = CLI.DAG.getMachineFunction();
  7244. DemoteStackIdx = MF.getFrameInfo().CreateStackObject(TySize, Align, false);
  7245. Type *StackSlotPtrType = PointerType::getUnqual(CLI.RetTy);
  7246. DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL));
  7247. ArgListEntry Entry;
  7248. Entry.Node = DemoteStackSlot;
  7249. Entry.Ty = StackSlotPtrType;
  7250. Entry.IsSExt = false;
  7251. Entry.IsZExt = false;
  7252. Entry.IsInReg = false;
  7253. Entry.IsSRet = true;
  7254. Entry.IsNest = false;
  7255. Entry.IsByVal = false;
  7256. Entry.IsReturned = false;
  7257. Entry.IsSwiftSelf = false;
  7258. Entry.IsSwiftError = false;
  7259. Entry.Alignment = Align;
  7260. CLI.getArgs().insert(CLI.getArgs().begin(), Entry);
  7261. CLI.NumFixedArgs += 1;
  7262. CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext());
  7263. // sret demotion isn't compatible with tail-calls, since the sret argument
  7264. // points into the callers stack frame.
  7265. CLI.IsTailCall = false;
  7266. } else {
  7267. for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
  7268. EVT VT = RetTys[I];
  7269. MVT RegisterVT =
  7270. getRegisterTypeForCallingConv(CLI.RetTy->getContext(), VT);
  7271. unsigned NumRegs =
  7272. getNumRegistersForCallingConv(CLI.RetTy->getContext(), VT);
  7273. for (unsigned i = 0; i != NumRegs; ++i) {
  7274. ISD::InputArg MyFlags;
  7275. MyFlags.VT = RegisterVT;
  7276. MyFlags.ArgVT = VT;
  7277. MyFlags.Used = CLI.IsReturnValueUsed;
  7278. if (CLI.RetSExt)
  7279. MyFlags.Flags.setSExt();
  7280. if (CLI.RetZExt)
  7281. MyFlags.Flags.setZExt();
  7282. if (CLI.IsInReg)
  7283. MyFlags.Flags.setInReg();
  7284. CLI.Ins.push_back(MyFlags);
  7285. }
  7286. }
  7287. }
  7288. // We push in swifterror return as the last element of CLI.Ins.
  7289. ArgListTy &Args = CLI.getArgs();
  7290. if (supportSwiftError()) {
  7291. for (unsigned i = 0, e = Args.size(); i != e; ++i) {
  7292. if (Args[i].IsSwiftError) {
  7293. ISD::InputArg MyFlags;
  7294. MyFlags.VT = getPointerTy(DL);
  7295. MyFlags.ArgVT = EVT(getPointerTy(DL));
  7296. MyFlags.Flags.setSwiftError();
  7297. CLI.Ins.push_back(MyFlags);
  7298. }
  7299. }
  7300. }
  7301. // Handle all of the outgoing arguments.
  7302. CLI.Outs.clear();
  7303. CLI.OutVals.clear();
  7304. for (unsigned i = 0, e = Args.size(); i != e; ++i) {
  7305. SmallVector<EVT, 4> ValueVTs;
  7306. ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs);
  7307. // FIXME: Split arguments if CLI.IsPostTypeLegalization
  7308. Type *FinalType = Args[i].Ty;
  7309. if (Args[i].IsByVal)
  7310. FinalType = cast<PointerType>(Args[i].Ty)->getElementType();
  7311. bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
  7312. FinalType, CLI.CallConv, CLI.IsVarArg);
  7313. for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues;
  7314. ++Value) {
  7315. EVT VT = ValueVTs[Value];
  7316. Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext());
  7317. SDValue Op = SDValue(Args[i].Node.getNode(),
  7318. Args[i].Node.getResNo() + Value);
  7319. ISD::ArgFlagsTy Flags;
  7320. // Certain targets (such as MIPS), may have a different ABI alignment
  7321. // for a type depending on the context. Give the target a chance to
  7322. // specify the alignment it wants.
  7323. unsigned OriginalAlignment = getABIAlignmentForCallingConv(ArgTy, DL);
  7324. if (Args[i].IsZExt)
  7325. Flags.setZExt();
  7326. if (Args[i].IsSExt)
  7327. Flags.setSExt();
  7328. if (Args[i].IsInReg) {
  7329. // If we are using vectorcall calling convention, a structure that is
  7330. // passed InReg - is surely an HVA
  7331. if (CLI.CallConv == CallingConv::X86_VectorCall &&
  7332. isa<StructType>(FinalType)) {
  7333. // The first value of a structure is marked
  7334. if (0 == Value)
  7335. Flags.setHvaStart();
  7336. Flags.setHva();
  7337. }
  7338. // Set InReg Flag
  7339. Flags.setInReg();
  7340. }
  7341. if (Args[i].IsSRet)
  7342. Flags.setSRet();
  7343. if (Args[i].IsSwiftSelf)
  7344. Flags.setSwiftSelf();
  7345. if (Args[i].IsSwiftError)
  7346. Flags.setSwiftError();
  7347. if (Args[i].IsByVal)
  7348. Flags.setByVal();
  7349. if (Args[i].IsInAlloca) {
  7350. Flags.setInAlloca();
  7351. // Set the byval flag for CCAssignFn callbacks that don't know about
  7352. // inalloca. This way we can know how many bytes we should've allocated
  7353. // and how many bytes a callee cleanup function will pop. If we port
  7354. // inalloca to more targets, we'll have to add custom inalloca handling
  7355. // in the various CC lowering callbacks.
  7356. Flags.setByVal();
  7357. }
  7358. if (Args[i].IsByVal || Args[i].IsInAlloca) {
  7359. PointerType *Ty = cast<PointerType>(Args[i].Ty);
  7360. Type *ElementTy = Ty->getElementType();
  7361. Flags.setByValSize(DL.getTypeAllocSize(ElementTy));
  7362. // For ByVal, alignment should come from FE. BE will guess if this
  7363. // info is not there but there are cases it cannot get right.
  7364. unsigned FrameAlign;
  7365. if (Args[i].Alignment)
  7366. FrameAlign = Args[i].Alignment;
  7367. else
  7368. FrameAlign = getByValTypeAlignment(ElementTy, DL);
  7369. Flags.setByValAlign(FrameAlign);
  7370. }
  7371. if (Args[i].IsNest)
  7372. Flags.setNest();
  7373. if (NeedsRegBlock)
  7374. Flags.setInConsecutiveRegs();
  7375. Flags.setOrigAlign(OriginalAlignment);
  7376. MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), VT);
  7377. unsigned NumParts =
  7378. getNumRegistersForCallingConv(CLI.RetTy->getContext(), VT);
  7379. SmallVector<SDValue, 4> Parts(NumParts);
  7380. ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
  7381. if (Args[i].IsSExt)
  7382. ExtendKind = ISD::SIGN_EXTEND;
  7383. else if (Args[i].IsZExt)
  7384. ExtendKind = ISD::ZERO_EXTEND;
  7385. // Conservatively only handle 'returned' on non-vectors that can be lowered,
  7386. // for now.
  7387. if (Args[i].IsReturned && !Op.getValueType().isVector() &&
  7388. CanLowerReturn) {
  7389. assert(CLI.RetTy == Args[i].Ty && RetTys.size() == NumValues &&
  7390. "unexpected use of 'returned'");
  7391. // Before passing 'returned' to the target lowering code, ensure that
  7392. // either the register MVT and the actual EVT are the same size or that
  7393. // the return value and argument are extended in the same way; in these
  7394. // cases it's safe to pass the argument register value unchanged as the
  7395. // return register value (although it's at the target's option whether
  7396. // to do so)
  7397. // TODO: allow code generation to take advantage of partially preserved
  7398. // registers rather than clobbering the entire register when the
  7399. // parameter extension method is not compatible with the return
  7400. // extension method
  7401. if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) ||
  7402. (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt &&
  7403. CLI.RetZExt == Args[i].IsZExt))
  7404. Flags.setReturned();
  7405. }
  7406. getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT,
  7407. CLI.CS.getInstruction(), ExtendKind, true);
  7408. for (unsigned j = 0; j != NumParts; ++j) {
  7409. // if it isn't first piece, alignment must be 1
  7410. ISD::OutputArg MyFlags(Flags, Parts[j].getValueType(), VT,
  7411. i < CLI.NumFixedArgs,
  7412. i, j*Parts[j].getValueType().getStoreSize());
  7413. if (NumParts > 1 && j == 0)
  7414. MyFlags.Flags.setSplit();
  7415. else if (j != 0) {
  7416. MyFlags.Flags.setOrigAlign(1);
  7417. if (j == NumParts - 1)
  7418. MyFlags.Flags.setSplitEnd();
  7419. }
  7420. CLI.Outs.push_back(MyFlags);
  7421. CLI.OutVals.push_back(Parts[j]);
  7422. }
  7423. if (NeedsRegBlock && Value == NumValues - 1)
  7424. CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast();
  7425. }
  7426. }
  7427. SmallVector<SDValue, 4> InVals;
  7428. CLI.Chain = LowerCall(CLI, InVals);
  7429. // Update CLI.InVals to use outside of this function.
  7430. CLI.InVals = InVals;
  7431. // Verify that the target's LowerCall behaved as expected.
  7432. assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other &&
  7433. "LowerCall didn't return a valid chain!");
  7434. assert((!CLI.IsTailCall || InVals.empty()) &&
  7435. "LowerCall emitted a return value for a tail call!");
  7436. assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) &&
  7437. "LowerCall didn't emit the correct number of values!");
  7438. // For a tail call, the return value is merely live-out and there aren't
  7439. // any nodes in the DAG representing it. Return a special value to
  7440. // indicate that a tail call has been emitted and no more Instructions
  7441. // should be processed in the current block.
  7442. if (CLI.IsTailCall) {
  7443. CLI.DAG.setRoot(CLI.Chain);
  7444. return std::make_pair(SDValue(), SDValue());
  7445. }
  7446. #ifndef NDEBUG
  7447. for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) {
  7448. assert(InVals[i].getNode() && "LowerCall emitted a null value!");
  7449. assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() &&
  7450. "LowerCall emitted a value with the wrong type!");
  7451. }
  7452. #endif
  7453. SmallVector<SDValue, 4> ReturnValues;
  7454. if (!CanLowerReturn) {
  7455. // The instruction result is the result of loading from the
  7456. // hidden sret parameter.
  7457. SmallVector<EVT, 1> PVTs;
  7458. Type *PtrRetTy = OrigRetTy->getPointerTo(DL.getAllocaAddrSpace());
  7459. ComputeValueVTs(*this, DL, PtrRetTy, PVTs);
  7460. assert(PVTs.size() == 1 && "Pointers should fit in one register");
  7461. EVT PtrVT = PVTs[0];
  7462. unsigned NumValues = RetTys.size();
  7463. ReturnValues.resize(NumValues);
  7464. SmallVector<SDValue, 4> Chains(NumValues);
  7465. // An aggregate return value cannot wrap around the address space, so
  7466. // offsets to its parts don't wrap either.
  7467. SDNodeFlags Flags;
  7468. Flags.setNoUnsignedWrap(true);
  7469. for (unsigned i = 0; i < NumValues; ++i) {
  7470. SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot,
  7471. CLI.DAG.getConstant(Offsets[i], CLI.DL,
  7472. PtrVT), Flags);
  7473. SDValue L = CLI.DAG.getLoad(
  7474. RetTys[i], CLI.DL, CLI.Chain, Add,
  7475. MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(),
  7476. DemoteStackIdx, Offsets[i]),
  7477. /* Alignment = */ 1);
  7478. ReturnValues[i] = L;
  7479. Chains[i] = L.getValue(1);
  7480. }
  7481. CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains);
  7482. } else {
  7483. // Collect the legal value parts into potentially illegal values
  7484. // that correspond to the original function's return values.
  7485. Optional<ISD::NodeType> AssertOp;
  7486. if (CLI.RetSExt)
  7487. AssertOp = ISD::AssertSext;
  7488. else if (CLI.RetZExt)
  7489. AssertOp = ISD::AssertZext;
  7490. unsigned CurReg = 0;
  7491. for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
  7492. EVT VT = RetTys[I];
  7493. MVT RegisterVT =
  7494. getRegisterTypeForCallingConv(CLI.RetTy->getContext(), VT);
  7495. unsigned NumRegs =
  7496. getNumRegistersForCallingConv(CLI.RetTy->getContext(), VT);
  7497. ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg],
  7498. NumRegs, RegisterVT, VT, nullptr,
  7499. AssertOp, true));
  7500. CurReg += NumRegs;
  7501. }
  7502. // For a function returning void, there is no return value. We can't create
  7503. // such a node, so we just return a null return value in that case. In
  7504. // that case, nothing will actually look at the value.
  7505. if (ReturnValues.empty())
  7506. return std::make_pair(SDValue(), CLI.Chain);
  7507. }
  7508. SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL,
  7509. CLI.DAG.getVTList(RetTys), ReturnValues);
  7510. return std::make_pair(Res, CLI.Chain);
  7511. }
  7512. void TargetLowering::LowerOperationWrapper(SDNode *N,
  7513. SmallVectorImpl<SDValue> &Results,
  7514. SelectionDAG &DAG) const {
  7515. if (SDValue Res = LowerOperation(SDValue(N, 0), DAG))
  7516. Results.push_back(Res);
  7517. }
  7518. SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
  7519. llvm_unreachable("LowerOperation not implemented for this target!");
  7520. }
  7521. void
  7522. SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) {
  7523. SDValue Op = getNonRegisterValue(V);
  7524. assert((Op.getOpcode() != ISD::CopyFromReg ||
  7525. cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
  7526. "Copy from a reg to the same reg!");
  7527. assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg");
  7528. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  7529. // If this is an InlineAsm we have to match the registers required, not the
  7530. // notional registers required by the type.
  7531. RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg,
  7532. V->getType(), isABIRegCopy(V));
  7533. SDValue Chain = DAG.getEntryNode();
  7534. ISD::NodeType ExtendType = (FuncInfo.PreferredExtendType.find(V) ==
  7535. FuncInfo.PreferredExtendType.end())
  7536. ? ISD::ANY_EXTEND
  7537. : FuncInfo.PreferredExtendType[V];
  7538. RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType);
  7539. PendingExports.push_back(Chain);
  7540. }
  7541. #include "llvm/CodeGen/SelectionDAGISel.h"
  7542. /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
  7543. /// entry block, return true. This includes arguments used by switches, since
  7544. /// the switch may expand into multiple basic blocks.
  7545. static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) {
  7546. // With FastISel active, we may be splitting blocks, so force creation
  7547. // of virtual registers for all non-dead arguments.
  7548. if (FastISel)
  7549. return A->use_empty();
  7550. const BasicBlock &Entry = A->getParent()->front();
  7551. for (const User *U : A->users())
  7552. if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U))
  7553. return false; // Use not in entry block.
  7554. return true;
  7555. }
  7556. using ArgCopyElisionMapTy =
  7557. DenseMap<const Argument *,
  7558. std::pair<const AllocaInst *, const StoreInst *>>;
  7559. /// Scan the entry block of the function in FuncInfo for arguments that look
  7560. /// like copies into a local alloca. Record any copied arguments in
  7561. /// ArgCopyElisionCandidates.
  7562. static void
  7563. findArgumentCopyElisionCandidates(const DataLayout &DL,
  7564. FunctionLoweringInfo *FuncInfo,
  7565. ArgCopyElisionMapTy &ArgCopyElisionCandidates) {
  7566. // Record the state of every static alloca used in the entry block. Argument
  7567. // allocas are all used in the entry block, so we need approximately as many
  7568. // entries as we have arguments.
  7569. enum StaticAllocaInfo { Unknown, Clobbered, Elidable };
  7570. SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas;
  7571. unsigned NumArgs = FuncInfo->Fn->arg_size();
  7572. StaticAllocas.reserve(NumArgs * 2);
  7573. auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * {
  7574. if (!V)
  7575. return nullptr;
  7576. V = V->stripPointerCasts();
  7577. const auto *AI = dyn_cast<AllocaInst>(V);
  7578. if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI))
  7579. return nullptr;
  7580. auto Iter = StaticAllocas.insert({AI, Unknown});
  7581. return &Iter.first->second;
  7582. };
  7583. // Look for stores of arguments to static allocas. Look through bitcasts and
  7584. // GEPs to handle type coercions, as long as the alloca is fully initialized
  7585. // by the store. Any non-store use of an alloca escapes it and any subsequent
  7586. // unanalyzed store might write it.
  7587. // FIXME: Handle structs initialized with multiple stores.
  7588. for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) {
  7589. // Look for stores, and handle non-store uses conservatively.
  7590. const auto *SI = dyn_cast<StoreInst>(&I);
  7591. if (!SI) {
  7592. // We will look through cast uses, so ignore them completely.
  7593. if (I.isCast())
  7594. continue;
  7595. // Ignore debug info intrinsics, they don't escape or store to allocas.
  7596. if (isa<DbgInfoIntrinsic>(I))
  7597. continue;
  7598. // This is an unknown instruction. Assume it escapes or writes to all
  7599. // static alloca operands.
  7600. for (const Use &U : I.operands()) {
  7601. if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U))
  7602. *Info = StaticAllocaInfo::Clobbered;
  7603. }
  7604. continue;
  7605. }
  7606. // If the stored value is a static alloca, mark it as escaped.
  7607. if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand()))
  7608. *Info = StaticAllocaInfo::Clobbered;
  7609. // Check if the destination is a static alloca.
  7610. const Value *Dst = SI->getPointerOperand()->stripPointerCasts();
  7611. StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst);
  7612. if (!Info)
  7613. continue;
  7614. const AllocaInst *AI = cast<AllocaInst>(Dst);
  7615. // Skip allocas that have been initialized or clobbered.
  7616. if (*Info != StaticAllocaInfo::Unknown)
  7617. continue;
  7618. // Check if the stored value is an argument, and that this store fully
  7619. // initializes the alloca. Don't elide copies from the same argument twice.
  7620. const Value *Val = SI->getValueOperand()->stripPointerCasts();
  7621. const auto *Arg = dyn_cast<Argument>(Val);
  7622. if (!Arg || Arg->hasInAllocaAttr() || Arg->hasByValAttr() ||
  7623. Arg->getType()->isEmptyTy() ||
  7624. DL.getTypeStoreSize(Arg->getType()) !=
  7625. DL.getTypeAllocSize(AI->getAllocatedType()) ||
  7626. ArgCopyElisionCandidates.count(Arg)) {
  7627. *Info = StaticAllocaInfo::Clobbered;
  7628. continue;
  7629. }
  7630. DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI << '\n');
  7631. // Mark this alloca and store for argument copy elision.
  7632. *Info = StaticAllocaInfo::Elidable;
  7633. ArgCopyElisionCandidates.insert({Arg, {AI, SI}});
  7634. // Stop scanning if we've seen all arguments. This will happen early in -O0
  7635. // builds, which is useful, because -O0 builds have large entry blocks and
  7636. // many allocas.
  7637. if (ArgCopyElisionCandidates.size() == NumArgs)
  7638. break;
  7639. }
  7640. }
  7641. /// Try to elide argument copies from memory into a local alloca. Succeeds if
  7642. /// ArgVal is a load from a suitable fixed stack object.
  7643. static void tryToElideArgumentCopy(
  7644. FunctionLoweringInfo *FuncInfo, SmallVectorImpl<SDValue> &Chains,
  7645. DenseMap<int, int> &ArgCopyElisionFrameIndexMap,
  7646. SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs,
  7647. ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg,
  7648. SDValue ArgVal, bool &ArgHasUses) {
  7649. // Check if this is a load from a fixed stack object.
  7650. auto *LNode = dyn_cast<LoadSDNode>(ArgVal);
  7651. if (!LNode)
  7652. return;
  7653. auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode());
  7654. if (!FINode)
  7655. return;
  7656. // Check that the fixed stack object is the right size and alignment.
  7657. // Look at the alignment that the user wrote on the alloca instead of looking
  7658. // at the stack object.
  7659. auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg);
  7660. assert(ArgCopyIter != ArgCopyElisionCandidates.end());
  7661. const AllocaInst *AI = ArgCopyIter->second.first;
  7662. int FixedIndex = FINode->getIndex();
  7663. int &AllocaIndex = FuncInfo->StaticAllocaMap[AI];
  7664. int OldIndex = AllocaIndex;
  7665. MachineFrameInfo &MFI = FuncInfo->MF->getFrameInfo();
  7666. if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) {
  7667. DEBUG(dbgs() << " argument copy elision failed due to bad fixed stack "
  7668. "object size\n");
  7669. return;
  7670. }
  7671. unsigned RequiredAlignment = AI->getAlignment();
  7672. if (!RequiredAlignment) {
  7673. RequiredAlignment = FuncInfo->MF->getDataLayout().getABITypeAlignment(
  7674. AI->getAllocatedType());
  7675. }
  7676. if (MFI.getObjectAlignment(FixedIndex) < RequiredAlignment) {
  7677. DEBUG(dbgs() << " argument copy elision failed: alignment of alloca "
  7678. "greater than stack argument alignment ("
  7679. << RequiredAlignment << " vs "
  7680. << MFI.getObjectAlignment(FixedIndex) << ")\n");
  7681. return;
  7682. }
  7683. // Perform the elision. Delete the old stack object and replace its only use
  7684. // in the variable info map. Mark the stack object as mutable.
  7685. DEBUG({
  7686. dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n'
  7687. << " Replacing frame index " << OldIndex << " with " << FixedIndex
  7688. << '\n';
  7689. });
  7690. MFI.RemoveStackObject(OldIndex);
  7691. MFI.setIsImmutableObjectIndex(FixedIndex, false);
  7692. AllocaIndex = FixedIndex;
  7693. ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex});
  7694. Chains.push_back(ArgVal.getValue(1));
  7695. // Avoid emitting code for the store implementing the copy.
  7696. const StoreInst *SI = ArgCopyIter->second.second;
  7697. ElidedArgCopyInstrs.insert(SI);
  7698. // Check for uses of the argument again so that we can avoid exporting ArgVal
  7699. // if it is't used by anything other than the store.
  7700. for (const Value *U : Arg.users()) {
  7701. if (U != SI) {
  7702. ArgHasUses = true;
  7703. break;
  7704. }
  7705. }
  7706. }
  7707. void SelectionDAGISel::LowerArguments(const Function &F) {
  7708. SelectionDAG &DAG = SDB->DAG;
  7709. SDLoc dl = SDB->getCurSDLoc();
  7710. const DataLayout &DL = DAG.getDataLayout();
  7711. SmallVector<ISD::InputArg, 16> Ins;
  7712. if (!FuncInfo->CanLowerReturn) {
  7713. // Put in an sret pointer parameter before all the other parameters.
  7714. SmallVector<EVT, 1> ValueVTs;
  7715. ComputeValueVTs(*TLI, DAG.getDataLayout(),
  7716. F.getReturnType()->getPointerTo(
  7717. DAG.getDataLayout().getAllocaAddrSpace()),
  7718. ValueVTs);
  7719. // NOTE: Assuming that a pointer will never break down to more than one VT
  7720. // or one register.
  7721. ISD::ArgFlagsTy Flags;
  7722. Flags.setSRet();
  7723. MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]);
  7724. ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true,
  7725. ISD::InputArg::NoArgIndex, 0);
  7726. Ins.push_back(RetArg);
  7727. }
  7728. // Look for stores of arguments to static allocas. Mark such arguments with a
  7729. // flag to ask the target to give us the memory location of that argument if
  7730. // available.
  7731. ArgCopyElisionMapTy ArgCopyElisionCandidates;
  7732. findArgumentCopyElisionCandidates(DL, FuncInfo, ArgCopyElisionCandidates);
  7733. // Set up the incoming argument description vector.
  7734. for (const Argument &Arg : F.args()) {
  7735. unsigned ArgNo = Arg.getArgNo();
  7736. SmallVector<EVT, 4> ValueVTs;
  7737. ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
  7738. bool isArgValueUsed = !Arg.use_empty();
  7739. unsigned PartBase = 0;
  7740. Type *FinalType = Arg.getType();
  7741. if (Arg.hasAttribute(Attribute::ByVal))
  7742. FinalType = cast<PointerType>(FinalType)->getElementType();
  7743. bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters(
  7744. FinalType, F.getCallingConv(), F.isVarArg());
  7745. for (unsigned Value = 0, NumValues = ValueVTs.size();
  7746. Value != NumValues; ++Value) {
  7747. EVT VT = ValueVTs[Value];
  7748. Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
  7749. ISD::ArgFlagsTy Flags;
  7750. // Certain targets (such as MIPS), may have a different ABI alignment
  7751. // for a type depending on the context. Give the target a chance to
  7752. // specify the alignment it wants.
  7753. unsigned OriginalAlignment =
  7754. TLI->getABIAlignmentForCallingConv(ArgTy, DL);
  7755. if (Arg.hasAttribute(Attribute::ZExt))
  7756. Flags.setZExt();
  7757. if (Arg.hasAttribute(Attribute::SExt))
  7758. Flags.setSExt();
  7759. if (Arg.hasAttribute(Attribute::InReg)) {
  7760. // If we are using vectorcall calling convention, a structure that is
  7761. // passed InReg - is surely an HVA
  7762. if (F.getCallingConv() == CallingConv::X86_VectorCall &&
  7763. isa<StructType>(Arg.getType())) {
  7764. // The first value of a structure is marked
  7765. if (0 == Value)
  7766. Flags.setHvaStart();
  7767. Flags.setHva();
  7768. }
  7769. // Set InReg Flag
  7770. Flags.setInReg();
  7771. }
  7772. if (Arg.hasAttribute(Attribute::StructRet))
  7773. Flags.setSRet();
  7774. if (Arg.hasAttribute(Attribute::SwiftSelf))
  7775. Flags.setSwiftSelf();
  7776. if (Arg.hasAttribute(Attribute::SwiftError))
  7777. Flags.setSwiftError();
  7778. if (Arg.hasAttribute(Attribute::ByVal))
  7779. Flags.setByVal();
  7780. if (Arg.hasAttribute(Attribute::InAlloca)) {
  7781. Flags.setInAlloca();
  7782. // Set the byval flag for CCAssignFn callbacks that don't know about
  7783. // inalloca. This way we can know how many bytes we should've allocated
  7784. // and how many bytes a callee cleanup function will pop. If we port
  7785. // inalloca to more targets, we'll have to add custom inalloca handling
  7786. // in the various CC lowering callbacks.
  7787. Flags.setByVal();
  7788. }
  7789. if (F.getCallingConv() == CallingConv::X86_INTR) {
  7790. // IA Interrupt passes frame (1st parameter) by value in the stack.
  7791. if (ArgNo == 0)
  7792. Flags.setByVal();
  7793. }
  7794. if (Flags.isByVal() || Flags.isInAlloca()) {
  7795. PointerType *Ty = cast<PointerType>(Arg.getType());
  7796. Type *ElementTy = Ty->getElementType();
  7797. Flags.setByValSize(DL.getTypeAllocSize(ElementTy));
  7798. // For ByVal, alignment should be passed from FE. BE will guess if
  7799. // this info is not there but there are cases it cannot get right.
  7800. unsigned FrameAlign;
  7801. if (Arg.getParamAlignment())
  7802. FrameAlign = Arg.getParamAlignment();
  7803. else
  7804. FrameAlign = TLI->getByValTypeAlignment(ElementTy, DL);
  7805. Flags.setByValAlign(FrameAlign);
  7806. }
  7807. if (Arg.hasAttribute(Attribute::Nest))
  7808. Flags.setNest();
  7809. if (NeedsRegBlock)
  7810. Flags.setInConsecutiveRegs();
  7811. Flags.setOrigAlign(OriginalAlignment);
  7812. if (ArgCopyElisionCandidates.count(&Arg))
  7813. Flags.setCopyElisionCandidate();
  7814. MVT RegisterVT =
  7815. TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(), VT);
  7816. unsigned NumRegs =
  7817. TLI->getNumRegistersForCallingConv(*CurDAG->getContext(), VT);
  7818. for (unsigned i = 0; i != NumRegs; ++i) {
  7819. ISD::InputArg MyFlags(Flags, RegisterVT, VT, isArgValueUsed,
  7820. ArgNo, PartBase+i*RegisterVT.getStoreSize());
  7821. if (NumRegs > 1 && i == 0)
  7822. MyFlags.Flags.setSplit();
  7823. // if it isn't first piece, alignment must be 1
  7824. else if (i > 0) {
  7825. MyFlags.Flags.setOrigAlign(1);
  7826. if (i == NumRegs - 1)
  7827. MyFlags.Flags.setSplitEnd();
  7828. }
  7829. Ins.push_back(MyFlags);
  7830. }
  7831. if (NeedsRegBlock && Value == NumValues - 1)
  7832. Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast();
  7833. PartBase += VT.getStoreSize();
  7834. }
  7835. }
  7836. // Call the target to set up the argument values.
  7837. SmallVector<SDValue, 8> InVals;
  7838. SDValue NewRoot = TLI->LowerFormalArguments(
  7839. DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals);
  7840. // Verify that the target's LowerFormalArguments behaved as expected.
  7841. assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
  7842. "LowerFormalArguments didn't return a valid chain!");
  7843. assert(InVals.size() == Ins.size() &&
  7844. "LowerFormalArguments didn't emit the correct number of values!");
  7845. DEBUG({
  7846. for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
  7847. assert(InVals[i].getNode() &&
  7848. "LowerFormalArguments emitted a null value!");
  7849. assert(EVT(Ins[i].VT) == InVals[i].getValueType() &&
  7850. "LowerFormalArguments emitted a value with the wrong type!");
  7851. }
  7852. });
  7853. // Update the DAG with the new chain value resulting from argument lowering.
  7854. DAG.setRoot(NewRoot);
  7855. // Set up the argument values.
  7856. unsigned i = 0;
  7857. if (!FuncInfo->CanLowerReturn) {
  7858. // Create a virtual register for the sret pointer, and put in a copy
  7859. // from the sret argument into it.
  7860. SmallVector<EVT, 1> ValueVTs;
  7861. ComputeValueVTs(*TLI, DAG.getDataLayout(),
  7862. F.getReturnType()->getPointerTo(
  7863. DAG.getDataLayout().getAllocaAddrSpace()),
  7864. ValueVTs);
  7865. MVT VT = ValueVTs[0].getSimpleVT();
  7866. MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
  7867. Optional<ISD::NodeType> AssertOp = None;
  7868. SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1,
  7869. RegVT, VT, nullptr, AssertOp);
  7870. MachineFunction& MF = SDB->DAG.getMachineFunction();
  7871. MachineRegisterInfo& RegInfo = MF.getRegInfo();
  7872. unsigned SRetReg = RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT));
  7873. FuncInfo->DemoteRegister = SRetReg;
  7874. NewRoot =
  7875. SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue);
  7876. DAG.setRoot(NewRoot);
  7877. // i indexes lowered arguments. Bump it past the hidden sret argument.
  7878. ++i;
  7879. }
  7880. SmallVector<SDValue, 4> Chains;
  7881. DenseMap<int, int> ArgCopyElisionFrameIndexMap;
  7882. for (const Argument &Arg : F.args()) {
  7883. SmallVector<SDValue, 4> ArgValues;
  7884. SmallVector<EVT, 4> ValueVTs;
  7885. ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
  7886. unsigned NumValues = ValueVTs.size();
  7887. if (NumValues == 0)
  7888. continue;
  7889. bool ArgHasUses = !Arg.use_empty();
  7890. // Elide the copying store if the target loaded this argument from a
  7891. // suitable fixed stack object.
  7892. if (Ins[i].Flags.isCopyElisionCandidate()) {
  7893. tryToElideArgumentCopy(FuncInfo, Chains, ArgCopyElisionFrameIndexMap,
  7894. ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg,
  7895. InVals[i], ArgHasUses);
  7896. }
  7897. // If this argument is unused then remember its value. It is used to generate
  7898. // debugging information.
  7899. bool isSwiftErrorArg =
  7900. TLI->supportSwiftError() &&
  7901. Arg.hasAttribute(Attribute::SwiftError);
  7902. if (!ArgHasUses && !isSwiftErrorArg) {
  7903. SDB->setUnusedArgValue(&Arg, InVals[i]);
  7904. // Also remember any frame index for use in FastISel.
  7905. if (FrameIndexSDNode *FI =
  7906. dyn_cast<FrameIndexSDNode>(InVals[i].getNode()))
  7907. FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
  7908. }
  7909. for (unsigned Val = 0; Val != NumValues; ++Val) {
  7910. EVT VT = ValueVTs[Val];
  7911. MVT PartVT =
  7912. TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(), VT);
  7913. unsigned NumParts =
  7914. TLI->getNumRegistersForCallingConv(*CurDAG->getContext(), VT);
  7915. // Even an apparant 'unused' swifterror argument needs to be returned. So
  7916. // we do generate a copy for it that can be used on return from the
  7917. // function.
  7918. if (ArgHasUses || isSwiftErrorArg) {
  7919. Optional<ISD::NodeType> AssertOp;
  7920. if (Arg.hasAttribute(Attribute::SExt))
  7921. AssertOp = ISD::AssertSext;
  7922. else if (Arg.hasAttribute(Attribute::ZExt))
  7923. AssertOp = ISD::AssertZext;
  7924. ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts,
  7925. PartVT, VT, nullptr, AssertOp,
  7926. true));
  7927. }
  7928. i += NumParts;
  7929. }
  7930. // We don't need to do anything else for unused arguments.
  7931. if (ArgValues.empty())
  7932. continue;
  7933. // Note down frame index.
  7934. if (FrameIndexSDNode *FI =
  7935. dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode()))
  7936. FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
  7937. SDValue Res = DAG.getMergeValues(makeArrayRef(ArgValues.data(), NumValues),
  7938. SDB->getCurSDLoc());
  7939. SDB->setValue(&Arg, Res);
  7940. if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) {
  7941. // We want to associate the argument with the frame index, among
  7942. // involved operands, that correspond to the lowest address. The
  7943. // getCopyFromParts function, called earlier, is swapping the order of
  7944. // the operands to BUILD_PAIR depending on endianness. The result of
  7945. // that swapping is that the least significant bits of the argument will
  7946. // be in the first operand of the BUILD_PAIR node, and the most
  7947. // significant bits will be in the second operand.
  7948. unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0;
  7949. if (LoadSDNode *LNode =
  7950. dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode()))
  7951. if (FrameIndexSDNode *FI =
  7952. dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
  7953. FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
  7954. }
  7955. // Update the SwiftErrorVRegDefMap.
  7956. if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) {
  7957. unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
  7958. if (TargetRegisterInfo::isVirtualRegister(Reg))
  7959. FuncInfo->setCurrentSwiftErrorVReg(FuncInfo->MBB,
  7960. FuncInfo->SwiftErrorArg, Reg);
  7961. }
  7962. // If this argument is live outside of the entry block, insert a copy from
  7963. // wherever we got it to the vreg that other BB's will reference it as.
  7964. if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::CopyFromReg) {
  7965. // If we can, though, try to skip creating an unnecessary vreg.
  7966. // FIXME: This isn't very clean... it would be nice to make this more
  7967. // general. It's also subtly incompatible with the hacks FastISel
  7968. // uses with vregs.
  7969. unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
  7970. if (TargetRegisterInfo::isVirtualRegister(Reg)) {
  7971. FuncInfo->ValueMap[&Arg] = Reg;
  7972. continue;
  7973. }
  7974. }
  7975. if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) {
  7976. FuncInfo->InitializeRegForValue(&Arg);
  7977. SDB->CopyToExportRegsIfNeeded(&Arg);
  7978. }
  7979. }
  7980. if (!Chains.empty()) {
  7981. Chains.push_back(NewRoot);
  7982. NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
  7983. }
  7984. DAG.setRoot(NewRoot);
  7985. assert(i == InVals.size() && "Argument register count mismatch!");
  7986. // If any argument copy elisions occurred and we have debug info, update the
  7987. // stale frame indices used in the dbg.declare variable info table.
  7988. MachineFunction::VariableDbgInfoMapTy &DbgDeclareInfo = MF->getVariableDbgInfo();
  7989. if (!DbgDeclareInfo.empty() && !ArgCopyElisionFrameIndexMap.empty()) {
  7990. for (MachineFunction::VariableDbgInfo &VI : DbgDeclareInfo) {
  7991. auto I = ArgCopyElisionFrameIndexMap.find(VI.Slot);
  7992. if (I != ArgCopyElisionFrameIndexMap.end())
  7993. VI.Slot = I->second;
  7994. }
  7995. }
  7996. // Finally, if the target has anything special to do, allow it to do so.
  7997. EmitFunctionEntryCode();
  7998. }
  7999. /// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
  8000. /// ensure constants are generated when needed. Remember the virtual registers
  8001. /// that need to be added to the Machine PHI nodes as input. We cannot just
  8002. /// directly add them, because expansion might result in multiple MBB's for one
  8003. /// BB. As such, the start of the BB might correspond to a different MBB than
  8004. /// the end.
  8005. void
  8006. SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
  8007. const TerminatorInst *TI = LLVMBB->getTerminator();
  8008. SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
  8009. // Check PHI nodes in successors that expect a value to be available from this
  8010. // block.
  8011. for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
  8012. const BasicBlock *SuccBB = TI->getSuccessor(succ);
  8013. if (!isa<PHINode>(SuccBB->begin())) continue;
  8014. MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
  8015. // If this terminator has multiple identical successors (common for
  8016. // switches), only handle each succ once.
  8017. if (!SuccsHandled.insert(SuccMBB).second)
  8018. continue;
  8019. MachineBasicBlock::iterator MBBI = SuccMBB->begin();
  8020. // At this point we know that there is a 1-1 correspondence between LLVM PHI
  8021. // nodes and Machine PHI nodes, but the incoming operands have not been
  8022. // emitted yet.
  8023. for (const PHINode &PN : SuccBB->phis()) {
  8024. // Ignore dead phi's.
  8025. if (PN.use_empty())
  8026. continue;
  8027. // Skip empty types
  8028. if (PN.getType()->isEmptyTy())
  8029. continue;
  8030. unsigned Reg;
  8031. const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB);
  8032. if (const Constant *C = dyn_cast<Constant>(PHIOp)) {
  8033. unsigned &RegOut = ConstantsOut[C];
  8034. if (RegOut == 0) {
  8035. RegOut = FuncInfo.CreateRegs(C->getType());
  8036. CopyValueToVirtualRegister(C, RegOut);
  8037. }
  8038. Reg = RegOut;
  8039. } else {
  8040. DenseMap<const Value *, unsigned>::iterator I =
  8041. FuncInfo.ValueMap.find(PHIOp);
  8042. if (I != FuncInfo.ValueMap.end())
  8043. Reg = I->second;
  8044. else {
  8045. assert(isa<AllocaInst>(PHIOp) &&
  8046. FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
  8047. "Didn't codegen value into a register!??");
  8048. Reg = FuncInfo.CreateRegs(PHIOp->getType());
  8049. CopyValueToVirtualRegister(PHIOp, Reg);
  8050. }
  8051. }
  8052. // Remember that this register needs to added to the machine PHI node as
  8053. // the input for this MBB.
  8054. SmallVector<EVT, 4> ValueVTs;
  8055. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  8056. ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs);
  8057. for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
  8058. EVT VT = ValueVTs[vti];
  8059. unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT);
  8060. for (unsigned i = 0, e = NumRegisters; i != e; ++i)
  8061. FuncInfo.PHINodesToUpdate.push_back(
  8062. std::make_pair(&*MBBI++, Reg + i));
  8063. Reg += NumRegisters;
  8064. }
  8065. }
  8066. }
  8067. ConstantsOut.clear();
  8068. }
  8069. /// Add a successor MBB to ParentMBB< creating a new MachineBB for BB if SuccMBB
  8070. /// is 0.
  8071. MachineBasicBlock *
  8072. SelectionDAGBuilder::StackProtectorDescriptor::
  8073. AddSuccessorMBB(const BasicBlock *BB,
  8074. MachineBasicBlock *ParentMBB,
  8075. bool IsLikely,
  8076. MachineBasicBlock *SuccMBB) {
  8077. // If SuccBB has not been created yet, create it.
  8078. if (!SuccMBB) {
  8079. MachineFunction *MF = ParentMBB->getParent();
  8080. MachineFunction::iterator BBI(ParentMBB);
  8081. SuccMBB = MF->CreateMachineBasicBlock(BB);
  8082. MF->insert(++BBI, SuccMBB);
  8083. }
  8084. // Add it as a successor of ParentMBB.
  8085. ParentMBB->addSuccessor(
  8086. SuccMBB, BranchProbabilityInfo::getBranchProbStackProtector(IsLikely));
  8087. return SuccMBB;
  8088. }
  8089. MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) {
  8090. MachineFunction::iterator I(MBB);
  8091. if (++I == FuncInfo.MF->end())
  8092. return nullptr;
  8093. return &*I;
  8094. }
  8095. /// During lowering new call nodes can be created (such as memset, etc.).
  8096. /// Those will become new roots of the current DAG, but complications arise
  8097. /// when they are tail calls. In such cases, the call lowering will update
  8098. /// the root, but the builder still needs to know that a tail call has been
  8099. /// lowered in order to avoid generating an additional return.
  8100. void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) {
  8101. // If the node is null, we do have a tail call.
  8102. if (MaybeTC.getNode() != nullptr)
  8103. DAG.setRoot(MaybeTC);
  8104. else
  8105. HasTailCall = true;
  8106. }
  8107. uint64_t
  8108. SelectionDAGBuilder::getJumpTableRange(const CaseClusterVector &Clusters,
  8109. unsigned First, unsigned Last) const {
  8110. assert(Last >= First);
  8111. const APInt &LowCase = Clusters[First].Low->getValue();
  8112. const APInt &HighCase = Clusters[Last].High->getValue();
  8113. assert(LowCase.getBitWidth() == HighCase.getBitWidth());
  8114. // FIXME: A range of consecutive cases has 100% density, but only requires one
  8115. // comparison to lower. We should discriminate against such consecutive ranges
  8116. // in jump tables.
  8117. return (HighCase - LowCase).getLimitedValue((UINT64_MAX - 1) / 100) + 1;
  8118. }
  8119. uint64_t SelectionDAGBuilder::getJumpTableNumCases(
  8120. const SmallVectorImpl<unsigned> &TotalCases, unsigned First,
  8121. unsigned Last) const {
  8122. assert(Last >= First);
  8123. assert(TotalCases[Last] >= TotalCases[First]);
  8124. uint64_t NumCases =
  8125. TotalCases[Last] - (First == 0 ? 0 : TotalCases[First - 1]);
  8126. return NumCases;
  8127. }
  8128. bool SelectionDAGBuilder::buildJumpTable(const CaseClusterVector &Clusters,
  8129. unsigned First, unsigned Last,
  8130. const SwitchInst *SI,
  8131. MachineBasicBlock *DefaultMBB,
  8132. CaseCluster &JTCluster) {
  8133. assert(First <= Last);
  8134. auto Prob = BranchProbability::getZero();
  8135. unsigned NumCmps = 0;
  8136. std::vector<MachineBasicBlock*> Table;
  8137. DenseMap<MachineBasicBlock*, BranchProbability> JTProbs;
  8138. // Initialize probabilities in JTProbs.
  8139. for (unsigned I = First; I <= Last; ++I)
  8140. JTProbs[Clusters[I].MBB] = BranchProbability::getZero();
  8141. for (unsigned I = First; I <= Last; ++I) {
  8142. assert(Clusters[I].Kind == CC_Range);
  8143. Prob += Clusters[I].Prob;
  8144. const APInt &Low = Clusters[I].Low->getValue();
  8145. const APInt &High = Clusters[I].High->getValue();
  8146. NumCmps += (Low == High) ? 1 : 2;
  8147. if (I != First) {
  8148. // Fill the gap between this and the previous cluster.
  8149. const APInt &PreviousHigh = Clusters[I - 1].High->getValue();
  8150. assert(PreviousHigh.slt(Low));
  8151. uint64_t Gap = (Low - PreviousHigh).getLimitedValue() - 1;
  8152. for (uint64_t J = 0; J < Gap; J++)
  8153. Table.push_back(DefaultMBB);
  8154. }
  8155. uint64_t ClusterSize = (High - Low).getLimitedValue() + 1;
  8156. for (uint64_t J = 0; J < ClusterSize; ++J)
  8157. Table.push_back(Clusters[I].MBB);
  8158. JTProbs[Clusters[I].MBB] += Clusters[I].Prob;
  8159. }
  8160. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  8161. unsigned NumDests = JTProbs.size();
  8162. if (TLI.isSuitableForBitTests(
  8163. NumDests, NumCmps, Clusters[First].Low->getValue(),
  8164. Clusters[Last].High->getValue(), DAG.getDataLayout())) {
  8165. // Clusters[First..Last] should be lowered as bit tests instead.
  8166. return false;
  8167. }
  8168. // Create the MBB that will load from and jump through the table.
  8169. // Note: We create it here, but it's not inserted into the function yet.
  8170. MachineFunction *CurMF = FuncInfo.MF;
  8171. MachineBasicBlock *JumpTableMBB =
  8172. CurMF->CreateMachineBasicBlock(SI->getParent());
  8173. // Add successors. Note: use table order for determinism.
  8174. SmallPtrSet<MachineBasicBlock *, 8> Done;
  8175. for (MachineBasicBlock *Succ : Table) {
  8176. if (Done.count(Succ))
  8177. continue;
  8178. addSuccessorWithProb(JumpTableMBB, Succ, JTProbs[Succ]);
  8179. Done.insert(Succ);
  8180. }
  8181. JumpTableMBB->normalizeSuccProbs();
  8182. unsigned JTI = CurMF->getOrCreateJumpTableInfo(TLI.getJumpTableEncoding())
  8183. ->createJumpTableIndex(Table);
  8184. // Set up the jump table info.
  8185. JumpTable JT(-1U, JTI, JumpTableMBB, nullptr);
  8186. JumpTableHeader JTH(Clusters[First].Low->getValue(),
  8187. Clusters[Last].High->getValue(), SI->getCondition(),
  8188. nullptr, false);
  8189. JTCases.emplace_back(std::move(JTH), std::move(JT));
  8190. JTCluster = CaseCluster::jumpTable(Clusters[First].Low, Clusters[Last].High,
  8191. JTCases.size() - 1, Prob);
  8192. return true;
  8193. }
  8194. void SelectionDAGBuilder::findJumpTables(CaseClusterVector &Clusters,
  8195. const SwitchInst *SI,
  8196. MachineBasicBlock *DefaultMBB) {
  8197. #ifndef NDEBUG
  8198. // Clusters must be non-empty, sorted, and only contain Range clusters.
  8199. assert(!Clusters.empty());
  8200. for (CaseCluster &C : Clusters)
  8201. assert(C.Kind == CC_Range);
  8202. for (unsigned i = 1, e = Clusters.size(); i < e; ++i)
  8203. assert(Clusters[i - 1].High->getValue().slt(Clusters[i].Low->getValue()));
  8204. #endif
  8205. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  8206. if (!TLI.areJTsAllowed(SI->getParent()->getParent()))
  8207. return;
  8208. const int64_t N = Clusters.size();
  8209. const unsigned MinJumpTableEntries = TLI.getMinimumJumpTableEntries();
  8210. const unsigned SmallNumberOfEntries = MinJumpTableEntries / 2;
  8211. if (N < 2 || N < MinJumpTableEntries)
  8212. return;
  8213. // TotalCases[i]: Total nbr of cases in Clusters[0..i].
  8214. SmallVector<unsigned, 8> TotalCases(N);
  8215. for (unsigned i = 0; i < N; ++i) {
  8216. const APInt &Hi = Clusters[i].High->getValue();
  8217. const APInt &Lo = Clusters[i].Low->getValue();
  8218. TotalCases[i] = (Hi - Lo).getLimitedValue() + 1;
  8219. if (i != 0)
  8220. TotalCases[i] += TotalCases[i - 1];
  8221. }
  8222. // Cheap case: the whole range may be suitable for jump table.
  8223. uint64_t Range = getJumpTableRange(Clusters,0, N - 1);
  8224. uint64_t NumCases = getJumpTableNumCases(TotalCases, 0, N - 1);
  8225. assert(NumCases < UINT64_MAX / 100);
  8226. assert(Range >= NumCases);
  8227. if (TLI.isSuitableForJumpTable(SI, NumCases, Range)) {
  8228. CaseCluster JTCluster;
  8229. if (buildJumpTable(Clusters, 0, N - 1, SI, DefaultMBB, JTCluster)) {
  8230. Clusters[0] = JTCluster;
  8231. Clusters.resize(1);
  8232. return;
  8233. }
  8234. }
  8235. // The algorithm below is not suitable for -O0.
  8236. if (TM.getOptLevel() == CodeGenOpt::None)
  8237. return;
  8238. // Split Clusters into minimum number of dense partitions. The algorithm uses
  8239. // the same idea as Kannan & Proebsting "Correction to 'Producing Good Code
  8240. // for the Case Statement'" (1994), but builds the MinPartitions array in
  8241. // reverse order to make it easier to reconstruct the partitions in ascending
  8242. // order. In the choice between two optimal partitionings, it picks the one
  8243. // which yields more jump tables.
  8244. // MinPartitions[i] is the minimum nbr of partitions of Clusters[i..N-1].
  8245. SmallVector<unsigned, 8> MinPartitions(N);
  8246. // LastElement[i] is the last element of the partition starting at i.
  8247. SmallVector<unsigned, 8> LastElement(N);
  8248. // PartitionsScore[i] is used to break ties when choosing between two
  8249. // partitionings resulting in the same number of partitions.
  8250. SmallVector<unsigned, 8> PartitionsScore(N);
  8251. // For PartitionsScore, a small number of comparisons is considered as good as
  8252. // a jump table and a single comparison is considered better than a jump
  8253. // table.
  8254. enum PartitionScores : unsigned {
  8255. NoTable = 0,
  8256. Table = 1,
  8257. FewCases = 1,
  8258. SingleCase = 2
  8259. };
  8260. // Base case: There is only one way to partition Clusters[N-1].
  8261. MinPartitions[N - 1] = 1;
  8262. LastElement[N - 1] = N - 1;
  8263. PartitionsScore[N - 1] = PartitionScores::SingleCase;
  8264. // Note: loop indexes are signed to avoid underflow.
  8265. for (int64_t i = N - 2; i >= 0; i--) {
  8266. // Find optimal partitioning of Clusters[i..N-1].
  8267. // Baseline: Put Clusters[i] into a partition on its own.
  8268. MinPartitions[i] = MinPartitions[i + 1] + 1;
  8269. LastElement[i] = i;
  8270. PartitionsScore[i] = PartitionsScore[i + 1] + PartitionScores::SingleCase;
  8271. // Search for a solution that results in fewer partitions.
  8272. for (int64_t j = N - 1; j > i; j--) {
  8273. // Try building a partition from Clusters[i..j].
  8274. uint64_t Range = getJumpTableRange(Clusters, i, j);
  8275. uint64_t NumCases = getJumpTableNumCases(TotalCases, i, j);
  8276. assert(NumCases < UINT64_MAX / 100);
  8277. assert(Range >= NumCases);
  8278. if (TLI.isSuitableForJumpTable(SI, NumCases, Range)) {
  8279. unsigned NumPartitions = 1 + (j == N - 1 ? 0 : MinPartitions[j + 1]);
  8280. unsigned Score = j == N - 1 ? 0 : PartitionsScore[j + 1];
  8281. int64_t NumEntries = j - i + 1;
  8282. if (NumEntries == 1)
  8283. Score += PartitionScores::SingleCase;
  8284. else if (NumEntries <= SmallNumberOfEntries)
  8285. Score += PartitionScores::FewCases;
  8286. else if (NumEntries >= MinJumpTableEntries)
  8287. Score += PartitionScores::Table;
  8288. // If this leads to fewer partitions, or to the same number of
  8289. // partitions with better score, it is a better partitioning.
  8290. if (NumPartitions < MinPartitions[i] ||
  8291. (NumPartitions == MinPartitions[i] && Score > PartitionsScore[i])) {
  8292. MinPartitions[i] = NumPartitions;
  8293. LastElement[i] = j;
  8294. PartitionsScore[i] = Score;
  8295. }
  8296. }
  8297. }
  8298. }
  8299. // Iterate over the partitions, replacing some with jump tables in-place.
  8300. unsigned DstIndex = 0;
  8301. for (unsigned First = 0, Last; First < N; First = Last + 1) {
  8302. Last = LastElement[First];
  8303. assert(Last >= First);
  8304. assert(DstIndex <= First);
  8305. unsigned NumClusters = Last - First + 1;
  8306. CaseCluster JTCluster;
  8307. if (NumClusters >= MinJumpTableEntries &&
  8308. buildJumpTable(Clusters, First, Last, SI, DefaultMBB, JTCluster)) {
  8309. Clusters[DstIndex++] = JTCluster;
  8310. } else {
  8311. for (unsigned I = First; I <= Last; ++I)
  8312. std::memmove(&Clusters[DstIndex++], &Clusters[I], sizeof(Clusters[I]));
  8313. }
  8314. }
  8315. Clusters.resize(DstIndex);
  8316. }
  8317. bool SelectionDAGBuilder::buildBitTests(CaseClusterVector &Clusters,
  8318. unsigned First, unsigned Last,
  8319. const SwitchInst *SI,
  8320. CaseCluster &BTCluster) {
  8321. assert(First <= Last);
  8322. if (First == Last)
  8323. return false;
  8324. BitVector Dests(FuncInfo.MF->getNumBlockIDs());
  8325. unsigned NumCmps = 0;
  8326. for (int64_t I = First; I <= Last; ++I) {
  8327. assert(Clusters[I].Kind == CC_Range);
  8328. Dests.set(Clusters[I].MBB->getNumber());
  8329. NumCmps += (Clusters[I].Low == Clusters[I].High) ? 1 : 2;
  8330. }
  8331. unsigned NumDests = Dests.count();
  8332. APInt Low = Clusters[First].Low->getValue();
  8333. APInt High = Clusters[Last].High->getValue();
  8334. assert(Low.slt(High));
  8335. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  8336. const DataLayout &DL = DAG.getDataLayout();
  8337. if (!TLI.isSuitableForBitTests(NumDests, NumCmps, Low, High, DL))
  8338. return false;
  8339. APInt LowBound;
  8340. APInt CmpRange;
  8341. const int BitWidth = TLI.getPointerTy(DL).getSizeInBits();
  8342. assert(TLI.rangeFitsInWord(Low, High, DL) &&
  8343. "Case range must fit in bit mask!");
  8344. // Check if the clusters cover a contiguous range such that no value in the
  8345. // range will jump to the default statement.
  8346. bool ContiguousRange = true;
  8347. for (int64_t I = First + 1; I <= Last; ++I) {
  8348. if (Clusters[I].Low->getValue() != Clusters[I - 1].High->getValue() + 1) {
  8349. ContiguousRange = false;
  8350. break;
  8351. }
  8352. }
  8353. if (Low.isStrictlyPositive() && High.slt(BitWidth)) {
  8354. // Optimize the case where all the case values fit in a word without having
  8355. // to subtract minValue. In this case, we can optimize away the subtraction.
  8356. LowBound = APInt::getNullValue(Low.getBitWidth());
  8357. CmpRange = High;
  8358. ContiguousRange = false;
  8359. } else {
  8360. LowBound = Low;
  8361. CmpRange = High - Low;
  8362. }
  8363. CaseBitsVector CBV;
  8364. auto TotalProb = BranchProbability::getZero();
  8365. for (unsigned i = First; i <= Last; ++i) {
  8366. // Find the CaseBits for this destination.
  8367. unsigned j;
  8368. for (j = 0; j < CBV.size(); ++j)
  8369. if (CBV[j].BB == Clusters[i].MBB)
  8370. break;
  8371. if (j == CBV.size())
  8372. CBV.push_back(
  8373. CaseBits(0, Clusters[i].MBB, 0, BranchProbability::getZero()));
  8374. CaseBits *CB = &CBV[j];
  8375. // Update Mask, Bits and ExtraProb.
  8376. uint64_t Lo = (Clusters[i].Low->getValue() - LowBound).getZExtValue();
  8377. uint64_t Hi = (Clusters[i].High->getValue() - LowBound).getZExtValue();
  8378. assert(Hi >= Lo && Hi < 64 && "Invalid bit case!");
  8379. CB->Mask |= (-1ULL >> (63 - (Hi - Lo))) << Lo;
  8380. CB->Bits += Hi - Lo + 1;
  8381. CB->ExtraProb += Clusters[i].Prob;
  8382. TotalProb += Clusters[i].Prob;
  8383. }
  8384. BitTestInfo BTI;
  8385. llvm::sort(CBV.begin(), CBV.end(), [](const CaseBits &a, const CaseBits &b) {
  8386. // Sort by probability first, number of bits second, bit mask third.
  8387. if (a.ExtraProb != b.ExtraProb)
  8388. return a.ExtraProb > b.ExtraProb;
  8389. if (a.Bits != b.Bits)
  8390. return a.Bits > b.Bits;
  8391. return a.Mask < b.Mask;
  8392. });
  8393. for (auto &CB : CBV) {
  8394. MachineBasicBlock *BitTestBB =
  8395. FuncInfo.MF->CreateMachineBasicBlock(SI->getParent());
  8396. BTI.push_back(BitTestCase(CB.Mask, BitTestBB, CB.BB, CB.ExtraProb));
  8397. }
  8398. BitTestCases.emplace_back(std::move(LowBound), std::move(CmpRange),
  8399. SI->getCondition(), -1U, MVT::Other, false,
  8400. ContiguousRange, nullptr, nullptr, std::move(BTI),
  8401. TotalProb);
  8402. BTCluster = CaseCluster::bitTests(Clusters[First].Low, Clusters[Last].High,
  8403. BitTestCases.size() - 1, TotalProb);
  8404. return true;
  8405. }
  8406. void SelectionDAGBuilder::findBitTestClusters(CaseClusterVector &Clusters,
  8407. const SwitchInst *SI) {
  8408. // Partition Clusters into as few subsets as possible, where each subset has a
  8409. // range that fits in a machine word and has <= 3 unique destinations.
  8410. #ifndef NDEBUG
  8411. // Clusters must be sorted and contain Range or JumpTable clusters.
  8412. assert(!Clusters.empty());
  8413. assert(Clusters[0].Kind == CC_Range || Clusters[0].Kind == CC_JumpTable);
  8414. for (const CaseCluster &C : Clusters)
  8415. assert(C.Kind == CC_Range || C.Kind == CC_JumpTable);
  8416. for (unsigned i = 1; i < Clusters.size(); ++i)
  8417. assert(Clusters[i-1].High->getValue().slt(Clusters[i].Low->getValue()));
  8418. #endif
  8419. // The algorithm below is not suitable for -O0.
  8420. if (TM.getOptLevel() == CodeGenOpt::None)
  8421. return;
  8422. // If target does not have legal shift left, do not emit bit tests at all.
  8423. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  8424. const DataLayout &DL = DAG.getDataLayout();
  8425. EVT PTy = TLI.getPointerTy(DL);
  8426. if (!TLI.isOperationLegal(ISD::SHL, PTy))
  8427. return;
  8428. int BitWidth = PTy.getSizeInBits();
  8429. const int64_t N = Clusters.size();
  8430. // MinPartitions[i] is the minimum nbr of partitions of Clusters[i..N-1].
  8431. SmallVector<unsigned, 8> MinPartitions(N);
  8432. // LastElement[i] is the last element of the partition starting at i.
  8433. SmallVector<unsigned, 8> LastElement(N);
  8434. // FIXME: This might not be the best algorithm for finding bit test clusters.
  8435. // Base case: There is only one way to partition Clusters[N-1].
  8436. MinPartitions[N - 1] = 1;
  8437. LastElement[N - 1] = N - 1;
  8438. // Note: loop indexes are signed to avoid underflow.
  8439. for (int64_t i = N - 2; i >= 0; --i) {
  8440. // Find optimal partitioning of Clusters[i..N-1].
  8441. // Baseline: Put Clusters[i] into a partition on its own.
  8442. MinPartitions[i] = MinPartitions[i + 1] + 1;
  8443. LastElement[i] = i;
  8444. // Search for a solution that results in fewer partitions.
  8445. // Note: the search is limited by BitWidth, reducing time complexity.
  8446. for (int64_t j = std::min(N - 1, i + BitWidth - 1); j > i; --j) {
  8447. // Try building a partition from Clusters[i..j].
  8448. // Check the range.
  8449. if (!TLI.rangeFitsInWord(Clusters[i].Low->getValue(),
  8450. Clusters[j].High->getValue(), DL))
  8451. continue;
  8452. // Check nbr of destinations and cluster types.
  8453. // FIXME: This works, but doesn't seem very efficient.
  8454. bool RangesOnly = true;
  8455. BitVector Dests(FuncInfo.MF->getNumBlockIDs());
  8456. for (int64_t k = i; k <= j; k++) {
  8457. if (Clusters[k].Kind != CC_Range) {
  8458. RangesOnly = false;
  8459. break;
  8460. }
  8461. Dests.set(Clusters[k].MBB->getNumber());
  8462. }
  8463. if (!RangesOnly || Dests.count() > 3)
  8464. break;
  8465. // Check if it's a better partition.
  8466. unsigned NumPartitions = 1 + (j == N - 1 ? 0 : MinPartitions[j + 1]);
  8467. if (NumPartitions < MinPartitions[i]) {
  8468. // Found a better partition.
  8469. MinPartitions[i] = NumPartitions;
  8470. LastElement[i] = j;
  8471. }
  8472. }
  8473. }
  8474. // Iterate over the partitions, replacing with bit-test clusters in-place.
  8475. unsigned DstIndex = 0;
  8476. for (unsigned First = 0, Last; First < N; First = Last + 1) {
  8477. Last = LastElement[First];
  8478. assert(First <= Last);
  8479. assert(DstIndex <= First);
  8480. CaseCluster BitTestCluster;
  8481. if (buildBitTests(Clusters, First, Last, SI, BitTestCluster)) {
  8482. Clusters[DstIndex++] = BitTestCluster;
  8483. } else {
  8484. size_t NumClusters = Last - First + 1;
  8485. std::memmove(&Clusters[DstIndex], &Clusters[First],
  8486. sizeof(Clusters[0]) * NumClusters);
  8487. DstIndex += NumClusters;
  8488. }
  8489. }
  8490. Clusters.resize(DstIndex);
  8491. }
  8492. void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond,
  8493. MachineBasicBlock *SwitchMBB,
  8494. MachineBasicBlock *DefaultMBB) {
  8495. MachineFunction *CurMF = FuncInfo.MF;
  8496. MachineBasicBlock *NextMBB = nullptr;
  8497. MachineFunction::iterator BBI(W.MBB);
  8498. if (++BBI != FuncInfo.MF->end())
  8499. NextMBB = &*BBI;
  8500. unsigned Size = W.LastCluster - W.FirstCluster + 1;
  8501. BranchProbabilityInfo *BPI = FuncInfo.BPI;
  8502. if (Size == 2 && W.MBB == SwitchMBB) {
  8503. // If any two of the cases has the same destination, and if one value
  8504. // is the same as the other, but has one bit unset that the other has set,
  8505. // use bit manipulation to do two compares at once. For example:
  8506. // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
  8507. // TODO: This could be extended to merge any 2 cases in switches with 3
  8508. // cases.
  8509. // TODO: Handle cases where W.CaseBB != SwitchBB.
  8510. CaseCluster &Small = *W.FirstCluster;
  8511. CaseCluster &Big = *W.LastCluster;
  8512. if (Small.Low == Small.High && Big.Low == Big.High &&
  8513. Small.MBB == Big.MBB) {
  8514. const APInt &SmallValue = Small.Low->getValue();
  8515. const APInt &BigValue = Big.Low->getValue();
  8516. // Check that there is only one bit different.
  8517. APInt CommonBit = BigValue ^ SmallValue;
  8518. if (CommonBit.isPowerOf2()) {
  8519. SDValue CondLHS = getValue(Cond);
  8520. EVT VT = CondLHS.getValueType();
  8521. SDLoc DL = getCurSDLoc();
  8522. SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS,
  8523. DAG.getConstant(CommonBit, DL, VT));
  8524. SDValue Cond = DAG.getSetCC(
  8525. DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT),
  8526. ISD::SETEQ);
  8527. // Update successor info.
  8528. // Both Small and Big will jump to Small.BB, so we sum up the
  8529. // probabilities.
  8530. addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob);
  8531. if (BPI)
  8532. addSuccessorWithProb(
  8533. SwitchMBB, DefaultMBB,
  8534. // The default destination is the first successor in IR.
  8535. BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0));
  8536. else
  8537. addSuccessorWithProb(SwitchMBB, DefaultMBB);
  8538. // Insert the true branch.
  8539. SDValue BrCond =
  8540. DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond,
  8541. DAG.getBasicBlock(Small.MBB));
  8542. // Insert the false branch.
  8543. BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond,
  8544. DAG.getBasicBlock(DefaultMBB));
  8545. DAG.setRoot(BrCond);
  8546. return;
  8547. }
  8548. }
  8549. }
  8550. if (TM.getOptLevel() != CodeGenOpt::None) {
  8551. // Here, we order cases by probability so the most likely case will be
  8552. // checked first. However, two clusters can have the same probability in
  8553. // which case their relative ordering is non-deterministic. So we use Low
  8554. // as a tie-breaker as clusters are guaranteed to never overlap.
  8555. llvm::sort(W.FirstCluster, W.LastCluster + 1,
  8556. [](const CaseCluster &a, const CaseCluster &b) {
  8557. return a.Prob != b.Prob ?
  8558. a.Prob > b.Prob :
  8559. a.Low->getValue().slt(b.Low->getValue());
  8560. });
  8561. // Rearrange the case blocks so that the last one falls through if possible
  8562. // without changing the order of probabilities.
  8563. for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) {
  8564. --I;
  8565. if (I->Prob > W.LastCluster->Prob)
  8566. break;
  8567. if (I->Kind == CC_Range && I->MBB == NextMBB) {
  8568. std::swap(*I, *W.LastCluster);
  8569. break;
  8570. }
  8571. }
  8572. }
  8573. // Compute total probability.
  8574. BranchProbability DefaultProb = W.DefaultProb;
  8575. BranchProbability UnhandledProbs = DefaultProb;
  8576. for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I)
  8577. UnhandledProbs += I->Prob;
  8578. MachineBasicBlock *CurMBB = W.MBB;
  8579. for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) {
  8580. MachineBasicBlock *Fallthrough;
  8581. if (I == W.LastCluster) {
  8582. // For the last cluster, fall through to the default destination.
  8583. Fallthrough = DefaultMBB;
  8584. } else {
  8585. Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock());
  8586. CurMF->insert(BBI, Fallthrough);
  8587. // Put Cond in a virtual register to make it available from the new blocks.
  8588. ExportFromCurrentBlock(Cond);
  8589. }
  8590. UnhandledProbs -= I->Prob;
  8591. switch (I->Kind) {
  8592. case CC_JumpTable: {
  8593. // FIXME: Optimize away range check based on pivot comparisons.
  8594. JumpTableHeader *JTH = &JTCases[I->JTCasesIndex].first;
  8595. JumpTable *JT = &JTCases[I->JTCasesIndex].second;
  8596. // The jump block hasn't been inserted yet; insert it here.
  8597. MachineBasicBlock *JumpMBB = JT->MBB;
  8598. CurMF->insert(BBI, JumpMBB);
  8599. auto JumpProb = I->Prob;
  8600. auto FallthroughProb = UnhandledProbs;
  8601. // If the default statement is a target of the jump table, we evenly
  8602. // distribute the default probability to successors of CurMBB. Also
  8603. // update the probability on the edge from JumpMBB to Fallthrough.
  8604. for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(),
  8605. SE = JumpMBB->succ_end();
  8606. SI != SE; ++SI) {
  8607. if (*SI == DefaultMBB) {
  8608. JumpProb += DefaultProb / 2;
  8609. FallthroughProb -= DefaultProb / 2;
  8610. JumpMBB->setSuccProbability(SI, DefaultProb / 2);
  8611. JumpMBB->normalizeSuccProbs();
  8612. break;
  8613. }
  8614. }
  8615. addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb);
  8616. addSuccessorWithProb(CurMBB, JumpMBB, JumpProb);
  8617. CurMBB->normalizeSuccProbs();
  8618. // The jump table header will be inserted in our current block, do the
  8619. // range check, and fall through to our fallthrough block.
  8620. JTH->HeaderBB = CurMBB;
  8621. JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader.
  8622. // If we're in the right place, emit the jump table header right now.
  8623. if (CurMBB == SwitchMBB) {
  8624. visitJumpTableHeader(*JT, *JTH, SwitchMBB);
  8625. JTH->Emitted = true;
  8626. }
  8627. break;
  8628. }
  8629. case CC_BitTests: {
  8630. // FIXME: Optimize away range check based on pivot comparisons.
  8631. BitTestBlock *BTB = &BitTestCases[I->BTCasesIndex];
  8632. // The bit test blocks haven't been inserted yet; insert them here.
  8633. for (BitTestCase &BTC : BTB->Cases)
  8634. CurMF->insert(BBI, BTC.ThisBB);
  8635. // Fill in fields of the BitTestBlock.
  8636. BTB->Parent = CurMBB;
  8637. BTB->Default = Fallthrough;
  8638. BTB->DefaultProb = UnhandledProbs;
  8639. // If the cases in bit test don't form a contiguous range, we evenly
  8640. // distribute the probability on the edge to Fallthrough to two
  8641. // successors of CurMBB.
  8642. if (!BTB->ContiguousRange) {
  8643. BTB->Prob += DefaultProb / 2;
  8644. BTB->DefaultProb -= DefaultProb / 2;
  8645. }
  8646. // If we're in the right place, emit the bit test header right now.
  8647. if (CurMBB == SwitchMBB) {
  8648. visitBitTestHeader(*BTB, SwitchMBB);
  8649. BTB->Emitted = true;
  8650. }
  8651. break;
  8652. }
  8653. case CC_Range: {
  8654. const Value *RHS, *LHS, *MHS;
  8655. ISD::CondCode CC;
  8656. if (I->Low == I->High) {
  8657. // Check Cond == I->Low.
  8658. CC = ISD::SETEQ;
  8659. LHS = Cond;
  8660. RHS=I->Low;
  8661. MHS = nullptr;
  8662. } else {
  8663. // Check I->Low <= Cond <= I->High.
  8664. CC = ISD::SETLE;
  8665. LHS = I->Low;
  8666. MHS = Cond;
  8667. RHS = I->High;
  8668. }
  8669. // The false probability is the sum of all unhandled cases.
  8670. CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB,
  8671. getCurSDLoc(), I->Prob, UnhandledProbs);
  8672. if (CurMBB == SwitchMBB)
  8673. visitSwitchCase(CB, SwitchMBB);
  8674. else
  8675. SwitchCases.push_back(CB);
  8676. break;
  8677. }
  8678. }
  8679. CurMBB = Fallthrough;
  8680. }
  8681. }
  8682. unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC,
  8683. CaseClusterIt First,
  8684. CaseClusterIt Last) {
  8685. return std::count_if(First, Last + 1, [&](const CaseCluster &X) {
  8686. if (X.Prob != CC.Prob)
  8687. return X.Prob > CC.Prob;
  8688. // Ties are broken by comparing the case value.
  8689. return X.Low->getValue().slt(CC.Low->getValue());
  8690. });
  8691. }
  8692. void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList,
  8693. const SwitchWorkListItem &W,
  8694. Value *Cond,
  8695. MachineBasicBlock *SwitchMBB) {
  8696. assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) &&
  8697. "Clusters not sorted?");
  8698. assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!");
  8699. // Balance the tree based on branch probabilities to create a near-optimal (in
  8700. // terms of search time given key frequency) binary search tree. See e.g. Kurt
  8701. // Mehlhorn "Nearly Optimal Binary Search Trees" (1975).
  8702. CaseClusterIt LastLeft = W.FirstCluster;
  8703. CaseClusterIt FirstRight = W.LastCluster;
  8704. auto LeftProb = LastLeft->Prob + W.DefaultProb / 2;
  8705. auto RightProb = FirstRight->Prob + W.DefaultProb / 2;
  8706. // Move LastLeft and FirstRight towards each other from opposite directions to
  8707. // find a partitioning of the clusters which balances the probability on both
  8708. // sides. If LeftProb and RightProb are equal, alternate which side is
  8709. // taken to ensure 0-probability nodes are distributed evenly.
  8710. unsigned I = 0;
  8711. while (LastLeft + 1 < FirstRight) {
  8712. if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1)))
  8713. LeftProb += (++LastLeft)->Prob;
  8714. else
  8715. RightProb += (--FirstRight)->Prob;
  8716. I++;
  8717. }
  8718. while (true) {
  8719. // Our binary search tree differs from a typical BST in that ours can have up
  8720. // to three values in each leaf. The pivot selection above doesn't take that
  8721. // into account, which means the tree might require more nodes and be less
  8722. // efficient. We compensate for this here.
  8723. unsigned NumLeft = LastLeft - W.FirstCluster + 1;
  8724. unsigned NumRight = W.LastCluster - FirstRight + 1;
  8725. if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) {
  8726. // If one side has less than 3 clusters, and the other has more than 3,
  8727. // consider taking a cluster from the other side.
  8728. if (NumLeft < NumRight) {
  8729. // Consider moving the first cluster on the right to the left side.
  8730. CaseCluster &CC = *FirstRight;
  8731. unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
  8732. unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
  8733. if (LeftSideRank <= RightSideRank) {
  8734. // Moving the cluster to the left does not demote it.
  8735. ++LastLeft;
  8736. ++FirstRight;
  8737. continue;
  8738. }
  8739. } else {
  8740. assert(NumRight < NumLeft);
  8741. // Consider moving the last element on the left to the right side.
  8742. CaseCluster &CC = *LastLeft;
  8743. unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
  8744. unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
  8745. if (RightSideRank <= LeftSideRank) {
  8746. // Moving the cluster to the right does not demot it.
  8747. --LastLeft;
  8748. --FirstRight;
  8749. continue;
  8750. }
  8751. }
  8752. }
  8753. break;
  8754. }
  8755. assert(LastLeft + 1 == FirstRight);
  8756. assert(LastLeft >= W.FirstCluster);
  8757. assert(FirstRight <= W.LastCluster);
  8758. // Use the first element on the right as pivot since we will make less-than
  8759. // comparisons against it.
  8760. CaseClusterIt PivotCluster = FirstRight;
  8761. assert(PivotCluster > W.FirstCluster);
  8762. assert(PivotCluster <= W.LastCluster);
  8763. CaseClusterIt FirstLeft = W.FirstCluster;
  8764. CaseClusterIt LastRight = W.LastCluster;
  8765. const ConstantInt *Pivot = PivotCluster->Low;
  8766. // New blocks will be inserted immediately after the current one.
  8767. MachineFunction::iterator BBI(W.MBB);
  8768. ++BBI;
  8769. // We will branch to the LHS if Value < Pivot. If LHS is a single cluster,
  8770. // we can branch to its destination directly if it's squeezed exactly in
  8771. // between the known lower bound and Pivot - 1.
  8772. MachineBasicBlock *LeftMBB;
  8773. if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range &&
  8774. FirstLeft->Low == W.GE &&
  8775. (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) {
  8776. LeftMBB = FirstLeft->MBB;
  8777. } else {
  8778. LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
  8779. FuncInfo.MF->insert(BBI, LeftMBB);
  8780. WorkList.push_back(
  8781. {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2});
  8782. // Put Cond in a virtual register to make it available from the new blocks.
  8783. ExportFromCurrentBlock(Cond);
  8784. }
  8785. // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a
  8786. // single cluster, RHS.Low == Pivot, and we can branch to its destination
  8787. // directly if RHS.High equals the current upper bound.
  8788. MachineBasicBlock *RightMBB;
  8789. if (FirstRight == LastRight && FirstRight->Kind == CC_Range &&
  8790. W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) {
  8791. RightMBB = FirstRight->MBB;
  8792. } else {
  8793. RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
  8794. FuncInfo.MF->insert(BBI, RightMBB);
  8795. WorkList.push_back(
  8796. {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2});
  8797. // Put Cond in a virtual register to make it available from the new blocks.
  8798. ExportFromCurrentBlock(Cond);
  8799. }
  8800. // Create the CaseBlock record that will be used to lower the branch.
  8801. CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB,
  8802. getCurSDLoc(), LeftProb, RightProb);
  8803. if (W.MBB == SwitchMBB)
  8804. visitSwitchCase(CB, SwitchMBB);
  8805. else
  8806. SwitchCases.push_back(CB);
  8807. }
  8808. // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb
  8809. // from the swith statement.
  8810. static BranchProbability scaleCaseProbality(BranchProbability CaseProb,
  8811. BranchProbability PeeledCaseProb) {
  8812. if (PeeledCaseProb == BranchProbability::getOne())
  8813. return BranchProbability::getZero();
  8814. BranchProbability SwitchProb = PeeledCaseProb.getCompl();
  8815. uint32_t Numerator = CaseProb.getNumerator();
  8816. uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator());
  8817. return BranchProbability(Numerator, std::max(Numerator, Denominator));
  8818. }
  8819. // Try to peel the top probability case if it exceeds the threshold.
  8820. // Return current MachineBasicBlock for the switch statement if the peeling
  8821. // does not occur.
  8822. // If the peeling is performed, return the newly created MachineBasicBlock
  8823. // for the peeled switch statement. Also update Clusters to remove the peeled
  8824. // case. PeeledCaseProb is the BranchProbability for the peeled case.
  8825. MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster(
  8826. const SwitchInst &SI, CaseClusterVector &Clusters,
  8827. BranchProbability &PeeledCaseProb) {
  8828. MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
  8829. // Don't perform if there is only one cluster or optimizing for size.
  8830. if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 ||
  8831. TM.getOptLevel() == CodeGenOpt::None ||
  8832. SwitchMBB->getParent()->getFunction().optForMinSize())
  8833. return SwitchMBB;
  8834. BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100);
  8835. unsigned PeeledCaseIndex = 0;
  8836. bool SwitchPeeled = false;
  8837. for (unsigned Index = 0; Index < Clusters.size(); ++Index) {
  8838. CaseCluster &CC = Clusters[Index];
  8839. if (CC.Prob < TopCaseProb)
  8840. continue;
  8841. TopCaseProb = CC.Prob;
  8842. PeeledCaseIndex = Index;
  8843. SwitchPeeled = true;
  8844. }
  8845. if (!SwitchPeeled)
  8846. return SwitchMBB;
  8847. DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: " << TopCaseProb
  8848. << "\n");
  8849. // Record the MBB for the peeled switch statement.
  8850. MachineFunction::iterator BBI(SwitchMBB);
  8851. ++BBI;
  8852. MachineBasicBlock *PeeledSwitchMBB =
  8853. FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock());
  8854. FuncInfo.MF->insert(BBI, PeeledSwitchMBB);
  8855. ExportFromCurrentBlock(SI.getCondition());
  8856. auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex;
  8857. SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt,
  8858. nullptr, nullptr, TopCaseProb.getCompl()};
  8859. lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB);
  8860. Clusters.erase(PeeledCaseIt);
  8861. for (CaseCluster &CC : Clusters) {
  8862. DEBUG(dbgs() << "Scale the probablity for one cluster, before scaling: "
  8863. << CC.Prob << "\n");
  8864. CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb);
  8865. DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n");
  8866. }
  8867. PeeledCaseProb = TopCaseProb;
  8868. return PeeledSwitchMBB;
  8869. }
  8870. void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) {
  8871. // Extract cases from the switch.
  8872. BranchProbabilityInfo *BPI = FuncInfo.BPI;
  8873. CaseClusterVector Clusters;
  8874. Clusters.reserve(SI.getNumCases());
  8875. for (auto I : SI.cases()) {
  8876. MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()];
  8877. const ConstantInt *CaseVal = I.getCaseValue();
  8878. BranchProbability Prob =
  8879. BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex())
  8880. : BranchProbability(1, SI.getNumCases() + 1);
  8881. Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob));
  8882. }
  8883. MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()];
  8884. // Cluster adjacent cases with the same destination. We do this at all
  8885. // optimization levels because it's cheap to do and will make codegen faster
  8886. // if there are many clusters.
  8887. sortAndRangeify(Clusters);
  8888. if (TM.getOptLevel() != CodeGenOpt::None) {
  8889. // Replace an unreachable default with the most popular destination.
  8890. // FIXME: Exploit unreachable default more aggressively.
  8891. bool UnreachableDefault =
  8892. isa<UnreachableInst>(SI.getDefaultDest()->getFirstNonPHIOrDbg());
  8893. if (UnreachableDefault && !Clusters.empty()) {
  8894. DenseMap<const BasicBlock *, unsigned> Popularity;
  8895. unsigned MaxPop = 0;
  8896. const BasicBlock *MaxBB = nullptr;
  8897. for (auto I : SI.cases()) {
  8898. const BasicBlock *BB = I.getCaseSuccessor();
  8899. if (++Popularity[BB] > MaxPop) {
  8900. MaxPop = Popularity[BB];
  8901. MaxBB = BB;
  8902. }
  8903. }
  8904. // Set new default.
  8905. assert(MaxPop > 0 && MaxBB);
  8906. DefaultMBB = FuncInfo.MBBMap[MaxBB];
  8907. // Remove cases that were pointing to the destination that is now the
  8908. // default.
  8909. CaseClusterVector New;
  8910. New.reserve(Clusters.size());
  8911. for (CaseCluster &CC : Clusters) {
  8912. if (CC.MBB != DefaultMBB)
  8913. New.push_back(CC);
  8914. }
  8915. Clusters = std::move(New);
  8916. }
  8917. }
  8918. // The branch probablity of the peeled case.
  8919. BranchProbability PeeledCaseProb = BranchProbability::getZero();
  8920. MachineBasicBlock *PeeledSwitchMBB =
  8921. peelDominantCaseCluster(SI, Clusters, PeeledCaseProb);
  8922. // If there is only the default destination, jump there directly.
  8923. MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
  8924. if (Clusters.empty()) {
  8925. assert(PeeledSwitchMBB == SwitchMBB);
  8926. SwitchMBB->addSuccessor(DefaultMBB);
  8927. if (DefaultMBB != NextBlock(SwitchMBB)) {
  8928. DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
  8929. getControlRoot(), DAG.getBasicBlock(DefaultMBB)));
  8930. }
  8931. return;
  8932. }
  8933. findJumpTables(Clusters, &SI, DefaultMBB);
  8934. findBitTestClusters(Clusters, &SI);
  8935. DEBUG({
  8936. dbgs() << "Case clusters: ";
  8937. for (const CaseCluster &C : Clusters) {
  8938. if (C.Kind == CC_JumpTable) dbgs() << "JT:";
  8939. if (C.Kind == CC_BitTests) dbgs() << "BT:";
  8940. C.Low->getValue().print(dbgs(), true);
  8941. if (C.Low != C.High) {
  8942. dbgs() << '-';
  8943. C.High->getValue().print(dbgs(), true);
  8944. }
  8945. dbgs() << ' ';
  8946. }
  8947. dbgs() << '\n';
  8948. });
  8949. assert(!Clusters.empty());
  8950. SwitchWorkList WorkList;
  8951. CaseClusterIt First = Clusters.begin();
  8952. CaseClusterIt Last = Clusters.end() - 1;
  8953. auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB);
  8954. // Scale the branchprobability for DefaultMBB if the peel occurs and
  8955. // DefaultMBB is not replaced.
  8956. if (PeeledCaseProb != BranchProbability::getZero() &&
  8957. DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()])
  8958. DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb);
  8959. WorkList.push_back(
  8960. {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb});
  8961. while (!WorkList.empty()) {
  8962. SwitchWorkListItem W = WorkList.back();
  8963. WorkList.pop_back();
  8964. unsigned NumClusters = W.LastCluster - W.FirstCluster + 1;
  8965. if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None &&
  8966. !DefaultMBB->getParent()->getFunction().optForMinSize()) {
  8967. // For optimized builds, lower large range as a balanced binary tree.
  8968. splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB);
  8969. continue;
  8970. }
  8971. lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB);
  8972. }
  8973. }