DAGCombiner.cpp 1017 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462
  1. //===- DAGCombiner.cpp - Implement a DAG node combiner --------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This pass combines dag nodes to form fewer, simpler DAG nodes. It can be run
  10. // both before and after the DAG is legalized.
  11. //
  12. // This pass is not a substitute for the LLVM IR instcombine pass. This pass is
  13. // primarily intended to handle simplification opportunities that are implicit
  14. // in the LLVM IR and exposed by the various codegen lowering phases.
  15. //
  16. //===----------------------------------------------------------------------===//
  17. #include "llvm/ADT/APFloat.h"
  18. #include "llvm/ADT/APInt.h"
  19. #include "llvm/ADT/ArrayRef.h"
  20. #include "llvm/ADT/DenseMap.h"
  21. #include "llvm/ADT/IntervalMap.h"
  22. #include "llvm/ADT/STLExtras.h"
  23. #include "llvm/ADT/SetVector.h"
  24. #include "llvm/ADT/SmallBitVector.h"
  25. #include "llvm/ADT/SmallPtrSet.h"
  26. #include "llvm/ADT/SmallSet.h"
  27. #include "llvm/ADT/SmallVector.h"
  28. #include "llvm/ADT/Statistic.h"
  29. #include "llvm/Analysis/AliasAnalysis.h"
  30. #include "llvm/Analysis/MemoryLocation.h"
  31. #include "llvm/Analysis/TargetLibraryInfo.h"
  32. #include "llvm/Analysis/VectorUtils.h"
  33. #include "llvm/CodeGen/DAGCombine.h"
  34. #include "llvm/CodeGen/ISDOpcodes.h"
  35. #include "llvm/CodeGen/MachineFunction.h"
  36. #include "llvm/CodeGen/MachineMemOperand.h"
  37. #include "llvm/CodeGen/RuntimeLibcalls.h"
  38. #include "llvm/CodeGen/SelectionDAG.h"
  39. #include "llvm/CodeGen/SelectionDAGAddressAnalysis.h"
  40. #include "llvm/CodeGen/SelectionDAGNodes.h"
  41. #include "llvm/CodeGen/SelectionDAGTargetInfo.h"
  42. #include "llvm/CodeGen/TargetLowering.h"
  43. #include "llvm/CodeGen/TargetRegisterInfo.h"
  44. #include "llvm/CodeGen/TargetSubtargetInfo.h"
  45. #include "llvm/CodeGen/ValueTypes.h"
  46. #include "llvm/IR/Attributes.h"
  47. #include "llvm/IR/Constant.h"
  48. #include "llvm/IR/DataLayout.h"
  49. #include "llvm/IR/DerivedTypes.h"
  50. #include "llvm/IR/Function.h"
  51. #include "llvm/IR/Metadata.h"
  52. #include "llvm/Support/Casting.h"
  53. #include "llvm/Support/CodeGen.h"
  54. #include "llvm/Support/CommandLine.h"
  55. #include "llvm/Support/Compiler.h"
  56. #include "llvm/Support/Debug.h"
  57. #include "llvm/Support/ErrorHandling.h"
  58. #include "llvm/Support/KnownBits.h"
  59. #include "llvm/Support/MachineValueType.h"
  60. #include "llvm/Support/MathExtras.h"
  61. #include "llvm/Support/raw_ostream.h"
  62. #include "llvm/Target/TargetMachine.h"
  63. #include "llvm/Target/TargetOptions.h"
  64. #include <algorithm>
  65. #include <cassert>
  66. #include <cstdint>
  67. #include <functional>
  68. #include <iterator>
  69. #include <optional>
  70. #include <string>
  71. #include <tuple>
  72. #include <utility>
  73. #include <variant>
  74. using namespace llvm;
  75. #define DEBUG_TYPE "dagcombine"
  76. STATISTIC(NodesCombined , "Number of dag nodes combined");
  77. STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created");
  78. STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created");
  79. STATISTIC(OpsNarrowed , "Number of load/op/store narrowed");
  80. STATISTIC(LdStFP2Int , "Number of fp load/store pairs transformed to int");
  81. STATISTIC(SlicedLoads, "Number of load sliced");
  82. STATISTIC(NumFPLogicOpsConv, "Number of logic ops converted to fp ops");
  83. static cl::opt<bool>
  84. CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
  85. cl::desc("Enable DAG combiner's use of IR alias analysis"));
  86. static cl::opt<bool>
  87. UseTBAA("combiner-use-tbaa", cl::Hidden, cl::init(true),
  88. cl::desc("Enable DAG combiner's use of TBAA"));
  89. #ifndef NDEBUG
  90. static cl::opt<std::string>
  91. CombinerAAOnlyFunc("combiner-aa-only-func", cl::Hidden,
  92. cl::desc("Only use DAG-combiner alias analysis in this"
  93. " function"));
  94. #endif
  95. /// Hidden option to stress test load slicing, i.e., when this option
  96. /// is enabled, load slicing bypasses most of its profitability guards.
  97. static cl::opt<bool>
  98. StressLoadSlicing("combiner-stress-load-slicing", cl::Hidden,
  99. cl::desc("Bypass the profitability model of load slicing"),
  100. cl::init(false));
  101. static cl::opt<bool>
  102. MaySplitLoadIndex("combiner-split-load-index", cl::Hidden, cl::init(true),
  103. cl::desc("DAG combiner may split indexing from loads"));
  104. static cl::opt<bool>
  105. EnableStoreMerging("combiner-store-merging", cl::Hidden, cl::init(true),
  106. cl::desc("DAG combiner enable merging multiple stores "
  107. "into a wider store"));
  108. static cl::opt<unsigned> TokenFactorInlineLimit(
  109. "combiner-tokenfactor-inline-limit", cl::Hidden, cl::init(2048),
  110. cl::desc("Limit the number of operands to inline for Token Factors"));
  111. static cl::opt<unsigned> StoreMergeDependenceLimit(
  112. "combiner-store-merge-dependence-limit", cl::Hidden, cl::init(10),
  113. cl::desc("Limit the number of times for the same StoreNode and RootNode "
  114. "to bail out in store merging dependence check"));
  115. static cl::opt<bool> EnableReduceLoadOpStoreWidth(
  116. "combiner-reduce-load-op-store-width", cl::Hidden, cl::init(true),
  117. cl::desc("DAG combiner enable reducing the width of load/op/store "
  118. "sequence"));
  119. static cl::opt<bool> EnableShrinkLoadReplaceStoreWithStore(
  120. "combiner-shrink-load-replace-store-with-store", cl::Hidden, cl::init(true),
  121. cl::desc("DAG combiner enable load/<replace bytes>/store with "
  122. "a narrower store"));
  123. static cl::opt<bool> EnableVectorFCopySignExtendRound(
  124. "combiner-vector-fcopysign-extend-round", cl::Hidden, cl::init(false),
  125. cl::desc(
  126. "Enable merging extends and rounds into FCOPYSIGN on vector types"));
  127. namespace {
  128. class DAGCombiner {
  129. SelectionDAG &DAG;
  130. const TargetLowering &TLI;
  131. const SelectionDAGTargetInfo *STI;
  132. CombineLevel Level = BeforeLegalizeTypes;
  133. CodeGenOpt::Level OptLevel;
  134. bool LegalDAG = false;
  135. bool LegalOperations = false;
  136. bool LegalTypes = false;
  137. bool ForCodeSize;
  138. bool DisableGenericCombines;
  139. /// Worklist of all of the nodes that need to be simplified.
  140. ///
  141. /// This must behave as a stack -- new nodes to process are pushed onto the
  142. /// back and when processing we pop off of the back.
  143. ///
  144. /// The worklist will not contain duplicates but may contain null entries
  145. /// due to nodes being deleted from the underlying DAG.
  146. SmallVector<SDNode *, 64> Worklist;
  147. /// Mapping from an SDNode to its position on the worklist.
  148. ///
  149. /// This is used to find and remove nodes from the worklist (by nulling
  150. /// them) when they are deleted from the underlying DAG. It relies on
  151. /// stable indices of nodes within the worklist.
  152. DenseMap<SDNode *, unsigned> WorklistMap;
  153. /// This records all nodes attempted to add to the worklist since we
  154. /// considered a new worklist entry. As we keep do not add duplicate nodes
  155. /// in the worklist, this is different from the tail of the worklist.
  156. SmallSetVector<SDNode *, 32> PruningList;
  157. /// Set of nodes which have been combined (at least once).
  158. ///
  159. /// This is used to allow us to reliably add any operands of a DAG node
  160. /// which have not yet been combined to the worklist.
  161. SmallPtrSet<SDNode *, 32> CombinedNodes;
  162. /// Map from candidate StoreNode to the pair of RootNode and count.
  163. /// The count is used to track how many times we have seen the StoreNode
  164. /// with the same RootNode bail out in dependence check. If we have seen
  165. /// the bail out for the same pair many times over a limit, we won't
  166. /// consider the StoreNode with the same RootNode as store merging
  167. /// candidate again.
  168. DenseMap<SDNode *, std::pair<SDNode *, unsigned>> StoreRootCountMap;
  169. // AA - Used for DAG load/store alias analysis.
  170. AliasAnalysis *AA;
  171. /// When an instruction is simplified, add all users of the instruction to
  172. /// the work lists because they might get more simplified now.
  173. void AddUsersToWorklist(SDNode *N) {
  174. for (SDNode *Node : N->uses())
  175. AddToWorklist(Node);
  176. }
  177. /// Convenient shorthand to add a node and all of its user to the worklist.
  178. void AddToWorklistWithUsers(SDNode *N) {
  179. AddUsersToWorklist(N);
  180. AddToWorklist(N);
  181. }
  182. // Prune potentially dangling nodes. This is called after
  183. // any visit to a node, but should also be called during a visit after any
  184. // failed combine which may have created a DAG node.
  185. void clearAddedDanglingWorklistEntries() {
  186. // Check any nodes added to the worklist to see if they are prunable.
  187. while (!PruningList.empty()) {
  188. auto *N = PruningList.pop_back_val();
  189. if (N->use_empty())
  190. recursivelyDeleteUnusedNodes(N);
  191. }
  192. }
  193. SDNode *getNextWorklistEntry() {
  194. // Before we do any work, remove nodes that are not in use.
  195. clearAddedDanglingWorklistEntries();
  196. SDNode *N = nullptr;
  197. // The Worklist holds the SDNodes in order, but it may contain null
  198. // entries.
  199. while (!N && !Worklist.empty()) {
  200. N = Worklist.pop_back_val();
  201. }
  202. if (N) {
  203. bool GoodWorklistEntry = WorklistMap.erase(N);
  204. (void)GoodWorklistEntry;
  205. assert(GoodWorklistEntry &&
  206. "Found a worklist entry without a corresponding map entry!");
  207. }
  208. return N;
  209. }
  210. /// Call the node-specific routine that folds each particular type of node.
  211. SDValue visit(SDNode *N);
  212. public:
  213. DAGCombiner(SelectionDAG &D, AliasAnalysis *AA, CodeGenOpt::Level OL)
  214. : DAG(D), TLI(D.getTargetLoweringInfo()),
  215. STI(D.getSubtarget().getSelectionDAGInfo()), OptLevel(OL), AA(AA) {
  216. ForCodeSize = DAG.shouldOptForSize();
  217. DisableGenericCombines = STI && STI->disableGenericCombines(OptLevel);
  218. MaximumLegalStoreInBits = 0;
  219. // We use the minimum store size here, since that's all we can guarantee
  220. // for the scalable vector types.
  221. for (MVT VT : MVT::all_valuetypes())
  222. if (EVT(VT).isSimple() && VT != MVT::Other &&
  223. TLI.isTypeLegal(EVT(VT)) &&
  224. VT.getSizeInBits().getKnownMinValue() >= MaximumLegalStoreInBits)
  225. MaximumLegalStoreInBits = VT.getSizeInBits().getKnownMinValue();
  226. }
  227. void ConsiderForPruning(SDNode *N) {
  228. // Mark this for potential pruning.
  229. PruningList.insert(N);
  230. }
  231. /// Add to the worklist making sure its instance is at the back (next to be
  232. /// processed.)
  233. void AddToWorklist(SDNode *N) {
  234. assert(N->getOpcode() != ISD::DELETED_NODE &&
  235. "Deleted Node added to Worklist");
  236. // Skip handle nodes as they can't usefully be combined and confuse the
  237. // zero-use deletion strategy.
  238. if (N->getOpcode() == ISD::HANDLENODE)
  239. return;
  240. ConsiderForPruning(N);
  241. if (WorklistMap.insert(std::make_pair(N, Worklist.size())).second)
  242. Worklist.push_back(N);
  243. }
  244. /// Remove all instances of N from the worklist.
  245. void removeFromWorklist(SDNode *N) {
  246. CombinedNodes.erase(N);
  247. PruningList.remove(N);
  248. StoreRootCountMap.erase(N);
  249. auto It = WorklistMap.find(N);
  250. if (It == WorklistMap.end())
  251. return; // Not in the worklist.
  252. // Null out the entry rather than erasing it to avoid a linear operation.
  253. Worklist[It->second] = nullptr;
  254. WorklistMap.erase(It);
  255. }
  256. void deleteAndRecombine(SDNode *N);
  257. bool recursivelyDeleteUnusedNodes(SDNode *N);
  258. /// Replaces all uses of the results of one DAG node with new values.
  259. SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
  260. bool AddTo = true);
  261. /// Replaces all uses of the results of one DAG node with new values.
  262. SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
  263. return CombineTo(N, &Res, 1, AddTo);
  264. }
  265. /// Replaces all uses of the results of one DAG node with new values.
  266. SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
  267. bool AddTo = true) {
  268. SDValue To[] = { Res0, Res1 };
  269. return CombineTo(N, To, 2, AddTo);
  270. }
  271. void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
  272. private:
  273. unsigned MaximumLegalStoreInBits;
  274. /// Check the specified integer node value to see if it can be simplified or
  275. /// if things it uses can be simplified by bit propagation.
  276. /// If so, return true.
  277. bool SimplifyDemandedBits(SDValue Op) {
  278. unsigned BitWidth = Op.getScalarValueSizeInBits();
  279. APInt DemandedBits = APInt::getAllOnes(BitWidth);
  280. return SimplifyDemandedBits(Op, DemandedBits);
  281. }
  282. bool SimplifyDemandedBits(SDValue Op, const APInt &DemandedBits) {
  283. TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
  284. KnownBits Known;
  285. if (!TLI.SimplifyDemandedBits(Op, DemandedBits, Known, TLO, 0, false))
  286. return false;
  287. // Revisit the node.
  288. AddToWorklist(Op.getNode());
  289. CommitTargetLoweringOpt(TLO);
  290. return true;
  291. }
  292. /// Check the specified vector node value to see if it can be simplified or
  293. /// if things it uses can be simplified as it only uses some of the
  294. /// elements. If so, return true.
  295. bool SimplifyDemandedVectorElts(SDValue Op) {
  296. // TODO: For now just pretend it cannot be simplified.
  297. if (Op.getValueType().isScalableVector())
  298. return false;
  299. unsigned NumElts = Op.getValueType().getVectorNumElements();
  300. APInt DemandedElts = APInt::getAllOnes(NumElts);
  301. return SimplifyDemandedVectorElts(Op, DemandedElts);
  302. }
  303. bool SimplifyDemandedBits(SDValue Op, const APInt &DemandedBits,
  304. const APInt &DemandedElts,
  305. bool AssumeSingleUse = false);
  306. bool SimplifyDemandedVectorElts(SDValue Op, const APInt &DemandedElts,
  307. bool AssumeSingleUse = false);
  308. bool CombineToPreIndexedLoadStore(SDNode *N);
  309. bool CombineToPostIndexedLoadStore(SDNode *N);
  310. SDValue SplitIndexingFromLoad(LoadSDNode *LD);
  311. bool SliceUpLoad(SDNode *N);
  312. // Scalars have size 0 to distinguish from singleton vectors.
  313. SDValue ForwardStoreValueToDirectLoad(LoadSDNode *LD);
  314. bool getTruncatedStoreValue(StoreSDNode *ST, SDValue &Val);
  315. bool extendLoadedValueToExtension(LoadSDNode *LD, SDValue &Val);
  316. /// Replace an ISD::EXTRACT_VECTOR_ELT of a load with a narrowed
  317. /// load.
  318. ///
  319. /// \param EVE ISD::EXTRACT_VECTOR_ELT to be replaced.
  320. /// \param InVecVT type of the input vector to EVE with bitcasts resolved.
  321. /// \param EltNo index of the vector element to load.
  322. /// \param OriginalLoad load that EVE came from to be replaced.
  323. /// \returns EVE on success SDValue() on failure.
  324. SDValue scalarizeExtractedVectorLoad(SDNode *EVE, EVT InVecVT,
  325. SDValue EltNo,
  326. LoadSDNode *OriginalLoad);
  327. void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
  328. SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
  329. SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
  330. SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
  331. SDValue PromoteIntBinOp(SDValue Op);
  332. SDValue PromoteIntShiftOp(SDValue Op);
  333. SDValue PromoteExtend(SDValue Op);
  334. bool PromoteLoad(SDValue Op);
  335. SDValue combineMinNumMaxNum(const SDLoc &DL, EVT VT, SDValue LHS,
  336. SDValue RHS, SDValue True, SDValue False,
  337. ISD::CondCode CC);
  338. /// Call the node-specific routine that knows how to fold each
  339. /// particular type of node. If that doesn't do anything, try the
  340. /// target-specific DAG combines.
  341. SDValue combine(SDNode *N);
  342. // Visitation implementation - Implement dag node combining for different
  343. // node types. The semantics are as follows:
  344. // Return Value:
  345. // SDValue.getNode() == 0 - No change was made
  346. // SDValue.getNode() == N - N was replaced, is dead and has been handled.
  347. // otherwise - N should be replaced by the returned Operand.
  348. //
  349. SDValue visitTokenFactor(SDNode *N);
  350. SDValue visitMERGE_VALUES(SDNode *N);
  351. SDValue visitADD(SDNode *N);
  352. SDValue visitADDLike(SDNode *N);
  353. SDValue visitADDLikeCommutative(SDValue N0, SDValue N1, SDNode *LocReference);
  354. SDValue visitSUB(SDNode *N);
  355. SDValue visitADDSAT(SDNode *N);
  356. SDValue visitSUBSAT(SDNode *N);
  357. SDValue visitADDC(SDNode *N);
  358. SDValue visitADDO(SDNode *N);
  359. SDValue visitUADDOLike(SDValue N0, SDValue N1, SDNode *N);
  360. SDValue visitSUBC(SDNode *N);
  361. SDValue visitSUBO(SDNode *N);
  362. SDValue visitADDE(SDNode *N);
  363. SDValue visitADDCARRY(SDNode *N);
  364. SDValue visitSADDO_CARRY(SDNode *N);
  365. SDValue visitADDCARRYLike(SDValue N0, SDValue N1, SDValue CarryIn, SDNode *N);
  366. SDValue visitSUBE(SDNode *N);
  367. SDValue visitSUBCARRY(SDNode *N);
  368. SDValue visitSSUBO_CARRY(SDNode *N);
  369. SDValue visitMUL(SDNode *N);
  370. SDValue visitMULFIX(SDNode *N);
  371. SDValue useDivRem(SDNode *N);
  372. SDValue visitSDIV(SDNode *N);
  373. SDValue visitSDIVLike(SDValue N0, SDValue N1, SDNode *N);
  374. SDValue visitUDIV(SDNode *N);
  375. SDValue visitUDIVLike(SDValue N0, SDValue N1, SDNode *N);
  376. SDValue visitREM(SDNode *N);
  377. SDValue visitMULHU(SDNode *N);
  378. SDValue visitMULHS(SDNode *N);
  379. SDValue visitAVG(SDNode *N);
  380. SDValue visitSMUL_LOHI(SDNode *N);
  381. SDValue visitUMUL_LOHI(SDNode *N);
  382. SDValue visitMULO(SDNode *N);
  383. SDValue visitIMINMAX(SDNode *N);
  384. SDValue visitAND(SDNode *N);
  385. SDValue visitANDLike(SDValue N0, SDValue N1, SDNode *N);
  386. SDValue visitOR(SDNode *N);
  387. SDValue visitORLike(SDValue N0, SDValue N1, SDNode *N);
  388. SDValue visitXOR(SDNode *N);
  389. SDValue SimplifyVCastOp(SDNode *N, const SDLoc &DL);
  390. SDValue SimplifyVBinOp(SDNode *N, const SDLoc &DL);
  391. SDValue visitSHL(SDNode *N);
  392. SDValue visitSRA(SDNode *N);
  393. SDValue visitSRL(SDNode *N);
  394. SDValue visitFunnelShift(SDNode *N);
  395. SDValue visitSHLSAT(SDNode *N);
  396. SDValue visitRotate(SDNode *N);
  397. SDValue visitABS(SDNode *N);
  398. SDValue visitBSWAP(SDNode *N);
  399. SDValue visitBITREVERSE(SDNode *N);
  400. SDValue visitCTLZ(SDNode *N);
  401. SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
  402. SDValue visitCTTZ(SDNode *N);
  403. SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
  404. SDValue visitCTPOP(SDNode *N);
  405. SDValue visitSELECT(SDNode *N);
  406. SDValue visitVSELECT(SDNode *N);
  407. SDValue visitSELECT_CC(SDNode *N);
  408. SDValue visitSETCC(SDNode *N);
  409. SDValue visitSETCCCARRY(SDNode *N);
  410. SDValue visitSIGN_EXTEND(SDNode *N);
  411. SDValue visitZERO_EXTEND(SDNode *N);
  412. SDValue visitANY_EXTEND(SDNode *N);
  413. SDValue visitAssertExt(SDNode *N);
  414. SDValue visitAssertAlign(SDNode *N);
  415. SDValue visitSIGN_EXTEND_INREG(SDNode *N);
  416. SDValue visitEXTEND_VECTOR_INREG(SDNode *N);
  417. SDValue visitTRUNCATE(SDNode *N);
  418. SDValue visitBITCAST(SDNode *N);
  419. SDValue visitFREEZE(SDNode *N);
  420. SDValue visitBUILD_PAIR(SDNode *N);
  421. SDValue visitFADD(SDNode *N);
  422. SDValue visitSTRICT_FADD(SDNode *N);
  423. SDValue visitFSUB(SDNode *N);
  424. SDValue visitFMUL(SDNode *N);
  425. SDValue visitFMA(SDNode *N);
  426. SDValue visitFDIV(SDNode *N);
  427. SDValue visitFREM(SDNode *N);
  428. SDValue visitFSQRT(SDNode *N);
  429. SDValue visitFCOPYSIGN(SDNode *N);
  430. SDValue visitFPOW(SDNode *N);
  431. SDValue visitSINT_TO_FP(SDNode *N);
  432. SDValue visitUINT_TO_FP(SDNode *N);
  433. SDValue visitFP_TO_SINT(SDNode *N);
  434. SDValue visitFP_TO_UINT(SDNode *N);
  435. SDValue visitFP_ROUND(SDNode *N);
  436. SDValue visitFP_EXTEND(SDNode *N);
  437. SDValue visitFNEG(SDNode *N);
  438. SDValue visitFABS(SDNode *N);
  439. SDValue visitFCEIL(SDNode *N);
  440. SDValue visitFTRUNC(SDNode *N);
  441. SDValue visitFFLOOR(SDNode *N);
  442. SDValue visitFMinMax(SDNode *N);
  443. SDValue visitBRCOND(SDNode *N);
  444. SDValue visitBR_CC(SDNode *N);
  445. SDValue visitLOAD(SDNode *N);
  446. SDValue replaceStoreChain(StoreSDNode *ST, SDValue BetterChain);
  447. SDValue replaceStoreOfFPConstant(StoreSDNode *ST);
  448. bool refineExtractVectorEltIntoMultipleNarrowExtractVectorElts(SDNode *N);
  449. SDValue visitSTORE(SDNode *N);
  450. SDValue visitLIFETIME_END(SDNode *N);
  451. SDValue visitINSERT_VECTOR_ELT(SDNode *N);
  452. SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
  453. SDValue visitBUILD_VECTOR(SDNode *N);
  454. SDValue visitCONCAT_VECTORS(SDNode *N);
  455. SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
  456. SDValue visitVECTOR_SHUFFLE(SDNode *N);
  457. SDValue visitSCALAR_TO_VECTOR(SDNode *N);
  458. SDValue visitINSERT_SUBVECTOR(SDNode *N);
  459. SDValue visitMLOAD(SDNode *N);
  460. SDValue visitMSTORE(SDNode *N);
  461. SDValue visitMGATHER(SDNode *N);
  462. SDValue visitMSCATTER(SDNode *N);
  463. SDValue visitVPGATHER(SDNode *N);
  464. SDValue visitVPSCATTER(SDNode *N);
  465. SDValue visitFP_TO_FP16(SDNode *N);
  466. SDValue visitFP16_TO_FP(SDNode *N);
  467. SDValue visitFP_TO_BF16(SDNode *N);
  468. SDValue visitVECREDUCE(SDNode *N);
  469. SDValue visitVPOp(SDNode *N);
  470. SDValue visitFADDForFMACombine(SDNode *N);
  471. SDValue visitFSUBForFMACombine(SDNode *N);
  472. SDValue visitFMULForFMADistributiveCombine(SDNode *N);
  473. SDValue XformToShuffleWithZero(SDNode *N);
  474. bool reassociationCanBreakAddressingModePattern(unsigned Opc,
  475. const SDLoc &DL,
  476. SDNode *N,
  477. SDValue N0,
  478. SDValue N1);
  479. SDValue reassociateOpsCommutative(unsigned Opc, const SDLoc &DL, SDValue N0,
  480. SDValue N1);
  481. SDValue reassociateOps(unsigned Opc, const SDLoc &DL, SDValue N0,
  482. SDValue N1, SDNodeFlags Flags);
  483. SDValue visitShiftByConstant(SDNode *N);
  484. SDValue foldSelectOfConstants(SDNode *N);
  485. SDValue foldVSelectOfConstants(SDNode *N);
  486. SDValue foldBinOpIntoSelect(SDNode *BO);
  487. bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
  488. SDValue hoistLogicOpWithSameOpcodeHands(SDNode *N);
  489. SDValue SimplifySelect(const SDLoc &DL, SDValue N0, SDValue N1, SDValue N2);
  490. SDValue SimplifySelectCC(const SDLoc &DL, SDValue N0, SDValue N1,
  491. SDValue N2, SDValue N3, ISD::CondCode CC,
  492. bool NotExtCompare = false);
  493. SDValue convertSelectOfFPConstantsToLoadOffset(
  494. const SDLoc &DL, SDValue N0, SDValue N1, SDValue N2, SDValue N3,
  495. ISD::CondCode CC);
  496. SDValue foldSignChangeInBitcast(SDNode *N);
  497. SDValue foldSelectCCToShiftAnd(const SDLoc &DL, SDValue N0, SDValue N1,
  498. SDValue N2, SDValue N3, ISD::CondCode CC);
  499. SDValue foldSelectOfBinops(SDNode *N);
  500. SDValue foldSextSetcc(SDNode *N);
  501. SDValue foldLogicOfSetCCs(bool IsAnd, SDValue N0, SDValue N1,
  502. const SDLoc &DL);
  503. SDValue foldSubToUSubSat(EVT DstVT, SDNode *N);
  504. SDValue foldABSToABD(SDNode *N);
  505. SDValue unfoldMaskedMerge(SDNode *N);
  506. SDValue unfoldExtremeBitClearingToShifts(SDNode *N);
  507. SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
  508. const SDLoc &DL, bool foldBooleans);
  509. SDValue rebuildSetCC(SDValue N);
  510. bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
  511. SDValue &CC, bool MatchStrict = false) const;
  512. bool isOneUseSetCC(SDValue N) const;
  513. SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
  514. unsigned HiOp);
  515. SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
  516. SDValue CombineExtLoad(SDNode *N);
  517. SDValue CombineZExtLogicopShiftLoad(SDNode *N);
  518. SDValue combineRepeatedFPDivisors(SDNode *N);
  519. SDValue mergeInsertEltWithShuffle(SDNode *N, unsigned InsIndex);
  520. SDValue combineInsertEltToShuffle(SDNode *N, unsigned InsIndex);
  521. SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
  522. SDValue BuildSDIV(SDNode *N);
  523. SDValue BuildSDIVPow2(SDNode *N);
  524. SDValue BuildUDIV(SDNode *N);
  525. SDValue BuildSREMPow2(SDNode *N);
  526. SDValue buildOptimizedSREM(SDValue N0, SDValue N1, SDNode *N);
  527. SDValue BuildLogBase2(SDValue V, const SDLoc &DL);
  528. SDValue BuildDivEstimate(SDValue N, SDValue Op, SDNodeFlags Flags);
  529. SDValue buildRsqrtEstimate(SDValue Op, SDNodeFlags Flags);
  530. SDValue buildSqrtEstimate(SDValue Op, SDNodeFlags Flags);
  531. SDValue buildSqrtEstimateImpl(SDValue Op, SDNodeFlags Flags, bool Recip);
  532. SDValue buildSqrtNROneConst(SDValue Arg, SDValue Est, unsigned Iterations,
  533. SDNodeFlags Flags, bool Reciprocal);
  534. SDValue buildSqrtNRTwoConst(SDValue Arg, SDValue Est, unsigned Iterations,
  535. SDNodeFlags Flags, bool Reciprocal);
  536. SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
  537. bool DemandHighBits = true);
  538. SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
  539. SDValue MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
  540. SDValue InnerPos, SDValue InnerNeg, bool HasPos,
  541. unsigned PosOpcode, unsigned NegOpcode,
  542. const SDLoc &DL);
  543. SDValue MatchFunnelPosNeg(SDValue N0, SDValue N1, SDValue Pos, SDValue Neg,
  544. SDValue InnerPos, SDValue InnerNeg, bool HasPos,
  545. unsigned PosOpcode, unsigned NegOpcode,
  546. const SDLoc &DL);
  547. SDValue MatchRotate(SDValue LHS, SDValue RHS, const SDLoc &DL);
  548. SDValue MatchLoadCombine(SDNode *N);
  549. SDValue mergeTruncStores(StoreSDNode *N);
  550. SDValue reduceLoadWidth(SDNode *N);
  551. SDValue ReduceLoadOpStoreWidth(SDNode *N);
  552. SDValue splitMergedValStore(StoreSDNode *ST);
  553. SDValue TransformFPLoadStorePair(SDNode *N);
  554. SDValue convertBuildVecZextToZext(SDNode *N);
  555. SDValue convertBuildVecZextToBuildVecWithZeros(SDNode *N);
  556. SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
  557. SDValue reduceBuildVecTruncToBitCast(SDNode *N);
  558. SDValue reduceBuildVecToShuffle(SDNode *N);
  559. SDValue createBuildVecShuffle(const SDLoc &DL, SDNode *N,
  560. ArrayRef<int> VectorMask, SDValue VecIn1,
  561. SDValue VecIn2, unsigned LeftIdx,
  562. bool DidSplitVec);
  563. SDValue matchVSelectOpSizesWithSetCC(SDNode *Cast);
  564. /// Walk up chain skipping non-aliasing memory nodes,
  565. /// looking for aliasing nodes and adding them to the Aliases vector.
  566. void GatherAllAliases(SDNode *N, SDValue OriginalChain,
  567. SmallVectorImpl<SDValue> &Aliases);
  568. /// Return true if there is any possibility that the two addresses overlap.
  569. bool mayAlias(SDNode *Op0, SDNode *Op1) const;
  570. /// Walk up chain skipping non-aliasing memory nodes, looking for a better
  571. /// chain (aliasing node.)
  572. SDValue FindBetterChain(SDNode *N, SDValue Chain);
  573. /// Try to replace a store and any possibly adjacent stores on
  574. /// consecutive chains with better chains. Return true only if St is
  575. /// replaced.
  576. ///
  577. /// Notice that other chains may still be replaced even if the function
  578. /// returns false.
  579. bool findBetterNeighborChains(StoreSDNode *St);
  580. // Helper for findBetterNeighborChains. Walk up store chain add additional
  581. // chained stores that do not overlap and can be parallelized.
  582. bool parallelizeChainedStores(StoreSDNode *St);
  583. /// Holds a pointer to an LSBaseSDNode as well as information on where it
  584. /// is located in a sequence of memory operations connected by a chain.
  585. struct MemOpLink {
  586. // Ptr to the mem node.
  587. LSBaseSDNode *MemNode;
  588. // Offset from the base ptr.
  589. int64_t OffsetFromBase;
  590. MemOpLink(LSBaseSDNode *N, int64_t Offset)
  591. : MemNode(N), OffsetFromBase(Offset) {}
  592. };
  593. // Classify the origin of a stored value.
  594. enum class StoreSource { Unknown, Constant, Extract, Load };
  595. StoreSource getStoreSource(SDValue StoreVal) {
  596. switch (StoreVal.getOpcode()) {
  597. case ISD::Constant:
  598. case ISD::ConstantFP:
  599. return StoreSource::Constant;
  600. case ISD::EXTRACT_VECTOR_ELT:
  601. case ISD::EXTRACT_SUBVECTOR:
  602. return StoreSource::Extract;
  603. case ISD::LOAD:
  604. return StoreSource::Load;
  605. default:
  606. return StoreSource::Unknown;
  607. }
  608. }
  609. /// This is a helper function for visitMUL to check the profitability
  610. /// of folding (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2).
  611. /// MulNode is the original multiply, AddNode is (add x, c1),
  612. /// and ConstNode is c2.
  613. bool isMulAddWithConstProfitable(SDNode *MulNode, SDValue AddNode,
  614. SDValue ConstNode);
  615. /// This is a helper function for visitAND and visitZERO_EXTEND. Returns
  616. /// true if the (and (load x) c) pattern matches an extload. ExtVT returns
  617. /// the type of the loaded value to be extended.
  618. bool isAndLoadExtLoad(ConstantSDNode *AndC, LoadSDNode *LoadN,
  619. EVT LoadResultTy, EVT &ExtVT);
  620. /// Helper function to calculate whether the given Load/Store can have its
  621. /// width reduced to ExtVT.
  622. bool isLegalNarrowLdSt(LSBaseSDNode *LDSTN, ISD::LoadExtType ExtType,
  623. EVT &MemVT, unsigned ShAmt = 0);
  624. /// Used by BackwardsPropagateMask to find suitable loads.
  625. bool SearchForAndLoads(SDNode *N, SmallVectorImpl<LoadSDNode*> &Loads,
  626. SmallPtrSetImpl<SDNode*> &NodesWithConsts,
  627. ConstantSDNode *Mask, SDNode *&NodeToMask);
  628. /// Attempt to propagate a given AND node back to load leaves so that they
  629. /// can be combined into narrow loads.
  630. bool BackwardsPropagateMask(SDNode *N);
  631. /// Helper function for mergeConsecutiveStores which merges the component
  632. /// store chains.
  633. SDValue getMergeStoreChains(SmallVectorImpl<MemOpLink> &StoreNodes,
  634. unsigned NumStores);
  635. /// This is a helper function for mergeConsecutiveStores. When the source
  636. /// elements of the consecutive stores are all constants or all extracted
  637. /// vector elements, try to merge them into one larger store introducing
  638. /// bitcasts if necessary. \return True if a merged store was created.
  639. bool mergeStoresOfConstantsOrVecElts(SmallVectorImpl<MemOpLink> &StoreNodes,
  640. EVT MemVT, unsigned NumStores,
  641. bool IsConstantSrc, bool UseVector,
  642. bool UseTrunc);
  643. /// This is a helper function for mergeConsecutiveStores. Stores that
  644. /// potentially may be merged with St are placed in StoreNodes. RootNode is
  645. /// a chain predecessor to all store candidates.
  646. void getStoreMergeCandidates(StoreSDNode *St,
  647. SmallVectorImpl<MemOpLink> &StoreNodes,
  648. SDNode *&Root);
  649. /// Helper function for mergeConsecutiveStores. Checks if candidate stores
  650. /// have indirect dependency through their operands. RootNode is the
  651. /// predecessor to all stores calculated by getStoreMergeCandidates and is
  652. /// used to prune the dependency check. \return True if safe to merge.
  653. bool checkMergeStoreCandidatesForDependencies(
  654. SmallVectorImpl<MemOpLink> &StoreNodes, unsigned NumStores,
  655. SDNode *RootNode);
  656. /// This is a helper function for mergeConsecutiveStores. Given a list of
  657. /// store candidates, find the first N that are consecutive in memory.
  658. /// Returns 0 if there are not at least 2 consecutive stores to try merging.
  659. unsigned getConsecutiveStores(SmallVectorImpl<MemOpLink> &StoreNodes,
  660. int64_t ElementSizeBytes) const;
  661. /// This is a helper function for mergeConsecutiveStores. It is used for
  662. /// store chains that are composed entirely of constant values.
  663. bool tryStoreMergeOfConstants(SmallVectorImpl<MemOpLink> &StoreNodes,
  664. unsigned NumConsecutiveStores,
  665. EVT MemVT, SDNode *Root, bool AllowVectors);
  666. /// This is a helper function for mergeConsecutiveStores. It is used for
  667. /// store chains that are composed entirely of extracted vector elements.
  668. /// When extracting multiple vector elements, try to store them in one
  669. /// vector store rather than a sequence of scalar stores.
  670. bool tryStoreMergeOfExtracts(SmallVectorImpl<MemOpLink> &StoreNodes,
  671. unsigned NumConsecutiveStores, EVT MemVT,
  672. SDNode *Root);
  673. /// This is a helper function for mergeConsecutiveStores. It is used for
  674. /// store chains that are composed entirely of loaded values.
  675. bool tryStoreMergeOfLoads(SmallVectorImpl<MemOpLink> &StoreNodes,
  676. unsigned NumConsecutiveStores, EVT MemVT,
  677. SDNode *Root, bool AllowVectors,
  678. bool IsNonTemporalStore, bool IsNonTemporalLoad);
  679. /// Merge consecutive store operations into a wide store.
  680. /// This optimization uses wide integers or vectors when possible.
  681. /// \return true if stores were merged.
  682. bool mergeConsecutiveStores(StoreSDNode *St);
  683. /// Try to transform a truncation where C is a constant:
  684. /// (trunc (and X, C)) -> (and (trunc X), (trunc C))
  685. ///
  686. /// \p N needs to be a truncation and its first operand an AND. Other
  687. /// requirements are checked by the function (e.g. that trunc is
  688. /// single-use) and if missed an empty SDValue is returned.
  689. SDValue distributeTruncateThroughAnd(SDNode *N);
  690. /// Helper function to determine whether the target supports operation
  691. /// given by \p Opcode for type \p VT, that is, whether the operation
  692. /// is legal or custom before legalizing operations, and whether is
  693. /// legal (but not custom) after legalization.
  694. bool hasOperation(unsigned Opcode, EVT VT) {
  695. return TLI.isOperationLegalOrCustom(Opcode, VT, LegalOperations);
  696. }
  697. public:
  698. /// Runs the dag combiner on all nodes in the work list
  699. void Run(CombineLevel AtLevel);
  700. SelectionDAG &getDAG() const { return DAG; }
  701. /// Returns a type large enough to hold any valid shift amount - before type
  702. /// legalization these can be huge.
  703. EVT getShiftAmountTy(EVT LHSTy) {
  704. assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
  705. return TLI.getShiftAmountTy(LHSTy, DAG.getDataLayout(), LegalTypes);
  706. }
  707. /// This method returns true if we are running before type legalization or
  708. /// if the specified VT is legal.
  709. bool isTypeLegal(const EVT &VT) {
  710. if (!LegalTypes) return true;
  711. return TLI.isTypeLegal(VT);
  712. }
  713. /// Convenience wrapper around TargetLowering::getSetCCResultType
  714. EVT getSetCCResultType(EVT VT) const {
  715. return TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
  716. }
  717. void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
  718. SDValue OrigLoad, SDValue ExtLoad,
  719. ISD::NodeType ExtType);
  720. };
  721. /// This class is a DAGUpdateListener that removes any deleted
  722. /// nodes from the worklist.
  723. class WorklistRemover : public SelectionDAG::DAGUpdateListener {
  724. DAGCombiner &DC;
  725. public:
  726. explicit WorklistRemover(DAGCombiner &dc)
  727. : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
  728. void NodeDeleted(SDNode *N, SDNode *E) override {
  729. DC.removeFromWorklist(N);
  730. }
  731. };
  732. class WorklistInserter : public SelectionDAG::DAGUpdateListener {
  733. DAGCombiner &DC;
  734. public:
  735. explicit WorklistInserter(DAGCombiner &dc)
  736. : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
  737. // FIXME: Ideally we could add N to the worklist, but this causes exponential
  738. // compile time costs in large DAGs, e.g. Halide.
  739. void NodeInserted(SDNode *N) override { DC.ConsiderForPruning(N); }
  740. };
  741. } // end anonymous namespace
  742. //===----------------------------------------------------------------------===//
  743. // TargetLowering::DAGCombinerInfo implementation
  744. //===----------------------------------------------------------------------===//
  745. void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
  746. ((DAGCombiner*)DC)->AddToWorklist(N);
  747. }
  748. SDValue TargetLowering::DAGCombinerInfo::
  749. CombineTo(SDNode *N, ArrayRef<SDValue> To, bool AddTo) {
  750. return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
  751. }
  752. SDValue TargetLowering::DAGCombinerInfo::
  753. CombineTo(SDNode *N, SDValue Res, bool AddTo) {
  754. return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
  755. }
  756. SDValue TargetLowering::DAGCombinerInfo::
  757. CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
  758. return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
  759. }
  760. bool TargetLowering::DAGCombinerInfo::
  761. recursivelyDeleteUnusedNodes(SDNode *N) {
  762. return ((DAGCombiner*)DC)->recursivelyDeleteUnusedNodes(N);
  763. }
  764. void TargetLowering::DAGCombinerInfo::
  765. CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
  766. return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
  767. }
  768. //===----------------------------------------------------------------------===//
  769. // Helper Functions
  770. //===----------------------------------------------------------------------===//
  771. void DAGCombiner::deleteAndRecombine(SDNode *N) {
  772. removeFromWorklist(N);
  773. // If the operands of this node are only used by the node, they will now be
  774. // dead. Make sure to re-visit them and recursively delete dead nodes.
  775. for (const SDValue &Op : N->ops())
  776. // For an operand generating multiple values, one of the values may
  777. // become dead allowing further simplification (e.g. split index
  778. // arithmetic from an indexed load).
  779. if (Op->hasOneUse() || Op->getNumValues() > 1)
  780. AddToWorklist(Op.getNode());
  781. DAG.DeleteNode(N);
  782. }
  783. // APInts must be the same size for most operations, this helper
  784. // function zero extends the shorter of the pair so that they match.
  785. // We provide an Offset so that we can create bitwidths that won't overflow.
  786. static void zeroExtendToMatch(APInt &LHS, APInt &RHS, unsigned Offset = 0) {
  787. unsigned Bits = Offset + std::max(LHS.getBitWidth(), RHS.getBitWidth());
  788. LHS = LHS.zext(Bits);
  789. RHS = RHS.zext(Bits);
  790. }
  791. // Return true if this node is a setcc, or is a select_cc
  792. // that selects between the target values used for true and false, making it
  793. // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
  794. // the appropriate nodes based on the type of node we are checking. This
  795. // simplifies life a bit for the callers.
  796. bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
  797. SDValue &CC, bool MatchStrict) const {
  798. if (N.getOpcode() == ISD::SETCC) {
  799. LHS = N.getOperand(0);
  800. RHS = N.getOperand(1);
  801. CC = N.getOperand(2);
  802. return true;
  803. }
  804. if (MatchStrict &&
  805. (N.getOpcode() == ISD::STRICT_FSETCC ||
  806. N.getOpcode() == ISD::STRICT_FSETCCS)) {
  807. LHS = N.getOperand(1);
  808. RHS = N.getOperand(2);
  809. CC = N.getOperand(3);
  810. return true;
  811. }
  812. if (N.getOpcode() != ISD::SELECT_CC || !TLI.isConstTrueVal(N.getOperand(2)) ||
  813. !TLI.isConstFalseVal(N.getOperand(3)))
  814. return false;
  815. if (TLI.getBooleanContents(N.getValueType()) ==
  816. TargetLowering::UndefinedBooleanContent)
  817. return false;
  818. LHS = N.getOperand(0);
  819. RHS = N.getOperand(1);
  820. CC = N.getOperand(4);
  821. return true;
  822. }
  823. /// Return true if this is a SetCC-equivalent operation with only one use.
  824. /// If this is true, it allows the users to invert the operation for free when
  825. /// it is profitable to do so.
  826. bool DAGCombiner::isOneUseSetCC(SDValue N) const {
  827. SDValue N0, N1, N2;
  828. if (isSetCCEquivalent(N, N0, N1, N2) && N->hasOneUse())
  829. return true;
  830. return false;
  831. }
  832. static bool isConstantSplatVectorMaskForType(SDNode *N, EVT ScalarTy) {
  833. if (!ScalarTy.isSimple())
  834. return false;
  835. uint64_t MaskForTy = 0ULL;
  836. switch (ScalarTy.getSimpleVT().SimpleTy) {
  837. case MVT::i8:
  838. MaskForTy = 0xFFULL;
  839. break;
  840. case MVT::i16:
  841. MaskForTy = 0xFFFFULL;
  842. break;
  843. case MVT::i32:
  844. MaskForTy = 0xFFFFFFFFULL;
  845. break;
  846. default:
  847. return false;
  848. break;
  849. }
  850. APInt Val;
  851. if (ISD::isConstantSplatVector(N, Val))
  852. return Val.getLimitedValue() == MaskForTy;
  853. return false;
  854. }
  855. // Determines if it is a constant integer or a splat/build vector of constant
  856. // integers (and undefs).
  857. // Do not permit build vector implicit truncation.
  858. static bool isConstantOrConstantVector(SDValue N, bool NoOpaques = false) {
  859. if (ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N))
  860. return !(Const->isOpaque() && NoOpaques);
  861. if (N.getOpcode() != ISD::BUILD_VECTOR && N.getOpcode() != ISD::SPLAT_VECTOR)
  862. return false;
  863. unsigned BitWidth = N.getScalarValueSizeInBits();
  864. for (const SDValue &Op : N->op_values()) {
  865. if (Op.isUndef())
  866. continue;
  867. ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Op);
  868. if (!Const || Const->getAPIntValue().getBitWidth() != BitWidth ||
  869. (Const->isOpaque() && NoOpaques))
  870. return false;
  871. }
  872. return true;
  873. }
  874. // Determines if a BUILD_VECTOR is composed of all-constants possibly mixed with
  875. // undef's.
  876. static bool isAnyConstantBuildVector(SDValue V, bool NoOpaques = false) {
  877. if (V.getOpcode() != ISD::BUILD_VECTOR)
  878. return false;
  879. return isConstantOrConstantVector(V, NoOpaques) ||
  880. ISD::isBuildVectorOfConstantFPSDNodes(V.getNode());
  881. }
  882. // Determine if this an indexed load with an opaque target constant index.
  883. static bool canSplitIdx(LoadSDNode *LD) {
  884. return MaySplitLoadIndex &&
  885. (LD->getOperand(2).getOpcode() != ISD::TargetConstant ||
  886. !cast<ConstantSDNode>(LD->getOperand(2))->isOpaque());
  887. }
  888. bool DAGCombiner::reassociationCanBreakAddressingModePattern(unsigned Opc,
  889. const SDLoc &DL,
  890. SDNode *N,
  891. SDValue N0,
  892. SDValue N1) {
  893. // Currently this only tries to ensure we don't undo the GEP splits done by
  894. // CodeGenPrepare when shouldConsiderGEPOffsetSplit is true. To ensure this,
  895. // we check if the following transformation would be problematic:
  896. // (load/store (add, (add, x, offset1), offset2)) ->
  897. // (load/store (add, x, offset1+offset2)).
  898. // (load/store (add, (add, x, y), offset2)) ->
  899. // (load/store (add, (add, x, offset2), y)).
  900. if (Opc != ISD::ADD || N0.getOpcode() != ISD::ADD)
  901. return false;
  902. auto *C2 = dyn_cast<ConstantSDNode>(N1);
  903. if (!C2)
  904. return false;
  905. const APInt &C2APIntVal = C2->getAPIntValue();
  906. if (C2APIntVal.getSignificantBits() > 64)
  907. return false;
  908. if (auto *C1 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
  909. if (N0.hasOneUse())
  910. return false;
  911. const APInt &C1APIntVal = C1->getAPIntValue();
  912. const APInt CombinedValueIntVal = C1APIntVal + C2APIntVal;
  913. if (CombinedValueIntVal.getSignificantBits() > 64)
  914. return false;
  915. const int64_t CombinedValue = CombinedValueIntVal.getSExtValue();
  916. for (SDNode *Node : N->uses()) {
  917. if (auto *LoadStore = dyn_cast<MemSDNode>(Node)) {
  918. // Is x[offset2] already not a legal addressing mode? If so then
  919. // reassociating the constants breaks nothing (we test offset2 because
  920. // that's the one we hope to fold into the load or store).
  921. TargetLoweringBase::AddrMode AM;
  922. AM.HasBaseReg = true;
  923. AM.BaseOffs = C2APIntVal.getSExtValue();
  924. EVT VT = LoadStore->getMemoryVT();
  925. unsigned AS = LoadStore->getAddressSpace();
  926. Type *AccessTy = VT.getTypeForEVT(*DAG.getContext());
  927. if (!TLI.isLegalAddressingMode(DAG.getDataLayout(), AM, AccessTy, AS))
  928. continue;
  929. // Would x[offset1+offset2] still be a legal addressing mode?
  930. AM.BaseOffs = CombinedValue;
  931. if (!TLI.isLegalAddressingMode(DAG.getDataLayout(), AM, AccessTy, AS))
  932. return true;
  933. }
  934. }
  935. } else {
  936. if (auto *GA = dyn_cast<GlobalAddressSDNode>(N0.getOperand(1)))
  937. if (GA->getOpcode() == ISD::GlobalAddress && TLI.isOffsetFoldingLegal(GA))
  938. return false;
  939. for (SDNode *Node : N->uses()) {
  940. auto *LoadStore = dyn_cast<MemSDNode>(Node);
  941. if (!LoadStore)
  942. return false;
  943. // Is x[offset2] a legal addressing mode? If so then
  944. // reassociating the constants breaks address pattern
  945. TargetLoweringBase::AddrMode AM;
  946. AM.HasBaseReg = true;
  947. AM.BaseOffs = C2APIntVal.getSExtValue();
  948. EVT VT = LoadStore->getMemoryVT();
  949. unsigned AS = LoadStore->getAddressSpace();
  950. Type *AccessTy = VT.getTypeForEVT(*DAG.getContext());
  951. if (!TLI.isLegalAddressingMode(DAG.getDataLayout(), AM, AccessTy, AS))
  952. return false;
  953. }
  954. return true;
  955. }
  956. return false;
  957. }
  958. // Helper for DAGCombiner::reassociateOps. Try to reassociate an expression
  959. // such as (Opc N0, N1), if \p N0 is the same kind of operation as \p Opc.
  960. SDValue DAGCombiner::reassociateOpsCommutative(unsigned Opc, const SDLoc &DL,
  961. SDValue N0, SDValue N1) {
  962. EVT VT = N0.getValueType();
  963. if (N0.getOpcode() != Opc)
  964. return SDValue();
  965. SDValue N00 = N0.getOperand(0);
  966. SDValue N01 = N0.getOperand(1);
  967. if (DAG.isConstantIntBuildVectorOrConstantInt(peekThroughBitcasts(N01))) {
  968. if (DAG.isConstantIntBuildVectorOrConstantInt(peekThroughBitcasts(N1))) {
  969. // Reassociate: (op (op x, c1), c2) -> (op x, (op c1, c2))
  970. if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, {N01, N1}))
  971. return DAG.getNode(Opc, DL, VT, N00, OpNode);
  972. return SDValue();
  973. }
  974. if (TLI.isReassocProfitable(DAG, N0, N1)) {
  975. // Reassociate: (op (op x, c1), y) -> (op (op x, y), c1)
  976. // iff (op x, c1) has one use
  977. SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N00, N1);
  978. return DAG.getNode(Opc, DL, VT, OpNode, N01);
  979. }
  980. }
  981. // Check for repeated operand logic simplifications.
  982. if (Opc == ISD::AND || Opc == ISD::OR) {
  983. // (N00 & N01) & N00 --> N00 & N01
  984. // (N00 & N01) & N01 --> N00 & N01
  985. // (N00 | N01) | N00 --> N00 | N01
  986. // (N00 | N01) | N01 --> N00 | N01
  987. if (N1 == N00 || N1 == N01)
  988. return N0;
  989. }
  990. if (Opc == ISD::XOR) {
  991. // (N00 ^ N01) ^ N00 --> N01
  992. if (N1 == N00)
  993. return N01;
  994. // (N00 ^ N01) ^ N01 --> N00
  995. if (N1 == N01)
  996. return N00;
  997. }
  998. if (TLI.isReassocProfitable(DAG, N0, N1)) {
  999. if (N1 != N01) {
  1000. // Reassociate if (op N00, N1) already exist
  1001. if (SDNode *NE = DAG.getNodeIfExists(Opc, DAG.getVTList(VT), {N00, N1})) {
  1002. // if Op (Op N00, N1), N01 already exist
  1003. // we need to stop reassciate to avoid dead loop
  1004. if (!DAG.doesNodeExist(Opc, DAG.getVTList(VT), {SDValue(NE, 0), N01}))
  1005. return DAG.getNode(Opc, DL, VT, SDValue(NE, 0), N01);
  1006. }
  1007. }
  1008. if (N1 != N00) {
  1009. // Reassociate if (op N01, N1) already exist
  1010. if (SDNode *NE = DAG.getNodeIfExists(Opc, DAG.getVTList(VT), {N01, N1})) {
  1011. // if Op (Op N01, N1), N00 already exist
  1012. // we need to stop reassciate to avoid dead loop
  1013. if (!DAG.doesNodeExist(Opc, DAG.getVTList(VT), {SDValue(NE, 0), N00}))
  1014. return DAG.getNode(Opc, DL, VT, SDValue(NE, 0), N00);
  1015. }
  1016. }
  1017. }
  1018. return SDValue();
  1019. }
  1020. // Try to reassociate commutative binops.
  1021. SDValue DAGCombiner::reassociateOps(unsigned Opc, const SDLoc &DL, SDValue N0,
  1022. SDValue N1, SDNodeFlags Flags) {
  1023. assert(TLI.isCommutativeBinOp(Opc) && "Operation not commutative.");
  1024. // Floating-point reassociation is not allowed without loose FP math.
  1025. if (N0.getValueType().isFloatingPoint() ||
  1026. N1.getValueType().isFloatingPoint())
  1027. if (!Flags.hasAllowReassociation() || !Flags.hasNoSignedZeros())
  1028. return SDValue();
  1029. if (SDValue Combined = reassociateOpsCommutative(Opc, DL, N0, N1))
  1030. return Combined;
  1031. if (SDValue Combined = reassociateOpsCommutative(Opc, DL, N1, N0))
  1032. return Combined;
  1033. return SDValue();
  1034. }
  1035. SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
  1036. bool AddTo) {
  1037. assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
  1038. ++NodesCombined;
  1039. LLVM_DEBUG(dbgs() << "\nReplacing.1 "; N->dump(&DAG); dbgs() << "\nWith: ";
  1040. To[0].dump(&DAG);
  1041. dbgs() << " and " << NumTo - 1 << " other values\n");
  1042. for (unsigned i = 0, e = NumTo; i != e; ++i)
  1043. assert((!To[i].getNode() ||
  1044. N->getValueType(i) == To[i].getValueType()) &&
  1045. "Cannot combine value to value of different type!");
  1046. WorklistRemover DeadNodes(*this);
  1047. DAG.ReplaceAllUsesWith(N, To);
  1048. if (AddTo) {
  1049. // Push the new nodes and any users onto the worklist
  1050. for (unsigned i = 0, e = NumTo; i != e; ++i) {
  1051. if (To[i].getNode())
  1052. AddToWorklistWithUsers(To[i].getNode());
  1053. }
  1054. }
  1055. // Finally, if the node is now dead, remove it from the graph. The node
  1056. // may not be dead if the replacement process recursively simplified to
  1057. // something else needing this node.
  1058. if (N->use_empty())
  1059. deleteAndRecombine(N);
  1060. return SDValue(N, 0);
  1061. }
  1062. void DAGCombiner::
  1063. CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
  1064. // Replace the old value with the new one.
  1065. ++NodesCombined;
  1066. LLVM_DEBUG(dbgs() << "\nReplacing.2 "; TLO.Old.dump(&DAG);
  1067. dbgs() << "\nWith: "; TLO.New.dump(&DAG); dbgs() << '\n');
  1068. // Replace all uses.
  1069. DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
  1070. // Push the new node and any (possibly new) users onto the worklist.
  1071. AddToWorklistWithUsers(TLO.New.getNode());
  1072. // Finally, if the node is now dead, remove it from the graph.
  1073. recursivelyDeleteUnusedNodes(TLO.Old.getNode());
  1074. }
  1075. /// Check the specified integer node value to see if it can be simplified or if
  1076. /// things it uses can be simplified by bit propagation. If so, return true.
  1077. bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &DemandedBits,
  1078. const APInt &DemandedElts,
  1079. bool AssumeSingleUse) {
  1080. TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
  1081. KnownBits Known;
  1082. if (!TLI.SimplifyDemandedBits(Op, DemandedBits, DemandedElts, Known, TLO, 0,
  1083. AssumeSingleUse))
  1084. return false;
  1085. // Revisit the node.
  1086. AddToWorklist(Op.getNode());
  1087. CommitTargetLoweringOpt(TLO);
  1088. return true;
  1089. }
  1090. /// Check the specified vector node value to see if it can be simplified or
  1091. /// if things it uses can be simplified as it only uses some of the elements.
  1092. /// If so, return true.
  1093. bool DAGCombiner::SimplifyDemandedVectorElts(SDValue Op,
  1094. const APInt &DemandedElts,
  1095. bool AssumeSingleUse) {
  1096. TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
  1097. APInt KnownUndef, KnownZero;
  1098. if (!TLI.SimplifyDemandedVectorElts(Op, DemandedElts, KnownUndef, KnownZero,
  1099. TLO, 0, AssumeSingleUse))
  1100. return false;
  1101. // Revisit the node.
  1102. AddToWorklist(Op.getNode());
  1103. CommitTargetLoweringOpt(TLO);
  1104. return true;
  1105. }
  1106. void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
  1107. SDLoc DL(Load);
  1108. EVT VT = Load->getValueType(0);
  1109. SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, VT, SDValue(ExtLoad, 0));
  1110. LLVM_DEBUG(dbgs() << "\nReplacing.9 "; Load->dump(&DAG); dbgs() << "\nWith: ";
  1111. Trunc.dump(&DAG); dbgs() << '\n');
  1112. DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
  1113. DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
  1114. AddToWorklist(Trunc.getNode());
  1115. recursivelyDeleteUnusedNodes(Load);
  1116. }
  1117. SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
  1118. Replace = false;
  1119. SDLoc DL(Op);
  1120. if (ISD::isUNINDEXEDLoad(Op.getNode())) {
  1121. LoadSDNode *LD = cast<LoadSDNode>(Op);
  1122. EVT MemVT = LD->getMemoryVT();
  1123. ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD) ? ISD::EXTLOAD
  1124. : LD->getExtensionType();
  1125. Replace = true;
  1126. return DAG.getExtLoad(ExtType, DL, PVT,
  1127. LD->getChain(), LD->getBasePtr(),
  1128. MemVT, LD->getMemOperand());
  1129. }
  1130. unsigned Opc = Op.getOpcode();
  1131. switch (Opc) {
  1132. default: break;
  1133. case ISD::AssertSext:
  1134. if (SDValue Op0 = SExtPromoteOperand(Op.getOperand(0), PVT))
  1135. return DAG.getNode(ISD::AssertSext, DL, PVT, Op0, Op.getOperand(1));
  1136. break;
  1137. case ISD::AssertZext:
  1138. if (SDValue Op0 = ZExtPromoteOperand(Op.getOperand(0), PVT))
  1139. return DAG.getNode(ISD::AssertZext, DL, PVT, Op0, Op.getOperand(1));
  1140. break;
  1141. case ISD::Constant: {
  1142. unsigned ExtOpc =
  1143. Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
  1144. return DAG.getNode(ExtOpc, DL, PVT, Op);
  1145. }
  1146. }
  1147. if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
  1148. return SDValue();
  1149. return DAG.getNode(ISD::ANY_EXTEND, DL, PVT, Op);
  1150. }
  1151. SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
  1152. if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
  1153. return SDValue();
  1154. EVT OldVT = Op.getValueType();
  1155. SDLoc DL(Op);
  1156. bool Replace = false;
  1157. SDValue NewOp = PromoteOperand(Op, PVT, Replace);
  1158. if (!NewOp.getNode())
  1159. return SDValue();
  1160. AddToWorklist(NewOp.getNode());
  1161. if (Replace)
  1162. ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
  1163. return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, NewOp.getValueType(), NewOp,
  1164. DAG.getValueType(OldVT));
  1165. }
  1166. SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
  1167. EVT OldVT = Op.getValueType();
  1168. SDLoc DL(Op);
  1169. bool Replace = false;
  1170. SDValue NewOp = PromoteOperand(Op, PVT, Replace);
  1171. if (!NewOp.getNode())
  1172. return SDValue();
  1173. AddToWorklist(NewOp.getNode());
  1174. if (Replace)
  1175. ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
  1176. return DAG.getZeroExtendInReg(NewOp, DL, OldVT);
  1177. }
  1178. /// Promote the specified integer binary operation if the target indicates it is
  1179. /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
  1180. /// i32 since i16 instructions are longer.
  1181. SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
  1182. if (!LegalOperations)
  1183. return SDValue();
  1184. EVT VT = Op.getValueType();
  1185. if (VT.isVector() || !VT.isInteger())
  1186. return SDValue();
  1187. // If operation type is 'undesirable', e.g. i16 on x86, consider
  1188. // promoting it.
  1189. unsigned Opc = Op.getOpcode();
  1190. if (TLI.isTypeDesirableForOp(Opc, VT))
  1191. return SDValue();
  1192. EVT PVT = VT;
  1193. // Consult target whether it is a good idea to promote this operation and
  1194. // what's the right type to promote it to.
  1195. if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
  1196. assert(PVT != VT && "Don't know what type to promote to!");
  1197. LLVM_DEBUG(dbgs() << "\nPromoting "; Op.dump(&DAG));
  1198. bool Replace0 = false;
  1199. SDValue N0 = Op.getOperand(0);
  1200. SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
  1201. bool Replace1 = false;
  1202. SDValue N1 = Op.getOperand(1);
  1203. SDValue NN1 = PromoteOperand(N1, PVT, Replace1);
  1204. SDLoc DL(Op);
  1205. SDValue RV =
  1206. DAG.getNode(ISD::TRUNCATE, DL, VT, DAG.getNode(Opc, DL, PVT, NN0, NN1));
  1207. // We are always replacing N0/N1's use in N and only need additional
  1208. // replacements if there are additional uses.
  1209. // Note: We are checking uses of the *nodes* (SDNode) rather than values
  1210. // (SDValue) here because the node may reference multiple values
  1211. // (for example, the chain value of a load node).
  1212. Replace0 &= !N0->hasOneUse();
  1213. Replace1 &= (N0 != N1) && !N1->hasOneUse();
  1214. // Combine Op here so it is preserved past replacements.
  1215. CombineTo(Op.getNode(), RV);
  1216. // If operands have a use ordering, make sure we deal with
  1217. // predecessor first.
  1218. if (Replace0 && Replace1 && N0->isPredecessorOf(N1.getNode())) {
  1219. std::swap(N0, N1);
  1220. std::swap(NN0, NN1);
  1221. }
  1222. if (Replace0) {
  1223. AddToWorklist(NN0.getNode());
  1224. ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
  1225. }
  1226. if (Replace1) {
  1227. AddToWorklist(NN1.getNode());
  1228. ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
  1229. }
  1230. return Op;
  1231. }
  1232. return SDValue();
  1233. }
  1234. /// Promote the specified integer shift operation if the target indicates it is
  1235. /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
  1236. /// i32 since i16 instructions are longer.
  1237. SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
  1238. if (!LegalOperations)
  1239. return SDValue();
  1240. EVT VT = Op.getValueType();
  1241. if (VT.isVector() || !VT.isInteger())
  1242. return SDValue();
  1243. // If operation type is 'undesirable', e.g. i16 on x86, consider
  1244. // promoting it.
  1245. unsigned Opc = Op.getOpcode();
  1246. if (TLI.isTypeDesirableForOp(Opc, VT))
  1247. return SDValue();
  1248. EVT PVT = VT;
  1249. // Consult target whether it is a good idea to promote this operation and
  1250. // what's the right type to promote it to.
  1251. if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
  1252. assert(PVT != VT && "Don't know what type to promote to!");
  1253. LLVM_DEBUG(dbgs() << "\nPromoting "; Op.dump(&DAG));
  1254. bool Replace = false;
  1255. SDValue N0 = Op.getOperand(0);
  1256. if (Opc == ISD::SRA)
  1257. N0 = SExtPromoteOperand(N0, PVT);
  1258. else if (Opc == ISD::SRL)
  1259. N0 = ZExtPromoteOperand(N0, PVT);
  1260. else
  1261. N0 = PromoteOperand(N0, PVT, Replace);
  1262. if (!N0.getNode())
  1263. return SDValue();
  1264. SDLoc DL(Op);
  1265. SDValue N1 = Op.getOperand(1);
  1266. SDValue RV =
  1267. DAG.getNode(ISD::TRUNCATE, DL, VT, DAG.getNode(Opc, DL, PVT, N0, N1));
  1268. if (Replace)
  1269. ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
  1270. // Deal with Op being deleted.
  1271. if (Op && Op.getOpcode() != ISD::DELETED_NODE)
  1272. return RV;
  1273. }
  1274. return SDValue();
  1275. }
  1276. SDValue DAGCombiner::PromoteExtend(SDValue Op) {
  1277. if (!LegalOperations)
  1278. return SDValue();
  1279. EVT VT = Op.getValueType();
  1280. if (VT.isVector() || !VT.isInteger())
  1281. return SDValue();
  1282. // If operation type is 'undesirable', e.g. i16 on x86, consider
  1283. // promoting it.
  1284. unsigned Opc = Op.getOpcode();
  1285. if (TLI.isTypeDesirableForOp(Opc, VT))
  1286. return SDValue();
  1287. EVT PVT = VT;
  1288. // Consult target whether it is a good idea to promote this operation and
  1289. // what's the right type to promote it to.
  1290. if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
  1291. assert(PVT != VT && "Don't know what type to promote to!");
  1292. // fold (aext (aext x)) -> (aext x)
  1293. // fold (aext (zext x)) -> (zext x)
  1294. // fold (aext (sext x)) -> (sext x)
  1295. LLVM_DEBUG(dbgs() << "\nPromoting "; Op.dump(&DAG));
  1296. return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
  1297. }
  1298. return SDValue();
  1299. }
  1300. bool DAGCombiner::PromoteLoad(SDValue Op) {
  1301. if (!LegalOperations)
  1302. return false;
  1303. if (!ISD::isUNINDEXEDLoad(Op.getNode()))
  1304. return false;
  1305. EVT VT = Op.getValueType();
  1306. if (VT.isVector() || !VT.isInteger())
  1307. return false;
  1308. // If operation type is 'undesirable', e.g. i16 on x86, consider
  1309. // promoting it.
  1310. unsigned Opc = Op.getOpcode();
  1311. if (TLI.isTypeDesirableForOp(Opc, VT))
  1312. return false;
  1313. EVT PVT = VT;
  1314. // Consult target whether it is a good idea to promote this operation and
  1315. // what's the right type to promote it to.
  1316. if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
  1317. assert(PVT != VT && "Don't know what type to promote to!");
  1318. SDLoc DL(Op);
  1319. SDNode *N = Op.getNode();
  1320. LoadSDNode *LD = cast<LoadSDNode>(N);
  1321. EVT MemVT = LD->getMemoryVT();
  1322. ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD) ? ISD::EXTLOAD
  1323. : LD->getExtensionType();
  1324. SDValue NewLD = DAG.getExtLoad(ExtType, DL, PVT,
  1325. LD->getChain(), LD->getBasePtr(),
  1326. MemVT, LD->getMemOperand());
  1327. SDValue Result = DAG.getNode(ISD::TRUNCATE, DL, VT, NewLD);
  1328. LLVM_DEBUG(dbgs() << "\nPromoting "; N->dump(&DAG); dbgs() << "\nTo: ";
  1329. Result.dump(&DAG); dbgs() << '\n');
  1330. DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
  1331. DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
  1332. AddToWorklist(Result.getNode());
  1333. recursivelyDeleteUnusedNodes(N);
  1334. return true;
  1335. }
  1336. return false;
  1337. }
  1338. /// Recursively delete a node which has no uses and any operands for
  1339. /// which it is the only use.
  1340. ///
  1341. /// Note that this both deletes the nodes and removes them from the worklist.
  1342. /// It also adds any nodes who have had a user deleted to the worklist as they
  1343. /// may now have only one use and subject to other combines.
  1344. bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) {
  1345. if (!N->use_empty())
  1346. return false;
  1347. SmallSetVector<SDNode *, 16> Nodes;
  1348. Nodes.insert(N);
  1349. do {
  1350. N = Nodes.pop_back_val();
  1351. if (!N)
  1352. continue;
  1353. if (N->use_empty()) {
  1354. for (const SDValue &ChildN : N->op_values())
  1355. Nodes.insert(ChildN.getNode());
  1356. removeFromWorklist(N);
  1357. DAG.DeleteNode(N);
  1358. } else {
  1359. AddToWorklist(N);
  1360. }
  1361. } while (!Nodes.empty());
  1362. return true;
  1363. }
  1364. //===----------------------------------------------------------------------===//
  1365. // Main DAG Combiner implementation
  1366. //===----------------------------------------------------------------------===//
  1367. void DAGCombiner::Run(CombineLevel AtLevel) {
  1368. // set the instance variables, so that the various visit routines may use it.
  1369. Level = AtLevel;
  1370. LegalDAG = Level >= AfterLegalizeDAG;
  1371. LegalOperations = Level >= AfterLegalizeVectorOps;
  1372. LegalTypes = Level >= AfterLegalizeTypes;
  1373. WorklistInserter AddNodes(*this);
  1374. // Add all the dag nodes to the worklist.
  1375. for (SDNode &Node : DAG.allnodes())
  1376. AddToWorklist(&Node);
  1377. // Create a dummy node (which is not added to allnodes), that adds a reference
  1378. // to the root node, preventing it from being deleted, and tracking any
  1379. // changes of the root.
  1380. HandleSDNode Dummy(DAG.getRoot());
  1381. // While we have a valid worklist entry node, try to combine it.
  1382. while (SDNode *N = getNextWorklistEntry()) {
  1383. // If N has no uses, it is dead. Make sure to revisit all N's operands once
  1384. // N is deleted from the DAG, since they too may now be dead or may have a
  1385. // reduced number of uses, allowing other xforms.
  1386. if (recursivelyDeleteUnusedNodes(N))
  1387. continue;
  1388. WorklistRemover DeadNodes(*this);
  1389. // If this combine is running after legalizing the DAG, re-legalize any
  1390. // nodes pulled off the worklist.
  1391. if (LegalDAG) {
  1392. SmallSetVector<SDNode *, 16> UpdatedNodes;
  1393. bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes);
  1394. for (SDNode *LN : UpdatedNodes)
  1395. AddToWorklistWithUsers(LN);
  1396. if (!NIsValid)
  1397. continue;
  1398. }
  1399. LLVM_DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG));
  1400. // Add any operands of the new node which have not yet been combined to the
  1401. // worklist as well. Because the worklist uniques things already, this
  1402. // won't repeatedly process the same operand.
  1403. CombinedNodes.insert(N);
  1404. for (const SDValue &ChildN : N->op_values())
  1405. if (!CombinedNodes.count(ChildN.getNode()))
  1406. AddToWorklist(ChildN.getNode());
  1407. SDValue RV = combine(N);
  1408. if (!RV.getNode())
  1409. continue;
  1410. ++NodesCombined;
  1411. // If we get back the same node we passed in, rather than a new node or
  1412. // zero, we know that the node must have defined multiple values and
  1413. // CombineTo was used. Since CombineTo takes care of the worklist
  1414. // mechanics for us, we have no work to do in this case.
  1415. if (RV.getNode() == N)
  1416. continue;
  1417. assert(N->getOpcode() != ISD::DELETED_NODE &&
  1418. RV.getOpcode() != ISD::DELETED_NODE &&
  1419. "Node was deleted but visit returned new node!");
  1420. LLVM_DEBUG(dbgs() << " ... into: "; RV.dump(&DAG));
  1421. if (N->getNumValues() == RV->getNumValues())
  1422. DAG.ReplaceAllUsesWith(N, RV.getNode());
  1423. else {
  1424. assert(N->getValueType(0) == RV.getValueType() &&
  1425. N->getNumValues() == 1 && "Type mismatch");
  1426. DAG.ReplaceAllUsesWith(N, &RV);
  1427. }
  1428. // Push the new node and any users onto the worklist. Omit this if the
  1429. // new node is the EntryToken (e.g. if a store managed to get optimized
  1430. // out), because re-visiting the EntryToken and its users will not uncover
  1431. // any additional opportunities, but there may be a large number of such
  1432. // users, potentially causing compile time explosion.
  1433. if (RV.getOpcode() != ISD::EntryToken) {
  1434. AddToWorklist(RV.getNode());
  1435. AddUsersToWorklist(RV.getNode());
  1436. }
  1437. // Finally, if the node is now dead, remove it from the graph. The node
  1438. // may not be dead if the replacement process recursively simplified to
  1439. // something else needing this node. This will also take care of adding any
  1440. // operands which have lost a user to the worklist.
  1441. recursivelyDeleteUnusedNodes(N);
  1442. }
  1443. // If the root changed (e.g. it was a dead load, update the root).
  1444. DAG.setRoot(Dummy.getValue());
  1445. DAG.RemoveDeadNodes();
  1446. }
  1447. SDValue DAGCombiner::visit(SDNode *N) {
  1448. switch (N->getOpcode()) {
  1449. default: break;
  1450. case ISD::TokenFactor: return visitTokenFactor(N);
  1451. case ISD::MERGE_VALUES: return visitMERGE_VALUES(N);
  1452. case ISD::ADD: return visitADD(N);
  1453. case ISD::SUB: return visitSUB(N);
  1454. case ISD::SADDSAT:
  1455. case ISD::UADDSAT: return visitADDSAT(N);
  1456. case ISD::SSUBSAT:
  1457. case ISD::USUBSAT: return visitSUBSAT(N);
  1458. case ISD::ADDC: return visitADDC(N);
  1459. case ISD::SADDO:
  1460. case ISD::UADDO: return visitADDO(N);
  1461. case ISD::SUBC: return visitSUBC(N);
  1462. case ISD::SSUBO:
  1463. case ISD::USUBO: return visitSUBO(N);
  1464. case ISD::ADDE: return visitADDE(N);
  1465. case ISD::ADDCARRY: return visitADDCARRY(N);
  1466. case ISD::SADDO_CARRY: return visitSADDO_CARRY(N);
  1467. case ISD::SUBE: return visitSUBE(N);
  1468. case ISD::SUBCARRY: return visitSUBCARRY(N);
  1469. case ISD::SSUBO_CARRY: return visitSSUBO_CARRY(N);
  1470. case ISD::SMULFIX:
  1471. case ISD::SMULFIXSAT:
  1472. case ISD::UMULFIX:
  1473. case ISD::UMULFIXSAT: return visitMULFIX(N);
  1474. case ISD::MUL: return visitMUL(N);
  1475. case ISD::SDIV: return visitSDIV(N);
  1476. case ISD::UDIV: return visitUDIV(N);
  1477. case ISD::SREM:
  1478. case ISD::UREM: return visitREM(N);
  1479. case ISD::MULHU: return visitMULHU(N);
  1480. case ISD::MULHS: return visitMULHS(N);
  1481. case ISD::AVGFLOORS:
  1482. case ISD::AVGFLOORU:
  1483. case ISD::AVGCEILS:
  1484. case ISD::AVGCEILU: return visitAVG(N);
  1485. case ISD::SMUL_LOHI: return visitSMUL_LOHI(N);
  1486. case ISD::UMUL_LOHI: return visitUMUL_LOHI(N);
  1487. case ISD::SMULO:
  1488. case ISD::UMULO: return visitMULO(N);
  1489. case ISD::SMIN:
  1490. case ISD::SMAX:
  1491. case ISD::UMIN:
  1492. case ISD::UMAX: return visitIMINMAX(N);
  1493. case ISD::AND: return visitAND(N);
  1494. case ISD::OR: return visitOR(N);
  1495. case ISD::XOR: return visitXOR(N);
  1496. case ISD::SHL: return visitSHL(N);
  1497. case ISD::SRA: return visitSRA(N);
  1498. case ISD::SRL: return visitSRL(N);
  1499. case ISD::ROTR:
  1500. case ISD::ROTL: return visitRotate(N);
  1501. case ISD::FSHL:
  1502. case ISD::FSHR: return visitFunnelShift(N);
  1503. case ISD::SSHLSAT:
  1504. case ISD::USHLSAT: return visitSHLSAT(N);
  1505. case ISD::ABS: return visitABS(N);
  1506. case ISD::BSWAP: return visitBSWAP(N);
  1507. case ISD::BITREVERSE: return visitBITREVERSE(N);
  1508. case ISD::CTLZ: return visitCTLZ(N);
  1509. case ISD::CTLZ_ZERO_UNDEF: return visitCTLZ_ZERO_UNDEF(N);
  1510. case ISD::CTTZ: return visitCTTZ(N);
  1511. case ISD::CTTZ_ZERO_UNDEF: return visitCTTZ_ZERO_UNDEF(N);
  1512. case ISD::CTPOP: return visitCTPOP(N);
  1513. case ISD::SELECT: return visitSELECT(N);
  1514. case ISD::VSELECT: return visitVSELECT(N);
  1515. case ISD::SELECT_CC: return visitSELECT_CC(N);
  1516. case ISD::SETCC: return visitSETCC(N);
  1517. case ISD::SETCCCARRY: return visitSETCCCARRY(N);
  1518. case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N);
  1519. case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N);
  1520. case ISD::ANY_EXTEND: return visitANY_EXTEND(N);
  1521. case ISD::AssertSext:
  1522. case ISD::AssertZext: return visitAssertExt(N);
  1523. case ISD::AssertAlign: return visitAssertAlign(N);
  1524. case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N);
  1525. case ISD::SIGN_EXTEND_VECTOR_INREG:
  1526. case ISD::ZERO_EXTEND_VECTOR_INREG:
  1527. case ISD::ANY_EXTEND_VECTOR_INREG: return visitEXTEND_VECTOR_INREG(N);
  1528. case ISD::TRUNCATE: return visitTRUNCATE(N);
  1529. case ISD::BITCAST: return visitBITCAST(N);
  1530. case ISD::BUILD_PAIR: return visitBUILD_PAIR(N);
  1531. case ISD::FADD: return visitFADD(N);
  1532. case ISD::STRICT_FADD: return visitSTRICT_FADD(N);
  1533. case ISD::FSUB: return visitFSUB(N);
  1534. case ISD::FMUL: return visitFMUL(N);
  1535. case ISD::FMA: return visitFMA(N);
  1536. case ISD::FDIV: return visitFDIV(N);
  1537. case ISD::FREM: return visitFREM(N);
  1538. case ISD::FSQRT: return visitFSQRT(N);
  1539. case ISD::FCOPYSIGN: return visitFCOPYSIGN(N);
  1540. case ISD::FPOW: return visitFPOW(N);
  1541. case ISD::SINT_TO_FP: return visitSINT_TO_FP(N);
  1542. case ISD::UINT_TO_FP: return visitUINT_TO_FP(N);
  1543. case ISD::FP_TO_SINT: return visitFP_TO_SINT(N);
  1544. case ISD::FP_TO_UINT: return visitFP_TO_UINT(N);
  1545. case ISD::FP_ROUND: return visitFP_ROUND(N);
  1546. case ISD::FP_EXTEND: return visitFP_EXTEND(N);
  1547. case ISD::FNEG: return visitFNEG(N);
  1548. case ISD::FABS: return visitFABS(N);
  1549. case ISD::FFLOOR: return visitFFLOOR(N);
  1550. case ISD::FMINNUM:
  1551. case ISD::FMAXNUM:
  1552. case ISD::FMINIMUM:
  1553. case ISD::FMAXIMUM: return visitFMinMax(N);
  1554. case ISD::FCEIL: return visitFCEIL(N);
  1555. case ISD::FTRUNC: return visitFTRUNC(N);
  1556. case ISD::BRCOND: return visitBRCOND(N);
  1557. case ISD::BR_CC: return visitBR_CC(N);
  1558. case ISD::LOAD: return visitLOAD(N);
  1559. case ISD::STORE: return visitSTORE(N);
  1560. case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N);
  1561. case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
  1562. case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N);
  1563. case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N);
  1564. case ISD::EXTRACT_SUBVECTOR: return visitEXTRACT_SUBVECTOR(N);
  1565. case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N);
  1566. case ISD::SCALAR_TO_VECTOR: return visitSCALAR_TO_VECTOR(N);
  1567. case ISD::INSERT_SUBVECTOR: return visitINSERT_SUBVECTOR(N);
  1568. case ISD::MGATHER: return visitMGATHER(N);
  1569. case ISD::MLOAD: return visitMLOAD(N);
  1570. case ISD::MSCATTER: return visitMSCATTER(N);
  1571. case ISD::MSTORE: return visitMSTORE(N);
  1572. case ISD::LIFETIME_END: return visitLIFETIME_END(N);
  1573. case ISD::FP_TO_FP16: return visitFP_TO_FP16(N);
  1574. case ISD::FP16_TO_FP: return visitFP16_TO_FP(N);
  1575. case ISD::FP_TO_BF16: return visitFP_TO_BF16(N);
  1576. case ISD::FREEZE: return visitFREEZE(N);
  1577. case ISD::VECREDUCE_FADD:
  1578. case ISD::VECREDUCE_FMUL:
  1579. case ISD::VECREDUCE_ADD:
  1580. case ISD::VECREDUCE_MUL:
  1581. case ISD::VECREDUCE_AND:
  1582. case ISD::VECREDUCE_OR:
  1583. case ISD::VECREDUCE_XOR:
  1584. case ISD::VECREDUCE_SMAX:
  1585. case ISD::VECREDUCE_SMIN:
  1586. case ISD::VECREDUCE_UMAX:
  1587. case ISD::VECREDUCE_UMIN:
  1588. case ISD::VECREDUCE_FMAX:
  1589. case ISD::VECREDUCE_FMIN: return visitVECREDUCE(N);
  1590. #define BEGIN_REGISTER_VP_SDNODE(SDOPC, ...) case ISD::SDOPC:
  1591. #include "llvm/IR/VPIntrinsics.def"
  1592. return visitVPOp(N);
  1593. }
  1594. return SDValue();
  1595. }
  1596. SDValue DAGCombiner::combine(SDNode *N) {
  1597. SDValue RV;
  1598. if (!DisableGenericCombines)
  1599. RV = visit(N);
  1600. // If nothing happened, try a target-specific DAG combine.
  1601. if (!RV.getNode()) {
  1602. assert(N->getOpcode() != ISD::DELETED_NODE &&
  1603. "Node was deleted but visit returned NULL!");
  1604. if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
  1605. TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
  1606. // Expose the DAG combiner to the target combiner impls.
  1607. TargetLowering::DAGCombinerInfo
  1608. DagCombineInfo(DAG, Level, false, this);
  1609. RV = TLI.PerformDAGCombine(N, DagCombineInfo);
  1610. }
  1611. }
  1612. // If nothing happened still, try promoting the operation.
  1613. if (!RV.getNode()) {
  1614. switch (N->getOpcode()) {
  1615. default: break;
  1616. case ISD::ADD:
  1617. case ISD::SUB:
  1618. case ISD::MUL:
  1619. case ISD::AND:
  1620. case ISD::OR:
  1621. case ISD::XOR:
  1622. RV = PromoteIntBinOp(SDValue(N, 0));
  1623. break;
  1624. case ISD::SHL:
  1625. case ISD::SRA:
  1626. case ISD::SRL:
  1627. RV = PromoteIntShiftOp(SDValue(N, 0));
  1628. break;
  1629. case ISD::SIGN_EXTEND:
  1630. case ISD::ZERO_EXTEND:
  1631. case ISD::ANY_EXTEND:
  1632. RV = PromoteExtend(SDValue(N, 0));
  1633. break;
  1634. case ISD::LOAD:
  1635. if (PromoteLoad(SDValue(N, 0)))
  1636. RV = SDValue(N, 0);
  1637. break;
  1638. }
  1639. }
  1640. // If N is a commutative binary node, try to eliminate it if the commuted
  1641. // version is already present in the DAG.
  1642. if (!RV.getNode() && TLI.isCommutativeBinOp(N->getOpcode())) {
  1643. SDValue N0 = N->getOperand(0);
  1644. SDValue N1 = N->getOperand(1);
  1645. // Constant operands are canonicalized to RHS.
  1646. if (N0 != N1 && (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1))) {
  1647. SDValue Ops[] = {N1, N0};
  1648. SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops,
  1649. N->getFlags());
  1650. if (CSENode)
  1651. return SDValue(CSENode, 0);
  1652. }
  1653. }
  1654. return RV;
  1655. }
  1656. /// Given a node, return its input chain if it has one, otherwise return a null
  1657. /// sd operand.
  1658. static SDValue getInputChainForNode(SDNode *N) {
  1659. if (unsigned NumOps = N->getNumOperands()) {
  1660. if (N->getOperand(0).getValueType() == MVT::Other)
  1661. return N->getOperand(0);
  1662. if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
  1663. return N->getOperand(NumOps-1);
  1664. for (unsigned i = 1; i < NumOps-1; ++i)
  1665. if (N->getOperand(i).getValueType() == MVT::Other)
  1666. return N->getOperand(i);
  1667. }
  1668. return SDValue();
  1669. }
  1670. SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
  1671. // If N has two operands, where one has an input chain equal to the other,
  1672. // the 'other' chain is redundant.
  1673. if (N->getNumOperands() == 2) {
  1674. if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
  1675. return N->getOperand(0);
  1676. if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
  1677. return N->getOperand(1);
  1678. }
  1679. // Don't simplify token factors if optnone.
  1680. if (OptLevel == CodeGenOpt::None)
  1681. return SDValue();
  1682. // Don't simplify the token factor if the node itself has too many operands.
  1683. if (N->getNumOperands() > TokenFactorInlineLimit)
  1684. return SDValue();
  1685. // If the sole user is a token factor, we should make sure we have a
  1686. // chance to merge them together. This prevents TF chains from inhibiting
  1687. // optimizations.
  1688. if (N->hasOneUse() && N->use_begin()->getOpcode() == ISD::TokenFactor)
  1689. AddToWorklist(*(N->use_begin()));
  1690. SmallVector<SDNode *, 8> TFs; // List of token factors to visit.
  1691. SmallVector<SDValue, 8> Ops; // Ops for replacing token factor.
  1692. SmallPtrSet<SDNode*, 16> SeenOps;
  1693. bool Changed = false; // If we should replace this token factor.
  1694. // Start out with this token factor.
  1695. TFs.push_back(N);
  1696. // Iterate through token factors. The TFs grows when new token factors are
  1697. // encountered.
  1698. for (unsigned i = 0; i < TFs.size(); ++i) {
  1699. // Limit number of nodes to inline, to avoid quadratic compile times.
  1700. // We have to add the outstanding Token Factors to Ops, otherwise we might
  1701. // drop Ops from the resulting Token Factors.
  1702. if (Ops.size() > TokenFactorInlineLimit) {
  1703. for (unsigned j = i; j < TFs.size(); j++)
  1704. Ops.emplace_back(TFs[j], 0);
  1705. // Drop unprocessed Token Factors from TFs, so we do not add them to the
  1706. // combiner worklist later.
  1707. TFs.resize(i);
  1708. break;
  1709. }
  1710. SDNode *TF = TFs[i];
  1711. // Check each of the operands.
  1712. for (const SDValue &Op : TF->op_values()) {
  1713. switch (Op.getOpcode()) {
  1714. case ISD::EntryToken:
  1715. // Entry tokens don't need to be added to the list. They are
  1716. // redundant.
  1717. Changed = true;
  1718. break;
  1719. case ISD::TokenFactor:
  1720. if (Op.hasOneUse() && !is_contained(TFs, Op.getNode())) {
  1721. // Queue up for processing.
  1722. TFs.push_back(Op.getNode());
  1723. Changed = true;
  1724. break;
  1725. }
  1726. [[fallthrough]];
  1727. default:
  1728. // Only add if it isn't already in the list.
  1729. if (SeenOps.insert(Op.getNode()).second)
  1730. Ops.push_back(Op);
  1731. else
  1732. Changed = true;
  1733. break;
  1734. }
  1735. }
  1736. }
  1737. // Re-visit inlined Token Factors, to clean them up in case they have been
  1738. // removed. Skip the first Token Factor, as this is the current node.
  1739. for (unsigned i = 1, e = TFs.size(); i < e; i++)
  1740. AddToWorklist(TFs[i]);
  1741. // Remove Nodes that are chained to another node in the list. Do so
  1742. // by walking up chains breath-first stopping when we've seen
  1743. // another operand. In general we must climb to the EntryNode, but we can exit
  1744. // early if we find all remaining work is associated with just one operand as
  1745. // no further pruning is possible.
  1746. // List of nodes to search through and original Ops from which they originate.
  1747. SmallVector<std::pair<SDNode *, unsigned>, 8> Worklist;
  1748. SmallVector<unsigned, 8> OpWorkCount; // Count of work for each Op.
  1749. SmallPtrSet<SDNode *, 16> SeenChains;
  1750. bool DidPruneOps = false;
  1751. unsigned NumLeftToConsider = 0;
  1752. for (const SDValue &Op : Ops) {
  1753. Worklist.push_back(std::make_pair(Op.getNode(), NumLeftToConsider++));
  1754. OpWorkCount.push_back(1);
  1755. }
  1756. auto AddToWorklist = [&](unsigned CurIdx, SDNode *Op, unsigned OpNumber) {
  1757. // If this is an Op, we can remove the op from the list. Remark any
  1758. // search associated with it as from the current OpNumber.
  1759. if (SeenOps.contains(Op)) {
  1760. Changed = true;
  1761. DidPruneOps = true;
  1762. unsigned OrigOpNumber = 0;
  1763. while (OrigOpNumber < Ops.size() && Ops[OrigOpNumber].getNode() != Op)
  1764. OrigOpNumber++;
  1765. assert((OrigOpNumber != Ops.size()) &&
  1766. "expected to find TokenFactor Operand");
  1767. // Re-mark worklist from OrigOpNumber to OpNumber
  1768. for (unsigned i = CurIdx + 1; i < Worklist.size(); ++i) {
  1769. if (Worklist[i].second == OrigOpNumber) {
  1770. Worklist[i].second = OpNumber;
  1771. }
  1772. }
  1773. OpWorkCount[OpNumber] += OpWorkCount[OrigOpNumber];
  1774. OpWorkCount[OrigOpNumber] = 0;
  1775. NumLeftToConsider--;
  1776. }
  1777. // Add if it's a new chain
  1778. if (SeenChains.insert(Op).second) {
  1779. OpWorkCount[OpNumber]++;
  1780. Worklist.push_back(std::make_pair(Op, OpNumber));
  1781. }
  1782. };
  1783. for (unsigned i = 0; i < Worklist.size() && i < 1024; ++i) {
  1784. // We need at least be consider at least 2 Ops to prune.
  1785. if (NumLeftToConsider <= 1)
  1786. break;
  1787. auto CurNode = Worklist[i].first;
  1788. auto CurOpNumber = Worklist[i].second;
  1789. assert((OpWorkCount[CurOpNumber] > 0) &&
  1790. "Node should not appear in worklist");
  1791. switch (CurNode->getOpcode()) {
  1792. case ISD::EntryToken:
  1793. // Hitting EntryToken is the only way for the search to terminate without
  1794. // hitting
  1795. // another operand's search. Prevent us from marking this operand
  1796. // considered.
  1797. NumLeftToConsider++;
  1798. break;
  1799. case ISD::TokenFactor:
  1800. for (const SDValue &Op : CurNode->op_values())
  1801. AddToWorklist(i, Op.getNode(), CurOpNumber);
  1802. break;
  1803. case ISD::LIFETIME_START:
  1804. case ISD::LIFETIME_END:
  1805. case ISD::CopyFromReg:
  1806. case ISD::CopyToReg:
  1807. AddToWorklist(i, CurNode->getOperand(0).getNode(), CurOpNumber);
  1808. break;
  1809. default:
  1810. if (auto *MemNode = dyn_cast<MemSDNode>(CurNode))
  1811. AddToWorklist(i, MemNode->getChain().getNode(), CurOpNumber);
  1812. break;
  1813. }
  1814. OpWorkCount[CurOpNumber]--;
  1815. if (OpWorkCount[CurOpNumber] == 0)
  1816. NumLeftToConsider--;
  1817. }
  1818. // If we've changed things around then replace token factor.
  1819. if (Changed) {
  1820. SDValue Result;
  1821. if (Ops.empty()) {
  1822. // The entry token is the only possible outcome.
  1823. Result = DAG.getEntryNode();
  1824. } else {
  1825. if (DidPruneOps) {
  1826. SmallVector<SDValue, 8> PrunedOps;
  1827. //
  1828. for (const SDValue &Op : Ops) {
  1829. if (SeenChains.count(Op.getNode()) == 0)
  1830. PrunedOps.push_back(Op);
  1831. }
  1832. Result = DAG.getTokenFactor(SDLoc(N), PrunedOps);
  1833. } else {
  1834. Result = DAG.getTokenFactor(SDLoc(N), Ops);
  1835. }
  1836. }
  1837. return Result;
  1838. }
  1839. return SDValue();
  1840. }
  1841. /// MERGE_VALUES can always be eliminated.
  1842. SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
  1843. WorklistRemover DeadNodes(*this);
  1844. // Replacing results may cause a different MERGE_VALUES to suddenly
  1845. // be CSE'd with N, and carry its uses with it. Iterate until no
  1846. // uses remain, to ensure that the node can be safely deleted.
  1847. // First add the users of this node to the work list so that they
  1848. // can be tried again once they have new operands.
  1849. AddUsersToWorklist(N);
  1850. do {
  1851. // Do as a single replacement to avoid rewalking use lists.
  1852. SmallVector<SDValue, 8> Ops;
  1853. for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
  1854. Ops.push_back(N->getOperand(i));
  1855. DAG.ReplaceAllUsesWith(N, Ops.data());
  1856. } while (!N->use_empty());
  1857. deleteAndRecombine(N);
  1858. return SDValue(N, 0); // Return N so it doesn't get rechecked!
  1859. }
  1860. /// If \p N is a ConstantSDNode with isOpaque() == false return it casted to a
  1861. /// ConstantSDNode pointer else nullptr.
  1862. static ConstantSDNode *getAsNonOpaqueConstant(SDValue N) {
  1863. ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N);
  1864. return Const != nullptr && !Const->isOpaque() ? Const : nullptr;
  1865. }
  1866. /// Return true if 'Use' is a load or a store that uses N as its base pointer
  1867. /// and that N may be folded in the load / store addressing mode.
  1868. static bool canFoldInAddressingMode(SDNode *N, SDNode *Use, SelectionDAG &DAG,
  1869. const TargetLowering &TLI) {
  1870. EVT VT;
  1871. unsigned AS;
  1872. if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) {
  1873. if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
  1874. return false;
  1875. VT = LD->getMemoryVT();
  1876. AS = LD->getAddressSpace();
  1877. } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) {
  1878. if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
  1879. return false;
  1880. VT = ST->getMemoryVT();
  1881. AS = ST->getAddressSpace();
  1882. } else if (MaskedLoadSDNode *LD = dyn_cast<MaskedLoadSDNode>(Use)) {
  1883. if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
  1884. return false;
  1885. VT = LD->getMemoryVT();
  1886. AS = LD->getAddressSpace();
  1887. } else if (MaskedStoreSDNode *ST = dyn_cast<MaskedStoreSDNode>(Use)) {
  1888. if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
  1889. return false;
  1890. VT = ST->getMemoryVT();
  1891. AS = ST->getAddressSpace();
  1892. } else {
  1893. return false;
  1894. }
  1895. TargetLowering::AddrMode AM;
  1896. if (N->getOpcode() == ISD::ADD) {
  1897. AM.HasBaseReg = true;
  1898. ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
  1899. if (Offset)
  1900. // [reg +/- imm]
  1901. AM.BaseOffs = Offset->getSExtValue();
  1902. else
  1903. // [reg +/- reg]
  1904. AM.Scale = 1;
  1905. } else if (N->getOpcode() == ISD::SUB) {
  1906. AM.HasBaseReg = true;
  1907. ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
  1908. if (Offset)
  1909. // [reg +/- imm]
  1910. AM.BaseOffs = -Offset->getSExtValue();
  1911. else
  1912. // [reg +/- reg]
  1913. AM.Scale = 1;
  1914. } else {
  1915. return false;
  1916. }
  1917. return TLI.isLegalAddressingMode(DAG.getDataLayout(), AM,
  1918. VT.getTypeForEVT(*DAG.getContext()), AS);
  1919. }
  1920. /// This inverts a canonicalization in IR that replaces a variable select arm
  1921. /// with an identity constant. Codegen improves if we re-use the variable
  1922. /// operand rather than load a constant. This can also be converted into a
  1923. /// masked vector operation if the target supports it.
  1924. static SDValue foldSelectWithIdentityConstant(SDNode *N, SelectionDAG &DAG,
  1925. bool ShouldCommuteOperands) {
  1926. // Match a select as operand 1. The identity constant that we are looking for
  1927. // is only valid as operand 1 of a non-commutative binop.
  1928. SDValue N0 = N->getOperand(0);
  1929. SDValue N1 = N->getOperand(1);
  1930. if (ShouldCommuteOperands)
  1931. std::swap(N0, N1);
  1932. // TODO: Should this apply to scalar select too?
  1933. if (N1.getOpcode() != ISD::VSELECT || !N1.hasOneUse())
  1934. return SDValue();
  1935. // We can't hoist div/rem because of immediate UB (not speculatable).
  1936. unsigned Opcode = N->getOpcode();
  1937. if (!DAG.isSafeToSpeculativelyExecute(Opcode))
  1938. return SDValue();
  1939. EVT VT = N->getValueType(0);
  1940. SDValue Cond = N1.getOperand(0);
  1941. SDValue TVal = N1.getOperand(1);
  1942. SDValue FVal = N1.getOperand(2);
  1943. // This transform increases uses of N0, so freeze it to be safe.
  1944. // binop N0, (vselect Cond, IDC, FVal) --> vselect Cond, N0, (binop N0, FVal)
  1945. unsigned OpNo = ShouldCommuteOperands ? 0 : 1;
  1946. if (isNeutralConstant(Opcode, N->getFlags(), TVal, OpNo)) {
  1947. SDValue F0 = DAG.getFreeze(N0);
  1948. SDValue NewBO = DAG.getNode(Opcode, SDLoc(N), VT, F0, FVal, N->getFlags());
  1949. return DAG.getSelect(SDLoc(N), VT, Cond, F0, NewBO);
  1950. }
  1951. // binop N0, (vselect Cond, TVal, IDC) --> vselect Cond, (binop N0, TVal), N0
  1952. if (isNeutralConstant(Opcode, N->getFlags(), FVal, OpNo)) {
  1953. SDValue F0 = DAG.getFreeze(N0);
  1954. SDValue NewBO = DAG.getNode(Opcode, SDLoc(N), VT, F0, TVal, N->getFlags());
  1955. return DAG.getSelect(SDLoc(N), VT, Cond, NewBO, F0);
  1956. }
  1957. return SDValue();
  1958. }
  1959. SDValue DAGCombiner::foldBinOpIntoSelect(SDNode *BO) {
  1960. assert(TLI.isBinOp(BO->getOpcode()) && BO->getNumValues() == 1 &&
  1961. "Unexpected binary operator");
  1962. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  1963. auto BinOpcode = BO->getOpcode();
  1964. EVT VT = BO->getValueType(0);
  1965. if (TLI.shouldFoldSelectWithIdentityConstant(BinOpcode, VT)) {
  1966. if (SDValue Sel = foldSelectWithIdentityConstant(BO, DAG, false))
  1967. return Sel;
  1968. if (TLI.isCommutativeBinOp(BO->getOpcode()))
  1969. if (SDValue Sel = foldSelectWithIdentityConstant(BO, DAG, true))
  1970. return Sel;
  1971. }
  1972. // Don't do this unless the old select is going away. We want to eliminate the
  1973. // binary operator, not replace a binop with a select.
  1974. // TODO: Handle ISD::SELECT_CC.
  1975. unsigned SelOpNo = 0;
  1976. SDValue Sel = BO->getOperand(0);
  1977. if (Sel.getOpcode() != ISD::SELECT || !Sel.hasOneUse()) {
  1978. SelOpNo = 1;
  1979. Sel = BO->getOperand(1);
  1980. }
  1981. if (Sel.getOpcode() != ISD::SELECT || !Sel.hasOneUse())
  1982. return SDValue();
  1983. SDValue CT = Sel.getOperand(1);
  1984. if (!isConstantOrConstantVector(CT, true) &&
  1985. !DAG.isConstantFPBuildVectorOrConstantFP(CT))
  1986. return SDValue();
  1987. SDValue CF = Sel.getOperand(2);
  1988. if (!isConstantOrConstantVector(CF, true) &&
  1989. !DAG.isConstantFPBuildVectorOrConstantFP(CF))
  1990. return SDValue();
  1991. // Bail out if any constants are opaque because we can't constant fold those.
  1992. // The exception is "and" and "or" with either 0 or -1 in which case we can
  1993. // propagate non constant operands into select. I.e.:
  1994. // and (select Cond, 0, -1), X --> select Cond, 0, X
  1995. // or X, (select Cond, -1, 0) --> select Cond, -1, X
  1996. bool CanFoldNonConst =
  1997. (BinOpcode == ISD::AND || BinOpcode == ISD::OR) &&
  1998. ((isNullOrNullSplat(CT) && isAllOnesOrAllOnesSplat(CF)) ||
  1999. (isNullOrNullSplat(CF) && isAllOnesOrAllOnesSplat(CT)));
  2000. SDValue CBO = BO->getOperand(SelOpNo ^ 1);
  2001. if (!CanFoldNonConst &&
  2002. !isConstantOrConstantVector(CBO, true) &&
  2003. !DAG.isConstantFPBuildVectorOrConstantFP(CBO))
  2004. return SDValue();
  2005. SDLoc DL(Sel);
  2006. SDValue NewCT, NewCF;
  2007. if (CanFoldNonConst) {
  2008. // If CBO is an opaque constant, we can't rely on getNode to constant fold.
  2009. if ((BinOpcode == ISD::AND && isNullOrNullSplat(CT)) ||
  2010. (BinOpcode == ISD::OR && isAllOnesOrAllOnesSplat(CT)))
  2011. NewCT = CT;
  2012. else
  2013. NewCT = CBO;
  2014. if ((BinOpcode == ISD::AND && isNullOrNullSplat(CF)) ||
  2015. (BinOpcode == ISD::OR && isAllOnesOrAllOnesSplat(CF)))
  2016. NewCF = CF;
  2017. else
  2018. NewCF = CBO;
  2019. } else {
  2020. // We have a select-of-constants followed by a binary operator with a
  2021. // constant. Eliminate the binop by pulling the constant math into the
  2022. // select. Example: add (select Cond, CT, CF), CBO --> select Cond, CT +
  2023. // CBO, CF + CBO
  2024. NewCT = SelOpNo ? DAG.getNode(BinOpcode, DL, VT, CBO, CT)
  2025. : DAG.getNode(BinOpcode, DL, VT, CT, CBO);
  2026. if (!CanFoldNonConst && !NewCT.isUndef() &&
  2027. !isConstantOrConstantVector(NewCT, true) &&
  2028. !DAG.isConstantFPBuildVectorOrConstantFP(NewCT))
  2029. return SDValue();
  2030. NewCF = SelOpNo ? DAG.getNode(BinOpcode, DL, VT, CBO, CF)
  2031. : DAG.getNode(BinOpcode, DL, VT, CF, CBO);
  2032. if (!CanFoldNonConst && !NewCF.isUndef() &&
  2033. !isConstantOrConstantVector(NewCF, true) &&
  2034. !DAG.isConstantFPBuildVectorOrConstantFP(NewCF))
  2035. return SDValue();
  2036. }
  2037. SDValue SelectOp = DAG.getSelect(DL, VT, Sel.getOperand(0), NewCT, NewCF);
  2038. SelectOp->setFlags(BO->getFlags());
  2039. return SelectOp;
  2040. }
  2041. static SDValue foldAddSubBoolOfMaskedVal(SDNode *N, SelectionDAG &DAG) {
  2042. assert((N->getOpcode() == ISD::ADD || N->getOpcode() == ISD::SUB) &&
  2043. "Expecting add or sub");
  2044. // Match a constant operand and a zext operand for the math instruction:
  2045. // add Z, C
  2046. // sub C, Z
  2047. bool IsAdd = N->getOpcode() == ISD::ADD;
  2048. SDValue C = IsAdd ? N->getOperand(1) : N->getOperand(0);
  2049. SDValue Z = IsAdd ? N->getOperand(0) : N->getOperand(1);
  2050. auto *CN = dyn_cast<ConstantSDNode>(C);
  2051. if (!CN || Z.getOpcode() != ISD::ZERO_EXTEND)
  2052. return SDValue();
  2053. // Match the zext operand as a setcc of a boolean.
  2054. if (Z.getOperand(0).getOpcode() != ISD::SETCC ||
  2055. Z.getOperand(0).getValueType() != MVT::i1)
  2056. return SDValue();
  2057. // Match the compare as: setcc (X & 1), 0, eq.
  2058. SDValue SetCC = Z.getOperand(0);
  2059. ISD::CondCode CC = cast<CondCodeSDNode>(SetCC->getOperand(2))->get();
  2060. if (CC != ISD::SETEQ || !isNullConstant(SetCC.getOperand(1)) ||
  2061. SetCC.getOperand(0).getOpcode() != ISD::AND ||
  2062. !isOneConstant(SetCC.getOperand(0).getOperand(1)))
  2063. return SDValue();
  2064. // We are adding/subtracting a constant and an inverted low bit. Turn that
  2065. // into a subtract/add of the low bit with incremented/decremented constant:
  2066. // add (zext i1 (seteq (X & 1), 0)), C --> sub C+1, (zext (X & 1))
  2067. // sub C, (zext i1 (seteq (X & 1), 0)) --> add C-1, (zext (X & 1))
  2068. EVT VT = C.getValueType();
  2069. SDLoc DL(N);
  2070. SDValue LowBit = DAG.getZExtOrTrunc(SetCC.getOperand(0), DL, VT);
  2071. SDValue C1 = IsAdd ? DAG.getConstant(CN->getAPIntValue() + 1, DL, VT) :
  2072. DAG.getConstant(CN->getAPIntValue() - 1, DL, VT);
  2073. return DAG.getNode(IsAdd ? ISD::SUB : ISD::ADD, DL, VT, C1, LowBit);
  2074. }
  2075. /// Try to fold a 'not' shifted sign-bit with add/sub with constant operand into
  2076. /// a shift and add with a different constant.
  2077. static SDValue foldAddSubOfSignBit(SDNode *N, SelectionDAG &DAG) {
  2078. assert((N->getOpcode() == ISD::ADD || N->getOpcode() == ISD::SUB) &&
  2079. "Expecting add or sub");
  2080. // We need a constant operand for the add/sub, and the other operand is a
  2081. // logical shift right: add (srl), C or sub C, (srl).
  2082. bool IsAdd = N->getOpcode() == ISD::ADD;
  2083. SDValue ConstantOp = IsAdd ? N->getOperand(1) : N->getOperand(0);
  2084. SDValue ShiftOp = IsAdd ? N->getOperand(0) : N->getOperand(1);
  2085. if (!DAG.isConstantIntBuildVectorOrConstantInt(ConstantOp) ||
  2086. ShiftOp.getOpcode() != ISD::SRL)
  2087. return SDValue();
  2088. // The shift must be of a 'not' value.
  2089. SDValue Not = ShiftOp.getOperand(0);
  2090. if (!Not.hasOneUse() || !isBitwiseNot(Not))
  2091. return SDValue();
  2092. // The shift must be moving the sign bit to the least-significant-bit.
  2093. EVT VT = ShiftOp.getValueType();
  2094. SDValue ShAmt = ShiftOp.getOperand(1);
  2095. ConstantSDNode *ShAmtC = isConstOrConstSplat(ShAmt);
  2096. if (!ShAmtC || ShAmtC->getAPIntValue() != (VT.getScalarSizeInBits() - 1))
  2097. return SDValue();
  2098. // Eliminate the 'not' by adjusting the shift and add/sub constant:
  2099. // add (srl (not X), 31), C --> add (sra X, 31), (C + 1)
  2100. // sub C, (srl (not X), 31) --> add (srl X, 31), (C - 1)
  2101. SDLoc DL(N);
  2102. if (SDValue NewC = DAG.FoldConstantArithmetic(
  2103. IsAdd ? ISD::ADD : ISD::SUB, DL, VT,
  2104. {ConstantOp, DAG.getConstant(1, DL, VT)})) {
  2105. SDValue NewShift = DAG.getNode(IsAdd ? ISD::SRA : ISD::SRL, DL, VT,
  2106. Not.getOperand(0), ShAmt);
  2107. return DAG.getNode(ISD::ADD, DL, VT, NewShift, NewC);
  2108. }
  2109. return SDValue();
  2110. }
  2111. static bool isADDLike(SDValue V, const SelectionDAG &DAG) {
  2112. unsigned Opcode = V.getOpcode();
  2113. if (Opcode == ISD::OR)
  2114. return DAG.haveNoCommonBitsSet(V.getOperand(0), V.getOperand(1));
  2115. if (Opcode == ISD::XOR)
  2116. return isMinSignedConstant(V.getOperand(1));
  2117. return false;
  2118. }
  2119. /// Try to fold a node that behaves like an ADD (note that N isn't necessarily
  2120. /// an ISD::ADD here, it could for example be an ISD::OR if we know that there
  2121. /// are no common bits set in the operands).
  2122. SDValue DAGCombiner::visitADDLike(SDNode *N) {
  2123. SDValue N0 = N->getOperand(0);
  2124. SDValue N1 = N->getOperand(1);
  2125. EVT VT = N0.getValueType();
  2126. SDLoc DL(N);
  2127. // fold (add x, undef) -> undef
  2128. if (N0.isUndef())
  2129. return N0;
  2130. if (N1.isUndef())
  2131. return N1;
  2132. // fold (add c1, c2) -> c1+c2
  2133. if (SDValue C = DAG.FoldConstantArithmetic(ISD::ADD, DL, VT, {N0, N1}))
  2134. return C;
  2135. // canonicalize constant to RHS
  2136. if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
  2137. !DAG.isConstantIntBuildVectorOrConstantInt(N1))
  2138. return DAG.getNode(ISD::ADD, DL, VT, N1, N0);
  2139. // fold vector ops
  2140. if (VT.isVector()) {
  2141. if (SDValue FoldedVOp = SimplifyVBinOp(N, DL))
  2142. return FoldedVOp;
  2143. // fold (add x, 0) -> x, vector edition
  2144. if (ISD::isConstantSplatVectorAllZeros(N1.getNode()))
  2145. return N0;
  2146. }
  2147. // fold (add x, 0) -> x
  2148. if (isNullConstant(N1))
  2149. return N0;
  2150. if (N0.getOpcode() == ISD::SUB) {
  2151. SDValue N00 = N0.getOperand(0);
  2152. SDValue N01 = N0.getOperand(1);
  2153. // fold ((A-c1)+c2) -> (A+(c2-c1))
  2154. if (SDValue Sub = DAG.FoldConstantArithmetic(ISD::SUB, DL, VT, {N1, N01}))
  2155. return DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(0), Sub);
  2156. // fold ((c1-A)+c2) -> (c1+c2)-A
  2157. if (SDValue Add = DAG.FoldConstantArithmetic(ISD::ADD, DL, VT, {N1, N00}))
  2158. return DAG.getNode(ISD::SUB, DL, VT, Add, N0.getOperand(1));
  2159. }
  2160. // add (sext i1 X), 1 -> zext (not i1 X)
  2161. // We don't transform this pattern:
  2162. // add (zext i1 X), -1 -> sext (not i1 X)
  2163. // because most (?) targets generate better code for the zext form.
  2164. if (N0.getOpcode() == ISD::SIGN_EXTEND && N0.hasOneUse() &&
  2165. isOneOrOneSplat(N1)) {
  2166. SDValue X = N0.getOperand(0);
  2167. if ((!LegalOperations ||
  2168. (TLI.isOperationLegal(ISD::XOR, X.getValueType()) &&
  2169. TLI.isOperationLegal(ISD::ZERO_EXTEND, VT))) &&
  2170. X.getScalarValueSizeInBits() == 1) {
  2171. SDValue Not = DAG.getNOT(DL, X, X.getValueType());
  2172. return DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Not);
  2173. }
  2174. }
  2175. // Fold (add (or x, c0), c1) -> (add x, (c0 + c1))
  2176. // iff (or x, c0) is equivalent to (add x, c0).
  2177. // Fold (add (xor x, c0), c1) -> (add x, (c0 + c1))
  2178. // iff (xor x, c0) is equivalent to (add x, c0).
  2179. if (isADDLike(N0, DAG)) {
  2180. SDValue N01 = N0.getOperand(1);
  2181. if (SDValue Add = DAG.FoldConstantArithmetic(ISD::ADD, DL, VT, {N1, N01}))
  2182. return DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(0), Add);
  2183. }
  2184. if (SDValue NewSel = foldBinOpIntoSelect(N))
  2185. return NewSel;
  2186. // reassociate add
  2187. if (!reassociationCanBreakAddressingModePattern(ISD::ADD, DL, N, N0, N1)) {
  2188. if (SDValue RADD = reassociateOps(ISD::ADD, DL, N0, N1, N->getFlags()))
  2189. return RADD;
  2190. // Reassociate (add (or x, c), y) -> (add add(x, y), c)) if (or x, c) is
  2191. // equivalent to (add x, c).
  2192. // Reassociate (add (xor x, c), y) -> (add add(x, y), c)) if (xor x, c) is
  2193. // equivalent to (add x, c).
  2194. auto ReassociateAddOr = [&](SDValue N0, SDValue N1) {
  2195. if (isADDLike(N0, DAG) && N0.hasOneUse() &&
  2196. isConstantOrConstantVector(N0.getOperand(1), /* NoOpaque */ true)) {
  2197. return DAG.getNode(ISD::ADD, DL, VT,
  2198. DAG.getNode(ISD::ADD, DL, VT, N1, N0.getOperand(0)),
  2199. N0.getOperand(1));
  2200. }
  2201. return SDValue();
  2202. };
  2203. if (SDValue Add = ReassociateAddOr(N0, N1))
  2204. return Add;
  2205. if (SDValue Add = ReassociateAddOr(N1, N0))
  2206. return Add;
  2207. }
  2208. // fold ((0-A) + B) -> B-A
  2209. if (N0.getOpcode() == ISD::SUB && isNullOrNullSplat(N0.getOperand(0)))
  2210. return DAG.getNode(ISD::SUB, DL, VT, N1, N0.getOperand(1));
  2211. // fold (A + (0-B)) -> A-B
  2212. if (N1.getOpcode() == ISD::SUB && isNullOrNullSplat(N1.getOperand(0)))
  2213. return DAG.getNode(ISD::SUB, DL, VT, N0, N1.getOperand(1));
  2214. // fold (A+(B-A)) -> B
  2215. if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
  2216. return N1.getOperand(0);
  2217. // fold ((B-A)+A) -> B
  2218. if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
  2219. return N0.getOperand(0);
  2220. // fold ((A-B)+(C-A)) -> (C-B)
  2221. if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB &&
  2222. N0.getOperand(0) == N1.getOperand(1))
  2223. return DAG.getNode(ISD::SUB, DL, VT, N1.getOperand(0),
  2224. N0.getOperand(1));
  2225. // fold ((A-B)+(B-C)) -> (A-C)
  2226. if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB &&
  2227. N0.getOperand(1) == N1.getOperand(0))
  2228. return DAG.getNode(ISD::SUB, DL, VT, N0.getOperand(0),
  2229. N1.getOperand(1));
  2230. // fold (A+(B-(A+C))) to (B-C)
  2231. if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
  2232. N0 == N1.getOperand(1).getOperand(0))
  2233. return DAG.getNode(ISD::SUB, DL, VT, N1.getOperand(0),
  2234. N1.getOperand(1).getOperand(1));
  2235. // fold (A+(B-(C+A))) to (B-C)
  2236. if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
  2237. N0 == N1.getOperand(1).getOperand(1))
  2238. return DAG.getNode(ISD::SUB, DL, VT, N1.getOperand(0),
  2239. N1.getOperand(1).getOperand(0));
  2240. // fold (A+((B-A)+or-C)) to (B+or-C)
  2241. if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
  2242. N1.getOperand(0).getOpcode() == ISD::SUB &&
  2243. N0 == N1.getOperand(0).getOperand(1))
  2244. return DAG.getNode(N1.getOpcode(), DL, VT, N1.getOperand(0).getOperand(0),
  2245. N1.getOperand(1));
  2246. // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
  2247. if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB &&
  2248. N0->hasOneUse() && N1->hasOneUse()) {
  2249. SDValue N00 = N0.getOperand(0);
  2250. SDValue N01 = N0.getOperand(1);
  2251. SDValue N10 = N1.getOperand(0);
  2252. SDValue N11 = N1.getOperand(1);
  2253. if (isConstantOrConstantVector(N00) || isConstantOrConstantVector(N10))
  2254. return DAG.getNode(ISD::SUB, DL, VT,
  2255. DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
  2256. DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
  2257. }
  2258. // fold (add (umax X, C), -C) --> (usubsat X, C)
  2259. if (N0.getOpcode() == ISD::UMAX && hasOperation(ISD::USUBSAT, VT)) {
  2260. auto MatchUSUBSAT = [](ConstantSDNode *Max, ConstantSDNode *Op) {
  2261. return (!Max && !Op) ||
  2262. (Max && Op && Max->getAPIntValue() == (-Op->getAPIntValue()));
  2263. };
  2264. if (ISD::matchBinaryPredicate(N0.getOperand(1), N1, MatchUSUBSAT,
  2265. /*AllowUndefs*/ true))
  2266. return DAG.getNode(ISD::USUBSAT, DL, VT, N0.getOperand(0),
  2267. N0.getOperand(1));
  2268. }
  2269. if (SimplifyDemandedBits(SDValue(N, 0)))
  2270. return SDValue(N, 0);
  2271. if (isOneOrOneSplat(N1)) {
  2272. // fold (add (xor a, -1), 1) -> (sub 0, a)
  2273. if (isBitwiseNot(N0))
  2274. return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT),
  2275. N0.getOperand(0));
  2276. // fold (add (add (xor a, -1), b), 1) -> (sub b, a)
  2277. if (N0.getOpcode() == ISD::ADD) {
  2278. SDValue A, Xor;
  2279. if (isBitwiseNot(N0.getOperand(0))) {
  2280. A = N0.getOperand(1);
  2281. Xor = N0.getOperand(0);
  2282. } else if (isBitwiseNot(N0.getOperand(1))) {
  2283. A = N0.getOperand(0);
  2284. Xor = N0.getOperand(1);
  2285. }
  2286. if (Xor)
  2287. return DAG.getNode(ISD::SUB, DL, VT, A, Xor.getOperand(0));
  2288. }
  2289. // Look for:
  2290. // add (add x, y), 1
  2291. // And if the target does not like this form then turn into:
  2292. // sub y, (xor x, -1)
  2293. if (!TLI.preferIncOfAddToSubOfNot(VT) && N0.getOpcode() == ISD::ADD &&
  2294. N0.hasOneUse()) {
  2295. SDValue Not = DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(0),
  2296. DAG.getAllOnesConstant(DL, VT));
  2297. return DAG.getNode(ISD::SUB, DL, VT, N0.getOperand(1), Not);
  2298. }
  2299. }
  2300. // (x - y) + -1 -> add (xor y, -1), x
  2301. if (N0.getOpcode() == ISD::SUB && N0.hasOneUse() &&
  2302. isAllOnesOrAllOnesSplat(N1)) {
  2303. SDValue Xor = DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(1), N1);
  2304. return DAG.getNode(ISD::ADD, DL, VT, Xor, N0.getOperand(0));
  2305. }
  2306. if (SDValue Combined = visitADDLikeCommutative(N0, N1, N))
  2307. return Combined;
  2308. if (SDValue Combined = visitADDLikeCommutative(N1, N0, N))
  2309. return Combined;
  2310. return SDValue();
  2311. }
  2312. SDValue DAGCombiner::visitADD(SDNode *N) {
  2313. SDValue N0 = N->getOperand(0);
  2314. SDValue N1 = N->getOperand(1);
  2315. EVT VT = N0.getValueType();
  2316. SDLoc DL(N);
  2317. if (SDValue Combined = visitADDLike(N))
  2318. return Combined;
  2319. if (SDValue V = foldAddSubBoolOfMaskedVal(N, DAG))
  2320. return V;
  2321. if (SDValue V = foldAddSubOfSignBit(N, DAG))
  2322. return V;
  2323. // fold (a+b) -> (a|b) iff a and b share no bits.
  2324. if ((!LegalOperations || TLI.isOperationLegal(ISD::OR, VT)) &&
  2325. DAG.haveNoCommonBitsSet(N0, N1))
  2326. return DAG.getNode(ISD::OR, DL, VT, N0, N1);
  2327. // Fold (add (vscale * C0), (vscale * C1)) to (vscale * (C0 + C1)).
  2328. if (N0.getOpcode() == ISD::VSCALE && N1.getOpcode() == ISD::VSCALE) {
  2329. const APInt &C0 = N0->getConstantOperandAPInt(0);
  2330. const APInt &C1 = N1->getConstantOperandAPInt(0);
  2331. return DAG.getVScale(DL, VT, C0 + C1);
  2332. }
  2333. // fold a+vscale(c1)+vscale(c2) -> a+vscale(c1+c2)
  2334. if (N0.getOpcode() == ISD::ADD &&
  2335. N0.getOperand(1).getOpcode() == ISD::VSCALE &&
  2336. N1.getOpcode() == ISD::VSCALE) {
  2337. const APInt &VS0 = N0.getOperand(1)->getConstantOperandAPInt(0);
  2338. const APInt &VS1 = N1->getConstantOperandAPInt(0);
  2339. SDValue VS = DAG.getVScale(DL, VT, VS0 + VS1);
  2340. return DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(0), VS);
  2341. }
  2342. // Fold (add step_vector(c1), step_vector(c2) to step_vector(c1+c2))
  2343. if (N0.getOpcode() == ISD::STEP_VECTOR &&
  2344. N1.getOpcode() == ISD::STEP_VECTOR) {
  2345. const APInt &C0 = N0->getConstantOperandAPInt(0);
  2346. const APInt &C1 = N1->getConstantOperandAPInt(0);
  2347. APInt NewStep = C0 + C1;
  2348. return DAG.getStepVector(DL, VT, NewStep);
  2349. }
  2350. // Fold a + step_vector(c1) + step_vector(c2) to a + step_vector(c1+c2)
  2351. if (N0.getOpcode() == ISD::ADD &&
  2352. N0.getOperand(1).getOpcode() == ISD::STEP_VECTOR &&
  2353. N1.getOpcode() == ISD::STEP_VECTOR) {
  2354. const APInt &SV0 = N0.getOperand(1)->getConstantOperandAPInt(0);
  2355. const APInt &SV1 = N1->getConstantOperandAPInt(0);
  2356. APInt NewStep = SV0 + SV1;
  2357. SDValue SV = DAG.getStepVector(DL, VT, NewStep);
  2358. return DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(0), SV);
  2359. }
  2360. return SDValue();
  2361. }
  2362. SDValue DAGCombiner::visitADDSAT(SDNode *N) {
  2363. unsigned Opcode = N->getOpcode();
  2364. SDValue N0 = N->getOperand(0);
  2365. SDValue N1 = N->getOperand(1);
  2366. EVT VT = N0.getValueType();
  2367. SDLoc DL(N);
  2368. // fold (add_sat x, undef) -> -1
  2369. if (N0.isUndef() || N1.isUndef())
  2370. return DAG.getAllOnesConstant(DL, VT);
  2371. // fold (add_sat c1, c2) -> c3
  2372. if (SDValue C = DAG.FoldConstantArithmetic(Opcode, DL, VT, {N0, N1}))
  2373. return C;
  2374. // canonicalize constant to RHS
  2375. if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
  2376. !DAG.isConstantIntBuildVectorOrConstantInt(N1))
  2377. return DAG.getNode(Opcode, DL, VT, N1, N0);
  2378. // fold vector ops
  2379. if (VT.isVector()) {
  2380. if (SDValue FoldedVOp = SimplifyVBinOp(N, DL))
  2381. return FoldedVOp;
  2382. // fold (add_sat x, 0) -> x, vector edition
  2383. if (ISD::isConstantSplatVectorAllZeros(N1.getNode()))
  2384. return N0;
  2385. }
  2386. // fold (add_sat x, 0) -> x
  2387. if (isNullConstant(N1))
  2388. return N0;
  2389. // If it cannot overflow, transform into an add.
  2390. if (Opcode == ISD::UADDSAT)
  2391. if (DAG.computeOverflowKind(N0, N1) == SelectionDAG::OFK_Never)
  2392. return DAG.getNode(ISD::ADD, DL, VT, N0, N1);
  2393. return SDValue();
  2394. }
  2395. static SDValue getAsCarry(const TargetLowering &TLI, SDValue V) {
  2396. bool Masked = false;
  2397. // First, peel away TRUNCATE/ZERO_EXTEND/AND nodes due to legalization.
  2398. while (true) {
  2399. if (V.getOpcode() == ISD::TRUNCATE || V.getOpcode() == ISD::ZERO_EXTEND) {
  2400. V = V.getOperand(0);
  2401. continue;
  2402. }
  2403. if (V.getOpcode() == ISD::AND && isOneConstant(V.getOperand(1))) {
  2404. Masked = true;
  2405. V = V.getOperand(0);
  2406. continue;
  2407. }
  2408. break;
  2409. }
  2410. // If this is not a carry, return.
  2411. if (V.getResNo() != 1)
  2412. return SDValue();
  2413. if (V.getOpcode() != ISD::ADDCARRY && V.getOpcode() != ISD::SUBCARRY &&
  2414. V.getOpcode() != ISD::UADDO && V.getOpcode() != ISD::USUBO)
  2415. return SDValue();
  2416. EVT VT = V->getValueType(0);
  2417. if (!TLI.isOperationLegalOrCustom(V.getOpcode(), VT))
  2418. return SDValue();
  2419. // If the result is masked, then no matter what kind of bool it is we can
  2420. // return. If it isn't, then we need to make sure the bool type is either 0 or
  2421. // 1 and not other values.
  2422. if (Masked ||
  2423. TLI.getBooleanContents(V.getValueType()) ==
  2424. TargetLoweringBase::ZeroOrOneBooleanContent)
  2425. return V;
  2426. return SDValue();
  2427. }
  2428. /// Given the operands of an add/sub operation, see if the 2nd operand is a
  2429. /// masked 0/1 whose source operand is actually known to be 0/-1. If so, invert
  2430. /// the opcode and bypass the mask operation.
  2431. static SDValue foldAddSubMasked1(bool IsAdd, SDValue N0, SDValue N1,
  2432. SelectionDAG &DAG, const SDLoc &DL) {
  2433. if (N1.getOpcode() == ISD::ZERO_EXTEND)
  2434. N1 = N1.getOperand(0);
  2435. if (N1.getOpcode() != ISD::AND || !isOneOrOneSplat(N1->getOperand(1)))
  2436. return SDValue();
  2437. EVT VT = N0.getValueType();
  2438. SDValue N10 = N1.getOperand(0);
  2439. if (N10.getValueType() != VT && N10.getOpcode() == ISD::TRUNCATE)
  2440. N10 = N10.getOperand(0);
  2441. if (N10.getValueType() != VT)
  2442. return SDValue();
  2443. if (DAG.ComputeNumSignBits(N10) != VT.getScalarSizeInBits())
  2444. return SDValue();
  2445. // add N0, (and (AssertSext X, i1), 1) --> sub N0, X
  2446. // sub N0, (and (AssertSext X, i1), 1) --> add N0, X
  2447. return DAG.getNode(IsAdd ? ISD::SUB : ISD::ADD, DL, VT, N0, N10);
  2448. }
  2449. /// Helper for doing combines based on N0 and N1 being added to each other.
  2450. SDValue DAGCombiner::visitADDLikeCommutative(SDValue N0, SDValue N1,
  2451. SDNode *LocReference) {
  2452. EVT VT = N0.getValueType();
  2453. SDLoc DL(LocReference);
  2454. // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
  2455. if (N1.getOpcode() == ISD::SHL && N1.getOperand(0).getOpcode() == ISD::SUB &&
  2456. isNullOrNullSplat(N1.getOperand(0).getOperand(0)))
  2457. return DAG.getNode(ISD::SUB, DL, VT, N0,
  2458. DAG.getNode(ISD::SHL, DL, VT,
  2459. N1.getOperand(0).getOperand(1),
  2460. N1.getOperand(1)));
  2461. if (SDValue V = foldAddSubMasked1(true, N0, N1, DAG, DL))
  2462. return V;
  2463. // Look for:
  2464. // add (add x, 1), y
  2465. // And if the target does not like this form then turn into:
  2466. // sub y, (xor x, -1)
  2467. if (!TLI.preferIncOfAddToSubOfNot(VT) && N0.getOpcode() == ISD::ADD &&
  2468. N0.hasOneUse() && isOneOrOneSplat(N0.getOperand(1))) {
  2469. SDValue Not = DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(0),
  2470. DAG.getAllOnesConstant(DL, VT));
  2471. return DAG.getNode(ISD::SUB, DL, VT, N1, Not);
  2472. }
  2473. if (N0.getOpcode() == ISD::SUB && N0.hasOneUse()) {
  2474. // Hoist one-use subtraction by non-opaque constant:
  2475. // (x - C) + y -> (x + y) - C
  2476. // This is necessary because SUB(X,C) -> ADD(X,-C) doesn't work for vectors.
  2477. if (isConstantOrConstantVector(N0.getOperand(1), /*NoOpaques=*/true)) {
  2478. SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(0), N1);
  2479. return DAG.getNode(ISD::SUB, DL, VT, Add, N0.getOperand(1));
  2480. }
  2481. // Hoist one-use subtraction from non-opaque constant:
  2482. // (C - x) + y -> (y - x) + C
  2483. if (isConstantOrConstantVector(N0.getOperand(0), /*NoOpaques=*/true)) {
  2484. SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N1, N0.getOperand(1));
  2485. return DAG.getNode(ISD::ADD, DL, VT, Sub, N0.getOperand(0));
  2486. }
  2487. }
  2488. // If the target's bool is represented as 0/1, prefer to make this 'sub 0/1'
  2489. // rather than 'add 0/-1' (the zext should get folded).
  2490. // add (sext i1 Y), X --> sub X, (zext i1 Y)
  2491. if (N0.getOpcode() == ISD::SIGN_EXTEND &&
  2492. N0.getOperand(0).getScalarValueSizeInBits() == 1 &&
  2493. TLI.getBooleanContents(VT) == TargetLowering::ZeroOrOneBooleanContent) {
  2494. SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
  2495. return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
  2496. }
  2497. // add X, (sextinreg Y i1) -> sub X, (and Y 1)
  2498. if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
  2499. VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
  2500. if (TN->getVT() == MVT::i1) {
  2501. SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
  2502. DAG.getConstant(1, DL, VT));
  2503. return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt);
  2504. }
  2505. }
  2506. // (add X, (addcarry Y, 0, Carry)) -> (addcarry X, Y, Carry)
  2507. if (N1.getOpcode() == ISD::ADDCARRY && isNullConstant(N1.getOperand(1)) &&
  2508. N1.getResNo() == 0)
  2509. return DAG.getNode(ISD::ADDCARRY, DL, N1->getVTList(),
  2510. N0, N1.getOperand(0), N1.getOperand(2));
  2511. // (add X, Carry) -> (addcarry X, 0, Carry)
  2512. if (TLI.isOperationLegalOrCustom(ISD::ADDCARRY, VT))
  2513. if (SDValue Carry = getAsCarry(TLI, N1))
  2514. return DAG.getNode(ISD::ADDCARRY, DL,
  2515. DAG.getVTList(VT, Carry.getValueType()), N0,
  2516. DAG.getConstant(0, DL, VT), Carry);
  2517. return SDValue();
  2518. }
  2519. SDValue DAGCombiner::visitADDC(SDNode *N) {
  2520. SDValue N0 = N->getOperand(0);
  2521. SDValue N1 = N->getOperand(1);
  2522. EVT VT = N0.getValueType();
  2523. SDLoc DL(N);
  2524. // If the flag result is dead, turn this into an ADD.
  2525. if (!N->hasAnyUseOfValue(1))
  2526. return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1),
  2527. DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
  2528. // canonicalize constant to RHS.
  2529. ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
  2530. ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
  2531. if (N0C && !N1C)
  2532. return DAG.getNode(ISD::ADDC, DL, N->getVTList(), N1, N0);
  2533. // fold (addc x, 0) -> x + no carry out
  2534. if (isNullConstant(N1))
  2535. return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
  2536. DL, MVT::Glue));
  2537. // If it cannot overflow, transform into an add.
  2538. if (DAG.computeOverflowKind(N0, N1) == SelectionDAG::OFK_Never)
  2539. return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1),
  2540. DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
  2541. return SDValue();
  2542. }
  2543. /**
  2544. * Flips a boolean if it is cheaper to compute. If the Force parameters is set,
  2545. * then the flip also occurs if computing the inverse is the same cost.
  2546. * This function returns an empty SDValue in case it cannot flip the boolean
  2547. * without increasing the cost of the computation. If you want to flip a boolean
  2548. * no matter what, use DAG.getLogicalNOT.
  2549. */
  2550. static SDValue extractBooleanFlip(SDValue V, SelectionDAG &DAG,
  2551. const TargetLowering &TLI,
  2552. bool Force) {
  2553. if (Force && isa<ConstantSDNode>(V))
  2554. return DAG.getLogicalNOT(SDLoc(V), V, V.getValueType());
  2555. if (V.getOpcode() != ISD::XOR)
  2556. return SDValue();
  2557. ConstantSDNode *Const = isConstOrConstSplat(V.getOperand(1), false);
  2558. if (!Const)
  2559. return SDValue();
  2560. EVT VT = V.getValueType();
  2561. bool IsFlip = false;
  2562. switch(TLI.getBooleanContents(VT)) {
  2563. case TargetLowering::ZeroOrOneBooleanContent:
  2564. IsFlip = Const->isOne();
  2565. break;
  2566. case TargetLowering::ZeroOrNegativeOneBooleanContent:
  2567. IsFlip = Const->isAllOnes();
  2568. break;
  2569. case TargetLowering::UndefinedBooleanContent:
  2570. IsFlip = (Const->getAPIntValue() & 0x01) == 1;
  2571. break;
  2572. }
  2573. if (IsFlip)
  2574. return V.getOperand(0);
  2575. if (Force)
  2576. return DAG.getLogicalNOT(SDLoc(V), V, V.getValueType());
  2577. return SDValue();
  2578. }
  2579. SDValue DAGCombiner::visitADDO(SDNode *N) {
  2580. SDValue N0 = N->getOperand(0);
  2581. SDValue N1 = N->getOperand(1);
  2582. EVT VT = N0.getValueType();
  2583. bool IsSigned = (ISD::SADDO == N->getOpcode());
  2584. EVT CarryVT = N->getValueType(1);
  2585. SDLoc DL(N);
  2586. // If the flag result is dead, turn this into an ADD.
  2587. if (!N->hasAnyUseOfValue(1))
  2588. return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1),
  2589. DAG.getUNDEF(CarryVT));
  2590. // canonicalize constant to RHS.
  2591. if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
  2592. !DAG.isConstantIntBuildVectorOrConstantInt(N1))
  2593. return DAG.getNode(N->getOpcode(), DL, N->getVTList(), N1, N0);
  2594. // fold (addo x, 0) -> x + no carry out
  2595. if (isNullOrNullSplat(N1))
  2596. return CombineTo(N, N0, DAG.getConstant(0, DL, CarryVT));
  2597. if (!IsSigned) {
  2598. // If it cannot overflow, transform into an add.
  2599. if (DAG.computeOverflowKind(N0, N1) == SelectionDAG::OFK_Never)
  2600. return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1),
  2601. DAG.getConstant(0, DL, CarryVT));
  2602. // fold (uaddo (xor a, -1), 1) -> (usub 0, a) and flip carry.
  2603. if (isBitwiseNot(N0) && isOneOrOneSplat(N1)) {
  2604. SDValue Sub = DAG.getNode(ISD::USUBO, DL, N->getVTList(),
  2605. DAG.getConstant(0, DL, VT), N0.getOperand(0));
  2606. return CombineTo(
  2607. N, Sub, DAG.getLogicalNOT(DL, Sub.getValue(1), Sub->getValueType(1)));
  2608. }
  2609. if (SDValue Combined = visitUADDOLike(N0, N1, N))
  2610. return Combined;
  2611. if (SDValue Combined = visitUADDOLike(N1, N0, N))
  2612. return Combined;
  2613. }
  2614. return SDValue();
  2615. }
  2616. SDValue DAGCombiner::visitUADDOLike(SDValue N0, SDValue N1, SDNode *N) {
  2617. EVT VT = N0.getValueType();
  2618. if (VT.isVector())
  2619. return SDValue();
  2620. // (uaddo X, (addcarry Y, 0, Carry)) -> (addcarry X, Y, Carry)
  2621. // If Y + 1 cannot overflow.
  2622. if (N1.getOpcode() == ISD::ADDCARRY && isNullConstant(N1.getOperand(1))) {
  2623. SDValue Y = N1.getOperand(0);
  2624. SDValue One = DAG.getConstant(1, SDLoc(N), Y.getValueType());
  2625. if (DAG.computeOverflowKind(Y, One) == SelectionDAG::OFK_Never)
  2626. return DAG.getNode(ISD::ADDCARRY, SDLoc(N), N->getVTList(), N0, Y,
  2627. N1.getOperand(2));
  2628. }
  2629. // (uaddo X, Carry) -> (addcarry X, 0, Carry)
  2630. if (TLI.isOperationLegalOrCustom(ISD::ADDCARRY, VT))
  2631. if (SDValue Carry = getAsCarry(TLI, N1))
  2632. return DAG.getNode(ISD::ADDCARRY, SDLoc(N), N->getVTList(), N0,
  2633. DAG.getConstant(0, SDLoc(N), VT), Carry);
  2634. return SDValue();
  2635. }
  2636. SDValue DAGCombiner::visitADDE(SDNode *N) {
  2637. SDValue N0 = N->getOperand(0);
  2638. SDValue N1 = N->getOperand(1);
  2639. SDValue CarryIn = N->getOperand(2);
  2640. // canonicalize constant to RHS
  2641. ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
  2642. ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
  2643. if (N0C && !N1C)
  2644. return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
  2645. N1, N0, CarryIn);
  2646. // fold (adde x, y, false) -> (addc x, y)
  2647. if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
  2648. return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
  2649. return SDValue();
  2650. }
  2651. SDValue DAGCombiner::visitADDCARRY(SDNode *N) {
  2652. SDValue N0 = N->getOperand(0);
  2653. SDValue N1 = N->getOperand(1);
  2654. SDValue CarryIn = N->getOperand(2);
  2655. SDLoc DL(N);
  2656. // canonicalize constant to RHS
  2657. ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
  2658. ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
  2659. if (N0C && !N1C)
  2660. return DAG.getNode(ISD::ADDCARRY, DL, N->getVTList(), N1, N0, CarryIn);
  2661. // fold (addcarry x, y, false) -> (uaddo x, y)
  2662. if (isNullConstant(CarryIn)) {
  2663. if (!LegalOperations ||
  2664. TLI.isOperationLegalOrCustom(ISD::UADDO, N->getValueType(0)))
  2665. return DAG.getNode(ISD::UADDO, DL, N->getVTList(), N0, N1);
  2666. }
  2667. // fold (addcarry 0, 0, X) -> (and (ext/trunc X), 1) and no carry.
  2668. if (isNullConstant(N0) && isNullConstant(N1)) {
  2669. EVT VT = N0.getValueType();
  2670. EVT CarryVT = CarryIn.getValueType();
  2671. SDValue CarryExt = DAG.getBoolExtOrTrunc(CarryIn, DL, VT, CarryVT);
  2672. AddToWorklist(CarryExt.getNode());
  2673. return CombineTo(N, DAG.getNode(ISD::AND, DL, VT, CarryExt,
  2674. DAG.getConstant(1, DL, VT)),
  2675. DAG.getConstant(0, DL, CarryVT));
  2676. }
  2677. if (SDValue Combined = visitADDCARRYLike(N0, N1, CarryIn, N))
  2678. return Combined;
  2679. if (SDValue Combined = visitADDCARRYLike(N1, N0, CarryIn, N))
  2680. return Combined;
  2681. // We want to avoid useless duplication.
  2682. // TODO: This is done automatically for binary operations. As ADDCARRY is
  2683. // not a binary operation, this is not really possible to leverage this
  2684. // existing mechanism for it. However, if more operations require the same
  2685. // deduplication logic, then it may be worth generalize.
  2686. SDValue Ops[] = {N1, N0, CarryIn};
  2687. SDNode *CSENode =
  2688. DAG.getNodeIfExists(ISD::ADDCARRY, N->getVTList(), Ops, N->getFlags());
  2689. if (CSENode)
  2690. return SDValue(CSENode, 0);
  2691. return SDValue();
  2692. }
  2693. SDValue DAGCombiner::visitSADDO_CARRY(SDNode *N) {
  2694. SDValue N0 = N->getOperand(0);
  2695. SDValue N1 = N->getOperand(1);
  2696. SDValue CarryIn = N->getOperand(2);
  2697. SDLoc DL(N);
  2698. // canonicalize constant to RHS
  2699. ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
  2700. ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
  2701. if (N0C && !N1C)
  2702. return DAG.getNode(ISD::SADDO_CARRY, DL, N->getVTList(), N1, N0, CarryIn);
  2703. // fold (saddo_carry x, y, false) -> (saddo x, y)
  2704. if (isNullConstant(CarryIn)) {
  2705. if (!LegalOperations ||
  2706. TLI.isOperationLegalOrCustom(ISD::SADDO, N->getValueType(0)))
  2707. return DAG.getNode(ISD::SADDO, DL, N->getVTList(), N0, N1);
  2708. }
  2709. return SDValue();
  2710. }
  2711. /**
  2712. * If we are facing some sort of diamond carry propapagtion pattern try to
  2713. * break it up to generate something like:
  2714. * (addcarry X, 0, (addcarry A, B, Z):Carry)
  2715. *
  2716. * The end result is usually an increase in operation required, but because the
  2717. * carry is now linearized, other transforms can kick in and optimize the DAG.
  2718. *
  2719. * Patterns typically look something like
  2720. * (uaddo A, B)
  2721. * / \
  2722. * Carry Sum
  2723. * | \
  2724. * | (addcarry *, 0, Z)
  2725. * | /
  2726. * \ Carry
  2727. * | /
  2728. * (addcarry X, *, *)
  2729. *
  2730. * But numerous variation exist. Our goal is to identify A, B, X and Z and
  2731. * produce a combine with a single path for carry propagation.
  2732. */
  2733. static SDValue combineADDCARRYDiamond(DAGCombiner &Combiner, SelectionDAG &DAG,
  2734. SDValue X, SDValue Carry0, SDValue Carry1,
  2735. SDNode *N) {
  2736. if (Carry1.getResNo() != 1 || Carry0.getResNo() != 1)
  2737. return SDValue();
  2738. if (Carry1.getOpcode() != ISD::UADDO)
  2739. return SDValue();
  2740. SDValue Z;
  2741. /**
  2742. * First look for a suitable Z. It will present itself in the form of
  2743. * (addcarry Y, 0, Z) or its equivalent (uaddo Y, 1) for Z=true
  2744. */
  2745. if (Carry0.getOpcode() == ISD::ADDCARRY &&
  2746. isNullConstant(Carry0.getOperand(1))) {
  2747. Z = Carry0.getOperand(2);
  2748. } else if (Carry0.getOpcode() == ISD::UADDO &&
  2749. isOneConstant(Carry0.getOperand(1))) {
  2750. EVT VT = Combiner.getSetCCResultType(Carry0.getValueType());
  2751. Z = DAG.getConstant(1, SDLoc(Carry0.getOperand(1)), VT);
  2752. } else {
  2753. // We couldn't find a suitable Z.
  2754. return SDValue();
  2755. }
  2756. auto cancelDiamond = [&](SDValue A,SDValue B) {
  2757. SDLoc DL(N);
  2758. SDValue NewY = DAG.getNode(ISD::ADDCARRY, DL, Carry0->getVTList(), A, B, Z);
  2759. Combiner.AddToWorklist(NewY.getNode());
  2760. return DAG.getNode(ISD::ADDCARRY, DL, N->getVTList(), X,
  2761. DAG.getConstant(0, DL, X.getValueType()),
  2762. NewY.getValue(1));
  2763. };
  2764. /**
  2765. * (uaddo A, B)
  2766. * |
  2767. * Sum
  2768. * |
  2769. * (addcarry *, 0, Z)
  2770. */
  2771. if (Carry0.getOperand(0) == Carry1.getValue(0)) {
  2772. return cancelDiamond(Carry1.getOperand(0), Carry1.getOperand(1));
  2773. }
  2774. /**
  2775. * (addcarry A, 0, Z)
  2776. * |
  2777. * Sum
  2778. * |
  2779. * (uaddo *, B)
  2780. */
  2781. if (Carry1.getOperand(0) == Carry0.getValue(0)) {
  2782. return cancelDiamond(Carry0.getOperand(0), Carry1.getOperand(1));
  2783. }
  2784. if (Carry1.getOperand(1) == Carry0.getValue(0)) {
  2785. return cancelDiamond(Carry1.getOperand(0), Carry0.getOperand(0));
  2786. }
  2787. return SDValue();
  2788. }
  2789. // If we are facing some sort of diamond carry/borrow in/out pattern try to
  2790. // match patterns like:
  2791. //
  2792. // (uaddo A, B) CarryIn
  2793. // | \ |
  2794. // | \ |
  2795. // PartialSum PartialCarryOutX /
  2796. // | | /
  2797. // | ____|____________/
  2798. // | / |
  2799. // (uaddo *, *) \________
  2800. // | \ \
  2801. // | \ |
  2802. // | PartialCarryOutY |
  2803. // | \ |
  2804. // | \ /
  2805. // AddCarrySum | ______/
  2806. // | /
  2807. // CarryOut = (or *, *)
  2808. //
  2809. // And generate ADDCARRY (or SUBCARRY) with two result values:
  2810. //
  2811. // {AddCarrySum, CarryOut} = (addcarry A, B, CarryIn)
  2812. //
  2813. // Our goal is to identify A, B, and CarryIn and produce ADDCARRY/SUBCARRY with
  2814. // a single path for carry/borrow out propagation:
  2815. static SDValue combineCarryDiamond(SelectionDAG &DAG, const TargetLowering &TLI,
  2816. SDValue N0, SDValue N1, SDNode *N) {
  2817. SDValue Carry0 = getAsCarry(TLI, N0);
  2818. if (!Carry0)
  2819. return SDValue();
  2820. SDValue Carry1 = getAsCarry(TLI, N1);
  2821. if (!Carry1)
  2822. return SDValue();
  2823. unsigned Opcode = Carry0.getOpcode();
  2824. if (Opcode != Carry1.getOpcode())
  2825. return SDValue();
  2826. if (Opcode != ISD::UADDO && Opcode != ISD::USUBO)
  2827. return SDValue();
  2828. // Canonicalize the add/sub of A and B (the top node in the above ASCII art)
  2829. // as Carry0 and the add/sub of the carry in as Carry1 (the middle node).
  2830. if (Carry1.getNode()->isOperandOf(Carry0.getNode()))
  2831. std::swap(Carry0, Carry1);
  2832. // Check if nodes are connected in expected way.
  2833. if (Carry1.getOperand(0) != Carry0.getValue(0) &&
  2834. Carry1.getOperand(1) != Carry0.getValue(0))
  2835. return SDValue();
  2836. // The carry in value must be on the righthand side for subtraction.
  2837. unsigned CarryInOperandNum =
  2838. Carry1.getOperand(0) == Carry0.getValue(0) ? 1 : 0;
  2839. if (Opcode == ISD::USUBO && CarryInOperandNum != 1)
  2840. return SDValue();
  2841. SDValue CarryIn = Carry1.getOperand(CarryInOperandNum);
  2842. unsigned NewOp = Opcode == ISD::UADDO ? ISD::ADDCARRY : ISD::SUBCARRY;
  2843. if (!TLI.isOperationLegalOrCustom(NewOp, Carry0.getValue(0).getValueType()))
  2844. return SDValue();
  2845. // Verify that the carry/borrow in is plausibly a carry/borrow bit.
  2846. // TODO: make getAsCarry() aware of how partial carries are merged.
  2847. if (CarryIn.getOpcode() != ISD::ZERO_EXTEND)
  2848. return SDValue();
  2849. CarryIn = CarryIn.getOperand(0);
  2850. if (CarryIn.getValueType() != MVT::i1)
  2851. return SDValue();
  2852. SDLoc DL(N);
  2853. SDValue Merged =
  2854. DAG.getNode(NewOp, DL, Carry1->getVTList(), Carry0.getOperand(0),
  2855. Carry0.getOperand(1), CarryIn);
  2856. // Please note that because we have proven that the result of the UADDO/USUBO
  2857. // of A and B feeds into the UADDO/USUBO that does the carry/borrow in, we can
  2858. // therefore prove that if the first UADDO/USUBO overflows, the second
  2859. // UADDO/USUBO cannot. For example consider 8-bit numbers where 0xFF is the
  2860. // maximum value.
  2861. //
  2862. // 0xFF + 0xFF == 0xFE with carry but 0xFE + 1 does not carry
  2863. // 0x00 - 0xFF == 1 with a carry/borrow but 1 - 1 == 0 (no carry/borrow)
  2864. //
  2865. // This is important because it means that OR and XOR can be used to merge
  2866. // carry flags; and that AND can return a constant zero.
  2867. //
  2868. // TODO: match other operations that can merge flags (ADD, etc)
  2869. DAG.ReplaceAllUsesOfValueWith(Carry1.getValue(0), Merged.getValue(0));
  2870. if (N->getOpcode() == ISD::AND)
  2871. return DAG.getConstant(0, DL, MVT::i1);
  2872. return Merged.getValue(1);
  2873. }
  2874. SDValue DAGCombiner::visitADDCARRYLike(SDValue N0, SDValue N1, SDValue CarryIn,
  2875. SDNode *N) {
  2876. // fold (addcarry (xor a, -1), b, c) -> (subcarry b, a, !c) and flip carry.
  2877. if (isBitwiseNot(N0))
  2878. if (SDValue NotC = extractBooleanFlip(CarryIn, DAG, TLI, true)) {
  2879. SDLoc DL(N);
  2880. SDValue Sub = DAG.getNode(ISD::SUBCARRY, DL, N->getVTList(), N1,
  2881. N0.getOperand(0), NotC);
  2882. return CombineTo(
  2883. N, Sub, DAG.getLogicalNOT(DL, Sub.getValue(1), Sub->getValueType(1)));
  2884. }
  2885. // Iff the flag result is dead:
  2886. // (addcarry (add|uaddo X, Y), 0, Carry) -> (addcarry X, Y, Carry)
  2887. // Don't do this if the Carry comes from the uaddo. It won't remove the uaddo
  2888. // or the dependency between the instructions.
  2889. if ((N0.getOpcode() == ISD::ADD ||
  2890. (N0.getOpcode() == ISD::UADDO && N0.getResNo() == 0 &&
  2891. N0.getValue(1) != CarryIn)) &&
  2892. isNullConstant(N1) && !N->hasAnyUseOfValue(1))
  2893. return DAG.getNode(ISD::ADDCARRY, SDLoc(N), N->getVTList(),
  2894. N0.getOperand(0), N0.getOperand(1), CarryIn);
  2895. /**
  2896. * When one of the addcarry argument is itself a carry, we may be facing
  2897. * a diamond carry propagation. In which case we try to transform the DAG
  2898. * to ensure linear carry propagation if that is possible.
  2899. */
  2900. if (auto Y = getAsCarry(TLI, N1)) {
  2901. // Because both are carries, Y and Z can be swapped.
  2902. if (auto R = combineADDCARRYDiamond(*this, DAG, N0, Y, CarryIn, N))
  2903. return R;
  2904. if (auto R = combineADDCARRYDiamond(*this, DAG, N0, CarryIn, Y, N))
  2905. return R;
  2906. }
  2907. return SDValue();
  2908. }
  2909. // Attempt to create a USUBSAT(LHS, RHS) node with DstVT, performing a
  2910. // clamp/truncation if necessary.
  2911. static SDValue getTruncatedUSUBSAT(EVT DstVT, EVT SrcVT, SDValue LHS,
  2912. SDValue RHS, SelectionDAG &DAG,
  2913. const SDLoc &DL) {
  2914. assert(DstVT.getScalarSizeInBits() <= SrcVT.getScalarSizeInBits() &&
  2915. "Illegal truncation");
  2916. if (DstVT == SrcVT)
  2917. return DAG.getNode(ISD::USUBSAT, DL, DstVT, LHS, RHS);
  2918. // If the LHS is zero-extended then we can perform the USUBSAT as DstVT by
  2919. // clamping RHS.
  2920. APInt UpperBits = APInt::getBitsSetFrom(SrcVT.getScalarSizeInBits(),
  2921. DstVT.getScalarSizeInBits());
  2922. if (!DAG.MaskedValueIsZero(LHS, UpperBits))
  2923. return SDValue();
  2924. SDValue SatLimit =
  2925. DAG.getConstant(APInt::getLowBitsSet(SrcVT.getScalarSizeInBits(),
  2926. DstVT.getScalarSizeInBits()),
  2927. DL, SrcVT);
  2928. RHS = DAG.getNode(ISD::UMIN, DL, SrcVT, RHS, SatLimit);
  2929. RHS = DAG.getNode(ISD::TRUNCATE, DL, DstVT, RHS);
  2930. LHS = DAG.getNode(ISD::TRUNCATE, DL, DstVT, LHS);
  2931. return DAG.getNode(ISD::USUBSAT, DL, DstVT, LHS, RHS);
  2932. }
  2933. // Try to find umax(a,b) - b or a - umin(a,b) patterns that may be converted to
  2934. // usubsat(a,b), optionally as a truncated type.
  2935. SDValue DAGCombiner::foldSubToUSubSat(EVT DstVT, SDNode *N) {
  2936. if (N->getOpcode() != ISD::SUB ||
  2937. !(!LegalOperations || hasOperation(ISD::USUBSAT, DstVT)))
  2938. return SDValue();
  2939. EVT SubVT = N->getValueType(0);
  2940. SDValue Op0 = N->getOperand(0);
  2941. SDValue Op1 = N->getOperand(1);
  2942. // Try to find umax(a,b) - b or a - umin(a,b) patterns
  2943. // they may be converted to usubsat(a,b).
  2944. if (Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) {
  2945. SDValue MaxLHS = Op0.getOperand(0);
  2946. SDValue MaxRHS = Op0.getOperand(1);
  2947. if (MaxLHS == Op1)
  2948. return getTruncatedUSUBSAT(DstVT, SubVT, MaxRHS, Op1, DAG, SDLoc(N));
  2949. if (MaxRHS == Op1)
  2950. return getTruncatedUSUBSAT(DstVT, SubVT, MaxLHS, Op1, DAG, SDLoc(N));
  2951. }
  2952. if (Op1.getOpcode() == ISD::UMIN && Op1.hasOneUse()) {
  2953. SDValue MinLHS = Op1.getOperand(0);
  2954. SDValue MinRHS = Op1.getOperand(1);
  2955. if (MinLHS == Op0)
  2956. return getTruncatedUSUBSAT(DstVT, SubVT, Op0, MinRHS, DAG, SDLoc(N));
  2957. if (MinRHS == Op0)
  2958. return getTruncatedUSUBSAT(DstVT, SubVT, Op0, MinLHS, DAG, SDLoc(N));
  2959. }
  2960. // sub(a,trunc(umin(zext(a),b))) -> usubsat(a,trunc(umin(b,SatLimit)))
  2961. if (Op1.getOpcode() == ISD::TRUNCATE &&
  2962. Op1.getOperand(0).getOpcode() == ISD::UMIN &&
  2963. Op1.getOperand(0).hasOneUse()) {
  2964. SDValue MinLHS = Op1.getOperand(0).getOperand(0);
  2965. SDValue MinRHS = Op1.getOperand(0).getOperand(1);
  2966. if (MinLHS.getOpcode() == ISD::ZERO_EXTEND && MinLHS.getOperand(0) == Op0)
  2967. return getTruncatedUSUBSAT(DstVT, MinLHS.getValueType(), MinLHS, MinRHS,
  2968. DAG, SDLoc(N));
  2969. if (MinRHS.getOpcode() == ISD::ZERO_EXTEND && MinRHS.getOperand(0) == Op0)
  2970. return getTruncatedUSUBSAT(DstVT, MinLHS.getValueType(), MinRHS, MinLHS,
  2971. DAG, SDLoc(N));
  2972. }
  2973. return SDValue();
  2974. }
  2975. // Since it may not be valid to emit a fold to zero for vector initializers
  2976. // check if we can before folding.
  2977. static SDValue tryFoldToZero(const SDLoc &DL, const TargetLowering &TLI, EVT VT,
  2978. SelectionDAG &DAG, bool LegalOperations) {
  2979. if (!VT.isVector())
  2980. return DAG.getConstant(0, DL, VT);
  2981. if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
  2982. return DAG.getConstant(0, DL, VT);
  2983. return SDValue();
  2984. }
  2985. SDValue DAGCombiner::visitSUB(SDNode *N) {
  2986. SDValue N0 = N->getOperand(0);
  2987. SDValue N1 = N->getOperand(1);
  2988. EVT VT = N0.getValueType();
  2989. SDLoc DL(N);
  2990. auto PeekThroughFreeze = [](SDValue N) {
  2991. if (N->getOpcode() == ISD::FREEZE && N.hasOneUse())
  2992. return N->getOperand(0);
  2993. return N;
  2994. };
  2995. // fold (sub x, x) -> 0
  2996. // FIXME: Refactor this and xor and other similar operations together.
  2997. if (PeekThroughFreeze(N0) == PeekThroughFreeze(N1))
  2998. return tryFoldToZero(DL, TLI, VT, DAG, LegalOperations);
  2999. // fold (sub c1, c2) -> c3
  3000. if (SDValue C = DAG.FoldConstantArithmetic(ISD::SUB, DL, VT, {N0, N1}))
  3001. return C;
  3002. // fold vector ops
  3003. if (VT.isVector()) {
  3004. if (SDValue FoldedVOp = SimplifyVBinOp(N, DL))
  3005. return FoldedVOp;
  3006. // fold (sub x, 0) -> x, vector edition
  3007. if (ISD::isConstantSplatVectorAllZeros(N1.getNode()))
  3008. return N0;
  3009. }
  3010. if (SDValue NewSel = foldBinOpIntoSelect(N))
  3011. return NewSel;
  3012. ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
  3013. // fold (sub x, c) -> (add x, -c)
  3014. if (N1C) {
  3015. return DAG.getNode(ISD::ADD, DL, VT, N0,
  3016. DAG.getConstant(-N1C->getAPIntValue(), DL, VT));
  3017. }
  3018. if (isNullOrNullSplat(N0)) {
  3019. unsigned BitWidth = VT.getScalarSizeInBits();
  3020. // Right-shifting everything out but the sign bit followed by negation is
  3021. // the same as flipping arithmetic/logical shift type without the negation:
  3022. // -(X >>u 31) -> (X >>s 31)
  3023. // -(X >>s 31) -> (X >>u 31)
  3024. if (N1->getOpcode() == ISD::SRA || N1->getOpcode() == ISD::SRL) {
  3025. ConstantSDNode *ShiftAmt = isConstOrConstSplat(N1.getOperand(1));
  3026. if (ShiftAmt && ShiftAmt->getAPIntValue() == (BitWidth - 1)) {
  3027. auto NewSh = N1->getOpcode() == ISD::SRA ? ISD::SRL : ISD::SRA;
  3028. if (!LegalOperations || TLI.isOperationLegal(NewSh, VT))
  3029. return DAG.getNode(NewSh, DL, VT, N1.getOperand(0), N1.getOperand(1));
  3030. }
  3031. }
  3032. // 0 - X --> 0 if the sub is NUW.
  3033. if (N->getFlags().hasNoUnsignedWrap())
  3034. return N0;
  3035. if (DAG.MaskedValueIsZero(N1, ~APInt::getSignMask(BitWidth))) {
  3036. // N1 is either 0 or the minimum signed value. If the sub is NSW, then
  3037. // N1 must be 0 because negating the minimum signed value is undefined.
  3038. if (N->getFlags().hasNoSignedWrap())
  3039. return N0;
  3040. // 0 - X --> X if X is 0 or the minimum signed value.
  3041. return N1;
  3042. }
  3043. // Convert 0 - abs(x).
  3044. if (N1.getOpcode() == ISD::ABS && N1.hasOneUse() &&
  3045. !TLI.isOperationLegalOrCustom(ISD::ABS, VT))
  3046. if (SDValue Result = TLI.expandABS(N1.getNode(), DAG, true))
  3047. return Result;
  3048. // Fold neg(splat(neg(x)) -> splat(x)
  3049. if (VT.isVector()) {
  3050. SDValue N1S = DAG.getSplatValue(N1, true);
  3051. if (N1S && N1S.getOpcode() == ISD::SUB &&
  3052. isNullConstant(N1S.getOperand(0)))
  3053. return DAG.getSplat(VT, DL, N1S.getOperand(1));
  3054. }
  3055. }
  3056. // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
  3057. if (isAllOnesOrAllOnesSplat(N0))
  3058. return DAG.getNode(ISD::XOR, DL, VT, N1, N0);
  3059. // fold (A - (0-B)) -> A+B
  3060. if (N1.getOpcode() == ISD::SUB && isNullOrNullSplat(N1.getOperand(0)))
  3061. return DAG.getNode(ISD::ADD, DL, VT, N0, N1.getOperand(1));
  3062. // fold A-(A-B) -> B
  3063. if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
  3064. return N1.getOperand(1);
  3065. // fold (A+B)-A -> B
  3066. if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
  3067. return N0.getOperand(1);
  3068. // fold (A+B)-B -> A
  3069. if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
  3070. return N0.getOperand(0);
  3071. // fold (A+C1)-C2 -> A+(C1-C2)
  3072. if (N0.getOpcode() == ISD::ADD) {
  3073. SDValue N01 = N0.getOperand(1);
  3074. if (SDValue NewC = DAG.FoldConstantArithmetic(ISD::SUB, DL, VT, {N01, N1}))
  3075. return DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(0), NewC);
  3076. }
  3077. // fold C2-(A+C1) -> (C2-C1)-A
  3078. if (N1.getOpcode() == ISD::ADD) {
  3079. SDValue N11 = N1.getOperand(1);
  3080. if (SDValue NewC = DAG.FoldConstantArithmetic(ISD::SUB, DL, VT, {N0, N11}))
  3081. return DAG.getNode(ISD::SUB, DL, VT, NewC, N1.getOperand(0));
  3082. }
  3083. // fold (A-C1)-C2 -> A-(C1+C2)
  3084. if (N0.getOpcode() == ISD::SUB) {
  3085. SDValue N01 = N0.getOperand(1);
  3086. if (SDValue NewC = DAG.FoldConstantArithmetic(ISD::ADD, DL, VT, {N01, N1}))
  3087. return DAG.getNode(ISD::SUB, DL, VT, N0.getOperand(0), NewC);
  3088. }
  3089. // fold (c1-A)-c2 -> (c1-c2)-A
  3090. if (N0.getOpcode() == ISD::SUB) {
  3091. SDValue N00 = N0.getOperand(0);
  3092. if (SDValue NewC = DAG.FoldConstantArithmetic(ISD::SUB, DL, VT, {N00, N1}))
  3093. return DAG.getNode(ISD::SUB, DL, VT, NewC, N0.getOperand(1));
  3094. }
  3095. // fold ((A+(B+or-C))-B) -> A+or-C
  3096. if (N0.getOpcode() == ISD::ADD &&
  3097. (N0.getOperand(1).getOpcode() == ISD::SUB ||
  3098. N0.getOperand(1).getOpcode() == ISD::ADD) &&
  3099. N0.getOperand(1).getOperand(0) == N1)
  3100. return DAG.getNode(N0.getOperand(1).getOpcode(), DL, VT, N0.getOperand(0),
  3101. N0.getOperand(1).getOperand(1));
  3102. // fold ((A+(C+B))-B) -> A+C
  3103. if (N0.getOpcode() == ISD::ADD && N0.getOperand(1).getOpcode() == ISD::ADD &&
  3104. N0.getOperand(1).getOperand(1) == N1)
  3105. return DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(0),
  3106. N0.getOperand(1).getOperand(0));
  3107. // fold ((A-(B-C))-C) -> A-B
  3108. if (N0.getOpcode() == ISD::SUB && N0.getOperand(1).getOpcode() == ISD::SUB &&
  3109. N0.getOperand(1).getOperand(1) == N1)
  3110. return DAG.getNode(ISD::SUB, DL, VT, N0.getOperand(0),
  3111. N0.getOperand(1).getOperand(0));
  3112. // fold (A-(B-C)) -> A+(C-B)
  3113. if (N1.getOpcode() == ISD::SUB && N1.hasOneUse())
  3114. return DAG.getNode(ISD::ADD, DL, VT, N0,
  3115. DAG.getNode(ISD::SUB, DL, VT, N1.getOperand(1),
  3116. N1.getOperand(0)));
  3117. // A - (A & B) -> A & (~B)
  3118. if (N1.getOpcode() == ISD::AND) {
  3119. SDValue A = N1.getOperand(0);
  3120. SDValue B = N1.getOperand(1);
  3121. if (A != N0)
  3122. std::swap(A, B);
  3123. if (A == N0 &&
  3124. (N1.hasOneUse() || isConstantOrConstantVector(B, /*NoOpaques=*/true))) {
  3125. SDValue InvB =
  3126. DAG.getNode(ISD::XOR, DL, VT, B, DAG.getAllOnesConstant(DL, VT));
  3127. return DAG.getNode(ISD::AND, DL, VT, A, InvB);
  3128. }
  3129. }
  3130. // fold (X - (-Y * Z)) -> (X + (Y * Z))
  3131. if (N1.getOpcode() == ISD::MUL && N1.hasOneUse()) {
  3132. if (N1.getOperand(0).getOpcode() == ISD::SUB &&
  3133. isNullOrNullSplat(N1.getOperand(0).getOperand(0))) {
  3134. SDValue Mul = DAG.getNode(ISD::MUL, DL, VT,
  3135. N1.getOperand(0).getOperand(1),
  3136. N1.getOperand(1));
  3137. return DAG.getNode(ISD::ADD, DL, VT, N0, Mul);
  3138. }
  3139. if (N1.getOperand(1).getOpcode() == ISD::SUB &&
  3140. isNullOrNullSplat(N1.getOperand(1).getOperand(0))) {
  3141. SDValue Mul = DAG.getNode(ISD::MUL, DL, VT,
  3142. N1.getOperand(0),
  3143. N1.getOperand(1).getOperand(1));
  3144. return DAG.getNode(ISD::ADD, DL, VT, N0, Mul);
  3145. }
  3146. }
  3147. // If either operand of a sub is undef, the result is undef
  3148. if (N0.isUndef())
  3149. return N0;
  3150. if (N1.isUndef())
  3151. return N1;
  3152. if (SDValue V = foldAddSubBoolOfMaskedVal(N, DAG))
  3153. return V;
  3154. if (SDValue V = foldAddSubOfSignBit(N, DAG))
  3155. return V;
  3156. if (SDValue V = foldAddSubMasked1(false, N0, N1, DAG, SDLoc(N)))
  3157. return V;
  3158. if (SDValue V = foldSubToUSubSat(VT, N))
  3159. return V;
  3160. // (x - y) - 1 -> add (xor y, -1), x
  3161. if (N0.getOpcode() == ISD::SUB && N0.hasOneUse() && isOneOrOneSplat(N1)) {
  3162. SDValue Xor = DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(1),
  3163. DAG.getAllOnesConstant(DL, VT));
  3164. return DAG.getNode(ISD::ADD, DL, VT, Xor, N0.getOperand(0));
  3165. }
  3166. // Look for:
  3167. // sub y, (xor x, -1)
  3168. // And if the target does not like this form then turn into:
  3169. // add (add x, y), 1
  3170. if (TLI.preferIncOfAddToSubOfNot(VT) && N1.hasOneUse() && isBitwiseNot(N1)) {
  3171. SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, N1.getOperand(0));
  3172. return DAG.getNode(ISD::ADD, DL, VT, Add, DAG.getConstant(1, DL, VT));
  3173. }
  3174. // Hoist one-use addition by non-opaque constant:
  3175. // (x + C) - y -> (x - y) + C
  3176. if (N0.getOpcode() == ISD::ADD && N0.hasOneUse() &&
  3177. isConstantOrConstantVector(N0.getOperand(1), /*NoOpaques=*/true)) {
  3178. SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N0.getOperand(0), N1);
  3179. return DAG.getNode(ISD::ADD, DL, VT, Sub, N0.getOperand(1));
  3180. }
  3181. // y - (x + C) -> (y - x) - C
  3182. if (N1.getOpcode() == ISD::ADD && N1.hasOneUse() &&
  3183. isConstantOrConstantVector(N1.getOperand(1), /*NoOpaques=*/true)) {
  3184. SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N0, N1.getOperand(0));
  3185. return DAG.getNode(ISD::SUB, DL, VT, Sub, N1.getOperand(1));
  3186. }
  3187. // (x - C) - y -> (x - y) - C
  3188. // This is necessary because SUB(X,C) -> ADD(X,-C) doesn't work for vectors.
  3189. if (N0.getOpcode() == ISD::SUB && N0.hasOneUse() &&
  3190. isConstantOrConstantVector(N0.getOperand(1), /*NoOpaques=*/true)) {
  3191. SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N0.getOperand(0), N1);
  3192. return DAG.getNode(ISD::SUB, DL, VT, Sub, N0.getOperand(1));
  3193. }
  3194. // (C - x) - y -> C - (x + y)
  3195. if (N0.getOpcode() == ISD::SUB && N0.hasOneUse() &&
  3196. isConstantOrConstantVector(N0.getOperand(0), /*NoOpaques=*/true)) {
  3197. SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(1), N1);
  3198. return DAG.getNode(ISD::SUB, DL, VT, N0.getOperand(0), Add);
  3199. }
  3200. // If the target's bool is represented as 0/-1, prefer to make this 'add 0/-1'
  3201. // rather than 'sub 0/1' (the sext should get folded).
  3202. // sub X, (zext i1 Y) --> add X, (sext i1 Y)
  3203. if (N1.getOpcode() == ISD::ZERO_EXTEND &&
  3204. N1.getOperand(0).getScalarValueSizeInBits() == 1 &&
  3205. TLI.getBooleanContents(VT) ==
  3206. TargetLowering::ZeroOrNegativeOneBooleanContent) {
  3207. SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, N1.getOperand(0));
  3208. return DAG.getNode(ISD::ADD, DL, VT, N0, SExt);
  3209. }
  3210. // fold Y = sra (X, size(X)-1); sub (xor (X, Y), Y) -> (abs X)
  3211. if (TLI.isOperationLegalOrCustom(ISD::ABS, VT)) {
  3212. if (N0.getOpcode() == ISD::XOR && N1.getOpcode() == ISD::SRA) {
  3213. SDValue X0 = N0.getOperand(0), X1 = N0.getOperand(1);
  3214. SDValue S0 = N1.getOperand(0);
  3215. if ((X0 == S0 && X1 == N1) || (X0 == N1 && X1 == S0))
  3216. if (ConstantSDNode *C = isConstOrConstSplat(N1.getOperand(1)))
  3217. if (C->getAPIntValue() == (VT.getScalarSizeInBits() - 1))
  3218. return DAG.getNode(ISD::ABS, SDLoc(N), VT, S0);
  3219. }
  3220. }
  3221. // If the relocation model supports it, consider symbol offsets.
  3222. if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
  3223. if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
  3224. // fold (sub Sym, c) -> Sym-c
  3225. if (N1C && GA->getOpcode() == ISD::GlobalAddress)
  3226. return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
  3227. GA->getOffset() -
  3228. (uint64_t)N1C->getSExtValue());
  3229. // fold (sub Sym+c1, Sym+c2) -> c1-c2
  3230. if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
  3231. if (GA->getGlobal() == GB->getGlobal())
  3232. return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
  3233. DL, VT);
  3234. }
  3235. // sub X, (sextinreg Y i1) -> add X, (and Y 1)
  3236. if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
  3237. VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
  3238. if (TN->getVT() == MVT::i1) {
  3239. SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
  3240. DAG.getConstant(1, DL, VT));
  3241. return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt);
  3242. }
  3243. }
  3244. // canonicalize (sub X, (vscale * C)) to (add X, (vscale * -C))
  3245. if (N1.getOpcode() == ISD::VSCALE && N1.hasOneUse()) {
  3246. const APInt &IntVal = N1.getConstantOperandAPInt(0);
  3247. return DAG.getNode(ISD::ADD, DL, VT, N0, DAG.getVScale(DL, VT, -IntVal));
  3248. }
  3249. // canonicalize (sub X, step_vector(C)) to (add X, step_vector(-C))
  3250. if (N1.getOpcode() == ISD::STEP_VECTOR && N1.hasOneUse()) {
  3251. APInt NewStep = -N1.getConstantOperandAPInt(0);
  3252. return DAG.getNode(ISD::ADD, DL, VT, N0,
  3253. DAG.getStepVector(DL, VT, NewStep));
  3254. }
  3255. // Prefer an add for more folding potential and possibly better codegen:
  3256. // sub N0, (lshr N10, width-1) --> add N0, (ashr N10, width-1)
  3257. if (!LegalOperations && N1.getOpcode() == ISD::SRL && N1.hasOneUse()) {
  3258. SDValue ShAmt = N1.getOperand(1);
  3259. ConstantSDNode *ShAmtC = isConstOrConstSplat(ShAmt);
  3260. if (ShAmtC &&
  3261. ShAmtC->getAPIntValue() == (N1.getScalarValueSizeInBits() - 1)) {
  3262. SDValue SRA = DAG.getNode(ISD::SRA, DL, VT, N1.getOperand(0), ShAmt);
  3263. return DAG.getNode(ISD::ADD, DL, VT, N0, SRA);
  3264. }
  3265. }
  3266. // As with the previous fold, prefer add for more folding potential.
  3267. // Subtracting SMIN/0 is the same as adding SMIN/0:
  3268. // N0 - (X << BW-1) --> N0 + (X << BW-1)
  3269. if (N1.getOpcode() == ISD::SHL) {
  3270. ConstantSDNode *ShlC = isConstOrConstSplat(N1.getOperand(1));
  3271. if (ShlC && ShlC->getAPIntValue() == VT.getScalarSizeInBits() - 1)
  3272. return DAG.getNode(ISD::ADD, DL, VT, N1, N0);
  3273. }
  3274. // (sub (subcarry X, 0, Carry), Y) -> (subcarry X, Y, Carry)
  3275. if (N0.getOpcode() == ISD::SUBCARRY && isNullConstant(N0.getOperand(1)) &&
  3276. N0.getResNo() == 0 && N0.hasOneUse())
  3277. return DAG.getNode(ISD::SUBCARRY, DL, N0->getVTList(),
  3278. N0.getOperand(0), N1, N0.getOperand(2));
  3279. if (TLI.isOperationLegalOrCustom(ISD::ADDCARRY, VT)) {
  3280. // (sub Carry, X) -> (addcarry (sub 0, X), 0, Carry)
  3281. if (SDValue Carry = getAsCarry(TLI, N0)) {
  3282. SDValue X = N1;
  3283. SDValue Zero = DAG.getConstant(0, DL, VT);
  3284. SDValue NegX = DAG.getNode(ISD::SUB, DL, VT, Zero, X);
  3285. return DAG.getNode(ISD::ADDCARRY, DL,
  3286. DAG.getVTList(VT, Carry.getValueType()), NegX, Zero,
  3287. Carry);
  3288. }
  3289. }
  3290. // If there's no chance of borrowing from adjacent bits, then sub is xor:
  3291. // sub C0, X --> xor X, C0
  3292. if (ConstantSDNode *C0 = isConstOrConstSplat(N0)) {
  3293. if (!C0->isOpaque()) {
  3294. const APInt &C0Val = C0->getAPIntValue();
  3295. const APInt &MaybeOnes = ~DAG.computeKnownBits(N1).Zero;
  3296. if ((C0Val - MaybeOnes) == (C0Val ^ MaybeOnes))
  3297. return DAG.getNode(ISD::XOR, DL, VT, N1, N0);
  3298. }
  3299. }
  3300. // max(a,b) - min(a,b) --> abd(a,b)
  3301. auto MatchSubMaxMin = [&](unsigned Max, unsigned Min, unsigned Abd) {
  3302. if (N0.getOpcode() != Max || N1.getOpcode() != Min)
  3303. return SDValue();
  3304. if ((N0.getOperand(0) != N1.getOperand(0) ||
  3305. N0.getOperand(1) != N1.getOperand(1)) &&
  3306. (N0.getOperand(0) != N1.getOperand(1) ||
  3307. N0.getOperand(1) != N1.getOperand(0)))
  3308. return SDValue();
  3309. if (!TLI.isOperationLegalOrCustom(Abd, VT))
  3310. return SDValue();
  3311. return DAG.getNode(Abd, DL, VT, N0.getOperand(0), N0.getOperand(1));
  3312. };
  3313. if (SDValue R = MatchSubMaxMin(ISD::SMAX, ISD::SMIN, ISD::ABDS))
  3314. return R;
  3315. if (SDValue R = MatchSubMaxMin(ISD::UMAX, ISD::UMIN, ISD::ABDU))
  3316. return R;
  3317. return SDValue();
  3318. }
  3319. SDValue DAGCombiner::visitSUBSAT(SDNode *N) {
  3320. SDValue N0 = N->getOperand(0);
  3321. SDValue N1 = N->getOperand(1);
  3322. EVT VT = N0.getValueType();
  3323. SDLoc DL(N);
  3324. // fold (sub_sat x, undef) -> 0
  3325. if (N0.isUndef() || N1.isUndef())
  3326. return DAG.getConstant(0, DL, VT);
  3327. // fold (sub_sat x, x) -> 0
  3328. if (N0 == N1)
  3329. return DAG.getConstant(0, DL, VT);
  3330. // fold (sub_sat c1, c2) -> c3
  3331. if (SDValue C = DAG.FoldConstantArithmetic(N->getOpcode(), DL, VT, {N0, N1}))
  3332. return C;
  3333. // fold vector ops
  3334. if (VT.isVector()) {
  3335. if (SDValue FoldedVOp = SimplifyVBinOp(N, DL))
  3336. return FoldedVOp;
  3337. // fold (sub_sat x, 0) -> x, vector edition
  3338. if (ISD::isConstantSplatVectorAllZeros(N1.getNode()))
  3339. return N0;
  3340. }
  3341. // fold (sub_sat x, 0) -> x
  3342. if (isNullConstant(N1))
  3343. return N0;
  3344. return SDValue();
  3345. }
  3346. SDValue DAGCombiner::visitSUBC(SDNode *N) {
  3347. SDValue N0 = N->getOperand(0);
  3348. SDValue N1 = N->getOperand(1);
  3349. EVT VT = N0.getValueType();
  3350. SDLoc DL(N);
  3351. // If the flag result is dead, turn this into an SUB.
  3352. if (!N->hasAnyUseOfValue(1))
  3353. return CombineTo(N, DAG.getNode(ISD::SUB, DL, VT, N0, N1),
  3354. DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
  3355. // fold (subc x, x) -> 0 + no borrow
  3356. if (N0 == N1)
  3357. return CombineTo(N, DAG.getConstant(0, DL, VT),
  3358. DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
  3359. // fold (subc x, 0) -> x + no borrow
  3360. if (isNullConstant(N1))
  3361. return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
  3362. // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
  3363. if (isAllOnesConstant(N0))
  3364. return CombineTo(N, DAG.getNode(ISD::XOR, DL, VT, N1, N0),
  3365. DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
  3366. return SDValue();
  3367. }
  3368. SDValue DAGCombiner::visitSUBO(SDNode *N) {
  3369. SDValue N0 = N->getOperand(0);
  3370. SDValue N1 = N->getOperand(1);
  3371. EVT VT = N0.getValueType();
  3372. bool IsSigned = (ISD::SSUBO == N->getOpcode());
  3373. EVT CarryVT = N->getValueType(1);
  3374. SDLoc DL(N);
  3375. // If the flag result is dead, turn this into an SUB.
  3376. if (!N->hasAnyUseOfValue(1))
  3377. return CombineTo(N, DAG.getNode(ISD::SUB, DL, VT, N0, N1),
  3378. DAG.getUNDEF(CarryVT));
  3379. // fold (subo x, x) -> 0 + no borrow
  3380. if (N0 == N1)
  3381. return CombineTo(N, DAG.getConstant(0, DL, VT),
  3382. DAG.getConstant(0, DL, CarryVT));
  3383. ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
  3384. // fold (subox, c) -> (addo x, -c)
  3385. if (IsSigned && N1C && !N1C->getAPIntValue().isMinSignedValue()) {
  3386. return DAG.getNode(ISD::SADDO, DL, N->getVTList(), N0,
  3387. DAG.getConstant(-N1C->getAPIntValue(), DL, VT));
  3388. }
  3389. // fold (subo x, 0) -> x + no borrow
  3390. if (isNullOrNullSplat(N1))
  3391. return CombineTo(N, N0, DAG.getConstant(0, DL, CarryVT));
  3392. // Canonicalize (usubo -1, x) -> ~x, i.e. (xor x, -1) + no borrow
  3393. if (!IsSigned && isAllOnesOrAllOnesSplat(N0))
  3394. return CombineTo(N, DAG.getNode(ISD::XOR, DL, VT, N1, N0),
  3395. DAG.getConstant(0, DL, CarryVT));
  3396. return SDValue();
  3397. }
  3398. SDValue DAGCombiner::visitSUBE(SDNode *N) {
  3399. SDValue N0 = N->getOperand(0);
  3400. SDValue N1 = N->getOperand(1);
  3401. SDValue CarryIn = N->getOperand(2);
  3402. // fold (sube x, y, false) -> (subc x, y)
  3403. if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
  3404. return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
  3405. return SDValue();
  3406. }
  3407. SDValue DAGCombiner::visitSUBCARRY(SDNode *N) {
  3408. SDValue N0 = N->getOperand(0);
  3409. SDValue N1 = N->getOperand(1);
  3410. SDValue CarryIn = N->getOperand(2);
  3411. // fold (subcarry x, y, false) -> (usubo x, y)
  3412. if (isNullConstant(CarryIn)) {
  3413. if (!LegalOperations ||
  3414. TLI.isOperationLegalOrCustom(ISD::USUBO, N->getValueType(0)))
  3415. return DAG.getNode(ISD::USUBO, SDLoc(N), N->getVTList(), N0, N1);
  3416. }
  3417. return SDValue();
  3418. }
  3419. SDValue DAGCombiner::visitSSUBO_CARRY(SDNode *N) {
  3420. SDValue N0 = N->getOperand(0);
  3421. SDValue N1 = N->getOperand(1);
  3422. SDValue CarryIn = N->getOperand(2);
  3423. // fold (ssubo_carry x, y, false) -> (ssubo x, y)
  3424. if (isNullConstant(CarryIn)) {
  3425. if (!LegalOperations ||
  3426. TLI.isOperationLegalOrCustom(ISD::SSUBO, N->getValueType(0)))
  3427. return DAG.getNode(ISD::SSUBO, SDLoc(N), N->getVTList(), N0, N1);
  3428. }
  3429. return SDValue();
  3430. }
  3431. // Notice that "mulfix" can be any of SMULFIX, SMULFIXSAT, UMULFIX and
  3432. // UMULFIXSAT here.
  3433. SDValue DAGCombiner::visitMULFIX(SDNode *N) {
  3434. SDValue N0 = N->getOperand(0);
  3435. SDValue N1 = N->getOperand(1);
  3436. SDValue Scale = N->getOperand(2);
  3437. EVT VT = N0.getValueType();
  3438. // fold (mulfix x, undef, scale) -> 0
  3439. if (N0.isUndef() || N1.isUndef())
  3440. return DAG.getConstant(0, SDLoc(N), VT);
  3441. // Canonicalize constant to RHS (vector doesn't have to splat)
  3442. if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
  3443. !DAG.isConstantIntBuildVectorOrConstantInt(N1))
  3444. return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N1, N0, Scale);
  3445. // fold (mulfix x, 0, scale) -> 0
  3446. if (isNullConstant(N1))
  3447. return DAG.getConstant(0, SDLoc(N), VT);
  3448. return SDValue();
  3449. }
  3450. SDValue DAGCombiner::visitMUL(SDNode *N) {
  3451. SDValue N0 = N->getOperand(0);
  3452. SDValue N1 = N->getOperand(1);
  3453. EVT VT = N0.getValueType();
  3454. SDLoc DL(N);
  3455. // fold (mul x, undef) -> 0
  3456. if (N0.isUndef() || N1.isUndef())
  3457. return DAG.getConstant(0, DL, VT);
  3458. // fold (mul c1, c2) -> c1*c2
  3459. if (SDValue C = DAG.FoldConstantArithmetic(ISD::MUL, DL, VT, {N0, N1}))
  3460. return C;
  3461. // canonicalize constant to RHS (vector doesn't have to splat)
  3462. if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
  3463. !DAG.isConstantIntBuildVectorOrConstantInt(N1))
  3464. return DAG.getNode(ISD::MUL, DL, VT, N1, N0);
  3465. bool N1IsConst = false;
  3466. bool N1IsOpaqueConst = false;
  3467. APInt ConstValue1;
  3468. // fold vector ops
  3469. if (VT.isVector()) {
  3470. if (SDValue FoldedVOp = SimplifyVBinOp(N, DL))
  3471. return FoldedVOp;
  3472. N1IsConst = ISD::isConstantSplatVector(N1.getNode(), ConstValue1);
  3473. assert((!N1IsConst ||
  3474. ConstValue1.getBitWidth() == VT.getScalarSizeInBits()) &&
  3475. "Splat APInt should be element width");
  3476. } else {
  3477. N1IsConst = isa<ConstantSDNode>(N1);
  3478. if (N1IsConst) {
  3479. ConstValue1 = cast<ConstantSDNode>(N1)->getAPIntValue();
  3480. N1IsOpaqueConst = cast<ConstantSDNode>(N1)->isOpaque();
  3481. }
  3482. }
  3483. // fold (mul x, 0) -> 0
  3484. if (N1IsConst && ConstValue1.isZero())
  3485. return N1;
  3486. // fold (mul x, 1) -> x
  3487. if (N1IsConst && ConstValue1.isOne())
  3488. return N0;
  3489. if (SDValue NewSel = foldBinOpIntoSelect(N))
  3490. return NewSel;
  3491. // fold (mul x, -1) -> 0-x
  3492. if (N1IsConst && ConstValue1.isAllOnes())
  3493. return DAG.getNegative(N0, DL, VT);
  3494. // fold (mul x, (1 << c)) -> x << c
  3495. if (isConstantOrConstantVector(N1, /*NoOpaques*/ true) &&
  3496. DAG.isKnownToBeAPowerOfTwo(N1) &&
  3497. (!VT.isVector() || Level <= AfterLegalizeVectorOps)) {
  3498. SDValue LogBase2 = BuildLogBase2(N1, DL);
  3499. EVT ShiftVT = getShiftAmountTy(N0.getValueType());
  3500. SDValue Trunc = DAG.getZExtOrTrunc(LogBase2, DL, ShiftVT);
  3501. return DAG.getNode(ISD::SHL, DL, VT, N0, Trunc);
  3502. }
  3503. // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
  3504. if (N1IsConst && !N1IsOpaqueConst && ConstValue1.isNegatedPowerOf2()) {
  3505. unsigned Log2Val = (-ConstValue1).logBase2();
  3506. // FIXME: If the input is something that is easily negated (e.g. a
  3507. // single-use add), we should put the negate there.
  3508. return DAG.getNode(ISD::SUB, DL, VT,
  3509. DAG.getConstant(0, DL, VT),
  3510. DAG.getNode(ISD::SHL, DL, VT, N0,
  3511. DAG.getConstant(Log2Val, DL,
  3512. getShiftAmountTy(N0.getValueType()))));
  3513. }
  3514. // Attempt to reuse an existing umul_lohi/smul_lohi node, but only if the
  3515. // hi result is in use in case we hit this mid-legalization.
  3516. for (unsigned LoHiOpc : {ISD::UMUL_LOHI, ISD::SMUL_LOHI}) {
  3517. if (!LegalOperations || TLI.isOperationLegalOrCustom(LoHiOpc, VT)) {
  3518. SDVTList LoHiVT = DAG.getVTList(VT, VT);
  3519. // TODO: Can we match commutable operands with getNodeIfExists?
  3520. if (SDNode *LoHi = DAG.getNodeIfExists(LoHiOpc, LoHiVT, {N0, N1}))
  3521. if (LoHi->hasAnyUseOfValue(1))
  3522. return SDValue(LoHi, 0);
  3523. if (SDNode *LoHi = DAG.getNodeIfExists(LoHiOpc, LoHiVT, {N1, N0}))
  3524. if (LoHi->hasAnyUseOfValue(1))
  3525. return SDValue(LoHi, 0);
  3526. }
  3527. }
  3528. // Try to transform:
  3529. // (1) multiply-by-(power-of-2 +/- 1) into shift and add/sub.
  3530. // mul x, (2^N + 1) --> add (shl x, N), x
  3531. // mul x, (2^N - 1) --> sub (shl x, N), x
  3532. // Examples: x * 33 --> (x << 5) + x
  3533. // x * 15 --> (x << 4) - x
  3534. // x * -33 --> -((x << 5) + x)
  3535. // x * -15 --> -((x << 4) - x) ; this reduces --> x - (x << 4)
  3536. // (2) multiply-by-(power-of-2 +/- power-of-2) into shifts and add/sub.
  3537. // mul x, (2^N + 2^M) --> (add (shl x, N), (shl x, M))
  3538. // mul x, (2^N - 2^M) --> (sub (shl x, N), (shl x, M))
  3539. // Examples: x * 0x8800 --> (x << 15) + (x << 11)
  3540. // x * 0xf800 --> (x << 16) - (x << 11)
  3541. // x * -0x8800 --> -((x << 15) + (x << 11))
  3542. // x * -0xf800 --> -((x << 16) - (x << 11)) ; (x << 11) - (x << 16)
  3543. if (N1IsConst && TLI.decomposeMulByConstant(*DAG.getContext(), VT, N1)) {
  3544. // TODO: We could handle more general decomposition of any constant by
  3545. // having the target set a limit on number of ops and making a
  3546. // callback to determine that sequence (similar to sqrt expansion).
  3547. unsigned MathOp = ISD::DELETED_NODE;
  3548. APInt MulC = ConstValue1.abs();
  3549. // The constant `2` should be treated as (2^0 + 1).
  3550. unsigned TZeros = MulC == 2 ? 0 : MulC.countTrailingZeros();
  3551. MulC.lshrInPlace(TZeros);
  3552. if ((MulC - 1).isPowerOf2())
  3553. MathOp = ISD::ADD;
  3554. else if ((MulC + 1).isPowerOf2())
  3555. MathOp = ISD::SUB;
  3556. if (MathOp != ISD::DELETED_NODE) {
  3557. unsigned ShAmt =
  3558. MathOp == ISD::ADD ? (MulC - 1).logBase2() : (MulC + 1).logBase2();
  3559. ShAmt += TZeros;
  3560. assert(ShAmt < VT.getScalarSizeInBits() &&
  3561. "multiply-by-constant generated out of bounds shift");
  3562. SDValue Shl =
  3563. DAG.getNode(ISD::SHL, DL, VT, N0, DAG.getConstant(ShAmt, DL, VT));
  3564. SDValue R =
  3565. TZeros ? DAG.getNode(MathOp, DL, VT, Shl,
  3566. DAG.getNode(ISD::SHL, DL, VT, N0,
  3567. DAG.getConstant(TZeros, DL, VT)))
  3568. : DAG.getNode(MathOp, DL, VT, Shl, N0);
  3569. if (ConstValue1.isNegative())
  3570. R = DAG.getNegative(R, DL, VT);
  3571. return R;
  3572. }
  3573. }
  3574. // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
  3575. if (N0.getOpcode() == ISD::SHL) {
  3576. SDValue N01 = N0.getOperand(1);
  3577. if (SDValue C3 = DAG.FoldConstantArithmetic(ISD::SHL, DL, VT, {N1, N01}))
  3578. return DAG.getNode(ISD::MUL, DL, VT, N0.getOperand(0), C3);
  3579. }
  3580. // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
  3581. // use.
  3582. {
  3583. SDValue Sh, Y;
  3584. // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)).
  3585. if (N0.getOpcode() == ISD::SHL &&
  3586. isConstantOrConstantVector(N0.getOperand(1)) && N0->hasOneUse()) {
  3587. Sh = N0; Y = N1;
  3588. } else if (N1.getOpcode() == ISD::SHL &&
  3589. isConstantOrConstantVector(N1.getOperand(1)) &&
  3590. N1->hasOneUse()) {
  3591. Sh = N1; Y = N0;
  3592. }
  3593. if (Sh.getNode()) {
  3594. SDValue Mul = DAG.getNode(ISD::MUL, DL, VT, Sh.getOperand(0), Y);
  3595. return DAG.getNode(ISD::SHL, DL, VT, Mul, Sh.getOperand(1));
  3596. }
  3597. }
  3598. // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
  3599. if (DAG.isConstantIntBuildVectorOrConstantInt(N1) &&
  3600. N0.getOpcode() == ISD::ADD &&
  3601. DAG.isConstantIntBuildVectorOrConstantInt(N0.getOperand(1)) &&
  3602. isMulAddWithConstProfitable(N, N0, N1))
  3603. return DAG.getNode(
  3604. ISD::ADD, DL, VT,
  3605. DAG.getNode(ISD::MUL, SDLoc(N0), VT, N0.getOperand(0), N1),
  3606. DAG.getNode(ISD::MUL, SDLoc(N1), VT, N0.getOperand(1), N1));
  3607. // Fold (mul (vscale * C0), C1) to (vscale * (C0 * C1)).
  3608. ConstantSDNode *NC1 = isConstOrConstSplat(N1);
  3609. if (N0.getOpcode() == ISD::VSCALE && NC1) {
  3610. const APInt &C0 = N0.getConstantOperandAPInt(0);
  3611. const APInt &C1 = NC1->getAPIntValue();
  3612. return DAG.getVScale(DL, VT, C0 * C1);
  3613. }
  3614. // Fold (mul step_vector(C0), C1) to (step_vector(C0 * C1)).
  3615. APInt MulVal;
  3616. if (N0.getOpcode() == ISD::STEP_VECTOR &&
  3617. ISD::isConstantSplatVector(N1.getNode(), MulVal)) {
  3618. const APInt &C0 = N0.getConstantOperandAPInt(0);
  3619. APInt NewStep = C0 * MulVal;
  3620. return DAG.getStepVector(DL, VT, NewStep);
  3621. }
  3622. // Fold ((mul x, 0/undef) -> 0,
  3623. // (mul x, 1) -> x) -> x)
  3624. // -> and(x, mask)
  3625. // We can replace vectors with '0' and '1' factors with a clearing mask.
  3626. if (VT.isFixedLengthVector()) {
  3627. unsigned NumElts = VT.getVectorNumElements();
  3628. SmallBitVector ClearMask;
  3629. ClearMask.reserve(NumElts);
  3630. auto IsClearMask = [&ClearMask](ConstantSDNode *V) {
  3631. if (!V || V->isZero()) {
  3632. ClearMask.push_back(true);
  3633. return true;
  3634. }
  3635. ClearMask.push_back(false);
  3636. return V->isOne();
  3637. };
  3638. if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::AND, VT)) &&
  3639. ISD::matchUnaryPredicate(N1, IsClearMask, /*AllowUndefs*/ true)) {
  3640. assert(N1.getOpcode() == ISD::BUILD_VECTOR && "Unknown constant vector");
  3641. EVT LegalSVT = N1.getOperand(0).getValueType();
  3642. SDValue Zero = DAG.getConstant(0, DL, LegalSVT);
  3643. SDValue AllOnes = DAG.getAllOnesConstant(DL, LegalSVT);
  3644. SmallVector<SDValue, 16> Mask(NumElts, AllOnes);
  3645. for (unsigned I = 0; I != NumElts; ++I)
  3646. if (ClearMask[I])
  3647. Mask[I] = Zero;
  3648. return DAG.getNode(ISD::AND, DL, VT, N0, DAG.getBuildVector(VT, DL, Mask));
  3649. }
  3650. }
  3651. // reassociate mul
  3652. if (SDValue RMUL = reassociateOps(ISD::MUL, DL, N0, N1, N->getFlags()))
  3653. return RMUL;
  3654. // Simplify the operands using demanded-bits information.
  3655. if (SimplifyDemandedBits(SDValue(N, 0)))
  3656. return SDValue(N, 0);
  3657. return SDValue();
  3658. }
  3659. /// Return true if divmod libcall is available.
  3660. static bool isDivRemLibcallAvailable(SDNode *Node, bool isSigned,
  3661. const TargetLowering &TLI) {
  3662. RTLIB::Libcall LC;
  3663. EVT NodeType = Node->getValueType(0);
  3664. if (!NodeType.isSimple())
  3665. return false;
  3666. switch (NodeType.getSimpleVT().SimpleTy) {
  3667. default: return false; // No libcall for vector types.
  3668. case MVT::i8: LC= isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break;
  3669. case MVT::i16: LC= isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
  3670. case MVT::i32: LC= isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
  3671. case MVT::i64: LC= isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
  3672. case MVT::i128: LC= isSigned ? RTLIB::SDIVREM_I128:RTLIB::UDIVREM_I128; break;
  3673. }
  3674. return TLI.getLibcallName(LC) != nullptr;
  3675. }
  3676. /// Issue divrem if both quotient and remainder are needed.
  3677. SDValue DAGCombiner::useDivRem(SDNode *Node) {
  3678. if (Node->use_empty())
  3679. return SDValue(); // This is a dead node, leave it alone.
  3680. unsigned Opcode = Node->getOpcode();
  3681. bool isSigned = (Opcode == ISD::SDIV) || (Opcode == ISD::SREM);
  3682. unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM;
  3683. // DivMod lib calls can still work on non-legal types if using lib-calls.
  3684. EVT VT = Node->getValueType(0);
  3685. if (VT.isVector() || !VT.isInteger())
  3686. return SDValue();
  3687. if (!TLI.isTypeLegal(VT) && !TLI.isOperationCustom(DivRemOpc, VT))
  3688. return SDValue();
  3689. // If DIVREM is going to get expanded into a libcall,
  3690. // but there is no libcall available, then don't combine.
  3691. if (!TLI.isOperationLegalOrCustom(DivRemOpc, VT) &&
  3692. !isDivRemLibcallAvailable(Node, isSigned, TLI))
  3693. return SDValue();
  3694. // If div is legal, it's better to do the normal expansion
  3695. unsigned OtherOpcode = 0;
  3696. if ((Opcode == ISD::SDIV) || (Opcode == ISD::UDIV)) {
  3697. OtherOpcode = isSigned ? ISD::SREM : ISD::UREM;
  3698. if (TLI.isOperationLegalOrCustom(Opcode, VT))
  3699. return SDValue();
  3700. } else {
  3701. OtherOpcode = isSigned ? ISD::SDIV : ISD::UDIV;
  3702. if (TLI.isOperationLegalOrCustom(OtherOpcode, VT))
  3703. return SDValue();
  3704. }
  3705. SDValue Op0 = Node->getOperand(0);
  3706. SDValue Op1 = Node->getOperand(1);
  3707. SDValue combined;
  3708. for (SDNode *User : Op0->uses()) {
  3709. if (User == Node || User->getOpcode() == ISD::DELETED_NODE ||
  3710. User->use_empty())
  3711. continue;
  3712. // Convert the other matching node(s), too;
  3713. // otherwise, the DIVREM may get target-legalized into something
  3714. // target-specific that we won't be able to recognize.
  3715. unsigned UserOpc = User->getOpcode();
  3716. if ((UserOpc == Opcode || UserOpc == OtherOpcode || UserOpc == DivRemOpc) &&
  3717. User->getOperand(0) == Op0 &&
  3718. User->getOperand(1) == Op1) {
  3719. if (!combined) {
  3720. if (UserOpc == OtherOpcode) {
  3721. SDVTList VTs = DAG.getVTList(VT, VT);
  3722. combined = DAG.getNode(DivRemOpc, SDLoc(Node), VTs, Op0, Op1);
  3723. } else if (UserOpc == DivRemOpc) {
  3724. combined = SDValue(User, 0);
  3725. } else {
  3726. assert(UserOpc == Opcode);
  3727. continue;
  3728. }
  3729. }
  3730. if (UserOpc == ISD::SDIV || UserOpc == ISD::UDIV)
  3731. CombineTo(User, combined);
  3732. else if (UserOpc == ISD::SREM || UserOpc == ISD::UREM)
  3733. CombineTo(User, combined.getValue(1));
  3734. }
  3735. }
  3736. return combined;
  3737. }
  3738. static SDValue simplifyDivRem(SDNode *N, SelectionDAG &DAG) {
  3739. SDValue N0 = N->getOperand(0);
  3740. SDValue N1 = N->getOperand(1);
  3741. EVT VT = N->getValueType(0);
  3742. SDLoc DL(N);
  3743. unsigned Opc = N->getOpcode();
  3744. bool IsDiv = (ISD::SDIV == Opc) || (ISD::UDIV == Opc);
  3745. ConstantSDNode *N1C = isConstOrConstSplat(N1);
  3746. // X / undef -> undef
  3747. // X % undef -> undef
  3748. // X / 0 -> undef
  3749. // X % 0 -> undef
  3750. // NOTE: This includes vectors where any divisor element is zero/undef.
  3751. if (DAG.isUndef(Opc, {N0, N1}))
  3752. return DAG.getUNDEF(VT);
  3753. // undef / X -> 0
  3754. // undef % X -> 0
  3755. if (N0.isUndef())
  3756. return DAG.getConstant(0, DL, VT);
  3757. // 0 / X -> 0
  3758. // 0 % X -> 0
  3759. ConstantSDNode *N0C = isConstOrConstSplat(N0);
  3760. if (N0C && N0C->isZero())
  3761. return N0;
  3762. // X / X -> 1
  3763. // X % X -> 0
  3764. if (N0 == N1)
  3765. return DAG.getConstant(IsDiv ? 1 : 0, DL, VT);
  3766. // X / 1 -> X
  3767. // X % 1 -> 0
  3768. // If this is a boolean op (single-bit element type), we can't have
  3769. // division-by-zero or remainder-by-zero, so assume the divisor is 1.
  3770. // TODO: Similarly, if we're zero-extending a boolean divisor, then assume
  3771. // it's a 1.
  3772. if ((N1C && N1C->isOne()) || (VT.getScalarType() == MVT::i1))
  3773. return IsDiv ? N0 : DAG.getConstant(0, DL, VT);
  3774. return SDValue();
  3775. }
  3776. SDValue DAGCombiner::visitSDIV(SDNode *N) {
  3777. SDValue N0 = N->getOperand(0);
  3778. SDValue N1 = N->getOperand(1);
  3779. EVT VT = N->getValueType(0);
  3780. EVT CCVT = getSetCCResultType(VT);
  3781. SDLoc DL(N);
  3782. // fold (sdiv c1, c2) -> c1/c2
  3783. if (SDValue C = DAG.FoldConstantArithmetic(ISD::SDIV, DL, VT, {N0, N1}))
  3784. return C;
  3785. // fold vector ops
  3786. if (VT.isVector())
  3787. if (SDValue FoldedVOp = SimplifyVBinOp(N, DL))
  3788. return FoldedVOp;
  3789. // fold (sdiv X, -1) -> 0-X
  3790. ConstantSDNode *N1C = isConstOrConstSplat(N1);
  3791. if (N1C && N1C->isAllOnes())
  3792. return DAG.getNegative(N0, DL, VT);
  3793. // fold (sdiv X, MIN_SIGNED) -> select(X == MIN_SIGNED, 1, 0)
  3794. if (N1C && N1C->getAPIntValue().isMinSignedValue())
  3795. return DAG.getSelect(DL, VT, DAG.getSetCC(DL, CCVT, N0, N1, ISD::SETEQ),
  3796. DAG.getConstant(1, DL, VT),
  3797. DAG.getConstant(0, DL, VT));
  3798. if (SDValue V = simplifyDivRem(N, DAG))
  3799. return V;
  3800. if (SDValue NewSel = foldBinOpIntoSelect(N))
  3801. return NewSel;
  3802. // If we know the sign bits of both operands are zero, strength reduce to a
  3803. // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2
  3804. if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
  3805. return DAG.getNode(ISD::UDIV, DL, N1.getValueType(), N0, N1);
  3806. if (SDValue V = visitSDIVLike(N0, N1, N)) {
  3807. // If the corresponding remainder node exists, update its users with
  3808. // (Dividend - (Quotient * Divisor).
  3809. if (SDNode *RemNode = DAG.getNodeIfExists(ISD::SREM, N->getVTList(),
  3810. { N0, N1 })) {
  3811. SDValue Mul = DAG.getNode(ISD::MUL, DL, VT, V, N1);
  3812. SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N0, Mul);
  3813. AddToWorklist(Mul.getNode());
  3814. AddToWorklist(Sub.getNode());
  3815. CombineTo(RemNode, Sub);
  3816. }
  3817. return V;
  3818. }
  3819. // sdiv, srem -> sdivrem
  3820. // If the divisor is constant, then return DIVREM only if isIntDivCheap() is
  3821. // true. Otherwise, we break the simplification logic in visitREM().
  3822. AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
  3823. if (!N1C || TLI.isIntDivCheap(N->getValueType(0), Attr))
  3824. if (SDValue DivRem = useDivRem(N))
  3825. return DivRem;
  3826. return SDValue();
  3827. }
  3828. static bool isDivisorPowerOfTwo(SDValue Divisor) {
  3829. // Helper for determining whether a value is a power-2 constant scalar or a
  3830. // vector of such elements.
  3831. auto IsPowerOfTwo = [](ConstantSDNode *C) {
  3832. if (C->isZero() || C->isOpaque())
  3833. return false;
  3834. if (C->getAPIntValue().isPowerOf2())
  3835. return true;
  3836. if (C->getAPIntValue().isNegatedPowerOf2())
  3837. return true;
  3838. return false;
  3839. };
  3840. return ISD::matchUnaryPredicate(Divisor, IsPowerOfTwo);
  3841. }
  3842. SDValue DAGCombiner::visitSDIVLike(SDValue N0, SDValue N1, SDNode *N) {
  3843. SDLoc DL(N);
  3844. EVT VT = N->getValueType(0);
  3845. EVT CCVT = getSetCCResultType(VT);
  3846. unsigned BitWidth = VT.getScalarSizeInBits();
  3847. // fold (sdiv X, pow2) -> simple ops after legalize
  3848. // FIXME: We check for the exact bit here because the generic lowering gives
  3849. // better results in that case. The target-specific lowering should learn how
  3850. // to handle exact sdivs efficiently.
  3851. if (!N->getFlags().hasExact() && isDivisorPowerOfTwo(N1)) {
  3852. // Target-specific implementation of sdiv x, pow2.
  3853. if (SDValue Res = BuildSDIVPow2(N))
  3854. return Res;
  3855. // Create constants that are functions of the shift amount value.
  3856. EVT ShiftAmtTy = getShiftAmountTy(N0.getValueType());
  3857. SDValue Bits = DAG.getConstant(BitWidth, DL, ShiftAmtTy);
  3858. SDValue C1 = DAG.getNode(ISD::CTTZ, DL, VT, N1);
  3859. C1 = DAG.getZExtOrTrunc(C1, DL, ShiftAmtTy);
  3860. SDValue Inexact = DAG.getNode(ISD::SUB, DL, ShiftAmtTy, Bits, C1);
  3861. if (!isConstantOrConstantVector(Inexact))
  3862. return SDValue();
  3863. // Splat the sign bit into the register
  3864. SDValue Sign = DAG.getNode(ISD::SRA, DL, VT, N0,
  3865. DAG.getConstant(BitWidth - 1, DL, ShiftAmtTy));
  3866. AddToWorklist(Sign.getNode());
  3867. // Add (N0 < 0) ? abs2 - 1 : 0;
  3868. SDValue Srl = DAG.getNode(ISD::SRL, DL, VT, Sign, Inexact);
  3869. AddToWorklist(Srl.getNode());
  3870. SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Srl);
  3871. AddToWorklist(Add.getNode());
  3872. SDValue Sra = DAG.getNode(ISD::SRA, DL, VT, Add, C1);
  3873. AddToWorklist(Sra.getNode());
  3874. // Special case: (sdiv X, 1) -> X
  3875. // Special Case: (sdiv X, -1) -> 0-X
  3876. SDValue One = DAG.getConstant(1, DL, VT);
  3877. SDValue AllOnes = DAG.getAllOnesConstant(DL, VT);
  3878. SDValue IsOne = DAG.getSetCC(DL, CCVT, N1, One, ISD::SETEQ);
  3879. SDValue IsAllOnes = DAG.getSetCC(DL, CCVT, N1, AllOnes, ISD::SETEQ);
  3880. SDValue IsOneOrAllOnes = DAG.getNode(ISD::OR, DL, CCVT, IsOne, IsAllOnes);
  3881. Sra = DAG.getSelect(DL, VT, IsOneOrAllOnes, N0, Sra);
  3882. // If dividing by a positive value, we're done. Otherwise, the result must
  3883. // be negated.
  3884. SDValue Zero = DAG.getConstant(0, DL, VT);
  3885. SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, Zero, Sra);
  3886. // FIXME: Use SELECT_CC once we improve SELECT_CC constant-folding.
  3887. SDValue IsNeg = DAG.getSetCC(DL, CCVT, N1, Zero, ISD::SETLT);
  3888. SDValue Res = DAG.getSelect(DL, VT, IsNeg, Sub, Sra);
  3889. return Res;
  3890. }
  3891. // If integer divide is expensive and we satisfy the requirements, emit an
  3892. // alternate sequence. Targets may check function attributes for size/speed
  3893. // trade-offs.
  3894. AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
  3895. if (isConstantOrConstantVector(N1) &&
  3896. !TLI.isIntDivCheap(N->getValueType(0), Attr))
  3897. if (SDValue Op = BuildSDIV(N))
  3898. return Op;
  3899. return SDValue();
  3900. }
  3901. SDValue DAGCombiner::visitUDIV(SDNode *N) {
  3902. SDValue N0 = N->getOperand(0);
  3903. SDValue N1 = N->getOperand(1);
  3904. EVT VT = N->getValueType(0);
  3905. EVT CCVT = getSetCCResultType(VT);
  3906. SDLoc DL(N);
  3907. // fold (udiv c1, c2) -> c1/c2
  3908. if (SDValue C = DAG.FoldConstantArithmetic(ISD::UDIV, DL, VT, {N0, N1}))
  3909. return C;
  3910. // fold vector ops
  3911. if (VT.isVector())
  3912. if (SDValue FoldedVOp = SimplifyVBinOp(N, DL))
  3913. return FoldedVOp;
  3914. // fold (udiv X, -1) -> select(X == -1, 1, 0)
  3915. ConstantSDNode *N1C = isConstOrConstSplat(N1);
  3916. if (N1C && N1C->isAllOnes() && CCVT.isVector() == VT.isVector()) {
  3917. return DAG.getSelect(DL, VT, DAG.getSetCC(DL, CCVT, N0, N1, ISD::SETEQ),
  3918. DAG.getConstant(1, DL, VT),
  3919. DAG.getConstant(0, DL, VT));
  3920. }
  3921. if (SDValue V = simplifyDivRem(N, DAG))
  3922. return V;
  3923. if (SDValue NewSel = foldBinOpIntoSelect(N))
  3924. return NewSel;
  3925. if (SDValue V = visitUDIVLike(N0, N1, N)) {
  3926. // If the corresponding remainder node exists, update its users with
  3927. // (Dividend - (Quotient * Divisor).
  3928. if (SDNode *RemNode = DAG.getNodeIfExists(ISD::UREM, N->getVTList(),
  3929. { N0, N1 })) {
  3930. SDValue Mul = DAG.getNode(ISD::MUL, DL, VT, V, N1);
  3931. SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N0, Mul);
  3932. AddToWorklist(Mul.getNode());
  3933. AddToWorklist(Sub.getNode());
  3934. CombineTo(RemNode, Sub);
  3935. }
  3936. return V;
  3937. }
  3938. // sdiv, srem -> sdivrem
  3939. // If the divisor is constant, then return DIVREM only if isIntDivCheap() is
  3940. // true. Otherwise, we break the simplification logic in visitREM().
  3941. AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
  3942. if (!N1C || TLI.isIntDivCheap(N->getValueType(0), Attr))
  3943. if (SDValue DivRem = useDivRem(N))
  3944. return DivRem;
  3945. return SDValue();
  3946. }
  3947. SDValue DAGCombiner::visitUDIVLike(SDValue N0, SDValue N1, SDNode *N) {
  3948. SDLoc DL(N);
  3949. EVT VT = N->getValueType(0);
  3950. // fold (udiv x, (1 << c)) -> x >>u c
  3951. if (isConstantOrConstantVector(N1, /*NoOpaques*/ true) &&
  3952. DAG.isKnownToBeAPowerOfTwo(N1)) {
  3953. SDValue LogBase2 = BuildLogBase2(N1, DL);
  3954. AddToWorklist(LogBase2.getNode());
  3955. EVT ShiftVT = getShiftAmountTy(N0.getValueType());
  3956. SDValue Trunc = DAG.getZExtOrTrunc(LogBase2, DL, ShiftVT);
  3957. AddToWorklist(Trunc.getNode());
  3958. return DAG.getNode(ISD::SRL, DL, VT, N0, Trunc);
  3959. }
  3960. // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
  3961. if (N1.getOpcode() == ISD::SHL) {
  3962. SDValue N10 = N1.getOperand(0);
  3963. if (isConstantOrConstantVector(N10, /*NoOpaques*/ true) &&
  3964. DAG.isKnownToBeAPowerOfTwo(N10)) {
  3965. SDValue LogBase2 = BuildLogBase2(N10, DL);
  3966. AddToWorklist(LogBase2.getNode());
  3967. EVT ADDVT = N1.getOperand(1).getValueType();
  3968. SDValue Trunc = DAG.getZExtOrTrunc(LogBase2, DL, ADDVT);
  3969. AddToWorklist(Trunc.getNode());
  3970. SDValue Add = DAG.getNode(ISD::ADD, DL, ADDVT, N1.getOperand(1), Trunc);
  3971. AddToWorklist(Add.getNode());
  3972. return DAG.getNode(ISD::SRL, DL, VT, N0, Add);
  3973. }
  3974. }
  3975. // fold (udiv x, c) -> alternate
  3976. AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
  3977. if (isConstantOrConstantVector(N1) &&
  3978. !TLI.isIntDivCheap(N->getValueType(0), Attr))
  3979. if (SDValue Op = BuildUDIV(N))
  3980. return Op;
  3981. return SDValue();
  3982. }
  3983. SDValue DAGCombiner::buildOptimizedSREM(SDValue N0, SDValue N1, SDNode *N) {
  3984. if (!N->getFlags().hasExact() && isDivisorPowerOfTwo(N1) &&
  3985. !DAG.doesNodeExist(ISD::SDIV, N->getVTList(), {N0, N1})) {
  3986. // Target-specific implementation of srem x, pow2.
  3987. if (SDValue Res = BuildSREMPow2(N))
  3988. return Res;
  3989. }
  3990. return SDValue();
  3991. }
  3992. // handles ISD::SREM and ISD::UREM
  3993. SDValue DAGCombiner::visitREM(SDNode *N) {
  3994. unsigned Opcode = N->getOpcode();
  3995. SDValue N0 = N->getOperand(0);
  3996. SDValue N1 = N->getOperand(1);
  3997. EVT VT = N->getValueType(0);
  3998. EVT CCVT = getSetCCResultType(VT);
  3999. bool isSigned = (Opcode == ISD::SREM);
  4000. SDLoc DL(N);
  4001. // fold (rem c1, c2) -> c1%c2
  4002. if (SDValue C = DAG.FoldConstantArithmetic(Opcode, DL, VT, {N0, N1}))
  4003. return C;
  4004. // fold (urem X, -1) -> select(FX == -1, 0, FX)
  4005. // Freeze the numerator to avoid a miscompile with an undefined value.
  4006. if (!isSigned && llvm::isAllOnesOrAllOnesSplat(N1, /*AllowUndefs*/ false) &&
  4007. CCVT.isVector() == VT.isVector()) {
  4008. SDValue F0 = DAG.getFreeze(N0);
  4009. SDValue EqualsNeg1 = DAG.getSetCC(DL, CCVT, F0, N1, ISD::SETEQ);
  4010. return DAG.getSelect(DL, VT, EqualsNeg1, DAG.getConstant(0, DL, VT), F0);
  4011. }
  4012. if (SDValue V = simplifyDivRem(N, DAG))
  4013. return V;
  4014. if (SDValue NewSel = foldBinOpIntoSelect(N))
  4015. return NewSel;
  4016. if (isSigned) {
  4017. // If we know the sign bits of both operands are zero, strength reduce to a
  4018. // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15
  4019. if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
  4020. return DAG.getNode(ISD::UREM, DL, VT, N0, N1);
  4021. } else {
  4022. if (DAG.isKnownToBeAPowerOfTwo(N1)) {
  4023. // fold (urem x, pow2) -> (and x, pow2-1)
  4024. SDValue NegOne = DAG.getAllOnesConstant(DL, VT);
  4025. SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N1, NegOne);
  4026. AddToWorklist(Add.getNode());
  4027. return DAG.getNode(ISD::AND, DL, VT, N0, Add);
  4028. }
  4029. // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
  4030. // fold (urem x, (lshr pow2, y)) -> (and x, (add (lshr pow2, y), -1))
  4031. // TODO: We should sink the following into isKnownToBePowerOfTwo
  4032. // using a OrZero parameter analogous to our handling in ValueTracking.
  4033. if ((N1.getOpcode() == ISD::SHL || N1.getOpcode() == ISD::SRL) &&
  4034. DAG.isKnownToBeAPowerOfTwo(N1.getOperand(0))) {
  4035. SDValue NegOne = DAG.getAllOnesConstant(DL, VT);
  4036. SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N1, NegOne);
  4037. AddToWorklist(Add.getNode());
  4038. return DAG.getNode(ISD::AND, DL, VT, N0, Add);
  4039. }
  4040. }
  4041. AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
  4042. // If X/C can be simplified by the division-by-constant logic, lower
  4043. // X%C to the equivalent of X-X/C*C.
  4044. // Reuse the SDIVLike/UDIVLike combines - to avoid mangling nodes, the
  4045. // speculative DIV must not cause a DIVREM conversion. We guard against this
  4046. // by skipping the simplification if isIntDivCheap(). When div is not cheap,
  4047. // combine will not return a DIVREM. Regardless, checking cheapness here
  4048. // makes sense since the simplification results in fatter code.
  4049. if (DAG.isKnownNeverZero(N1) && !TLI.isIntDivCheap(VT, Attr)) {
  4050. if (isSigned) {
  4051. // check if we can build faster implementation for srem
  4052. if (SDValue OptimizedRem = buildOptimizedSREM(N0, N1, N))
  4053. return OptimizedRem;
  4054. }
  4055. SDValue OptimizedDiv =
  4056. isSigned ? visitSDIVLike(N0, N1, N) : visitUDIVLike(N0, N1, N);
  4057. if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != N) {
  4058. // If the equivalent Div node also exists, update its users.
  4059. unsigned DivOpcode = isSigned ? ISD::SDIV : ISD::UDIV;
  4060. if (SDNode *DivNode = DAG.getNodeIfExists(DivOpcode, N->getVTList(),
  4061. { N0, N1 }))
  4062. CombineTo(DivNode, OptimizedDiv);
  4063. SDValue Mul = DAG.getNode(ISD::MUL, DL, VT, OptimizedDiv, N1);
  4064. SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N0, Mul);
  4065. AddToWorklist(OptimizedDiv.getNode());
  4066. AddToWorklist(Mul.getNode());
  4067. return Sub;
  4068. }
  4069. }
  4070. // sdiv, srem -> sdivrem
  4071. if (SDValue DivRem = useDivRem(N))
  4072. return DivRem.getValue(1);
  4073. return SDValue();
  4074. }
  4075. SDValue DAGCombiner::visitMULHS(SDNode *N) {
  4076. SDValue N0 = N->getOperand(0);
  4077. SDValue N1 = N->getOperand(1);
  4078. EVT VT = N->getValueType(0);
  4079. SDLoc DL(N);
  4080. // fold (mulhs c1, c2)
  4081. if (SDValue C = DAG.FoldConstantArithmetic(ISD::MULHS, DL, VT, {N0, N1}))
  4082. return C;
  4083. // canonicalize constant to RHS.
  4084. if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
  4085. !DAG.isConstantIntBuildVectorOrConstantInt(N1))
  4086. return DAG.getNode(ISD::MULHS, DL, N->getVTList(), N1, N0);
  4087. if (VT.isVector()) {
  4088. if (SDValue FoldedVOp = SimplifyVBinOp(N, DL))
  4089. return FoldedVOp;
  4090. // fold (mulhs x, 0) -> 0
  4091. // do not return N1, because undef node may exist.
  4092. if (ISD::isConstantSplatVectorAllZeros(N1.getNode()))
  4093. return DAG.getConstant(0, DL, VT);
  4094. }
  4095. // fold (mulhs x, 0) -> 0
  4096. if (isNullConstant(N1))
  4097. return N1;
  4098. // fold (mulhs x, 1) -> (sra x, size(x)-1)
  4099. if (isOneConstant(N1))
  4100. return DAG.getNode(ISD::SRA, DL, N0.getValueType(), N0,
  4101. DAG.getConstant(N0.getScalarValueSizeInBits() - 1, DL,
  4102. getShiftAmountTy(N0.getValueType())));
  4103. // fold (mulhs x, undef) -> 0
  4104. if (N0.isUndef() || N1.isUndef())
  4105. return DAG.getConstant(0, DL, VT);
  4106. // If the type twice as wide is legal, transform the mulhs to a wider multiply
  4107. // plus a shift.
  4108. if (!TLI.isOperationLegalOrCustom(ISD::MULHS, VT) && VT.isSimple() &&
  4109. !VT.isVector()) {
  4110. MVT Simple = VT.getSimpleVT();
  4111. unsigned SimpleSize = Simple.getSizeInBits();
  4112. EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
  4113. if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
  4114. N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
  4115. N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
  4116. N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
  4117. N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
  4118. DAG.getConstant(SimpleSize, DL,
  4119. getShiftAmountTy(N1.getValueType())));
  4120. return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
  4121. }
  4122. }
  4123. return SDValue();
  4124. }
  4125. SDValue DAGCombiner::visitMULHU(SDNode *N) {
  4126. SDValue N0 = N->getOperand(0);
  4127. SDValue N1 = N->getOperand(1);
  4128. EVT VT = N->getValueType(0);
  4129. SDLoc DL(N);
  4130. // fold (mulhu c1, c2)
  4131. if (SDValue C = DAG.FoldConstantArithmetic(ISD::MULHU, DL, VT, {N0, N1}))
  4132. return C;
  4133. // canonicalize constant to RHS.
  4134. if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
  4135. !DAG.isConstantIntBuildVectorOrConstantInt(N1))
  4136. return DAG.getNode(ISD::MULHU, DL, N->getVTList(), N1, N0);
  4137. if (VT.isVector()) {
  4138. if (SDValue FoldedVOp = SimplifyVBinOp(N, DL))
  4139. return FoldedVOp;
  4140. // fold (mulhu x, 0) -> 0
  4141. // do not return N1, because undef node may exist.
  4142. if (ISD::isConstantSplatVectorAllZeros(N1.getNode()))
  4143. return DAG.getConstant(0, DL, VT);
  4144. }
  4145. // fold (mulhu x, 0) -> 0
  4146. if (isNullConstant(N1))
  4147. return N1;
  4148. // fold (mulhu x, 1) -> 0
  4149. if (isOneConstant(N1))
  4150. return DAG.getConstant(0, DL, N0.getValueType());
  4151. // fold (mulhu x, undef) -> 0
  4152. if (N0.isUndef() || N1.isUndef())
  4153. return DAG.getConstant(0, DL, VT);
  4154. // fold (mulhu x, (1 << c)) -> x >> (bitwidth - c)
  4155. if (isConstantOrConstantVector(N1, /*NoOpaques*/ true) &&
  4156. DAG.isKnownToBeAPowerOfTwo(N1) && hasOperation(ISD::SRL, VT)) {
  4157. unsigned NumEltBits = VT.getScalarSizeInBits();
  4158. SDValue LogBase2 = BuildLogBase2(N1, DL);
  4159. SDValue SRLAmt = DAG.getNode(
  4160. ISD::SUB, DL, VT, DAG.getConstant(NumEltBits, DL, VT), LogBase2);
  4161. EVT ShiftVT = getShiftAmountTy(N0.getValueType());
  4162. SDValue Trunc = DAG.getZExtOrTrunc(SRLAmt, DL, ShiftVT);
  4163. return DAG.getNode(ISD::SRL, DL, VT, N0, Trunc);
  4164. }
  4165. // If the type twice as wide is legal, transform the mulhu to a wider multiply
  4166. // plus a shift.
  4167. if (!TLI.isOperationLegalOrCustom(ISD::MULHU, VT) && VT.isSimple() &&
  4168. !VT.isVector()) {
  4169. MVT Simple = VT.getSimpleVT();
  4170. unsigned SimpleSize = Simple.getSizeInBits();
  4171. EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
  4172. if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
  4173. N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
  4174. N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
  4175. N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
  4176. N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
  4177. DAG.getConstant(SimpleSize, DL,
  4178. getShiftAmountTy(N1.getValueType())));
  4179. return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
  4180. }
  4181. }
  4182. // Simplify the operands using demanded-bits information.
  4183. // We don't have demanded bits support for MULHU so this just enables constant
  4184. // folding based on known bits.
  4185. if (SimplifyDemandedBits(SDValue(N, 0)))
  4186. return SDValue(N, 0);
  4187. return SDValue();
  4188. }
  4189. SDValue DAGCombiner::visitAVG(SDNode *N) {
  4190. unsigned Opcode = N->getOpcode();
  4191. SDValue N0 = N->getOperand(0);
  4192. SDValue N1 = N->getOperand(1);
  4193. EVT VT = N->getValueType(0);
  4194. SDLoc DL(N);
  4195. // fold (avg c1, c2)
  4196. if (SDValue C = DAG.FoldConstantArithmetic(Opcode, DL, VT, {N0, N1}))
  4197. return C;
  4198. // canonicalize constant to RHS.
  4199. if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
  4200. !DAG.isConstantIntBuildVectorOrConstantInt(N1))
  4201. return DAG.getNode(Opcode, DL, N->getVTList(), N1, N0);
  4202. if (VT.isVector()) {
  4203. if (SDValue FoldedVOp = SimplifyVBinOp(N, DL))
  4204. return FoldedVOp;
  4205. // fold (avgfloor x, 0) -> x >> 1
  4206. if (ISD::isConstantSplatVectorAllZeros(N1.getNode())) {
  4207. if (Opcode == ISD::AVGFLOORS)
  4208. return DAG.getNode(ISD::SRA, DL, VT, N0, DAG.getConstant(1, DL, VT));
  4209. if (Opcode == ISD::AVGFLOORU)
  4210. return DAG.getNode(ISD::SRL, DL, VT, N0, DAG.getConstant(1, DL, VT));
  4211. }
  4212. }
  4213. // fold (avg x, undef) -> x
  4214. if (N0.isUndef())
  4215. return N1;
  4216. if (N1.isUndef())
  4217. return N0;
  4218. // TODO If we use avg for scalars anywhere, we can add (avgfl x, 0) -> x >> 1
  4219. return SDValue();
  4220. }
  4221. /// Perform optimizations common to nodes that compute two values. LoOp and HiOp
  4222. /// give the opcodes for the two computations that are being performed. Return
  4223. /// true if a simplification was made.
  4224. SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
  4225. unsigned HiOp) {
  4226. // If the high half is not needed, just compute the low half.
  4227. bool HiExists = N->hasAnyUseOfValue(1);
  4228. if (!HiExists && (!LegalOperations ||
  4229. TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
  4230. SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
  4231. return CombineTo(N, Res, Res);
  4232. }
  4233. // If the low half is not needed, just compute the high half.
  4234. bool LoExists = N->hasAnyUseOfValue(0);
  4235. if (!LoExists && (!LegalOperations ||
  4236. TLI.isOperationLegalOrCustom(HiOp, N->getValueType(1)))) {
  4237. SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
  4238. return CombineTo(N, Res, Res);
  4239. }
  4240. // If both halves are used, return as it is.
  4241. if (LoExists && HiExists)
  4242. return SDValue();
  4243. // If the two computed results can be simplified separately, separate them.
  4244. if (LoExists) {
  4245. SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
  4246. AddToWorklist(Lo.getNode());
  4247. SDValue LoOpt = combine(Lo.getNode());
  4248. if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
  4249. (!LegalOperations ||
  4250. TLI.isOperationLegalOrCustom(LoOpt.getOpcode(), LoOpt.getValueType())))
  4251. return CombineTo(N, LoOpt, LoOpt);
  4252. }
  4253. if (HiExists) {
  4254. SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
  4255. AddToWorklist(Hi.getNode());
  4256. SDValue HiOpt = combine(Hi.getNode());
  4257. if (HiOpt.getNode() && HiOpt != Hi &&
  4258. (!LegalOperations ||
  4259. TLI.isOperationLegalOrCustom(HiOpt.getOpcode(), HiOpt.getValueType())))
  4260. return CombineTo(N, HiOpt, HiOpt);
  4261. }
  4262. return SDValue();
  4263. }
  4264. SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
  4265. if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS))
  4266. return Res;
  4267. SDValue N0 = N->getOperand(0);
  4268. SDValue N1 = N->getOperand(1);
  4269. EVT VT = N->getValueType(0);
  4270. SDLoc DL(N);
  4271. // canonicalize constant to RHS (vector doesn't have to splat)
  4272. if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
  4273. !DAG.isConstantIntBuildVectorOrConstantInt(N1))
  4274. return DAG.getNode(ISD::SMUL_LOHI, DL, N->getVTList(), N1, N0);
  4275. // If the type is twice as wide is legal, transform the mulhu to a wider
  4276. // multiply plus a shift.
  4277. if (VT.isSimple() && !VT.isVector()) {
  4278. MVT Simple = VT.getSimpleVT();
  4279. unsigned SimpleSize = Simple.getSizeInBits();
  4280. EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
  4281. if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
  4282. SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
  4283. SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
  4284. Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
  4285. // Compute the high part as N1.
  4286. Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
  4287. DAG.getConstant(SimpleSize, DL,
  4288. getShiftAmountTy(Lo.getValueType())));
  4289. Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
  4290. // Compute the low part as N0.
  4291. Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
  4292. return CombineTo(N, Lo, Hi);
  4293. }
  4294. }
  4295. return SDValue();
  4296. }
  4297. SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
  4298. if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU))
  4299. return Res;
  4300. SDValue N0 = N->getOperand(0);
  4301. SDValue N1 = N->getOperand(1);
  4302. EVT VT = N->getValueType(0);
  4303. SDLoc DL(N);
  4304. // canonicalize constant to RHS (vector doesn't have to splat)
  4305. if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
  4306. !DAG.isConstantIntBuildVectorOrConstantInt(N1))
  4307. return DAG.getNode(ISD::UMUL_LOHI, DL, N->getVTList(), N1, N0);
  4308. // (umul_lohi N0, 0) -> (0, 0)
  4309. if (isNullConstant(N1)) {
  4310. SDValue Zero = DAG.getConstant(0, DL, VT);
  4311. return CombineTo(N, Zero, Zero);
  4312. }
  4313. // (umul_lohi N0, 1) -> (N0, 0)
  4314. if (isOneConstant(N1)) {
  4315. SDValue Zero = DAG.getConstant(0, DL, VT);
  4316. return CombineTo(N, N0, Zero);
  4317. }
  4318. // If the type is twice as wide is legal, transform the mulhu to a wider
  4319. // multiply plus a shift.
  4320. if (VT.isSimple() && !VT.isVector()) {
  4321. MVT Simple = VT.getSimpleVT();
  4322. unsigned SimpleSize = Simple.getSizeInBits();
  4323. EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
  4324. if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
  4325. SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
  4326. SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
  4327. Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
  4328. // Compute the high part as N1.
  4329. Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
  4330. DAG.getConstant(SimpleSize, DL,
  4331. getShiftAmountTy(Lo.getValueType())));
  4332. Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
  4333. // Compute the low part as N0.
  4334. Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
  4335. return CombineTo(N, Lo, Hi);
  4336. }
  4337. }
  4338. return SDValue();
  4339. }
  4340. SDValue DAGCombiner::visitMULO(SDNode *N) {
  4341. SDValue N0 = N->getOperand(0);
  4342. SDValue N1 = N->getOperand(1);
  4343. EVT VT = N0.getValueType();
  4344. bool IsSigned = (ISD::SMULO == N->getOpcode());
  4345. EVT CarryVT = N->getValueType(1);
  4346. SDLoc DL(N);
  4347. ConstantSDNode *N0C = isConstOrConstSplat(N0);
  4348. ConstantSDNode *N1C = isConstOrConstSplat(N1);
  4349. // fold operation with constant operands.
  4350. // TODO: Move this to FoldConstantArithmetic when it supports nodes with
  4351. // multiple results.
  4352. if (N0C && N1C) {
  4353. bool Overflow;
  4354. APInt Result =
  4355. IsSigned ? N0C->getAPIntValue().smul_ov(N1C->getAPIntValue(), Overflow)
  4356. : N0C->getAPIntValue().umul_ov(N1C->getAPIntValue(), Overflow);
  4357. return CombineTo(N, DAG.getConstant(Result, DL, VT),
  4358. DAG.getBoolConstant(Overflow, DL, CarryVT, CarryVT));
  4359. }
  4360. // canonicalize constant to RHS.
  4361. if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
  4362. !DAG.isConstantIntBuildVectorOrConstantInt(N1))
  4363. return DAG.getNode(N->getOpcode(), DL, N->getVTList(), N1, N0);
  4364. // fold (mulo x, 0) -> 0 + no carry out
  4365. if (isNullOrNullSplat(N1))
  4366. return CombineTo(N, DAG.getConstant(0, DL, VT),
  4367. DAG.getConstant(0, DL, CarryVT));
  4368. // (mulo x, 2) -> (addo x, x)
  4369. // FIXME: This needs a freeze.
  4370. if (N1C && N1C->getAPIntValue() == 2 &&
  4371. (!IsSigned || VT.getScalarSizeInBits() > 2))
  4372. return DAG.getNode(IsSigned ? ISD::SADDO : ISD::UADDO, DL,
  4373. N->getVTList(), N0, N0);
  4374. if (IsSigned) {
  4375. // A 1 bit SMULO overflows if both inputs are 1.
  4376. if (VT.getScalarSizeInBits() == 1) {
  4377. SDValue And = DAG.getNode(ISD::AND, DL, VT, N0, N1);
  4378. return CombineTo(N, And,
  4379. DAG.getSetCC(DL, CarryVT, And,
  4380. DAG.getConstant(0, DL, VT), ISD::SETNE));
  4381. }
  4382. // Multiplying n * m significant bits yields a result of n + m significant
  4383. // bits. If the total number of significant bits does not exceed the
  4384. // result bit width (minus 1), there is no overflow.
  4385. unsigned SignBits = DAG.ComputeNumSignBits(N0);
  4386. if (SignBits > 1)
  4387. SignBits += DAG.ComputeNumSignBits(N1);
  4388. if (SignBits > VT.getScalarSizeInBits() + 1)
  4389. return CombineTo(N, DAG.getNode(ISD::MUL, DL, VT, N0, N1),
  4390. DAG.getConstant(0, DL, CarryVT));
  4391. } else {
  4392. KnownBits N1Known = DAG.computeKnownBits(N1);
  4393. KnownBits N0Known = DAG.computeKnownBits(N0);
  4394. bool Overflow;
  4395. (void)N0Known.getMaxValue().umul_ov(N1Known.getMaxValue(), Overflow);
  4396. if (!Overflow)
  4397. return CombineTo(N, DAG.getNode(ISD::MUL, DL, VT, N0, N1),
  4398. DAG.getConstant(0, DL, CarryVT));
  4399. }
  4400. return SDValue();
  4401. }
  4402. // Function to calculate whether the Min/Max pair of SDNodes (potentially
  4403. // swapped around) make a signed saturate pattern, clamping to between a signed
  4404. // saturate of -2^(BW-1) and 2^(BW-1)-1, or an unsigned saturate of 0 and 2^BW.
  4405. // Returns the node being clamped and the bitwidth of the clamp in BW. Should
  4406. // work with both SMIN/SMAX nodes and setcc/select combo. The operands are the
  4407. // same as SimplifySelectCC. N0<N1 ? N2 : N3.
  4408. static SDValue isSaturatingMinMax(SDValue N0, SDValue N1, SDValue N2,
  4409. SDValue N3, ISD::CondCode CC, unsigned &BW,
  4410. bool &Unsigned) {
  4411. auto isSignedMinMax = [&](SDValue N0, SDValue N1, SDValue N2, SDValue N3,
  4412. ISD::CondCode CC) {
  4413. // The compare and select operand should be the same or the select operands
  4414. // should be truncated versions of the comparison.
  4415. if (N0 != N2 && (N2.getOpcode() != ISD::TRUNCATE || N0 != N2.getOperand(0)))
  4416. return 0;
  4417. // The constants need to be the same or a truncated version of each other.
  4418. ConstantSDNode *N1C = isConstOrConstSplat(N1);
  4419. ConstantSDNode *N3C = isConstOrConstSplat(N3);
  4420. if (!N1C || !N3C)
  4421. return 0;
  4422. const APInt &C1 = N1C->getAPIntValue();
  4423. const APInt &C2 = N3C->getAPIntValue();
  4424. if (C1.getBitWidth() < C2.getBitWidth() || C1 != C2.sext(C1.getBitWidth()))
  4425. return 0;
  4426. return CC == ISD::SETLT ? ISD::SMIN : (CC == ISD::SETGT ? ISD::SMAX : 0);
  4427. };
  4428. // Check the initial value is a SMIN/SMAX equivalent.
  4429. unsigned Opcode0 = isSignedMinMax(N0, N1, N2, N3, CC);
  4430. if (!Opcode0)
  4431. return SDValue();
  4432. SDValue N00, N01, N02, N03;
  4433. ISD::CondCode N0CC;
  4434. switch (N0.getOpcode()) {
  4435. case ISD::SMIN:
  4436. case ISD::SMAX:
  4437. N00 = N02 = N0.getOperand(0);
  4438. N01 = N03 = N0.getOperand(1);
  4439. N0CC = N0.getOpcode() == ISD::SMIN ? ISD::SETLT : ISD::SETGT;
  4440. break;
  4441. case ISD::SELECT_CC:
  4442. N00 = N0.getOperand(0);
  4443. N01 = N0.getOperand(1);
  4444. N02 = N0.getOperand(2);
  4445. N03 = N0.getOperand(3);
  4446. N0CC = cast<CondCodeSDNode>(N0.getOperand(4))->get();
  4447. break;
  4448. case ISD::SELECT:
  4449. case ISD::VSELECT:
  4450. if (N0.getOperand(0).getOpcode() != ISD::SETCC)
  4451. return SDValue();
  4452. N00 = N0.getOperand(0).getOperand(0);
  4453. N01 = N0.getOperand(0).getOperand(1);
  4454. N02 = N0.getOperand(1);
  4455. N03 = N0.getOperand(2);
  4456. N0CC = cast<CondCodeSDNode>(N0.getOperand(0).getOperand(2))->get();
  4457. break;
  4458. default:
  4459. return SDValue();
  4460. }
  4461. unsigned Opcode1 = isSignedMinMax(N00, N01, N02, N03, N0CC);
  4462. if (!Opcode1 || Opcode0 == Opcode1)
  4463. return SDValue();
  4464. ConstantSDNode *MinCOp = isConstOrConstSplat(Opcode0 == ISD::SMIN ? N1 : N01);
  4465. ConstantSDNode *MaxCOp = isConstOrConstSplat(Opcode0 == ISD::SMIN ? N01 : N1);
  4466. if (!MinCOp || !MaxCOp || MinCOp->getValueType(0) != MaxCOp->getValueType(0))
  4467. return SDValue();
  4468. const APInt &MinC = MinCOp->getAPIntValue();
  4469. const APInt &MaxC = MaxCOp->getAPIntValue();
  4470. APInt MinCPlus1 = MinC + 1;
  4471. if (-MaxC == MinCPlus1 && MinCPlus1.isPowerOf2()) {
  4472. BW = MinCPlus1.exactLogBase2() + 1;
  4473. Unsigned = false;
  4474. return N02;
  4475. }
  4476. if (MaxC == 0 && MinCPlus1.isPowerOf2()) {
  4477. BW = MinCPlus1.exactLogBase2();
  4478. Unsigned = true;
  4479. return N02;
  4480. }
  4481. return SDValue();
  4482. }
  4483. static SDValue PerformMinMaxFpToSatCombine(SDValue N0, SDValue N1, SDValue N2,
  4484. SDValue N3, ISD::CondCode CC,
  4485. SelectionDAG &DAG) {
  4486. unsigned BW;
  4487. bool Unsigned;
  4488. SDValue Fp = isSaturatingMinMax(N0, N1, N2, N3, CC, BW, Unsigned);
  4489. if (!Fp || Fp.getOpcode() != ISD::FP_TO_SINT)
  4490. return SDValue();
  4491. EVT FPVT = Fp.getOperand(0).getValueType();
  4492. EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), BW);
  4493. if (FPVT.isVector())
  4494. NewVT = EVT::getVectorVT(*DAG.getContext(), NewVT,
  4495. FPVT.getVectorElementCount());
  4496. unsigned NewOpc = Unsigned ? ISD::FP_TO_UINT_SAT : ISD::FP_TO_SINT_SAT;
  4497. if (!DAG.getTargetLoweringInfo().shouldConvertFpToSat(NewOpc, FPVT, NewVT))
  4498. return SDValue();
  4499. SDLoc DL(Fp);
  4500. SDValue Sat = DAG.getNode(NewOpc, DL, NewVT, Fp.getOperand(0),
  4501. DAG.getValueType(NewVT.getScalarType()));
  4502. return Unsigned ? DAG.getZExtOrTrunc(Sat, DL, N2->getValueType(0))
  4503. : DAG.getSExtOrTrunc(Sat, DL, N2->getValueType(0));
  4504. }
  4505. static SDValue PerformUMinFpToSatCombine(SDValue N0, SDValue N1, SDValue N2,
  4506. SDValue N3, ISD::CondCode CC,
  4507. SelectionDAG &DAG) {
  4508. // We are looking for UMIN(FPTOUI(X), (2^n)-1), which may have come via a
  4509. // select/vselect/select_cc. The two operands pairs for the select (N2/N3) may
  4510. // be truncated versions of the the setcc (N0/N1).
  4511. if ((N0 != N2 &&
  4512. (N2.getOpcode() != ISD::TRUNCATE || N0 != N2.getOperand(0))) ||
  4513. N0.getOpcode() != ISD::FP_TO_UINT || CC != ISD::SETULT)
  4514. return SDValue();
  4515. ConstantSDNode *N1C = isConstOrConstSplat(N1);
  4516. ConstantSDNode *N3C = isConstOrConstSplat(N3);
  4517. if (!N1C || !N3C)
  4518. return SDValue();
  4519. const APInt &C1 = N1C->getAPIntValue();
  4520. const APInt &C3 = N3C->getAPIntValue();
  4521. if (!(C1 + 1).isPowerOf2() || C1.getBitWidth() < C3.getBitWidth() ||
  4522. C1 != C3.zext(C1.getBitWidth()))
  4523. return SDValue();
  4524. unsigned BW = (C1 + 1).exactLogBase2();
  4525. EVT FPVT = N0.getOperand(0).getValueType();
  4526. EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), BW);
  4527. if (FPVT.isVector())
  4528. NewVT = EVT::getVectorVT(*DAG.getContext(), NewVT,
  4529. FPVT.getVectorElementCount());
  4530. if (!DAG.getTargetLoweringInfo().shouldConvertFpToSat(ISD::FP_TO_UINT_SAT,
  4531. FPVT, NewVT))
  4532. return SDValue();
  4533. SDValue Sat =
  4534. DAG.getNode(ISD::FP_TO_UINT_SAT, SDLoc(N0), NewVT, N0.getOperand(0),
  4535. DAG.getValueType(NewVT.getScalarType()));
  4536. return DAG.getZExtOrTrunc(Sat, SDLoc(N0), N3.getValueType());
  4537. }
  4538. SDValue DAGCombiner::visitIMINMAX(SDNode *N) {
  4539. SDValue N0 = N->getOperand(0);
  4540. SDValue N1 = N->getOperand(1);
  4541. EVT VT = N0.getValueType();
  4542. unsigned Opcode = N->getOpcode();
  4543. SDLoc DL(N);
  4544. // fold operation with constant operands.
  4545. if (SDValue C = DAG.FoldConstantArithmetic(Opcode, DL, VT, {N0, N1}))
  4546. return C;
  4547. // If the operands are the same, this is a no-op.
  4548. if (N0 == N1)
  4549. return N0;
  4550. // canonicalize constant to RHS
  4551. if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
  4552. !DAG.isConstantIntBuildVectorOrConstantInt(N1))
  4553. return DAG.getNode(Opcode, DL, VT, N1, N0);
  4554. // fold vector ops
  4555. if (VT.isVector())
  4556. if (SDValue FoldedVOp = SimplifyVBinOp(N, DL))
  4557. return FoldedVOp;
  4558. // Is sign bits are zero, flip between UMIN/UMAX and SMIN/SMAX.
  4559. // Only do this if the current op isn't legal and the flipped is.
  4560. if (!TLI.isOperationLegal(Opcode, VT) &&
  4561. (N0.isUndef() || DAG.SignBitIsZero(N0)) &&
  4562. (N1.isUndef() || DAG.SignBitIsZero(N1))) {
  4563. unsigned AltOpcode;
  4564. switch (Opcode) {
  4565. case ISD::SMIN: AltOpcode = ISD::UMIN; break;
  4566. case ISD::SMAX: AltOpcode = ISD::UMAX; break;
  4567. case ISD::UMIN: AltOpcode = ISD::SMIN; break;
  4568. case ISD::UMAX: AltOpcode = ISD::SMAX; break;
  4569. default: llvm_unreachable("Unknown MINMAX opcode");
  4570. }
  4571. if (TLI.isOperationLegal(AltOpcode, VT))
  4572. return DAG.getNode(AltOpcode, DL, VT, N0, N1);
  4573. }
  4574. if (Opcode == ISD::SMIN || Opcode == ISD::SMAX)
  4575. if (SDValue S = PerformMinMaxFpToSatCombine(
  4576. N0, N1, N0, N1, Opcode == ISD::SMIN ? ISD::SETLT : ISD::SETGT, DAG))
  4577. return S;
  4578. if (Opcode == ISD::UMIN)
  4579. if (SDValue S = PerformUMinFpToSatCombine(N0, N1, N0, N1, ISD::SETULT, DAG))
  4580. return S;
  4581. // Simplify the operands using demanded-bits information.
  4582. if (SimplifyDemandedBits(SDValue(N, 0)))
  4583. return SDValue(N, 0);
  4584. return SDValue();
  4585. }
  4586. /// If this is a bitwise logic instruction and both operands have the same
  4587. /// opcode, try to sink the other opcode after the logic instruction.
  4588. SDValue DAGCombiner::hoistLogicOpWithSameOpcodeHands(SDNode *N) {
  4589. SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
  4590. EVT VT = N0.getValueType();
  4591. unsigned LogicOpcode = N->getOpcode();
  4592. unsigned HandOpcode = N0.getOpcode();
  4593. assert((LogicOpcode == ISD::AND || LogicOpcode == ISD::OR ||
  4594. LogicOpcode == ISD::XOR) && "Expected logic opcode");
  4595. assert(HandOpcode == N1.getOpcode() && "Bad input!");
  4596. // Bail early if none of these transforms apply.
  4597. if (N0.getNumOperands() == 0)
  4598. return SDValue();
  4599. // FIXME: We should check number of uses of the operands to not increase
  4600. // the instruction count for all transforms.
  4601. // Handle size-changing casts.
  4602. SDValue X = N0.getOperand(0);
  4603. SDValue Y = N1.getOperand(0);
  4604. EVT XVT = X.getValueType();
  4605. SDLoc DL(N);
  4606. if (HandOpcode == ISD::ANY_EXTEND || HandOpcode == ISD::ZERO_EXTEND ||
  4607. HandOpcode == ISD::SIGN_EXTEND) {
  4608. // If both operands have other uses, this transform would create extra
  4609. // instructions without eliminating anything.
  4610. if (!N0.hasOneUse() && !N1.hasOneUse())
  4611. return SDValue();
  4612. // We need matching integer source types.
  4613. if (XVT != Y.getValueType())
  4614. return SDValue();
  4615. // Don't create an illegal op during or after legalization. Don't ever
  4616. // create an unsupported vector op.
  4617. if ((VT.isVector() || LegalOperations) &&
  4618. !TLI.isOperationLegalOrCustom(LogicOpcode, XVT))
  4619. return SDValue();
  4620. // Avoid infinite looping with PromoteIntBinOp.
  4621. // TODO: Should we apply desirable/legal constraints to all opcodes?
  4622. if (HandOpcode == ISD::ANY_EXTEND && LegalTypes &&
  4623. !TLI.isTypeDesirableForOp(LogicOpcode, XVT))
  4624. return SDValue();
  4625. // logic_op (hand_op X), (hand_op Y) --> hand_op (logic_op X, Y)
  4626. SDValue Logic = DAG.getNode(LogicOpcode, DL, XVT, X, Y);
  4627. return DAG.getNode(HandOpcode, DL, VT, Logic);
  4628. }
  4629. // logic_op (truncate x), (truncate y) --> truncate (logic_op x, y)
  4630. if (HandOpcode == ISD::TRUNCATE) {
  4631. // If both operands have other uses, this transform would create extra
  4632. // instructions without eliminating anything.
  4633. if (!N0.hasOneUse() && !N1.hasOneUse())
  4634. return SDValue();
  4635. // We need matching source types.
  4636. if (XVT != Y.getValueType())
  4637. return SDValue();
  4638. // Don't create an illegal op during or after legalization.
  4639. if (LegalOperations && !TLI.isOperationLegal(LogicOpcode, XVT))
  4640. return SDValue();
  4641. // Be extra careful sinking truncate. If it's free, there's no benefit in
  4642. // widening a binop. Also, don't create a logic op on an illegal type.
  4643. if (TLI.isZExtFree(VT, XVT) && TLI.isTruncateFree(XVT, VT))
  4644. return SDValue();
  4645. if (!TLI.isTypeLegal(XVT))
  4646. return SDValue();
  4647. SDValue Logic = DAG.getNode(LogicOpcode, DL, XVT, X, Y);
  4648. return DAG.getNode(HandOpcode, DL, VT, Logic);
  4649. }
  4650. // For binops SHL/SRL/SRA/AND:
  4651. // logic_op (OP x, z), (OP y, z) --> OP (logic_op x, y), z
  4652. if ((HandOpcode == ISD::SHL || HandOpcode == ISD::SRL ||
  4653. HandOpcode == ISD::SRA || HandOpcode == ISD::AND) &&
  4654. N0.getOperand(1) == N1.getOperand(1)) {
  4655. // If either operand has other uses, this transform is not an improvement.
  4656. if (!N0.hasOneUse() || !N1.hasOneUse())
  4657. return SDValue();
  4658. SDValue Logic = DAG.getNode(LogicOpcode, DL, XVT, X, Y);
  4659. return DAG.getNode(HandOpcode, DL, VT, Logic, N0.getOperand(1));
  4660. }
  4661. // Unary ops: logic_op (bswap x), (bswap y) --> bswap (logic_op x, y)
  4662. if (HandOpcode == ISD::BSWAP) {
  4663. // If either operand has other uses, this transform is not an improvement.
  4664. if (!N0.hasOneUse() || !N1.hasOneUse())
  4665. return SDValue();
  4666. SDValue Logic = DAG.getNode(LogicOpcode, DL, XVT, X, Y);
  4667. return DAG.getNode(HandOpcode, DL, VT, Logic);
  4668. }
  4669. // For funnel shifts FSHL/FSHR:
  4670. // logic_op (OP x, x1, s), (OP y, y1, s) -->
  4671. // --> OP (logic_op x, y), (logic_op, x1, y1), s
  4672. if ((HandOpcode == ISD::FSHL || HandOpcode == ISD::FSHR) &&
  4673. N0.getOperand(2) == N1.getOperand(2)) {
  4674. if (!N0.hasOneUse() || !N1.hasOneUse())
  4675. return SDValue();
  4676. SDValue X1 = N0.getOperand(1);
  4677. SDValue Y1 = N1.getOperand(1);
  4678. SDValue S = N0.getOperand(2);
  4679. SDValue Logic0 = DAG.getNode(LogicOpcode, DL, VT, X, Y);
  4680. SDValue Logic1 = DAG.getNode(LogicOpcode, DL, VT, X1, Y1);
  4681. return DAG.getNode(HandOpcode, DL, VT, Logic0, Logic1, S);
  4682. }
  4683. // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
  4684. // Only perform this optimization up until type legalization, before
  4685. // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
  4686. // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
  4687. // we don't want to undo this promotion.
  4688. // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
  4689. // on scalars.
  4690. if ((HandOpcode == ISD::BITCAST || HandOpcode == ISD::SCALAR_TO_VECTOR) &&
  4691. Level <= AfterLegalizeTypes) {
  4692. // Input types must be integer and the same.
  4693. if (XVT.isInteger() && XVT == Y.getValueType() &&
  4694. !(VT.isVector() && TLI.isTypeLegal(VT) &&
  4695. !XVT.isVector() && !TLI.isTypeLegal(XVT))) {
  4696. SDValue Logic = DAG.getNode(LogicOpcode, DL, XVT, X, Y);
  4697. return DAG.getNode(HandOpcode, DL, VT, Logic);
  4698. }
  4699. }
  4700. // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
  4701. // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
  4702. // If both shuffles use the same mask, and both shuffle within a single
  4703. // vector, then it is worthwhile to move the swizzle after the operation.
  4704. // The type-legalizer generates this pattern when loading illegal
  4705. // vector types from memory. In many cases this allows additional shuffle
  4706. // optimizations.
  4707. // There are other cases where moving the shuffle after the xor/and/or
  4708. // is profitable even if shuffles don't perform a swizzle.
  4709. // If both shuffles use the same mask, and both shuffles have the same first
  4710. // or second operand, then it might still be profitable to move the shuffle
  4711. // after the xor/and/or operation.
  4712. if (HandOpcode == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
  4713. auto *SVN0 = cast<ShuffleVectorSDNode>(N0);
  4714. auto *SVN1 = cast<ShuffleVectorSDNode>(N1);
  4715. assert(X.getValueType() == Y.getValueType() &&
  4716. "Inputs to shuffles are not the same type");
  4717. // Check that both shuffles use the same mask. The masks are known to be of
  4718. // the same length because the result vector type is the same.
  4719. // Check also that shuffles have only one use to avoid introducing extra
  4720. // instructions.
  4721. if (!SVN0->hasOneUse() || !SVN1->hasOneUse() ||
  4722. !SVN0->getMask().equals(SVN1->getMask()))
  4723. return SDValue();
  4724. // Don't try to fold this node if it requires introducing a
  4725. // build vector of all zeros that might be illegal at this stage.
  4726. SDValue ShOp = N0.getOperand(1);
  4727. if (LogicOpcode == ISD::XOR && !ShOp.isUndef())
  4728. ShOp = tryFoldToZero(DL, TLI, VT, DAG, LegalOperations);
  4729. // (logic_op (shuf (A, C), shuf (B, C))) --> shuf (logic_op (A, B), C)
  4730. if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
  4731. SDValue Logic = DAG.getNode(LogicOpcode, DL, VT,
  4732. N0.getOperand(0), N1.getOperand(0));
  4733. return DAG.getVectorShuffle(VT, DL, Logic, ShOp, SVN0->getMask());
  4734. }
  4735. // Don't try to fold this node if it requires introducing a
  4736. // build vector of all zeros that might be illegal at this stage.
  4737. ShOp = N0.getOperand(0);
  4738. if (LogicOpcode == ISD::XOR && !ShOp.isUndef())
  4739. ShOp = tryFoldToZero(DL, TLI, VT, DAG, LegalOperations);
  4740. // (logic_op (shuf (C, A), shuf (C, B))) --> shuf (C, logic_op (A, B))
  4741. if (N0.getOperand(0) == N1.getOperand(0) && ShOp.getNode()) {
  4742. SDValue Logic = DAG.getNode(LogicOpcode, DL, VT, N0.getOperand(1),
  4743. N1.getOperand(1));
  4744. return DAG.getVectorShuffle(VT, DL, ShOp, Logic, SVN0->getMask());
  4745. }
  4746. }
  4747. return SDValue();
  4748. }
  4749. /// Try to make (and/or setcc (LL, LR), setcc (RL, RR)) more efficient.
  4750. SDValue DAGCombiner::foldLogicOfSetCCs(bool IsAnd, SDValue N0, SDValue N1,
  4751. const SDLoc &DL) {
  4752. SDValue LL, LR, RL, RR, N0CC, N1CC;
  4753. if (!isSetCCEquivalent(N0, LL, LR, N0CC) ||
  4754. !isSetCCEquivalent(N1, RL, RR, N1CC))
  4755. return SDValue();
  4756. assert(N0.getValueType() == N1.getValueType() &&
  4757. "Unexpected operand types for bitwise logic op");
  4758. assert(LL.getValueType() == LR.getValueType() &&
  4759. RL.getValueType() == RR.getValueType() &&
  4760. "Unexpected operand types for setcc");
  4761. // If we're here post-legalization or the logic op type is not i1, the logic
  4762. // op type must match a setcc result type. Also, all folds require new
  4763. // operations on the left and right operands, so those types must match.
  4764. EVT VT = N0.getValueType();
  4765. EVT OpVT = LL.getValueType();
  4766. if (LegalOperations || VT.getScalarType() != MVT::i1)
  4767. if (VT != getSetCCResultType(OpVT))
  4768. return SDValue();
  4769. if (OpVT != RL.getValueType())
  4770. return SDValue();
  4771. ISD::CondCode CC0 = cast<CondCodeSDNode>(N0CC)->get();
  4772. ISD::CondCode CC1 = cast<CondCodeSDNode>(N1CC)->get();
  4773. bool IsInteger = OpVT.isInteger();
  4774. if (LR == RR && CC0 == CC1 && IsInteger) {
  4775. bool IsZero = isNullOrNullSplat(LR);
  4776. bool IsNeg1 = isAllOnesOrAllOnesSplat(LR);
  4777. // All bits clear?
  4778. bool AndEqZero = IsAnd && CC1 == ISD::SETEQ && IsZero;
  4779. // All sign bits clear?
  4780. bool AndGtNeg1 = IsAnd && CC1 == ISD::SETGT && IsNeg1;
  4781. // Any bits set?
  4782. bool OrNeZero = !IsAnd && CC1 == ISD::SETNE && IsZero;
  4783. // Any sign bits set?
  4784. bool OrLtZero = !IsAnd && CC1 == ISD::SETLT && IsZero;
  4785. // (and (seteq X, 0), (seteq Y, 0)) --> (seteq (or X, Y), 0)
  4786. // (and (setgt X, -1), (setgt Y, -1)) --> (setgt (or X, Y), -1)
  4787. // (or (setne X, 0), (setne Y, 0)) --> (setne (or X, Y), 0)
  4788. // (or (setlt X, 0), (setlt Y, 0)) --> (setlt (or X, Y), 0)
  4789. if (AndEqZero || AndGtNeg1 || OrNeZero || OrLtZero) {
  4790. SDValue Or = DAG.getNode(ISD::OR, SDLoc(N0), OpVT, LL, RL);
  4791. AddToWorklist(Or.getNode());
  4792. return DAG.getSetCC(DL, VT, Or, LR, CC1);
  4793. }
  4794. // All bits set?
  4795. bool AndEqNeg1 = IsAnd && CC1 == ISD::SETEQ && IsNeg1;
  4796. // All sign bits set?
  4797. bool AndLtZero = IsAnd && CC1 == ISD::SETLT && IsZero;
  4798. // Any bits clear?
  4799. bool OrNeNeg1 = !IsAnd && CC1 == ISD::SETNE && IsNeg1;
  4800. // Any sign bits clear?
  4801. bool OrGtNeg1 = !IsAnd && CC1 == ISD::SETGT && IsNeg1;
  4802. // (and (seteq X, -1), (seteq Y, -1)) --> (seteq (and X, Y), -1)
  4803. // (and (setlt X, 0), (setlt Y, 0)) --> (setlt (and X, Y), 0)
  4804. // (or (setne X, -1), (setne Y, -1)) --> (setne (and X, Y), -1)
  4805. // (or (setgt X, -1), (setgt Y -1)) --> (setgt (and X, Y), -1)
  4806. if (AndEqNeg1 || AndLtZero || OrNeNeg1 || OrGtNeg1) {
  4807. SDValue And = DAG.getNode(ISD::AND, SDLoc(N0), OpVT, LL, RL);
  4808. AddToWorklist(And.getNode());
  4809. return DAG.getSetCC(DL, VT, And, LR, CC1);
  4810. }
  4811. }
  4812. // TODO: What is the 'or' equivalent of this fold?
  4813. // (and (setne X, 0), (setne X, -1)) --> (setuge (add X, 1), 2)
  4814. if (IsAnd && LL == RL && CC0 == CC1 && OpVT.getScalarSizeInBits() > 1 &&
  4815. IsInteger && CC0 == ISD::SETNE &&
  4816. ((isNullConstant(LR) && isAllOnesConstant(RR)) ||
  4817. (isAllOnesConstant(LR) && isNullConstant(RR)))) {
  4818. SDValue One = DAG.getConstant(1, DL, OpVT);
  4819. SDValue Two = DAG.getConstant(2, DL, OpVT);
  4820. SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0), OpVT, LL, One);
  4821. AddToWorklist(Add.getNode());
  4822. return DAG.getSetCC(DL, VT, Add, Two, ISD::SETUGE);
  4823. }
  4824. // Try more general transforms if the predicates match and the only user of
  4825. // the compares is the 'and' or 'or'.
  4826. if (IsInteger && TLI.convertSetCCLogicToBitwiseLogic(OpVT) && CC0 == CC1 &&
  4827. N0.hasOneUse() && N1.hasOneUse()) {
  4828. // and (seteq A, B), (seteq C, D) --> seteq (or (xor A, B), (xor C, D)), 0
  4829. // or (setne A, B), (setne C, D) --> setne (or (xor A, B), (xor C, D)), 0
  4830. if ((IsAnd && CC1 == ISD::SETEQ) || (!IsAnd && CC1 == ISD::SETNE)) {
  4831. SDValue XorL = DAG.getNode(ISD::XOR, SDLoc(N0), OpVT, LL, LR);
  4832. SDValue XorR = DAG.getNode(ISD::XOR, SDLoc(N1), OpVT, RL, RR);
  4833. SDValue Or = DAG.getNode(ISD::OR, DL, OpVT, XorL, XorR);
  4834. SDValue Zero = DAG.getConstant(0, DL, OpVT);
  4835. return DAG.getSetCC(DL, VT, Or, Zero, CC1);
  4836. }
  4837. // Turn compare of constants whose difference is 1 bit into add+and+setcc.
  4838. if ((IsAnd && CC1 == ISD::SETNE) || (!IsAnd && CC1 == ISD::SETEQ)) {
  4839. // Match a shared variable operand and 2 non-opaque constant operands.
  4840. auto MatchDiffPow2 = [&](ConstantSDNode *C0, ConstantSDNode *C1) {
  4841. // The difference of the constants must be a single bit.
  4842. const APInt &CMax =
  4843. APIntOps::umax(C0->getAPIntValue(), C1->getAPIntValue());
  4844. const APInt &CMin =
  4845. APIntOps::umin(C0->getAPIntValue(), C1->getAPIntValue());
  4846. return !C0->isOpaque() && !C1->isOpaque() && (CMax - CMin).isPowerOf2();
  4847. };
  4848. if (LL == RL && ISD::matchBinaryPredicate(LR, RR, MatchDiffPow2)) {
  4849. // and/or (setcc X, CMax, ne), (setcc X, CMin, ne/eq) -->
  4850. // setcc ((sub X, CMin), ~(CMax - CMin)), 0, ne/eq
  4851. SDValue Max = DAG.getNode(ISD::UMAX, DL, OpVT, LR, RR);
  4852. SDValue Min = DAG.getNode(ISD::UMIN, DL, OpVT, LR, RR);
  4853. SDValue Offset = DAG.getNode(ISD::SUB, DL, OpVT, LL, Min);
  4854. SDValue Diff = DAG.getNode(ISD::SUB, DL, OpVT, Max, Min);
  4855. SDValue Mask = DAG.getNOT(DL, Diff, OpVT);
  4856. SDValue And = DAG.getNode(ISD::AND, DL, OpVT, Offset, Mask);
  4857. SDValue Zero = DAG.getConstant(0, DL, OpVT);
  4858. return DAG.getSetCC(DL, VT, And, Zero, CC0);
  4859. }
  4860. }
  4861. }
  4862. // Canonicalize equivalent operands to LL == RL.
  4863. if (LL == RR && LR == RL) {
  4864. CC1 = ISD::getSetCCSwappedOperands(CC1);
  4865. std::swap(RL, RR);
  4866. }
  4867. // (and (setcc X, Y, CC0), (setcc X, Y, CC1)) --> (setcc X, Y, NewCC)
  4868. // (or (setcc X, Y, CC0), (setcc X, Y, CC1)) --> (setcc X, Y, NewCC)
  4869. if (LL == RL && LR == RR) {
  4870. ISD::CondCode NewCC = IsAnd ? ISD::getSetCCAndOperation(CC0, CC1, OpVT)
  4871. : ISD::getSetCCOrOperation(CC0, CC1, OpVT);
  4872. if (NewCC != ISD::SETCC_INVALID &&
  4873. (!LegalOperations ||
  4874. (TLI.isCondCodeLegal(NewCC, LL.getSimpleValueType()) &&
  4875. TLI.isOperationLegal(ISD::SETCC, OpVT))))
  4876. return DAG.getSetCC(DL, VT, LL, LR, NewCC);
  4877. }
  4878. return SDValue();
  4879. }
  4880. /// This contains all DAGCombine rules which reduce two values combined by
  4881. /// an And operation to a single value. This makes them reusable in the context
  4882. /// of visitSELECT(). Rules involving constants are not included as
  4883. /// visitSELECT() already handles those cases.
  4884. SDValue DAGCombiner::visitANDLike(SDValue N0, SDValue N1, SDNode *N) {
  4885. EVT VT = N1.getValueType();
  4886. SDLoc DL(N);
  4887. // fold (and x, undef) -> 0
  4888. if (N0.isUndef() || N1.isUndef())
  4889. return DAG.getConstant(0, DL, VT);
  4890. if (SDValue V = foldLogicOfSetCCs(true, N0, N1, DL))
  4891. return V;
  4892. // TODO: Rewrite this to return a new 'AND' instead of using CombineTo.
  4893. if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
  4894. VT.getSizeInBits() <= 64 && N0->hasOneUse()) {
  4895. if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
  4896. if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
  4897. // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
  4898. // immediate for an add, but it is legal if its top c2 bits are set,
  4899. // transform the ADD so the immediate doesn't need to be materialized
  4900. // in a register.
  4901. APInt ADDC = ADDI->getAPIntValue();
  4902. APInt SRLC = SRLI->getAPIntValue();
  4903. if (ADDC.getMinSignedBits() <= 64 &&
  4904. SRLC.ult(VT.getSizeInBits()) &&
  4905. !TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
  4906. APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
  4907. SRLC.getZExtValue());
  4908. if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
  4909. ADDC |= Mask;
  4910. if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
  4911. SDLoc DL0(N0);
  4912. SDValue NewAdd =
  4913. DAG.getNode(ISD::ADD, DL0, VT,
  4914. N0.getOperand(0), DAG.getConstant(ADDC, DL, VT));
  4915. CombineTo(N0.getNode(), NewAdd);
  4916. // Return N so it doesn't get rechecked!
  4917. return SDValue(N, 0);
  4918. }
  4919. }
  4920. }
  4921. }
  4922. }
  4923. }
  4924. // Reduce bit extract of low half of an integer to the narrower type.
  4925. // (and (srl i64:x, K), KMask) ->
  4926. // (i64 zero_extend (and (srl (i32 (trunc i64:x)), K)), KMask)
  4927. if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
  4928. if (ConstantSDNode *CAnd = dyn_cast<ConstantSDNode>(N1)) {
  4929. if (ConstantSDNode *CShift = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
  4930. unsigned Size = VT.getSizeInBits();
  4931. const APInt &AndMask = CAnd->getAPIntValue();
  4932. unsigned ShiftBits = CShift->getZExtValue();
  4933. // Bail out, this node will probably disappear anyway.
  4934. if (ShiftBits == 0)
  4935. return SDValue();
  4936. unsigned MaskBits = AndMask.countTrailingOnes();
  4937. EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), Size / 2);
  4938. if (AndMask.isMask() &&
  4939. // Required bits must not span the two halves of the integer and
  4940. // must fit in the half size type.
  4941. (ShiftBits + MaskBits <= Size / 2) &&
  4942. TLI.isNarrowingProfitable(VT, HalfVT) &&
  4943. TLI.isTypeDesirableForOp(ISD::AND, HalfVT) &&
  4944. TLI.isTypeDesirableForOp(ISD::SRL, HalfVT) &&
  4945. TLI.isTruncateFree(VT, HalfVT) &&
  4946. TLI.isZExtFree(HalfVT, VT)) {
  4947. // The isNarrowingProfitable is to avoid regressions on PPC and
  4948. // AArch64 which match a few 64-bit bit insert / bit extract patterns
  4949. // on downstream users of this. Those patterns could probably be
  4950. // extended to handle extensions mixed in.
  4951. SDValue SL(N0);
  4952. assert(MaskBits <= Size);
  4953. // Extracting the highest bit of the low half.
  4954. EVT ShiftVT = TLI.getShiftAmountTy(HalfVT, DAG.getDataLayout());
  4955. SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, HalfVT,
  4956. N0.getOperand(0));
  4957. SDValue NewMask = DAG.getConstant(AndMask.trunc(Size / 2), SL, HalfVT);
  4958. SDValue ShiftK = DAG.getConstant(ShiftBits, SL, ShiftVT);
  4959. SDValue Shift = DAG.getNode(ISD::SRL, SL, HalfVT, Trunc, ShiftK);
  4960. SDValue And = DAG.getNode(ISD::AND, SL, HalfVT, Shift, NewMask);
  4961. return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, And);
  4962. }
  4963. }
  4964. }
  4965. }
  4966. return SDValue();
  4967. }
  4968. bool DAGCombiner::isAndLoadExtLoad(ConstantSDNode *AndC, LoadSDNode *LoadN,
  4969. EVT LoadResultTy, EVT &ExtVT) {
  4970. if (!AndC->getAPIntValue().isMask())
  4971. return false;
  4972. unsigned ActiveBits = AndC->getAPIntValue().countTrailingOnes();
  4973. ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
  4974. EVT LoadedVT = LoadN->getMemoryVT();
  4975. if (ExtVT == LoadedVT &&
  4976. (!LegalOperations ||
  4977. TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, ExtVT))) {
  4978. // ZEXTLOAD will match without needing to change the size of the value being
  4979. // loaded.
  4980. return true;
  4981. }
  4982. // Do not change the width of a volatile or atomic loads.
  4983. if (!LoadN->isSimple())
  4984. return false;
  4985. // Do not generate loads of non-round integer types since these can
  4986. // be expensive (and would be wrong if the type is not byte sized).
  4987. if (!LoadedVT.bitsGT(ExtVT) || !ExtVT.isRound())
  4988. return false;
  4989. if (LegalOperations &&
  4990. !TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, ExtVT))
  4991. return false;
  4992. if (!TLI.shouldReduceLoadWidth(LoadN, ISD::ZEXTLOAD, ExtVT))
  4993. return false;
  4994. return true;
  4995. }
  4996. bool DAGCombiner::isLegalNarrowLdSt(LSBaseSDNode *LDST,
  4997. ISD::LoadExtType ExtType, EVT &MemVT,
  4998. unsigned ShAmt) {
  4999. if (!LDST)
  5000. return false;
  5001. // Only allow byte offsets.
  5002. if (ShAmt % 8)
  5003. return false;
  5004. // Do not generate loads of non-round integer types since these can
  5005. // be expensive (and would be wrong if the type is not byte sized).
  5006. if (!MemVT.isRound())
  5007. return false;
  5008. // Don't change the width of a volatile or atomic loads.
  5009. if (!LDST->isSimple())
  5010. return false;
  5011. EVT LdStMemVT = LDST->getMemoryVT();
  5012. // Bail out when changing the scalable property, since we can't be sure that
  5013. // we're actually narrowing here.
  5014. if (LdStMemVT.isScalableVector() != MemVT.isScalableVector())
  5015. return false;
  5016. // Verify that we are actually reducing a load width here.
  5017. if (LdStMemVT.bitsLT(MemVT))
  5018. return false;
  5019. // Ensure that this isn't going to produce an unsupported memory access.
  5020. if (ShAmt) {
  5021. assert(ShAmt % 8 == 0 && "ShAmt is byte offset");
  5022. const unsigned ByteShAmt = ShAmt / 8;
  5023. const Align LDSTAlign = LDST->getAlign();
  5024. const Align NarrowAlign = commonAlignment(LDSTAlign, ByteShAmt);
  5025. if (!TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), MemVT,
  5026. LDST->getAddressSpace(), NarrowAlign,
  5027. LDST->getMemOperand()->getFlags()))
  5028. return false;
  5029. }
  5030. // It's not possible to generate a constant of extended or untyped type.
  5031. EVT PtrType = LDST->getBasePtr().getValueType();
  5032. if (PtrType == MVT::Untyped || PtrType.isExtended())
  5033. return false;
  5034. if (isa<LoadSDNode>(LDST)) {
  5035. LoadSDNode *Load = cast<LoadSDNode>(LDST);
  5036. // Don't transform one with multiple uses, this would require adding a new
  5037. // load.
  5038. if (!SDValue(Load, 0).hasOneUse())
  5039. return false;
  5040. if (LegalOperations &&
  5041. !TLI.isLoadExtLegal(ExtType, Load->getValueType(0), MemVT))
  5042. return false;
  5043. // For the transform to be legal, the load must produce only two values
  5044. // (the value loaded and the chain). Don't transform a pre-increment
  5045. // load, for example, which produces an extra value. Otherwise the
  5046. // transformation is not equivalent, and the downstream logic to replace
  5047. // uses gets things wrong.
  5048. if (Load->getNumValues() > 2)
  5049. return false;
  5050. // If the load that we're shrinking is an extload and we're not just
  5051. // discarding the extension we can't simply shrink the load. Bail.
  5052. // TODO: It would be possible to merge the extensions in some cases.
  5053. if (Load->getExtensionType() != ISD::NON_EXTLOAD &&
  5054. Load->getMemoryVT().getSizeInBits() < MemVT.getSizeInBits() + ShAmt)
  5055. return false;
  5056. if (!TLI.shouldReduceLoadWidth(Load, ExtType, MemVT))
  5057. return false;
  5058. } else {
  5059. assert(isa<StoreSDNode>(LDST) && "It is not a Load nor a Store SDNode");
  5060. StoreSDNode *Store = cast<StoreSDNode>(LDST);
  5061. // Can't write outside the original store
  5062. if (Store->getMemoryVT().getSizeInBits() < MemVT.getSizeInBits() + ShAmt)
  5063. return false;
  5064. if (LegalOperations &&
  5065. !TLI.isTruncStoreLegal(Store->getValue().getValueType(), MemVT))
  5066. return false;
  5067. }
  5068. return true;
  5069. }
  5070. bool DAGCombiner::SearchForAndLoads(SDNode *N,
  5071. SmallVectorImpl<LoadSDNode*> &Loads,
  5072. SmallPtrSetImpl<SDNode*> &NodesWithConsts,
  5073. ConstantSDNode *Mask,
  5074. SDNode *&NodeToMask) {
  5075. // Recursively search for the operands, looking for loads which can be
  5076. // narrowed.
  5077. for (SDValue Op : N->op_values()) {
  5078. if (Op.getValueType().isVector())
  5079. return false;
  5080. // Some constants may need fixing up later if they are too large.
  5081. if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
  5082. if ((N->getOpcode() == ISD::OR || N->getOpcode() == ISD::XOR) &&
  5083. (Mask->getAPIntValue() & C->getAPIntValue()) != C->getAPIntValue())
  5084. NodesWithConsts.insert(N);
  5085. continue;
  5086. }
  5087. if (!Op.hasOneUse())
  5088. return false;
  5089. switch(Op.getOpcode()) {
  5090. case ISD::LOAD: {
  5091. auto *Load = cast<LoadSDNode>(Op);
  5092. EVT ExtVT;
  5093. if (isAndLoadExtLoad(Mask, Load, Load->getValueType(0), ExtVT) &&
  5094. isLegalNarrowLdSt(Load, ISD::ZEXTLOAD, ExtVT)) {
  5095. // ZEXTLOAD is already small enough.
  5096. if (Load->getExtensionType() == ISD::ZEXTLOAD &&
  5097. ExtVT.bitsGE(Load->getMemoryVT()))
  5098. continue;
  5099. // Use LE to convert equal sized loads to zext.
  5100. if (ExtVT.bitsLE(Load->getMemoryVT()))
  5101. Loads.push_back(Load);
  5102. continue;
  5103. }
  5104. return false;
  5105. }
  5106. case ISD::ZERO_EXTEND:
  5107. case ISD::AssertZext: {
  5108. unsigned ActiveBits = Mask->getAPIntValue().countTrailingOnes();
  5109. EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
  5110. EVT VT = Op.getOpcode() == ISD::AssertZext ?
  5111. cast<VTSDNode>(Op.getOperand(1))->getVT() :
  5112. Op.getOperand(0).getValueType();
  5113. // We can accept extending nodes if the mask is wider or an equal
  5114. // width to the original type.
  5115. if (ExtVT.bitsGE(VT))
  5116. continue;
  5117. break;
  5118. }
  5119. case ISD::OR:
  5120. case ISD::XOR:
  5121. case ISD::AND:
  5122. if (!SearchForAndLoads(Op.getNode(), Loads, NodesWithConsts, Mask,
  5123. NodeToMask))
  5124. return false;
  5125. continue;
  5126. }
  5127. // Allow one node which will masked along with any loads found.
  5128. if (NodeToMask)
  5129. return false;
  5130. // Also ensure that the node to be masked only produces one data result.
  5131. NodeToMask = Op.getNode();
  5132. if (NodeToMask->getNumValues() > 1) {
  5133. bool HasValue = false;
  5134. for (unsigned i = 0, e = NodeToMask->getNumValues(); i < e; ++i) {
  5135. MVT VT = SDValue(NodeToMask, i).getSimpleValueType();
  5136. if (VT != MVT::Glue && VT != MVT::Other) {
  5137. if (HasValue) {
  5138. NodeToMask = nullptr;
  5139. return false;
  5140. }
  5141. HasValue = true;
  5142. }
  5143. }
  5144. assert(HasValue && "Node to be masked has no data result?");
  5145. }
  5146. }
  5147. return true;
  5148. }
  5149. bool DAGCombiner::BackwardsPropagateMask(SDNode *N) {
  5150. auto *Mask = dyn_cast<ConstantSDNode>(N->getOperand(1));
  5151. if (!Mask)
  5152. return false;
  5153. if (!Mask->getAPIntValue().isMask())
  5154. return false;
  5155. // No need to do anything if the and directly uses a load.
  5156. if (isa<LoadSDNode>(N->getOperand(0)))
  5157. return false;
  5158. SmallVector<LoadSDNode*, 8> Loads;
  5159. SmallPtrSet<SDNode*, 2> NodesWithConsts;
  5160. SDNode *FixupNode = nullptr;
  5161. if (SearchForAndLoads(N, Loads, NodesWithConsts, Mask, FixupNode)) {
  5162. if (Loads.size() == 0)
  5163. return false;
  5164. LLVM_DEBUG(dbgs() << "Backwards propagate AND: "; N->dump());
  5165. SDValue MaskOp = N->getOperand(1);
  5166. // If it exists, fixup the single node we allow in the tree that needs
  5167. // masking.
  5168. if (FixupNode) {
  5169. LLVM_DEBUG(dbgs() << "First, need to fix up: "; FixupNode->dump());
  5170. SDValue And = DAG.getNode(ISD::AND, SDLoc(FixupNode),
  5171. FixupNode->getValueType(0),
  5172. SDValue(FixupNode, 0), MaskOp);
  5173. DAG.ReplaceAllUsesOfValueWith(SDValue(FixupNode, 0), And);
  5174. if (And.getOpcode() == ISD ::AND)
  5175. DAG.UpdateNodeOperands(And.getNode(), SDValue(FixupNode, 0), MaskOp);
  5176. }
  5177. // Narrow any constants that need it.
  5178. for (auto *LogicN : NodesWithConsts) {
  5179. SDValue Op0 = LogicN->getOperand(0);
  5180. SDValue Op1 = LogicN->getOperand(1);
  5181. if (isa<ConstantSDNode>(Op0))
  5182. std::swap(Op0, Op1);
  5183. SDValue And = DAG.getNode(ISD::AND, SDLoc(Op1), Op1.getValueType(),
  5184. Op1, MaskOp);
  5185. DAG.UpdateNodeOperands(LogicN, Op0, And);
  5186. }
  5187. // Create narrow loads.
  5188. for (auto *Load : Loads) {
  5189. LLVM_DEBUG(dbgs() << "Propagate AND back to: "; Load->dump());
  5190. SDValue And = DAG.getNode(ISD::AND, SDLoc(Load), Load->getValueType(0),
  5191. SDValue(Load, 0), MaskOp);
  5192. DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), And);
  5193. if (And.getOpcode() == ISD ::AND)
  5194. And = SDValue(
  5195. DAG.UpdateNodeOperands(And.getNode(), SDValue(Load, 0), MaskOp), 0);
  5196. SDValue NewLoad = reduceLoadWidth(And.getNode());
  5197. assert(NewLoad &&
  5198. "Shouldn't be masking the load if it can't be narrowed");
  5199. CombineTo(Load, NewLoad, NewLoad.getValue(1));
  5200. }
  5201. DAG.ReplaceAllUsesWith(N, N->getOperand(0).getNode());
  5202. return true;
  5203. }
  5204. return false;
  5205. }
  5206. // Unfold
  5207. // x & (-1 'logical shift' y)
  5208. // To
  5209. // (x 'opposite logical shift' y) 'logical shift' y
  5210. // if it is better for performance.
  5211. SDValue DAGCombiner::unfoldExtremeBitClearingToShifts(SDNode *N) {
  5212. assert(N->getOpcode() == ISD::AND);
  5213. SDValue N0 = N->getOperand(0);
  5214. SDValue N1 = N->getOperand(1);
  5215. // Do we actually prefer shifts over mask?
  5216. if (!TLI.shouldFoldMaskToVariableShiftPair(N0))
  5217. return SDValue();
  5218. // Try to match (-1 '[outer] logical shift' y)
  5219. unsigned OuterShift;
  5220. unsigned InnerShift; // The opposite direction to the OuterShift.
  5221. SDValue Y; // Shift amount.
  5222. auto matchMask = [&OuterShift, &InnerShift, &Y](SDValue M) -> bool {
  5223. if (!M.hasOneUse())
  5224. return false;
  5225. OuterShift = M->getOpcode();
  5226. if (OuterShift == ISD::SHL)
  5227. InnerShift = ISD::SRL;
  5228. else if (OuterShift == ISD::SRL)
  5229. InnerShift = ISD::SHL;
  5230. else
  5231. return false;
  5232. if (!isAllOnesConstant(M->getOperand(0)))
  5233. return false;
  5234. Y = M->getOperand(1);
  5235. return true;
  5236. };
  5237. SDValue X;
  5238. if (matchMask(N1))
  5239. X = N0;
  5240. else if (matchMask(N0))
  5241. X = N1;
  5242. else
  5243. return SDValue();
  5244. SDLoc DL(N);
  5245. EVT VT = N->getValueType(0);
  5246. // tmp = x 'opposite logical shift' y
  5247. SDValue T0 = DAG.getNode(InnerShift, DL, VT, X, Y);
  5248. // ret = tmp 'logical shift' y
  5249. SDValue T1 = DAG.getNode(OuterShift, DL, VT, T0, Y);
  5250. return T1;
  5251. }
  5252. /// Try to replace shift/logic that tests if a bit is clear with mask + setcc.
  5253. /// For a target with a bit test, this is expected to become test + set and save
  5254. /// at least 1 instruction.
  5255. static SDValue combineShiftAnd1ToBitTest(SDNode *And, SelectionDAG &DAG) {
  5256. assert(And->getOpcode() == ISD::AND && "Expected an 'and' op");
  5257. // This is probably not worthwhile without a supported type.
  5258. EVT VT = And->getValueType(0);
  5259. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  5260. if (!TLI.isTypeLegal(VT))
  5261. return SDValue();
  5262. // Look through an optional extension.
  5263. SDValue And0 = And->getOperand(0), And1 = And->getOperand(1);
  5264. if (And0.getOpcode() == ISD::ANY_EXTEND && And0.hasOneUse())
  5265. And0 = And0.getOperand(0);
  5266. if (!isOneConstant(And1) || !And0.hasOneUse())
  5267. return SDValue();
  5268. SDValue Src = And0;
  5269. // Attempt to find a 'not' op.
  5270. // TODO: Should we favor test+set even without the 'not' op?
  5271. bool FoundNot = false;
  5272. if (isBitwiseNot(Src)) {
  5273. FoundNot = true;
  5274. Src = Src.getOperand(0);
  5275. // Look though an optional truncation. The source operand may not be the
  5276. // same type as the original 'and', but that is ok because we are masking
  5277. // off everything but the low bit.
  5278. if (Src.getOpcode() == ISD::TRUNCATE && Src.hasOneUse())
  5279. Src = Src.getOperand(0);
  5280. }
  5281. // Match a shift-right by constant.
  5282. if (Src.getOpcode() != ISD::SRL || !Src.hasOneUse())
  5283. return SDValue();
  5284. // We might have looked through casts that make this transform invalid.
  5285. // TODO: If the source type is wider than the result type, do the mask and
  5286. // compare in the source type.
  5287. unsigned VTBitWidth = VT.getScalarSizeInBits();
  5288. SDValue ShiftAmt = Src.getOperand(1);
  5289. auto *ShiftAmtC = dyn_cast<ConstantSDNode>(ShiftAmt);
  5290. if (!ShiftAmtC || !ShiftAmtC->getAPIntValue().ult(VTBitWidth))
  5291. return SDValue();
  5292. // Set source to shift source.
  5293. Src = Src.getOperand(0);
  5294. // Try again to find a 'not' op.
  5295. // TODO: Should we favor test+set even with two 'not' ops?
  5296. if (!FoundNot) {
  5297. if (!isBitwiseNot(Src))
  5298. return SDValue();
  5299. Src = Src.getOperand(0);
  5300. }
  5301. if (!TLI.hasBitTest(Src, ShiftAmt))
  5302. return SDValue();
  5303. // Turn this into a bit-test pattern using mask op + setcc:
  5304. // and (not (srl X, C)), 1 --> (and X, 1<<C) == 0
  5305. // and (srl (not X), C)), 1 --> (and X, 1<<C) == 0
  5306. SDLoc DL(And);
  5307. SDValue X = DAG.getZExtOrTrunc(Src, DL, VT);
  5308. EVT CCVT = TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
  5309. SDValue Mask = DAG.getConstant(
  5310. APInt::getOneBitSet(VTBitWidth, ShiftAmtC->getZExtValue()), DL, VT);
  5311. SDValue NewAnd = DAG.getNode(ISD::AND, DL, VT, X, Mask);
  5312. SDValue Zero = DAG.getConstant(0, DL, VT);
  5313. SDValue Setcc = DAG.getSetCC(DL, CCVT, NewAnd, Zero, ISD::SETEQ);
  5314. return DAG.getZExtOrTrunc(Setcc, DL, VT);
  5315. }
  5316. /// For targets that support usubsat, match a bit-hack form of that operation
  5317. /// that ends in 'and' and convert it.
  5318. static SDValue foldAndToUsubsat(SDNode *N, SelectionDAG &DAG) {
  5319. SDValue N0 = N->getOperand(0);
  5320. SDValue N1 = N->getOperand(1);
  5321. EVT VT = N1.getValueType();
  5322. // Canonicalize SRA as operand 1.
  5323. if (N0.getOpcode() == ISD::SRA)
  5324. std::swap(N0, N1);
  5325. // xor/add with SMIN (signmask) are logically equivalent.
  5326. if (N0.getOpcode() != ISD::XOR && N0.getOpcode() != ISD::ADD)
  5327. return SDValue();
  5328. if (N1.getOpcode() != ISD::SRA || !N0.hasOneUse() || !N1.hasOneUse() ||
  5329. N0.getOperand(0) != N1.getOperand(0))
  5330. return SDValue();
  5331. unsigned BitWidth = VT.getScalarSizeInBits();
  5332. ConstantSDNode *XorC = isConstOrConstSplat(N0.getOperand(1), true);
  5333. ConstantSDNode *SraC = isConstOrConstSplat(N1.getOperand(1), true);
  5334. if (!XorC || !XorC->getAPIntValue().isSignMask() ||
  5335. !SraC || SraC->getAPIntValue() != BitWidth - 1)
  5336. return SDValue();
  5337. // (i8 X ^ 128) & (i8 X s>> 7) --> usubsat X, 128
  5338. // (i8 X + 128) & (i8 X s>> 7) --> usubsat X, 128
  5339. SDLoc DL(N);
  5340. SDValue SignMask = DAG.getConstant(XorC->getAPIntValue(), DL, VT);
  5341. return DAG.getNode(ISD::USUBSAT, DL, VT, N0.getOperand(0), SignMask);
  5342. }
  5343. /// Given a bitwise logic operation N with a matching bitwise logic operand,
  5344. /// fold a pattern where 2 of the source operands are identically shifted
  5345. /// values. For example:
  5346. /// ((X0 << Y) | Z) | (X1 << Y) --> ((X0 | X1) << Y) | Z
  5347. static SDValue foldLogicOfShifts(SDNode *N, SDValue LogicOp, SDValue ShiftOp,
  5348. SelectionDAG &DAG) {
  5349. unsigned LogicOpcode = N->getOpcode();
  5350. assert((LogicOpcode == ISD::AND || LogicOpcode == ISD::OR ||
  5351. LogicOpcode == ISD::XOR)
  5352. && "Expected bitwise logic operation");
  5353. if (!LogicOp.hasOneUse() || !ShiftOp.hasOneUse())
  5354. return SDValue();
  5355. // Match another bitwise logic op and a shift.
  5356. unsigned ShiftOpcode = ShiftOp.getOpcode();
  5357. if (LogicOp.getOpcode() != LogicOpcode ||
  5358. !(ShiftOpcode == ISD::SHL || ShiftOpcode == ISD::SRL ||
  5359. ShiftOpcode == ISD::SRA))
  5360. return SDValue();
  5361. // Match another shift op inside the first logic operand. Handle both commuted
  5362. // possibilities.
  5363. // LOGIC (LOGIC (SH X0, Y), Z), (SH X1, Y) --> LOGIC (SH (LOGIC X0, X1), Y), Z
  5364. // LOGIC (LOGIC Z, (SH X0, Y)), (SH X1, Y) --> LOGIC (SH (LOGIC X0, X1), Y), Z
  5365. SDValue X1 = ShiftOp.getOperand(0);
  5366. SDValue Y = ShiftOp.getOperand(1);
  5367. SDValue X0, Z;
  5368. if (LogicOp.getOperand(0).getOpcode() == ShiftOpcode &&
  5369. LogicOp.getOperand(0).getOperand(1) == Y) {
  5370. X0 = LogicOp.getOperand(0).getOperand(0);
  5371. Z = LogicOp.getOperand(1);
  5372. } else if (LogicOp.getOperand(1).getOpcode() == ShiftOpcode &&
  5373. LogicOp.getOperand(1).getOperand(1) == Y) {
  5374. X0 = LogicOp.getOperand(1).getOperand(0);
  5375. Z = LogicOp.getOperand(0);
  5376. } else {
  5377. return SDValue();
  5378. }
  5379. EVT VT = N->getValueType(0);
  5380. SDLoc DL(N);
  5381. SDValue LogicX = DAG.getNode(LogicOpcode, DL, VT, X0, X1);
  5382. SDValue NewShift = DAG.getNode(ShiftOpcode, DL, VT, LogicX, Y);
  5383. return DAG.getNode(LogicOpcode, DL, VT, NewShift, Z);
  5384. }
  5385. /// Given a tree of logic operations with shape like
  5386. /// (LOGIC (LOGIC (X, Y), LOGIC (Z, Y)))
  5387. /// try to match and fold shift operations with the same shift amount.
  5388. /// For example:
  5389. /// LOGIC (LOGIC (SH X0, Y), Z), (LOGIC (SH X1, Y), W) -->
  5390. /// --> LOGIC (SH (LOGIC X0, X1), Y), (LOGIC Z, W)
  5391. static SDValue foldLogicTreeOfShifts(SDNode *N, SDValue LeftHand,
  5392. SDValue RightHand, SelectionDAG &DAG) {
  5393. unsigned LogicOpcode = N->getOpcode();
  5394. assert((LogicOpcode == ISD::AND || LogicOpcode == ISD::OR ||
  5395. LogicOpcode == ISD::XOR));
  5396. if (LeftHand.getOpcode() != LogicOpcode ||
  5397. RightHand.getOpcode() != LogicOpcode)
  5398. return SDValue();
  5399. if (!LeftHand.hasOneUse() || !RightHand.hasOneUse())
  5400. return SDValue();
  5401. // Try to match one of following patterns:
  5402. // LOGIC (LOGIC (SH X0, Y), Z), (LOGIC (SH X1, Y), W)
  5403. // LOGIC (LOGIC (SH X0, Y), Z), (LOGIC W, (SH X1, Y))
  5404. // Note that foldLogicOfShifts will handle commuted versions of the left hand
  5405. // itself.
  5406. SDValue CombinedShifts, W;
  5407. SDValue R0 = RightHand.getOperand(0);
  5408. SDValue R1 = RightHand.getOperand(1);
  5409. if ((CombinedShifts = foldLogicOfShifts(N, LeftHand, R0, DAG)))
  5410. W = R1;
  5411. else if ((CombinedShifts = foldLogicOfShifts(N, LeftHand, R1, DAG)))
  5412. W = R0;
  5413. else
  5414. return SDValue();
  5415. EVT VT = N->getValueType(0);
  5416. SDLoc DL(N);
  5417. return DAG.getNode(LogicOpcode, DL, VT, CombinedShifts, W);
  5418. }
  5419. SDValue DAGCombiner::visitAND(SDNode *N) {
  5420. SDValue N0 = N->getOperand(0);
  5421. SDValue N1 = N->getOperand(1);
  5422. EVT VT = N1.getValueType();
  5423. // x & x --> x
  5424. if (N0 == N1)
  5425. return N0;
  5426. // fold (and c1, c2) -> c1&c2
  5427. if (SDValue C = DAG.FoldConstantArithmetic(ISD::AND, SDLoc(N), VT, {N0, N1}))
  5428. return C;
  5429. // canonicalize constant to RHS
  5430. if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
  5431. !DAG.isConstantIntBuildVectorOrConstantInt(N1))
  5432. return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
  5433. // fold vector ops
  5434. if (VT.isVector()) {
  5435. if (SDValue FoldedVOp = SimplifyVBinOp(N, SDLoc(N)))
  5436. return FoldedVOp;
  5437. // fold (and x, 0) -> 0, vector edition
  5438. if (ISD::isConstantSplatVectorAllZeros(N1.getNode()))
  5439. // do not return N1, because undef node may exist in N1
  5440. return DAG.getConstant(APInt::getZero(N1.getScalarValueSizeInBits()),
  5441. SDLoc(N), N1.getValueType());
  5442. // fold (and x, -1) -> x, vector edition
  5443. if (ISD::isConstantSplatVectorAllOnes(N1.getNode()))
  5444. return N0;
  5445. // fold (and (masked_load) (splat_vec (x, ...))) to zext_masked_load
  5446. auto *MLoad = dyn_cast<MaskedLoadSDNode>(N0);
  5447. ConstantSDNode *Splat = isConstOrConstSplat(N1, true, true);
  5448. if (MLoad && MLoad->getExtensionType() == ISD::EXTLOAD && Splat &&
  5449. N1.hasOneUse()) {
  5450. EVT LoadVT = MLoad->getMemoryVT();
  5451. EVT ExtVT = VT;
  5452. if (TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT, LoadVT)) {
  5453. // For this AND to be a zero extension of the masked load the elements
  5454. // of the BuildVec must mask the bottom bits of the extended element
  5455. // type
  5456. uint64_t ElementSize =
  5457. LoadVT.getVectorElementType().getScalarSizeInBits();
  5458. if (Splat->getAPIntValue().isMask(ElementSize)) {
  5459. auto NewLoad = DAG.getMaskedLoad(
  5460. ExtVT, SDLoc(N), MLoad->getChain(), MLoad->getBasePtr(),
  5461. MLoad->getOffset(), MLoad->getMask(), MLoad->getPassThru(),
  5462. LoadVT, MLoad->getMemOperand(), MLoad->getAddressingMode(),
  5463. ISD::ZEXTLOAD, MLoad->isExpandingLoad());
  5464. bool LoadHasOtherUsers = !N0.hasOneUse();
  5465. CombineTo(N, NewLoad);
  5466. if (LoadHasOtherUsers)
  5467. CombineTo(MLoad, NewLoad.getValue(0), NewLoad.getValue(1));
  5468. return SDValue(N, 0);
  5469. }
  5470. }
  5471. }
  5472. }
  5473. // fold (and x, -1) -> x
  5474. if (isAllOnesConstant(N1))
  5475. return N0;
  5476. // if (and x, c) is known to be zero, return 0
  5477. unsigned BitWidth = VT.getScalarSizeInBits();
  5478. ConstantSDNode *N1C = isConstOrConstSplat(N1);
  5479. if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0), APInt::getAllOnes(BitWidth)))
  5480. return DAG.getConstant(0, SDLoc(N), VT);
  5481. if (SDValue NewSel = foldBinOpIntoSelect(N))
  5482. return NewSel;
  5483. // reassociate and
  5484. if (SDValue RAND = reassociateOps(ISD::AND, SDLoc(N), N0, N1, N->getFlags()))
  5485. return RAND;
  5486. // fold (and (or x, C), D) -> D if (C & D) == D
  5487. auto MatchSubset = [](ConstantSDNode *LHS, ConstantSDNode *RHS) {
  5488. return RHS->getAPIntValue().isSubsetOf(LHS->getAPIntValue());
  5489. };
  5490. if (N0.getOpcode() == ISD::OR &&
  5491. ISD::matchBinaryPredicate(N0.getOperand(1), N1, MatchSubset))
  5492. return N1;
  5493. // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
  5494. if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
  5495. SDValue N0Op0 = N0.getOperand(0);
  5496. APInt Mask = ~N1C->getAPIntValue();
  5497. Mask = Mask.trunc(N0Op0.getScalarValueSizeInBits());
  5498. if (DAG.MaskedValueIsZero(N0Op0, Mask))
  5499. return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), N0.getValueType(), N0Op0);
  5500. }
  5501. // fold (and (ext (and V, c1)), c2) -> (and (ext V), (and c1, (ext c2)))
  5502. if (ISD::isExtOpcode(N0.getOpcode())) {
  5503. unsigned ExtOpc = N0.getOpcode();
  5504. SDValue N0Op0 = N0.getOperand(0);
  5505. if (N0Op0.getOpcode() == ISD::AND &&
  5506. (ExtOpc != ISD::ZERO_EXTEND || !TLI.isZExtFree(N0Op0, VT)) &&
  5507. DAG.isConstantIntBuildVectorOrConstantInt(N1) &&
  5508. DAG.isConstantIntBuildVectorOrConstantInt(N0Op0.getOperand(1)) &&
  5509. N0->hasOneUse() && N0Op0->hasOneUse()) {
  5510. SDLoc DL(N);
  5511. SDValue NewMask =
  5512. DAG.getNode(ISD::AND, DL, VT, N1,
  5513. DAG.getNode(ExtOpc, DL, VT, N0Op0.getOperand(1)));
  5514. return DAG.getNode(ISD::AND, DL, VT,
  5515. DAG.getNode(ExtOpc, DL, VT, N0Op0.getOperand(0)),
  5516. NewMask);
  5517. }
  5518. }
  5519. // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
  5520. // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
  5521. // already be zero by virtue of the width of the base type of the load.
  5522. //
  5523. // the 'X' node here can either be nothing or an extract_vector_elt to catch
  5524. // more cases.
  5525. if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
  5526. N0.getValueSizeInBits() == N0.getOperand(0).getScalarValueSizeInBits() &&
  5527. N0.getOperand(0).getOpcode() == ISD::LOAD &&
  5528. N0.getOperand(0).getResNo() == 0) ||
  5529. (N0.getOpcode() == ISD::LOAD && N0.getResNo() == 0)) {
  5530. LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
  5531. N0 : N0.getOperand(0) );
  5532. // Get the constant (if applicable) the zero'th operand is being ANDed with.
  5533. // This can be a pure constant or a vector splat, in which case we treat the
  5534. // vector as a scalar and use the splat value.
  5535. APInt Constant = APInt::getZero(1);
  5536. if (const ConstantSDNode *C = isConstOrConstSplat(
  5537. N1, /*AllowUndef=*/false, /*AllowTruncation=*/true)) {
  5538. Constant = C->getAPIntValue();
  5539. } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
  5540. APInt SplatValue, SplatUndef;
  5541. unsigned SplatBitSize;
  5542. bool HasAnyUndefs;
  5543. bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
  5544. SplatBitSize, HasAnyUndefs);
  5545. if (IsSplat) {
  5546. // Undef bits can contribute to a possible optimisation if set, so
  5547. // set them.
  5548. SplatValue |= SplatUndef;
  5549. // The splat value may be something like "0x00FFFFFF", which means 0 for
  5550. // the first vector value and FF for the rest, repeating. We need a mask
  5551. // that will apply equally to all members of the vector, so AND all the
  5552. // lanes of the constant together.
  5553. unsigned EltBitWidth = Vector->getValueType(0).getScalarSizeInBits();
  5554. // If the splat value has been compressed to a bitlength lower
  5555. // than the size of the vector lane, we need to re-expand it to
  5556. // the lane size.
  5557. if (EltBitWidth > SplatBitSize)
  5558. for (SplatValue = SplatValue.zextOrTrunc(EltBitWidth);
  5559. SplatBitSize < EltBitWidth; SplatBitSize = SplatBitSize * 2)
  5560. SplatValue |= SplatValue.shl(SplatBitSize);
  5561. // Make sure that variable 'Constant' is only set if 'SplatBitSize' is a
  5562. // multiple of 'BitWidth'. Otherwise, we could propagate a wrong value.
  5563. if ((SplatBitSize % EltBitWidth) == 0) {
  5564. Constant = APInt::getAllOnes(EltBitWidth);
  5565. for (unsigned i = 0, n = (SplatBitSize / EltBitWidth); i < n; ++i)
  5566. Constant &= SplatValue.extractBits(EltBitWidth, i * EltBitWidth);
  5567. }
  5568. }
  5569. }
  5570. // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
  5571. // actually legal and isn't going to get expanded, else this is a false
  5572. // optimisation.
  5573. bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
  5574. Load->getValueType(0),
  5575. Load->getMemoryVT());
  5576. // Resize the constant to the same size as the original memory access before
  5577. // extension. If it is still the AllOnesValue then this AND is completely
  5578. // unneeded.
  5579. Constant = Constant.zextOrTrunc(Load->getMemoryVT().getScalarSizeInBits());
  5580. bool B;
  5581. switch (Load->getExtensionType()) {
  5582. default: B = false; break;
  5583. case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
  5584. case ISD::ZEXTLOAD:
  5585. case ISD::NON_EXTLOAD: B = true; break;
  5586. }
  5587. if (B && Constant.isAllOnes()) {
  5588. // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
  5589. // preserve semantics once we get rid of the AND.
  5590. SDValue NewLoad(Load, 0);
  5591. // Fold the AND away. NewLoad may get replaced immediately.
  5592. CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
  5593. if (Load->getExtensionType() == ISD::EXTLOAD) {
  5594. NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
  5595. Load->getValueType(0), SDLoc(Load),
  5596. Load->getChain(), Load->getBasePtr(),
  5597. Load->getOffset(), Load->getMemoryVT(),
  5598. Load->getMemOperand());
  5599. // Replace uses of the EXTLOAD with the new ZEXTLOAD.
  5600. if (Load->getNumValues() == 3) {
  5601. // PRE/POST_INC loads have 3 values.
  5602. SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
  5603. NewLoad.getValue(2) };
  5604. CombineTo(Load, To, 3, true);
  5605. } else {
  5606. CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
  5607. }
  5608. }
  5609. return SDValue(N, 0); // Return N so it doesn't get rechecked!
  5610. }
  5611. }
  5612. // Try to convert a constant mask AND into a shuffle clear mask.
  5613. if (VT.isVector())
  5614. if (SDValue Shuffle = XformToShuffleWithZero(N))
  5615. return Shuffle;
  5616. if (SDValue Combined = combineCarryDiamond(DAG, TLI, N0, N1, N))
  5617. return Combined;
  5618. if (N0.getOpcode() == ISD::EXTRACT_SUBVECTOR && N0.hasOneUse() && N1C &&
  5619. ISD::isExtOpcode(N0.getOperand(0).getOpcode())) {
  5620. SDValue Ext = N0.getOperand(0);
  5621. EVT ExtVT = Ext->getValueType(0);
  5622. SDValue Extendee = Ext->getOperand(0);
  5623. unsigned ScalarWidth = Extendee.getValueType().getScalarSizeInBits();
  5624. if (N1C->getAPIntValue().isMask(ScalarWidth) &&
  5625. (!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, ExtVT))) {
  5626. // (and (extract_subvector (zext|anyext|sext v) _) iN_mask)
  5627. // => (extract_subvector (iN_zeroext v))
  5628. SDValue ZeroExtExtendee =
  5629. DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), ExtVT, Extendee);
  5630. return DAG.getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(N), VT, ZeroExtExtendee,
  5631. N0.getOperand(1));
  5632. }
  5633. }
  5634. // fold (and (masked_gather x)) -> (zext_masked_gather x)
  5635. if (auto *GN0 = dyn_cast<MaskedGatherSDNode>(N0)) {
  5636. EVT MemVT = GN0->getMemoryVT();
  5637. EVT ScalarVT = MemVT.getScalarType();
  5638. if (SDValue(GN0, 0).hasOneUse() &&
  5639. isConstantSplatVectorMaskForType(N1.getNode(), ScalarVT) &&
  5640. TLI.isVectorLoadExtDesirable(SDValue(SDValue(GN0, 0)))) {
  5641. SDValue Ops[] = {GN0->getChain(), GN0->getPassThru(), GN0->getMask(),
  5642. GN0->getBasePtr(), GN0->getIndex(), GN0->getScale()};
  5643. SDValue ZExtLoad = DAG.getMaskedGather(
  5644. DAG.getVTList(VT, MVT::Other), MemVT, SDLoc(N), Ops,
  5645. GN0->getMemOperand(), GN0->getIndexType(), ISD::ZEXTLOAD);
  5646. CombineTo(N, ZExtLoad);
  5647. AddToWorklist(ZExtLoad.getNode());
  5648. // Avoid recheck of N.
  5649. return SDValue(N, 0);
  5650. }
  5651. }
  5652. // fold (and (load x), 255) -> (zextload x, i8)
  5653. // fold (and (extload x, i16), 255) -> (zextload x, i8)
  5654. if (N1C && N0.getOpcode() == ISD::LOAD && !VT.isVector())
  5655. if (SDValue Res = reduceLoadWidth(N))
  5656. return Res;
  5657. if (LegalTypes) {
  5658. // Attempt to propagate the AND back up to the leaves which, if they're
  5659. // loads, can be combined to narrow loads and the AND node can be removed.
  5660. // Perform after legalization so that extend nodes will already be
  5661. // combined into the loads.
  5662. if (BackwardsPropagateMask(N))
  5663. return SDValue(N, 0);
  5664. }
  5665. if (SDValue Combined = visitANDLike(N0, N1, N))
  5666. return Combined;
  5667. // Simplify: (and (op x...), (op y...)) -> (op (and x, y))
  5668. if (N0.getOpcode() == N1.getOpcode())
  5669. if (SDValue V = hoistLogicOpWithSameOpcodeHands(N))
  5670. return V;
  5671. if (SDValue R = foldLogicOfShifts(N, N0, N1, DAG))
  5672. return R;
  5673. if (SDValue R = foldLogicOfShifts(N, N1, N0, DAG))
  5674. return R;
  5675. // Masking the negated extension of a boolean is just the zero-extended
  5676. // boolean:
  5677. // and (sub 0, zext(bool X)), 1 --> zext(bool X)
  5678. // and (sub 0, sext(bool X)), 1 --> zext(bool X)
  5679. //
  5680. // Note: the SimplifyDemandedBits fold below can make an information-losing
  5681. // transform, and then we have no way to find this better fold.
  5682. if (N1C && N1C->isOne() && N0.getOpcode() == ISD::SUB) {
  5683. if (isNullOrNullSplat(N0.getOperand(0))) {
  5684. SDValue SubRHS = N0.getOperand(1);
  5685. if (SubRHS.getOpcode() == ISD::ZERO_EXTEND &&
  5686. SubRHS.getOperand(0).getScalarValueSizeInBits() == 1)
  5687. return SubRHS;
  5688. if (SubRHS.getOpcode() == ISD::SIGN_EXTEND &&
  5689. SubRHS.getOperand(0).getScalarValueSizeInBits() == 1)
  5690. return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, SubRHS.getOperand(0));
  5691. }
  5692. }
  5693. // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
  5694. // fold (and (sra)) -> (and (srl)) when possible.
  5695. if (SimplifyDemandedBits(SDValue(N, 0)))
  5696. return SDValue(N, 0);
  5697. // fold (zext_inreg (extload x)) -> (zextload x)
  5698. // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
  5699. if (ISD::isUNINDEXEDLoad(N0.getNode()) &&
  5700. (ISD::isEXTLoad(N0.getNode()) ||
  5701. (ISD::isSEXTLoad(N0.getNode()) && N0.hasOneUse()))) {
  5702. LoadSDNode *LN0 = cast<LoadSDNode>(N0);
  5703. EVT MemVT = LN0->getMemoryVT();
  5704. // If we zero all the possible extended bits, then we can turn this into
  5705. // a zextload if we are running before legalize or the operation is legal.
  5706. unsigned ExtBitSize = N1.getScalarValueSizeInBits();
  5707. unsigned MemBitSize = MemVT.getScalarSizeInBits();
  5708. APInt ExtBits = APInt::getHighBitsSet(ExtBitSize, ExtBitSize - MemBitSize);
  5709. if (DAG.MaskedValueIsZero(N1, ExtBits) &&
  5710. ((!LegalOperations && LN0->isSimple()) ||
  5711. TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
  5712. SDValue ExtLoad =
  5713. DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT, LN0->getChain(),
  5714. LN0->getBasePtr(), MemVT, LN0->getMemOperand());
  5715. AddToWorklist(N);
  5716. CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
  5717. return SDValue(N, 0); // Return N so it doesn't get rechecked!
  5718. }
  5719. }
  5720. // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
  5721. if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
  5722. if (SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
  5723. N0.getOperand(1), false))
  5724. return BSwap;
  5725. }
  5726. if (SDValue Shifts = unfoldExtremeBitClearingToShifts(N))
  5727. return Shifts;
  5728. if (SDValue V = combineShiftAnd1ToBitTest(N, DAG))
  5729. return V;
  5730. // Recognize the following pattern:
  5731. //
  5732. // AndVT = (and (sign_extend NarrowVT to AndVT) #bitmask)
  5733. //
  5734. // where bitmask is a mask that clears the upper bits of AndVT. The
  5735. // number of bits in bitmask must be a power of two.
  5736. auto IsAndZeroExtMask = [](SDValue LHS, SDValue RHS) {
  5737. if (LHS->getOpcode() != ISD::SIGN_EXTEND)
  5738. return false;
  5739. auto *C = dyn_cast<ConstantSDNode>(RHS);
  5740. if (!C)
  5741. return false;
  5742. if (!C->getAPIntValue().isMask(
  5743. LHS.getOperand(0).getValueType().getFixedSizeInBits()))
  5744. return false;
  5745. return true;
  5746. };
  5747. // Replace (and (sign_extend ...) #bitmask) with (zero_extend ...).
  5748. if (IsAndZeroExtMask(N0, N1))
  5749. return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0.getOperand(0));
  5750. if (hasOperation(ISD::USUBSAT, VT))
  5751. if (SDValue V = foldAndToUsubsat(N, DAG))
  5752. return V;
  5753. // Postpone until legalization completed to avoid interference with bswap
  5754. // folding
  5755. if (LegalOperations || VT.isVector())
  5756. if (SDValue R = foldLogicTreeOfShifts(N, N0, N1, DAG))
  5757. return R;
  5758. return SDValue();
  5759. }
  5760. /// Match (a >> 8) | (a << 8) as (bswap a) >> 16.
  5761. SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
  5762. bool DemandHighBits) {
  5763. if (!LegalOperations)
  5764. return SDValue();
  5765. EVT VT = N->getValueType(0);
  5766. if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
  5767. return SDValue();
  5768. if (!TLI.isOperationLegalOrCustom(ISD::BSWAP, VT))
  5769. return SDValue();
  5770. // Recognize (and (shl a, 8), 0xff00), (and (srl a, 8), 0xff)
  5771. bool LookPassAnd0 = false;
  5772. bool LookPassAnd1 = false;
  5773. if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
  5774. std::swap(N0, N1);
  5775. if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
  5776. std::swap(N0, N1);
  5777. if (N0.getOpcode() == ISD::AND) {
  5778. if (!N0->hasOneUse())
  5779. return SDValue();
  5780. ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
  5781. // Also handle 0xffff since the LHS is guaranteed to have zeros there.
  5782. // This is needed for X86.
  5783. if (!N01C || (N01C->getZExtValue() != 0xFF00 &&
  5784. N01C->getZExtValue() != 0xFFFF))
  5785. return SDValue();
  5786. N0 = N0.getOperand(0);
  5787. LookPassAnd0 = true;
  5788. }
  5789. if (N1.getOpcode() == ISD::AND) {
  5790. if (!N1->hasOneUse())
  5791. return SDValue();
  5792. ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
  5793. if (!N11C || N11C->getZExtValue() != 0xFF)
  5794. return SDValue();
  5795. N1 = N1.getOperand(0);
  5796. LookPassAnd1 = true;
  5797. }
  5798. if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
  5799. std::swap(N0, N1);
  5800. if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
  5801. return SDValue();
  5802. if (!N0->hasOneUse() || !N1->hasOneUse())
  5803. return SDValue();
  5804. ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
  5805. ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
  5806. if (!N01C || !N11C)
  5807. return SDValue();
  5808. if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
  5809. return SDValue();
  5810. // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
  5811. SDValue N00 = N0->getOperand(0);
  5812. if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
  5813. if (!N00->hasOneUse())
  5814. return SDValue();
  5815. ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
  5816. if (!N001C || N001C->getZExtValue() != 0xFF)
  5817. return SDValue();
  5818. N00 = N00.getOperand(0);
  5819. LookPassAnd0 = true;
  5820. }
  5821. SDValue N10 = N1->getOperand(0);
  5822. if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
  5823. if (!N10->hasOneUse())
  5824. return SDValue();
  5825. ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
  5826. // Also allow 0xFFFF since the bits will be shifted out. This is needed
  5827. // for X86.
  5828. if (!N101C || (N101C->getZExtValue() != 0xFF00 &&
  5829. N101C->getZExtValue() != 0xFFFF))
  5830. return SDValue();
  5831. N10 = N10.getOperand(0);
  5832. LookPassAnd1 = true;
  5833. }
  5834. if (N00 != N10)
  5835. return SDValue();
  5836. // Make sure everything beyond the low halfword gets set to zero since the SRL
  5837. // 16 will clear the top bits.
  5838. unsigned OpSizeInBits = VT.getSizeInBits();
  5839. if (OpSizeInBits > 16) {
  5840. // If the left-shift isn't masked out then the only way this is a bswap is
  5841. // if all bits beyond the low 8 are 0. In that case the entire pattern
  5842. // reduces to a left shift anyway: leave it for other parts of the combiner.
  5843. if (DemandHighBits && !LookPassAnd0)
  5844. return SDValue();
  5845. // However, if the right shift isn't masked out then it might be because
  5846. // it's not needed. See if we can spot that too. If the high bits aren't
  5847. // demanded, we only need bits 23:16 to be zero. Otherwise, we need all
  5848. // upper bits to be zero.
  5849. if (!LookPassAnd1) {
  5850. unsigned HighBit = DemandHighBits ? OpSizeInBits : 24;
  5851. if (!DAG.MaskedValueIsZero(N10,
  5852. APInt::getBitsSet(OpSizeInBits, 16, HighBit)))
  5853. return SDValue();
  5854. }
  5855. }
  5856. SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
  5857. if (OpSizeInBits > 16) {
  5858. SDLoc DL(N);
  5859. Res = DAG.getNode(ISD::SRL, DL, VT, Res,
  5860. DAG.getConstant(OpSizeInBits - 16, DL,
  5861. getShiftAmountTy(VT)));
  5862. }
  5863. return Res;
  5864. }
  5865. /// Return true if the specified node is an element that makes up a 32-bit
  5866. /// packed halfword byteswap.
  5867. /// ((x & 0x000000ff) << 8) |
  5868. /// ((x & 0x0000ff00) >> 8) |
  5869. /// ((x & 0x00ff0000) << 8) |
  5870. /// ((x & 0xff000000) >> 8)
  5871. static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) {
  5872. if (!N->hasOneUse())
  5873. return false;
  5874. unsigned Opc = N.getOpcode();
  5875. if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
  5876. return false;
  5877. SDValue N0 = N.getOperand(0);
  5878. unsigned Opc0 = N0.getOpcode();
  5879. if (Opc0 != ISD::AND && Opc0 != ISD::SHL && Opc0 != ISD::SRL)
  5880. return false;
  5881. ConstantSDNode *N1C = nullptr;
  5882. // SHL or SRL: look upstream for AND mask operand
  5883. if (Opc == ISD::AND)
  5884. N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
  5885. else if (Opc0 == ISD::AND)
  5886. N1C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
  5887. if (!N1C)
  5888. return false;
  5889. unsigned MaskByteOffset;
  5890. switch (N1C->getZExtValue()) {
  5891. default:
  5892. return false;
  5893. case 0xFF: MaskByteOffset = 0; break;
  5894. case 0xFF00: MaskByteOffset = 1; break;
  5895. case 0xFFFF:
  5896. // In case demanded bits didn't clear the bits that will be shifted out.
  5897. // This is needed for X86.
  5898. if (Opc == ISD::SRL || (Opc == ISD::AND && Opc0 == ISD::SHL)) {
  5899. MaskByteOffset = 1;
  5900. break;
  5901. }
  5902. return false;
  5903. case 0xFF0000: MaskByteOffset = 2; break;
  5904. case 0xFF000000: MaskByteOffset = 3; break;
  5905. }
  5906. // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
  5907. if (Opc == ISD::AND) {
  5908. if (MaskByteOffset == 0 || MaskByteOffset == 2) {
  5909. // (x >> 8) & 0xff
  5910. // (x >> 8) & 0xff0000
  5911. if (Opc0 != ISD::SRL)
  5912. return false;
  5913. ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
  5914. if (!C || C->getZExtValue() != 8)
  5915. return false;
  5916. } else {
  5917. // (x << 8) & 0xff00
  5918. // (x << 8) & 0xff000000
  5919. if (Opc0 != ISD::SHL)
  5920. return false;
  5921. ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
  5922. if (!C || C->getZExtValue() != 8)
  5923. return false;
  5924. }
  5925. } else if (Opc == ISD::SHL) {
  5926. // (x & 0xff) << 8
  5927. // (x & 0xff0000) << 8
  5928. if (MaskByteOffset != 0 && MaskByteOffset != 2)
  5929. return false;
  5930. ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
  5931. if (!C || C->getZExtValue() != 8)
  5932. return false;
  5933. } else { // Opc == ISD::SRL
  5934. // (x & 0xff00) >> 8
  5935. // (x & 0xff000000) >> 8
  5936. if (MaskByteOffset != 1 && MaskByteOffset != 3)
  5937. return false;
  5938. ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
  5939. if (!C || C->getZExtValue() != 8)
  5940. return false;
  5941. }
  5942. if (Parts[MaskByteOffset])
  5943. return false;
  5944. Parts[MaskByteOffset] = N0.getOperand(0).getNode();
  5945. return true;
  5946. }
  5947. // Match 2 elements of a packed halfword bswap.
  5948. static bool isBSwapHWordPair(SDValue N, MutableArrayRef<SDNode *> Parts) {
  5949. if (N.getOpcode() == ISD::OR)
  5950. return isBSwapHWordElement(N.getOperand(0), Parts) &&
  5951. isBSwapHWordElement(N.getOperand(1), Parts);
  5952. if (N.getOpcode() == ISD::SRL && N.getOperand(0).getOpcode() == ISD::BSWAP) {
  5953. ConstantSDNode *C = isConstOrConstSplat(N.getOperand(1));
  5954. if (!C || C->getAPIntValue() != 16)
  5955. return false;
  5956. Parts[0] = Parts[1] = N.getOperand(0).getOperand(0).getNode();
  5957. return true;
  5958. }
  5959. return false;
  5960. }
  5961. // Match this pattern:
  5962. // (or (and (shl (A, 8)), 0xff00ff00), (and (srl (A, 8)), 0x00ff00ff))
  5963. // And rewrite this to:
  5964. // (rotr (bswap A), 16)
  5965. static SDValue matchBSwapHWordOrAndAnd(const TargetLowering &TLI,
  5966. SelectionDAG &DAG, SDNode *N, SDValue N0,
  5967. SDValue N1, EVT VT, EVT ShiftAmountTy) {
  5968. assert(N->getOpcode() == ISD::OR && VT == MVT::i32 &&
  5969. "MatchBSwapHWordOrAndAnd: expecting i32");
  5970. if (!TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
  5971. return SDValue();
  5972. if (N0.getOpcode() != ISD::AND || N1.getOpcode() != ISD::AND)
  5973. return SDValue();
  5974. // TODO: this is too restrictive; lifting this restriction requires more tests
  5975. if (!N0->hasOneUse() || !N1->hasOneUse())
  5976. return SDValue();
  5977. ConstantSDNode *Mask0 = isConstOrConstSplat(N0.getOperand(1));
  5978. ConstantSDNode *Mask1 = isConstOrConstSplat(N1.getOperand(1));
  5979. if (!Mask0 || !Mask1)
  5980. return SDValue();
  5981. if (Mask0->getAPIntValue() != 0xff00ff00 ||
  5982. Mask1->getAPIntValue() != 0x00ff00ff)
  5983. return SDValue();
  5984. SDValue Shift0 = N0.getOperand(0);
  5985. SDValue Shift1 = N1.getOperand(0);
  5986. if (Shift0.getOpcode() != ISD::SHL || Shift1.getOpcode() != ISD::SRL)
  5987. return SDValue();
  5988. ConstantSDNode *ShiftAmt0 = isConstOrConstSplat(Shift0.getOperand(1));
  5989. ConstantSDNode *ShiftAmt1 = isConstOrConstSplat(Shift1.getOperand(1));
  5990. if (!ShiftAmt0 || !ShiftAmt1)
  5991. return SDValue();
  5992. if (ShiftAmt0->getAPIntValue() != 8 || ShiftAmt1->getAPIntValue() != 8)
  5993. return SDValue();
  5994. if (Shift0.getOperand(0) != Shift1.getOperand(0))
  5995. return SDValue();
  5996. SDLoc DL(N);
  5997. SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT, Shift0.getOperand(0));
  5998. SDValue ShAmt = DAG.getConstant(16, DL, ShiftAmountTy);
  5999. return DAG.getNode(ISD::ROTR, DL, VT, BSwap, ShAmt);
  6000. }
  6001. /// Match a 32-bit packed halfword bswap. That is
  6002. /// ((x & 0x000000ff) << 8) |
  6003. /// ((x & 0x0000ff00) >> 8) |
  6004. /// ((x & 0x00ff0000) << 8) |
  6005. /// ((x & 0xff000000) >> 8)
  6006. /// => (rotl (bswap x), 16)
  6007. SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
  6008. if (!LegalOperations)
  6009. return SDValue();
  6010. EVT VT = N->getValueType(0);
  6011. if (VT != MVT::i32)
  6012. return SDValue();
  6013. if (!TLI.isOperationLegalOrCustom(ISD::BSWAP, VT))
  6014. return SDValue();
  6015. if (SDValue BSwap = matchBSwapHWordOrAndAnd(TLI, DAG, N, N0, N1, VT,
  6016. getShiftAmountTy(VT)))
  6017. return BSwap;
  6018. // Try again with commuted operands.
  6019. if (SDValue BSwap = matchBSwapHWordOrAndAnd(TLI, DAG, N, N1, N0, VT,
  6020. getShiftAmountTy(VT)))
  6021. return BSwap;
  6022. // Look for either
  6023. // (or (bswaphpair), (bswaphpair))
  6024. // (or (or (bswaphpair), (and)), (and))
  6025. // (or (or (and), (bswaphpair)), (and))
  6026. SDNode *Parts[4] = {};
  6027. if (isBSwapHWordPair(N0, Parts)) {
  6028. // (or (or (and), (and)), (or (and), (and)))
  6029. if (!isBSwapHWordPair(N1, Parts))
  6030. return SDValue();
  6031. } else if (N0.getOpcode() == ISD::OR) {
  6032. // (or (or (or (and), (and)), (and)), (and))
  6033. if (!isBSwapHWordElement(N1, Parts))
  6034. return SDValue();
  6035. SDValue N00 = N0.getOperand(0);
  6036. SDValue N01 = N0.getOperand(1);
  6037. if (!(isBSwapHWordElement(N01, Parts) && isBSwapHWordPair(N00, Parts)) &&
  6038. !(isBSwapHWordElement(N00, Parts) && isBSwapHWordPair(N01, Parts)))
  6039. return SDValue();
  6040. } else {
  6041. return SDValue();
  6042. }
  6043. // Make sure the parts are all coming from the same node.
  6044. if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
  6045. return SDValue();
  6046. SDLoc DL(N);
  6047. SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT,
  6048. SDValue(Parts[0], 0));
  6049. // Result of the bswap should be rotated by 16. If it's not legal, then
  6050. // do (x << 16) | (x >> 16).
  6051. SDValue ShAmt = DAG.getConstant(16, DL, getShiftAmountTy(VT));
  6052. if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
  6053. return DAG.getNode(ISD::ROTL, DL, VT, BSwap, ShAmt);
  6054. if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
  6055. return DAG.getNode(ISD::ROTR, DL, VT, BSwap, ShAmt);
  6056. return DAG.getNode(ISD::OR, DL, VT,
  6057. DAG.getNode(ISD::SHL, DL, VT, BSwap, ShAmt),
  6058. DAG.getNode(ISD::SRL, DL, VT, BSwap, ShAmt));
  6059. }
  6060. /// This contains all DAGCombine rules which reduce two values combined by
  6061. /// an Or operation to a single value \see visitANDLike().
  6062. SDValue DAGCombiner::visitORLike(SDValue N0, SDValue N1, SDNode *N) {
  6063. EVT VT = N1.getValueType();
  6064. SDLoc DL(N);
  6065. // fold (or x, undef) -> -1
  6066. if (!LegalOperations && (N0.isUndef() || N1.isUndef()))
  6067. return DAG.getAllOnesConstant(DL, VT);
  6068. if (SDValue V = foldLogicOfSetCCs(false, N0, N1, DL))
  6069. return V;
  6070. // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible.
  6071. if (N0.getOpcode() == ISD::AND && N1.getOpcode() == ISD::AND &&
  6072. // Don't increase # computations.
  6073. (N0->hasOneUse() || N1->hasOneUse())) {
  6074. // We can only do this xform if we know that bits from X that are set in C2
  6075. // but not in C1 are already zero. Likewise for Y.
  6076. if (const ConstantSDNode *N0O1C =
  6077. getAsNonOpaqueConstant(N0.getOperand(1))) {
  6078. if (const ConstantSDNode *N1O1C =
  6079. getAsNonOpaqueConstant(N1.getOperand(1))) {
  6080. // We can only do this xform if we know that bits from X that are set in
  6081. // C2 but not in C1 are already zero. Likewise for Y.
  6082. const APInt &LHSMask = N0O1C->getAPIntValue();
  6083. const APInt &RHSMask = N1O1C->getAPIntValue();
  6084. if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
  6085. DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
  6086. SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
  6087. N0.getOperand(0), N1.getOperand(0));
  6088. return DAG.getNode(ISD::AND, DL, VT, X,
  6089. DAG.getConstant(LHSMask | RHSMask, DL, VT));
  6090. }
  6091. }
  6092. }
  6093. }
  6094. // (or (and X, M), (and X, N)) -> (and X, (or M, N))
  6095. if (N0.getOpcode() == ISD::AND &&
  6096. N1.getOpcode() == ISD::AND &&
  6097. N0.getOperand(0) == N1.getOperand(0) &&
  6098. // Don't increase # computations.
  6099. (N0->hasOneUse() || N1->hasOneUse())) {
  6100. SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
  6101. N0.getOperand(1), N1.getOperand(1));
  6102. return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), X);
  6103. }
  6104. return SDValue();
  6105. }
  6106. /// OR combines for which the commuted variant will be tried as well.
  6107. static SDValue visitORCommutative(SelectionDAG &DAG, SDValue N0, SDValue N1,
  6108. SDNode *N) {
  6109. EVT VT = N0.getValueType();
  6110. if (N0.getOpcode() == ISD::AND) {
  6111. SDValue N00 = N0.getOperand(0);
  6112. SDValue N01 = N0.getOperand(1);
  6113. // fold or (and x, y), x --> x
  6114. if (N00 == N1 || N01 == N1)
  6115. return N1;
  6116. // fold (or (and X, (xor Y, -1)), Y) -> (or X, Y)
  6117. // TODO: Set AllowUndefs = true.
  6118. if (getBitwiseNotOperand(N01, N00,
  6119. /* AllowUndefs */ false) == N1)
  6120. return DAG.getNode(ISD::OR, SDLoc(N), VT, N00, N1);
  6121. // fold (or (and (xor Y, -1), X), Y) -> (or X, Y)
  6122. if (getBitwiseNotOperand(N00, N01,
  6123. /* AllowUndefs */ false) == N1)
  6124. return DAG.getNode(ISD::OR, SDLoc(N), VT, N01, N1);
  6125. }
  6126. if (N0.getOpcode() == ISD::XOR) {
  6127. // fold or (xor x, y), x --> or x, y
  6128. // or (xor x, y), (x and/or y) --> or x, y
  6129. SDValue N00 = N0.getOperand(0);
  6130. SDValue N01 = N0.getOperand(1);
  6131. if (N00 == N1)
  6132. return DAG.getNode(ISD::OR, SDLoc(N), VT, N01, N1);
  6133. if (N01 == N1)
  6134. return DAG.getNode(ISD::OR, SDLoc(N), VT, N00, N1);
  6135. if (N1.getOpcode() == ISD::AND || N1.getOpcode() == ISD::OR) {
  6136. SDValue N10 = N1.getOperand(0);
  6137. SDValue N11 = N1.getOperand(1);
  6138. if ((N00 == N10 && N01 == N11) || (N00 == N11 && N01 == N10))
  6139. return DAG.getNode(ISD::OR, SDLoc(N), VT, N00, N01);
  6140. }
  6141. }
  6142. if (SDValue R = foldLogicOfShifts(N, N0, N1, DAG))
  6143. return R;
  6144. auto peekThroughZext = [](SDValue V) {
  6145. if (V->getOpcode() == ISD::ZERO_EXTEND)
  6146. return V->getOperand(0);
  6147. return V;
  6148. };
  6149. // (fshl X, ?, Y) | (shl X, Y) --> fshl X, ?, Y
  6150. if (N0.getOpcode() == ISD::FSHL && N1.getOpcode() == ISD::SHL &&
  6151. N0.getOperand(0) == N1.getOperand(0) &&
  6152. peekThroughZext(N0.getOperand(2)) == peekThroughZext(N1.getOperand(1)))
  6153. return N0;
  6154. // (fshr ?, X, Y) | (srl X, Y) --> fshr ?, X, Y
  6155. if (N0.getOpcode() == ISD::FSHR && N1.getOpcode() == ISD::SRL &&
  6156. N0.getOperand(1) == N1.getOperand(0) &&
  6157. peekThroughZext(N0.getOperand(2)) == peekThroughZext(N1.getOperand(1)))
  6158. return N0;
  6159. return SDValue();
  6160. }
  6161. SDValue DAGCombiner::visitOR(SDNode *N) {
  6162. SDValue N0 = N->getOperand(0);
  6163. SDValue N1 = N->getOperand(1);
  6164. EVT VT = N1.getValueType();
  6165. // x | x --> x
  6166. if (N0 == N1)
  6167. return N0;
  6168. // fold (or c1, c2) -> c1|c2
  6169. if (SDValue C = DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N), VT, {N0, N1}))
  6170. return C;
  6171. // canonicalize constant to RHS
  6172. if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
  6173. !DAG.isConstantIntBuildVectorOrConstantInt(N1))
  6174. return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
  6175. // fold vector ops
  6176. if (VT.isVector()) {
  6177. if (SDValue FoldedVOp = SimplifyVBinOp(N, SDLoc(N)))
  6178. return FoldedVOp;
  6179. // fold (or x, 0) -> x, vector edition
  6180. if (ISD::isConstantSplatVectorAllZeros(N1.getNode()))
  6181. return N0;
  6182. // fold (or x, -1) -> -1, vector edition
  6183. if (ISD::isConstantSplatVectorAllOnes(N1.getNode()))
  6184. // do not return N1, because undef node may exist in N1
  6185. return DAG.getAllOnesConstant(SDLoc(N), N1.getValueType());
  6186. // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask)
  6187. // Do this only if the resulting type / shuffle is legal.
  6188. auto *SV0 = dyn_cast<ShuffleVectorSDNode>(N0);
  6189. auto *SV1 = dyn_cast<ShuffleVectorSDNode>(N1);
  6190. if (SV0 && SV1 && TLI.isTypeLegal(VT)) {
  6191. bool ZeroN00 = ISD::isBuildVectorAllZeros(N0.getOperand(0).getNode());
  6192. bool ZeroN01 = ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode());
  6193. bool ZeroN10 = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
  6194. bool ZeroN11 = ISD::isBuildVectorAllZeros(N1.getOperand(1).getNode());
  6195. // Ensure both shuffles have a zero input.
  6196. if ((ZeroN00 != ZeroN01) && (ZeroN10 != ZeroN11)) {
  6197. assert((!ZeroN00 || !ZeroN01) && "Both inputs zero!");
  6198. assert((!ZeroN10 || !ZeroN11) && "Both inputs zero!");
  6199. bool CanFold = true;
  6200. int NumElts = VT.getVectorNumElements();
  6201. SmallVector<int, 4> Mask(NumElts, -1);
  6202. for (int i = 0; i != NumElts; ++i) {
  6203. int M0 = SV0->getMaskElt(i);
  6204. int M1 = SV1->getMaskElt(i);
  6205. // Determine if either index is pointing to a zero vector.
  6206. bool M0Zero = M0 < 0 || (ZeroN00 == (M0 < NumElts));
  6207. bool M1Zero = M1 < 0 || (ZeroN10 == (M1 < NumElts));
  6208. // If one element is zero and the otherside is undef, keep undef.
  6209. // This also handles the case that both are undef.
  6210. if ((M0Zero && M1 < 0) || (M1Zero && M0 < 0))
  6211. continue;
  6212. // Make sure only one of the elements is zero.
  6213. if (M0Zero == M1Zero) {
  6214. CanFold = false;
  6215. break;
  6216. }
  6217. assert((M0 >= 0 || M1 >= 0) && "Undef index!");
  6218. // We have a zero and non-zero element. If the non-zero came from
  6219. // SV0 make the index a LHS index. If it came from SV1, make it
  6220. // a RHS index. We need to mod by NumElts because we don't care
  6221. // which operand it came from in the original shuffles.
  6222. Mask[i] = M1Zero ? M0 % NumElts : (M1 % NumElts) + NumElts;
  6223. }
  6224. if (CanFold) {
  6225. SDValue NewLHS = ZeroN00 ? N0.getOperand(1) : N0.getOperand(0);
  6226. SDValue NewRHS = ZeroN10 ? N1.getOperand(1) : N1.getOperand(0);
  6227. SDValue LegalShuffle =
  6228. TLI.buildLegalVectorShuffle(VT, SDLoc(N), NewLHS, NewRHS,
  6229. Mask, DAG);
  6230. if (LegalShuffle)
  6231. return LegalShuffle;
  6232. }
  6233. }
  6234. }
  6235. }
  6236. // fold (or x, 0) -> x
  6237. if (isNullConstant(N1))
  6238. return N0;
  6239. // fold (or x, -1) -> -1
  6240. if (isAllOnesConstant(N1))
  6241. return N1;
  6242. if (SDValue NewSel = foldBinOpIntoSelect(N))
  6243. return NewSel;
  6244. // fold (or x, c) -> c iff (x & ~c) == 0
  6245. ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
  6246. if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
  6247. return N1;
  6248. if (SDValue Combined = visitORLike(N0, N1, N))
  6249. return Combined;
  6250. if (SDValue Combined = combineCarryDiamond(DAG, TLI, N0, N1, N))
  6251. return Combined;
  6252. // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
  6253. if (SDValue BSwap = MatchBSwapHWord(N, N0, N1))
  6254. return BSwap;
  6255. if (SDValue BSwap = MatchBSwapHWordLow(N, N0, N1))
  6256. return BSwap;
  6257. // reassociate or
  6258. if (SDValue ROR = reassociateOps(ISD::OR, SDLoc(N), N0, N1, N->getFlags()))
  6259. return ROR;
  6260. // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
  6261. // iff (c1 & c2) != 0 or c1/c2 are undef.
  6262. auto MatchIntersect = [](ConstantSDNode *C1, ConstantSDNode *C2) {
  6263. return !C1 || !C2 || C1->getAPIntValue().intersects(C2->getAPIntValue());
  6264. };
  6265. if (N0.getOpcode() == ISD::AND && N0->hasOneUse() &&
  6266. ISD::matchBinaryPredicate(N0.getOperand(1), N1, MatchIntersect, true)) {
  6267. if (SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N1), VT,
  6268. {N1, N0.getOperand(1)})) {
  6269. SDValue IOR = DAG.getNode(ISD::OR, SDLoc(N0), VT, N0.getOperand(0), N1);
  6270. AddToWorklist(IOR.getNode());
  6271. return DAG.getNode(ISD::AND, SDLoc(N), VT, COR, IOR);
  6272. }
  6273. }
  6274. if (SDValue Combined = visitORCommutative(DAG, N0, N1, N))
  6275. return Combined;
  6276. if (SDValue Combined = visitORCommutative(DAG, N1, N0, N))
  6277. return Combined;
  6278. // Simplify: (or (op x...), (op y...)) -> (op (or x, y))
  6279. if (N0.getOpcode() == N1.getOpcode())
  6280. if (SDValue V = hoistLogicOpWithSameOpcodeHands(N))
  6281. return V;
  6282. // See if this is some rotate idiom.
  6283. if (SDValue Rot = MatchRotate(N0, N1, SDLoc(N)))
  6284. return Rot;
  6285. if (SDValue Load = MatchLoadCombine(N))
  6286. return Load;
  6287. // Simplify the operands using demanded-bits information.
  6288. if (SimplifyDemandedBits(SDValue(N, 0)))
  6289. return SDValue(N, 0);
  6290. // If OR can be rewritten into ADD, try combines based on ADD.
  6291. if ((!LegalOperations || TLI.isOperationLegal(ISD::ADD, VT)) &&
  6292. DAG.haveNoCommonBitsSet(N0, N1))
  6293. if (SDValue Combined = visitADDLike(N))
  6294. return Combined;
  6295. // Postpone until legalization completed to avoid interference with bswap
  6296. // folding
  6297. if (LegalOperations || VT.isVector())
  6298. if (SDValue R = foldLogicTreeOfShifts(N, N0, N1, DAG))
  6299. return R;
  6300. return SDValue();
  6301. }
  6302. static SDValue stripConstantMask(const SelectionDAG &DAG, SDValue Op,
  6303. SDValue &Mask) {
  6304. if (Op.getOpcode() == ISD::AND &&
  6305. DAG.isConstantIntBuildVectorOrConstantInt(Op.getOperand(1))) {
  6306. Mask = Op.getOperand(1);
  6307. return Op.getOperand(0);
  6308. }
  6309. return Op;
  6310. }
  6311. /// Match "(X shl/srl V1) & V2" where V2 may not be present.
  6312. static bool matchRotateHalf(const SelectionDAG &DAG, SDValue Op, SDValue &Shift,
  6313. SDValue &Mask) {
  6314. Op = stripConstantMask(DAG, Op, Mask);
  6315. if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
  6316. Shift = Op;
  6317. return true;
  6318. }
  6319. return false;
  6320. }
  6321. /// Helper function for visitOR to extract the needed side of a rotate idiom
  6322. /// from a shl/srl/mul/udiv. This is meant to handle cases where
  6323. /// InstCombine merged some outside op with one of the shifts from
  6324. /// the rotate pattern.
  6325. /// \returns An empty \c SDValue if the needed shift couldn't be extracted.
  6326. /// Otherwise, returns an expansion of \p ExtractFrom based on the following
  6327. /// patterns:
  6328. ///
  6329. /// (or (add v v) (shrl v bitwidth-1)):
  6330. /// expands (add v v) -> (shl v 1)
  6331. ///
  6332. /// (or (mul v c0) (shrl (mul v c1) c2)):
  6333. /// expands (mul v c0) -> (shl (mul v c1) c3)
  6334. ///
  6335. /// (or (udiv v c0) (shl (udiv v c1) c2)):
  6336. /// expands (udiv v c0) -> (shrl (udiv v c1) c3)
  6337. ///
  6338. /// (or (shl v c0) (shrl (shl v c1) c2)):
  6339. /// expands (shl v c0) -> (shl (shl v c1) c3)
  6340. ///
  6341. /// (or (shrl v c0) (shl (shrl v c1) c2)):
  6342. /// expands (shrl v c0) -> (shrl (shrl v c1) c3)
  6343. ///
  6344. /// Such that in all cases, c3+c2==bitwidth(op v c1).
  6345. static SDValue extractShiftForRotate(SelectionDAG &DAG, SDValue OppShift,
  6346. SDValue ExtractFrom, SDValue &Mask,
  6347. const SDLoc &DL) {
  6348. assert(OppShift && ExtractFrom && "Empty SDValue");
  6349. if (OppShift.getOpcode() != ISD::SHL && OppShift.getOpcode() != ISD::SRL)
  6350. return SDValue();
  6351. ExtractFrom = stripConstantMask(DAG, ExtractFrom, Mask);
  6352. // Value and Type of the shift.
  6353. SDValue OppShiftLHS = OppShift.getOperand(0);
  6354. EVT ShiftedVT = OppShiftLHS.getValueType();
  6355. // Amount of the existing shift.
  6356. ConstantSDNode *OppShiftCst = isConstOrConstSplat(OppShift.getOperand(1));
  6357. // (add v v) -> (shl v 1)
  6358. // TODO: Should this be a general DAG canonicalization?
  6359. if (OppShift.getOpcode() == ISD::SRL && OppShiftCst &&
  6360. ExtractFrom.getOpcode() == ISD::ADD &&
  6361. ExtractFrom.getOperand(0) == ExtractFrom.getOperand(1) &&
  6362. ExtractFrom.getOperand(0) == OppShiftLHS &&
  6363. OppShiftCst->getAPIntValue() == ShiftedVT.getScalarSizeInBits() - 1)
  6364. return DAG.getNode(ISD::SHL, DL, ShiftedVT, OppShiftLHS,
  6365. DAG.getShiftAmountConstant(1, ShiftedVT, DL));
  6366. // Preconditions:
  6367. // (or (op0 v c0) (shiftl/r (op0 v c1) c2))
  6368. //
  6369. // Find opcode of the needed shift to be extracted from (op0 v c0).
  6370. unsigned Opcode = ISD::DELETED_NODE;
  6371. bool IsMulOrDiv = false;
  6372. // Set Opcode and IsMulOrDiv if the extract opcode matches the needed shift
  6373. // opcode or its arithmetic (mul or udiv) variant.
  6374. auto SelectOpcode = [&](unsigned NeededShift, unsigned MulOrDivVariant) {
  6375. IsMulOrDiv = ExtractFrom.getOpcode() == MulOrDivVariant;
  6376. if (!IsMulOrDiv && ExtractFrom.getOpcode() != NeededShift)
  6377. return false;
  6378. Opcode = NeededShift;
  6379. return true;
  6380. };
  6381. // op0 must be either the needed shift opcode or the mul/udiv equivalent
  6382. // that the needed shift can be extracted from.
  6383. if ((OppShift.getOpcode() != ISD::SRL || !SelectOpcode(ISD::SHL, ISD::MUL)) &&
  6384. (OppShift.getOpcode() != ISD::SHL || !SelectOpcode(ISD::SRL, ISD::UDIV)))
  6385. return SDValue();
  6386. // op0 must be the same opcode on both sides, have the same LHS argument,
  6387. // and produce the same value type.
  6388. if (OppShiftLHS.getOpcode() != ExtractFrom.getOpcode() ||
  6389. OppShiftLHS.getOperand(0) != ExtractFrom.getOperand(0) ||
  6390. ShiftedVT != ExtractFrom.getValueType())
  6391. return SDValue();
  6392. // Constant mul/udiv/shift amount from the RHS of the shift's LHS op.
  6393. ConstantSDNode *OppLHSCst = isConstOrConstSplat(OppShiftLHS.getOperand(1));
  6394. // Constant mul/udiv/shift amount from the RHS of the ExtractFrom op.
  6395. ConstantSDNode *ExtractFromCst =
  6396. isConstOrConstSplat(ExtractFrom.getOperand(1));
  6397. // TODO: We should be able to handle non-uniform constant vectors for these values
  6398. // Check that we have constant values.
  6399. if (!OppShiftCst || !OppShiftCst->getAPIntValue() ||
  6400. !OppLHSCst || !OppLHSCst->getAPIntValue() ||
  6401. !ExtractFromCst || !ExtractFromCst->getAPIntValue())
  6402. return SDValue();
  6403. // Compute the shift amount we need to extract to complete the rotate.
  6404. const unsigned VTWidth = ShiftedVT.getScalarSizeInBits();
  6405. if (OppShiftCst->getAPIntValue().ugt(VTWidth))
  6406. return SDValue();
  6407. APInt NeededShiftAmt = VTWidth - OppShiftCst->getAPIntValue();
  6408. // Normalize the bitwidth of the two mul/udiv/shift constant operands.
  6409. APInt ExtractFromAmt = ExtractFromCst->getAPIntValue();
  6410. APInt OppLHSAmt = OppLHSCst->getAPIntValue();
  6411. zeroExtendToMatch(ExtractFromAmt, OppLHSAmt);
  6412. // Now try extract the needed shift from the ExtractFrom op and see if the
  6413. // result matches up with the existing shift's LHS op.
  6414. if (IsMulOrDiv) {
  6415. // Op to extract from is a mul or udiv by a constant.
  6416. // Check:
  6417. // c2 / (1 << (bitwidth(op0 v c0) - c1)) == c0
  6418. // c2 % (1 << (bitwidth(op0 v c0) - c1)) == 0
  6419. const APInt ExtractDiv = APInt::getOneBitSet(ExtractFromAmt.getBitWidth(),
  6420. NeededShiftAmt.getZExtValue());
  6421. APInt ResultAmt;
  6422. APInt Rem;
  6423. APInt::udivrem(ExtractFromAmt, ExtractDiv, ResultAmt, Rem);
  6424. if (Rem != 0 || ResultAmt != OppLHSAmt)
  6425. return SDValue();
  6426. } else {
  6427. // Op to extract from is a shift by a constant.
  6428. // Check:
  6429. // c2 - (bitwidth(op0 v c0) - c1) == c0
  6430. if (OppLHSAmt != ExtractFromAmt - NeededShiftAmt.zextOrTrunc(
  6431. ExtractFromAmt.getBitWidth()))
  6432. return SDValue();
  6433. }
  6434. // Return the expanded shift op that should allow a rotate to be formed.
  6435. EVT ShiftVT = OppShift.getOperand(1).getValueType();
  6436. EVT ResVT = ExtractFrom.getValueType();
  6437. SDValue NewShiftNode = DAG.getConstant(NeededShiftAmt, DL, ShiftVT);
  6438. return DAG.getNode(Opcode, DL, ResVT, OppShiftLHS, NewShiftNode);
  6439. }
  6440. // Return true if we can prove that, whenever Neg and Pos are both in the
  6441. // range [0, EltSize), Neg == (Pos == 0 ? 0 : EltSize - Pos). This means that
  6442. // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
  6443. //
  6444. // (or (shift1 X, Neg), (shift2 X, Pos))
  6445. //
  6446. // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
  6447. // in direction shift1 by Neg. The range [0, EltSize) means that we only need
  6448. // to consider shift amounts with defined behavior.
  6449. //
  6450. // The IsRotate flag should be set when the LHS of both shifts is the same.
  6451. // Otherwise if matching a general funnel shift, it should be clear.
  6452. static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned EltSize,
  6453. SelectionDAG &DAG, bool IsRotate) {
  6454. const auto &TLI = DAG.getTargetLoweringInfo();
  6455. // If EltSize is a power of 2 then:
  6456. //
  6457. // (a) (Pos == 0 ? 0 : EltSize - Pos) == (EltSize - Pos) & (EltSize - 1)
  6458. // (b) Neg == Neg & (EltSize - 1) whenever Neg is in [0, EltSize).
  6459. //
  6460. // So if EltSize is a power of 2 and Neg is (and Neg', EltSize-1), we check
  6461. // for the stronger condition:
  6462. //
  6463. // Neg & (EltSize - 1) == (EltSize - Pos) & (EltSize - 1) [A]
  6464. //
  6465. // for all Neg and Pos. Since Neg & (EltSize - 1) == Neg' & (EltSize - 1)
  6466. // we can just replace Neg with Neg' for the rest of the function.
  6467. //
  6468. // In other cases we check for the even stronger condition:
  6469. //
  6470. // Neg == EltSize - Pos [B]
  6471. //
  6472. // for all Neg and Pos. Note that the (or ...) then invokes undefined
  6473. // behavior if Pos == 0 (and consequently Neg == EltSize).
  6474. //
  6475. // We could actually use [A] whenever EltSize is a power of 2, but the
  6476. // only extra cases that it would match are those uninteresting ones
  6477. // where Neg and Pos are never in range at the same time. E.g. for
  6478. // EltSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
  6479. // as well as (sub 32, Pos), but:
  6480. //
  6481. // (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
  6482. //
  6483. // always invokes undefined behavior for 32-bit X.
  6484. //
  6485. // Below, Mask == EltSize - 1 when using [A] and is all-ones otherwise.
  6486. // This allows us to peek through any operations that only affect Mask's
  6487. // un-demanded bits.
  6488. //
  6489. // NOTE: We can only do this when matching operations which won't modify the
  6490. // least Log2(EltSize) significant bits and not a general funnel shift.
  6491. unsigned MaskLoBits = 0;
  6492. if (IsRotate && isPowerOf2_64(EltSize)) {
  6493. unsigned Bits = Log2_64(EltSize);
  6494. unsigned NegBits = Neg.getScalarValueSizeInBits();
  6495. if (NegBits >= Bits) {
  6496. APInt DemandedBits = APInt::getLowBitsSet(NegBits, Bits);
  6497. if (SDValue Inner =
  6498. TLI.SimplifyMultipleUseDemandedBits(Neg, DemandedBits, DAG)) {
  6499. Neg = Inner;
  6500. MaskLoBits = Bits;
  6501. }
  6502. }
  6503. }
  6504. // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
  6505. if (Neg.getOpcode() != ISD::SUB)
  6506. return false;
  6507. ConstantSDNode *NegC = isConstOrConstSplat(Neg.getOperand(0));
  6508. if (!NegC)
  6509. return false;
  6510. SDValue NegOp1 = Neg.getOperand(1);
  6511. // On the RHS of [A], if Pos is the result of operation on Pos' that won't
  6512. // affect Mask's demanded bits, just replace Pos with Pos'. These operations
  6513. // are redundant for the purpose of the equality.
  6514. if (MaskLoBits) {
  6515. unsigned PosBits = Pos.getScalarValueSizeInBits();
  6516. if (PosBits >= MaskLoBits) {
  6517. APInt DemandedBits = APInt::getLowBitsSet(PosBits, MaskLoBits);
  6518. if (SDValue Inner =
  6519. TLI.SimplifyMultipleUseDemandedBits(Pos, DemandedBits, DAG)) {
  6520. Pos = Inner;
  6521. }
  6522. }
  6523. }
  6524. // The condition we need is now:
  6525. //
  6526. // (NegC - NegOp1) & Mask == (EltSize - Pos) & Mask
  6527. //
  6528. // If NegOp1 == Pos then we need:
  6529. //
  6530. // EltSize & Mask == NegC & Mask
  6531. //
  6532. // (because "x & Mask" is a truncation and distributes through subtraction).
  6533. //
  6534. // We also need to account for a potential truncation of NegOp1 if the amount
  6535. // has already been legalized to a shift amount type.
  6536. APInt Width;
  6537. if ((Pos == NegOp1) ||
  6538. (NegOp1.getOpcode() == ISD::TRUNCATE && Pos == NegOp1.getOperand(0)))
  6539. Width = NegC->getAPIntValue();
  6540. // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
  6541. // Then the condition we want to prove becomes:
  6542. //
  6543. // (NegC - NegOp1) & Mask == (EltSize - (NegOp1 + PosC)) & Mask
  6544. //
  6545. // which, again because "x & Mask" is a truncation, becomes:
  6546. //
  6547. // NegC & Mask == (EltSize - PosC) & Mask
  6548. // EltSize & Mask == (NegC + PosC) & Mask
  6549. else if (Pos.getOpcode() == ISD::ADD && Pos.getOperand(0) == NegOp1) {
  6550. if (ConstantSDNode *PosC = isConstOrConstSplat(Pos.getOperand(1)))
  6551. Width = PosC->getAPIntValue() + NegC->getAPIntValue();
  6552. else
  6553. return false;
  6554. } else
  6555. return false;
  6556. // Now we just need to check that EltSize & Mask == Width & Mask.
  6557. if (MaskLoBits)
  6558. // EltSize & Mask is 0 since Mask is EltSize - 1.
  6559. return Width.getLoBits(MaskLoBits) == 0;
  6560. return Width == EltSize;
  6561. }
  6562. // A subroutine of MatchRotate used once we have found an OR of two opposite
  6563. // shifts of Shifted. If Neg == <operand size> - Pos then the OR reduces
  6564. // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
  6565. // former being preferred if supported. InnerPos and InnerNeg are Pos and
  6566. // Neg with outer conversions stripped away.
  6567. SDValue DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
  6568. SDValue Neg, SDValue InnerPos,
  6569. SDValue InnerNeg, bool HasPos,
  6570. unsigned PosOpcode, unsigned NegOpcode,
  6571. const SDLoc &DL) {
  6572. // fold (or (shl x, (*ext y)),
  6573. // (srl x, (*ext (sub 32, y)))) ->
  6574. // (rotl x, y) or (rotr x, (sub 32, y))
  6575. //
  6576. // fold (or (shl x, (*ext (sub 32, y))),
  6577. // (srl x, (*ext y))) ->
  6578. // (rotr x, y) or (rotl x, (sub 32, y))
  6579. EVT VT = Shifted.getValueType();
  6580. if (matchRotateSub(InnerPos, InnerNeg, VT.getScalarSizeInBits(), DAG,
  6581. /*IsRotate*/ true)) {
  6582. return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
  6583. HasPos ? Pos : Neg);
  6584. }
  6585. return SDValue();
  6586. }
  6587. // A subroutine of MatchRotate used once we have found an OR of two opposite
  6588. // shifts of N0 + N1. If Neg == <operand size> - Pos then the OR reduces
  6589. // to both (PosOpcode N0, N1, Pos) and (NegOpcode N0, N1, Neg), with the
  6590. // former being preferred if supported. InnerPos and InnerNeg are Pos and
  6591. // Neg with outer conversions stripped away.
  6592. // TODO: Merge with MatchRotatePosNeg.
  6593. SDValue DAGCombiner::MatchFunnelPosNeg(SDValue N0, SDValue N1, SDValue Pos,
  6594. SDValue Neg, SDValue InnerPos,
  6595. SDValue InnerNeg, bool HasPos,
  6596. unsigned PosOpcode, unsigned NegOpcode,
  6597. const SDLoc &DL) {
  6598. EVT VT = N0.getValueType();
  6599. unsigned EltBits = VT.getScalarSizeInBits();
  6600. // fold (or (shl x0, (*ext y)),
  6601. // (srl x1, (*ext (sub 32, y)))) ->
  6602. // (fshl x0, x1, y) or (fshr x0, x1, (sub 32, y))
  6603. //
  6604. // fold (or (shl x0, (*ext (sub 32, y))),
  6605. // (srl x1, (*ext y))) ->
  6606. // (fshr x0, x1, y) or (fshl x0, x1, (sub 32, y))
  6607. if (matchRotateSub(InnerPos, InnerNeg, EltBits, DAG, /*IsRotate*/ N0 == N1)) {
  6608. return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, N0, N1,
  6609. HasPos ? Pos : Neg);
  6610. }
  6611. // Matching the shift+xor cases, we can't easily use the xor'd shift amount
  6612. // so for now just use the PosOpcode case if its legal.
  6613. // TODO: When can we use the NegOpcode case?
  6614. if (PosOpcode == ISD::FSHL && isPowerOf2_32(EltBits)) {
  6615. auto IsBinOpImm = [](SDValue Op, unsigned BinOpc, unsigned Imm) {
  6616. if (Op.getOpcode() != BinOpc)
  6617. return false;
  6618. ConstantSDNode *Cst = isConstOrConstSplat(Op.getOperand(1));
  6619. return Cst && (Cst->getAPIntValue() == Imm);
  6620. };
  6621. // fold (or (shl x0, y), (srl (srl x1, 1), (xor y, 31)))
  6622. // -> (fshl x0, x1, y)
  6623. if (IsBinOpImm(N1, ISD::SRL, 1) &&
  6624. IsBinOpImm(InnerNeg, ISD::XOR, EltBits - 1) &&
  6625. InnerPos == InnerNeg.getOperand(0) &&
  6626. TLI.isOperationLegalOrCustom(ISD::FSHL, VT)) {
  6627. return DAG.getNode(ISD::FSHL, DL, VT, N0, N1.getOperand(0), Pos);
  6628. }
  6629. // fold (or (shl (shl x0, 1), (xor y, 31)), (srl x1, y))
  6630. // -> (fshr x0, x1, y)
  6631. if (IsBinOpImm(N0, ISD::SHL, 1) &&
  6632. IsBinOpImm(InnerPos, ISD::XOR, EltBits - 1) &&
  6633. InnerNeg == InnerPos.getOperand(0) &&
  6634. TLI.isOperationLegalOrCustom(ISD::FSHR, VT)) {
  6635. return DAG.getNode(ISD::FSHR, DL, VT, N0.getOperand(0), N1, Neg);
  6636. }
  6637. // fold (or (shl (add x0, x0), (xor y, 31)), (srl x1, y))
  6638. // -> (fshr x0, x1, y)
  6639. // TODO: Should add(x,x) -> shl(x,1) be a general DAG canonicalization?
  6640. if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N0.getOperand(1) &&
  6641. IsBinOpImm(InnerPos, ISD::XOR, EltBits - 1) &&
  6642. InnerNeg == InnerPos.getOperand(0) &&
  6643. TLI.isOperationLegalOrCustom(ISD::FSHR, VT)) {
  6644. return DAG.getNode(ISD::FSHR, DL, VT, N0.getOperand(0), N1, Neg);
  6645. }
  6646. }
  6647. return SDValue();
  6648. }
  6649. // MatchRotate - Handle an 'or' of two operands. If this is one of the many
  6650. // idioms for rotate, and if the target supports rotation instructions, generate
  6651. // a rot[lr]. This also matches funnel shift patterns, similar to rotation but
  6652. // with different shifted sources.
  6653. SDValue DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, const SDLoc &DL) {
  6654. EVT VT = LHS.getValueType();
  6655. // The target must have at least one rotate/funnel flavor.
  6656. // We still try to match rotate by constant pre-legalization.
  6657. // TODO: Support pre-legalization funnel-shift by constant.
  6658. bool HasROTL = hasOperation(ISD::ROTL, VT);
  6659. bool HasROTR = hasOperation(ISD::ROTR, VT);
  6660. bool HasFSHL = hasOperation(ISD::FSHL, VT);
  6661. bool HasFSHR = hasOperation(ISD::FSHR, VT);
  6662. // If the type is going to be promoted and the target has enabled custom
  6663. // lowering for rotate, allow matching rotate by non-constants. Only allow
  6664. // this for scalar types.
  6665. if (VT.isScalarInteger() && TLI.getTypeAction(*DAG.getContext(), VT) ==
  6666. TargetLowering::TypePromoteInteger) {
  6667. HasROTL |= TLI.getOperationAction(ISD::ROTL, VT) == TargetLowering::Custom;
  6668. HasROTR |= TLI.getOperationAction(ISD::ROTR, VT) == TargetLowering::Custom;
  6669. }
  6670. if (LegalOperations && !HasROTL && !HasROTR && !HasFSHL && !HasFSHR)
  6671. return SDValue();
  6672. // Check for truncated rotate.
  6673. if (LHS.getOpcode() == ISD::TRUNCATE && RHS.getOpcode() == ISD::TRUNCATE &&
  6674. LHS.getOperand(0).getValueType() == RHS.getOperand(0).getValueType()) {
  6675. assert(LHS.getValueType() == RHS.getValueType());
  6676. if (SDValue Rot = MatchRotate(LHS.getOperand(0), RHS.getOperand(0), DL)) {
  6677. return DAG.getNode(ISD::TRUNCATE, SDLoc(LHS), LHS.getValueType(), Rot);
  6678. }
  6679. }
  6680. // Match "(X shl/srl V1) & V2" where V2 may not be present.
  6681. SDValue LHSShift; // The shift.
  6682. SDValue LHSMask; // AND value if any.
  6683. matchRotateHalf(DAG, LHS, LHSShift, LHSMask);
  6684. SDValue RHSShift; // The shift.
  6685. SDValue RHSMask; // AND value if any.
  6686. matchRotateHalf(DAG, RHS, RHSShift, RHSMask);
  6687. // If neither side matched a rotate half, bail
  6688. if (!LHSShift && !RHSShift)
  6689. return SDValue();
  6690. // InstCombine may have combined a constant shl, srl, mul, or udiv with one
  6691. // side of the rotate, so try to handle that here. In all cases we need to
  6692. // pass the matched shift from the opposite side to compute the opcode and
  6693. // needed shift amount to extract. We still want to do this if both sides
  6694. // matched a rotate half because one half may be a potential overshift that
  6695. // can be broken down (ie if InstCombine merged two shl or srl ops into a
  6696. // single one).
  6697. // Have LHS side of the rotate, try to extract the needed shift from the RHS.
  6698. if (LHSShift)
  6699. if (SDValue NewRHSShift =
  6700. extractShiftForRotate(DAG, LHSShift, RHS, RHSMask, DL))
  6701. RHSShift = NewRHSShift;
  6702. // Have RHS side of the rotate, try to extract the needed shift from the LHS.
  6703. if (RHSShift)
  6704. if (SDValue NewLHSShift =
  6705. extractShiftForRotate(DAG, RHSShift, LHS, LHSMask, DL))
  6706. LHSShift = NewLHSShift;
  6707. // If a side is still missing, nothing else we can do.
  6708. if (!RHSShift || !LHSShift)
  6709. return SDValue();
  6710. // At this point we've matched or extracted a shift op on each side.
  6711. if (LHSShift.getOpcode() == RHSShift.getOpcode())
  6712. return SDValue(); // Shifts must disagree.
  6713. // Canonicalize shl to left side in a shl/srl pair.
  6714. if (RHSShift.getOpcode() == ISD::SHL) {
  6715. std::swap(LHS, RHS);
  6716. std::swap(LHSShift, RHSShift);
  6717. std::swap(LHSMask, RHSMask);
  6718. }
  6719. // Something has gone wrong - we've lost the shl/srl pair - bail.
  6720. if (LHSShift.getOpcode() != ISD::SHL || RHSShift.getOpcode() != ISD::SRL)
  6721. return SDValue();
  6722. unsigned EltSizeInBits = VT.getScalarSizeInBits();
  6723. SDValue LHSShiftArg = LHSShift.getOperand(0);
  6724. SDValue LHSShiftAmt = LHSShift.getOperand(1);
  6725. SDValue RHSShiftArg = RHSShift.getOperand(0);
  6726. SDValue RHSShiftAmt = RHSShift.getOperand(1);
  6727. auto MatchRotateSum = [EltSizeInBits](ConstantSDNode *LHS,
  6728. ConstantSDNode *RHS) {
  6729. return (LHS->getAPIntValue() + RHS->getAPIntValue()) == EltSizeInBits;
  6730. };
  6731. auto ApplyMasks = [&](SDValue Res) {
  6732. // If there is an AND of either shifted operand, apply it to the result.
  6733. if (LHSMask.getNode() || RHSMask.getNode()) {
  6734. SDValue AllOnes = DAG.getAllOnesConstant(DL, VT);
  6735. SDValue Mask = AllOnes;
  6736. if (LHSMask.getNode()) {
  6737. SDValue RHSBits = DAG.getNode(ISD::SRL, DL, VT, AllOnes, RHSShiftAmt);
  6738. Mask = DAG.getNode(ISD::AND, DL, VT, Mask,
  6739. DAG.getNode(ISD::OR, DL, VT, LHSMask, RHSBits));
  6740. }
  6741. if (RHSMask.getNode()) {
  6742. SDValue LHSBits = DAG.getNode(ISD::SHL, DL, VT, AllOnes, LHSShiftAmt);
  6743. Mask = DAG.getNode(ISD::AND, DL, VT, Mask,
  6744. DAG.getNode(ISD::OR, DL, VT, RHSMask, LHSBits));
  6745. }
  6746. Res = DAG.getNode(ISD::AND, DL, VT, Res, Mask);
  6747. }
  6748. return Res;
  6749. };
  6750. // TODO: Support pre-legalization funnel-shift by constant.
  6751. bool IsRotate = LHSShiftArg == RHSShiftArg;
  6752. if (!IsRotate && !(HasFSHL || HasFSHR)) {
  6753. if (TLI.isTypeLegal(VT) && LHS.hasOneUse() && RHS.hasOneUse() &&
  6754. ISD::matchBinaryPredicate(LHSShiftAmt, RHSShiftAmt, MatchRotateSum)) {
  6755. // Look for a disguised rotate by constant.
  6756. // The common shifted operand X may be hidden inside another 'or'.
  6757. SDValue X, Y;
  6758. auto matchOr = [&X, &Y](SDValue Or, SDValue CommonOp) {
  6759. if (!Or.hasOneUse() || Or.getOpcode() != ISD::OR)
  6760. return false;
  6761. if (CommonOp == Or.getOperand(0)) {
  6762. X = CommonOp;
  6763. Y = Or.getOperand(1);
  6764. return true;
  6765. }
  6766. if (CommonOp == Or.getOperand(1)) {
  6767. X = CommonOp;
  6768. Y = Or.getOperand(0);
  6769. return true;
  6770. }
  6771. return false;
  6772. };
  6773. SDValue Res;
  6774. if (matchOr(LHSShiftArg, RHSShiftArg)) {
  6775. // (shl (X | Y), C1) | (srl X, C2) --> (rotl X, C1) | (shl Y, C1)
  6776. SDValue RotX = DAG.getNode(ISD::ROTL, DL, VT, X, LHSShiftAmt);
  6777. SDValue ShlY = DAG.getNode(ISD::SHL, DL, VT, Y, LHSShiftAmt);
  6778. Res = DAG.getNode(ISD::OR, DL, VT, RotX, ShlY);
  6779. } else if (matchOr(RHSShiftArg, LHSShiftArg)) {
  6780. // (shl X, C1) | (srl (X | Y), C2) --> (rotl X, C1) | (srl Y, C2)
  6781. SDValue RotX = DAG.getNode(ISD::ROTL, DL, VT, X, LHSShiftAmt);
  6782. SDValue SrlY = DAG.getNode(ISD::SRL, DL, VT, Y, RHSShiftAmt);
  6783. Res = DAG.getNode(ISD::OR, DL, VT, RotX, SrlY);
  6784. } else {
  6785. return SDValue();
  6786. }
  6787. return ApplyMasks(Res);
  6788. }
  6789. return SDValue(); // Requires funnel shift support.
  6790. }
  6791. // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
  6792. // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
  6793. // fold (or (shl x, C1), (srl y, C2)) -> (fshl x, y, C1)
  6794. // fold (or (shl x, C1), (srl y, C2)) -> (fshr x, y, C2)
  6795. // iff C1+C2 == EltSizeInBits
  6796. if (ISD::matchBinaryPredicate(LHSShiftAmt, RHSShiftAmt, MatchRotateSum)) {
  6797. SDValue Res;
  6798. if (IsRotate && (HasROTL || HasROTR || !(HasFSHL || HasFSHR))) {
  6799. bool UseROTL = !LegalOperations || HasROTL;
  6800. Res = DAG.getNode(UseROTL ? ISD::ROTL : ISD::ROTR, DL, VT, LHSShiftArg,
  6801. UseROTL ? LHSShiftAmt : RHSShiftAmt);
  6802. } else {
  6803. bool UseFSHL = !LegalOperations || HasFSHL;
  6804. Res = DAG.getNode(UseFSHL ? ISD::FSHL : ISD::FSHR, DL, VT, LHSShiftArg,
  6805. RHSShiftArg, UseFSHL ? LHSShiftAmt : RHSShiftAmt);
  6806. }
  6807. return ApplyMasks(Res);
  6808. }
  6809. // Even pre-legalization, we can't easily rotate/funnel-shift by a variable
  6810. // shift.
  6811. if (!HasROTL && !HasROTR && !HasFSHL && !HasFSHR)
  6812. return SDValue();
  6813. // If there is a mask here, and we have a variable shift, we can't be sure
  6814. // that we're masking out the right stuff.
  6815. if (LHSMask.getNode() || RHSMask.getNode())
  6816. return SDValue();
  6817. // If the shift amount is sign/zext/any-extended just peel it off.
  6818. SDValue LExtOp0 = LHSShiftAmt;
  6819. SDValue RExtOp0 = RHSShiftAmt;
  6820. if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
  6821. LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
  6822. LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
  6823. LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
  6824. (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
  6825. RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
  6826. RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
  6827. RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
  6828. LExtOp0 = LHSShiftAmt.getOperand(0);
  6829. RExtOp0 = RHSShiftAmt.getOperand(0);
  6830. }
  6831. if (IsRotate && (HasROTL || HasROTR)) {
  6832. SDValue TryL =
  6833. MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt, LExtOp0,
  6834. RExtOp0, HasROTL, ISD::ROTL, ISD::ROTR, DL);
  6835. if (TryL)
  6836. return TryL;
  6837. SDValue TryR =
  6838. MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt, RExtOp0,
  6839. LExtOp0, HasROTR, ISD::ROTR, ISD::ROTL, DL);
  6840. if (TryR)
  6841. return TryR;
  6842. }
  6843. SDValue TryL =
  6844. MatchFunnelPosNeg(LHSShiftArg, RHSShiftArg, LHSShiftAmt, RHSShiftAmt,
  6845. LExtOp0, RExtOp0, HasFSHL, ISD::FSHL, ISD::FSHR, DL);
  6846. if (TryL)
  6847. return TryL;
  6848. SDValue TryR =
  6849. MatchFunnelPosNeg(LHSShiftArg, RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
  6850. RExtOp0, LExtOp0, HasFSHR, ISD::FSHR, ISD::FSHL, DL);
  6851. if (TryR)
  6852. return TryR;
  6853. return SDValue();
  6854. }
  6855. namespace {
  6856. /// Represents known origin of an individual byte in load combine pattern. The
  6857. /// value of the byte is either constant zero or comes from memory.
  6858. struct ByteProvider {
  6859. // For constant zero providers Load is set to nullptr. For memory providers
  6860. // Load represents the node which loads the byte from memory.
  6861. // ByteOffset is the offset of the byte in the value produced by the load.
  6862. LoadSDNode *Load = nullptr;
  6863. unsigned ByteOffset = 0;
  6864. unsigned VectorOffset = 0;
  6865. ByteProvider() = default;
  6866. static ByteProvider getMemory(LoadSDNode *Load, unsigned ByteOffset,
  6867. unsigned VectorOffset) {
  6868. return ByteProvider(Load, ByteOffset, VectorOffset);
  6869. }
  6870. static ByteProvider getConstantZero() { return ByteProvider(nullptr, 0, 0); }
  6871. bool isConstantZero() const { return !Load; }
  6872. bool isMemory() const { return Load; }
  6873. bool operator==(const ByteProvider &Other) const {
  6874. return Other.Load == Load && Other.ByteOffset == ByteOffset &&
  6875. Other.VectorOffset == VectorOffset;
  6876. }
  6877. private:
  6878. ByteProvider(LoadSDNode *Load, unsigned ByteOffset, unsigned VectorOffset)
  6879. : Load(Load), ByteOffset(ByteOffset), VectorOffset(VectorOffset) {}
  6880. };
  6881. } // end anonymous namespace
  6882. /// Recursively traverses the expression calculating the origin of the requested
  6883. /// byte of the given value. Returns std::nullopt if the provider can't be
  6884. /// calculated.
  6885. ///
  6886. /// For all the values except the root of the expression, we verify that the
  6887. /// value has exactly one use and if not then return std::nullopt. This way if
  6888. /// the origin of the byte is returned it's guaranteed that the values which
  6889. /// contribute to the byte are not used outside of this expression.
  6890. /// However, there is a special case when dealing with vector loads -- we allow
  6891. /// more than one use if the load is a vector type. Since the values that
  6892. /// contribute to the byte ultimately come from the ExtractVectorElements of the
  6893. /// Load, we don't care if the Load has uses other than ExtractVectorElements,
  6894. /// because those operations are independent from the pattern to be combined.
  6895. /// For vector loads, we simply care that the ByteProviders are adjacent
  6896. /// positions of the same vector, and their index matches the byte that is being
  6897. /// provided. This is captured by the \p VectorIndex algorithm. \p VectorIndex
  6898. /// is the index used in an ExtractVectorElement, and \p StartingIndex is the
  6899. /// byte position we are trying to provide for the LoadCombine. If these do
  6900. /// not match, then we can not combine the vector loads. \p Index uses the
  6901. /// byte position we are trying to provide for and is matched against the
  6902. /// shl and load size. The \p Index algorithm ensures the requested byte is
  6903. /// provided for by the pattern, and the pattern does not over provide bytes.
  6904. ///
  6905. ///
  6906. /// The supported LoadCombine pattern for vector loads is as follows
  6907. /// or
  6908. /// / \
  6909. /// or shl
  6910. /// / \ |
  6911. /// or shl zext
  6912. /// / \ | |
  6913. /// shl zext zext EVE*
  6914. /// | | | |
  6915. /// zext EVE* EVE* LOAD
  6916. /// | | |
  6917. /// EVE* LOAD LOAD
  6918. /// |
  6919. /// LOAD
  6920. ///
  6921. /// *ExtractVectorElement
  6922. static const std::optional<ByteProvider>
  6923. calculateByteProvider(SDValue Op, unsigned Index, unsigned Depth,
  6924. std::optional<uint64_t> VectorIndex,
  6925. unsigned StartingIndex = 0) {
  6926. // Typical i64 by i8 pattern requires recursion up to 8 calls depth
  6927. if (Depth == 10)
  6928. return std::nullopt;
  6929. // Only allow multiple uses if the instruction is a vector load (in which
  6930. // case we will use the load for every ExtractVectorElement)
  6931. if (Depth && !Op.hasOneUse() &&
  6932. (Op.getOpcode() != ISD::LOAD || !Op.getValueType().isVector()))
  6933. return std::nullopt;
  6934. // Fail to combine if we have encountered anything but a LOAD after handling
  6935. // an ExtractVectorElement.
  6936. if (Op.getOpcode() != ISD::LOAD && VectorIndex.has_value())
  6937. return std::nullopt;
  6938. unsigned BitWidth = Op.getValueSizeInBits();
  6939. if (BitWidth % 8 != 0)
  6940. return std::nullopt;
  6941. unsigned ByteWidth = BitWidth / 8;
  6942. assert(Index < ByteWidth && "invalid index requested");
  6943. (void) ByteWidth;
  6944. switch (Op.getOpcode()) {
  6945. case ISD::OR: {
  6946. auto LHS =
  6947. calculateByteProvider(Op->getOperand(0), Index, Depth + 1, VectorIndex);
  6948. if (!LHS)
  6949. return std::nullopt;
  6950. auto RHS =
  6951. calculateByteProvider(Op->getOperand(1), Index, Depth + 1, VectorIndex);
  6952. if (!RHS)
  6953. return std::nullopt;
  6954. if (LHS->isConstantZero())
  6955. return RHS;
  6956. if (RHS->isConstantZero())
  6957. return LHS;
  6958. return std::nullopt;
  6959. }
  6960. case ISD::SHL: {
  6961. auto ShiftOp = dyn_cast<ConstantSDNode>(Op->getOperand(1));
  6962. if (!ShiftOp)
  6963. return std::nullopt;
  6964. uint64_t BitShift = ShiftOp->getZExtValue();
  6965. if (BitShift % 8 != 0)
  6966. return std::nullopt;
  6967. uint64_t ByteShift = BitShift / 8;
  6968. // If we are shifting by an amount greater than the index we are trying to
  6969. // provide, then do not provide anything. Otherwise, subtract the index by
  6970. // the amount we shifted by.
  6971. return Index < ByteShift
  6972. ? ByteProvider::getConstantZero()
  6973. : calculateByteProvider(Op->getOperand(0), Index - ByteShift,
  6974. Depth + 1, VectorIndex, Index);
  6975. }
  6976. case ISD::ANY_EXTEND:
  6977. case ISD::SIGN_EXTEND:
  6978. case ISD::ZERO_EXTEND: {
  6979. SDValue NarrowOp = Op->getOperand(0);
  6980. unsigned NarrowBitWidth = NarrowOp.getScalarValueSizeInBits();
  6981. if (NarrowBitWidth % 8 != 0)
  6982. return std::nullopt;
  6983. uint64_t NarrowByteWidth = NarrowBitWidth / 8;
  6984. if (Index >= NarrowByteWidth)
  6985. return Op.getOpcode() == ISD::ZERO_EXTEND
  6986. ? std::optional<ByteProvider>(ByteProvider::getConstantZero())
  6987. : std::nullopt;
  6988. return calculateByteProvider(NarrowOp, Index, Depth + 1, VectorIndex,
  6989. StartingIndex);
  6990. }
  6991. case ISD::BSWAP:
  6992. return calculateByteProvider(Op->getOperand(0), ByteWidth - Index - 1,
  6993. Depth + 1, VectorIndex, StartingIndex);
  6994. case ISD::EXTRACT_VECTOR_ELT: {
  6995. auto OffsetOp = dyn_cast<ConstantSDNode>(Op->getOperand(1));
  6996. if (!OffsetOp)
  6997. return std::nullopt;
  6998. VectorIndex = OffsetOp->getZExtValue();
  6999. SDValue NarrowOp = Op->getOperand(0);
  7000. unsigned NarrowBitWidth = NarrowOp.getScalarValueSizeInBits();
  7001. if (NarrowBitWidth % 8 != 0)
  7002. return std::nullopt;
  7003. uint64_t NarrowByteWidth = NarrowBitWidth / 8;
  7004. // Check to see if the position of the element in the vector corresponds
  7005. // with the byte we are trying to provide for. In the case of a vector of
  7006. // i8, this simply means the VectorIndex == StartingIndex. For non i8 cases,
  7007. // the element will provide a range of bytes. For example, if we have a
  7008. // vector of i16s, each element provides two bytes (V[1] provides byte 2 and
  7009. // 3).
  7010. if (*VectorIndex * NarrowByteWidth > StartingIndex)
  7011. return std::nullopt;
  7012. if ((*VectorIndex + 1) * NarrowByteWidth <= StartingIndex)
  7013. return std::nullopt;
  7014. return calculateByteProvider(Op->getOperand(0), Index, Depth + 1,
  7015. VectorIndex, StartingIndex);
  7016. }
  7017. case ISD::LOAD: {
  7018. auto L = cast<LoadSDNode>(Op.getNode());
  7019. if (!L->isSimple() || L->isIndexed())
  7020. return std::nullopt;
  7021. unsigned NarrowBitWidth = L->getMemoryVT().getSizeInBits();
  7022. if (NarrowBitWidth % 8 != 0)
  7023. return std::nullopt;
  7024. uint64_t NarrowByteWidth = NarrowBitWidth / 8;
  7025. // If the width of the load does not reach byte we are trying to provide for
  7026. // and it is not a ZEXTLOAD, then the load does not provide for the byte in
  7027. // question
  7028. if (Index >= NarrowByteWidth)
  7029. return L->getExtensionType() == ISD::ZEXTLOAD
  7030. ? std::optional<ByteProvider>(ByteProvider::getConstantZero())
  7031. : std::nullopt;
  7032. unsigned BPVectorIndex = VectorIndex.value_or(0U);
  7033. return ByteProvider::getMemory(L, Index, BPVectorIndex);
  7034. }
  7035. }
  7036. return std::nullopt;
  7037. }
  7038. static unsigned littleEndianByteAt(unsigned BW, unsigned i) {
  7039. return i;
  7040. }
  7041. static unsigned bigEndianByteAt(unsigned BW, unsigned i) {
  7042. return BW - i - 1;
  7043. }
  7044. // Check if the bytes offsets we are looking at match with either big or
  7045. // little endian value loaded. Return true for big endian, false for little
  7046. // endian, and std::nullopt if match failed.
  7047. static std::optional<bool> isBigEndian(const ArrayRef<int64_t> ByteOffsets,
  7048. int64_t FirstOffset) {
  7049. // The endian can be decided only when it is 2 bytes at least.
  7050. unsigned Width = ByteOffsets.size();
  7051. if (Width < 2)
  7052. return std::nullopt;
  7053. bool BigEndian = true, LittleEndian = true;
  7054. for (unsigned i = 0; i < Width; i++) {
  7055. int64_t CurrentByteOffset = ByteOffsets[i] - FirstOffset;
  7056. LittleEndian &= CurrentByteOffset == littleEndianByteAt(Width, i);
  7057. BigEndian &= CurrentByteOffset == bigEndianByteAt(Width, i);
  7058. if (!BigEndian && !LittleEndian)
  7059. return std::nullopt;
  7060. }
  7061. assert((BigEndian != LittleEndian) && "It should be either big endian or"
  7062. "little endian");
  7063. return BigEndian;
  7064. }
  7065. static SDValue stripTruncAndExt(SDValue Value) {
  7066. switch (Value.getOpcode()) {
  7067. case ISD::TRUNCATE:
  7068. case ISD::ZERO_EXTEND:
  7069. case ISD::SIGN_EXTEND:
  7070. case ISD::ANY_EXTEND:
  7071. return stripTruncAndExt(Value.getOperand(0));
  7072. }
  7073. return Value;
  7074. }
  7075. /// Match a pattern where a wide type scalar value is stored by several narrow
  7076. /// stores. Fold it into a single store or a BSWAP and a store if the targets
  7077. /// supports it.
  7078. ///
  7079. /// Assuming little endian target:
  7080. /// i8 *p = ...
  7081. /// i32 val = ...
  7082. /// p[0] = (val >> 0) & 0xFF;
  7083. /// p[1] = (val >> 8) & 0xFF;
  7084. /// p[2] = (val >> 16) & 0xFF;
  7085. /// p[3] = (val >> 24) & 0xFF;
  7086. /// =>
  7087. /// *((i32)p) = val;
  7088. ///
  7089. /// i8 *p = ...
  7090. /// i32 val = ...
  7091. /// p[0] = (val >> 24) & 0xFF;
  7092. /// p[1] = (val >> 16) & 0xFF;
  7093. /// p[2] = (val >> 8) & 0xFF;
  7094. /// p[3] = (val >> 0) & 0xFF;
  7095. /// =>
  7096. /// *((i32)p) = BSWAP(val);
  7097. SDValue DAGCombiner::mergeTruncStores(StoreSDNode *N) {
  7098. // The matching looks for "store (trunc x)" patterns that appear early but are
  7099. // likely to be replaced by truncating store nodes during combining.
  7100. // TODO: If there is evidence that running this later would help, this
  7101. // limitation could be removed. Legality checks may need to be added
  7102. // for the created store and optional bswap/rotate.
  7103. if (LegalOperations || OptLevel == CodeGenOpt::None)
  7104. return SDValue();
  7105. // We only handle merging simple stores of 1-4 bytes.
  7106. // TODO: Allow unordered atomics when wider type is legal (see D66309)
  7107. EVT MemVT = N->getMemoryVT();
  7108. if (!(MemVT == MVT::i8 || MemVT == MVT::i16 || MemVT == MVT::i32) ||
  7109. !N->isSimple() || N->isIndexed())
  7110. return SDValue();
  7111. // Collect all of the stores in the chain.
  7112. SDValue Chain = N->getChain();
  7113. SmallVector<StoreSDNode *, 8> Stores = {N};
  7114. while (auto *Store = dyn_cast<StoreSDNode>(Chain)) {
  7115. // All stores must be the same size to ensure that we are writing all of the
  7116. // bytes in the wide value.
  7117. // This store should have exactly one use as a chain operand for another
  7118. // store in the merging set. If there are other chain uses, then the
  7119. // transform may not be safe because order of loads/stores outside of this
  7120. // set may not be preserved.
  7121. // TODO: We could allow multiple sizes by tracking each stored byte.
  7122. if (Store->getMemoryVT() != MemVT || !Store->isSimple() ||
  7123. Store->isIndexed() || !Store->hasOneUse())
  7124. return SDValue();
  7125. Stores.push_back(Store);
  7126. Chain = Store->getChain();
  7127. }
  7128. // There is no reason to continue if we do not have at least a pair of stores.
  7129. if (Stores.size() < 2)
  7130. return SDValue();
  7131. // Handle simple types only.
  7132. LLVMContext &Context = *DAG.getContext();
  7133. unsigned NumStores = Stores.size();
  7134. unsigned NarrowNumBits = N->getMemoryVT().getScalarSizeInBits();
  7135. unsigned WideNumBits = NumStores * NarrowNumBits;
  7136. EVT WideVT = EVT::getIntegerVT(Context, WideNumBits);
  7137. if (WideVT != MVT::i16 && WideVT != MVT::i32 && WideVT != MVT::i64)
  7138. return SDValue();
  7139. // Check if all bytes of the source value that we are looking at are stored
  7140. // to the same base address. Collect offsets from Base address into OffsetMap.
  7141. SDValue SourceValue;
  7142. SmallVector<int64_t, 8> OffsetMap(NumStores, INT64_MAX);
  7143. int64_t FirstOffset = INT64_MAX;
  7144. StoreSDNode *FirstStore = nullptr;
  7145. std::optional<BaseIndexOffset> Base;
  7146. for (auto *Store : Stores) {
  7147. // All the stores store different parts of the CombinedValue. A truncate is
  7148. // required to get the partial value.
  7149. SDValue Trunc = Store->getValue();
  7150. if (Trunc.getOpcode() != ISD::TRUNCATE)
  7151. return SDValue();
  7152. // Other than the first/last part, a shift operation is required to get the
  7153. // offset.
  7154. int64_t Offset = 0;
  7155. SDValue WideVal = Trunc.getOperand(0);
  7156. if ((WideVal.getOpcode() == ISD::SRL || WideVal.getOpcode() == ISD::SRA) &&
  7157. isa<ConstantSDNode>(WideVal.getOperand(1))) {
  7158. // The shift amount must be a constant multiple of the narrow type.
  7159. // It is translated to the offset address in the wide source value "y".
  7160. //
  7161. // x = srl y, ShiftAmtC
  7162. // i8 z = trunc x
  7163. // store z, ...
  7164. uint64_t ShiftAmtC = WideVal.getConstantOperandVal(1);
  7165. if (ShiftAmtC % NarrowNumBits != 0)
  7166. return SDValue();
  7167. Offset = ShiftAmtC / NarrowNumBits;
  7168. WideVal = WideVal.getOperand(0);
  7169. }
  7170. // Stores must share the same source value with different offsets.
  7171. // Truncate and extends should be stripped to get the single source value.
  7172. if (!SourceValue)
  7173. SourceValue = WideVal;
  7174. else if (stripTruncAndExt(SourceValue) != stripTruncAndExt(WideVal))
  7175. return SDValue();
  7176. else if (SourceValue.getValueType() != WideVT) {
  7177. if (WideVal.getValueType() == WideVT ||
  7178. WideVal.getScalarValueSizeInBits() >
  7179. SourceValue.getScalarValueSizeInBits())
  7180. SourceValue = WideVal;
  7181. // Give up if the source value type is smaller than the store size.
  7182. if (SourceValue.getScalarValueSizeInBits() < WideVT.getScalarSizeInBits())
  7183. return SDValue();
  7184. }
  7185. // Stores must share the same base address.
  7186. BaseIndexOffset Ptr = BaseIndexOffset::match(Store, DAG);
  7187. int64_t ByteOffsetFromBase = 0;
  7188. if (!Base)
  7189. Base = Ptr;
  7190. else if (!Base->equalBaseIndex(Ptr, DAG, ByteOffsetFromBase))
  7191. return SDValue();
  7192. // Remember the first store.
  7193. if (ByteOffsetFromBase < FirstOffset) {
  7194. FirstStore = Store;
  7195. FirstOffset = ByteOffsetFromBase;
  7196. }
  7197. // Map the offset in the store and the offset in the combined value, and
  7198. // early return if it has been set before.
  7199. if (Offset < 0 || Offset >= NumStores || OffsetMap[Offset] != INT64_MAX)
  7200. return SDValue();
  7201. OffsetMap[Offset] = ByteOffsetFromBase;
  7202. }
  7203. assert(FirstOffset != INT64_MAX && "First byte offset must be set");
  7204. assert(FirstStore && "First store must be set");
  7205. // Check that a store of the wide type is both allowed and fast on the target
  7206. const DataLayout &Layout = DAG.getDataLayout();
  7207. unsigned Fast = 0;
  7208. bool Allowed = TLI.allowsMemoryAccess(Context, Layout, WideVT,
  7209. *FirstStore->getMemOperand(), &Fast);
  7210. if (!Allowed || !Fast)
  7211. return SDValue();
  7212. // Check if the pieces of the value are going to the expected places in memory
  7213. // to merge the stores.
  7214. auto checkOffsets = [&](bool MatchLittleEndian) {
  7215. if (MatchLittleEndian) {
  7216. for (unsigned i = 0; i != NumStores; ++i)
  7217. if (OffsetMap[i] != i * (NarrowNumBits / 8) + FirstOffset)
  7218. return false;
  7219. } else { // MatchBigEndian by reversing loop counter.
  7220. for (unsigned i = 0, j = NumStores - 1; i != NumStores; ++i, --j)
  7221. if (OffsetMap[j] != i * (NarrowNumBits / 8) + FirstOffset)
  7222. return false;
  7223. }
  7224. return true;
  7225. };
  7226. // Check if the offsets line up for the native data layout of this target.
  7227. bool NeedBswap = false;
  7228. bool NeedRotate = false;
  7229. if (!checkOffsets(Layout.isLittleEndian())) {
  7230. // Special-case: check if byte offsets line up for the opposite endian.
  7231. if (NarrowNumBits == 8 && checkOffsets(Layout.isBigEndian()))
  7232. NeedBswap = true;
  7233. else if (NumStores == 2 && checkOffsets(Layout.isBigEndian()))
  7234. NeedRotate = true;
  7235. else
  7236. return SDValue();
  7237. }
  7238. SDLoc DL(N);
  7239. if (WideVT != SourceValue.getValueType()) {
  7240. assert(SourceValue.getValueType().getScalarSizeInBits() > WideNumBits &&
  7241. "Unexpected store value to merge");
  7242. SourceValue = DAG.getNode(ISD::TRUNCATE, DL, WideVT, SourceValue);
  7243. }
  7244. // Before legalize we can introduce illegal bswaps/rotates which will be later
  7245. // converted to an explicit bswap sequence. This way we end up with a single
  7246. // store and byte shuffling instead of several stores and byte shuffling.
  7247. if (NeedBswap) {
  7248. SourceValue = DAG.getNode(ISD::BSWAP, DL, WideVT, SourceValue);
  7249. } else if (NeedRotate) {
  7250. assert(WideNumBits % 2 == 0 && "Unexpected type for rotate");
  7251. SDValue RotAmt = DAG.getConstant(WideNumBits / 2, DL, WideVT);
  7252. SourceValue = DAG.getNode(ISD::ROTR, DL, WideVT, SourceValue, RotAmt);
  7253. }
  7254. SDValue NewStore =
  7255. DAG.getStore(Chain, DL, SourceValue, FirstStore->getBasePtr(),
  7256. FirstStore->getPointerInfo(), FirstStore->getAlign());
  7257. // Rely on other DAG combine rules to remove the other individual stores.
  7258. DAG.ReplaceAllUsesWith(N, NewStore.getNode());
  7259. return NewStore;
  7260. }
  7261. /// Match a pattern where a wide type scalar value is loaded by several narrow
  7262. /// loads and combined by shifts and ors. Fold it into a single load or a load
  7263. /// and a BSWAP if the targets supports it.
  7264. ///
  7265. /// Assuming little endian target:
  7266. /// i8 *a = ...
  7267. /// i32 val = a[0] | (a[1] << 8) | (a[2] << 16) | (a[3] << 24)
  7268. /// =>
  7269. /// i32 val = *((i32)a)
  7270. ///
  7271. /// i8 *a = ...
  7272. /// i32 val = (a[0] << 24) | (a[1] << 16) | (a[2] << 8) | a[3]
  7273. /// =>
  7274. /// i32 val = BSWAP(*((i32)a))
  7275. ///
  7276. /// TODO: This rule matches complex patterns with OR node roots and doesn't
  7277. /// interact well with the worklist mechanism. When a part of the pattern is
  7278. /// updated (e.g. one of the loads) its direct users are put into the worklist,
  7279. /// but the root node of the pattern which triggers the load combine is not
  7280. /// necessarily a direct user of the changed node. For example, once the address
  7281. /// of t28 load is reassociated load combine won't be triggered:
  7282. /// t25: i32 = add t4, Constant:i32<2>
  7283. /// t26: i64 = sign_extend t25
  7284. /// t27: i64 = add t2, t26
  7285. /// t28: i8,ch = load<LD1[%tmp9]> t0, t27, undef:i64
  7286. /// t29: i32 = zero_extend t28
  7287. /// t32: i32 = shl t29, Constant:i8<8>
  7288. /// t33: i32 = or t23, t32
  7289. /// As a possible fix visitLoad can check if the load can be a part of a load
  7290. /// combine pattern and add corresponding OR roots to the worklist.
  7291. SDValue DAGCombiner::MatchLoadCombine(SDNode *N) {
  7292. assert(N->getOpcode() == ISD::OR &&
  7293. "Can only match load combining against OR nodes");
  7294. // Handles simple types only
  7295. EVT VT = N->getValueType(0);
  7296. if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
  7297. return SDValue();
  7298. unsigned ByteWidth = VT.getSizeInBits() / 8;
  7299. bool IsBigEndianTarget = DAG.getDataLayout().isBigEndian();
  7300. auto MemoryByteOffset = [&] (ByteProvider P) {
  7301. assert(P.isMemory() && "Must be a memory byte provider");
  7302. unsigned LoadBitWidth = P.Load->getMemoryVT().getScalarSizeInBits();
  7303. assert(LoadBitWidth % 8 == 0 &&
  7304. "can only analyze providers for individual bytes not bit");
  7305. unsigned LoadByteWidth = LoadBitWidth / 8;
  7306. return IsBigEndianTarget
  7307. ? bigEndianByteAt(LoadByteWidth, P.ByteOffset)
  7308. : littleEndianByteAt(LoadByteWidth, P.ByteOffset);
  7309. };
  7310. std::optional<BaseIndexOffset> Base;
  7311. SDValue Chain;
  7312. SmallPtrSet<LoadSDNode *, 8> Loads;
  7313. std::optional<ByteProvider> FirstByteProvider;
  7314. int64_t FirstOffset = INT64_MAX;
  7315. // Check if all the bytes of the OR we are looking at are loaded from the same
  7316. // base address. Collect bytes offsets from Base address in ByteOffsets.
  7317. SmallVector<int64_t, 8> ByteOffsets(ByteWidth);
  7318. unsigned ZeroExtendedBytes = 0;
  7319. for (int i = ByteWidth - 1; i >= 0; --i) {
  7320. auto P =
  7321. calculateByteProvider(SDValue(N, 0), i, 0, /*VectorIndex*/ std::nullopt,
  7322. /*StartingIndex*/ i);
  7323. if (!P)
  7324. return SDValue();
  7325. if (P->isConstantZero()) {
  7326. // It's OK for the N most significant bytes to be 0, we can just
  7327. // zero-extend the load.
  7328. if (++ZeroExtendedBytes != (ByteWidth - static_cast<unsigned>(i)))
  7329. return SDValue();
  7330. continue;
  7331. }
  7332. assert(P->isMemory() && "provenance should either be memory or zero");
  7333. LoadSDNode *L = P->Load;
  7334. // All loads must share the same chain
  7335. SDValue LChain = L->getChain();
  7336. if (!Chain)
  7337. Chain = LChain;
  7338. else if (Chain != LChain)
  7339. return SDValue();
  7340. // Loads must share the same base address
  7341. BaseIndexOffset Ptr = BaseIndexOffset::match(L, DAG);
  7342. int64_t ByteOffsetFromBase = 0;
  7343. // For vector loads, the expected load combine pattern will have an
  7344. // ExtractElement for each index in the vector. While each of these
  7345. // ExtractElements will be accessing the same base address as determined
  7346. // by the load instruction, the actual bytes they interact with will differ
  7347. // due to different ExtractElement indices. To accurately determine the
  7348. // byte position of an ExtractElement, we offset the base load ptr with
  7349. // the index multiplied by the byte size of each element in the vector.
  7350. if (L->getMemoryVT().isVector()) {
  7351. unsigned LoadWidthInBit = L->getMemoryVT().getScalarSizeInBits();
  7352. if (LoadWidthInBit % 8 != 0)
  7353. return SDValue();
  7354. unsigned ByteOffsetFromVector = P->VectorOffset * LoadWidthInBit / 8;
  7355. Ptr.addToOffset(ByteOffsetFromVector);
  7356. }
  7357. if (!Base)
  7358. Base = Ptr;
  7359. else if (!Base->equalBaseIndex(Ptr, DAG, ByteOffsetFromBase))
  7360. return SDValue();
  7361. // Calculate the offset of the current byte from the base address
  7362. ByteOffsetFromBase += MemoryByteOffset(*P);
  7363. ByteOffsets[i] = ByteOffsetFromBase;
  7364. // Remember the first byte load
  7365. if (ByteOffsetFromBase < FirstOffset) {
  7366. FirstByteProvider = P;
  7367. FirstOffset = ByteOffsetFromBase;
  7368. }
  7369. Loads.insert(L);
  7370. }
  7371. assert(!Loads.empty() && "All the bytes of the value must be loaded from "
  7372. "memory, so there must be at least one load which produces the value");
  7373. assert(Base && "Base address of the accessed memory location must be set");
  7374. assert(FirstOffset != INT64_MAX && "First byte offset must be set");
  7375. bool NeedsZext = ZeroExtendedBytes > 0;
  7376. EVT MemVT =
  7377. EVT::getIntegerVT(*DAG.getContext(), (ByteWidth - ZeroExtendedBytes) * 8);
  7378. if (!MemVT.isSimple())
  7379. return SDValue();
  7380. // Before legalize we can introduce too wide illegal loads which will be later
  7381. // split into legal sized loads. This enables us to combine i64 load by i8
  7382. // patterns to a couple of i32 loads on 32 bit targets.
  7383. if (LegalOperations &&
  7384. !TLI.isOperationLegal(NeedsZext ? ISD::ZEXTLOAD : ISD::NON_EXTLOAD,
  7385. MemVT))
  7386. return SDValue();
  7387. // Check if the bytes of the OR we are looking at match with either big or
  7388. // little endian value load
  7389. std::optional<bool> IsBigEndian = isBigEndian(
  7390. ArrayRef(ByteOffsets).drop_back(ZeroExtendedBytes), FirstOffset);
  7391. if (!IsBigEndian)
  7392. return SDValue();
  7393. assert(FirstByteProvider && "must be set");
  7394. // Ensure that the first byte is loaded from zero offset of the first load.
  7395. // So the combined value can be loaded from the first load address.
  7396. if (MemoryByteOffset(*FirstByteProvider) != 0)
  7397. return SDValue();
  7398. LoadSDNode *FirstLoad = FirstByteProvider->Load;
  7399. // The node we are looking at matches with the pattern, check if we can
  7400. // replace it with a single (possibly zero-extended) load and bswap + shift if
  7401. // needed.
  7402. // If the load needs byte swap check if the target supports it
  7403. bool NeedsBswap = IsBigEndianTarget != *IsBigEndian;
  7404. // Before legalize we can introduce illegal bswaps which will be later
  7405. // converted to an explicit bswap sequence. This way we end up with a single
  7406. // load and byte shuffling instead of several loads and byte shuffling.
  7407. // We do not introduce illegal bswaps when zero-extending as this tends to
  7408. // introduce too many arithmetic instructions.
  7409. if (NeedsBswap && (LegalOperations || NeedsZext) &&
  7410. !TLI.isOperationLegal(ISD::BSWAP, VT))
  7411. return SDValue();
  7412. // If we need to bswap and zero extend, we have to insert a shift. Check that
  7413. // it is legal.
  7414. if (NeedsBswap && NeedsZext && LegalOperations &&
  7415. !TLI.isOperationLegal(ISD::SHL, VT))
  7416. return SDValue();
  7417. // Check that a load of the wide type is both allowed and fast on the target
  7418. unsigned Fast = 0;
  7419. bool Allowed =
  7420. TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), MemVT,
  7421. *FirstLoad->getMemOperand(), &Fast);
  7422. if (!Allowed || !Fast)
  7423. return SDValue();
  7424. SDValue NewLoad =
  7425. DAG.getExtLoad(NeedsZext ? ISD::ZEXTLOAD : ISD::NON_EXTLOAD, SDLoc(N), VT,
  7426. Chain, FirstLoad->getBasePtr(),
  7427. FirstLoad->getPointerInfo(), MemVT, FirstLoad->getAlign());
  7428. // Transfer chain users from old loads to the new load.
  7429. for (LoadSDNode *L : Loads)
  7430. DAG.ReplaceAllUsesOfValueWith(SDValue(L, 1), SDValue(NewLoad.getNode(), 1));
  7431. if (!NeedsBswap)
  7432. return NewLoad;
  7433. SDValue ShiftedLoad =
  7434. NeedsZext
  7435. ? DAG.getNode(ISD::SHL, SDLoc(N), VT, NewLoad,
  7436. DAG.getShiftAmountConstant(ZeroExtendedBytes * 8, VT,
  7437. SDLoc(N), LegalOperations))
  7438. : NewLoad;
  7439. return DAG.getNode(ISD::BSWAP, SDLoc(N), VT, ShiftedLoad);
  7440. }
  7441. // If the target has andn, bsl, or a similar bit-select instruction,
  7442. // we want to unfold masked merge, with canonical pattern of:
  7443. // | A | |B|
  7444. // ((x ^ y) & m) ^ y
  7445. // | D |
  7446. // Into:
  7447. // (x & m) | (y & ~m)
  7448. // If y is a constant, m is not a 'not', and the 'andn' does not work with
  7449. // immediates, we unfold into a different pattern:
  7450. // ~(~x & m) & (m | y)
  7451. // If x is a constant, m is a 'not', and the 'andn' does not work with
  7452. // immediates, we unfold into a different pattern:
  7453. // (x | ~m) & ~(~m & ~y)
  7454. // NOTE: we don't unfold the pattern if 'xor' is actually a 'not', because at
  7455. // the very least that breaks andnpd / andnps patterns, and because those
  7456. // patterns are simplified in IR and shouldn't be created in the DAG
  7457. SDValue DAGCombiner::unfoldMaskedMerge(SDNode *N) {
  7458. assert(N->getOpcode() == ISD::XOR);
  7459. // Don't touch 'not' (i.e. where y = -1).
  7460. if (isAllOnesOrAllOnesSplat(N->getOperand(1)))
  7461. return SDValue();
  7462. EVT VT = N->getValueType(0);
  7463. // There are 3 commutable operators in the pattern,
  7464. // so we have to deal with 8 possible variants of the basic pattern.
  7465. SDValue X, Y, M;
  7466. auto matchAndXor = [&X, &Y, &M](SDValue And, unsigned XorIdx, SDValue Other) {
  7467. if (And.getOpcode() != ISD::AND || !And.hasOneUse())
  7468. return false;
  7469. SDValue Xor = And.getOperand(XorIdx);
  7470. if (Xor.getOpcode() != ISD::XOR || !Xor.hasOneUse())
  7471. return false;
  7472. SDValue Xor0 = Xor.getOperand(0);
  7473. SDValue Xor1 = Xor.getOperand(1);
  7474. // Don't touch 'not' (i.e. where y = -1).
  7475. if (isAllOnesOrAllOnesSplat(Xor1))
  7476. return false;
  7477. if (Other == Xor0)
  7478. std::swap(Xor0, Xor1);
  7479. if (Other != Xor1)
  7480. return false;
  7481. X = Xor0;
  7482. Y = Xor1;
  7483. M = And.getOperand(XorIdx ? 0 : 1);
  7484. return true;
  7485. };
  7486. SDValue N0 = N->getOperand(0);
  7487. SDValue N1 = N->getOperand(1);
  7488. if (!matchAndXor(N0, 0, N1) && !matchAndXor(N0, 1, N1) &&
  7489. !matchAndXor(N1, 0, N0) && !matchAndXor(N1, 1, N0))
  7490. return SDValue();
  7491. // Don't do anything if the mask is constant. This should not be reachable.
  7492. // InstCombine should have already unfolded this pattern, and DAGCombiner
  7493. // probably shouldn't produce it, too.
  7494. if (isa<ConstantSDNode>(M.getNode()))
  7495. return SDValue();
  7496. // We can transform if the target has AndNot
  7497. if (!TLI.hasAndNot(M))
  7498. return SDValue();
  7499. SDLoc DL(N);
  7500. // If Y is a constant, check that 'andn' works with immediates. Unless M is
  7501. // a bitwise not that would already allow ANDN to be used.
  7502. if (!TLI.hasAndNot(Y) && !isBitwiseNot(M)) {
  7503. assert(TLI.hasAndNot(X) && "Only mask is a variable? Unreachable.");
  7504. // If not, we need to do a bit more work to make sure andn is still used.
  7505. SDValue NotX = DAG.getNOT(DL, X, VT);
  7506. SDValue LHS = DAG.getNode(ISD::AND, DL, VT, NotX, M);
  7507. SDValue NotLHS = DAG.getNOT(DL, LHS, VT);
  7508. SDValue RHS = DAG.getNode(ISD::OR, DL, VT, M, Y);
  7509. return DAG.getNode(ISD::AND, DL, VT, NotLHS, RHS);
  7510. }
  7511. // If X is a constant and M is a bitwise not, check that 'andn' works with
  7512. // immediates.
  7513. if (!TLI.hasAndNot(X) && isBitwiseNot(M)) {
  7514. assert(TLI.hasAndNot(Y) && "Only mask is a variable? Unreachable.");
  7515. // If not, we need to do a bit more work to make sure andn is still used.
  7516. SDValue NotM = M.getOperand(0);
  7517. SDValue LHS = DAG.getNode(ISD::OR, DL, VT, X, NotM);
  7518. SDValue NotY = DAG.getNOT(DL, Y, VT);
  7519. SDValue RHS = DAG.getNode(ISD::AND, DL, VT, NotM, NotY);
  7520. SDValue NotRHS = DAG.getNOT(DL, RHS, VT);
  7521. return DAG.getNode(ISD::AND, DL, VT, LHS, NotRHS);
  7522. }
  7523. SDValue LHS = DAG.getNode(ISD::AND, DL, VT, X, M);
  7524. SDValue NotM = DAG.getNOT(DL, M, VT);
  7525. SDValue RHS = DAG.getNode(ISD::AND, DL, VT, Y, NotM);
  7526. return DAG.getNode(ISD::OR, DL, VT, LHS, RHS);
  7527. }
  7528. SDValue DAGCombiner::visitXOR(SDNode *N) {
  7529. SDValue N0 = N->getOperand(0);
  7530. SDValue N1 = N->getOperand(1);
  7531. EVT VT = N0.getValueType();
  7532. SDLoc DL(N);
  7533. // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
  7534. if (N0.isUndef() && N1.isUndef())
  7535. return DAG.getConstant(0, DL, VT);
  7536. // fold (xor x, undef) -> undef
  7537. if (N0.isUndef())
  7538. return N0;
  7539. if (N1.isUndef())
  7540. return N1;
  7541. // fold (xor c1, c2) -> c1^c2
  7542. if (SDValue C = DAG.FoldConstantArithmetic(ISD::XOR, DL, VT, {N0, N1}))
  7543. return C;
  7544. // canonicalize constant to RHS
  7545. if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
  7546. !DAG.isConstantIntBuildVectorOrConstantInt(N1))
  7547. return DAG.getNode(ISD::XOR, DL, VT, N1, N0);
  7548. // fold vector ops
  7549. if (VT.isVector()) {
  7550. if (SDValue FoldedVOp = SimplifyVBinOp(N, DL))
  7551. return FoldedVOp;
  7552. // fold (xor x, 0) -> x, vector edition
  7553. if (ISD::isConstantSplatVectorAllZeros(N1.getNode()))
  7554. return N0;
  7555. }
  7556. // fold (xor x, 0) -> x
  7557. if (isNullConstant(N1))
  7558. return N0;
  7559. if (SDValue NewSel = foldBinOpIntoSelect(N))
  7560. return NewSel;
  7561. // reassociate xor
  7562. if (SDValue RXOR = reassociateOps(ISD::XOR, DL, N0, N1, N->getFlags()))
  7563. return RXOR;
  7564. // fold (a^b) -> (a|b) iff a and b share no bits.
  7565. if ((!LegalOperations || TLI.isOperationLegal(ISD::OR, VT)) &&
  7566. DAG.haveNoCommonBitsSet(N0, N1))
  7567. return DAG.getNode(ISD::OR, DL, VT, N0, N1);
  7568. // look for 'add-like' folds:
  7569. // XOR(N0,MIN_SIGNED_VALUE) == ADD(N0,MIN_SIGNED_VALUE)
  7570. if ((!LegalOperations || TLI.isOperationLegal(ISD::ADD, VT)) &&
  7571. isMinSignedConstant(N1))
  7572. if (SDValue Combined = visitADDLike(N))
  7573. return Combined;
  7574. // fold !(x cc y) -> (x !cc y)
  7575. unsigned N0Opcode = N0.getOpcode();
  7576. SDValue LHS, RHS, CC;
  7577. if (TLI.isConstTrueVal(N1) &&
  7578. isSetCCEquivalent(N0, LHS, RHS, CC, /*MatchStrict*/ true)) {
  7579. ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
  7580. LHS.getValueType());
  7581. if (!LegalOperations ||
  7582. TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
  7583. switch (N0Opcode) {
  7584. default:
  7585. llvm_unreachable("Unhandled SetCC Equivalent!");
  7586. case ISD::SETCC:
  7587. return DAG.getSetCC(SDLoc(N0), VT, LHS, RHS, NotCC);
  7588. case ISD::SELECT_CC:
  7589. return DAG.getSelectCC(SDLoc(N0), LHS, RHS, N0.getOperand(2),
  7590. N0.getOperand(3), NotCC);
  7591. case ISD::STRICT_FSETCC:
  7592. case ISD::STRICT_FSETCCS: {
  7593. if (N0.hasOneUse()) {
  7594. // FIXME Can we handle multiple uses? Could we token factor the chain
  7595. // results from the new/old setcc?
  7596. SDValue SetCC =
  7597. DAG.getSetCC(SDLoc(N0), VT, LHS, RHS, NotCC,
  7598. N0.getOperand(0), N0Opcode == ISD::STRICT_FSETCCS);
  7599. CombineTo(N, SetCC);
  7600. DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), SetCC.getValue(1));
  7601. recursivelyDeleteUnusedNodes(N0.getNode());
  7602. return SDValue(N, 0); // Return N so it doesn't get rechecked!
  7603. }
  7604. break;
  7605. }
  7606. }
  7607. }
  7608. }
  7609. // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
  7610. if (isOneConstant(N1) && N0Opcode == ISD::ZERO_EXTEND && N0.hasOneUse() &&
  7611. isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
  7612. SDValue V = N0.getOperand(0);
  7613. SDLoc DL0(N0);
  7614. V = DAG.getNode(ISD::XOR, DL0, V.getValueType(), V,
  7615. DAG.getConstant(1, DL0, V.getValueType()));
  7616. AddToWorklist(V.getNode());
  7617. return DAG.getNode(ISD::ZERO_EXTEND, DL, VT, V);
  7618. }
  7619. // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
  7620. if (isOneConstant(N1) && VT == MVT::i1 && N0.hasOneUse() &&
  7621. (N0Opcode == ISD::OR || N0Opcode == ISD::AND)) {
  7622. SDValue N00 = N0.getOperand(0), N01 = N0.getOperand(1);
  7623. if (isOneUseSetCC(N01) || isOneUseSetCC(N00)) {
  7624. unsigned NewOpcode = N0Opcode == ISD::AND ? ISD::OR : ISD::AND;
  7625. N00 = DAG.getNode(ISD::XOR, SDLoc(N00), VT, N00, N1); // N00 = ~N00
  7626. N01 = DAG.getNode(ISD::XOR, SDLoc(N01), VT, N01, N1); // N01 = ~N01
  7627. AddToWorklist(N00.getNode()); AddToWorklist(N01.getNode());
  7628. return DAG.getNode(NewOpcode, DL, VT, N00, N01);
  7629. }
  7630. }
  7631. // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
  7632. if (isAllOnesConstant(N1) && N0.hasOneUse() &&
  7633. (N0Opcode == ISD::OR || N0Opcode == ISD::AND)) {
  7634. SDValue N00 = N0.getOperand(0), N01 = N0.getOperand(1);
  7635. if (isa<ConstantSDNode>(N01) || isa<ConstantSDNode>(N00)) {
  7636. unsigned NewOpcode = N0Opcode == ISD::AND ? ISD::OR : ISD::AND;
  7637. N00 = DAG.getNode(ISD::XOR, SDLoc(N00), VT, N00, N1); // N00 = ~N00
  7638. N01 = DAG.getNode(ISD::XOR, SDLoc(N01), VT, N01, N1); // N01 = ~N01
  7639. AddToWorklist(N00.getNode()); AddToWorklist(N01.getNode());
  7640. return DAG.getNode(NewOpcode, DL, VT, N00, N01);
  7641. }
  7642. }
  7643. // fold (not (neg x)) -> (add X, -1)
  7644. // FIXME: This can be generalized to (not (sub Y, X)) -> (add X, ~Y) if
  7645. // Y is a constant or the subtract has a single use.
  7646. if (isAllOnesConstant(N1) && N0.getOpcode() == ISD::SUB &&
  7647. isNullConstant(N0.getOperand(0))) {
  7648. return DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(1),
  7649. DAG.getAllOnesConstant(DL, VT));
  7650. }
  7651. // fold (not (add X, -1)) -> (neg X)
  7652. if (isAllOnesConstant(N1) && N0.getOpcode() == ISD::ADD &&
  7653. isAllOnesOrAllOnesSplat(N0.getOperand(1))) {
  7654. return DAG.getNegative(N0.getOperand(0), DL, VT);
  7655. }
  7656. // fold (xor (and x, y), y) -> (and (not x), y)
  7657. if (N0Opcode == ISD::AND && N0.hasOneUse() && N0->getOperand(1) == N1) {
  7658. SDValue X = N0.getOperand(0);
  7659. SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
  7660. AddToWorklist(NotX.getNode());
  7661. return DAG.getNode(ISD::AND, DL, VT, NotX, N1);
  7662. }
  7663. // fold Y = sra (X, size(X)-1); xor (add (X, Y), Y) -> (abs X)
  7664. if (TLI.isOperationLegalOrCustom(ISD::ABS, VT)) {
  7665. SDValue A = N0Opcode == ISD::ADD ? N0 : N1;
  7666. SDValue S = N0Opcode == ISD::SRA ? N0 : N1;
  7667. if (A.getOpcode() == ISD::ADD && S.getOpcode() == ISD::SRA) {
  7668. SDValue A0 = A.getOperand(0), A1 = A.getOperand(1);
  7669. SDValue S0 = S.getOperand(0);
  7670. if ((A0 == S && A1 == S0) || (A1 == S && A0 == S0))
  7671. if (ConstantSDNode *C = isConstOrConstSplat(S.getOperand(1)))
  7672. if (C->getAPIntValue() == (VT.getScalarSizeInBits() - 1))
  7673. return DAG.getNode(ISD::ABS, DL, VT, S0);
  7674. }
  7675. }
  7676. // fold (xor x, x) -> 0
  7677. if (N0 == N1)
  7678. return tryFoldToZero(DL, TLI, VT, DAG, LegalOperations);
  7679. // fold (xor (shl 1, x), -1) -> (rotl ~1, x)
  7680. // Here is a concrete example of this equivalence:
  7681. // i16 x == 14
  7682. // i16 shl == 1 << 14 == 16384 == 0b0100000000000000
  7683. // i16 xor == ~(1 << 14) == 49151 == 0b1011111111111111
  7684. //
  7685. // =>
  7686. //
  7687. // i16 ~1 == 0b1111111111111110
  7688. // i16 rol(~1, 14) == 0b1011111111111111
  7689. //
  7690. // Some additional tips to help conceptualize this transform:
  7691. // - Try to see the operation as placing a single zero in a value of all ones.
  7692. // - There exists no value for x which would allow the result to contain zero.
  7693. // - Values of x larger than the bitwidth are undefined and do not require a
  7694. // consistent result.
  7695. // - Pushing the zero left requires shifting one bits in from the right.
  7696. // A rotate left of ~1 is a nice way of achieving the desired result.
  7697. if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT) && N0Opcode == ISD::SHL &&
  7698. isAllOnesConstant(N1) && isOneConstant(N0.getOperand(0))) {
  7699. return DAG.getNode(ISD::ROTL, DL, VT, DAG.getConstant(~1, DL, VT),
  7700. N0.getOperand(1));
  7701. }
  7702. // Simplify: xor (op x...), (op y...) -> (op (xor x, y))
  7703. if (N0Opcode == N1.getOpcode())
  7704. if (SDValue V = hoistLogicOpWithSameOpcodeHands(N))
  7705. return V;
  7706. if (SDValue R = foldLogicOfShifts(N, N0, N1, DAG))
  7707. return R;
  7708. if (SDValue R = foldLogicOfShifts(N, N1, N0, DAG))
  7709. return R;
  7710. if (SDValue R = foldLogicTreeOfShifts(N, N0, N1, DAG))
  7711. return R;
  7712. // Unfold ((x ^ y) & m) ^ y into (x & m) | (y & ~m) if profitable
  7713. if (SDValue MM = unfoldMaskedMerge(N))
  7714. return MM;
  7715. // Simplify the expression using non-local knowledge.
  7716. if (SimplifyDemandedBits(SDValue(N, 0)))
  7717. return SDValue(N, 0);
  7718. if (SDValue Combined = combineCarryDiamond(DAG, TLI, N0, N1, N))
  7719. return Combined;
  7720. return SDValue();
  7721. }
  7722. /// If we have a shift-by-constant of a bitwise logic op that itself has a
  7723. /// shift-by-constant operand with identical opcode, we may be able to convert
  7724. /// that into 2 independent shifts followed by the logic op. This is a
  7725. /// throughput improvement.
  7726. static SDValue combineShiftOfShiftedLogic(SDNode *Shift, SelectionDAG &DAG) {
  7727. // Match a one-use bitwise logic op.
  7728. SDValue LogicOp = Shift->getOperand(0);
  7729. if (!LogicOp.hasOneUse())
  7730. return SDValue();
  7731. unsigned LogicOpcode = LogicOp.getOpcode();
  7732. if (LogicOpcode != ISD::AND && LogicOpcode != ISD::OR &&
  7733. LogicOpcode != ISD::XOR)
  7734. return SDValue();
  7735. // Find a matching one-use shift by constant.
  7736. unsigned ShiftOpcode = Shift->getOpcode();
  7737. SDValue C1 = Shift->getOperand(1);
  7738. ConstantSDNode *C1Node = isConstOrConstSplat(C1);
  7739. assert(C1Node && "Expected a shift with constant operand");
  7740. const APInt &C1Val = C1Node->getAPIntValue();
  7741. auto matchFirstShift = [&](SDValue V, SDValue &ShiftOp,
  7742. const APInt *&ShiftAmtVal) {
  7743. if (V.getOpcode() != ShiftOpcode || !V.hasOneUse())
  7744. return false;
  7745. ConstantSDNode *ShiftCNode = isConstOrConstSplat(V.getOperand(1));
  7746. if (!ShiftCNode)
  7747. return false;
  7748. // Capture the shifted operand and shift amount value.
  7749. ShiftOp = V.getOperand(0);
  7750. ShiftAmtVal = &ShiftCNode->getAPIntValue();
  7751. // Shift amount types do not have to match their operand type, so check that
  7752. // the constants are the same width.
  7753. if (ShiftAmtVal->getBitWidth() != C1Val.getBitWidth())
  7754. return false;
  7755. // The fold is not valid if the sum of the shift values exceeds bitwidth.
  7756. if ((*ShiftAmtVal + C1Val).uge(V.getScalarValueSizeInBits()))
  7757. return false;
  7758. return true;
  7759. };
  7760. // Logic ops are commutative, so check each operand for a match.
  7761. SDValue X, Y;
  7762. const APInt *C0Val;
  7763. if (matchFirstShift(LogicOp.getOperand(0), X, C0Val))
  7764. Y = LogicOp.getOperand(1);
  7765. else if (matchFirstShift(LogicOp.getOperand(1), X, C0Val))
  7766. Y = LogicOp.getOperand(0);
  7767. else
  7768. return SDValue();
  7769. // shift (logic (shift X, C0), Y), C1 -> logic (shift X, C0+C1), (shift Y, C1)
  7770. SDLoc DL(Shift);
  7771. EVT VT = Shift->getValueType(0);
  7772. EVT ShiftAmtVT = Shift->getOperand(1).getValueType();
  7773. SDValue ShiftSumC = DAG.getConstant(*C0Val + C1Val, DL, ShiftAmtVT);
  7774. SDValue NewShift1 = DAG.getNode(ShiftOpcode, DL, VT, X, ShiftSumC);
  7775. SDValue NewShift2 = DAG.getNode(ShiftOpcode, DL, VT, Y, C1);
  7776. return DAG.getNode(LogicOpcode, DL, VT, NewShift1, NewShift2);
  7777. }
  7778. /// Handle transforms common to the three shifts, when the shift amount is a
  7779. /// constant.
  7780. /// We are looking for: (shift being one of shl/sra/srl)
  7781. /// shift (binop X, C0), C1
  7782. /// And want to transform into:
  7783. /// binop (shift X, C1), (shift C0, C1)
  7784. SDValue DAGCombiner::visitShiftByConstant(SDNode *N) {
  7785. assert(isConstOrConstSplat(N->getOperand(1)) && "Expected constant operand");
  7786. // Do not turn a 'not' into a regular xor.
  7787. if (isBitwiseNot(N->getOperand(0)))
  7788. return SDValue();
  7789. // The inner binop must be one-use, since we want to replace it.
  7790. SDValue LHS = N->getOperand(0);
  7791. if (!LHS.hasOneUse() || !TLI.isDesirableToCommuteWithShift(N, Level))
  7792. return SDValue();
  7793. // Fold shift(bitop(shift(x,c1),y), c2) -> bitop(shift(x,c1+c2),shift(y,c2)).
  7794. if (SDValue R = combineShiftOfShiftedLogic(N, DAG))
  7795. return R;
  7796. // We want to pull some binops through shifts, so that we have (and (shift))
  7797. // instead of (shift (and)), likewise for add, or, xor, etc. This sort of
  7798. // thing happens with address calculations, so it's important to canonicalize
  7799. // it.
  7800. switch (LHS.getOpcode()) {
  7801. default:
  7802. return SDValue();
  7803. case ISD::OR:
  7804. case ISD::XOR:
  7805. case ISD::AND:
  7806. break;
  7807. case ISD::ADD:
  7808. if (N->getOpcode() != ISD::SHL)
  7809. return SDValue(); // only shl(add) not sr[al](add).
  7810. break;
  7811. }
  7812. // FIXME: disable this unless the input to the binop is a shift by a constant
  7813. // or is copy/select. Enable this in other cases when figure out it's exactly
  7814. // profitable.
  7815. SDValue BinOpLHSVal = LHS.getOperand(0);
  7816. bool IsShiftByConstant = (BinOpLHSVal.getOpcode() == ISD::SHL ||
  7817. BinOpLHSVal.getOpcode() == ISD::SRA ||
  7818. BinOpLHSVal.getOpcode() == ISD::SRL) &&
  7819. isa<ConstantSDNode>(BinOpLHSVal.getOperand(1));
  7820. bool IsCopyOrSelect = BinOpLHSVal.getOpcode() == ISD::CopyFromReg ||
  7821. BinOpLHSVal.getOpcode() == ISD::SELECT;
  7822. if (!IsShiftByConstant && !IsCopyOrSelect)
  7823. return SDValue();
  7824. if (IsCopyOrSelect && N->hasOneUse())
  7825. return SDValue();
  7826. // Attempt to fold the constants, shifting the binop RHS by the shift amount.
  7827. SDLoc DL(N);
  7828. EVT VT = N->getValueType(0);
  7829. if (SDValue NewRHS = DAG.FoldConstantArithmetic(
  7830. N->getOpcode(), DL, VT, {LHS.getOperand(1), N->getOperand(1)})) {
  7831. SDValue NewShift = DAG.getNode(N->getOpcode(), DL, VT, LHS.getOperand(0),
  7832. N->getOperand(1));
  7833. return DAG.getNode(LHS.getOpcode(), DL, VT, NewShift, NewRHS);
  7834. }
  7835. return SDValue();
  7836. }
  7837. SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
  7838. assert(N->getOpcode() == ISD::TRUNCATE);
  7839. assert(N->getOperand(0).getOpcode() == ISD::AND);
  7840. // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
  7841. EVT TruncVT = N->getValueType(0);
  7842. if (N->hasOneUse() && N->getOperand(0).hasOneUse() &&
  7843. TLI.isTypeDesirableForOp(ISD::AND, TruncVT)) {
  7844. SDValue N01 = N->getOperand(0).getOperand(1);
  7845. if (isConstantOrConstantVector(N01, /* NoOpaques */ true)) {
  7846. SDLoc DL(N);
  7847. SDValue N00 = N->getOperand(0).getOperand(0);
  7848. SDValue Trunc00 = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N00);
  7849. SDValue Trunc01 = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N01);
  7850. AddToWorklist(Trunc00.getNode());
  7851. AddToWorklist(Trunc01.getNode());
  7852. return DAG.getNode(ISD::AND, DL, TruncVT, Trunc00, Trunc01);
  7853. }
  7854. }
  7855. return SDValue();
  7856. }
  7857. SDValue DAGCombiner::visitRotate(SDNode *N) {
  7858. SDLoc dl(N);
  7859. SDValue N0 = N->getOperand(0);
  7860. SDValue N1 = N->getOperand(1);
  7861. EVT VT = N->getValueType(0);
  7862. unsigned Bitsize = VT.getScalarSizeInBits();
  7863. // fold (rot x, 0) -> x
  7864. if (isNullOrNullSplat(N1))
  7865. return N0;
  7866. // fold (rot x, c) -> x iff (c % BitSize) == 0
  7867. if (isPowerOf2_32(Bitsize) && Bitsize > 1) {
  7868. APInt ModuloMask(N1.getScalarValueSizeInBits(), Bitsize - 1);
  7869. if (DAG.MaskedValueIsZero(N1, ModuloMask))
  7870. return N0;
  7871. }
  7872. // fold (rot x, c) -> (rot x, c % BitSize)
  7873. bool OutOfRange = false;
  7874. auto MatchOutOfRange = [Bitsize, &OutOfRange](ConstantSDNode *C) {
  7875. OutOfRange |= C->getAPIntValue().uge(Bitsize);
  7876. return true;
  7877. };
  7878. if (ISD::matchUnaryPredicate(N1, MatchOutOfRange) && OutOfRange) {
  7879. EVT AmtVT = N1.getValueType();
  7880. SDValue Bits = DAG.getConstant(Bitsize, dl, AmtVT);
  7881. if (SDValue Amt =
  7882. DAG.FoldConstantArithmetic(ISD::UREM, dl, AmtVT, {N1, Bits}))
  7883. return DAG.getNode(N->getOpcode(), dl, VT, N0, Amt);
  7884. }
  7885. // rot i16 X, 8 --> bswap X
  7886. auto *RotAmtC = isConstOrConstSplat(N1);
  7887. if (RotAmtC && RotAmtC->getAPIntValue() == 8 &&
  7888. VT.getScalarSizeInBits() == 16 && hasOperation(ISD::BSWAP, VT))
  7889. return DAG.getNode(ISD::BSWAP, dl, VT, N0);
  7890. // Simplify the operands using demanded-bits information.
  7891. if (SimplifyDemandedBits(SDValue(N, 0)))
  7892. return SDValue(N, 0);
  7893. // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
  7894. if (N1.getOpcode() == ISD::TRUNCATE &&
  7895. N1.getOperand(0).getOpcode() == ISD::AND) {
  7896. if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
  7897. return DAG.getNode(N->getOpcode(), dl, VT, N0, NewOp1);
  7898. }
  7899. unsigned NextOp = N0.getOpcode();
  7900. // fold (rot* (rot* x, c2), c1)
  7901. // -> (rot* x, ((c1 % bitsize) +- (c2 % bitsize) + bitsize) % bitsize)
  7902. if (NextOp == ISD::ROTL || NextOp == ISD::ROTR) {
  7903. SDNode *C1 = DAG.isConstantIntBuildVectorOrConstantInt(N1);
  7904. SDNode *C2 = DAG.isConstantIntBuildVectorOrConstantInt(N0.getOperand(1));
  7905. if (C1 && C2 && C1->getValueType(0) == C2->getValueType(0)) {
  7906. EVT ShiftVT = C1->getValueType(0);
  7907. bool SameSide = (N->getOpcode() == NextOp);
  7908. unsigned CombineOp = SameSide ? ISD::ADD : ISD::SUB;
  7909. SDValue BitsizeC = DAG.getConstant(Bitsize, dl, ShiftVT);
  7910. SDValue Norm1 = DAG.FoldConstantArithmetic(ISD::UREM, dl, ShiftVT,
  7911. {N1, BitsizeC});
  7912. SDValue Norm2 = DAG.FoldConstantArithmetic(ISD::UREM, dl, ShiftVT,
  7913. {N0.getOperand(1), BitsizeC});
  7914. if (Norm1 && Norm2)
  7915. if (SDValue CombinedShift = DAG.FoldConstantArithmetic(
  7916. CombineOp, dl, ShiftVT, {Norm1, Norm2})) {
  7917. CombinedShift = DAG.FoldConstantArithmetic(ISD::ADD, dl, ShiftVT,
  7918. {CombinedShift, BitsizeC});
  7919. SDValue CombinedShiftNorm = DAG.FoldConstantArithmetic(
  7920. ISD::UREM, dl, ShiftVT, {CombinedShift, BitsizeC});
  7921. return DAG.getNode(N->getOpcode(), dl, VT, N0->getOperand(0),
  7922. CombinedShiftNorm);
  7923. }
  7924. }
  7925. }
  7926. return SDValue();
  7927. }
  7928. SDValue DAGCombiner::visitSHL(SDNode *N) {
  7929. SDValue N0 = N->getOperand(0);
  7930. SDValue N1 = N->getOperand(1);
  7931. if (SDValue V = DAG.simplifyShift(N0, N1))
  7932. return V;
  7933. EVT VT = N0.getValueType();
  7934. EVT ShiftVT = N1.getValueType();
  7935. unsigned OpSizeInBits = VT.getScalarSizeInBits();
  7936. // fold (shl c1, c2) -> c1<<c2
  7937. if (SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, {N0, N1}))
  7938. return C;
  7939. // fold vector ops
  7940. if (VT.isVector()) {
  7941. if (SDValue FoldedVOp = SimplifyVBinOp(N, SDLoc(N)))
  7942. return FoldedVOp;
  7943. BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
  7944. // If setcc produces all-one true value then:
  7945. // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
  7946. if (N1CV && N1CV->isConstant()) {
  7947. if (N0.getOpcode() == ISD::AND) {
  7948. SDValue N00 = N0->getOperand(0);
  7949. SDValue N01 = N0->getOperand(1);
  7950. BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
  7951. if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
  7952. TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
  7953. TargetLowering::ZeroOrNegativeOneBooleanContent) {
  7954. if (SDValue C =
  7955. DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, {N01, N1}))
  7956. return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
  7957. }
  7958. }
  7959. }
  7960. }
  7961. if (SDValue NewSel = foldBinOpIntoSelect(N))
  7962. return NewSel;
  7963. // if (shl x, c) is known to be zero, return 0
  7964. if (DAG.MaskedValueIsZero(SDValue(N, 0), APInt::getAllOnes(OpSizeInBits)))
  7965. return DAG.getConstant(0, SDLoc(N), VT);
  7966. // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
  7967. if (N1.getOpcode() == ISD::TRUNCATE &&
  7968. N1.getOperand(0).getOpcode() == ISD::AND) {
  7969. if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
  7970. return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
  7971. }
  7972. if (SimplifyDemandedBits(SDValue(N, 0)))
  7973. return SDValue(N, 0);
  7974. // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
  7975. if (N0.getOpcode() == ISD::SHL) {
  7976. auto MatchOutOfRange = [OpSizeInBits](ConstantSDNode *LHS,
  7977. ConstantSDNode *RHS) {
  7978. APInt c1 = LHS->getAPIntValue();
  7979. APInt c2 = RHS->getAPIntValue();
  7980. zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
  7981. return (c1 + c2).uge(OpSizeInBits);
  7982. };
  7983. if (ISD::matchBinaryPredicate(N1, N0.getOperand(1), MatchOutOfRange))
  7984. return DAG.getConstant(0, SDLoc(N), VT);
  7985. auto MatchInRange = [OpSizeInBits](ConstantSDNode *LHS,
  7986. ConstantSDNode *RHS) {
  7987. APInt c1 = LHS->getAPIntValue();
  7988. APInt c2 = RHS->getAPIntValue();
  7989. zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
  7990. return (c1 + c2).ult(OpSizeInBits);
  7991. };
  7992. if (ISD::matchBinaryPredicate(N1, N0.getOperand(1), MatchInRange)) {
  7993. SDLoc DL(N);
  7994. SDValue Sum = DAG.getNode(ISD::ADD, DL, ShiftVT, N1, N0.getOperand(1));
  7995. return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0), Sum);
  7996. }
  7997. }
  7998. // fold (shl (ext (shl x, c1)), c2) -> (shl (ext x), (add c1, c2))
  7999. // For this to be valid, the second form must not preserve any of the bits
  8000. // that are shifted out by the inner shift in the first form. This means
  8001. // the outer shift size must be >= the number of bits added by the ext.
  8002. // As a corollary, we don't care what kind of ext it is.
  8003. if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
  8004. N0.getOpcode() == ISD::ANY_EXTEND ||
  8005. N0.getOpcode() == ISD::SIGN_EXTEND) &&
  8006. N0.getOperand(0).getOpcode() == ISD::SHL) {
  8007. SDValue N0Op0 = N0.getOperand(0);
  8008. SDValue InnerShiftAmt = N0Op0.getOperand(1);
  8009. EVT InnerVT = N0Op0.getValueType();
  8010. uint64_t InnerBitwidth = InnerVT.getScalarSizeInBits();
  8011. auto MatchOutOfRange = [OpSizeInBits, InnerBitwidth](ConstantSDNode *LHS,
  8012. ConstantSDNode *RHS) {
  8013. APInt c1 = LHS->getAPIntValue();
  8014. APInt c2 = RHS->getAPIntValue();
  8015. zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
  8016. return c2.uge(OpSizeInBits - InnerBitwidth) &&
  8017. (c1 + c2).uge(OpSizeInBits);
  8018. };
  8019. if (ISD::matchBinaryPredicate(InnerShiftAmt, N1, MatchOutOfRange,
  8020. /*AllowUndefs*/ false,
  8021. /*AllowTypeMismatch*/ true))
  8022. return DAG.getConstant(0, SDLoc(N), VT);
  8023. auto MatchInRange = [OpSizeInBits, InnerBitwidth](ConstantSDNode *LHS,
  8024. ConstantSDNode *RHS) {
  8025. APInt c1 = LHS->getAPIntValue();
  8026. APInt c2 = RHS->getAPIntValue();
  8027. zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
  8028. return c2.uge(OpSizeInBits - InnerBitwidth) &&
  8029. (c1 + c2).ult(OpSizeInBits);
  8030. };
  8031. if (ISD::matchBinaryPredicate(InnerShiftAmt, N1, MatchInRange,
  8032. /*AllowUndefs*/ false,
  8033. /*AllowTypeMismatch*/ true)) {
  8034. SDLoc DL(N);
  8035. SDValue Ext = DAG.getNode(N0.getOpcode(), DL, VT, N0Op0.getOperand(0));
  8036. SDValue Sum = DAG.getZExtOrTrunc(InnerShiftAmt, DL, ShiftVT);
  8037. Sum = DAG.getNode(ISD::ADD, DL, ShiftVT, Sum, N1);
  8038. return DAG.getNode(ISD::SHL, DL, VT, Ext, Sum);
  8039. }
  8040. }
  8041. // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
  8042. // Only fold this if the inner zext has no other uses to avoid increasing
  8043. // the total number of instructions.
  8044. if (N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
  8045. N0.getOperand(0).getOpcode() == ISD::SRL) {
  8046. SDValue N0Op0 = N0.getOperand(0);
  8047. SDValue InnerShiftAmt = N0Op0.getOperand(1);
  8048. auto MatchEqual = [VT](ConstantSDNode *LHS, ConstantSDNode *RHS) {
  8049. APInt c1 = LHS->getAPIntValue();
  8050. APInt c2 = RHS->getAPIntValue();
  8051. zeroExtendToMatch(c1, c2);
  8052. return c1.ult(VT.getScalarSizeInBits()) && (c1 == c2);
  8053. };
  8054. if (ISD::matchBinaryPredicate(InnerShiftAmt, N1, MatchEqual,
  8055. /*AllowUndefs*/ false,
  8056. /*AllowTypeMismatch*/ true)) {
  8057. SDLoc DL(N);
  8058. EVT InnerShiftAmtVT = N0Op0.getOperand(1).getValueType();
  8059. SDValue NewSHL = DAG.getZExtOrTrunc(N1, DL, InnerShiftAmtVT);
  8060. NewSHL = DAG.getNode(ISD::SHL, DL, N0Op0.getValueType(), N0Op0, NewSHL);
  8061. AddToWorklist(NewSHL.getNode());
  8062. return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
  8063. }
  8064. }
  8065. if (N0.getOpcode() == ISD::SRL || N0.getOpcode() == ISD::SRA) {
  8066. auto MatchShiftAmount = [OpSizeInBits](ConstantSDNode *LHS,
  8067. ConstantSDNode *RHS) {
  8068. const APInt &LHSC = LHS->getAPIntValue();
  8069. const APInt &RHSC = RHS->getAPIntValue();
  8070. return LHSC.ult(OpSizeInBits) && RHSC.ult(OpSizeInBits) &&
  8071. LHSC.getZExtValue() <= RHSC.getZExtValue();
  8072. };
  8073. SDLoc DL(N);
  8074. // fold (shl (sr[la] exact X, C1), C2) -> (shl X, (C2-C1)) if C1 <= C2
  8075. // fold (shl (sr[la] exact X, C1), C2) -> (sr[la] X, (C2-C1)) if C1 >= C2
  8076. if (N0->getFlags().hasExact()) {
  8077. if (ISD::matchBinaryPredicate(N0.getOperand(1), N1, MatchShiftAmount,
  8078. /*AllowUndefs*/ false,
  8079. /*AllowTypeMismatch*/ true)) {
  8080. SDValue N01 = DAG.getZExtOrTrunc(N0.getOperand(1), DL, ShiftVT);
  8081. SDValue Diff = DAG.getNode(ISD::SUB, DL, ShiftVT, N1, N01);
  8082. return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0), Diff);
  8083. }
  8084. if (ISD::matchBinaryPredicate(N1, N0.getOperand(1), MatchShiftAmount,
  8085. /*AllowUndefs*/ false,
  8086. /*AllowTypeMismatch*/ true)) {
  8087. SDValue N01 = DAG.getZExtOrTrunc(N0.getOperand(1), DL, ShiftVT);
  8088. SDValue Diff = DAG.getNode(ISD::SUB, DL, ShiftVT, N01, N1);
  8089. return DAG.getNode(N0.getOpcode(), DL, VT, N0.getOperand(0), Diff);
  8090. }
  8091. }
  8092. // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
  8093. // (and (srl x, (sub c1, c2), MASK)
  8094. // Only fold this if the inner shift has no other uses -- if it does,
  8095. // folding this will increase the total number of instructions.
  8096. if (N0.getOpcode() == ISD::SRL &&
  8097. (N0.getOperand(1) == N1 || N0.hasOneUse()) &&
  8098. TLI.shouldFoldConstantShiftPairToMask(N, Level)) {
  8099. if (ISD::matchBinaryPredicate(N1, N0.getOperand(1), MatchShiftAmount,
  8100. /*AllowUndefs*/ false,
  8101. /*AllowTypeMismatch*/ true)) {
  8102. SDValue N01 = DAG.getZExtOrTrunc(N0.getOperand(1), DL, ShiftVT);
  8103. SDValue Diff = DAG.getNode(ISD::SUB, DL, ShiftVT, N01, N1);
  8104. SDValue Mask = DAG.getAllOnesConstant(DL, VT);
  8105. Mask = DAG.getNode(ISD::SHL, DL, VT, Mask, N01);
  8106. Mask = DAG.getNode(ISD::SRL, DL, VT, Mask, Diff);
  8107. SDValue Shift = DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0), Diff);
  8108. return DAG.getNode(ISD::AND, DL, VT, Shift, Mask);
  8109. }
  8110. if (ISD::matchBinaryPredicate(N0.getOperand(1), N1, MatchShiftAmount,
  8111. /*AllowUndefs*/ false,
  8112. /*AllowTypeMismatch*/ true)) {
  8113. SDValue N01 = DAG.getZExtOrTrunc(N0.getOperand(1), DL, ShiftVT);
  8114. SDValue Diff = DAG.getNode(ISD::SUB, DL, ShiftVT, N1, N01);
  8115. SDValue Mask = DAG.getAllOnesConstant(DL, VT);
  8116. Mask = DAG.getNode(ISD::SHL, DL, VT, Mask, N1);
  8117. SDValue Shift = DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0), Diff);
  8118. return DAG.getNode(ISD::AND, DL, VT, Shift, Mask);
  8119. }
  8120. }
  8121. }
  8122. // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
  8123. if (N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1) &&
  8124. isConstantOrConstantVector(N1, /* No Opaques */ true)) {
  8125. SDLoc DL(N);
  8126. SDValue AllBits = DAG.getAllOnesConstant(DL, VT);
  8127. SDValue HiBitsMask = DAG.getNode(ISD::SHL, DL, VT, AllBits, N1);
  8128. return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), HiBitsMask);
  8129. }
  8130. // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
  8131. // fold (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2)
  8132. // Variant of version done on multiply, except mul by a power of 2 is turned
  8133. // into a shift.
  8134. if ((N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::OR) &&
  8135. N0->hasOneUse() &&
  8136. isConstantOrConstantVector(N1, /* No Opaques */ true) &&
  8137. isConstantOrConstantVector(N0.getOperand(1), /* No Opaques */ true) &&
  8138. TLI.isDesirableToCommuteWithShift(N, Level)) {
  8139. SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1);
  8140. SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
  8141. AddToWorklist(Shl0.getNode());
  8142. AddToWorklist(Shl1.getNode());
  8143. return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, Shl0, Shl1);
  8144. }
  8145. // fold (shl (mul x, c1), c2) -> (mul x, c1 << c2)
  8146. if (N0.getOpcode() == ISD::MUL && N0->hasOneUse()) {
  8147. SDValue N01 = N0.getOperand(1);
  8148. if (SDValue Shl =
  8149. DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N1), VT, {N01, N1}))
  8150. return DAG.getNode(ISD::MUL, SDLoc(N), VT, N0.getOperand(0), Shl);
  8151. }
  8152. ConstantSDNode *N1C = isConstOrConstSplat(N1);
  8153. if (N1C && !N1C->isOpaque())
  8154. if (SDValue NewSHL = visitShiftByConstant(N))
  8155. return NewSHL;
  8156. // Fold (shl (vscale * C0), C1) to (vscale * (C0 << C1)).
  8157. if (N0.getOpcode() == ISD::VSCALE && N1C) {
  8158. const APInt &C0 = N0.getConstantOperandAPInt(0);
  8159. const APInt &C1 = N1C->getAPIntValue();
  8160. return DAG.getVScale(SDLoc(N), VT, C0 << C1);
  8161. }
  8162. // Fold (shl step_vector(C0), C1) to (step_vector(C0 << C1)).
  8163. APInt ShlVal;
  8164. if (N0.getOpcode() == ISD::STEP_VECTOR &&
  8165. ISD::isConstantSplatVector(N1.getNode(), ShlVal)) {
  8166. const APInt &C0 = N0.getConstantOperandAPInt(0);
  8167. if (ShlVal.ult(C0.getBitWidth())) {
  8168. APInt NewStep = C0 << ShlVal;
  8169. return DAG.getStepVector(SDLoc(N), VT, NewStep);
  8170. }
  8171. }
  8172. return SDValue();
  8173. }
  8174. // Transform a right shift of a multiply into a multiply-high.
  8175. // Examples:
  8176. // (srl (mul (zext i32:$a to i64), (zext i32:$a to i64)), 32) -> (mulhu $a, $b)
  8177. // (sra (mul (sext i32:$a to i64), (sext i32:$a to i64)), 32) -> (mulhs $a, $b)
  8178. static SDValue combineShiftToMULH(SDNode *N, SelectionDAG &DAG,
  8179. const TargetLowering &TLI) {
  8180. assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
  8181. "SRL or SRA node is required here!");
  8182. // Check the shift amount. Proceed with the transformation if the shift
  8183. // amount is constant.
  8184. ConstantSDNode *ShiftAmtSrc = isConstOrConstSplat(N->getOperand(1));
  8185. if (!ShiftAmtSrc)
  8186. return SDValue();
  8187. SDLoc DL(N);
  8188. // The operation feeding into the shift must be a multiply.
  8189. SDValue ShiftOperand = N->getOperand(0);
  8190. if (ShiftOperand.getOpcode() != ISD::MUL)
  8191. return SDValue();
  8192. // Both operands must be equivalent extend nodes.
  8193. SDValue LeftOp = ShiftOperand.getOperand(0);
  8194. SDValue RightOp = ShiftOperand.getOperand(1);
  8195. bool IsSignExt = LeftOp.getOpcode() == ISD::SIGN_EXTEND;
  8196. bool IsZeroExt = LeftOp.getOpcode() == ISD::ZERO_EXTEND;
  8197. if (!IsSignExt && !IsZeroExt)
  8198. return SDValue();
  8199. EVT NarrowVT = LeftOp.getOperand(0).getValueType();
  8200. unsigned NarrowVTSize = NarrowVT.getScalarSizeInBits();
  8201. // return true if U may use the lower bits of its operands
  8202. auto UserOfLowerBits = [NarrowVTSize](SDNode *U) {
  8203. if (U->getOpcode() != ISD::SRL && U->getOpcode() != ISD::SRA) {
  8204. return true;
  8205. }
  8206. ConstantSDNode *UShiftAmtSrc = isConstOrConstSplat(U->getOperand(1));
  8207. if (!UShiftAmtSrc) {
  8208. return true;
  8209. }
  8210. unsigned UShiftAmt = UShiftAmtSrc->getZExtValue();
  8211. return UShiftAmt < NarrowVTSize;
  8212. };
  8213. // If the lower part of the MUL is also used and MUL_LOHI is supported
  8214. // do not introduce the MULH in favor of MUL_LOHI
  8215. unsigned MulLoHiOp = IsSignExt ? ISD::SMUL_LOHI : ISD::UMUL_LOHI;
  8216. if (!ShiftOperand.hasOneUse() &&
  8217. TLI.isOperationLegalOrCustom(MulLoHiOp, NarrowVT) &&
  8218. llvm::any_of(ShiftOperand->uses(), UserOfLowerBits)) {
  8219. return SDValue();
  8220. }
  8221. SDValue MulhRightOp;
  8222. if (ConstantSDNode *Constant = isConstOrConstSplat(RightOp)) {
  8223. unsigned ActiveBits = IsSignExt
  8224. ? Constant->getAPIntValue().getMinSignedBits()
  8225. : Constant->getAPIntValue().getActiveBits();
  8226. if (ActiveBits > NarrowVTSize)
  8227. return SDValue();
  8228. MulhRightOp = DAG.getConstant(
  8229. Constant->getAPIntValue().trunc(NarrowVT.getScalarSizeInBits()), DL,
  8230. NarrowVT);
  8231. } else {
  8232. if (LeftOp.getOpcode() != RightOp.getOpcode())
  8233. return SDValue();
  8234. // Check that the two extend nodes are the same type.
  8235. if (NarrowVT != RightOp.getOperand(0).getValueType())
  8236. return SDValue();
  8237. MulhRightOp = RightOp.getOperand(0);
  8238. }
  8239. EVT WideVT = LeftOp.getValueType();
  8240. // Proceed with the transformation if the wide types match.
  8241. assert((WideVT == RightOp.getValueType()) &&
  8242. "Cannot have a multiply node with two different operand types.");
  8243. // Proceed with the transformation if the wide type is twice as large
  8244. // as the narrow type.
  8245. if (WideVT.getScalarSizeInBits() != 2 * NarrowVTSize)
  8246. return SDValue();
  8247. // Check the shift amount with the narrow type size.
  8248. // Proceed with the transformation if the shift amount is the width
  8249. // of the narrow type.
  8250. unsigned ShiftAmt = ShiftAmtSrc->getZExtValue();
  8251. if (ShiftAmt != NarrowVTSize)
  8252. return SDValue();
  8253. // If the operation feeding into the MUL is a sign extend (sext),
  8254. // we use mulhs. Othewise, zero extends (zext) use mulhu.
  8255. unsigned MulhOpcode = IsSignExt ? ISD::MULHS : ISD::MULHU;
  8256. // Combine to mulh if mulh is legal/custom for the narrow type on the target.
  8257. if (!TLI.isOperationLegalOrCustom(MulhOpcode, NarrowVT))
  8258. return SDValue();
  8259. SDValue Result =
  8260. DAG.getNode(MulhOpcode, DL, NarrowVT, LeftOp.getOperand(0), MulhRightOp);
  8261. return (N->getOpcode() == ISD::SRA ? DAG.getSExtOrTrunc(Result, DL, WideVT)
  8262. : DAG.getZExtOrTrunc(Result, DL, WideVT));
  8263. }
  8264. SDValue DAGCombiner::visitSRA(SDNode *N) {
  8265. SDValue N0 = N->getOperand(0);
  8266. SDValue N1 = N->getOperand(1);
  8267. if (SDValue V = DAG.simplifyShift(N0, N1))
  8268. return V;
  8269. EVT VT = N0.getValueType();
  8270. unsigned OpSizeInBits = VT.getScalarSizeInBits();
  8271. // fold (sra c1, c2) -> (sra c1, c2)
  8272. if (SDValue C = DAG.FoldConstantArithmetic(ISD::SRA, SDLoc(N), VT, {N0, N1}))
  8273. return C;
  8274. // Arithmetic shifting an all-sign-bit value is a no-op.
  8275. // fold (sra 0, x) -> 0
  8276. // fold (sra -1, x) -> -1
  8277. if (DAG.ComputeNumSignBits(N0) == OpSizeInBits)
  8278. return N0;
  8279. // fold vector ops
  8280. if (VT.isVector())
  8281. if (SDValue FoldedVOp = SimplifyVBinOp(N, SDLoc(N)))
  8282. return FoldedVOp;
  8283. if (SDValue NewSel = foldBinOpIntoSelect(N))
  8284. return NewSel;
  8285. // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
  8286. // sext_inreg.
  8287. ConstantSDNode *N1C = isConstOrConstSplat(N1);
  8288. if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
  8289. unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
  8290. EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
  8291. if (VT.isVector())
  8292. ExtVT = EVT::getVectorVT(*DAG.getContext(), ExtVT,
  8293. VT.getVectorElementCount());
  8294. if (!LegalOperations ||
  8295. TLI.getOperationAction(ISD::SIGN_EXTEND_INREG, ExtVT) ==
  8296. TargetLowering::Legal)
  8297. return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
  8298. N0.getOperand(0), DAG.getValueType(ExtVT));
  8299. // Even if we can't convert to sext_inreg, we might be able to remove
  8300. // this shift pair if the input is already sign extended.
  8301. if (DAG.ComputeNumSignBits(N0.getOperand(0)) > N1C->getZExtValue())
  8302. return N0.getOperand(0);
  8303. }
  8304. // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
  8305. // clamp (add c1, c2) to max shift.
  8306. if (N0.getOpcode() == ISD::SRA) {
  8307. SDLoc DL(N);
  8308. EVT ShiftVT = N1.getValueType();
  8309. EVT ShiftSVT = ShiftVT.getScalarType();
  8310. SmallVector<SDValue, 16> ShiftValues;
  8311. auto SumOfShifts = [&](ConstantSDNode *LHS, ConstantSDNode *RHS) {
  8312. APInt c1 = LHS->getAPIntValue();
  8313. APInt c2 = RHS->getAPIntValue();
  8314. zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
  8315. APInt Sum = c1 + c2;
  8316. unsigned ShiftSum =
  8317. Sum.uge(OpSizeInBits) ? (OpSizeInBits - 1) : Sum.getZExtValue();
  8318. ShiftValues.push_back(DAG.getConstant(ShiftSum, DL, ShiftSVT));
  8319. return true;
  8320. };
  8321. if (ISD::matchBinaryPredicate(N1, N0.getOperand(1), SumOfShifts)) {
  8322. SDValue ShiftValue;
  8323. if (N1.getOpcode() == ISD::BUILD_VECTOR)
  8324. ShiftValue = DAG.getBuildVector(ShiftVT, DL, ShiftValues);
  8325. else if (N1.getOpcode() == ISD::SPLAT_VECTOR) {
  8326. assert(ShiftValues.size() == 1 &&
  8327. "Expected matchBinaryPredicate to return one element for "
  8328. "SPLAT_VECTORs");
  8329. ShiftValue = DAG.getSplatVector(ShiftVT, DL, ShiftValues[0]);
  8330. } else
  8331. ShiftValue = ShiftValues[0];
  8332. return DAG.getNode(ISD::SRA, DL, VT, N0.getOperand(0), ShiftValue);
  8333. }
  8334. }
  8335. // fold (sra (shl X, m), (sub result_size, n))
  8336. // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
  8337. // result_size - n != m.
  8338. // If truncate is free for the target sext(shl) is likely to result in better
  8339. // code.
  8340. if (N0.getOpcode() == ISD::SHL && N1C) {
  8341. // Get the two constanst of the shifts, CN0 = m, CN = n.
  8342. const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
  8343. if (N01C) {
  8344. LLVMContext &Ctx = *DAG.getContext();
  8345. // Determine what the truncate's result bitsize and type would be.
  8346. EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
  8347. if (VT.isVector())
  8348. TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorElementCount());
  8349. // Determine the residual right-shift amount.
  8350. int ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
  8351. // If the shift is not a no-op (in which case this should be just a sign
  8352. // extend already), the truncated to type is legal, sign_extend is legal
  8353. // on that type, and the truncate to that type is both legal and free,
  8354. // perform the transform.
  8355. if ((ShiftAmt > 0) &&
  8356. TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
  8357. TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
  8358. TLI.isTruncateFree(VT, TruncVT)) {
  8359. SDLoc DL(N);
  8360. SDValue Amt = DAG.getConstant(ShiftAmt, DL,
  8361. getShiftAmountTy(N0.getOperand(0).getValueType()));
  8362. SDValue Shift = DAG.getNode(ISD::SRL, DL, VT,
  8363. N0.getOperand(0), Amt);
  8364. SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, TruncVT,
  8365. Shift);
  8366. return DAG.getNode(ISD::SIGN_EXTEND, DL,
  8367. N->getValueType(0), Trunc);
  8368. }
  8369. }
  8370. }
  8371. // We convert trunc/ext to opposing shifts in IR, but casts may be cheaper.
  8372. // sra (add (shl X, N1C), AddC), N1C -->
  8373. // sext (add (trunc X to (width - N1C)), AddC')
  8374. // sra (sub AddC, (shl X, N1C)), N1C -->
  8375. // sext (sub AddC1',(trunc X to (width - N1C)))
  8376. if ((N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::SUB) && N1C &&
  8377. N0.hasOneUse()) {
  8378. bool IsAdd = N0.getOpcode() == ISD::ADD;
  8379. SDValue Shl = N0.getOperand(IsAdd ? 0 : 1);
  8380. if (Shl.getOpcode() == ISD::SHL && Shl.getOperand(1) == N1 &&
  8381. Shl.hasOneUse()) {
  8382. // TODO: AddC does not need to be a splat.
  8383. if (ConstantSDNode *AddC =
  8384. isConstOrConstSplat(N0.getOperand(IsAdd ? 1 : 0))) {
  8385. // Determine what the truncate's type would be and ask the target if
  8386. // that is a free operation.
  8387. LLVMContext &Ctx = *DAG.getContext();
  8388. unsigned ShiftAmt = N1C->getZExtValue();
  8389. EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - ShiftAmt);
  8390. if (VT.isVector())
  8391. TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorElementCount());
  8392. // TODO: The simple type check probably belongs in the default hook
  8393. // implementation and/or target-specific overrides (because
  8394. // non-simple types likely require masking when legalized), but
  8395. // that restriction may conflict with other transforms.
  8396. if (TruncVT.isSimple() && isTypeLegal(TruncVT) &&
  8397. TLI.isTruncateFree(VT, TruncVT)) {
  8398. SDLoc DL(N);
  8399. SDValue Trunc = DAG.getZExtOrTrunc(Shl.getOperand(0), DL, TruncVT);
  8400. SDValue ShiftC =
  8401. DAG.getConstant(AddC->getAPIntValue().lshr(ShiftAmt).trunc(
  8402. TruncVT.getScalarSizeInBits()),
  8403. DL, TruncVT);
  8404. SDValue Add;
  8405. if (IsAdd)
  8406. Add = DAG.getNode(ISD::ADD, DL, TruncVT, Trunc, ShiftC);
  8407. else
  8408. Add = DAG.getNode(ISD::SUB, DL, TruncVT, ShiftC, Trunc);
  8409. return DAG.getSExtOrTrunc(Add, DL, VT);
  8410. }
  8411. }
  8412. }
  8413. }
  8414. // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
  8415. if (N1.getOpcode() == ISD::TRUNCATE &&
  8416. N1.getOperand(0).getOpcode() == ISD::AND) {
  8417. if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
  8418. return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
  8419. }
  8420. // fold (sra (trunc (sra x, c1)), c2) -> (trunc (sra x, c1 + c2))
  8421. // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
  8422. // if c1 is equal to the number of bits the trunc removes
  8423. // TODO - support non-uniform vector shift amounts.
  8424. if (N0.getOpcode() == ISD::TRUNCATE &&
  8425. (N0.getOperand(0).getOpcode() == ISD::SRL ||
  8426. N0.getOperand(0).getOpcode() == ISD::SRA) &&
  8427. N0.getOperand(0).hasOneUse() &&
  8428. N0.getOperand(0).getOperand(1).hasOneUse() && N1C) {
  8429. SDValue N0Op0 = N0.getOperand(0);
  8430. if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
  8431. EVT LargeVT = N0Op0.getValueType();
  8432. unsigned TruncBits = LargeVT.getScalarSizeInBits() - OpSizeInBits;
  8433. if (LargeShift->getAPIntValue() == TruncBits) {
  8434. SDLoc DL(N);
  8435. EVT LargeShiftVT = getShiftAmountTy(LargeVT);
  8436. SDValue Amt = DAG.getZExtOrTrunc(N1, DL, LargeShiftVT);
  8437. Amt = DAG.getNode(ISD::ADD, DL, LargeShiftVT, Amt,
  8438. DAG.getConstant(TruncBits, DL, LargeShiftVT));
  8439. SDValue SRA =
  8440. DAG.getNode(ISD::SRA, DL, LargeVT, N0Op0.getOperand(0), Amt);
  8441. return DAG.getNode(ISD::TRUNCATE, DL, VT, SRA);
  8442. }
  8443. }
  8444. }
  8445. // Simplify, based on bits shifted out of the LHS.
  8446. if (SimplifyDemandedBits(SDValue(N, 0)))
  8447. return SDValue(N, 0);
  8448. // If the sign bit is known to be zero, switch this to a SRL.
  8449. if (DAG.SignBitIsZero(N0))
  8450. return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
  8451. if (N1C && !N1C->isOpaque())
  8452. if (SDValue NewSRA = visitShiftByConstant(N))
  8453. return NewSRA;
  8454. // Try to transform this shift into a multiply-high if
  8455. // it matches the appropriate pattern detected in combineShiftToMULH.
  8456. if (SDValue MULH = combineShiftToMULH(N, DAG, TLI))
  8457. return MULH;
  8458. // Attempt to convert a sra of a load into a narrower sign-extending load.
  8459. if (SDValue NarrowLoad = reduceLoadWidth(N))
  8460. return NarrowLoad;
  8461. return SDValue();
  8462. }
  8463. SDValue DAGCombiner::visitSRL(SDNode *N) {
  8464. SDValue N0 = N->getOperand(0);
  8465. SDValue N1 = N->getOperand(1);
  8466. if (SDValue V = DAG.simplifyShift(N0, N1))
  8467. return V;
  8468. EVT VT = N0.getValueType();
  8469. EVT ShiftVT = N1.getValueType();
  8470. unsigned OpSizeInBits = VT.getScalarSizeInBits();
  8471. // fold (srl c1, c2) -> c1 >>u c2
  8472. if (SDValue C = DAG.FoldConstantArithmetic(ISD::SRL, SDLoc(N), VT, {N0, N1}))
  8473. return C;
  8474. // fold vector ops
  8475. if (VT.isVector())
  8476. if (SDValue FoldedVOp = SimplifyVBinOp(N, SDLoc(N)))
  8477. return FoldedVOp;
  8478. if (SDValue NewSel = foldBinOpIntoSelect(N))
  8479. return NewSel;
  8480. // if (srl x, c) is known to be zero, return 0
  8481. ConstantSDNode *N1C = isConstOrConstSplat(N1);
  8482. if (N1C &&
  8483. DAG.MaskedValueIsZero(SDValue(N, 0), APInt::getAllOnes(OpSizeInBits)))
  8484. return DAG.getConstant(0, SDLoc(N), VT);
  8485. // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
  8486. if (N0.getOpcode() == ISD::SRL) {
  8487. auto MatchOutOfRange = [OpSizeInBits](ConstantSDNode *LHS,
  8488. ConstantSDNode *RHS) {
  8489. APInt c1 = LHS->getAPIntValue();
  8490. APInt c2 = RHS->getAPIntValue();
  8491. zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
  8492. return (c1 + c2).uge(OpSizeInBits);
  8493. };
  8494. if (ISD::matchBinaryPredicate(N1, N0.getOperand(1), MatchOutOfRange))
  8495. return DAG.getConstant(0, SDLoc(N), VT);
  8496. auto MatchInRange = [OpSizeInBits](ConstantSDNode *LHS,
  8497. ConstantSDNode *RHS) {
  8498. APInt c1 = LHS->getAPIntValue();
  8499. APInt c2 = RHS->getAPIntValue();
  8500. zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
  8501. return (c1 + c2).ult(OpSizeInBits);
  8502. };
  8503. if (ISD::matchBinaryPredicate(N1, N0.getOperand(1), MatchInRange)) {
  8504. SDLoc DL(N);
  8505. SDValue Sum = DAG.getNode(ISD::ADD, DL, ShiftVT, N1, N0.getOperand(1));
  8506. return DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0), Sum);
  8507. }
  8508. }
  8509. if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
  8510. N0.getOperand(0).getOpcode() == ISD::SRL) {
  8511. SDValue InnerShift = N0.getOperand(0);
  8512. // TODO - support non-uniform vector shift amounts.
  8513. if (auto *N001C = isConstOrConstSplat(InnerShift.getOperand(1))) {
  8514. uint64_t c1 = N001C->getZExtValue();
  8515. uint64_t c2 = N1C->getZExtValue();
  8516. EVT InnerShiftVT = InnerShift.getValueType();
  8517. EVT ShiftAmtVT = InnerShift.getOperand(1).getValueType();
  8518. uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
  8519. // srl (trunc (srl x, c1)), c2 --> 0 or (trunc (srl x, (add c1, c2)))
  8520. // This is only valid if the OpSizeInBits + c1 = size of inner shift.
  8521. if (c1 + OpSizeInBits == InnerShiftSize) {
  8522. SDLoc DL(N);
  8523. if (c1 + c2 >= InnerShiftSize)
  8524. return DAG.getConstant(0, DL, VT);
  8525. SDValue NewShiftAmt = DAG.getConstant(c1 + c2, DL, ShiftAmtVT);
  8526. SDValue NewShift = DAG.getNode(ISD::SRL, DL, InnerShiftVT,
  8527. InnerShift.getOperand(0), NewShiftAmt);
  8528. return DAG.getNode(ISD::TRUNCATE, DL, VT, NewShift);
  8529. }
  8530. // In the more general case, we can clear the high bits after the shift:
  8531. // srl (trunc (srl x, c1)), c2 --> trunc (and (srl x, (c1+c2)), Mask)
  8532. if (N0.hasOneUse() && InnerShift.hasOneUse() &&
  8533. c1 + c2 < InnerShiftSize) {
  8534. SDLoc DL(N);
  8535. SDValue NewShiftAmt = DAG.getConstant(c1 + c2, DL, ShiftAmtVT);
  8536. SDValue NewShift = DAG.getNode(ISD::SRL, DL, InnerShiftVT,
  8537. InnerShift.getOperand(0), NewShiftAmt);
  8538. SDValue Mask = DAG.getConstant(APInt::getLowBitsSet(InnerShiftSize,
  8539. OpSizeInBits - c2),
  8540. DL, InnerShiftVT);
  8541. SDValue And = DAG.getNode(ISD::AND, DL, InnerShiftVT, NewShift, Mask);
  8542. return DAG.getNode(ISD::TRUNCATE, DL, VT, And);
  8543. }
  8544. }
  8545. }
  8546. // fold (srl (shl x, c1), c2) -> (and (shl x, (sub c1, c2), MASK) or
  8547. // (and (srl x, (sub c2, c1), MASK)
  8548. if (N0.getOpcode() == ISD::SHL &&
  8549. (N0.getOperand(1) == N1 || N0->hasOneUse()) &&
  8550. TLI.shouldFoldConstantShiftPairToMask(N, Level)) {
  8551. auto MatchShiftAmount = [OpSizeInBits](ConstantSDNode *LHS,
  8552. ConstantSDNode *RHS) {
  8553. const APInt &LHSC = LHS->getAPIntValue();
  8554. const APInt &RHSC = RHS->getAPIntValue();
  8555. return LHSC.ult(OpSizeInBits) && RHSC.ult(OpSizeInBits) &&
  8556. LHSC.getZExtValue() <= RHSC.getZExtValue();
  8557. };
  8558. if (ISD::matchBinaryPredicate(N1, N0.getOperand(1), MatchShiftAmount,
  8559. /*AllowUndefs*/ false,
  8560. /*AllowTypeMismatch*/ true)) {
  8561. SDLoc DL(N);
  8562. SDValue N01 = DAG.getZExtOrTrunc(N0.getOperand(1), DL, ShiftVT);
  8563. SDValue Diff = DAG.getNode(ISD::SUB, DL, ShiftVT, N01, N1);
  8564. SDValue Mask = DAG.getAllOnesConstant(DL, VT);
  8565. Mask = DAG.getNode(ISD::SRL, DL, VT, Mask, N01);
  8566. Mask = DAG.getNode(ISD::SHL, DL, VT, Mask, Diff);
  8567. SDValue Shift = DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0), Diff);
  8568. return DAG.getNode(ISD::AND, DL, VT, Shift, Mask);
  8569. }
  8570. if (ISD::matchBinaryPredicate(N0.getOperand(1), N1, MatchShiftAmount,
  8571. /*AllowUndefs*/ false,
  8572. /*AllowTypeMismatch*/ true)) {
  8573. SDLoc DL(N);
  8574. SDValue N01 = DAG.getZExtOrTrunc(N0.getOperand(1), DL, ShiftVT);
  8575. SDValue Diff = DAG.getNode(ISD::SUB, DL, ShiftVT, N1, N01);
  8576. SDValue Mask = DAG.getAllOnesConstant(DL, VT);
  8577. Mask = DAG.getNode(ISD::SRL, DL, VT, Mask, N1);
  8578. SDValue Shift = DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0), Diff);
  8579. return DAG.getNode(ISD::AND, DL, VT, Shift, Mask);
  8580. }
  8581. }
  8582. // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
  8583. // TODO - support non-uniform vector shift amounts.
  8584. if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
  8585. // Shifting in all undef bits?
  8586. EVT SmallVT = N0.getOperand(0).getValueType();
  8587. unsigned BitSize = SmallVT.getScalarSizeInBits();
  8588. if (N1C->getAPIntValue().uge(BitSize))
  8589. return DAG.getUNDEF(VT);
  8590. if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
  8591. uint64_t ShiftAmt = N1C->getZExtValue();
  8592. SDLoc DL0(N0);
  8593. SDValue SmallShift = DAG.getNode(ISD::SRL, DL0, SmallVT,
  8594. N0.getOperand(0),
  8595. DAG.getConstant(ShiftAmt, DL0,
  8596. getShiftAmountTy(SmallVT)));
  8597. AddToWorklist(SmallShift.getNode());
  8598. APInt Mask = APInt::getLowBitsSet(OpSizeInBits, OpSizeInBits - ShiftAmt);
  8599. SDLoc DL(N);
  8600. return DAG.getNode(ISD::AND, DL, VT,
  8601. DAG.getNode(ISD::ANY_EXTEND, DL, VT, SmallShift),
  8602. DAG.getConstant(Mask, DL, VT));
  8603. }
  8604. }
  8605. // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign
  8606. // bit, which is unmodified by sra.
  8607. if (N1C && N1C->getAPIntValue() == (OpSizeInBits - 1)) {
  8608. if (N0.getOpcode() == ISD::SRA)
  8609. return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
  8610. }
  8611. // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit).
  8612. if (N1C && N0.getOpcode() == ISD::CTLZ &&
  8613. N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
  8614. KnownBits Known = DAG.computeKnownBits(N0.getOperand(0));
  8615. // If any of the input bits are KnownOne, then the input couldn't be all
  8616. // zeros, thus the result of the srl will always be zero.
  8617. if (Known.One.getBoolValue()) return DAG.getConstant(0, SDLoc(N0), VT);
  8618. // If all of the bits input the to ctlz node are known to be zero, then
  8619. // the result of the ctlz is "32" and the result of the shift is one.
  8620. APInt UnknownBits = ~Known.Zero;
  8621. if (UnknownBits == 0) return DAG.getConstant(1, SDLoc(N0), VT);
  8622. // Otherwise, check to see if there is exactly one bit input to the ctlz.
  8623. if (UnknownBits.isPowerOf2()) {
  8624. // Okay, we know that only that the single bit specified by UnknownBits
  8625. // could be set on input to the CTLZ node. If this bit is set, the SRL
  8626. // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
  8627. // to an SRL/XOR pair, which is likely to simplify more.
  8628. unsigned ShAmt = UnknownBits.countTrailingZeros();
  8629. SDValue Op = N0.getOperand(0);
  8630. if (ShAmt) {
  8631. SDLoc DL(N0);
  8632. Op = DAG.getNode(ISD::SRL, DL, VT, Op,
  8633. DAG.getConstant(ShAmt, DL,
  8634. getShiftAmountTy(Op.getValueType())));
  8635. AddToWorklist(Op.getNode());
  8636. }
  8637. SDLoc DL(N);
  8638. return DAG.getNode(ISD::XOR, DL, VT,
  8639. Op, DAG.getConstant(1, DL, VT));
  8640. }
  8641. }
  8642. // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
  8643. if (N1.getOpcode() == ISD::TRUNCATE &&
  8644. N1.getOperand(0).getOpcode() == ISD::AND) {
  8645. if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
  8646. return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
  8647. }
  8648. // fold operands of srl based on knowledge that the low bits are not
  8649. // demanded.
  8650. if (SimplifyDemandedBits(SDValue(N, 0)))
  8651. return SDValue(N, 0);
  8652. if (N1C && !N1C->isOpaque())
  8653. if (SDValue NewSRL = visitShiftByConstant(N))
  8654. return NewSRL;
  8655. // Attempt to convert a srl of a load into a narrower zero-extending load.
  8656. if (SDValue NarrowLoad = reduceLoadWidth(N))
  8657. return NarrowLoad;
  8658. // Here is a common situation. We want to optimize:
  8659. //
  8660. // %a = ...
  8661. // %b = and i32 %a, 2
  8662. // %c = srl i32 %b, 1
  8663. // brcond i32 %c ...
  8664. //
  8665. // into
  8666. //
  8667. // %a = ...
  8668. // %b = and %a, 2
  8669. // %c = setcc eq %b, 0
  8670. // brcond %c ...
  8671. //
  8672. // However when after the source operand of SRL is optimized into AND, the SRL
  8673. // itself may not be optimized further. Look for it and add the BRCOND into
  8674. // the worklist.
  8675. //
  8676. // The also tends to happen for binary operations when SimplifyDemandedBits
  8677. // is involved.
  8678. //
  8679. // FIXME: This is unecessary if we process the DAG in topological order,
  8680. // which we plan to do. This workaround can be removed once the DAG is
  8681. // processed in topological order.
  8682. if (N->hasOneUse()) {
  8683. SDNode *Use = *N->use_begin();
  8684. // Look pass the truncate.
  8685. if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse())
  8686. Use = *Use->use_begin();
  8687. if (Use->getOpcode() == ISD::BRCOND || Use->getOpcode() == ISD::AND ||
  8688. Use->getOpcode() == ISD::OR || Use->getOpcode() == ISD::XOR)
  8689. AddToWorklist(Use);
  8690. }
  8691. // Try to transform this shift into a multiply-high if
  8692. // it matches the appropriate pattern detected in combineShiftToMULH.
  8693. if (SDValue MULH = combineShiftToMULH(N, DAG, TLI))
  8694. return MULH;
  8695. return SDValue();
  8696. }
  8697. SDValue DAGCombiner::visitFunnelShift(SDNode *N) {
  8698. EVT VT = N->getValueType(0);
  8699. SDValue N0 = N->getOperand(0);
  8700. SDValue N1 = N->getOperand(1);
  8701. SDValue N2 = N->getOperand(2);
  8702. bool IsFSHL = N->getOpcode() == ISD::FSHL;
  8703. unsigned BitWidth = VT.getScalarSizeInBits();
  8704. // fold (fshl N0, N1, 0) -> N0
  8705. // fold (fshr N0, N1, 0) -> N1
  8706. if (isPowerOf2_32(BitWidth))
  8707. if (DAG.MaskedValueIsZero(
  8708. N2, APInt(N2.getScalarValueSizeInBits(), BitWidth - 1)))
  8709. return IsFSHL ? N0 : N1;
  8710. auto IsUndefOrZero = [](SDValue V) {
  8711. return V.isUndef() || isNullOrNullSplat(V, /*AllowUndefs*/ true);
  8712. };
  8713. // TODO - support non-uniform vector shift amounts.
  8714. if (ConstantSDNode *Cst = isConstOrConstSplat(N2)) {
  8715. EVT ShAmtTy = N2.getValueType();
  8716. // fold (fsh* N0, N1, c) -> (fsh* N0, N1, c % BitWidth)
  8717. if (Cst->getAPIntValue().uge(BitWidth)) {
  8718. uint64_t RotAmt = Cst->getAPIntValue().urem(BitWidth);
  8719. return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N0, N1,
  8720. DAG.getConstant(RotAmt, SDLoc(N), ShAmtTy));
  8721. }
  8722. unsigned ShAmt = Cst->getZExtValue();
  8723. if (ShAmt == 0)
  8724. return IsFSHL ? N0 : N1;
  8725. // fold fshl(undef_or_zero, N1, C) -> lshr(N1, BW-C)
  8726. // fold fshr(undef_or_zero, N1, C) -> lshr(N1, C)
  8727. // fold fshl(N0, undef_or_zero, C) -> shl(N0, C)
  8728. // fold fshr(N0, undef_or_zero, C) -> shl(N0, BW-C)
  8729. if (IsUndefOrZero(N0))
  8730. return DAG.getNode(ISD::SRL, SDLoc(N), VT, N1,
  8731. DAG.getConstant(IsFSHL ? BitWidth - ShAmt : ShAmt,
  8732. SDLoc(N), ShAmtTy));
  8733. if (IsUndefOrZero(N1))
  8734. return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
  8735. DAG.getConstant(IsFSHL ? ShAmt : BitWidth - ShAmt,
  8736. SDLoc(N), ShAmtTy));
  8737. // fold (fshl ld1, ld0, c) -> (ld0[ofs]) iff ld0 and ld1 are consecutive.
  8738. // fold (fshr ld1, ld0, c) -> (ld0[ofs]) iff ld0 and ld1 are consecutive.
  8739. // TODO - bigendian support once we have test coverage.
  8740. // TODO - can we merge this with CombineConseutiveLoads/MatchLoadCombine?
  8741. // TODO - permit LHS EXTLOAD if extensions are shifted out.
  8742. if ((BitWidth % 8) == 0 && (ShAmt % 8) == 0 && !VT.isVector() &&
  8743. !DAG.getDataLayout().isBigEndian()) {
  8744. auto *LHS = dyn_cast<LoadSDNode>(N0);
  8745. auto *RHS = dyn_cast<LoadSDNode>(N1);
  8746. if (LHS && RHS && LHS->isSimple() && RHS->isSimple() &&
  8747. LHS->getAddressSpace() == RHS->getAddressSpace() &&
  8748. (LHS->hasOneUse() || RHS->hasOneUse()) && ISD::isNON_EXTLoad(RHS) &&
  8749. ISD::isNON_EXTLoad(LHS)) {
  8750. if (DAG.areNonVolatileConsecutiveLoads(LHS, RHS, BitWidth / 8, 1)) {
  8751. SDLoc DL(RHS);
  8752. uint64_t PtrOff =
  8753. IsFSHL ? (((BitWidth - ShAmt) % BitWidth) / 8) : (ShAmt / 8);
  8754. Align NewAlign = commonAlignment(RHS->getAlign(), PtrOff);
  8755. unsigned Fast = 0;
  8756. if (TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT,
  8757. RHS->getAddressSpace(), NewAlign,
  8758. RHS->getMemOperand()->getFlags(), &Fast) &&
  8759. Fast) {
  8760. SDValue NewPtr = DAG.getMemBasePlusOffset(
  8761. RHS->getBasePtr(), TypeSize::Fixed(PtrOff), DL);
  8762. AddToWorklist(NewPtr.getNode());
  8763. SDValue Load = DAG.getLoad(
  8764. VT, DL, RHS->getChain(), NewPtr,
  8765. RHS->getPointerInfo().getWithOffset(PtrOff), NewAlign,
  8766. RHS->getMemOperand()->getFlags(), RHS->getAAInfo());
  8767. // Replace the old load's chain with the new load's chain.
  8768. WorklistRemover DeadNodes(*this);
  8769. DAG.ReplaceAllUsesOfValueWith(N1.getValue(1), Load.getValue(1));
  8770. return Load;
  8771. }
  8772. }
  8773. }
  8774. }
  8775. }
  8776. // fold fshr(undef_or_zero, N1, N2) -> lshr(N1, N2)
  8777. // fold fshl(N0, undef_or_zero, N2) -> shl(N0, N2)
  8778. // iff We know the shift amount is in range.
  8779. // TODO: when is it worth doing SUB(BW, N2) as well?
  8780. if (isPowerOf2_32(BitWidth)) {
  8781. APInt ModuloBits(N2.getScalarValueSizeInBits(), BitWidth - 1);
  8782. if (IsUndefOrZero(N0) && !IsFSHL && DAG.MaskedValueIsZero(N2, ~ModuloBits))
  8783. return DAG.getNode(ISD::SRL, SDLoc(N), VT, N1, N2);
  8784. if (IsUndefOrZero(N1) && IsFSHL && DAG.MaskedValueIsZero(N2, ~ModuloBits))
  8785. return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, N2);
  8786. }
  8787. // fold (fshl N0, N0, N2) -> (rotl N0, N2)
  8788. // fold (fshr N0, N0, N2) -> (rotr N0, N2)
  8789. // TODO: Investigate flipping this rotate if only one is legal, if funnel shift
  8790. // is legal as well we might be better off avoiding non-constant (BW - N2).
  8791. unsigned RotOpc = IsFSHL ? ISD::ROTL : ISD::ROTR;
  8792. if (N0 == N1 && hasOperation(RotOpc, VT))
  8793. return DAG.getNode(RotOpc, SDLoc(N), VT, N0, N2);
  8794. // Simplify, based on bits shifted out of N0/N1.
  8795. if (SimplifyDemandedBits(SDValue(N, 0)))
  8796. return SDValue(N, 0);
  8797. return SDValue();
  8798. }
  8799. SDValue DAGCombiner::visitSHLSAT(SDNode *N) {
  8800. SDValue N0 = N->getOperand(0);
  8801. SDValue N1 = N->getOperand(1);
  8802. if (SDValue V = DAG.simplifyShift(N0, N1))
  8803. return V;
  8804. EVT VT = N0.getValueType();
  8805. // fold (*shlsat c1, c2) -> c1<<c2
  8806. if (SDValue C =
  8807. DAG.FoldConstantArithmetic(N->getOpcode(), SDLoc(N), VT, {N0, N1}))
  8808. return C;
  8809. ConstantSDNode *N1C = isConstOrConstSplat(N1);
  8810. if (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::SHL, VT)) {
  8811. // fold (sshlsat x, c) -> (shl x, c)
  8812. if (N->getOpcode() == ISD::SSHLSAT && N1C &&
  8813. N1C->getAPIntValue().ult(DAG.ComputeNumSignBits(N0)))
  8814. return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, N1);
  8815. // fold (ushlsat x, c) -> (shl x, c)
  8816. if (N->getOpcode() == ISD::USHLSAT && N1C &&
  8817. N1C->getAPIntValue().ule(
  8818. DAG.computeKnownBits(N0).countMinLeadingZeros()))
  8819. return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, N1);
  8820. }
  8821. return SDValue();
  8822. }
  8823. // Given a ABS node, detect the following pattern:
  8824. // (ABS (SUB (EXTEND a), (EXTEND b))).
  8825. // Generates UABD/SABD instruction.
  8826. SDValue DAGCombiner::foldABSToABD(SDNode *N) {
  8827. EVT VT = N->getValueType(0);
  8828. SDValue AbsOp1 = N->getOperand(0);
  8829. SDValue Op0, Op1;
  8830. if (AbsOp1.getOpcode() != ISD::SUB)
  8831. return SDValue();
  8832. Op0 = AbsOp1.getOperand(0);
  8833. Op1 = AbsOp1.getOperand(1);
  8834. unsigned Opc0 = Op0.getOpcode();
  8835. // Check if the operands of the sub are (zero|sign)-extended.
  8836. if (Opc0 != Op1.getOpcode() ||
  8837. (Opc0 != ISD::ZERO_EXTEND && Opc0 != ISD::SIGN_EXTEND)) {
  8838. // fold (abs (sub nsw x, y)) -> abds(x, y)
  8839. if (AbsOp1->getFlags().hasNoSignedWrap() &&
  8840. TLI.isOperationLegalOrCustom(ISD::ABDS, VT))
  8841. return DAG.getNode(ISD::ABDS, SDLoc(N), VT, Op0, Op1);
  8842. return SDValue();
  8843. }
  8844. EVT VT1 = Op0.getOperand(0).getValueType();
  8845. EVT VT2 = Op1.getOperand(0).getValueType();
  8846. unsigned ABDOpcode = (Opc0 == ISD::SIGN_EXTEND) ? ISD::ABDS : ISD::ABDU;
  8847. // fold abs(sext(x) - sext(y)) -> zext(abds(x, y))
  8848. // fold abs(zext(x) - zext(y)) -> zext(abdu(x, y))
  8849. // NOTE: Extensions must be equivalent.
  8850. if (VT1 == VT2 && TLI.isOperationLegalOrCustom(ABDOpcode, VT1)) {
  8851. Op0 = Op0.getOperand(0);
  8852. Op1 = Op1.getOperand(0);
  8853. SDValue ABD = DAG.getNode(ABDOpcode, SDLoc(N), VT1, Op0, Op1);
  8854. return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, ABD);
  8855. }
  8856. // fold abs(sext(x) - sext(y)) -> abds(sext(x), sext(y))
  8857. // fold abs(zext(x) - zext(y)) -> abdu(zext(x), zext(y))
  8858. if (TLI.isOperationLegalOrCustom(ABDOpcode, VT))
  8859. return DAG.getNode(ABDOpcode, SDLoc(N), VT, Op0, Op1);
  8860. return SDValue();
  8861. }
  8862. SDValue DAGCombiner::visitABS(SDNode *N) {
  8863. SDValue N0 = N->getOperand(0);
  8864. EVT VT = N->getValueType(0);
  8865. // fold (abs c1) -> c2
  8866. if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
  8867. return DAG.getNode(ISD::ABS, SDLoc(N), VT, N0);
  8868. // fold (abs (abs x)) -> (abs x)
  8869. if (N0.getOpcode() == ISD::ABS)
  8870. return N0;
  8871. // fold (abs x) -> x iff not-negative
  8872. if (DAG.SignBitIsZero(N0))
  8873. return N0;
  8874. if (SDValue ABD = foldABSToABD(N))
  8875. return ABD;
  8876. // fold (abs (sign_extend_inreg x)) -> (zero_extend (abs (truncate x)))
  8877. // iff zero_extend/truncate are free.
  8878. if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG) {
  8879. EVT ExtVT = cast<VTSDNode>(N0.getOperand(1))->getVT();
  8880. if (TLI.isTruncateFree(VT, ExtVT) && TLI.isZExtFree(ExtVT, VT) &&
  8881. TLI.isTypeDesirableForOp(ISD::ABS, ExtVT) &&
  8882. hasOperation(ISD::ABS, ExtVT)) {
  8883. SDLoc DL(N);
  8884. return DAG.getNode(
  8885. ISD::ZERO_EXTEND, DL, VT,
  8886. DAG.getNode(ISD::ABS, DL, ExtVT,
  8887. DAG.getNode(ISD::TRUNCATE, DL, ExtVT, N0.getOperand(0))));
  8888. }
  8889. }
  8890. return SDValue();
  8891. }
  8892. SDValue DAGCombiner::visitBSWAP(SDNode *N) {
  8893. SDValue N0 = N->getOperand(0);
  8894. EVT VT = N->getValueType(0);
  8895. SDLoc DL(N);
  8896. // fold (bswap c1) -> c2
  8897. if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
  8898. return DAG.getNode(ISD::BSWAP, DL, VT, N0);
  8899. // fold (bswap (bswap x)) -> x
  8900. if (N0.getOpcode() == ISD::BSWAP)
  8901. return N0.getOperand(0);
  8902. // Canonicalize bswap(bitreverse(x)) -> bitreverse(bswap(x)). If bitreverse
  8903. // isn't supported, it will be expanded to bswap followed by a manual reversal
  8904. // of bits in each byte. By placing bswaps before bitreverse, we can remove
  8905. // the two bswaps if the bitreverse gets expanded.
  8906. if (N0.getOpcode() == ISD::BITREVERSE && N0.hasOneUse()) {
  8907. SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT, N0.getOperand(0));
  8908. return DAG.getNode(ISD::BITREVERSE, DL, VT, BSwap);
  8909. }
  8910. // fold (bswap shl(x,c)) -> (zext(bswap(trunc(shl(x,sub(c,bw/2))))))
  8911. // iff x >= bw/2 (i.e. lower half is known zero)
  8912. unsigned BW = VT.getScalarSizeInBits();
  8913. if (BW >= 32 && N0.getOpcode() == ISD::SHL && N0.hasOneUse()) {
  8914. auto *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1));
  8915. EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), BW / 2);
  8916. if (ShAmt && ShAmt->getAPIntValue().ult(BW) &&
  8917. ShAmt->getZExtValue() >= (BW / 2) &&
  8918. (ShAmt->getZExtValue() % 16) == 0 && TLI.isTypeLegal(HalfVT) &&
  8919. TLI.isTruncateFree(VT, HalfVT) &&
  8920. (!LegalOperations || hasOperation(ISD::BSWAP, HalfVT))) {
  8921. SDValue Res = N0.getOperand(0);
  8922. if (uint64_t NewShAmt = (ShAmt->getZExtValue() - (BW / 2)))
  8923. Res = DAG.getNode(ISD::SHL, DL, VT, Res,
  8924. DAG.getConstant(NewShAmt, DL, getShiftAmountTy(VT)));
  8925. Res = DAG.getZExtOrTrunc(Res, DL, HalfVT);
  8926. Res = DAG.getNode(ISD::BSWAP, DL, HalfVT, Res);
  8927. return DAG.getZExtOrTrunc(Res, DL, VT);
  8928. }
  8929. }
  8930. // Try to canonicalize bswap-of-logical-shift-by-8-bit-multiple as
  8931. // inverse-shift-of-bswap:
  8932. // bswap (X u<< C) --> (bswap X) u>> C
  8933. // bswap (X u>> C) --> (bswap X) u<< C
  8934. if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
  8935. N0.hasOneUse()) {
  8936. auto *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1));
  8937. if (ShAmt && ShAmt->getAPIntValue().ult(BW) &&
  8938. ShAmt->getZExtValue() % 8 == 0) {
  8939. SDValue NewSwap = DAG.getNode(ISD::BSWAP, DL, VT, N0.getOperand(0));
  8940. unsigned InverseShift = N0.getOpcode() == ISD::SHL ? ISD::SRL : ISD::SHL;
  8941. return DAG.getNode(InverseShift, DL, VT, NewSwap, N0.getOperand(1));
  8942. }
  8943. }
  8944. return SDValue();
  8945. }
  8946. SDValue DAGCombiner::visitBITREVERSE(SDNode *N) {
  8947. SDValue N0 = N->getOperand(0);
  8948. EVT VT = N->getValueType(0);
  8949. // fold (bitreverse c1) -> c2
  8950. if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
  8951. return DAG.getNode(ISD::BITREVERSE, SDLoc(N), VT, N0);
  8952. // fold (bitreverse (bitreverse x)) -> x
  8953. if (N0.getOpcode() == ISD::BITREVERSE)
  8954. return N0.getOperand(0);
  8955. return SDValue();
  8956. }
  8957. SDValue DAGCombiner::visitCTLZ(SDNode *N) {
  8958. SDValue N0 = N->getOperand(0);
  8959. EVT VT = N->getValueType(0);
  8960. // fold (ctlz c1) -> c2
  8961. if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
  8962. return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
  8963. // If the value is known never to be zero, switch to the undef version.
  8964. if (!LegalOperations || TLI.isOperationLegal(ISD::CTLZ_ZERO_UNDEF, VT)) {
  8965. if (DAG.isKnownNeverZero(N0))
  8966. return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
  8967. }
  8968. return SDValue();
  8969. }
  8970. SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
  8971. SDValue N0 = N->getOperand(0);
  8972. EVT VT = N->getValueType(0);
  8973. // fold (ctlz_zero_undef c1) -> c2
  8974. if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
  8975. return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
  8976. return SDValue();
  8977. }
  8978. SDValue DAGCombiner::visitCTTZ(SDNode *N) {
  8979. SDValue N0 = N->getOperand(0);
  8980. EVT VT = N->getValueType(0);
  8981. // fold (cttz c1) -> c2
  8982. if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
  8983. return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
  8984. // If the value is known never to be zero, switch to the undef version.
  8985. if (!LegalOperations || TLI.isOperationLegal(ISD::CTTZ_ZERO_UNDEF, VT)) {
  8986. if (DAG.isKnownNeverZero(N0))
  8987. return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
  8988. }
  8989. return SDValue();
  8990. }
  8991. SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
  8992. SDValue N0 = N->getOperand(0);
  8993. EVT VT = N->getValueType(0);
  8994. // fold (cttz_zero_undef c1) -> c2
  8995. if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
  8996. return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
  8997. return SDValue();
  8998. }
  8999. SDValue DAGCombiner::visitCTPOP(SDNode *N) {
  9000. SDValue N0 = N->getOperand(0);
  9001. EVT VT = N->getValueType(0);
  9002. // fold (ctpop c1) -> c2
  9003. if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
  9004. return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
  9005. return SDValue();
  9006. }
  9007. // FIXME: This should be checking for no signed zeros on individual operands, as
  9008. // well as no nans.
  9009. static bool isLegalToCombineMinNumMaxNum(SelectionDAG &DAG, SDValue LHS,
  9010. SDValue RHS,
  9011. const TargetLowering &TLI) {
  9012. const TargetOptions &Options = DAG.getTarget().Options;
  9013. EVT VT = LHS.getValueType();
  9014. return Options.NoSignedZerosFPMath && VT.isFloatingPoint() &&
  9015. TLI.isProfitableToCombineMinNumMaxNum(VT) &&
  9016. DAG.isKnownNeverNaN(LHS) && DAG.isKnownNeverNaN(RHS);
  9017. }
  9018. static SDValue combineMinNumMaxNumImpl(const SDLoc &DL, EVT VT, SDValue LHS,
  9019. SDValue RHS, SDValue True, SDValue False,
  9020. ISD::CondCode CC,
  9021. const TargetLowering &TLI,
  9022. SelectionDAG &DAG) {
  9023. EVT TransformVT = TLI.getTypeToTransformTo(*DAG.getContext(), VT);
  9024. switch (CC) {
  9025. case ISD::SETOLT:
  9026. case ISD::SETOLE:
  9027. case ISD::SETLT:
  9028. case ISD::SETLE:
  9029. case ISD::SETULT:
  9030. case ISD::SETULE: {
  9031. // Since it's known never nan to get here already, either fminnum or
  9032. // fminnum_ieee are OK. Try the ieee version first, since it's fminnum is
  9033. // expanded in terms of it.
  9034. unsigned IEEEOpcode = (LHS == True) ? ISD::FMINNUM_IEEE : ISD::FMAXNUM_IEEE;
  9035. if (TLI.isOperationLegalOrCustom(IEEEOpcode, VT))
  9036. return DAG.getNode(IEEEOpcode, DL, VT, LHS, RHS);
  9037. unsigned Opcode = (LHS == True) ? ISD::FMINNUM : ISD::FMAXNUM;
  9038. if (TLI.isOperationLegalOrCustom(Opcode, TransformVT))
  9039. return DAG.getNode(Opcode, DL, VT, LHS, RHS);
  9040. return SDValue();
  9041. }
  9042. case ISD::SETOGT:
  9043. case ISD::SETOGE:
  9044. case ISD::SETGT:
  9045. case ISD::SETGE:
  9046. case ISD::SETUGT:
  9047. case ISD::SETUGE: {
  9048. unsigned IEEEOpcode = (LHS == True) ? ISD::FMAXNUM_IEEE : ISD::FMINNUM_IEEE;
  9049. if (TLI.isOperationLegalOrCustom(IEEEOpcode, VT))
  9050. return DAG.getNode(IEEEOpcode, DL, VT, LHS, RHS);
  9051. unsigned Opcode = (LHS == True) ? ISD::FMAXNUM : ISD::FMINNUM;
  9052. if (TLI.isOperationLegalOrCustom(Opcode, TransformVT))
  9053. return DAG.getNode(Opcode, DL, VT, LHS, RHS);
  9054. return SDValue();
  9055. }
  9056. default:
  9057. return SDValue();
  9058. }
  9059. }
  9060. /// Generate Min/Max node
  9061. SDValue DAGCombiner::combineMinNumMaxNum(const SDLoc &DL, EVT VT, SDValue LHS,
  9062. SDValue RHS, SDValue True,
  9063. SDValue False, ISD::CondCode CC) {
  9064. if ((LHS == True && RHS == False) || (LHS == False && RHS == True))
  9065. return combineMinNumMaxNumImpl(DL, VT, LHS, RHS, True, False, CC, TLI, DAG);
  9066. // If we can't directly match this, try to see if we can pull an fneg out of
  9067. // the select.
  9068. SDValue NegTrue = TLI.getCheaperOrNeutralNegatedExpression(
  9069. True, DAG, LegalOperations, ForCodeSize);
  9070. if (!NegTrue)
  9071. return SDValue();
  9072. HandleSDNode NegTrueHandle(NegTrue);
  9073. // Try to unfold an fneg from the select if we are comparing the negated
  9074. // constant.
  9075. //
  9076. // select (setcc x, K) (fneg x), -K -> fneg(minnum(x, K))
  9077. //
  9078. // TODO: Handle fabs
  9079. if (LHS == NegTrue) {
  9080. // If we can't directly match this, try to see if we can pull an fneg out of
  9081. // the select.
  9082. SDValue NegRHS = TLI.getCheaperOrNeutralNegatedExpression(
  9083. RHS, DAG, LegalOperations, ForCodeSize);
  9084. if (NegRHS) {
  9085. HandleSDNode NegRHSHandle(NegRHS);
  9086. if (NegRHS == False) {
  9087. SDValue Combined = combineMinNumMaxNumImpl(DL, VT, LHS, RHS, NegTrue,
  9088. False, CC, TLI, DAG);
  9089. if (Combined)
  9090. return DAG.getNode(ISD::FNEG, DL, VT, Combined);
  9091. }
  9092. }
  9093. }
  9094. return SDValue();
  9095. }
  9096. /// If a (v)select has a condition value that is a sign-bit test, try to smear
  9097. /// the condition operand sign-bit across the value width and use it as a mask.
  9098. static SDValue foldSelectOfConstantsUsingSra(SDNode *N, SelectionDAG &DAG) {
  9099. SDValue Cond = N->getOperand(0);
  9100. SDValue C1 = N->getOperand(1);
  9101. SDValue C2 = N->getOperand(2);
  9102. if (!isConstantOrConstantVector(C1) || !isConstantOrConstantVector(C2))
  9103. return SDValue();
  9104. EVT VT = N->getValueType(0);
  9105. if (Cond.getOpcode() != ISD::SETCC || !Cond.hasOneUse() ||
  9106. VT != Cond.getOperand(0).getValueType())
  9107. return SDValue();
  9108. // The inverted-condition + commuted-select variants of these patterns are
  9109. // canonicalized to these forms in IR.
  9110. SDValue X = Cond.getOperand(0);
  9111. SDValue CondC = Cond.getOperand(1);
  9112. ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
  9113. if (CC == ISD::SETGT && isAllOnesOrAllOnesSplat(CondC) &&
  9114. isAllOnesOrAllOnesSplat(C2)) {
  9115. // i32 X > -1 ? C1 : -1 --> (X >>s 31) | C1
  9116. SDLoc DL(N);
  9117. SDValue ShAmtC = DAG.getConstant(X.getScalarValueSizeInBits() - 1, DL, VT);
  9118. SDValue Sra = DAG.getNode(ISD::SRA, DL, VT, X, ShAmtC);
  9119. return DAG.getNode(ISD::OR, DL, VT, Sra, C1);
  9120. }
  9121. if (CC == ISD::SETLT && isNullOrNullSplat(CondC) && isNullOrNullSplat(C2)) {
  9122. // i8 X < 0 ? C1 : 0 --> (X >>s 7) & C1
  9123. SDLoc DL(N);
  9124. SDValue ShAmtC = DAG.getConstant(X.getScalarValueSizeInBits() - 1, DL, VT);
  9125. SDValue Sra = DAG.getNode(ISD::SRA, DL, VT, X, ShAmtC);
  9126. return DAG.getNode(ISD::AND, DL, VT, Sra, C1);
  9127. }
  9128. return SDValue();
  9129. }
  9130. static bool shouldConvertSelectOfConstantsToMath(const SDValue &Cond, EVT VT,
  9131. const TargetLowering &TLI) {
  9132. if (!TLI.convertSelectOfConstantsToMath(VT))
  9133. return false;
  9134. if (Cond.getOpcode() != ISD::SETCC || !Cond->hasOneUse())
  9135. return true;
  9136. if (!TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT))
  9137. return true;
  9138. ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
  9139. if (CC == ISD::SETLT && isNullOrNullSplat(Cond.getOperand(1)))
  9140. return true;
  9141. if (CC == ISD::SETGT && isAllOnesOrAllOnesSplat(Cond.getOperand(1)))
  9142. return true;
  9143. return false;
  9144. }
  9145. SDValue DAGCombiner::foldSelectOfConstants(SDNode *N) {
  9146. SDValue Cond = N->getOperand(0);
  9147. SDValue N1 = N->getOperand(1);
  9148. SDValue N2 = N->getOperand(2);
  9149. EVT VT = N->getValueType(0);
  9150. EVT CondVT = Cond.getValueType();
  9151. SDLoc DL(N);
  9152. if (!VT.isInteger())
  9153. return SDValue();
  9154. auto *C1 = dyn_cast<ConstantSDNode>(N1);
  9155. auto *C2 = dyn_cast<ConstantSDNode>(N2);
  9156. if (!C1 || !C2)
  9157. return SDValue();
  9158. if (CondVT != MVT::i1 || LegalOperations) {
  9159. // fold (select Cond, 0, 1) -> (xor Cond, 1)
  9160. // We can't do this reliably if integer based booleans have different contents
  9161. // to floating point based booleans. This is because we can't tell whether we
  9162. // have an integer-based boolean or a floating-point-based boolean unless we
  9163. // can find the SETCC that produced it and inspect its operands. This is
  9164. // fairly easy if C is the SETCC node, but it can potentially be
  9165. // undiscoverable (or not reasonably discoverable). For example, it could be
  9166. // in another basic block or it could require searching a complicated
  9167. // expression.
  9168. if (CondVT.isInteger() &&
  9169. TLI.getBooleanContents(/*isVec*/false, /*isFloat*/true) ==
  9170. TargetLowering::ZeroOrOneBooleanContent &&
  9171. TLI.getBooleanContents(/*isVec*/false, /*isFloat*/false) ==
  9172. TargetLowering::ZeroOrOneBooleanContent &&
  9173. C1->isZero() && C2->isOne()) {
  9174. SDValue NotCond =
  9175. DAG.getNode(ISD::XOR, DL, CondVT, Cond, DAG.getConstant(1, DL, CondVT));
  9176. if (VT.bitsEq(CondVT))
  9177. return NotCond;
  9178. return DAG.getZExtOrTrunc(NotCond, DL, VT);
  9179. }
  9180. return SDValue();
  9181. }
  9182. // Only do this before legalization to avoid conflicting with target-specific
  9183. // transforms in the other direction (create a select from a zext/sext). There
  9184. // is also a target-independent combine here in DAGCombiner in the other
  9185. // direction for (select Cond, -1, 0) when the condition is not i1.
  9186. assert(CondVT == MVT::i1 && !LegalOperations);
  9187. // select Cond, 1, 0 --> zext (Cond)
  9188. if (C1->isOne() && C2->isZero())
  9189. return DAG.getZExtOrTrunc(Cond, DL, VT);
  9190. // select Cond, -1, 0 --> sext (Cond)
  9191. if (C1->isAllOnes() && C2->isZero())
  9192. return DAG.getSExtOrTrunc(Cond, DL, VT);
  9193. // select Cond, 0, 1 --> zext (!Cond)
  9194. if (C1->isZero() && C2->isOne()) {
  9195. SDValue NotCond = DAG.getNOT(DL, Cond, MVT::i1);
  9196. NotCond = DAG.getZExtOrTrunc(NotCond, DL, VT);
  9197. return NotCond;
  9198. }
  9199. // select Cond, 0, -1 --> sext (!Cond)
  9200. if (C1->isZero() && C2->isAllOnes()) {
  9201. SDValue NotCond = DAG.getNOT(DL, Cond, MVT::i1);
  9202. NotCond = DAG.getSExtOrTrunc(NotCond, DL, VT);
  9203. return NotCond;
  9204. }
  9205. // Use a target hook because some targets may prefer to transform in the
  9206. // other direction.
  9207. if (!shouldConvertSelectOfConstantsToMath(Cond, VT, TLI))
  9208. return SDValue();
  9209. // For any constants that differ by 1, we can transform the select into
  9210. // an extend and add.
  9211. const APInt &C1Val = C1->getAPIntValue();
  9212. const APInt &C2Val = C2->getAPIntValue();
  9213. // select Cond, C1, C1-1 --> add (zext Cond), C1-1
  9214. if (C1Val - 1 == C2Val) {
  9215. Cond = DAG.getZExtOrTrunc(Cond, DL, VT);
  9216. return DAG.getNode(ISD::ADD, DL, VT, Cond, N2);
  9217. }
  9218. // select Cond, C1, C1+1 --> add (sext Cond), C1+1
  9219. if (C1Val + 1 == C2Val) {
  9220. Cond = DAG.getSExtOrTrunc(Cond, DL, VT);
  9221. return DAG.getNode(ISD::ADD, DL, VT, Cond, N2);
  9222. }
  9223. // select Cond, Pow2, 0 --> (zext Cond) << log2(Pow2)
  9224. if (C1Val.isPowerOf2() && C2Val.isZero()) {
  9225. Cond = DAG.getZExtOrTrunc(Cond, DL, VT);
  9226. SDValue ShAmtC =
  9227. DAG.getShiftAmountConstant(C1Val.exactLogBase2(), VT, DL);
  9228. return DAG.getNode(ISD::SHL, DL, VT, Cond, ShAmtC);
  9229. }
  9230. // select Cond, -1, C --> or (sext Cond), C
  9231. if (C1->isAllOnes()) {
  9232. Cond = DAG.getSExtOrTrunc(Cond, DL, VT);
  9233. return DAG.getNode(ISD::OR, DL, VT, Cond, N2);
  9234. }
  9235. // select Cond, C, -1 --> or (sext (not Cond)), C
  9236. if (C2->isAllOnes()) {
  9237. SDValue NotCond = DAG.getNOT(DL, Cond, MVT::i1);
  9238. NotCond = DAG.getSExtOrTrunc(NotCond, DL, VT);
  9239. return DAG.getNode(ISD::OR, DL, VT, NotCond, N1);
  9240. }
  9241. if (SDValue V = foldSelectOfConstantsUsingSra(N, DAG))
  9242. return V;
  9243. return SDValue();
  9244. }
  9245. static SDValue foldBoolSelectToLogic(SDNode *N, SelectionDAG &DAG) {
  9246. assert((N->getOpcode() == ISD::SELECT || N->getOpcode() == ISD::VSELECT) &&
  9247. "Expected a (v)select");
  9248. SDValue Cond = N->getOperand(0);
  9249. SDValue T = N->getOperand(1), F = N->getOperand(2);
  9250. EVT VT = N->getValueType(0);
  9251. if (VT != Cond.getValueType() || VT.getScalarSizeInBits() != 1)
  9252. return SDValue();
  9253. // select Cond, Cond, F --> or Cond, F
  9254. // select Cond, 1, F --> or Cond, F
  9255. if (Cond == T || isOneOrOneSplat(T, /* AllowUndefs */ true))
  9256. return DAG.getNode(ISD::OR, SDLoc(N), VT, Cond, F);
  9257. // select Cond, T, Cond --> and Cond, T
  9258. // select Cond, T, 0 --> and Cond, T
  9259. if (Cond == F || isNullOrNullSplat(F, /* AllowUndefs */ true))
  9260. return DAG.getNode(ISD::AND, SDLoc(N), VT, Cond, T);
  9261. // select Cond, T, 1 --> or (not Cond), T
  9262. if (isOneOrOneSplat(F, /* AllowUndefs */ true)) {
  9263. SDValue NotCond = DAG.getNOT(SDLoc(N), Cond, VT);
  9264. return DAG.getNode(ISD::OR, SDLoc(N), VT, NotCond, T);
  9265. }
  9266. // select Cond, 0, F --> and (not Cond), F
  9267. if (isNullOrNullSplat(T, /* AllowUndefs */ true)) {
  9268. SDValue NotCond = DAG.getNOT(SDLoc(N), Cond, VT);
  9269. return DAG.getNode(ISD::AND, SDLoc(N), VT, NotCond, F);
  9270. }
  9271. return SDValue();
  9272. }
  9273. static SDValue foldVSelectToSignBitSplatMask(SDNode *N, SelectionDAG &DAG) {
  9274. SDValue N0 = N->getOperand(0);
  9275. SDValue N1 = N->getOperand(1);
  9276. SDValue N2 = N->getOperand(2);
  9277. EVT VT = N->getValueType(0);
  9278. if (N0.getOpcode() != ISD::SETCC || !N0.hasOneUse())
  9279. return SDValue();
  9280. SDValue Cond0 = N0.getOperand(0);
  9281. SDValue Cond1 = N0.getOperand(1);
  9282. ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
  9283. if (VT != Cond0.getValueType())
  9284. return SDValue();
  9285. // Match a signbit check of Cond0 as "Cond0 s<0". Swap select operands if the
  9286. // compare is inverted from that pattern ("Cond0 s> -1").
  9287. if (CC == ISD::SETLT && isNullOrNullSplat(Cond1))
  9288. ; // This is the pattern we are looking for.
  9289. else if (CC == ISD::SETGT && isAllOnesOrAllOnesSplat(Cond1))
  9290. std::swap(N1, N2);
  9291. else
  9292. return SDValue();
  9293. // (Cond0 s< 0) ? N1 : 0 --> (Cond0 s>> BW-1) & N1
  9294. if (isNullOrNullSplat(N2)) {
  9295. SDLoc DL(N);
  9296. SDValue ShiftAmt = DAG.getConstant(VT.getScalarSizeInBits() - 1, DL, VT);
  9297. SDValue Sra = DAG.getNode(ISD::SRA, DL, VT, Cond0, ShiftAmt);
  9298. return DAG.getNode(ISD::AND, DL, VT, Sra, N1);
  9299. }
  9300. // (Cond0 s< 0) ? -1 : N2 --> (Cond0 s>> BW-1) | N2
  9301. if (isAllOnesOrAllOnesSplat(N1)) {
  9302. SDLoc DL(N);
  9303. SDValue ShiftAmt = DAG.getConstant(VT.getScalarSizeInBits() - 1, DL, VT);
  9304. SDValue Sra = DAG.getNode(ISD::SRA, DL, VT, Cond0, ShiftAmt);
  9305. return DAG.getNode(ISD::OR, DL, VT, Sra, N2);
  9306. }
  9307. // If we have to invert the sign bit mask, only do that transform if the
  9308. // target has a bitwise 'and not' instruction (the invert is free).
  9309. // (Cond0 s< -0) ? 0 : N2 --> ~(Cond0 s>> BW-1) & N2
  9310. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  9311. if (isNullOrNullSplat(N1) && TLI.hasAndNot(N1)) {
  9312. SDLoc DL(N);
  9313. SDValue ShiftAmt = DAG.getConstant(VT.getScalarSizeInBits() - 1, DL, VT);
  9314. SDValue Sra = DAG.getNode(ISD::SRA, DL, VT, Cond0, ShiftAmt);
  9315. SDValue Not = DAG.getNOT(DL, Sra, VT);
  9316. return DAG.getNode(ISD::AND, DL, VT, Not, N2);
  9317. }
  9318. // TODO: There's another pattern in this family, but it may require
  9319. // implementing hasOrNot() to check for profitability:
  9320. // (Cond0 s> -1) ? -1 : N2 --> ~(Cond0 s>> BW-1) | N2
  9321. return SDValue();
  9322. }
  9323. SDValue DAGCombiner::visitSELECT(SDNode *N) {
  9324. SDValue N0 = N->getOperand(0);
  9325. SDValue N1 = N->getOperand(1);
  9326. SDValue N2 = N->getOperand(2);
  9327. EVT VT = N->getValueType(0);
  9328. EVT VT0 = N0.getValueType();
  9329. SDLoc DL(N);
  9330. SDNodeFlags Flags = N->getFlags();
  9331. if (SDValue V = DAG.simplifySelect(N0, N1, N2))
  9332. return V;
  9333. if (SDValue V = foldBoolSelectToLogic(N, DAG))
  9334. return V;
  9335. // select (not Cond), N1, N2 -> select Cond, N2, N1
  9336. if (SDValue F = extractBooleanFlip(N0, DAG, TLI, false)) {
  9337. SDValue SelectOp = DAG.getSelect(DL, VT, F, N2, N1);
  9338. SelectOp->setFlags(Flags);
  9339. return SelectOp;
  9340. }
  9341. if (SDValue V = foldSelectOfConstants(N))
  9342. return V;
  9343. // If we can fold this based on the true/false value, do so.
  9344. if (SimplifySelectOps(N, N1, N2))
  9345. return SDValue(N, 0); // Don't revisit N.
  9346. if (VT0 == MVT::i1) {
  9347. // The code in this block deals with the following 2 equivalences:
  9348. // select(C0|C1, x, y) <=> select(C0, x, select(C1, x, y))
  9349. // select(C0&C1, x, y) <=> select(C0, select(C1, x, y), y)
  9350. // The target can specify its preferred form with the
  9351. // shouldNormalizeToSelectSequence() callback. However we always transform
  9352. // to the right anyway if we find the inner select exists in the DAG anyway
  9353. // and we always transform to the left side if we know that we can further
  9354. // optimize the combination of the conditions.
  9355. bool normalizeToSequence =
  9356. TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT);
  9357. // select (and Cond0, Cond1), X, Y
  9358. // -> select Cond0, (select Cond1, X, Y), Y
  9359. if (N0->getOpcode() == ISD::AND && N0->hasOneUse()) {
  9360. SDValue Cond0 = N0->getOperand(0);
  9361. SDValue Cond1 = N0->getOperand(1);
  9362. SDValue InnerSelect =
  9363. DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Cond1, N1, N2, Flags);
  9364. if (normalizeToSequence || !InnerSelect.use_empty())
  9365. return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Cond0,
  9366. InnerSelect, N2, Flags);
  9367. // Cleanup on failure.
  9368. if (InnerSelect.use_empty())
  9369. recursivelyDeleteUnusedNodes(InnerSelect.getNode());
  9370. }
  9371. // select (or Cond0, Cond1), X, Y -> select Cond0, X, (select Cond1, X, Y)
  9372. if (N0->getOpcode() == ISD::OR && N0->hasOneUse()) {
  9373. SDValue Cond0 = N0->getOperand(0);
  9374. SDValue Cond1 = N0->getOperand(1);
  9375. SDValue InnerSelect = DAG.getNode(ISD::SELECT, DL, N1.getValueType(),
  9376. Cond1, N1, N2, Flags);
  9377. if (normalizeToSequence || !InnerSelect.use_empty())
  9378. return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Cond0, N1,
  9379. InnerSelect, Flags);
  9380. // Cleanup on failure.
  9381. if (InnerSelect.use_empty())
  9382. recursivelyDeleteUnusedNodes(InnerSelect.getNode());
  9383. }
  9384. // select Cond0, (select Cond1, X, Y), Y -> select (and Cond0, Cond1), X, Y
  9385. if (N1->getOpcode() == ISD::SELECT && N1->hasOneUse()) {
  9386. SDValue N1_0 = N1->getOperand(0);
  9387. SDValue N1_1 = N1->getOperand(1);
  9388. SDValue N1_2 = N1->getOperand(2);
  9389. if (N1_2 == N2 && N0.getValueType() == N1_0.getValueType()) {
  9390. // Create the actual and node if we can generate good code for it.
  9391. if (!normalizeToSequence) {
  9392. SDValue And = DAG.getNode(ISD::AND, DL, N0.getValueType(), N0, N1_0);
  9393. return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), And, N1_1,
  9394. N2, Flags);
  9395. }
  9396. // Otherwise see if we can optimize the "and" to a better pattern.
  9397. if (SDValue Combined = visitANDLike(N0, N1_0, N)) {
  9398. return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Combined, N1_1,
  9399. N2, Flags);
  9400. }
  9401. }
  9402. }
  9403. // select Cond0, X, (select Cond1, X, Y) -> select (or Cond0, Cond1), X, Y
  9404. if (N2->getOpcode() == ISD::SELECT && N2->hasOneUse()) {
  9405. SDValue N2_0 = N2->getOperand(0);
  9406. SDValue N2_1 = N2->getOperand(1);
  9407. SDValue N2_2 = N2->getOperand(2);
  9408. if (N2_1 == N1 && N0.getValueType() == N2_0.getValueType()) {
  9409. // Create the actual or node if we can generate good code for it.
  9410. if (!normalizeToSequence) {
  9411. SDValue Or = DAG.getNode(ISD::OR, DL, N0.getValueType(), N0, N2_0);
  9412. return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Or, N1,
  9413. N2_2, Flags);
  9414. }
  9415. // Otherwise see if we can optimize to a better pattern.
  9416. if (SDValue Combined = visitORLike(N0, N2_0, N))
  9417. return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Combined, N1,
  9418. N2_2, Flags);
  9419. }
  9420. }
  9421. }
  9422. // Fold selects based on a setcc into other things, such as min/max/abs.
  9423. if (N0.getOpcode() == ISD::SETCC) {
  9424. SDValue Cond0 = N0.getOperand(0), Cond1 = N0.getOperand(1);
  9425. ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
  9426. // select (fcmp lt x, y), x, y -> fminnum x, y
  9427. // select (fcmp gt x, y), x, y -> fmaxnum x, y
  9428. //
  9429. // This is OK if we don't care what happens if either operand is a NaN.
  9430. if (N0.hasOneUse() && isLegalToCombineMinNumMaxNum(DAG, N1, N2, TLI))
  9431. if (SDValue FMinMax =
  9432. combineMinNumMaxNum(DL, VT, Cond0, Cond1, N1, N2, CC))
  9433. return FMinMax;
  9434. // Use 'unsigned add with overflow' to optimize an unsigned saturating add.
  9435. // This is conservatively limited to pre-legal-operations to give targets
  9436. // a chance to reverse the transform if they want to do that. Also, it is
  9437. // unlikely that the pattern would be formed late, so it's probably not
  9438. // worth going through the other checks.
  9439. if (!LegalOperations && TLI.isOperationLegalOrCustom(ISD::UADDO, VT) &&
  9440. CC == ISD::SETUGT && N0.hasOneUse() && isAllOnesConstant(N1) &&
  9441. N2.getOpcode() == ISD::ADD && Cond0 == N2.getOperand(0)) {
  9442. auto *C = dyn_cast<ConstantSDNode>(N2.getOperand(1));
  9443. auto *NotC = dyn_cast<ConstantSDNode>(Cond1);
  9444. if (C && NotC && C->getAPIntValue() == ~NotC->getAPIntValue()) {
  9445. // select (setcc Cond0, ~C, ugt), -1, (add Cond0, C) -->
  9446. // uaddo Cond0, C; select uaddo.1, -1, uaddo.0
  9447. //
  9448. // The IR equivalent of this transform would have this form:
  9449. // %a = add %x, C
  9450. // %c = icmp ugt %x, ~C
  9451. // %r = select %c, -1, %a
  9452. // =>
  9453. // %u = call {iN,i1} llvm.uadd.with.overflow(%x, C)
  9454. // %u0 = extractvalue %u, 0
  9455. // %u1 = extractvalue %u, 1
  9456. // %r = select %u1, -1, %u0
  9457. SDVTList VTs = DAG.getVTList(VT, VT0);
  9458. SDValue UAO = DAG.getNode(ISD::UADDO, DL, VTs, Cond0, N2.getOperand(1));
  9459. return DAG.getSelect(DL, VT, UAO.getValue(1), N1, UAO.getValue(0));
  9460. }
  9461. }
  9462. if (TLI.isOperationLegal(ISD::SELECT_CC, VT) ||
  9463. (!LegalOperations &&
  9464. TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT))) {
  9465. // Any flags available in a select/setcc fold will be on the setcc as they
  9466. // migrated from fcmp
  9467. Flags = N0->getFlags();
  9468. SDValue SelectNode = DAG.getNode(ISD::SELECT_CC, DL, VT, Cond0, Cond1, N1,
  9469. N2, N0.getOperand(2));
  9470. SelectNode->setFlags(Flags);
  9471. return SelectNode;
  9472. }
  9473. if (SDValue NewSel = SimplifySelect(DL, N0, N1, N2))
  9474. return NewSel;
  9475. }
  9476. if (!VT.isVector())
  9477. if (SDValue BinOp = foldSelectOfBinops(N))
  9478. return BinOp;
  9479. return SDValue();
  9480. }
  9481. // This function assumes all the vselect's arguments are CONCAT_VECTOR
  9482. // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
  9483. static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
  9484. SDLoc DL(N);
  9485. SDValue Cond = N->getOperand(0);
  9486. SDValue LHS = N->getOperand(1);
  9487. SDValue RHS = N->getOperand(2);
  9488. EVT VT = N->getValueType(0);
  9489. int NumElems = VT.getVectorNumElements();
  9490. assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
  9491. RHS.getOpcode() == ISD::CONCAT_VECTORS &&
  9492. Cond.getOpcode() == ISD::BUILD_VECTOR);
  9493. // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about
  9494. // binary ones here.
  9495. if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2)
  9496. return SDValue();
  9497. // We're sure we have an even number of elements due to the
  9498. // concat_vectors we have as arguments to vselect.
  9499. // Skip BV elements until we find one that's not an UNDEF
  9500. // After we find an UNDEF element, keep looping until we get to half the
  9501. // length of the BV and see if all the non-undef nodes are the same.
  9502. ConstantSDNode *BottomHalf = nullptr;
  9503. for (int i = 0; i < NumElems / 2; ++i) {
  9504. if (Cond->getOperand(i)->isUndef())
  9505. continue;
  9506. if (BottomHalf == nullptr)
  9507. BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
  9508. else if (Cond->getOperand(i).getNode() != BottomHalf)
  9509. return SDValue();
  9510. }
  9511. // Do the same for the second half of the BuildVector
  9512. ConstantSDNode *TopHalf = nullptr;
  9513. for (int i = NumElems / 2; i < NumElems; ++i) {
  9514. if (Cond->getOperand(i)->isUndef())
  9515. continue;
  9516. if (TopHalf == nullptr)
  9517. TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
  9518. else if (Cond->getOperand(i).getNode() != TopHalf)
  9519. return SDValue();
  9520. }
  9521. assert(TopHalf && BottomHalf &&
  9522. "One half of the selector was all UNDEFs and the other was all the "
  9523. "same value. This should have been addressed before this function.");
  9524. return DAG.getNode(
  9525. ISD::CONCAT_VECTORS, DL, VT,
  9526. BottomHalf->isZero() ? RHS->getOperand(0) : LHS->getOperand(0),
  9527. TopHalf->isZero() ? RHS->getOperand(1) : LHS->getOperand(1));
  9528. }
  9529. bool refineUniformBase(SDValue &BasePtr, SDValue &Index, bool IndexIsScaled,
  9530. SelectionDAG &DAG, const SDLoc &DL) {
  9531. if (Index.getOpcode() != ISD::ADD)
  9532. return false;
  9533. // Only perform the transformation when existing operands can be reused.
  9534. if (IndexIsScaled)
  9535. return false;
  9536. if (!isNullConstant(BasePtr) && !Index.hasOneUse())
  9537. return false;
  9538. EVT VT = BasePtr.getValueType();
  9539. if (SDValue SplatVal = DAG.getSplatValue(Index.getOperand(0));
  9540. SplatVal && SplatVal.getValueType() == VT) {
  9541. if (isNullConstant(BasePtr))
  9542. BasePtr = SplatVal;
  9543. else
  9544. BasePtr = DAG.getNode(ISD::ADD, DL, VT, BasePtr, SplatVal);
  9545. Index = Index.getOperand(1);
  9546. return true;
  9547. }
  9548. if (SDValue SplatVal = DAG.getSplatValue(Index.getOperand(1));
  9549. SplatVal && SplatVal.getValueType() == VT) {
  9550. if (isNullConstant(BasePtr))
  9551. BasePtr = SplatVal;
  9552. else
  9553. BasePtr = DAG.getNode(ISD::ADD, DL, VT, BasePtr, SplatVal);
  9554. Index = Index.getOperand(0);
  9555. return true;
  9556. }
  9557. return false;
  9558. }
  9559. // Fold sext/zext of index into index type.
  9560. bool refineIndexType(SDValue &Index, ISD::MemIndexType &IndexType, EVT DataVT,
  9561. SelectionDAG &DAG) {
  9562. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  9563. // It's always safe to look through zero extends.
  9564. if (Index.getOpcode() == ISD::ZERO_EXTEND) {
  9565. SDValue Op = Index.getOperand(0);
  9566. if (TLI.shouldRemoveExtendFromGSIndex(Op.getValueType(), DataVT)) {
  9567. IndexType = ISD::UNSIGNED_SCALED;
  9568. Index = Op;
  9569. return true;
  9570. }
  9571. if (ISD::isIndexTypeSigned(IndexType)) {
  9572. IndexType = ISD::UNSIGNED_SCALED;
  9573. return true;
  9574. }
  9575. }
  9576. // It's only safe to look through sign extends when Index is signed.
  9577. if (Index.getOpcode() == ISD::SIGN_EXTEND &&
  9578. ISD::isIndexTypeSigned(IndexType)) {
  9579. SDValue Op = Index.getOperand(0);
  9580. if (TLI.shouldRemoveExtendFromGSIndex(Op.getValueType(), DataVT)) {
  9581. Index = Op;
  9582. return true;
  9583. }
  9584. }
  9585. return false;
  9586. }
  9587. SDValue DAGCombiner::visitVPSCATTER(SDNode *N) {
  9588. VPScatterSDNode *MSC = cast<VPScatterSDNode>(N);
  9589. SDValue Mask = MSC->getMask();
  9590. SDValue Chain = MSC->getChain();
  9591. SDValue Index = MSC->getIndex();
  9592. SDValue Scale = MSC->getScale();
  9593. SDValue StoreVal = MSC->getValue();
  9594. SDValue BasePtr = MSC->getBasePtr();
  9595. SDValue VL = MSC->getVectorLength();
  9596. ISD::MemIndexType IndexType = MSC->getIndexType();
  9597. SDLoc DL(N);
  9598. // Zap scatters with a zero mask.
  9599. if (ISD::isConstantSplatVectorAllZeros(Mask.getNode()))
  9600. return Chain;
  9601. if (refineUniformBase(BasePtr, Index, MSC->isIndexScaled(), DAG, DL)) {
  9602. SDValue Ops[] = {Chain, StoreVal, BasePtr, Index, Scale, Mask, VL};
  9603. return DAG.getScatterVP(DAG.getVTList(MVT::Other), MSC->getMemoryVT(),
  9604. DL, Ops, MSC->getMemOperand(), IndexType);
  9605. }
  9606. if (refineIndexType(Index, IndexType, StoreVal.getValueType(), DAG)) {
  9607. SDValue Ops[] = {Chain, StoreVal, BasePtr, Index, Scale, Mask, VL};
  9608. return DAG.getScatterVP(DAG.getVTList(MVT::Other), MSC->getMemoryVT(),
  9609. DL, Ops, MSC->getMemOperand(), IndexType);
  9610. }
  9611. return SDValue();
  9612. }
  9613. SDValue DAGCombiner::visitMSCATTER(SDNode *N) {
  9614. MaskedScatterSDNode *MSC = cast<MaskedScatterSDNode>(N);
  9615. SDValue Mask = MSC->getMask();
  9616. SDValue Chain = MSC->getChain();
  9617. SDValue Index = MSC->getIndex();
  9618. SDValue Scale = MSC->getScale();
  9619. SDValue StoreVal = MSC->getValue();
  9620. SDValue BasePtr = MSC->getBasePtr();
  9621. ISD::MemIndexType IndexType = MSC->getIndexType();
  9622. SDLoc DL(N);
  9623. // Zap scatters with a zero mask.
  9624. if (ISD::isConstantSplatVectorAllZeros(Mask.getNode()))
  9625. return Chain;
  9626. if (refineUniformBase(BasePtr, Index, MSC->isIndexScaled(), DAG, DL)) {
  9627. SDValue Ops[] = {Chain, StoreVal, Mask, BasePtr, Index, Scale};
  9628. return DAG.getMaskedScatter(DAG.getVTList(MVT::Other), MSC->getMemoryVT(),
  9629. DL, Ops, MSC->getMemOperand(), IndexType,
  9630. MSC->isTruncatingStore());
  9631. }
  9632. if (refineIndexType(Index, IndexType, StoreVal.getValueType(), DAG)) {
  9633. SDValue Ops[] = {Chain, StoreVal, Mask, BasePtr, Index, Scale};
  9634. return DAG.getMaskedScatter(DAG.getVTList(MVT::Other), MSC->getMemoryVT(),
  9635. DL, Ops, MSC->getMemOperand(), IndexType,
  9636. MSC->isTruncatingStore());
  9637. }
  9638. return SDValue();
  9639. }
  9640. SDValue DAGCombiner::visitMSTORE(SDNode *N) {
  9641. MaskedStoreSDNode *MST = cast<MaskedStoreSDNode>(N);
  9642. SDValue Mask = MST->getMask();
  9643. SDValue Chain = MST->getChain();
  9644. SDValue Value = MST->getValue();
  9645. SDValue Ptr = MST->getBasePtr();
  9646. SDLoc DL(N);
  9647. // Zap masked stores with a zero mask.
  9648. if (ISD::isConstantSplatVectorAllZeros(Mask.getNode()))
  9649. return Chain;
  9650. // If this is a masked load with an all ones mask, we can use a unmasked load.
  9651. // FIXME: Can we do this for indexed, compressing, or truncating stores?
  9652. if (ISD::isConstantSplatVectorAllOnes(Mask.getNode()) && MST->isUnindexed() &&
  9653. !MST->isCompressingStore() && !MST->isTruncatingStore())
  9654. return DAG.getStore(MST->getChain(), SDLoc(N), MST->getValue(),
  9655. MST->getBasePtr(), MST->getPointerInfo(),
  9656. MST->getOriginalAlign(), MachineMemOperand::MOStore,
  9657. MST->getAAInfo());
  9658. // Try transforming N to an indexed store.
  9659. if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
  9660. return SDValue(N, 0);
  9661. if (MST->isTruncatingStore() && MST->isUnindexed() &&
  9662. Value.getValueType().isInteger() &&
  9663. (!isa<ConstantSDNode>(Value) ||
  9664. !cast<ConstantSDNode>(Value)->isOpaque())) {
  9665. APInt TruncDemandedBits =
  9666. APInt::getLowBitsSet(Value.getScalarValueSizeInBits(),
  9667. MST->getMemoryVT().getScalarSizeInBits());
  9668. // See if we can simplify the operation with
  9669. // SimplifyDemandedBits, which only works if the value has a single use.
  9670. if (SimplifyDemandedBits(Value, TruncDemandedBits)) {
  9671. // Re-visit the store if anything changed and the store hasn't been merged
  9672. // with another node (N is deleted) SimplifyDemandedBits will add Value's
  9673. // node back to the worklist if necessary, but we also need to re-visit
  9674. // the Store node itself.
  9675. if (N->getOpcode() != ISD::DELETED_NODE)
  9676. AddToWorklist(N);
  9677. return SDValue(N, 0);
  9678. }
  9679. }
  9680. // If this is a TRUNC followed by a masked store, fold this into a masked
  9681. // truncating store. We can do this even if this is already a masked
  9682. // truncstore.
  9683. // TODO: Try combine to masked compress store if possiable.
  9684. if ((Value.getOpcode() == ISD::TRUNCATE) && Value->hasOneUse() &&
  9685. MST->isUnindexed() && !MST->isCompressingStore() &&
  9686. TLI.canCombineTruncStore(Value.getOperand(0).getValueType(),
  9687. MST->getMemoryVT(), LegalOperations)) {
  9688. auto Mask = TLI.promoteTargetBoolean(DAG, MST->getMask(),
  9689. Value.getOperand(0).getValueType());
  9690. return DAG.getMaskedStore(Chain, SDLoc(N), Value.getOperand(0), Ptr,
  9691. MST->getOffset(), Mask, MST->getMemoryVT(),
  9692. MST->getMemOperand(), MST->getAddressingMode(),
  9693. /*IsTruncating=*/true);
  9694. }
  9695. return SDValue();
  9696. }
  9697. SDValue DAGCombiner::visitVPGATHER(SDNode *N) {
  9698. VPGatherSDNode *MGT = cast<VPGatherSDNode>(N);
  9699. SDValue Mask = MGT->getMask();
  9700. SDValue Chain = MGT->getChain();
  9701. SDValue Index = MGT->getIndex();
  9702. SDValue Scale = MGT->getScale();
  9703. SDValue BasePtr = MGT->getBasePtr();
  9704. SDValue VL = MGT->getVectorLength();
  9705. ISD::MemIndexType IndexType = MGT->getIndexType();
  9706. SDLoc DL(N);
  9707. if (refineUniformBase(BasePtr, Index, MGT->isIndexScaled(), DAG, DL)) {
  9708. SDValue Ops[] = {Chain, BasePtr, Index, Scale, Mask, VL};
  9709. return DAG.getGatherVP(
  9710. DAG.getVTList(N->getValueType(0), MVT::Other), MGT->getMemoryVT(), DL,
  9711. Ops, MGT->getMemOperand(), IndexType);
  9712. }
  9713. if (refineIndexType(Index, IndexType, N->getValueType(0), DAG)) {
  9714. SDValue Ops[] = {Chain, BasePtr, Index, Scale, Mask, VL};
  9715. return DAG.getGatherVP(
  9716. DAG.getVTList(N->getValueType(0), MVT::Other), MGT->getMemoryVT(), DL,
  9717. Ops, MGT->getMemOperand(), IndexType);
  9718. }
  9719. return SDValue();
  9720. }
  9721. SDValue DAGCombiner::visitMGATHER(SDNode *N) {
  9722. MaskedGatherSDNode *MGT = cast<MaskedGatherSDNode>(N);
  9723. SDValue Mask = MGT->getMask();
  9724. SDValue Chain = MGT->getChain();
  9725. SDValue Index = MGT->getIndex();
  9726. SDValue Scale = MGT->getScale();
  9727. SDValue PassThru = MGT->getPassThru();
  9728. SDValue BasePtr = MGT->getBasePtr();
  9729. ISD::MemIndexType IndexType = MGT->getIndexType();
  9730. SDLoc DL(N);
  9731. // Zap gathers with a zero mask.
  9732. if (ISD::isConstantSplatVectorAllZeros(Mask.getNode()))
  9733. return CombineTo(N, PassThru, MGT->getChain());
  9734. if (refineUniformBase(BasePtr, Index, MGT->isIndexScaled(), DAG, DL)) {
  9735. SDValue Ops[] = {Chain, PassThru, Mask, BasePtr, Index, Scale};
  9736. return DAG.getMaskedGather(
  9737. DAG.getVTList(N->getValueType(0), MVT::Other), MGT->getMemoryVT(), DL,
  9738. Ops, MGT->getMemOperand(), IndexType, MGT->getExtensionType());
  9739. }
  9740. if (refineIndexType(Index, IndexType, N->getValueType(0), DAG)) {
  9741. SDValue Ops[] = {Chain, PassThru, Mask, BasePtr, Index, Scale};
  9742. return DAG.getMaskedGather(
  9743. DAG.getVTList(N->getValueType(0), MVT::Other), MGT->getMemoryVT(), DL,
  9744. Ops, MGT->getMemOperand(), IndexType, MGT->getExtensionType());
  9745. }
  9746. return SDValue();
  9747. }
  9748. SDValue DAGCombiner::visitMLOAD(SDNode *N) {
  9749. MaskedLoadSDNode *MLD = cast<MaskedLoadSDNode>(N);
  9750. SDValue Mask = MLD->getMask();
  9751. SDLoc DL(N);
  9752. // Zap masked loads with a zero mask.
  9753. if (ISD::isConstantSplatVectorAllZeros(Mask.getNode()))
  9754. return CombineTo(N, MLD->getPassThru(), MLD->getChain());
  9755. // If this is a masked load with an all ones mask, we can use a unmasked load.
  9756. // FIXME: Can we do this for indexed, expanding, or extending loads?
  9757. if (ISD::isConstantSplatVectorAllOnes(Mask.getNode()) && MLD->isUnindexed() &&
  9758. !MLD->isExpandingLoad() && MLD->getExtensionType() == ISD::NON_EXTLOAD) {
  9759. SDValue NewLd = DAG.getLoad(
  9760. N->getValueType(0), SDLoc(N), MLD->getChain(), MLD->getBasePtr(),
  9761. MLD->getPointerInfo(), MLD->getOriginalAlign(),
  9762. MachineMemOperand::MOLoad, MLD->getAAInfo(), MLD->getRanges());
  9763. return CombineTo(N, NewLd, NewLd.getValue(1));
  9764. }
  9765. // Try transforming N to an indexed load.
  9766. if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
  9767. return SDValue(N, 0);
  9768. return SDValue();
  9769. }
  9770. /// A vector select of 2 constant vectors can be simplified to math/logic to
  9771. /// avoid a variable select instruction and possibly avoid constant loads.
  9772. SDValue DAGCombiner::foldVSelectOfConstants(SDNode *N) {
  9773. SDValue Cond = N->getOperand(0);
  9774. SDValue N1 = N->getOperand(1);
  9775. SDValue N2 = N->getOperand(2);
  9776. EVT VT = N->getValueType(0);
  9777. if (!Cond.hasOneUse() || Cond.getScalarValueSizeInBits() != 1 ||
  9778. !shouldConvertSelectOfConstantsToMath(Cond, VT, TLI) ||
  9779. !ISD::isBuildVectorOfConstantSDNodes(N1.getNode()) ||
  9780. !ISD::isBuildVectorOfConstantSDNodes(N2.getNode()))
  9781. return SDValue();
  9782. // Check if we can use the condition value to increment/decrement a single
  9783. // constant value. This simplifies a select to an add and removes a constant
  9784. // load/materialization from the general case.
  9785. bool AllAddOne = true;
  9786. bool AllSubOne = true;
  9787. unsigned Elts = VT.getVectorNumElements();
  9788. for (unsigned i = 0; i != Elts; ++i) {
  9789. SDValue N1Elt = N1.getOperand(i);
  9790. SDValue N2Elt = N2.getOperand(i);
  9791. if (N1Elt.isUndef() || N2Elt.isUndef())
  9792. continue;
  9793. if (N1Elt.getValueType() != N2Elt.getValueType())
  9794. continue;
  9795. const APInt &C1 = cast<ConstantSDNode>(N1Elt)->getAPIntValue();
  9796. const APInt &C2 = cast<ConstantSDNode>(N2Elt)->getAPIntValue();
  9797. if (C1 != C2 + 1)
  9798. AllAddOne = false;
  9799. if (C1 != C2 - 1)
  9800. AllSubOne = false;
  9801. }
  9802. // Further simplifications for the extra-special cases where the constants are
  9803. // all 0 or all -1 should be implemented as folds of these patterns.
  9804. SDLoc DL(N);
  9805. if (AllAddOne || AllSubOne) {
  9806. // vselect <N x i1> Cond, C+1, C --> add (zext Cond), C
  9807. // vselect <N x i1> Cond, C-1, C --> add (sext Cond), C
  9808. auto ExtendOpcode = AllAddOne ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
  9809. SDValue ExtendedCond = DAG.getNode(ExtendOpcode, DL, VT, Cond);
  9810. return DAG.getNode(ISD::ADD, DL, VT, ExtendedCond, N2);
  9811. }
  9812. // select Cond, Pow2C, 0 --> (zext Cond) << log2(Pow2C)
  9813. APInt Pow2C;
  9814. if (ISD::isConstantSplatVector(N1.getNode(), Pow2C) && Pow2C.isPowerOf2() &&
  9815. isNullOrNullSplat(N2)) {
  9816. SDValue ZextCond = DAG.getZExtOrTrunc(Cond, DL, VT);
  9817. SDValue ShAmtC = DAG.getConstant(Pow2C.exactLogBase2(), DL, VT);
  9818. return DAG.getNode(ISD::SHL, DL, VT, ZextCond, ShAmtC);
  9819. }
  9820. if (SDValue V = foldSelectOfConstantsUsingSra(N, DAG))
  9821. return V;
  9822. // The general case for select-of-constants:
  9823. // vselect <N x i1> Cond, C1, C2 --> xor (and (sext Cond), (C1^C2)), C2
  9824. // ...but that only makes sense if a vselect is slower than 2 logic ops, so
  9825. // leave that to a machine-specific pass.
  9826. return SDValue();
  9827. }
  9828. SDValue DAGCombiner::visitVSELECT(SDNode *N) {
  9829. SDValue N0 = N->getOperand(0);
  9830. SDValue N1 = N->getOperand(1);
  9831. SDValue N2 = N->getOperand(2);
  9832. EVT VT = N->getValueType(0);
  9833. SDLoc DL(N);
  9834. if (SDValue V = DAG.simplifySelect(N0, N1, N2))
  9835. return V;
  9836. if (SDValue V = foldBoolSelectToLogic(N, DAG))
  9837. return V;
  9838. // vselect (not Cond), N1, N2 -> vselect Cond, N2, N1
  9839. if (SDValue F = extractBooleanFlip(N0, DAG, TLI, false))
  9840. return DAG.getSelect(DL, VT, F, N2, N1);
  9841. // Canonicalize integer abs.
  9842. // vselect (setg[te] X, 0), X, -X ->
  9843. // vselect (setgt X, -1), X, -X ->
  9844. // vselect (setl[te] X, 0), -X, X ->
  9845. // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
  9846. if (N0.getOpcode() == ISD::SETCC) {
  9847. SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
  9848. ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
  9849. bool isAbs = false;
  9850. bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
  9851. if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
  9852. (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
  9853. N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
  9854. isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
  9855. else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
  9856. N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
  9857. isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
  9858. if (isAbs) {
  9859. if (TLI.isOperationLegalOrCustom(ISD::ABS, VT))
  9860. return DAG.getNode(ISD::ABS, DL, VT, LHS);
  9861. SDValue Shift = DAG.getNode(ISD::SRA, DL, VT, LHS,
  9862. DAG.getConstant(VT.getScalarSizeInBits() - 1,
  9863. DL, getShiftAmountTy(VT)));
  9864. SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
  9865. AddToWorklist(Shift.getNode());
  9866. AddToWorklist(Add.getNode());
  9867. return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
  9868. }
  9869. // vselect x, y (fcmp lt x, y) -> fminnum x, y
  9870. // vselect x, y (fcmp gt x, y) -> fmaxnum x, y
  9871. //
  9872. // This is OK if we don't care about what happens if either operand is a
  9873. // NaN.
  9874. //
  9875. if (N0.hasOneUse() && isLegalToCombineMinNumMaxNum(DAG, LHS, RHS, TLI)) {
  9876. if (SDValue FMinMax = combineMinNumMaxNum(DL, VT, LHS, RHS, N1, N2, CC))
  9877. return FMinMax;
  9878. }
  9879. if (SDValue S = PerformMinMaxFpToSatCombine(LHS, RHS, N1, N2, CC, DAG))
  9880. return S;
  9881. if (SDValue S = PerformUMinFpToSatCombine(LHS, RHS, N1, N2, CC, DAG))
  9882. return S;
  9883. // If this select has a condition (setcc) with narrower operands than the
  9884. // select, try to widen the compare to match the select width.
  9885. // TODO: This should be extended to handle any constant.
  9886. // TODO: This could be extended to handle non-loading patterns, but that
  9887. // requires thorough testing to avoid regressions.
  9888. if (isNullOrNullSplat(RHS)) {
  9889. EVT NarrowVT = LHS.getValueType();
  9890. EVT WideVT = N1.getValueType().changeVectorElementTypeToInteger();
  9891. EVT SetCCVT = getSetCCResultType(LHS.getValueType());
  9892. unsigned SetCCWidth = SetCCVT.getScalarSizeInBits();
  9893. unsigned WideWidth = WideVT.getScalarSizeInBits();
  9894. bool IsSigned = isSignedIntSetCC(CC);
  9895. auto LoadExtOpcode = IsSigned ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
  9896. if (LHS.getOpcode() == ISD::LOAD && LHS.hasOneUse() &&
  9897. SetCCWidth != 1 && SetCCWidth < WideWidth &&
  9898. TLI.isLoadExtLegalOrCustom(LoadExtOpcode, WideVT, NarrowVT) &&
  9899. TLI.isOperationLegalOrCustom(ISD::SETCC, WideVT)) {
  9900. // Both compare operands can be widened for free. The LHS can use an
  9901. // extended load, and the RHS is a constant:
  9902. // vselect (ext (setcc load(X), C)), N1, N2 -->
  9903. // vselect (setcc extload(X), C'), N1, N2
  9904. auto ExtOpcode = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
  9905. SDValue WideLHS = DAG.getNode(ExtOpcode, DL, WideVT, LHS);
  9906. SDValue WideRHS = DAG.getNode(ExtOpcode, DL, WideVT, RHS);
  9907. EVT WideSetCCVT = getSetCCResultType(WideVT);
  9908. SDValue WideSetCC = DAG.getSetCC(DL, WideSetCCVT, WideLHS, WideRHS, CC);
  9909. return DAG.getSelect(DL, N1.getValueType(), WideSetCC, N1, N2);
  9910. }
  9911. }
  9912. // Match VSELECTs into add with unsigned saturation.
  9913. if (hasOperation(ISD::UADDSAT, VT)) {
  9914. // Check if one of the arms of the VSELECT is vector with all bits set.
  9915. // If it's on the left side invert the predicate to simplify logic below.
  9916. SDValue Other;
  9917. ISD::CondCode SatCC = CC;
  9918. if (ISD::isConstantSplatVectorAllOnes(N1.getNode())) {
  9919. Other = N2;
  9920. SatCC = ISD::getSetCCInverse(SatCC, VT.getScalarType());
  9921. } else if (ISD::isConstantSplatVectorAllOnes(N2.getNode())) {
  9922. Other = N1;
  9923. }
  9924. if (Other && Other.getOpcode() == ISD::ADD) {
  9925. SDValue CondLHS = LHS, CondRHS = RHS;
  9926. SDValue OpLHS = Other.getOperand(0), OpRHS = Other.getOperand(1);
  9927. // Canonicalize condition operands.
  9928. if (SatCC == ISD::SETUGE) {
  9929. std::swap(CondLHS, CondRHS);
  9930. SatCC = ISD::SETULE;
  9931. }
  9932. // We can test against either of the addition operands.
  9933. // x <= x+y ? x+y : ~0 --> uaddsat x, y
  9934. // x+y >= x ? x+y : ~0 --> uaddsat x, y
  9935. if (SatCC == ISD::SETULE && Other == CondRHS &&
  9936. (OpLHS == CondLHS || OpRHS == CondLHS))
  9937. return DAG.getNode(ISD::UADDSAT, DL, VT, OpLHS, OpRHS);
  9938. if (OpRHS.getOpcode() == CondRHS.getOpcode() &&
  9939. (OpRHS.getOpcode() == ISD::BUILD_VECTOR ||
  9940. OpRHS.getOpcode() == ISD::SPLAT_VECTOR) &&
  9941. CondLHS == OpLHS) {
  9942. // If the RHS is a constant we have to reverse the const
  9943. // canonicalization.
  9944. // x >= ~C ? x+C : ~0 --> uaddsat x, C
  9945. auto MatchUADDSAT = [](ConstantSDNode *Op, ConstantSDNode *Cond) {
  9946. return Cond->getAPIntValue() == ~Op->getAPIntValue();
  9947. };
  9948. if (SatCC == ISD::SETULE &&
  9949. ISD::matchBinaryPredicate(OpRHS, CondRHS, MatchUADDSAT))
  9950. return DAG.getNode(ISD::UADDSAT, DL, VT, OpLHS, OpRHS);
  9951. }
  9952. }
  9953. }
  9954. // Match VSELECTs into sub with unsigned saturation.
  9955. if (hasOperation(ISD::USUBSAT, VT)) {
  9956. // Check if one of the arms of the VSELECT is a zero vector. If it's on
  9957. // the left side invert the predicate to simplify logic below.
  9958. SDValue Other;
  9959. ISD::CondCode SatCC = CC;
  9960. if (ISD::isConstantSplatVectorAllZeros(N1.getNode())) {
  9961. Other = N2;
  9962. SatCC = ISD::getSetCCInverse(SatCC, VT.getScalarType());
  9963. } else if (ISD::isConstantSplatVectorAllZeros(N2.getNode())) {
  9964. Other = N1;
  9965. }
  9966. // zext(x) >= y ? trunc(zext(x) - y) : 0
  9967. // --> usubsat(trunc(zext(x)),trunc(umin(y,SatLimit)))
  9968. // zext(x) > y ? trunc(zext(x) - y) : 0
  9969. // --> usubsat(trunc(zext(x)),trunc(umin(y,SatLimit)))
  9970. if (Other && Other.getOpcode() == ISD::TRUNCATE &&
  9971. Other.getOperand(0).getOpcode() == ISD::SUB &&
  9972. (SatCC == ISD::SETUGE || SatCC == ISD::SETUGT)) {
  9973. SDValue OpLHS = Other.getOperand(0).getOperand(0);
  9974. SDValue OpRHS = Other.getOperand(0).getOperand(1);
  9975. if (LHS == OpLHS && RHS == OpRHS && LHS.getOpcode() == ISD::ZERO_EXTEND)
  9976. if (SDValue R = getTruncatedUSUBSAT(VT, LHS.getValueType(), LHS, RHS,
  9977. DAG, DL))
  9978. return R;
  9979. }
  9980. if (Other && Other.getNumOperands() == 2) {
  9981. SDValue CondRHS = RHS;
  9982. SDValue OpLHS = Other.getOperand(0), OpRHS = Other.getOperand(1);
  9983. if (OpLHS == LHS) {
  9984. // Look for a general sub with unsigned saturation first.
  9985. // x >= y ? x-y : 0 --> usubsat x, y
  9986. // x > y ? x-y : 0 --> usubsat x, y
  9987. if ((SatCC == ISD::SETUGE || SatCC == ISD::SETUGT) &&
  9988. Other.getOpcode() == ISD::SUB && OpRHS == CondRHS)
  9989. return DAG.getNode(ISD::USUBSAT, DL, VT, OpLHS, OpRHS);
  9990. if (OpRHS.getOpcode() == ISD::BUILD_VECTOR ||
  9991. OpRHS.getOpcode() == ISD::SPLAT_VECTOR) {
  9992. if (CondRHS.getOpcode() == ISD::BUILD_VECTOR ||
  9993. CondRHS.getOpcode() == ISD::SPLAT_VECTOR) {
  9994. // If the RHS is a constant we have to reverse the const
  9995. // canonicalization.
  9996. // x > C-1 ? x+-C : 0 --> usubsat x, C
  9997. auto MatchUSUBSAT = [](ConstantSDNode *Op, ConstantSDNode *Cond) {
  9998. return (!Op && !Cond) ||
  9999. (Op && Cond &&
  10000. Cond->getAPIntValue() == (-Op->getAPIntValue() - 1));
  10001. };
  10002. if (SatCC == ISD::SETUGT && Other.getOpcode() == ISD::ADD &&
  10003. ISD::matchBinaryPredicate(OpRHS, CondRHS, MatchUSUBSAT,
  10004. /*AllowUndefs*/ true)) {
  10005. OpRHS = DAG.getNegative(OpRHS, DL, VT);
  10006. return DAG.getNode(ISD::USUBSAT, DL, VT, OpLHS, OpRHS);
  10007. }
  10008. // Another special case: If C was a sign bit, the sub has been
  10009. // canonicalized into a xor.
  10010. // FIXME: Would it be better to use computeKnownBits to
  10011. // determine whether it's safe to decanonicalize the xor?
  10012. // x s< 0 ? x^C : 0 --> usubsat x, C
  10013. APInt SplatValue;
  10014. if (SatCC == ISD::SETLT && Other.getOpcode() == ISD::XOR &&
  10015. ISD::isConstantSplatVector(OpRHS.getNode(), SplatValue) &&
  10016. ISD::isConstantSplatVectorAllZeros(CondRHS.getNode()) &&
  10017. SplatValue.isSignMask()) {
  10018. // Note that we have to rebuild the RHS constant here to
  10019. // ensure we don't rely on particular values of undef lanes.
  10020. OpRHS = DAG.getConstant(SplatValue, DL, VT);
  10021. return DAG.getNode(ISD::USUBSAT, DL, VT, OpLHS, OpRHS);
  10022. }
  10023. }
  10024. }
  10025. }
  10026. }
  10027. }
  10028. }
  10029. if (SimplifySelectOps(N, N1, N2))
  10030. return SDValue(N, 0); // Don't revisit N.
  10031. // Fold (vselect all_ones, N1, N2) -> N1
  10032. if (ISD::isConstantSplatVectorAllOnes(N0.getNode()))
  10033. return N1;
  10034. // Fold (vselect all_zeros, N1, N2) -> N2
  10035. if (ISD::isConstantSplatVectorAllZeros(N0.getNode()))
  10036. return N2;
  10037. // The ConvertSelectToConcatVector function is assuming both the above
  10038. // checks for (vselect (build_vector all{ones,zeros) ...) have been made
  10039. // and addressed.
  10040. if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
  10041. N2.getOpcode() == ISD::CONCAT_VECTORS &&
  10042. ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
  10043. if (SDValue CV = ConvertSelectToConcatVector(N, DAG))
  10044. return CV;
  10045. }
  10046. if (SDValue V = foldVSelectOfConstants(N))
  10047. return V;
  10048. if (hasOperation(ISD::SRA, VT))
  10049. if (SDValue V = foldVSelectToSignBitSplatMask(N, DAG))
  10050. return V;
  10051. if (SimplifyDemandedVectorElts(SDValue(N, 0)))
  10052. return SDValue(N, 0);
  10053. return SDValue();
  10054. }
  10055. SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
  10056. SDValue N0 = N->getOperand(0);
  10057. SDValue N1 = N->getOperand(1);
  10058. SDValue N2 = N->getOperand(2);
  10059. SDValue N3 = N->getOperand(3);
  10060. SDValue N4 = N->getOperand(4);
  10061. ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
  10062. // fold select_cc lhs, rhs, x, x, cc -> x
  10063. if (N2 == N3)
  10064. return N2;
  10065. // select_cc bool, 0, x, y, seteq -> select bool, y, x
  10066. if (CC == ISD::SETEQ && !LegalTypes && N0.getValueType() == MVT::i1 &&
  10067. isNullConstant(N1))
  10068. return DAG.getSelect(SDLoc(N), N2.getValueType(), N0, N3, N2);
  10069. // Determine if the condition we're dealing with is constant
  10070. if (SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()), N0, N1,
  10071. CC, SDLoc(N), false)) {
  10072. AddToWorklist(SCC.getNode());
  10073. // cond always true -> true val
  10074. // cond always false -> false val
  10075. if (auto *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode()))
  10076. return SCCC->isZero() ? N3 : N2;
  10077. // When the condition is UNDEF, just return the first operand. This is
  10078. // coherent the DAG creation, no setcc node is created in this case
  10079. if (SCC->isUndef())
  10080. return N2;
  10081. // Fold to a simpler select_cc
  10082. if (SCC.getOpcode() == ISD::SETCC) {
  10083. SDValue SelectOp = DAG.getNode(
  10084. ISD::SELECT_CC, SDLoc(N), N2.getValueType(), SCC.getOperand(0),
  10085. SCC.getOperand(1), N2, N3, SCC.getOperand(2));
  10086. SelectOp->setFlags(SCC->getFlags());
  10087. return SelectOp;
  10088. }
  10089. }
  10090. // If we can fold this based on the true/false value, do so.
  10091. if (SimplifySelectOps(N, N2, N3))
  10092. return SDValue(N, 0); // Don't revisit N.
  10093. // fold select_cc into other things, such as min/max/abs
  10094. return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
  10095. }
  10096. SDValue DAGCombiner::visitSETCC(SDNode *N) {
  10097. // setcc is very commonly used as an argument to brcond. This pattern
  10098. // also lend itself to numerous combines and, as a result, it is desired
  10099. // we keep the argument to a brcond as a setcc as much as possible.
  10100. bool PreferSetCC =
  10101. N->hasOneUse() && N->use_begin()->getOpcode() == ISD::BRCOND;
  10102. ISD::CondCode Cond = cast<CondCodeSDNode>(N->getOperand(2))->get();
  10103. EVT VT = N->getValueType(0);
  10104. // SETCC(FREEZE(X), CONST, Cond)
  10105. // =>
  10106. // FREEZE(SETCC(X, CONST, Cond))
  10107. // This is correct if FREEZE(X) has one use and SETCC(FREEZE(X), CONST, Cond)
  10108. // isn't equivalent to true or false.
  10109. // For example, SETCC(FREEZE(X), -128, SETULT) cannot be folded to
  10110. // FREEZE(SETCC(X, -128, SETULT)) because X can be poison.
  10111. //
  10112. // This transformation is beneficial because visitBRCOND can fold
  10113. // BRCOND(FREEZE(X)) to BRCOND(X).
  10114. // Conservatively optimize integer comparisons only.
  10115. if (PreferSetCC) {
  10116. // Do this only when SETCC is going to be used by BRCOND.
  10117. SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
  10118. ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
  10119. ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
  10120. bool Updated = false;
  10121. // Is 'X Cond C' always true or false?
  10122. auto IsAlwaysTrueOrFalse = [](ISD::CondCode Cond, ConstantSDNode *C) {
  10123. bool False = (Cond == ISD::SETULT && C->isZero()) ||
  10124. (Cond == ISD::SETLT && C->isMinSignedValue()) ||
  10125. (Cond == ISD::SETUGT && C->isAllOnes()) ||
  10126. (Cond == ISD::SETGT && C->isMaxSignedValue());
  10127. bool True = (Cond == ISD::SETULE && C->isAllOnes()) ||
  10128. (Cond == ISD::SETLE && C->isMaxSignedValue()) ||
  10129. (Cond == ISD::SETUGE && C->isZero()) ||
  10130. (Cond == ISD::SETGE && C->isMinSignedValue());
  10131. return True || False;
  10132. };
  10133. if (N0->getOpcode() == ISD::FREEZE && N0.hasOneUse() && N1C) {
  10134. if (!IsAlwaysTrueOrFalse(Cond, N1C)) {
  10135. N0 = N0->getOperand(0);
  10136. Updated = true;
  10137. }
  10138. }
  10139. if (N1->getOpcode() == ISD::FREEZE && N1.hasOneUse() && N0C) {
  10140. if (!IsAlwaysTrueOrFalse(ISD::getSetCCSwappedOperands(Cond),
  10141. N0C)) {
  10142. N1 = N1->getOperand(0);
  10143. Updated = true;
  10144. }
  10145. }
  10146. if (Updated)
  10147. return DAG.getFreeze(DAG.getSetCC(SDLoc(N), VT, N0, N1, Cond));
  10148. }
  10149. SDValue Combined = SimplifySetCC(VT, N->getOperand(0), N->getOperand(1), Cond,
  10150. SDLoc(N), !PreferSetCC);
  10151. if (!Combined)
  10152. return SDValue();
  10153. // If we prefer to have a setcc, and we don't, we'll try our best to
  10154. // recreate one using rebuildSetCC.
  10155. if (PreferSetCC && Combined.getOpcode() != ISD::SETCC) {
  10156. SDValue NewSetCC = rebuildSetCC(Combined);
  10157. // We don't have anything interesting to combine to.
  10158. if (NewSetCC.getNode() == N)
  10159. return SDValue();
  10160. if (NewSetCC)
  10161. return NewSetCC;
  10162. }
  10163. return Combined;
  10164. }
  10165. SDValue DAGCombiner::visitSETCCCARRY(SDNode *N) {
  10166. SDValue LHS = N->getOperand(0);
  10167. SDValue RHS = N->getOperand(1);
  10168. SDValue Carry = N->getOperand(2);
  10169. SDValue Cond = N->getOperand(3);
  10170. // If Carry is false, fold to a regular SETCC.
  10171. if (isNullConstant(Carry))
  10172. return DAG.getNode(ISD::SETCC, SDLoc(N), N->getVTList(), LHS, RHS, Cond);
  10173. return SDValue();
  10174. }
  10175. /// Check if N satisfies:
  10176. /// N is used once.
  10177. /// N is a Load.
  10178. /// The load is compatible with ExtOpcode. It means
  10179. /// If load has explicit zero/sign extension, ExpOpcode must have the same
  10180. /// extension.
  10181. /// Otherwise returns true.
  10182. static bool isCompatibleLoad(SDValue N, unsigned ExtOpcode) {
  10183. if (!N.hasOneUse())
  10184. return false;
  10185. if (!isa<LoadSDNode>(N))
  10186. return false;
  10187. LoadSDNode *Load = cast<LoadSDNode>(N);
  10188. ISD::LoadExtType LoadExt = Load->getExtensionType();
  10189. if (LoadExt == ISD::NON_EXTLOAD || LoadExt == ISD::EXTLOAD)
  10190. return true;
  10191. // Now LoadExt is either SEXTLOAD or ZEXTLOAD, ExtOpcode must have the same
  10192. // extension.
  10193. if ((LoadExt == ISD::SEXTLOAD && ExtOpcode != ISD::SIGN_EXTEND) ||
  10194. (LoadExt == ISD::ZEXTLOAD && ExtOpcode != ISD::ZERO_EXTEND))
  10195. return false;
  10196. return true;
  10197. }
  10198. /// Fold
  10199. /// (sext (select c, load x, load y)) -> (select c, sextload x, sextload y)
  10200. /// (zext (select c, load x, load y)) -> (select c, zextload x, zextload y)
  10201. /// (aext (select c, load x, load y)) -> (select c, extload x, extload y)
  10202. /// This function is called by the DAGCombiner when visiting sext/zext/aext
  10203. /// dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
  10204. static SDValue tryToFoldExtendSelectLoad(SDNode *N, const TargetLowering &TLI,
  10205. SelectionDAG &DAG) {
  10206. unsigned Opcode = N->getOpcode();
  10207. SDValue N0 = N->getOperand(0);
  10208. EVT VT = N->getValueType(0);
  10209. SDLoc DL(N);
  10210. assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
  10211. Opcode == ISD::ANY_EXTEND) &&
  10212. "Expected EXTEND dag node in input!");
  10213. if (!(N0->getOpcode() == ISD::SELECT || N0->getOpcode() == ISD::VSELECT) ||
  10214. !N0.hasOneUse())
  10215. return SDValue();
  10216. SDValue Op1 = N0->getOperand(1);
  10217. SDValue Op2 = N0->getOperand(2);
  10218. if (!isCompatibleLoad(Op1, Opcode) || !isCompatibleLoad(Op2, Opcode))
  10219. return SDValue();
  10220. auto ExtLoadOpcode = ISD::EXTLOAD;
  10221. if (Opcode == ISD::SIGN_EXTEND)
  10222. ExtLoadOpcode = ISD::SEXTLOAD;
  10223. else if (Opcode == ISD::ZERO_EXTEND)
  10224. ExtLoadOpcode = ISD::ZEXTLOAD;
  10225. LoadSDNode *Load1 = cast<LoadSDNode>(Op1);
  10226. LoadSDNode *Load2 = cast<LoadSDNode>(Op2);
  10227. if (!TLI.isLoadExtLegal(ExtLoadOpcode, VT, Load1->getMemoryVT()) ||
  10228. !TLI.isLoadExtLegal(ExtLoadOpcode, VT, Load2->getMemoryVT()))
  10229. return SDValue();
  10230. SDValue Ext1 = DAG.getNode(Opcode, DL, VT, Op1);
  10231. SDValue Ext2 = DAG.getNode(Opcode, DL, VT, Op2);
  10232. return DAG.getSelect(DL, VT, N0->getOperand(0), Ext1, Ext2);
  10233. }
  10234. /// Try to fold a sext/zext/aext dag node into a ConstantSDNode or
  10235. /// a build_vector of constants.
  10236. /// This function is called by the DAGCombiner when visiting sext/zext/aext
  10237. /// dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
  10238. /// Vector extends are not folded if operations are legal; this is to
  10239. /// avoid introducing illegal build_vector dag nodes.
  10240. static SDValue tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
  10241. SelectionDAG &DAG, bool LegalTypes) {
  10242. unsigned Opcode = N->getOpcode();
  10243. SDValue N0 = N->getOperand(0);
  10244. EVT VT = N->getValueType(0);
  10245. SDLoc DL(N);
  10246. assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
  10247. Opcode == ISD::ANY_EXTEND ||
  10248. Opcode == ISD::SIGN_EXTEND_VECTOR_INREG ||
  10249. Opcode == ISD::ZERO_EXTEND_VECTOR_INREG ||
  10250. Opcode == ISD::ANY_EXTEND_VECTOR_INREG) &&
  10251. "Expected EXTEND dag node in input!");
  10252. // fold (sext c1) -> c1
  10253. // fold (zext c1) -> c1
  10254. // fold (aext c1) -> c1
  10255. if (isa<ConstantSDNode>(N0))
  10256. return DAG.getNode(Opcode, DL, VT, N0);
  10257. // fold (sext (select cond, c1, c2)) -> (select cond, sext c1, sext c2)
  10258. // fold (zext (select cond, c1, c2)) -> (select cond, zext c1, zext c2)
  10259. // fold (aext (select cond, c1, c2)) -> (select cond, sext c1, sext c2)
  10260. if (N0->getOpcode() == ISD::SELECT) {
  10261. SDValue Op1 = N0->getOperand(1);
  10262. SDValue Op2 = N0->getOperand(2);
  10263. if (isa<ConstantSDNode>(Op1) && isa<ConstantSDNode>(Op2) &&
  10264. (Opcode != ISD::ZERO_EXTEND || !TLI.isZExtFree(N0.getValueType(), VT))) {
  10265. // For any_extend, choose sign extension of the constants to allow a
  10266. // possible further transform to sign_extend_inreg.i.e.
  10267. //
  10268. // t1: i8 = select t0, Constant:i8<-1>, Constant:i8<0>
  10269. // t2: i64 = any_extend t1
  10270. // -->
  10271. // t3: i64 = select t0, Constant:i64<-1>, Constant:i64<0>
  10272. // -->
  10273. // t4: i64 = sign_extend_inreg t3
  10274. unsigned FoldOpc = Opcode;
  10275. if (FoldOpc == ISD::ANY_EXTEND)
  10276. FoldOpc = ISD::SIGN_EXTEND;
  10277. return DAG.getSelect(DL, VT, N0->getOperand(0),
  10278. DAG.getNode(FoldOpc, DL, VT, Op1),
  10279. DAG.getNode(FoldOpc, DL, VT, Op2));
  10280. }
  10281. }
  10282. // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
  10283. // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
  10284. // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
  10285. EVT SVT = VT.getScalarType();
  10286. if (!(VT.isVector() && (!LegalTypes || TLI.isTypeLegal(SVT)) &&
  10287. ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
  10288. return SDValue();
  10289. // We can fold this node into a build_vector.
  10290. unsigned VTBits = SVT.getSizeInBits();
  10291. unsigned EVTBits = N0->getValueType(0).getScalarSizeInBits();
  10292. SmallVector<SDValue, 8> Elts;
  10293. unsigned NumElts = VT.getVectorNumElements();
  10294. for (unsigned i = 0; i != NumElts; ++i) {
  10295. SDValue Op = N0.getOperand(i);
  10296. if (Op.isUndef()) {
  10297. if (Opcode == ISD::ANY_EXTEND || Opcode == ISD::ANY_EXTEND_VECTOR_INREG)
  10298. Elts.push_back(DAG.getUNDEF(SVT));
  10299. else
  10300. Elts.push_back(DAG.getConstant(0, DL, SVT));
  10301. continue;
  10302. }
  10303. SDLoc DL(Op);
  10304. // Get the constant value and if needed trunc it to the size of the type.
  10305. // Nodes like build_vector might have constants wider than the scalar type.
  10306. APInt C = cast<ConstantSDNode>(Op)->getAPIntValue().zextOrTrunc(EVTBits);
  10307. if (Opcode == ISD::SIGN_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG)
  10308. Elts.push_back(DAG.getConstant(C.sext(VTBits), DL, SVT));
  10309. else
  10310. Elts.push_back(DAG.getConstant(C.zext(VTBits), DL, SVT));
  10311. }
  10312. return DAG.getBuildVector(VT, DL, Elts);
  10313. }
  10314. // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
  10315. // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
  10316. // transformation. Returns true if extension are possible and the above
  10317. // mentioned transformation is profitable.
  10318. static bool ExtendUsesToFormExtLoad(EVT VT, SDNode *N, SDValue N0,
  10319. unsigned ExtOpc,
  10320. SmallVectorImpl<SDNode *> &ExtendNodes,
  10321. const TargetLowering &TLI) {
  10322. bool HasCopyToRegUses = false;
  10323. bool isTruncFree = TLI.isTruncateFree(VT, N0.getValueType());
  10324. for (SDNode::use_iterator UI = N0->use_begin(), UE = N0->use_end(); UI != UE;
  10325. ++UI) {
  10326. SDNode *User = *UI;
  10327. if (User == N)
  10328. continue;
  10329. if (UI.getUse().getResNo() != N0.getResNo())
  10330. continue;
  10331. // FIXME: Only extend SETCC N, N and SETCC N, c for now.
  10332. if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
  10333. ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
  10334. if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
  10335. // Sign bits will be lost after a zext.
  10336. return false;
  10337. bool Add = false;
  10338. for (unsigned i = 0; i != 2; ++i) {
  10339. SDValue UseOp = User->getOperand(i);
  10340. if (UseOp == N0)
  10341. continue;
  10342. if (!isa<ConstantSDNode>(UseOp))
  10343. return false;
  10344. Add = true;
  10345. }
  10346. if (Add)
  10347. ExtendNodes.push_back(User);
  10348. continue;
  10349. }
  10350. // If truncates aren't free and there are users we can't
  10351. // extend, it isn't worthwhile.
  10352. if (!isTruncFree)
  10353. return false;
  10354. // Remember if this value is live-out.
  10355. if (User->getOpcode() == ISD::CopyToReg)
  10356. HasCopyToRegUses = true;
  10357. }
  10358. if (HasCopyToRegUses) {
  10359. bool BothLiveOut = false;
  10360. for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
  10361. UI != UE; ++UI) {
  10362. SDUse &Use = UI.getUse();
  10363. if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
  10364. BothLiveOut = true;
  10365. break;
  10366. }
  10367. }
  10368. if (BothLiveOut)
  10369. // Both unextended and extended values are live out. There had better be
  10370. // a good reason for the transformation.
  10371. return ExtendNodes.size();
  10372. }
  10373. return true;
  10374. }
  10375. void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
  10376. SDValue OrigLoad, SDValue ExtLoad,
  10377. ISD::NodeType ExtType) {
  10378. // Extend SetCC uses if necessary.
  10379. SDLoc DL(ExtLoad);
  10380. for (SDNode *SetCC : SetCCs) {
  10381. SmallVector<SDValue, 4> Ops;
  10382. for (unsigned j = 0; j != 2; ++j) {
  10383. SDValue SOp = SetCC->getOperand(j);
  10384. if (SOp == OrigLoad)
  10385. Ops.push_back(ExtLoad);
  10386. else
  10387. Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
  10388. }
  10389. Ops.push_back(SetCC->getOperand(2));
  10390. CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
  10391. }
  10392. }
  10393. // FIXME: Bring more similar combines here, common to sext/zext (maybe aext?).
  10394. SDValue DAGCombiner::CombineExtLoad(SDNode *N) {
  10395. SDValue N0 = N->getOperand(0);
  10396. EVT DstVT = N->getValueType(0);
  10397. EVT SrcVT = N0.getValueType();
  10398. assert((N->getOpcode() == ISD::SIGN_EXTEND ||
  10399. N->getOpcode() == ISD::ZERO_EXTEND) &&
  10400. "Unexpected node type (not an extend)!");
  10401. // fold (sext (load x)) to multiple smaller sextloads; same for zext.
  10402. // For example, on a target with legal v4i32, but illegal v8i32, turn:
  10403. // (v8i32 (sext (v8i16 (load x))))
  10404. // into:
  10405. // (v8i32 (concat_vectors (v4i32 (sextload x)),
  10406. // (v4i32 (sextload (x + 16)))))
  10407. // Where uses of the original load, i.e.:
  10408. // (v8i16 (load x))
  10409. // are replaced with:
  10410. // (v8i16 (truncate
  10411. // (v8i32 (concat_vectors (v4i32 (sextload x)),
  10412. // (v4i32 (sextload (x + 16)))))))
  10413. //
  10414. // This combine is only applicable to illegal, but splittable, vectors.
  10415. // All legal types, and illegal non-vector types, are handled elsewhere.
  10416. // This combine is controlled by TargetLowering::isVectorLoadExtDesirable.
  10417. //
  10418. if (N0->getOpcode() != ISD::LOAD)
  10419. return SDValue();
  10420. LoadSDNode *LN0 = cast<LoadSDNode>(N0);
  10421. if (!ISD::isNON_EXTLoad(LN0) || !ISD::isUNINDEXEDLoad(LN0) ||
  10422. !N0.hasOneUse() || !LN0->isSimple() ||
  10423. !DstVT.isVector() || !DstVT.isPow2VectorType() ||
  10424. !TLI.isVectorLoadExtDesirable(SDValue(N, 0)))
  10425. return SDValue();
  10426. SmallVector<SDNode *, 4> SetCCs;
  10427. if (!ExtendUsesToFormExtLoad(DstVT, N, N0, N->getOpcode(), SetCCs, TLI))
  10428. return SDValue();
  10429. ISD::LoadExtType ExtType =
  10430. N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
  10431. // Try to split the vector types to get down to legal types.
  10432. EVT SplitSrcVT = SrcVT;
  10433. EVT SplitDstVT = DstVT;
  10434. while (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT) &&
  10435. SplitSrcVT.getVectorNumElements() > 1) {
  10436. SplitDstVT = DAG.GetSplitDestVTs(SplitDstVT).first;
  10437. SplitSrcVT = DAG.GetSplitDestVTs(SplitSrcVT).first;
  10438. }
  10439. if (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT))
  10440. return SDValue();
  10441. assert(!DstVT.isScalableVector() && "Unexpected scalable vector type");
  10442. SDLoc DL(N);
  10443. const unsigned NumSplits =
  10444. DstVT.getVectorNumElements() / SplitDstVT.getVectorNumElements();
  10445. const unsigned Stride = SplitSrcVT.getStoreSize();
  10446. SmallVector<SDValue, 4> Loads;
  10447. SmallVector<SDValue, 4> Chains;
  10448. SDValue BasePtr = LN0->getBasePtr();
  10449. for (unsigned Idx = 0; Idx < NumSplits; Idx++) {
  10450. const unsigned Offset = Idx * Stride;
  10451. const Align Align = commonAlignment(LN0->getAlign(), Offset);
  10452. SDValue SplitLoad = DAG.getExtLoad(
  10453. ExtType, SDLoc(LN0), SplitDstVT, LN0->getChain(), BasePtr,
  10454. LN0->getPointerInfo().getWithOffset(Offset), SplitSrcVT, Align,
  10455. LN0->getMemOperand()->getFlags(), LN0->getAAInfo());
  10456. BasePtr = DAG.getMemBasePlusOffset(BasePtr, TypeSize::Fixed(Stride), DL);
  10457. Loads.push_back(SplitLoad.getValue(0));
  10458. Chains.push_back(SplitLoad.getValue(1));
  10459. }
  10460. SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
  10461. SDValue NewValue = DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, Loads);
  10462. // Simplify TF.
  10463. AddToWorklist(NewChain.getNode());
  10464. CombineTo(N, NewValue);
  10465. // Replace uses of the original load (before extension)
  10466. // with a truncate of the concatenated sextloaded vectors.
  10467. SDValue Trunc =
  10468. DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), NewValue);
  10469. ExtendSetCCUses(SetCCs, N0, NewValue, (ISD::NodeType)N->getOpcode());
  10470. CombineTo(N0.getNode(), Trunc, NewChain);
  10471. return SDValue(N, 0); // Return N so it doesn't get rechecked!
  10472. }
  10473. // fold (zext (and/or/xor (shl/shr (load x), cst), cst)) ->
  10474. // (and/or/xor (shl/shr (zextload x), (zext cst)), (zext cst))
  10475. SDValue DAGCombiner::CombineZExtLogicopShiftLoad(SDNode *N) {
  10476. assert(N->getOpcode() == ISD::ZERO_EXTEND);
  10477. EVT VT = N->getValueType(0);
  10478. EVT OrigVT = N->getOperand(0).getValueType();
  10479. if (TLI.isZExtFree(OrigVT, VT))
  10480. return SDValue();
  10481. // and/or/xor
  10482. SDValue N0 = N->getOperand(0);
  10483. if (!(N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
  10484. N0.getOpcode() == ISD::XOR) ||
  10485. N0.getOperand(1).getOpcode() != ISD::Constant ||
  10486. (LegalOperations && !TLI.isOperationLegal(N0.getOpcode(), VT)))
  10487. return SDValue();
  10488. // shl/shr
  10489. SDValue N1 = N0->getOperand(0);
  10490. if (!(N1.getOpcode() == ISD::SHL || N1.getOpcode() == ISD::SRL) ||
  10491. N1.getOperand(1).getOpcode() != ISD::Constant ||
  10492. (LegalOperations && !TLI.isOperationLegal(N1.getOpcode(), VT)))
  10493. return SDValue();
  10494. // load
  10495. if (!isa<LoadSDNode>(N1.getOperand(0)))
  10496. return SDValue();
  10497. LoadSDNode *Load = cast<LoadSDNode>(N1.getOperand(0));
  10498. EVT MemVT = Load->getMemoryVT();
  10499. if (!TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT) ||
  10500. Load->getExtensionType() == ISD::SEXTLOAD || Load->isIndexed())
  10501. return SDValue();
  10502. // If the shift op is SHL, the logic op must be AND, otherwise the result
  10503. // will be wrong.
  10504. if (N1.getOpcode() == ISD::SHL && N0.getOpcode() != ISD::AND)
  10505. return SDValue();
  10506. if (!N0.hasOneUse() || !N1.hasOneUse())
  10507. return SDValue();
  10508. SmallVector<SDNode*, 4> SetCCs;
  10509. if (!ExtendUsesToFormExtLoad(VT, N1.getNode(), N1.getOperand(0),
  10510. ISD::ZERO_EXTEND, SetCCs, TLI))
  10511. return SDValue();
  10512. // Actually do the transformation.
  10513. SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(Load), VT,
  10514. Load->getChain(), Load->getBasePtr(),
  10515. Load->getMemoryVT(), Load->getMemOperand());
  10516. SDLoc DL1(N1);
  10517. SDValue Shift = DAG.getNode(N1.getOpcode(), DL1, VT, ExtLoad,
  10518. N1.getOperand(1));
  10519. APInt Mask = N0.getConstantOperandAPInt(1).zext(VT.getSizeInBits());
  10520. SDLoc DL0(N0);
  10521. SDValue And = DAG.getNode(N0.getOpcode(), DL0, VT, Shift,
  10522. DAG.getConstant(Mask, DL0, VT));
  10523. ExtendSetCCUses(SetCCs, N1.getOperand(0), ExtLoad, ISD::ZERO_EXTEND);
  10524. CombineTo(N, And);
  10525. if (SDValue(Load, 0).hasOneUse()) {
  10526. DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), ExtLoad.getValue(1));
  10527. } else {
  10528. SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(Load),
  10529. Load->getValueType(0), ExtLoad);
  10530. CombineTo(Load, Trunc, ExtLoad.getValue(1));
  10531. }
  10532. // N0 is dead at this point.
  10533. recursivelyDeleteUnusedNodes(N0.getNode());
  10534. return SDValue(N,0); // Return N so it doesn't get rechecked!
  10535. }
  10536. /// If we're narrowing or widening the result of a vector select and the final
  10537. /// size is the same size as a setcc (compare) feeding the select, then try to
  10538. /// apply the cast operation to the select's operands because matching vector
  10539. /// sizes for a select condition and other operands should be more efficient.
  10540. SDValue DAGCombiner::matchVSelectOpSizesWithSetCC(SDNode *Cast) {
  10541. unsigned CastOpcode = Cast->getOpcode();
  10542. assert((CastOpcode == ISD::SIGN_EXTEND || CastOpcode == ISD::ZERO_EXTEND ||
  10543. CastOpcode == ISD::TRUNCATE || CastOpcode == ISD::FP_EXTEND ||
  10544. CastOpcode == ISD::FP_ROUND) &&
  10545. "Unexpected opcode for vector select narrowing/widening");
  10546. // We only do this transform before legal ops because the pattern may be
  10547. // obfuscated by target-specific operations after legalization. Do not create
  10548. // an illegal select op, however, because that may be difficult to lower.
  10549. EVT VT = Cast->getValueType(0);
  10550. if (LegalOperations || !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
  10551. return SDValue();
  10552. SDValue VSel = Cast->getOperand(0);
  10553. if (VSel.getOpcode() != ISD::VSELECT || !VSel.hasOneUse() ||
  10554. VSel.getOperand(0).getOpcode() != ISD::SETCC)
  10555. return SDValue();
  10556. // Does the setcc have the same vector size as the casted select?
  10557. SDValue SetCC = VSel.getOperand(0);
  10558. EVT SetCCVT = getSetCCResultType(SetCC.getOperand(0).getValueType());
  10559. if (SetCCVT.getSizeInBits() != VT.getSizeInBits())
  10560. return SDValue();
  10561. // cast (vsel (setcc X), A, B) --> vsel (setcc X), (cast A), (cast B)
  10562. SDValue A = VSel.getOperand(1);
  10563. SDValue B = VSel.getOperand(2);
  10564. SDValue CastA, CastB;
  10565. SDLoc DL(Cast);
  10566. if (CastOpcode == ISD::FP_ROUND) {
  10567. // FP_ROUND (fptrunc) has an extra flag operand to pass along.
  10568. CastA = DAG.getNode(CastOpcode, DL, VT, A, Cast->getOperand(1));
  10569. CastB = DAG.getNode(CastOpcode, DL, VT, B, Cast->getOperand(1));
  10570. } else {
  10571. CastA = DAG.getNode(CastOpcode, DL, VT, A);
  10572. CastB = DAG.getNode(CastOpcode, DL, VT, B);
  10573. }
  10574. return DAG.getNode(ISD::VSELECT, DL, VT, SetCC, CastA, CastB);
  10575. }
  10576. // fold ([s|z]ext ([s|z]extload x)) -> ([s|z]ext (truncate ([s|z]extload x)))
  10577. // fold ([s|z]ext ( extload x)) -> ([s|z]ext (truncate ([s|z]extload x)))
  10578. static SDValue tryToFoldExtOfExtload(SelectionDAG &DAG, DAGCombiner &Combiner,
  10579. const TargetLowering &TLI, EVT VT,
  10580. bool LegalOperations, SDNode *N,
  10581. SDValue N0, ISD::LoadExtType ExtLoadType) {
  10582. SDNode *N0Node = N0.getNode();
  10583. bool isAExtLoad = (ExtLoadType == ISD::SEXTLOAD) ? ISD::isSEXTLoad(N0Node)
  10584. : ISD::isZEXTLoad(N0Node);
  10585. if ((!isAExtLoad && !ISD::isEXTLoad(N0Node)) ||
  10586. !ISD::isUNINDEXEDLoad(N0Node) || !N0.hasOneUse())
  10587. return SDValue();
  10588. LoadSDNode *LN0 = cast<LoadSDNode>(N0);
  10589. EVT MemVT = LN0->getMemoryVT();
  10590. if ((LegalOperations || !LN0->isSimple() ||
  10591. VT.isVector()) &&
  10592. !TLI.isLoadExtLegal(ExtLoadType, VT, MemVT))
  10593. return SDValue();
  10594. SDValue ExtLoad =
  10595. DAG.getExtLoad(ExtLoadType, SDLoc(LN0), VT, LN0->getChain(),
  10596. LN0->getBasePtr(), MemVT, LN0->getMemOperand());
  10597. Combiner.CombineTo(N, ExtLoad);
  10598. DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), ExtLoad.getValue(1));
  10599. if (LN0->use_empty())
  10600. Combiner.recursivelyDeleteUnusedNodes(LN0);
  10601. return SDValue(N, 0); // Return N so it doesn't get rechecked!
  10602. }
  10603. // fold ([s|z]ext (load x)) -> ([s|z]ext (truncate ([s|z]extload x)))
  10604. // Only generate vector extloads when 1) they're legal, and 2) they are
  10605. // deemed desirable by the target.
  10606. static SDValue tryToFoldExtOfLoad(SelectionDAG &DAG, DAGCombiner &Combiner,
  10607. const TargetLowering &TLI, EVT VT,
  10608. bool LegalOperations, SDNode *N, SDValue N0,
  10609. ISD::LoadExtType ExtLoadType,
  10610. ISD::NodeType ExtOpc) {
  10611. // TODO: isFixedLengthVector() should be removed and any negative effects on
  10612. // code generation being the result of that target's implementation of
  10613. // isVectorLoadExtDesirable().
  10614. if (!ISD::isNON_EXTLoad(N0.getNode()) ||
  10615. !ISD::isUNINDEXEDLoad(N0.getNode()) ||
  10616. ((LegalOperations || VT.isFixedLengthVector() ||
  10617. !cast<LoadSDNode>(N0)->isSimple()) &&
  10618. !TLI.isLoadExtLegal(ExtLoadType, VT, N0.getValueType())))
  10619. return {};
  10620. bool DoXform = true;
  10621. SmallVector<SDNode *, 4> SetCCs;
  10622. if (!N0.hasOneUse())
  10623. DoXform = ExtendUsesToFormExtLoad(VT, N, N0, ExtOpc, SetCCs, TLI);
  10624. if (VT.isVector())
  10625. DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
  10626. if (!DoXform)
  10627. return {};
  10628. LoadSDNode *LN0 = cast<LoadSDNode>(N0);
  10629. SDValue ExtLoad = DAG.getExtLoad(ExtLoadType, SDLoc(LN0), VT, LN0->getChain(),
  10630. LN0->getBasePtr(), N0.getValueType(),
  10631. LN0->getMemOperand());
  10632. Combiner.ExtendSetCCUses(SetCCs, N0, ExtLoad, ExtOpc);
  10633. // If the load value is used only by N, replace it via CombineTo N.
  10634. bool NoReplaceTrunc = SDValue(LN0, 0).hasOneUse();
  10635. Combiner.CombineTo(N, ExtLoad);
  10636. if (NoReplaceTrunc) {
  10637. DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), ExtLoad.getValue(1));
  10638. Combiner.recursivelyDeleteUnusedNodes(LN0);
  10639. } else {
  10640. SDValue Trunc =
  10641. DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), ExtLoad);
  10642. Combiner.CombineTo(LN0, Trunc, ExtLoad.getValue(1));
  10643. }
  10644. return SDValue(N, 0); // Return N so it doesn't get rechecked!
  10645. }
  10646. static SDValue tryToFoldExtOfMaskedLoad(SelectionDAG &DAG,
  10647. const TargetLowering &TLI, EVT VT,
  10648. SDNode *N, SDValue N0,
  10649. ISD::LoadExtType ExtLoadType,
  10650. ISD::NodeType ExtOpc) {
  10651. if (!N0.hasOneUse())
  10652. return SDValue();
  10653. MaskedLoadSDNode *Ld = dyn_cast<MaskedLoadSDNode>(N0);
  10654. if (!Ld || Ld->getExtensionType() != ISD::NON_EXTLOAD)
  10655. return SDValue();
  10656. if (!TLI.isLoadExtLegalOrCustom(ExtLoadType, VT, Ld->getValueType(0)))
  10657. return SDValue();
  10658. if (!TLI.isVectorLoadExtDesirable(SDValue(N, 0)))
  10659. return SDValue();
  10660. SDLoc dl(Ld);
  10661. SDValue PassThru = DAG.getNode(ExtOpc, dl, VT, Ld->getPassThru());
  10662. SDValue NewLoad = DAG.getMaskedLoad(
  10663. VT, dl, Ld->getChain(), Ld->getBasePtr(), Ld->getOffset(), Ld->getMask(),
  10664. PassThru, Ld->getMemoryVT(), Ld->getMemOperand(), Ld->getAddressingMode(),
  10665. ExtLoadType, Ld->isExpandingLoad());
  10666. DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), SDValue(NewLoad.getNode(), 1));
  10667. return NewLoad;
  10668. }
  10669. static SDValue foldExtendedSignBitTest(SDNode *N, SelectionDAG &DAG,
  10670. bool LegalOperations) {
  10671. assert((N->getOpcode() == ISD::SIGN_EXTEND ||
  10672. N->getOpcode() == ISD::ZERO_EXTEND) && "Expected sext or zext");
  10673. SDValue SetCC = N->getOperand(0);
  10674. if (LegalOperations || SetCC.getOpcode() != ISD::SETCC ||
  10675. !SetCC.hasOneUse() || SetCC.getValueType() != MVT::i1)
  10676. return SDValue();
  10677. SDValue X = SetCC.getOperand(0);
  10678. SDValue Ones = SetCC.getOperand(1);
  10679. ISD::CondCode CC = cast<CondCodeSDNode>(SetCC.getOperand(2))->get();
  10680. EVT VT = N->getValueType(0);
  10681. EVT XVT = X.getValueType();
  10682. // setge X, C is canonicalized to setgt, so we do not need to match that
  10683. // pattern. The setlt sibling is folded in SimplifySelectCC() because it does
  10684. // not require the 'not' op.
  10685. if (CC == ISD::SETGT && isAllOnesConstant(Ones) && VT == XVT) {
  10686. // Invert and smear/shift the sign bit:
  10687. // sext i1 (setgt iN X, -1) --> sra (not X), (N - 1)
  10688. // zext i1 (setgt iN X, -1) --> srl (not X), (N - 1)
  10689. SDLoc DL(N);
  10690. unsigned ShCt = VT.getSizeInBits() - 1;
  10691. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  10692. if (!TLI.shouldAvoidTransformToShift(VT, ShCt)) {
  10693. SDValue NotX = DAG.getNOT(DL, X, VT);
  10694. SDValue ShiftAmount = DAG.getConstant(ShCt, DL, VT);
  10695. auto ShiftOpcode =
  10696. N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SRA : ISD::SRL;
  10697. return DAG.getNode(ShiftOpcode, DL, VT, NotX, ShiftAmount);
  10698. }
  10699. }
  10700. return SDValue();
  10701. }
  10702. SDValue DAGCombiner::foldSextSetcc(SDNode *N) {
  10703. SDValue N0 = N->getOperand(0);
  10704. if (N0.getOpcode() != ISD::SETCC)
  10705. return SDValue();
  10706. SDValue N00 = N0.getOperand(0);
  10707. SDValue N01 = N0.getOperand(1);
  10708. ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
  10709. EVT VT = N->getValueType(0);
  10710. EVT N00VT = N00.getValueType();
  10711. SDLoc DL(N);
  10712. // Propagate fast-math-flags.
  10713. SelectionDAG::FlagInserter FlagsInserter(DAG, N0->getFlags());
  10714. // On some architectures (such as SSE/NEON/etc) the SETCC result type is
  10715. // the same size as the compared operands. Try to optimize sext(setcc())
  10716. // if this is the case.
  10717. if (VT.isVector() && !LegalOperations &&
  10718. TLI.getBooleanContents(N00VT) ==
  10719. TargetLowering::ZeroOrNegativeOneBooleanContent) {
  10720. EVT SVT = getSetCCResultType(N00VT);
  10721. // If we already have the desired type, don't change it.
  10722. if (SVT != N0.getValueType()) {
  10723. // We know that the # elements of the results is the same as the
  10724. // # elements of the compare (and the # elements of the compare result
  10725. // for that matter). Check to see that they are the same size. If so,
  10726. // we know that the element size of the sext'd result matches the
  10727. // element size of the compare operands.
  10728. if (VT.getSizeInBits() == SVT.getSizeInBits())
  10729. return DAG.getSetCC(DL, VT, N00, N01, CC);
  10730. // If the desired elements are smaller or larger than the source
  10731. // elements, we can use a matching integer vector type and then
  10732. // truncate/sign extend.
  10733. EVT MatchingVecType = N00VT.changeVectorElementTypeToInteger();
  10734. if (SVT == MatchingVecType) {
  10735. SDValue VsetCC = DAG.getSetCC(DL, MatchingVecType, N00, N01, CC);
  10736. return DAG.getSExtOrTrunc(VsetCC, DL, VT);
  10737. }
  10738. }
  10739. // Try to eliminate the sext of a setcc by zexting the compare operands.
  10740. if (N0.hasOneUse() && TLI.isOperationLegalOrCustom(ISD::SETCC, VT) &&
  10741. !TLI.isOperationLegalOrCustom(ISD::SETCC, SVT)) {
  10742. bool IsSignedCmp = ISD::isSignedIntSetCC(CC);
  10743. unsigned LoadOpcode = IsSignedCmp ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
  10744. unsigned ExtOpcode = IsSignedCmp ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
  10745. // We have an unsupported narrow vector compare op that would be legal
  10746. // if extended to the destination type. See if the compare operands
  10747. // can be freely extended to the destination type.
  10748. auto IsFreeToExtend = [&](SDValue V) {
  10749. if (isConstantOrConstantVector(V, /*NoOpaques*/ true))
  10750. return true;
  10751. // Match a simple, non-extended load that can be converted to a
  10752. // legal {z/s}ext-load.
  10753. // TODO: Allow widening of an existing {z/s}ext-load?
  10754. if (!(ISD::isNON_EXTLoad(V.getNode()) &&
  10755. ISD::isUNINDEXEDLoad(V.getNode()) &&
  10756. cast<LoadSDNode>(V)->isSimple() &&
  10757. TLI.isLoadExtLegal(LoadOpcode, VT, V.getValueType())))
  10758. return false;
  10759. // Non-chain users of this value must either be the setcc in this
  10760. // sequence or extends that can be folded into the new {z/s}ext-load.
  10761. for (SDNode::use_iterator UI = V->use_begin(), UE = V->use_end();
  10762. UI != UE; ++UI) {
  10763. // Skip uses of the chain and the setcc.
  10764. SDNode *User = *UI;
  10765. if (UI.getUse().getResNo() != 0 || User == N0.getNode())
  10766. continue;
  10767. // Extra users must have exactly the same cast we are about to create.
  10768. // TODO: This restriction could be eased if ExtendUsesToFormExtLoad()
  10769. // is enhanced similarly.
  10770. if (User->getOpcode() != ExtOpcode || User->getValueType(0) != VT)
  10771. return false;
  10772. }
  10773. return true;
  10774. };
  10775. if (IsFreeToExtend(N00) && IsFreeToExtend(N01)) {
  10776. SDValue Ext0 = DAG.getNode(ExtOpcode, DL, VT, N00);
  10777. SDValue Ext1 = DAG.getNode(ExtOpcode, DL, VT, N01);
  10778. return DAG.getSetCC(DL, VT, Ext0, Ext1, CC);
  10779. }
  10780. }
  10781. }
  10782. // sext(setcc x, y, cc) -> (select (setcc x, y, cc), T, 0)
  10783. // Here, T can be 1 or -1, depending on the type of the setcc and
  10784. // getBooleanContents().
  10785. unsigned SetCCWidth = N0.getScalarValueSizeInBits();
  10786. // To determine the "true" side of the select, we need to know the high bit
  10787. // of the value returned by the setcc if it evaluates to true.
  10788. // If the type of the setcc is i1, then the true case of the select is just
  10789. // sext(i1 1), that is, -1.
  10790. // If the type of the setcc is larger (say, i8) then the value of the high
  10791. // bit depends on getBooleanContents(), so ask TLI for a real "true" value
  10792. // of the appropriate width.
  10793. SDValue ExtTrueVal = (SetCCWidth == 1)
  10794. ? DAG.getAllOnesConstant(DL, VT)
  10795. : DAG.getBoolConstant(true, DL, VT, N00VT);
  10796. SDValue Zero = DAG.getConstant(0, DL, VT);
  10797. if (SDValue SCC = SimplifySelectCC(DL, N00, N01, ExtTrueVal, Zero, CC, true))
  10798. return SCC;
  10799. if (!VT.isVector() && !shouldConvertSelectOfConstantsToMath(N0, VT, TLI)) {
  10800. EVT SetCCVT = getSetCCResultType(N00VT);
  10801. // Don't do this transform for i1 because there's a select transform
  10802. // that would reverse it.
  10803. // TODO: We should not do this transform at all without a target hook
  10804. // because a sext is likely cheaper than a select?
  10805. if (SetCCVT.getScalarSizeInBits() != 1 &&
  10806. (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, N00VT))) {
  10807. SDValue SetCC = DAG.getSetCC(DL, SetCCVT, N00, N01, CC);
  10808. return DAG.getSelect(DL, VT, SetCC, ExtTrueVal, Zero);
  10809. }
  10810. }
  10811. return SDValue();
  10812. }
  10813. SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
  10814. SDValue N0 = N->getOperand(0);
  10815. EVT VT = N->getValueType(0);
  10816. SDLoc DL(N);
  10817. if (VT.isVector())
  10818. if (SDValue FoldedVOp = SimplifyVCastOp(N, DL))
  10819. return FoldedVOp;
  10820. // sext(undef) = 0 because the top bit will all be the same.
  10821. if (N0.isUndef())
  10822. return DAG.getConstant(0, DL, VT);
  10823. if (SDValue Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes))
  10824. return Res;
  10825. // fold (sext (sext x)) -> (sext x)
  10826. // fold (sext (aext x)) -> (sext x)
  10827. if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
  10828. return DAG.getNode(ISD::SIGN_EXTEND, DL, VT, N0.getOperand(0));
  10829. // fold (sext (sext_inreg x)) -> (sext (trunc x))
  10830. if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG) {
  10831. SDValue N00 = N0.getOperand(0);
  10832. EVT ExtVT = cast<VTSDNode>(N0->getOperand(1))->getVT();
  10833. if (N00.getOpcode() == ISD::TRUNCATE &&
  10834. (!LegalTypes || TLI.isTypeLegal(ExtVT))) {
  10835. SDValue T = DAG.getNode(ISD::TRUNCATE, DL, ExtVT, N00.getOperand(0));
  10836. return DAG.getNode(ISD::SIGN_EXTEND, DL, VT, T);
  10837. }
  10838. }
  10839. if (N0.getOpcode() == ISD::TRUNCATE) {
  10840. // fold (sext (truncate (load x))) -> (sext (smaller load x))
  10841. // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
  10842. if (SDValue NarrowLoad = reduceLoadWidth(N0.getNode())) {
  10843. SDNode *oye = N0.getOperand(0).getNode();
  10844. if (NarrowLoad.getNode() != N0.getNode()) {
  10845. CombineTo(N0.getNode(), NarrowLoad);
  10846. // CombineTo deleted the truncate, if needed, but not what's under it.
  10847. AddToWorklist(oye);
  10848. }
  10849. return SDValue(N, 0); // Return N so it doesn't get rechecked!
  10850. }
  10851. // See if the value being truncated is already sign extended. If so, just
  10852. // eliminate the trunc/sext pair.
  10853. SDValue Op = N0.getOperand(0);
  10854. unsigned OpBits = Op.getScalarValueSizeInBits();
  10855. unsigned MidBits = N0.getScalarValueSizeInBits();
  10856. unsigned DestBits = VT.getScalarSizeInBits();
  10857. unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
  10858. if (OpBits == DestBits) {
  10859. // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
  10860. // bits, it is already ready.
  10861. if (NumSignBits > DestBits-MidBits)
  10862. return Op;
  10863. } else if (OpBits < DestBits) {
  10864. // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
  10865. // bits, just sext from i32.
  10866. if (NumSignBits > OpBits-MidBits)
  10867. return DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Op);
  10868. } else {
  10869. // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
  10870. // bits, just truncate to i32.
  10871. if (NumSignBits > OpBits-MidBits)
  10872. return DAG.getNode(ISD::TRUNCATE, DL, VT, Op);
  10873. }
  10874. // fold (sext (truncate x)) -> (sextinreg x).
  10875. if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
  10876. N0.getValueType())) {
  10877. if (OpBits < DestBits)
  10878. Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
  10879. else if (OpBits > DestBits)
  10880. Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
  10881. return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, Op,
  10882. DAG.getValueType(N0.getValueType()));
  10883. }
  10884. }
  10885. // Try to simplify (sext (load x)).
  10886. if (SDValue foldedExt =
  10887. tryToFoldExtOfLoad(DAG, *this, TLI, VT, LegalOperations, N, N0,
  10888. ISD::SEXTLOAD, ISD::SIGN_EXTEND))
  10889. return foldedExt;
  10890. if (SDValue foldedExt =
  10891. tryToFoldExtOfMaskedLoad(DAG, TLI, VT, N, N0, ISD::SEXTLOAD,
  10892. ISD::SIGN_EXTEND))
  10893. return foldedExt;
  10894. // fold (sext (load x)) to multiple smaller sextloads.
  10895. // Only on illegal but splittable vectors.
  10896. if (SDValue ExtLoad = CombineExtLoad(N))
  10897. return ExtLoad;
  10898. // Try to simplify (sext (sextload x)).
  10899. if (SDValue foldedExt = tryToFoldExtOfExtload(
  10900. DAG, *this, TLI, VT, LegalOperations, N, N0, ISD::SEXTLOAD))
  10901. return foldedExt;
  10902. // fold (sext (and/or/xor (load x), cst)) ->
  10903. // (and/or/xor (sextload x), (sext cst))
  10904. if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
  10905. N0.getOpcode() == ISD::XOR) &&
  10906. isa<LoadSDNode>(N0.getOperand(0)) &&
  10907. N0.getOperand(1).getOpcode() == ISD::Constant &&
  10908. (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
  10909. LoadSDNode *LN00 = cast<LoadSDNode>(N0.getOperand(0));
  10910. EVT MemVT = LN00->getMemoryVT();
  10911. if (TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT) &&
  10912. LN00->getExtensionType() != ISD::ZEXTLOAD && LN00->isUnindexed()) {
  10913. SmallVector<SDNode*, 4> SetCCs;
  10914. bool DoXform = ExtendUsesToFormExtLoad(VT, N0.getNode(), N0.getOperand(0),
  10915. ISD::SIGN_EXTEND, SetCCs, TLI);
  10916. if (DoXform) {
  10917. SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN00), VT,
  10918. LN00->getChain(), LN00->getBasePtr(),
  10919. LN00->getMemoryVT(),
  10920. LN00->getMemOperand());
  10921. APInt Mask = N0.getConstantOperandAPInt(1).sext(VT.getSizeInBits());
  10922. SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
  10923. ExtLoad, DAG.getConstant(Mask, DL, VT));
  10924. ExtendSetCCUses(SetCCs, N0.getOperand(0), ExtLoad, ISD::SIGN_EXTEND);
  10925. bool NoReplaceTruncAnd = !N0.hasOneUse();
  10926. bool NoReplaceTrunc = SDValue(LN00, 0).hasOneUse();
  10927. CombineTo(N, And);
  10928. // If N0 has multiple uses, change other uses as well.
  10929. if (NoReplaceTruncAnd) {
  10930. SDValue TruncAnd =
  10931. DAG.getNode(ISD::TRUNCATE, DL, N0.getValueType(), And);
  10932. CombineTo(N0.getNode(), TruncAnd);
  10933. }
  10934. if (NoReplaceTrunc) {
  10935. DAG.ReplaceAllUsesOfValueWith(SDValue(LN00, 1), ExtLoad.getValue(1));
  10936. } else {
  10937. SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(LN00),
  10938. LN00->getValueType(0), ExtLoad);
  10939. CombineTo(LN00, Trunc, ExtLoad.getValue(1));
  10940. }
  10941. return SDValue(N,0); // Return N so it doesn't get rechecked!
  10942. }
  10943. }
  10944. }
  10945. if (SDValue V = foldExtendedSignBitTest(N, DAG, LegalOperations))
  10946. return V;
  10947. if (SDValue V = foldSextSetcc(N))
  10948. return V;
  10949. // fold (sext x) -> (zext x) if the sign bit is known zero.
  10950. if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
  10951. DAG.SignBitIsZero(N0))
  10952. return DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0);
  10953. if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N))
  10954. return NewVSel;
  10955. // Eliminate this sign extend by doing a negation in the destination type:
  10956. // sext i32 (0 - (zext i8 X to i32)) to i64 --> 0 - (zext i8 X to i64)
  10957. if (N0.getOpcode() == ISD::SUB && N0.hasOneUse() &&
  10958. isNullOrNullSplat(N0.getOperand(0)) &&
  10959. N0.getOperand(1).getOpcode() == ISD::ZERO_EXTEND &&
  10960. TLI.isOperationLegalOrCustom(ISD::SUB, VT)) {
  10961. SDValue Zext = DAG.getZExtOrTrunc(N0.getOperand(1).getOperand(0), DL, VT);
  10962. return DAG.getNegative(Zext, DL, VT);
  10963. }
  10964. // Eliminate this sign extend by doing a decrement in the destination type:
  10965. // sext i32 ((zext i8 X to i32) + (-1)) to i64 --> (zext i8 X to i64) + (-1)
  10966. if (N0.getOpcode() == ISD::ADD && N0.hasOneUse() &&
  10967. isAllOnesOrAllOnesSplat(N0.getOperand(1)) &&
  10968. N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
  10969. TLI.isOperationLegalOrCustom(ISD::ADD, VT)) {
  10970. SDValue Zext = DAG.getZExtOrTrunc(N0.getOperand(0).getOperand(0), DL, VT);
  10971. return DAG.getNode(ISD::ADD, DL, VT, Zext, DAG.getAllOnesConstant(DL, VT));
  10972. }
  10973. // fold sext (not i1 X) -> add (zext i1 X), -1
  10974. // TODO: This could be extended to handle bool vectors.
  10975. if (N0.getValueType() == MVT::i1 && isBitwiseNot(N0) && N0.hasOneUse() &&
  10976. (!LegalOperations || (TLI.isOperationLegal(ISD::ZERO_EXTEND, VT) &&
  10977. TLI.isOperationLegal(ISD::ADD, VT)))) {
  10978. // If we can eliminate the 'not', the sext form should be better
  10979. if (SDValue NewXor = visitXOR(N0.getNode())) {
  10980. // Returning N0 is a form of in-visit replacement that may have
  10981. // invalidated N0.
  10982. if (NewXor.getNode() == N0.getNode()) {
  10983. // Return SDValue here as the xor should have already been replaced in
  10984. // this sext.
  10985. return SDValue();
  10986. }
  10987. // Return a new sext with the new xor.
  10988. return DAG.getNode(ISD::SIGN_EXTEND, DL, VT, NewXor);
  10989. }
  10990. SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
  10991. return DAG.getNode(ISD::ADD, DL, VT, Zext, DAG.getAllOnesConstant(DL, VT));
  10992. }
  10993. if (SDValue Res = tryToFoldExtendSelectLoad(N, TLI, DAG))
  10994. return Res;
  10995. return SDValue();
  10996. }
  10997. // isTruncateOf - If N is a truncate of some other value, return true, record
  10998. // the value being truncated in Op and which of Op's bits are zero/one in Known.
  10999. // This function computes KnownBits to avoid a duplicated call to
  11000. // computeKnownBits in the caller.
  11001. static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
  11002. KnownBits &Known) {
  11003. if (N->getOpcode() == ISD::TRUNCATE) {
  11004. Op = N->getOperand(0);
  11005. Known = DAG.computeKnownBits(Op);
  11006. return true;
  11007. }
  11008. if (N.getOpcode() != ISD::SETCC ||
  11009. N.getValueType().getScalarType() != MVT::i1 ||
  11010. cast<CondCodeSDNode>(N.getOperand(2))->get() != ISD::SETNE)
  11011. return false;
  11012. SDValue Op0 = N->getOperand(0);
  11013. SDValue Op1 = N->getOperand(1);
  11014. assert(Op0.getValueType() == Op1.getValueType());
  11015. if (isNullOrNullSplat(Op0))
  11016. Op = Op1;
  11017. else if (isNullOrNullSplat(Op1))
  11018. Op = Op0;
  11019. else
  11020. return false;
  11021. Known = DAG.computeKnownBits(Op);
  11022. return (Known.Zero | 1).isAllOnes();
  11023. }
  11024. /// Given an extending node with a pop-count operand, if the target does not
  11025. /// support a pop-count in the narrow source type but does support it in the
  11026. /// destination type, widen the pop-count to the destination type.
  11027. static SDValue widenCtPop(SDNode *Extend, SelectionDAG &DAG) {
  11028. assert((Extend->getOpcode() == ISD::ZERO_EXTEND ||
  11029. Extend->getOpcode() == ISD::ANY_EXTEND) && "Expected extend op");
  11030. SDValue CtPop = Extend->getOperand(0);
  11031. if (CtPop.getOpcode() != ISD::CTPOP || !CtPop.hasOneUse())
  11032. return SDValue();
  11033. EVT VT = Extend->getValueType(0);
  11034. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  11035. if (TLI.isOperationLegalOrCustom(ISD::CTPOP, CtPop.getValueType()) ||
  11036. !TLI.isOperationLegalOrCustom(ISD::CTPOP, VT))
  11037. return SDValue();
  11038. // zext (ctpop X) --> ctpop (zext X)
  11039. SDLoc DL(Extend);
  11040. SDValue NewZext = DAG.getZExtOrTrunc(CtPop.getOperand(0), DL, VT);
  11041. return DAG.getNode(ISD::CTPOP, DL, VT, NewZext);
  11042. }
  11043. // If we have (zext (abs X)) where X is a type that will be promoted by type
  11044. // legalization, convert to (abs (sext X)). But don't extend past a legal type.
  11045. static SDValue widenAbs(SDNode *Extend, SelectionDAG &DAG) {
  11046. assert(Extend->getOpcode() == ISD::ZERO_EXTEND && "Expected zero extend.");
  11047. EVT VT = Extend->getValueType(0);
  11048. if (VT.isVector())
  11049. return SDValue();
  11050. SDValue Abs = Extend->getOperand(0);
  11051. if (Abs.getOpcode() != ISD::ABS || !Abs.hasOneUse())
  11052. return SDValue();
  11053. EVT AbsVT = Abs.getValueType();
  11054. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  11055. if (TLI.getTypeAction(*DAG.getContext(), AbsVT) !=
  11056. TargetLowering::TypePromoteInteger)
  11057. return SDValue();
  11058. EVT LegalVT = TLI.getTypeToTransformTo(*DAG.getContext(), AbsVT);
  11059. SDValue SExt =
  11060. DAG.getNode(ISD::SIGN_EXTEND, SDLoc(Abs), LegalVT, Abs.getOperand(0));
  11061. SDValue NewAbs = DAG.getNode(ISD::ABS, SDLoc(Abs), LegalVT, SExt);
  11062. return DAG.getZExtOrTrunc(NewAbs, SDLoc(Extend), VT);
  11063. }
  11064. SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
  11065. SDValue N0 = N->getOperand(0);
  11066. EVT VT = N->getValueType(0);
  11067. if (VT.isVector())
  11068. if (SDValue FoldedVOp = SimplifyVCastOp(N, SDLoc(N)))
  11069. return FoldedVOp;
  11070. // zext(undef) = 0
  11071. if (N0.isUndef())
  11072. return DAG.getConstant(0, SDLoc(N), VT);
  11073. if (SDValue Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes))
  11074. return Res;
  11075. // fold (zext (zext x)) -> (zext x)
  11076. // fold (zext (aext x)) -> (zext x)
  11077. if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
  11078. return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
  11079. N0.getOperand(0));
  11080. // fold (zext (truncate x)) -> (zext x) or
  11081. // (zext (truncate x)) -> (truncate x)
  11082. // This is valid when the truncated bits of x are already zero.
  11083. SDValue Op;
  11084. KnownBits Known;
  11085. if (isTruncateOf(DAG, N0, Op, Known)) {
  11086. APInt TruncatedBits =
  11087. (Op.getScalarValueSizeInBits() == N0.getScalarValueSizeInBits()) ?
  11088. APInt(Op.getScalarValueSizeInBits(), 0) :
  11089. APInt::getBitsSet(Op.getScalarValueSizeInBits(),
  11090. N0.getScalarValueSizeInBits(),
  11091. std::min(Op.getScalarValueSizeInBits(),
  11092. VT.getScalarSizeInBits()));
  11093. if (TruncatedBits.isSubsetOf(Known.Zero))
  11094. return DAG.getZExtOrTrunc(Op, SDLoc(N), VT);
  11095. }
  11096. // fold (zext (truncate x)) -> (and x, mask)
  11097. if (N0.getOpcode() == ISD::TRUNCATE) {
  11098. // fold (zext (truncate (load x))) -> (zext (smaller load x))
  11099. // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
  11100. if (SDValue NarrowLoad = reduceLoadWidth(N0.getNode())) {
  11101. SDNode *oye = N0.getOperand(0).getNode();
  11102. if (NarrowLoad.getNode() != N0.getNode()) {
  11103. CombineTo(N0.getNode(), NarrowLoad);
  11104. // CombineTo deleted the truncate, if needed, but not what's under it.
  11105. AddToWorklist(oye);
  11106. }
  11107. return SDValue(N, 0); // Return N so it doesn't get rechecked!
  11108. }
  11109. EVT SrcVT = N0.getOperand(0).getValueType();
  11110. EVT MinVT = N0.getValueType();
  11111. // Try to mask before the extension to avoid having to generate a larger mask,
  11112. // possibly over several sub-vectors.
  11113. if (SrcVT.bitsLT(VT) && VT.isVector()) {
  11114. if (!LegalOperations || (TLI.isOperationLegal(ISD::AND, SrcVT) &&
  11115. TLI.isOperationLegal(ISD::ZERO_EXTEND, VT))) {
  11116. SDValue Op = N0.getOperand(0);
  11117. Op = DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT);
  11118. AddToWorklist(Op.getNode());
  11119. SDValue ZExtOrTrunc = DAG.getZExtOrTrunc(Op, SDLoc(N), VT);
  11120. // Transfer the debug info; the new node is equivalent to N0.
  11121. DAG.transferDbgValues(N0, ZExtOrTrunc);
  11122. return ZExtOrTrunc;
  11123. }
  11124. }
  11125. if (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT)) {
  11126. SDValue Op = DAG.getAnyExtOrTrunc(N0.getOperand(0), SDLoc(N), VT);
  11127. AddToWorklist(Op.getNode());
  11128. SDValue And = DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT);
  11129. // We may safely transfer the debug info describing the truncate node over
  11130. // to the equivalent and operation.
  11131. DAG.transferDbgValues(N0, And);
  11132. return And;
  11133. }
  11134. }
  11135. // Fold (zext (and (trunc x), cst)) -> (and x, cst),
  11136. // if either of the casts is not free.
  11137. if (N0.getOpcode() == ISD::AND &&
  11138. N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
  11139. N0.getOperand(1).getOpcode() == ISD::Constant &&
  11140. (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
  11141. N0.getValueType()) ||
  11142. !TLI.isZExtFree(N0.getValueType(), VT))) {
  11143. SDValue X = N0.getOperand(0).getOperand(0);
  11144. X = DAG.getAnyExtOrTrunc(X, SDLoc(X), VT);
  11145. APInt Mask = N0.getConstantOperandAPInt(1).zext(VT.getSizeInBits());
  11146. SDLoc DL(N);
  11147. return DAG.getNode(ISD::AND, DL, VT,
  11148. X, DAG.getConstant(Mask, DL, VT));
  11149. }
  11150. // Try to simplify (zext (load x)).
  11151. if (SDValue foldedExt =
  11152. tryToFoldExtOfLoad(DAG, *this, TLI, VT, LegalOperations, N, N0,
  11153. ISD::ZEXTLOAD, ISD::ZERO_EXTEND))
  11154. return foldedExt;
  11155. if (SDValue foldedExt =
  11156. tryToFoldExtOfMaskedLoad(DAG, TLI, VT, N, N0, ISD::ZEXTLOAD,
  11157. ISD::ZERO_EXTEND))
  11158. return foldedExt;
  11159. // fold (zext (load x)) to multiple smaller zextloads.
  11160. // Only on illegal but splittable vectors.
  11161. if (SDValue ExtLoad = CombineExtLoad(N))
  11162. return ExtLoad;
  11163. // fold (zext (and/or/xor (load x), cst)) ->
  11164. // (and/or/xor (zextload x), (zext cst))
  11165. // Unless (and (load x) cst) will match as a zextload already and has
  11166. // additional users.
  11167. if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
  11168. N0.getOpcode() == ISD::XOR) &&
  11169. isa<LoadSDNode>(N0.getOperand(0)) &&
  11170. N0.getOperand(1).getOpcode() == ISD::Constant &&
  11171. (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
  11172. LoadSDNode *LN00 = cast<LoadSDNode>(N0.getOperand(0));
  11173. EVT MemVT = LN00->getMemoryVT();
  11174. if (TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT) &&
  11175. LN00->getExtensionType() != ISD::SEXTLOAD && LN00->isUnindexed()) {
  11176. bool DoXform = true;
  11177. SmallVector<SDNode*, 4> SetCCs;
  11178. if (!N0.hasOneUse()) {
  11179. if (N0.getOpcode() == ISD::AND) {
  11180. auto *AndC = cast<ConstantSDNode>(N0.getOperand(1));
  11181. EVT LoadResultTy = AndC->getValueType(0);
  11182. EVT ExtVT;
  11183. if (isAndLoadExtLoad(AndC, LN00, LoadResultTy, ExtVT))
  11184. DoXform = false;
  11185. }
  11186. }
  11187. if (DoXform)
  11188. DoXform = ExtendUsesToFormExtLoad(VT, N0.getNode(), N0.getOperand(0),
  11189. ISD::ZERO_EXTEND, SetCCs, TLI);
  11190. if (DoXform) {
  11191. SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN00), VT,
  11192. LN00->getChain(), LN00->getBasePtr(),
  11193. LN00->getMemoryVT(),
  11194. LN00->getMemOperand());
  11195. APInt Mask = N0.getConstantOperandAPInt(1).zext(VT.getSizeInBits());
  11196. SDLoc DL(N);
  11197. SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
  11198. ExtLoad, DAG.getConstant(Mask, DL, VT));
  11199. ExtendSetCCUses(SetCCs, N0.getOperand(0), ExtLoad, ISD::ZERO_EXTEND);
  11200. bool NoReplaceTruncAnd = !N0.hasOneUse();
  11201. bool NoReplaceTrunc = SDValue(LN00, 0).hasOneUse();
  11202. CombineTo(N, And);
  11203. // If N0 has multiple uses, change other uses as well.
  11204. if (NoReplaceTruncAnd) {
  11205. SDValue TruncAnd =
  11206. DAG.getNode(ISD::TRUNCATE, DL, N0.getValueType(), And);
  11207. CombineTo(N0.getNode(), TruncAnd);
  11208. }
  11209. if (NoReplaceTrunc) {
  11210. DAG.ReplaceAllUsesOfValueWith(SDValue(LN00, 1), ExtLoad.getValue(1));
  11211. } else {
  11212. SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(LN00),
  11213. LN00->getValueType(0), ExtLoad);
  11214. CombineTo(LN00, Trunc, ExtLoad.getValue(1));
  11215. }
  11216. return SDValue(N,0); // Return N so it doesn't get rechecked!
  11217. }
  11218. }
  11219. }
  11220. // fold (zext (and/or/xor (shl/shr (load x), cst), cst)) ->
  11221. // (and/or/xor (shl/shr (zextload x), (zext cst)), (zext cst))
  11222. if (SDValue ZExtLoad = CombineZExtLogicopShiftLoad(N))
  11223. return ZExtLoad;
  11224. // Try to simplify (zext (zextload x)).
  11225. if (SDValue foldedExt = tryToFoldExtOfExtload(
  11226. DAG, *this, TLI, VT, LegalOperations, N, N0, ISD::ZEXTLOAD))
  11227. return foldedExt;
  11228. if (SDValue V = foldExtendedSignBitTest(N, DAG, LegalOperations))
  11229. return V;
  11230. if (N0.getOpcode() == ISD::SETCC) {
  11231. // Propagate fast-math-flags.
  11232. SelectionDAG::FlagInserter FlagsInserter(DAG, N0->getFlags());
  11233. // Only do this before legalize for now.
  11234. if (!LegalOperations && VT.isVector() &&
  11235. N0.getValueType().getVectorElementType() == MVT::i1) {
  11236. EVT N00VT = N0.getOperand(0).getValueType();
  11237. if (getSetCCResultType(N00VT) == N0.getValueType())
  11238. return SDValue();
  11239. // We know that the # elements of the results is the same as the #
  11240. // elements of the compare (and the # elements of the compare result for
  11241. // that matter). Check to see that they are the same size. If so, we know
  11242. // that the element size of the sext'd result matches the element size of
  11243. // the compare operands.
  11244. SDLoc DL(N);
  11245. if (VT.getSizeInBits() == N00VT.getSizeInBits()) {
  11246. // zext(setcc) -> zext_in_reg(vsetcc) for vectors.
  11247. SDValue VSetCC = DAG.getNode(ISD::SETCC, DL, VT, N0.getOperand(0),
  11248. N0.getOperand(1), N0.getOperand(2));
  11249. return DAG.getZeroExtendInReg(VSetCC, DL, N0.getValueType());
  11250. }
  11251. // If the desired elements are smaller or larger than the source
  11252. // elements we can use a matching integer vector type and then
  11253. // truncate/any extend followed by zext_in_reg.
  11254. EVT MatchingVectorType = N00VT.changeVectorElementTypeToInteger();
  11255. SDValue VsetCC =
  11256. DAG.getNode(ISD::SETCC, DL, MatchingVectorType, N0.getOperand(0),
  11257. N0.getOperand(1), N0.getOperand(2));
  11258. return DAG.getZeroExtendInReg(DAG.getAnyExtOrTrunc(VsetCC, DL, VT), DL,
  11259. N0.getValueType());
  11260. }
  11261. // zext(setcc x,y,cc) -> zext(select x, y, true, false, cc)
  11262. SDLoc DL(N);
  11263. EVT N0VT = N0.getValueType();
  11264. EVT N00VT = N0.getOperand(0).getValueType();
  11265. if (SDValue SCC = SimplifySelectCC(
  11266. DL, N0.getOperand(0), N0.getOperand(1),
  11267. DAG.getBoolConstant(true, DL, N0VT, N00VT),
  11268. DAG.getBoolConstant(false, DL, N0VT, N00VT),
  11269. cast<CondCodeSDNode>(N0.getOperand(2))->get(), true))
  11270. return DAG.getNode(ISD::ZERO_EXTEND, DL, VT, SCC);
  11271. }
  11272. // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
  11273. if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
  11274. isa<ConstantSDNode>(N0.getOperand(1)) &&
  11275. N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
  11276. N0.hasOneUse()) {
  11277. SDValue ShAmt = N0.getOperand(1);
  11278. if (N0.getOpcode() == ISD::SHL) {
  11279. SDValue InnerZExt = N0.getOperand(0);
  11280. // If the original shl may be shifting out bits, do not perform this
  11281. // transformation.
  11282. unsigned KnownZeroBits = InnerZExt.getValueSizeInBits() -
  11283. InnerZExt.getOperand(0).getValueSizeInBits();
  11284. if (cast<ConstantSDNode>(ShAmt)->getAPIntValue().ugt(KnownZeroBits))
  11285. return SDValue();
  11286. }
  11287. SDLoc DL(N);
  11288. // Ensure that the shift amount is wide enough for the shifted value.
  11289. if (Log2_32_Ceil(VT.getSizeInBits()) > ShAmt.getValueSizeInBits())
  11290. ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
  11291. return DAG.getNode(N0.getOpcode(), DL, VT,
  11292. DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
  11293. ShAmt);
  11294. }
  11295. if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N))
  11296. return NewVSel;
  11297. if (SDValue NewCtPop = widenCtPop(N, DAG))
  11298. return NewCtPop;
  11299. if (SDValue V = widenAbs(N, DAG))
  11300. return V;
  11301. if (SDValue Res = tryToFoldExtendSelectLoad(N, TLI, DAG))
  11302. return Res;
  11303. return SDValue();
  11304. }
  11305. SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
  11306. SDValue N0 = N->getOperand(0);
  11307. EVT VT = N->getValueType(0);
  11308. // aext(undef) = undef
  11309. if (N0.isUndef())
  11310. return DAG.getUNDEF(VT);
  11311. if (SDValue Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes))
  11312. return Res;
  11313. // fold (aext (aext x)) -> (aext x)
  11314. // fold (aext (zext x)) -> (zext x)
  11315. // fold (aext (sext x)) -> (sext x)
  11316. if (N0.getOpcode() == ISD::ANY_EXTEND ||
  11317. N0.getOpcode() == ISD::ZERO_EXTEND ||
  11318. N0.getOpcode() == ISD::SIGN_EXTEND)
  11319. return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
  11320. // fold (aext (truncate (load x))) -> (aext (smaller load x))
  11321. // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
  11322. if (N0.getOpcode() == ISD::TRUNCATE) {
  11323. if (SDValue NarrowLoad = reduceLoadWidth(N0.getNode())) {
  11324. SDNode *oye = N0.getOperand(0).getNode();
  11325. if (NarrowLoad.getNode() != N0.getNode()) {
  11326. CombineTo(N0.getNode(), NarrowLoad);
  11327. // CombineTo deleted the truncate, if needed, but not what's under it.
  11328. AddToWorklist(oye);
  11329. }
  11330. return SDValue(N, 0); // Return N so it doesn't get rechecked!
  11331. }
  11332. }
  11333. // fold (aext (truncate x))
  11334. if (N0.getOpcode() == ISD::TRUNCATE)
  11335. return DAG.getAnyExtOrTrunc(N0.getOperand(0), SDLoc(N), VT);
  11336. // Fold (aext (and (trunc x), cst)) -> (and x, cst)
  11337. // if the trunc is not free.
  11338. if (N0.getOpcode() == ISD::AND &&
  11339. N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
  11340. N0.getOperand(1).getOpcode() == ISD::Constant &&
  11341. !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
  11342. N0.getValueType())) {
  11343. SDLoc DL(N);
  11344. SDValue X = DAG.getAnyExtOrTrunc(N0.getOperand(0).getOperand(0), DL, VT);
  11345. SDValue Y = DAG.getNode(ISD::ANY_EXTEND, DL, VT, N0.getOperand(1));
  11346. assert(isa<ConstantSDNode>(Y) && "Expected constant to be folded!");
  11347. return DAG.getNode(ISD::AND, DL, VT, X, Y);
  11348. }
  11349. // fold (aext (load x)) -> (aext (truncate (extload x)))
  11350. // None of the supported targets knows how to perform load and any_ext
  11351. // on vectors in one instruction, so attempt to fold to zext instead.
  11352. if (VT.isVector()) {
  11353. // Try to simplify (zext (load x)).
  11354. if (SDValue foldedExt =
  11355. tryToFoldExtOfLoad(DAG, *this, TLI, VT, LegalOperations, N, N0,
  11356. ISD::ZEXTLOAD, ISD::ZERO_EXTEND))
  11357. return foldedExt;
  11358. } else if (ISD::isNON_EXTLoad(N0.getNode()) &&
  11359. ISD::isUNINDEXEDLoad(N0.getNode()) &&
  11360. TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
  11361. bool DoXform = true;
  11362. SmallVector<SDNode *, 4> SetCCs;
  11363. if (!N0.hasOneUse())
  11364. DoXform =
  11365. ExtendUsesToFormExtLoad(VT, N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
  11366. if (DoXform) {
  11367. LoadSDNode *LN0 = cast<LoadSDNode>(N0);
  11368. SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
  11369. LN0->getChain(), LN0->getBasePtr(),
  11370. N0.getValueType(), LN0->getMemOperand());
  11371. ExtendSetCCUses(SetCCs, N0, ExtLoad, ISD::ANY_EXTEND);
  11372. // If the load value is used only by N, replace it via CombineTo N.
  11373. bool NoReplaceTrunc = N0.hasOneUse();
  11374. CombineTo(N, ExtLoad);
  11375. if (NoReplaceTrunc) {
  11376. DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), ExtLoad.getValue(1));
  11377. recursivelyDeleteUnusedNodes(LN0);
  11378. } else {
  11379. SDValue Trunc =
  11380. DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), ExtLoad);
  11381. CombineTo(LN0, Trunc, ExtLoad.getValue(1));
  11382. }
  11383. return SDValue(N, 0); // Return N so it doesn't get rechecked!
  11384. }
  11385. }
  11386. // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
  11387. // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
  11388. // fold (aext ( extload x)) -> (aext (truncate (extload x)))
  11389. if (N0.getOpcode() == ISD::LOAD && !ISD::isNON_EXTLoad(N0.getNode()) &&
  11390. ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
  11391. LoadSDNode *LN0 = cast<LoadSDNode>(N0);
  11392. ISD::LoadExtType ExtType = LN0->getExtensionType();
  11393. EVT MemVT = LN0->getMemoryVT();
  11394. if (!LegalOperations || TLI.isLoadExtLegal(ExtType, VT, MemVT)) {
  11395. SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
  11396. VT, LN0->getChain(), LN0->getBasePtr(),
  11397. MemVT, LN0->getMemOperand());
  11398. CombineTo(N, ExtLoad);
  11399. DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), ExtLoad.getValue(1));
  11400. recursivelyDeleteUnusedNodes(LN0);
  11401. return SDValue(N, 0); // Return N so it doesn't get rechecked!
  11402. }
  11403. }
  11404. if (N0.getOpcode() == ISD::SETCC) {
  11405. // Propagate fast-math-flags.
  11406. SelectionDAG::FlagInserter FlagsInserter(DAG, N0->getFlags());
  11407. // For vectors:
  11408. // aext(setcc) -> vsetcc
  11409. // aext(setcc) -> truncate(vsetcc)
  11410. // aext(setcc) -> aext(vsetcc)
  11411. // Only do this before legalize for now.
  11412. if (VT.isVector() && !LegalOperations) {
  11413. EVT N00VT = N0.getOperand(0).getValueType();
  11414. if (getSetCCResultType(N00VT) == N0.getValueType())
  11415. return SDValue();
  11416. // We know that the # elements of the results is the same as the
  11417. // # elements of the compare (and the # elements of the compare result
  11418. // for that matter). Check to see that they are the same size. If so,
  11419. // we know that the element size of the sext'd result matches the
  11420. // element size of the compare operands.
  11421. if (VT.getSizeInBits() == N00VT.getSizeInBits())
  11422. return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
  11423. N0.getOperand(1),
  11424. cast<CondCodeSDNode>(N0.getOperand(2))->get());
  11425. // If the desired elements are smaller or larger than the source
  11426. // elements we can use a matching integer vector type and then
  11427. // truncate/any extend
  11428. EVT MatchingVectorType = N00VT.changeVectorElementTypeToInteger();
  11429. SDValue VsetCC =
  11430. DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
  11431. N0.getOperand(1),
  11432. cast<CondCodeSDNode>(N0.getOperand(2))->get());
  11433. return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
  11434. }
  11435. // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
  11436. SDLoc DL(N);
  11437. if (SDValue SCC = SimplifySelectCC(
  11438. DL, N0.getOperand(0), N0.getOperand(1), DAG.getConstant(1, DL, VT),
  11439. DAG.getConstant(0, DL, VT),
  11440. cast<CondCodeSDNode>(N0.getOperand(2))->get(), true))
  11441. return SCC;
  11442. }
  11443. if (SDValue NewCtPop = widenCtPop(N, DAG))
  11444. return NewCtPop;
  11445. if (SDValue Res = tryToFoldExtendSelectLoad(N, TLI, DAG))
  11446. return Res;
  11447. return SDValue();
  11448. }
  11449. SDValue DAGCombiner::visitAssertExt(SDNode *N) {
  11450. unsigned Opcode = N->getOpcode();
  11451. SDValue N0 = N->getOperand(0);
  11452. SDValue N1 = N->getOperand(1);
  11453. EVT AssertVT = cast<VTSDNode>(N1)->getVT();
  11454. // fold (assert?ext (assert?ext x, vt), vt) -> (assert?ext x, vt)
  11455. if (N0.getOpcode() == Opcode &&
  11456. AssertVT == cast<VTSDNode>(N0.getOperand(1))->getVT())
  11457. return N0;
  11458. if (N0.getOpcode() == ISD::TRUNCATE && N0.hasOneUse() &&
  11459. N0.getOperand(0).getOpcode() == Opcode) {
  11460. // We have an assert, truncate, assert sandwich. Make one stronger assert
  11461. // by asserting on the smallest asserted type to the larger source type.
  11462. // This eliminates the later assert:
  11463. // assert (trunc (assert X, i8) to iN), i1 --> trunc (assert X, i1) to iN
  11464. // assert (trunc (assert X, i1) to iN), i8 --> trunc (assert X, i1) to iN
  11465. SDLoc DL(N);
  11466. SDValue BigA = N0.getOperand(0);
  11467. EVT BigA_AssertVT = cast<VTSDNode>(BigA.getOperand(1))->getVT();
  11468. EVT MinAssertVT = AssertVT.bitsLT(BigA_AssertVT) ? AssertVT : BigA_AssertVT;
  11469. SDValue MinAssertVTVal = DAG.getValueType(MinAssertVT);
  11470. SDValue NewAssert = DAG.getNode(Opcode, DL, BigA.getValueType(),
  11471. BigA.getOperand(0), MinAssertVTVal);
  11472. return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewAssert);
  11473. }
  11474. // If we have (AssertZext (truncate (AssertSext X, iX)), iY) and Y is smaller
  11475. // than X. Just move the AssertZext in front of the truncate and drop the
  11476. // AssertSExt.
  11477. if (N0.getOpcode() == ISD::TRUNCATE && N0.hasOneUse() &&
  11478. N0.getOperand(0).getOpcode() == ISD::AssertSext &&
  11479. Opcode == ISD::AssertZext) {
  11480. SDValue BigA = N0.getOperand(0);
  11481. EVT BigA_AssertVT = cast<VTSDNode>(BigA.getOperand(1))->getVT();
  11482. if (AssertVT.bitsLT(BigA_AssertVT)) {
  11483. SDLoc DL(N);
  11484. SDValue NewAssert = DAG.getNode(Opcode, DL, BigA.getValueType(),
  11485. BigA.getOperand(0), N1);
  11486. return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewAssert);
  11487. }
  11488. }
  11489. return SDValue();
  11490. }
  11491. SDValue DAGCombiner::visitAssertAlign(SDNode *N) {
  11492. SDLoc DL(N);
  11493. Align AL = cast<AssertAlignSDNode>(N)->getAlign();
  11494. SDValue N0 = N->getOperand(0);
  11495. // Fold (assertalign (assertalign x, AL0), AL1) ->
  11496. // (assertalign x, max(AL0, AL1))
  11497. if (auto *AAN = dyn_cast<AssertAlignSDNode>(N0))
  11498. return DAG.getAssertAlign(DL, N0.getOperand(0),
  11499. std::max(AL, AAN->getAlign()));
  11500. // In rare cases, there are trivial arithmetic ops in source operands. Sink
  11501. // this assert down to source operands so that those arithmetic ops could be
  11502. // exposed to the DAG combining.
  11503. switch (N0.getOpcode()) {
  11504. default:
  11505. break;
  11506. case ISD::ADD:
  11507. case ISD::SUB: {
  11508. unsigned AlignShift = Log2(AL);
  11509. SDValue LHS = N0.getOperand(0);
  11510. SDValue RHS = N0.getOperand(1);
  11511. unsigned LHSAlignShift = DAG.computeKnownBits(LHS).countMinTrailingZeros();
  11512. unsigned RHSAlignShift = DAG.computeKnownBits(RHS).countMinTrailingZeros();
  11513. if (LHSAlignShift >= AlignShift || RHSAlignShift >= AlignShift) {
  11514. if (LHSAlignShift < AlignShift)
  11515. LHS = DAG.getAssertAlign(DL, LHS, AL);
  11516. if (RHSAlignShift < AlignShift)
  11517. RHS = DAG.getAssertAlign(DL, RHS, AL);
  11518. return DAG.getNode(N0.getOpcode(), DL, N0.getValueType(), LHS, RHS);
  11519. }
  11520. break;
  11521. }
  11522. }
  11523. return SDValue();
  11524. }
  11525. /// If the result of a load is shifted/masked/truncated to an effectively
  11526. /// narrower type, try to transform the load to a narrower type and/or
  11527. /// use an extending load.
  11528. SDValue DAGCombiner::reduceLoadWidth(SDNode *N) {
  11529. unsigned Opc = N->getOpcode();
  11530. ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
  11531. SDValue N0 = N->getOperand(0);
  11532. EVT VT = N->getValueType(0);
  11533. EVT ExtVT = VT;
  11534. // This transformation isn't valid for vector loads.
  11535. if (VT.isVector())
  11536. return SDValue();
  11537. // The ShAmt variable is used to indicate that we've consumed a right
  11538. // shift. I.e. we want to narrow the width of the load by skipping to load the
  11539. // ShAmt least significant bits.
  11540. unsigned ShAmt = 0;
  11541. // A special case is when the least significant bits from the load are masked
  11542. // away, but using an AND rather than a right shift. HasShiftedOffset is used
  11543. // to indicate that the narrowed load should be left-shifted ShAmt bits to get
  11544. // the result.
  11545. bool HasShiftedOffset = false;
  11546. // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
  11547. // extended to VT.
  11548. if (Opc == ISD::SIGN_EXTEND_INREG) {
  11549. ExtType = ISD::SEXTLOAD;
  11550. ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
  11551. } else if (Opc == ISD::SRL || Opc == ISD::SRA) {
  11552. // Another special-case: SRL/SRA is basically zero/sign-extending a narrower
  11553. // value, or it may be shifting a higher subword, half or byte into the
  11554. // lowest bits.
  11555. // Only handle shift with constant shift amount, and the shiftee must be a
  11556. // load.
  11557. auto *LN = dyn_cast<LoadSDNode>(N0);
  11558. auto *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1));
  11559. if (!N1C || !LN)
  11560. return SDValue();
  11561. // If the shift amount is larger than the memory type then we're not
  11562. // accessing any of the loaded bytes.
  11563. ShAmt = N1C->getZExtValue();
  11564. uint64_t MemoryWidth = LN->getMemoryVT().getScalarSizeInBits();
  11565. if (MemoryWidth <= ShAmt)
  11566. return SDValue();
  11567. // Attempt to fold away the SRL by using ZEXTLOAD and SRA by using SEXTLOAD.
  11568. ExtType = Opc == ISD::SRL ? ISD::ZEXTLOAD : ISD::SEXTLOAD;
  11569. ExtVT = EVT::getIntegerVT(*DAG.getContext(), MemoryWidth - ShAmt);
  11570. // If original load is a SEXTLOAD then we can't simply replace it by a
  11571. // ZEXTLOAD (we could potentially replace it by a more narrow SEXTLOAD
  11572. // followed by a ZEXT, but that is not handled at the moment). Similarly if
  11573. // the original load is a ZEXTLOAD and we want to use a SEXTLOAD.
  11574. if ((LN->getExtensionType() == ISD::SEXTLOAD ||
  11575. LN->getExtensionType() == ISD::ZEXTLOAD) &&
  11576. LN->getExtensionType() != ExtType)
  11577. return SDValue();
  11578. } else if (Opc == ISD::AND) {
  11579. // An AND with a constant mask is the same as a truncate + zero-extend.
  11580. auto AndC = dyn_cast<ConstantSDNode>(N->getOperand(1));
  11581. if (!AndC)
  11582. return SDValue();
  11583. const APInt &Mask = AndC->getAPIntValue();
  11584. unsigned ActiveBits = 0;
  11585. if (Mask.isMask()) {
  11586. ActiveBits = Mask.countTrailingOnes();
  11587. } else if (Mask.isShiftedMask(ShAmt, ActiveBits)) {
  11588. HasShiftedOffset = true;
  11589. } else {
  11590. return SDValue();
  11591. }
  11592. ExtType = ISD::ZEXTLOAD;
  11593. ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
  11594. }
  11595. // In case Opc==SRL we've already prepared ExtVT/ExtType/ShAmt based on doing
  11596. // a right shift. Here we redo some of those checks, to possibly adjust the
  11597. // ExtVT even further based on "a masking AND". We could also end up here for
  11598. // other reasons (e.g. based on Opc==TRUNCATE) and that is why some checks
  11599. // need to be done here as well.
  11600. if (Opc == ISD::SRL || N0.getOpcode() == ISD::SRL) {
  11601. SDValue SRL = Opc == ISD::SRL ? SDValue(N, 0) : N0;
  11602. // Bail out when the SRL has more than one use. This is done for historical
  11603. // (undocumented) reasons. Maybe intent was to guard the AND-masking below
  11604. // check below? And maybe it could be non-profitable to do the transform in
  11605. // case the SRL has multiple uses and we get here with Opc!=ISD::SRL?
  11606. // FIXME: Can't we just skip this check for the Opc==ISD::SRL case.
  11607. if (!SRL.hasOneUse())
  11608. return SDValue();
  11609. // Only handle shift with constant shift amount, and the shiftee must be a
  11610. // load.
  11611. auto *LN = dyn_cast<LoadSDNode>(SRL.getOperand(0));
  11612. auto *SRL1C = dyn_cast<ConstantSDNode>(SRL.getOperand(1));
  11613. if (!SRL1C || !LN)
  11614. return SDValue();
  11615. // If the shift amount is larger than the input type then we're not
  11616. // accessing any of the loaded bytes. If the load was a zextload/extload
  11617. // then the result of the shift+trunc is zero/undef (handled elsewhere).
  11618. ShAmt = SRL1C->getZExtValue();
  11619. uint64_t MemoryWidth = LN->getMemoryVT().getSizeInBits();
  11620. if (ShAmt >= MemoryWidth)
  11621. return SDValue();
  11622. // Because a SRL must be assumed to *need* to zero-extend the high bits
  11623. // (as opposed to anyext the high bits), we can't combine the zextload
  11624. // lowering of SRL and an sextload.
  11625. if (LN->getExtensionType() == ISD::SEXTLOAD)
  11626. return SDValue();
  11627. // Avoid reading outside the memory accessed by the original load (could
  11628. // happened if we only adjust the load base pointer by ShAmt). Instead we
  11629. // try to narrow the load even further. The typical scenario here is:
  11630. // (i64 (truncate (i96 (srl (load x), 64)))) ->
  11631. // (i64 (truncate (i96 (zextload (load i32 + offset) from i32))))
  11632. if (ExtVT.getScalarSizeInBits() > MemoryWidth - ShAmt) {
  11633. // Don't replace sextload by zextload.
  11634. if (ExtType == ISD::SEXTLOAD)
  11635. return SDValue();
  11636. // Narrow the load.
  11637. ExtType = ISD::ZEXTLOAD;
  11638. ExtVT = EVT::getIntegerVT(*DAG.getContext(), MemoryWidth - ShAmt);
  11639. }
  11640. // If the SRL is only used by a masking AND, we may be able to adjust
  11641. // the ExtVT to make the AND redundant.
  11642. SDNode *Mask = *(SRL->use_begin());
  11643. if (SRL.hasOneUse() && Mask->getOpcode() == ISD::AND &&
  11644. isa<ConstantSDNode>(Mask->getOperand(1))) {
  11645. const APInt& ShiftMask = Mask->getConstantOperandAPInt(1);
  11646. if (ShiftMask.isMask()) {
  11647. EVT MaskedVT = EVT::getIntegerVT(*DAG.getContext(),
  11648. ShiftMask.countTrailingOnes());
  11649. // If the mask is smaller, recompute the type.
  11650. if ((ExtVT.getScalarSizeInBits() > MaskedVT.getScalarSizeInBits()) &&
  11651. TLI.isLoadExtLegal(ExtType, SRL.getValueType(), MaskedVT))
  11652. ExtVT = MaskedVT;
  11653. }
  11654. }
  11655. N0 = SRL.getOperand(0);
  11656. }
  11657. // If the load is shifted left (and the result isn't shifted back right), we
  11658. // can fold a truncate through the shift. The typical scenario is that N
  11659. // points at a TRUNCATE here so the attempted fold is:
  11660. // (truncate (shl (load x), c))) -> (shl (narrow load x), c)
  11661. // ShLeftAmt will indicate how much a narrowed load should be shifted left.
  11662. unsigned ShLeftAmt = 0;
  11663. if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
  11664. ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
  11665. if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
  11666. ShLeftAmt = N01->getZExtValue();
  11667. N0 = N0.getOperand(0);
  11668. }
  11669. }
  11670. // If we haven't found a load, we can't narrow it.
  11671. if (!isa<LoadSDNode>(N0))
  11672. return SDValue();
  11673. LoadSDNode *LN0 = cast<LoadSDNode>(N0);
  11674. // Reducing the width of a volatile load is illegal. For atomics, we may be
  11675. // able to reduce the width provided we never widen again. (see D66309)
  11676. if (!LN0->isSimple() ||
  11677. !isLegalNarrowLdSt(LN0, ExtType, ExtVT, ShAmt))
  11678. return SDValue();
  11679. auto AdjustBigEndianShift = [&](unsigned ShAmt) {
  11680. unsigned LVTStoreBits =
  11681. LN0->getMemoryVT().getStoreSizeInBits().getFixedValue();
  11682. unsigned EVTStoreBits = ExtVT.getStoreSizeInBits().getFixedValue();
  11683. return LVTStoreBits - EVTStoreBits - ShAmt;
  11684. };
  11685. // We need to adjust the pointer to the load by ShAmt bits in order to load
  11686. // the correct bytes.
  11687. unsigned PtrAdjustmentInBits =
  11688. DAG.getDataLayout().isBigEndian() ? AdjustBigEndianShift(ShAmt) : ShAmt;
  11689. uint64_t PtrOff = PtrAdjustmentInBits / 8;
  11690. Align NewAlign = commonAlignment(LN0->getAlign(), PtrOff);
  11691. SDLoc DL(LN0);
  11692. // The original load itself didn't wrap, so an offset within it doesn't.
  11693. SDNodeFlags Flags;
  11694. Flags.setNoUnsignedWrap(true);
  11695. SDValue NewPtr = DAG.getMemBasePlusOffset(LN0->getBasePtr(),
  11696. TypeSize::Fixed(PtrOff), DL, Flags);
  11697. AddToWorklist(NewPtr.getNode());
  11698. SDValue Load;
  11699. if (ExtType == ISD::NON_EXTLOAD)
  11700. Load = DAG.getLoad(VT, DL, LN0->getChain(), NewPtr,
  11701. LN0->getPointerInfo().getWithOffset(PtrOff), NewAlign,
  11702. LN0->getMemOperand()->getFlags(), LN0->getAAInfo());
  11703. else
  11704. Load = DAG.getExtLoad(ExtType, DL, VT, LN0->getChain(), NewPtr,
  11705. LN0->getPointerInfo().getWithOffset(PtrOff), ExtVT,
  11706. NewAlign, LN0->getMemOperand()->getFlags(),
  11707. LN0->getAAInfo());
  11708. // Replace the old load's chain with the new load's chain.
  11709. WorklistRemover DeadNodes(*this);
  11710. DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
  11711. // Shift the result left, if we've swallowed a left shift.
  11712. SDValue Result = Load;
  11713. if (ShLeftAmt != 0) {
  11714. EVT ShImmTy = getShiftAmountTy(Result.getValueType());
  11715. if (!isUIntN(ShImmTy.getScalarSizeInBits(), ShLeftAmt))
  11716. ShImmTy = VT;
  11717. // If the shift amount is as large as the result size (but, presumably,
  11718. // no larger than the source) then the useful bits of the result are
  11719. // zero; we can't simply return the shortened shift, because the result
  11720. // of that operation is undefined.
  11721. if (ShLeftAmt >= VT.getScalarSizeInBits())
  11722. Result = DAG.getConstant(0, DL, VT);
  11723. else
  11724. Result = DAG.getNode(ISD::SHL, DL, VT,
  11725. Result, DAG.getConstant(ShLeftAmt, DL, ShImmTy));
  11726. }
  11727. if (HasShiftedOffset) {
  11728. // We're using a shifted mask, so the load now has an offset. This means
  11729. // that data has been loaded into the lower bytes than it would have been
  11730. // before, so we need to shl the loaded data into the correct position in the
  11731. // register.
  11732. SDValue ShiftC = DAG.getConstant(ShAmt, DL, VT);
  11733. Result = DAG.getNode(ISD::SHL, DL, VT, Result, ShiftC);
  11734. DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
  11735. }
  11736. // Return the new loaded value.
  11737. return Result;
  11738. }
  11739. SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
  11740. SDValue N0 = N->getOperand(0);
  11741. SDValue N1 = N->getOperand(1);
  11742. EVT VT = N->getValueType(0);
  11743. EVT ExtVT = cast<VTSDNode>(N1)->getVT();
  11744. unsigned VTBits = VT.getScalarSizeInBits();
  11745. unsigned ExtVTBits = ExtVT.getScalarSizeInBits();
  11746. // sext_vector_inreg(undef) = 0 because the top bit will all be the same.
  11747. if (N0.isUndef())
  11748. return DAG.getConstant(0, SDLoc(N), VT);
  11749. // fold (sext_in_reg c1) -> c1
  11750. if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
  11751. return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
  11752. // If the input is already sign extended, just drop the extension.
  11753. if (ExtVTBits >= DAG.ComputeMaxSignificantBits(N0))
  11754. return N0;
  11755. // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
  11756. if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
  11757. ExtVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
  11758. return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0.getOperand(0),
  11759. N1);
  11760. // fold (sext_in_reg (sext x)) -> (sext x)
  11761. // fold (sext_in_reg (aext x)) -> (sext x)
  11762. // if x is small enough or if we know that x has more than 1 sign bit and the
  11763. // sign_extend_inreg is extending from one of them.
  11764. if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
  11765. SDValue N00 = N0.getOperand(0);
  11766. unsigned N00Bits = N00.getScalarValueSizeInBits();
  11767. if ((N00Bits <= ExtVTBits ||
  11768. DAG.ComputeMaxSignificantBits(N00) <= ExtVTBits) &&
  11769. (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
  11770. return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00);
  11771. }
  11772. // fold (sext_in_reg (*_extend_vector_inreg x)) -> (sext_vector_inreg x)
  11773. // if x is small enough or if we know that x has more than 1 sign bit and the
  11774. // sign_extend_inreg is extending from one of them.
  11775. if (N0.getOpcode() == ISD::ANY_EXTEND_VECTOR_INREG ||
  11776. N0.getOpcode() == ISD::SIGN_EXTEND_VECTOR_INREG ||
  11777. N0.getOpcode() == ISD::ZERO_EXTEND_VECTOR_INREG) {
  11778. SDValue N00 = N0.getOperand(0);
  11779. unsigned N00Bits = N00.getScalarValueSizeInBits();
  11780. unsigned DstElts = N0.getValueType().getVectorMinNumElements();
  11781. unsigned SrcElts = N00.getValueType().getVectorMinNumElements();
  11782. bool IsZext = N0.getOpcode() == ISD::ZERO_EXTEND_VECTOR_INREG;
  11783. APInt DemandedSrcElts = APInt::getLowBitsSet(SrcElts, DstElts);
  11784. if ((N00Bits == ExtVTBits ||
  11785. (!IsZext && (N00Bits < ExtVTBits ||
  11786. DAG.ComputeMaxSignificantBits(N00) <= ExtVTBits))) &&
  11787. (!LegalOperations ||
  11788. TLI.isOperationLegal(ISD::SIGN_EXTEND_VECTOR_INREG, VT)))
  11789. return DAG.getNode(ISD::SIGN_EXTEND_VECTOR_INREG, SDLoc(N), VT, N00);
  11790. }
  11791. // fold (sext_in_reg (zext x)) -> (sext x)
  11792. // iff we are extending the source sign bit.
  11793. if (N0.getOpcode() == ISD::ZERO_EXTEND) {
  11794. SDValue N00 = N0.getOperand(0);
  11795. if (N00.getScalarValueSizeInBits() == ExtVTBits &&
  11796. (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
  11797. return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
  11798. }
  11799. // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
  11800. if (DAG.MaskedValueIsZero(N0, APInt::getOneBitSet(VTBits, ExtVTBits - 1)))
  11801. return DAG.getZeroExtendInReg(N0, SDLoc(N), ExtVT);
  11802. // fold operands of sext_in_reg based on knowledge that the top bits are not
  11803. // demanded.
  11804. if (SimplifyDemandedBits(SDValue(N, 0)))
  11805. return SDValue(N, 0);
  11806. // fold (sext_in_reg (load x)) -> (smaller sextload x)
  11807. // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
  11808. if (SDValue NarrowLoad = reduceLoadWidth(N))
  11809. return NarrowLoad;
  11810. // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
  11811. // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
  11812. // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
  11813. if (N0.getOpcode() == ISD::SRL) {
  11814. if (auto *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
  11815. if (ShAmt->getAPIntValue().ule(VTBits - ExtVTBits)) {
  11816. // We can turn this into an SRA iff the input to the SRL is already sign
  11817. // extended enough.
  11818. unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
  11819. if (((VTBits - ExtVTBits) - ShAmt->getZExtValue()) < InSignBits)
  11820. return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0.getOperand(0),
  11821. N0.getOperand(1));
  11822. }
  11823. }
  11824. // fold (sext_inreg (extload x)) -> (sextload x)
  11825. // If sextload is not supported by target, we can only do the combine when
  11826. // load has one use. Doing otherwise can block folding the extload with other
  11827. // extends that the target does support.
  11828. if (ISD::isEXTLoad(N0.getNode()) &&
  11829. ISD::isUNINDEXEDLoad(N0.getNode()) &&
  11830. ExtVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
  11831. ((!LegalOperations && cast<LoadSDNode>(N0)->isSimple() &&
  11832. N0.hasOneUse()) ||
  11833. TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, ExtVT))) {
  11834. LoadSDNode *LN0 = cast<LoadSDNode>(N0);
  11835. SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
  11836. LN0->getChain(),
  11837. LN0->getBasePtr(), ExtVT,
  11838. LN0->getMemOperand());
  11839. CombineTo(N, ExtLoad);
  11840. CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
  11841. AddToWorklist(ExtLoad.getNode());
  11842. return SDValue(N, 0); // Return N so it doesn't get rechecked!
  11843. }
  11844. // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
  11845. if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
  11846. N0.hasOneUse() &&
  11847. ExtVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
  11848. ((!LegalOperations && cast<LoadSDNode>(N0)->isSimple()) &&
  11849. TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, ExtVT))) {
  11850. LoadSDNode *LN0 = cast<LoadSDNode>(N0);
  11851. SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
  11852. LN0->getChain(),
  11853. LN0->getBasePtr(), ExtVT,
  11854. LN0->getMemOperand());
  11855. CombineTo(N, ExtLoad);
  11856. CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
  11857. return SDValue(N, 0); // Return N so it doesn't get rechecked!
  11858. }
  11859. // fold (sext_inreg (masked_load x)) -> (sext_masked_load x)
  11860. // ignore it if the masked load is already sign extended
  11861. if (MaskedLoadSDNode *Ld = dyn_cast<MaskedLoadSDNode>(N0)) {
  11862. if (ExtVT == Ld->getMemoryVT() && N0.hasOneUse() &&
  11863. Ld->getExtensionType() != ISD::LoadExtType::NON_EXTLOAD &&
  11864. TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, ExtVT)) {
  11865. SDValue ExtMaskedLoad = DAG.getMaskedLoad(
  11866. VT, SDLoc(N), Ld->getChain(), Ld->getBasePtr(), Ld->getOffset(),
  11867. Ld->getMask(), Ld->getPassThru(), ExtVT, Ld->getMemOperand(),
  11868. Ld->getAddressingMode(), ISD::SEXTLOAD, Ld->isExpandingLoad());
  11869. CombineTo(N, ExtMaskedLoad);
  11870. CombineTo(N0.getNode(), ExtMaskedLoad, ExtMaskedLoad.getValue(1));
  11871. return SDValue(N, 0); // Return N so it doesn't get rechecked!
  11872. }
  11873. }
  11874. // fold (sext_inreg (masked_gather x)) -> (sext_masked_gather x)
  11875. if (auto *GN0 = dyn_cast<MaskedGatherSDNode>(N0)) {
  11876. if (SDValue(GN0, 0).hasOneUse() &&
  11877. ExtVT == GN0->getMemoryVT() &&
  11878. TLI.isVectorLoadExtDesirable(SDValue(SDValue(GN0, 0)))) {
  11879. SDValue Ops[] = {GN0->getChain(), GN0->getPassThru(), GN0->getMask(),
  11880. GN0->getBasePtr(), GN0->getIndex(), GN0->getScale()};
  11881. SDValue ExtLoad = DAG.getMaskedGather(
  11882. DAG.getVTList(VT, MVT::Other), ExtVT, SDLoc(N), Ops,
  11883. GN0->getMemOperand(), GN0->getIndexType(), ISD::SEXTLOAD);
  11884. CombineTo(N, ExtLoad);
  11885. CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
  11886. AddToWorklist(ExtLoad.getNode());
  11887. return SDValue(N, 0); // Return N so it doesn't get rechecked!
  11888. }
  11889. }
  11890. // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
  11891. if (ExtVTBits <= 16 && N0.getOpcode() == ISD::OR) {
  11892. if (SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
  11893. N0.getOperand(1), false))
  11894. return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, BSwap, N1);
  11895. }
  11896. // Fold (iM_signext_inreg
  11897. // (extract_subvector (zext|anyext|sext iN_v to _) _)
  11898. // from iN)
  11899. // -> (extract_subvector (signext iN_v to iM))
  11900. if (N0.getOpcode() == ISD::EXTRACT_SUBVECTOR && N0.hasOneUse() &&
  11901. ISD::isExtOpcode(N0.getOperand(0).getOpcode())) {
  11902. SDValue InnerExt = N0.getOperand(0);
  11903. EVT InnerExtVT = InnerExt->getValueType(0);
  11904. SDValue Extendee = InnerExt->getOperand(0);
  11905. if (ExtVTBits == Extendee.getValueType().getScalarSizeInBits() &&
  11906. (!LegalOperations ||
  11907. TLI.isOperationLegal(ISD::SIGN_EXTEND, InnerExtVT))) {
  11908. SDValue SignExtExtendee =
  11909. DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), InnerExtVT, Extendee);
  11910. return DAG.getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(N), VT, SignExtExtendee,
  11911. N0.getOperand(1));
  11912. }
  11913. }
  11914. return SDValue();
  11915. }
  11916. static SDValue
  11917. foldExtendVectorInregToExtendOfSubvector(SDNode *N, const TargetLowering &TLI,
  11918. SelectionDAG &DAG,
  11919. bool LegalOperations) {
  11920. unsigned InregOpcode = N->getOpcode();
  11921. unsigned Opcode = DAG.getOpcode_EXTEND(InregOpcode);
  11922. SDValue Src = N->getOperand(0);
  11923. EVT VT = N->getValueType(0);
  11924. EVT SrcVT = EVT::getVectorVT(*DAG.getContext(),
  11925. Src.getValueType().getVectorElementType(),
  11926. VT.getVectorElementCount());
  11927. assert((InregOpcode == ISD::SIGN_EXTEND_VECTOR_INREG ||
  11928. InregOpcode == ISD::ZERO_EXTEND_VECTOR_INREG ||
  11929. InregOpcode == ISD::ANY_EXTEND_VECTOR_INREG) &&
  11930. "Expected EXTEND_VECTOR_INREG dag node in input!");
  11931. // Profitability check: our operand must be an one-use CONCAT_VECTORS.
  11932. // FIXME: one-use check may be overly restrictive
  11933. if (!Src.hasOneUse() || Src.getOpcode() != ISD::CONCAT_VECTORS)
  11934. return SDValue();
  11935. // Profitability check: we must be extending exactly one of it's operands.
  11936. // FIXME: this is probably overly restrictive.
  11937. Src = Src.getOperand(0);
  11938. if (Src.getValueType() != SrcVT)
  11939. return SDValue();
  11940. if (LegalOperations && !TLI.isOperationLegal(Opcode, VT))
  11941. return SDValue();
  11942. return DAG.getNode(Opcode, SDLoc(N), VT, Src);
  11943. }
  11944. SDValue DAGCombiner::visitEXTEND_VECTOR_INREG(SDNode *N) {
  11945. SDValue N0 = N->getOperand(0);
  11946. EVT VT = N->getValueType(0);
  11947. if (N0.isUndef()) {
  11948. // aext_vector_inreg(undef) = undef because the top bits are undefined.
  11949. // {s/z}ext_vector_inreg(undef) = 0 because the top bits must be the same.
  11950. return N->getOpcode() == ISD::ANY_EXTEND_VECTOR_INREG
  11951. ? DAG.getUNDEF(VT)
  11952. : DAG.getConstant(0, SDLoc(N), VT);
  11953. }
  11954. if (SDValue Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes))
  11955. return Res;
  11956. if (SimplifyDemandedVectorElts(SDValue(N, 0)))
  11957. return SDValue(N, 0);
  11958. if (SDValue R = foldExtendVectorInregToExtendOfSubvector(N, TLI, DAG,
  11959. LegalOperations))
  11960. return R;
  11961. return SDValue();
  11962. }
  11963. SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
  11964. SDValue N0 = N->getOperand(0);
  11965. EVT VT = N->getValueType(0);
  11966. EVT SrcVT = N0.getValueType();
  11967. bool isLE = DAG.getDataLayout().isLittleEndian();
  11968. // noop truncate
  11969. if (SrcVT == VT)
  11970. return N0;
  11971. // fold (truncate (truncate x)) -> (truncate x)
  11972. if (N0.getOpcode() == ISD::TRUNCATE)
  11973. return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
  11974. // fold (truncate c1) -> c1
  11975. if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) {
  11976. SDValue C = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
  11977. if (C.getNode() != N)
  11978. return C;
  11979. }
  11980. // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
  11981. if (N0.getOpcode() == ISD::ZERO_EXTEND ||
  11982. N0.getOpcode() == ISD::SIGN_EXTEND ||
  11983. N0.getOpcode() == ISD::ANY_EXTEND) {
  11984. // if the source is smaller than the dest, we still need an extend.
  11985. if (N0.getOperand(0).getValueType().bitsLT(VT))
  11986. return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
  11987. // if the source is larger than the dest, than we just need the truncate.
  11988. if (N0.getOperand(0).getValueType().bitsGT(VT))
  11989. return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
  11990. // if the source and dest are the same type, we can drop both the extend
  11991. // and the truncate.
  11992. return N0.getOperand(0);
  11993. }
  11994. // Try to narrow a truncate-of-sext_in_reg to the destination type:
  11995. // trunc (sign_ext_inreg X, iM) to iN --> sign_ext_inreg (trunc X to iN), iM
  11996. if (!LegalTypes && N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
  11997. N0.hasOneUse()) {
  11998. SDValue X = N0.getOperand(0);
  11999. SDValue ExtVal = N0.getOperand(1);
  12000. EVT ExtVT = cast<VTSDNode>(ExtVal)->getVT();
  12001. if (ExtVT.bitsLT(VT)) {
  12002. SDValue TrX = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
  12003. return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, TrX, ExtVal);
  12004. }
  12005. }
  12006. // If this is anyext(trunc), don't fold it, allow ourselves to be folded.
  12007. if (N->hasOneUse() && (N->use_begin()->getOpcode() == ISD::ANY_EXTEND))
  12008. return SDValue();
  12009. // Fold extract-and-trunc into a narrow extract. For example:
  12010. // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
  12011. // i32 y = TRUNCATE(i64 x)
  12012. // -- becomes --
  12013. // v16i8 b = BITCAST (v2i64 val)
  12014. // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
  12015. //
  12016. // Note: We only run this optimization after type legalization (which often
  12017. // creates this pattern) and before operation legalization after which
  12018. // we need to be more careful about the vector instructions that we generate.
  12019. if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
  12020. LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
  12021. EVT VecTy = N0.getOperand(0).getValueType();
  12022. EVT ExTy = N0.getValueType();
  12023. EVT TrTy = N->getValueType(0);
  12024. auto EltCnt = VecTy.getVectorElementCount();
  12025. unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
  12026. auto NewEltCnt = EltCnt * SizeRatio;
  12027. EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, NewEltCnt);
  12028. assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
  12029. SDValue EltNo = N0->getOperand(1);
  12030. if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
  12031. int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
  12032. int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
  12033. SDLoc DL(N);
  12034. return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, TrTy,
  12035. DAG.getBitcast(NVT, N0.getOperand(0)),
  12036. DAG.getVectorIdxConstant(Index, DL));
  12037. }
  12038. }
  12039. // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
  12040. if (N0.getOpcode() == ISD::SELECT && N0.hasOneUse()) {
  12041. if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
  12042. TLI.isTruncateFree(SrcVT, VT)) {
  12043. SDLoc SL(N0);
  12044. SDValue Cond = N0.getOperand(0);
  12045. SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
  12046. SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
  12047. return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
  12048. }
  12049. }
  12050. // trunc (shl x, K) -> shl (trunc x), K => K < VT.getScalarSizeInBits()
  12051. if (N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
  12052. (!LegalOperations || TLI.isOperationLegal(ISD::SHL, VT)) &&
  12053. TLI.isTypeDesirableForOp(ISD::SHL, VT)) {
  12054. SDValue Amt = N0.getOperand(1);
  12055. KnownBits Known = DAG.computeKnownBits(Amt);
  12056. unsigned Size = VT.getScalarSizeInBits();
  12057. if (Known.countMaxActiveBits() <= Log2_32(Size)) {
  12058. SDLoc SL(N);
  12059. EVT AmtVT = TLI.getShiftAmountTy(VT, DAG.getDataLayout());
  12060. SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(0));
  12061. if (AmtVT != Amt.getValueType()) {
  12062. Amt = DAG.getZExtOrTrunc(Amt, SL, AmtVT);
  12063. AddToWorklist(Amt.getNode());
  12064. }
  12065. return DAG.getNode(ISD::SHL, SL, VT, Trunc, Amt);
  12066. }
  12067. }
  12068. if (SDValue V = foldSubToUSubSat(VT, N0.getNode()))
  12069. return V;
  12070. // Attempt to pre-truncate BUILD_VECTOR sources.
  12071. if (N0.getOpcode() == ISD::BUILD_VECTOR && !LegalOperations &&
  12072. TLI.isTruncateFree(SrcVT.getScalarType(), VT.getScalarType()) &&
  12073. // Avoid creating illegal types if running after type legalizer.
  12074. (!LegalTypes || TLI.isTypeLegal(VT.getScalarType()))) {
  12075. SDLoc DL(N);
  12076. EVT SVT = VT.getScalarType();
  12077. SmallVector<SDValue, 8> TruncOps;
  12078. for (const SDValue &Op : N0->op_values()) {
  12079. SDValue TruncOp = DAG.getNode(ISD::TRUNCATE, DL, SVT, Op);
  12080. TruncOps.push_back(TruncOp);
  12081. }
  12082. return DAG.getBuildVector(VT, DL, TruncOps);
  12083. }
  12084. // Fold a series of buildvector, bitcast, and truncate if possible.
  12085. // For example fold
  12086. // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
  12087. // (2xi32 (buildvector x, y)).
  12088. if (Level == AfterLegalizeVectorOps && VT.isVector() &&
  12089. N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
  12090. N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
  12091. N0.getOperand(0).hasOneUse()) {
  12092. SDValue BuildVect = N0.getOperand(0);
  12093. EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
  12094. EVT TruncVecEltTy = VT.getVectorElementType();
  12095. // Check that the element types match.
  12096. if (BuildVectEltTy == TruncVecEltTy) {
  12097. // Now we only need to compute the offset of the truncated elements.
  12098. unsigned BuildVecNumElts = BuildVect.getNumOperands();
  12099. unsigned TruncVecNumElts = VT.getVectorNumElements();
  12100. unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
  12101. assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
  12102. "Invalid number of elements");
  12103. SmallVector<SDValue, 8> Opnds;
  12104. for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
  12105. Opnds.push_back(BuildVect.getOperand(i));
  12106. return DAG.getBuildVector(VT, SDLoc(N), Opnds);
  12107. }
  12108. }
  12109. // fold (truncate (load x)) -> (smaller load x)
  12110. // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
  12111. if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
  12112. if (SDValue Reduced = reduceLoadWidth(N))
  12113. return Reduced;
  12114. // Handle the case where the load remains an extending load even
  12115. // after truncation.
  12116. if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
  12117. LoadSDNode *LN0 = cast<LoadSDNode>(N0);
  12118. if (LN0->isSimple() && LN0->getMemoryVT().bitsLT(VT)) {
  12119. SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
  12120. VT, LN0->getChain(), LN0->getBasePtr(),
  12121. LN0->getMemoryVT(),
  12122. LN0->getMemOperand());
  12123. DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
  12124. return NewLoad;
  12125. }
  12126. }
  12127. }
  12128. // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
  12129. // where ... are all 'undef'.
  12130. if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
  12131. SmallVector<EVT, 8> VTs;
  12132. SDValue V;
  12133. unsigned Idx = 0;
  12134. unsigned NumDefs = 0;
  12135. for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
  12136. SDValue X = N0.getOperand(i);
  12137. if (!X.isUndef()) {
  12138. V = X;
  12139. Idx = i;
  12140. NumDefs++;
  12141. }
  12142. // Stop if more than one members are non-undef.
  12143. if (NumDefs > 1)
  12144. break;
  12145. VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
  12146. VT.getVectorElementType(),
  12147. X.getValueType().getVectorElementCount()));
  12148. }
  12149. if (NumDefs == 0)
  12150. return DAG.getUNDEF(VT);
  12151. if (NumDefs == 1) {
  12152. assert(V.getNode() && "The single defined operand is empty!");
  12153. SmallVector<SDValue, 8> Opnds;
  12154. for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
  12155. if (i != Idx) {
  12156. Opnds.push_back(DAG.getUNDEF(VTs[i]));
  12157. continue;
  12158. }
  12159. SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
  12160. AddToWorklist(NV.getNode());
  12161. Opnds.push_back(NV);
  12162. }
  12163. return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
  12164. }
  12165. }
  12166. // Fold truncate of a bitcast of a vector to an extract of the low vector
  12167. // element.
  12168. //
  12169. // e.g. trunc (i64 (bitcast v2i32:x)) -> extract_vector_elt v2i32:x, idx
  12170. if (N0.getOpcode() == ISD::BITCAST && !VT.isVector()) {
  12171. SDValue VecSrc = N0.getOperand(0);
  12172. EVT VecSrcVT = VecSrc.getValueType();
  12173. if (VecSrcVT.isVector() && VecSrcVT.getScalarType() == VT &&
  12174. (!LegalOperations ||
  12175. TLI.isOperationLegal(ISD::EXTRACT_VECTOR_ELT, VecSrcVT))) {
  12176. SDLoc SL(N);
  12177. unsigned Idx = isLE ? 0 : VecSrcVT.getVectorNumElements() - 1;
  12178. return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, VT, VecSrc,
  12179. DAG.getVectorIdxConstant(Idx, SL));
  12180. }
  12181. }
  12182. // Simplify the operands using demanded-bits information.
  12183. if (SimplifyDemandedBits(SDValue(N, 0)))
  12184. return SDValue(N, 0);
  12185. // fold (truncate (extract_subvector(ext x))) ->
  12186. // (extract_subvector x)
  12187. // TODO: This can be generalized to cover cases where the truncate and extract
  12188. // do not fully cancel each other out.
  12189. if (!LegalTypes && N0.getOpcode() == ISD::EXTRACT_SUBVECTOR) {
  12190. SDValue N00 = N0.getOperand(0);
  12191. if (N00.getOpcode() == ISD::SIGN_EXTEND ||
  12192. N00.getOpcode() == ISD::ZERO_EXTEND ||
  12193. N00.getOpcode() == ISD::ANY_EXTEND) {
  12194. if (N00.getOperand(0)->getValueType(0).getVectorElementType() ==
  12195. VT.getVectorElementType())
  12196. return DAG.getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(N0->getOperand(0)), VT,
  12197. N00.getOperand(0), N0.getOperand(1));
  12198. }
  12199. }
  12200. if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N))
  12201. return NewVSel;
  12202. // Narrow a suitable binary operation with a non-opaque constant operand by
  12203. // moving it ahead of the truncate. This is limited to pre-legalization
  12204. // because targets may prefer a wider type during later combines and invert
  12205. // this transform.
  12206. switch (N0.getOpcode()) {
  12207. case ISD::ADD:
  12208. case ISD::SUB:
  12209. case ISD::MUL:
  12210. case ISD::AND:
  12211. case ISD::OR:
  12212. case ISD::XOR:
  12213. if (!LegalOperations && N0.hasOneUse() &&
  12214. (isConstantOrConstantVector(N0.getOperand(0), true) ||
  12215. isConstantOrConstantVector(N0.getOperand(1), true))) {
  12216. // TODO: We already restricted this to pre-legalization, but for vectors
  12217. // we are extra cautious to not create an unsupported operation.
  12218. // Target-specific changes are likely needed to avoid regressions here.
  12219. if (VT.isScalarInteger() || TLI.isOperationLegal(N0.getOpcode(), VT)) {
  12220. SDLoc DL(N);
  12221. SDValue NarrowL = DAG.getNode(ISD::TRUNCATE, DL, VT, N0.getOperand(0));
  12222. SDValue NarrowR = DAG.getNode(ISD::TRUNCATE, DL, VT, N0.getOperand(1));
  12223. return DAG.getNode(N0.getOpcode(), DL, VT, NarrowL, NarrowR);
  12224. }
  12225. }
  12226. break;
  12227. case ISD::ADDE:
  12228. case ISD::ADDCARRY:
  12229. // (trunc adde(X, Y, Carry)) -> (adde trunc(X), trunc(Y), Carry)
  12230. // (trunc addcarry(X, Y, Carry)) -> (addcarry trunc(X), trunc(Y), Carry)
  12231. // When the adde's carry is not used.
  12232. // We only do for addcarry before legalize operation
  12233. if (((!LegalOperations && N0.getOpcode() == ISD::ADDCARRY) ||
  12234. TLI.isOperationLegal(N0.getOpcode(), VT)) &&
  12235. N0.hasOneUse() && !N0->hasAnyUseOfValue(1)) {
  12236. SDLoc DL(N);
  12237. SDValue X = DAG.getNode(ISD::TRUNCATE, DL, VT, N0.getOperand(0));
  12238. SDValue Y = DAG.getNode(ISD::TRUNCATE, DL, VT, N0.getOperand(1));
  12239. SDVTList VTs = DAG.getVTList(VT, N0->getValueType(1));
  12240. return DAG.getNode(N0.getOpcode(), DL, VTs, X, Y, N0.getOperand(2));
  12241. }
  12242. break;
  12243. case ISD::USUBSAT:
  12244. // Truncate the USUBSAT only if LHS is a known zero-extension, its not
  12245. // enough to know that the upper bits are zero we must ensure that we don't
  12246. // introduce an extra truncate.
  12247. if (!LegalOperations && N0.hasOneUse() &&
  12248. N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
  12249. N0.getOperand(0).getOperand(0).getScalarValueSizeInBits() <=
  12250. VT.getScalarSizeInBits() &&
  12251. hasOperation(N0.getOpcode(), VT)) {
  12252. return getTruncatedUSUBSAT(VT, SrcVT, N0.getOperand(0), N0.getOperand(1),
  12253. DAG, SDLoc(N));
  12254. }
  12255. break;
  12256. }
  12257. return SDValue();
  12258. }
  12259. static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
  12260. SDValue Elt = N->getOperand(i);
  12261. if (Elt.getOpcode() != ISD::MERGE_VALUES)
  12262. return Elt.getNode();
  12263. return Elt.getOperand(Elt.getResNo()).getNode();
  12264. }
  12265. /// build_pair (load, load) -> load
  12266. /// if load locations are consecutive.
  12267. SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
  12268. assert(N->getOpcode() == ISD::BUILD_PAIR);
  12269. auto *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
  12270. auto *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
  12271. // A BUILD_PAIR is always having the least significant part in elt 0 and the
  12272. // most significant part in elt 1. So when combining into one large load, we
  12273. // need to consider the endianness.
  12274. if (DAG.getDataLayout().isBigEndian())
  12275. std::swap(LD1, LD2);
  12276. if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !ISD::isNON_EXTLoad(LD2) ||
  12277. !LD1->hasOneUse() || !LD2->hasOneUse() ||
  12278. LD1->getAddressSpace() != LD2->getAddressSpace())
  12279. return SDValue();
  12280. unsigned LD1Fast = 0;
  12281. EVT LD1VT = LD1->getValueType(0);
  12282. unsigned LD1Bytes = LD1VT.getStoreSize();
  12283. if ((!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
  12284. DAG.areNonVolatileConsecutiveLoads(LD2, LD1, LD1Bytes, 1) &&
  12285. TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT,
  12286. *LD1->getMemOperand(), &LD1Fast) && LD1Fast)
  12287. return DAG.getLoad(VT, SDLoc(N), LD1->getChain(), LD1->getBasePtr(),
  12288. LD1->getPointerInfo(), LD1->getAlign());
  12289. return SDValue();
  12290. }
  12291. static unsigned getPPCf128HiElementSelector(const SelectionDAG &DAG) {
  12292. // On little-endian machines, bitcasting from ppcf128 to i128 does swap the Hi
  12293. // and Lo parts; on big-endian machines it doesn't.
  12294. return DAG.getDataLayout().isBigEndian() ? 1 : 0;
  12295. }
  12296. static SDValue foldBitcastedFPLogic(SDNode *N, SelectionDAG &DAG,
  12297. const TargetLowering &TLI) {
  12298. // If this is not a bitcast to an FP type or if the target doesn't have
  12299. // IEEE754-compliant FP logic, we're done.
  12300. EVT VT = N->getValueType(0);
  12301. if (!VT.isFloatingPoint() || !TLI.hasBitPreservingFPLogic(VT))
  12302. return SDValue();
  12303. // TODO: Handle cases where the integer constant is a different scalar
  12304. // bitwidth to the FP.
  12305. SDValue N0 = N->getOperand(0);
  12306. EVT SourceVT = N0.getValueType();
  12307. if (VT.getScalarSizeInBits() != SourceVT.getScalarSizeInBits())
  12308. return SDValue();
  12309. unsigned FPOpcode;
  12310. APInt SignMask;
  12311. switch (N0.getOpcode()) {
  12312. case ISD::AND:
  12313. FPOpcode = ISD::FABS;
  12314. SignMask = ~APInt::getSignMask(SourceVT.getScalarSizeInBits());
  12315. break;
  12316. case ISD::XOR:
  12317. FPOpcode = ISD::FNEG;
  12318. SignMask = APInt::getSignMask(SourceVT.getScalarSizeInBits());
  12319. break;
  12320. case ISD::OR:
  12321. FPOpcode = ISD::FABS;
  12322. SignMask = APInt::getSignMask(SourceVT.getScalarSizeInBits());
  12323. break;
  12324. default:
  12325. return SDValue();
  12326. }
  12327. // Fold (bitcast int (and (bitcast fp X to int), 0x7fff...) to fp) -> fabs X
  12328. // Fold (bitcast int (xor (bitcast fp X to int), 0x8000...) to fp) -> fneg X
  12329. // Fold (bitcast int (or (bitcast fp X to int), 0x8000...) to fp) ->
  12330. // fneg (fabs X)
  12331. SDValue LogicOp0 = N0.getOperand(0);
  12332. ConstantSDNode *LogicOp1 = isConstOrConstSplat(N0.getOperand(1), true);
  12333. if (LogicOp1 && LogicOp1->getAPIntValue() == SignMask &&
  12334. LogicOp0.getOpcode() == ISD::BITCAST &&
  12335. LogicOp0.getOperand(0).getValueType() == VT) {
  12336. SDValue FPOp = DAG.getNode(FPOpcode, SDLoc(N), VT, LogicOp0.getOperand(0));
  12337. NumFPLogicOpsConv++;
  12338. if (N0.getOpcode() == ISD::OR)
  12339. return DAG.getNode(ISD::FNEG, SDLoc(N), VT, FPOp);
  12340. return FPOp;
  12341. }
  12342. return SDValue();
  12343. }
  12344. SDValue DAGCombiner::visitBITCAST(SDNode *N) {
  12345. SDValue N0 = N->getOperand(0);
  12346. EVT VT = N->getValueType(0);
  12347. if (N0.isUndef())
  12348. return DAG.getUNDEF(VT);
  12349. // If the input is a BUILD_VECTOR with all constant elements, fold this now.
  12350. // Only do this before legalize types, unless both types are integer and the
  12351. // scalar type is legal. Only do this before legalize ops, since the target
  12352. // maybe depending on the bitcast.
  12353. // First check to see if this is all constant.
  12354. // TODO: Support FP bitcasts after legalize types.
  12355. if (VT.isVector() &&
  12356. (!LegalTypes ||
  12357. (!LegalOperations && VT.isInteger() && N0.getValueType().isInteger() &&
  12358. TLI.isTypeLegal(VT.getVectorElementType()))) &&
  12359. N0.getOpcode() == ISD::BUILD_VECTOR && N0->hasOneUse() &&
  12360. cast<BuildVectorSDNode>(N0)->isConstant())
  12361. return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(),
  12362. VT.getVectorElementType());
  12363. // If the input is a constant, let getNode fold it.
  12364. if (isIntOrFPConstant(N0)) {
  12365. // If we can't allow illegal operations, we need to check that this is just
  12366. // a fp -> int or int -> conversion and that the resulting operation will
  12367. // be legal.
  12368. if (!LegalOperations ||
  12369. (isa<ConstantSDNode>(N0) && VT.isFloatingPoint() && !VT.isVector() &&
  12370. TLI.isOperationLegal(ISD::ConstantFP, VT)) ||
  12371. (isa<ConstantFPSDNode>(N0) && VT.isInteger() && !VT.isVector() &&
  12372. TLI.isOperationLegal(ISD::Constant, VT))) {
  12373. SDValue C = DAG.getBitcast(VT, N0);
  12374. if (C.getNode() != N)
  12375. return C;
  12376. }
  12377. }
  12378. // (conv (conv x, t1), t2) -> (conv x, t2)
  12379. if (N0.getOpcode() == ISD::BITCAST)
  12380. return DAG.getBitcast(VT, N0.getOperand(0));
  12381. // fold (conv (load x)) -> (load (conv*)x)
  12382. // If the resultant load doesn't need a higher alignment than the original!
  12383. if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
  12384. // Do not remove the cast if the types differ in endian layout.
  12385. TLI.hasBigEndianPartOrdering(N0.getValueType(), DAG.getDataLayout()) ==
  12386. TLI.hasBigEndianPartOrdering(VT, DAG.getDataLayout()) &&
  12387. // If the load is volatile, we only want to change the load type if the
  12388. // resulting load is legal. Otherwise we might increase the number of
  12389. // memory accesses. We don't care if the original type was legal or not
  12390. // as we assume software couldn't rely on the number of accesses of an
  12391. // illegal type.
  12392. ((!LegalOperations && cast<LoadSDNode>(N0)->isSimple()) ||
  12393. TLI.isOperationLegal(ISD::LOAD, VT))) {
  12394. LoadSDNode *LN0 = cast<LoadSDNode>(N0);
  12395. if (TLI.isLoadBitCastBeneficial(N0.getValueType(), VT, DAG,
  12396. *LN0->getMemOperand())) {
  12397. SDValue Load =
  12398. DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(),
  12399. LN0->getPointerInfo(), LN0->getAlign(),
  12400. LN0->getMemOperand()->getFlags(), LN0->getAAInfo());
  12401. DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
  12402. return Load;
  12403. }
  12404. }
  12405. if (SDValue V = foldBitcastedFPLogic(N, DAG, TLI))
  12406. return V;
  12407. // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
  12408. // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
  12409. //
  12410. // For ppc_fp128:
  12411. // fold (bitcast (fneg x)) ->
  12412. // flipbit = signbit
  12413. // (xor (bitcast x) (build_pair flipbit, flipbit))
  12414. //
  12415. // fold (bitcast (fabs x)) ->
  12416. // flipbit = (and (extract_element (bitcast x), 0), signbit)
  12417. // (xor (bitcast x) (build_pair flipbit, flipbit))
  12418. // This often reduces constant pool loads.
  12419. if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
  12420. (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
  12421. N0->hasOneUse() && VT.isInteger() && !VT.isVector() &&
  12422. !N0.getValueType().isVector()) {
  12423. SDValue NewConv = DAG.getBitcast(VT, N0.getOperand(0));
  12424. AddToWorklist(NewConv.getNode());
  12425. SDLoc DL(N);
  12426. if (N0.getValueType() == MVT::ppcf128 && !LegalTypes) {
  12427. assert(VT.getSizeInBits() == 128);
  12428. SDValue SignBit = DAG.getConstant(
  12429. APInt::getSignMask(VT.getSizeInBits() / 2), SDLoc(N0), MVT::i64);
  12430. SDValue FlipBit;
  12431. if (N0.getOpcode() == ISD::FNEG) {
  12432. FlipBit = SignBit;
  12433. AddToWorklist(FlipBit.getNode());
  12434. } else {
  12435. assert(N0.getOpcode() == ISD::FABS);
  12436. SDValue Hi =
  12437. DAG.getNode(ISD::EXTRACT_ELEMENT, SDLoc(NewConv), MVT::i64, NewConv,
  12438. DAG.getIntPtrConstant(getPPCf128HiElementSelector(DAG),
  12439. SDLoc(NewConv)));
  12440. AddToWorklist(Hi.getNode());
  12441. FlipBit = DAG.getNode(ISD::AND, SDLoc(N0), MVT::i64, Hi, SignBit);
  12442. AddToWorklist(FlipBit.getNode());
  12443. }
  12444. SDValue FlipBits =
  12445. DAG.getNode(ISD::BUILD_PAIR, SDLoc(N0), VT, FlipBit, FlipBit);
  12446. AddToWorklist(FlipBits.getNode());
  12447. return DAG.getNode(ISD::XOR, DL, VT, NewConv, FlipBits);
  12448. }
  12449. APInt SignBit = APInt::getSignMask(VT.getSizeInBits());
  12450. if (N0.getOpcode() == ISD::FNEG)
  12451. return DAG.getNode(ISD::XOR, DL, VT,
  12452. NewConv, DAG.getConstant(SignBit, DL, VT));
  12453. assert(N0.getOpcode() == ISD::FABS);
  12454. return DAG.getNode(ISD::AND, DL, VT,
  12455. NewConv, DAG.getConstant(~SignBit, DL, VT));
  12456. }
  12457. // fold (bitconvert (fcopysign cst, x)) ->
  12458. // (or (and (bitconvert x), sign), (and cst, (not sign)))
  12459. // Note that we don't handle (copysign x, cst) because this can always be
  12460. // folded to an fneg or fabs.
  12461. //
  12462. // For ppc_fp128:
  12463. // fold (bitcast (fcopysign cst, x)) ->
  12464. // flipbit = (and (extract_element
  12465. // (xor (bitcast cst), (bitcast x)), 0),
  12466. // signbit)
  12467. // (xor (bitcast cst) (build_pair flipbit, flipbit))
  12468. if (N0.getOpcode() == ISD::FCOPYSIGN && N0->hasOneUse() &&
  12469. isa<ConstantFPSDNode>(N0.getOperand(0)) && VT.isInteger() &&
  12470. !VT.isVector()) {
  12471. unsigned OrigXWidth = N0.getOperand(1).getValueSizeInBits();
  12472. EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
  12473. if (isTypeLegal(IntXVT)) {
  12474. SDValue X = DAG.getBitcast(IntXVT, N0.getOperand(1));
  12475. AddToWorklist(X.getNode());
  12476. // If X has a different width than the result/lhs, sext it or truncate it.
  12477. unsigned VTWidth = VT.getSizeInBits();
  12478. if (OrigXWidth < VTWidth) {
  12479. X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
  12480. AddToWorklist(X.getNode());
  12481. } else if (OrigXWidth > VTWidth) {
  12482. // To get the sign bit in the right place, we have to shift it right
  12483. // before truncating.
  12484. SDLoc DL(X);
  12485. X = DAG.getNode(ISD::SRL, DL,
  12486. X.getValueType(), X,
  12487. DAG.getConstant(OrigXWidth-VTWidth, DL,
  12488. X.getValueType()));
  12489. AddToWorklist(X.getNode());
  12490. X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
  12491. AddToWorklist(X.getNode());
  12492. }
  12493. if (N0.getValueType() == MVT::ppcf128 && !LegalTypes) {
  12494. APInt SignBit = APInt::getSignMask(VT.getSizeInBits() / 2);
  12495. SDValue Cst = DAG.getBitcast(VT, N0.getOperand(0));
  12496. AddToWorklist(Cst.getNode());
  12497. SDValue X = DAG.getBitcast(VT, N0.getOperand(1));
  12498. AddToWorklist(X.getNode());
  12499. SDValue XorResult = DAG.getNode(ISD::XOR, SDLoc(N0), VT, Cst, X);
  12500. AddToWorklist(XorResult.getNode());
  12501. SDValue XorResult64 = DAG.getNode(
  12502. ISD::EXTRACT_ELEMENT, SDLoc(XorResult), MVT::i64, XorResult,
  12503. DAG.getIntPtrConstant(getPPCf128HiElementSelector(DAG),
  12504. SDLoc(XorResult)));
  12505. AddToWorklist(XorResult64.getNode());
  12506. SDValue FlipBit =
  12507. DAG.getNode(ISD::AND, SDLoc(XorResult64), MVT::i64, XorResult64,
  12508. DAG.getConstant(SignBit, SDLoc(XorResult64), MVT::i64));
  12509. AddToWorklist(FlipBit.getNode());
  12510. SDValue FlipBits =
  12511. DAG.getNode(ISD::BUILD_PAIR, SDLoc(N0), VT, FlipBit, FlipBit);
  12512. AddToWorklist(FlipBits.getNode());
  12513. return DAG.getNode(ISD::XOR, SDLoc(N), VT, Cst, FlipBits);
  12514. }
  12515. APInt SignBit = APInt::getSignMask(VT.getSizeInBits());
  12516. X = DAG.getNode(ISD::AND, SDLoc(X), VT,
  12517. X, DAG.getConstant(SignBit, SDLoc(X), VT));
  12518. AddToWorklist(X.getNode());
  12519. SDValue Cst = DAG.getBitcast(VT, N0.getOperand(0));
  12520. Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
  12521. Cst, DAG.getConstant(~SignBit, SDLoc(Cst), VT));
  12522. AddToWorklist(Cst.getNode());
  12523. return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
  12524. }
  12525. }
  12526. // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
  12527. if (N0.getOpcode() == ISD::BUILD_PAIR)
  12528. if (SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT))
  12529. return CombineLD;
  12530. // Remove double bitcasts from shuffles - this is often a legacy of
  12531. // XformToShuffleWithZero being used to combine bitmaskings (of
  12532. // float vectors bitcast to integer vectors) into shuffles.
  12533. // bitcast(shuffle(bitcast(s0),bitcast(s1))) -> shuffle(s0,s1)
  12534. if (Level < AfterLegalizeDAG && TLI.isTypeLegal(VT) && VT.isVector() &&
  12535. N0->getOpcode() == ISD::VECTOR_SHUFFLE && N0.hasOneUse() &&
  12536. VT.getVectorNumElements() >= N0.getValueType().getVectorNumElements() &&
  12537. !(VT.getVectorNumElements() % N0.getValueType().getVectorNumElements())) {
  12538. ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N0);
  12539. // If operands are a bitcast, peek through if it casts the original VT.
  12540. // If operands are a constant, just bitcast back to original VT.
  12541. auto PeekThroughBitcast = [&](SDValue Op) {
  12542. if (Op.getOpcode() == ISD::BITCAST &&
  12543. Op.getOperand(0).getValueType() == VT)
  12544. return SDValue(Op.getOperand(0));
  12545. if (Op.isUndef() || isAnyConstantBuildVector(Op))
  12546. return DAG.getBitcast(VT, Op);
  12547. return SDValue();
  12548. };
  12549. // FIXME: If either input vector is bitcast, try to convert the shuffle to
  12550. // the result type of this bitcast. This would eliminate at least one
  12551. // bitcast. See the transform in InstCombine.
  12552. SDValue SV0 = PeekThroughBitcast(N0->getOperand(0));
  12553. SDValue SV1 = PeekThroughBitcast(N0->getOperand(1));
  12554. if (!(SV0 && SV1))
  12555. return SDValue();
  12556. int MaskScale =
  12557. VT.getVectorNumElements() / N0.getValueType().getVectorNumElements();
  12558. SmallVector<int, 8> NewMask;
  12559. for (int M : SVN->getMask())
  12560. for (int i = 0; i != MaskScale; ++i)
  12561. NewMask.push_back(M < 0 ? -1 : M * MaskScale + i);
  12562. SDValue LegalShuffle =
  12563. TLI.buildLegalVectorShuffle(VT, SDLoc(N), SV0, SV1, NewMask, DAG);
  12564. if (LegalShuffle)
  12565. return LegalShuffle;
  12566. }
  12567. return SDValue();
  12568. }
  12569. SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
  12570. EVT VT = N->getValueType(0);
  12571. return CombineConsecutiveLoads(N, VT);
  12572. }
  12573. SDValue DAGCombiner::visitFREEZE(SDNode *N) {
  12574. SDValue N0 = N->getOperand(0);
  12575. if (DAG.isGuaranteedNotToBeUndefOrPoison(N0, /*PoisonOnly*/ false))
  12576. return N0;
  12577. // Fold freeze(op(x, ...)) -> op(freeze(x), ...).
  12578. // Try to push freeze through instructions that propagate but don't produce
  12579. // poison as far as possible. If an operand of freeze follows three
  12580. // conditions 1) one-use, 2) does not produce poison, and 3) has all but one
  12581. // guaranteed-non-poison operands (or is a BUILD_VECTOR or similar) then push
  12582. // the freeze through to the operands that are not guaranteed non-poison.
  12583. // NOTE: we will strip poison-generating flags, so ignore them here.
  12584. if (DAG.canCreateUndefOrPoison(N0, /*PoisonOnly*/ false,
  12585. /*ConsiderFlags*/ false) ||
  12586. N0->getNumValues() != 1 || !N0->hasOneUse())
  12587. return SDValue();
  12588. bool AllowMultipleMaybePoisonOperands = N0.getOpcode() == ISD::BUILD_VECTOR;
  12589. SmallSetVector<SDValue, 8> MaybePoisonOperands;
  12590. for (SDValue Op : N0->ops()) {
  12591. if (DAG.isGuaranteedNotToBeUndefOrPoison(Op, /*PoisonOnly*/ false,
  12592. /*Depth*/ 1))
  12593. continue;
  12594. bool HadMaybePoisonOperands = !MaybePoisonOperands.empty();
  12595. bool IsNewMaybePoisonOperand = MaybePoisonOperands.insert(Op);
  12596. if (!HadMaybePoisonOperands)
  12597. continue;
  12598. if (IsNewMaybePoisonOperand && !AllowMultipleMaybePoisonOperands) {
  12599. // Multiple maybe-poison ops when not allowed - bail out.
  12600. return SDValue();
  12601. }
  12602. }
  12603. // NOTE: the whole op may be not guaranteed to not be undef or poison because
  12604. // it could create undef or poison due to it's poison-generating flags.
  12605. // So not finding any maybe-poison operands is fine.
  12606. for (SDValue MaybePoisonOperand : MaybePoisonOperands) {
  12607. // Don't replace every single UNDEF everywhere with frozen UNDEF, though.
  12608. if (MaybePoisonOperand.getOpcode() == ISD::UNDEF)
  12609. continue;
  12610. // First, freeze each offending operand.
  12611. SDValue FrozenMaybePoisonOperand = DAG.getFreeze(MaybePoisonOperand);
  12612. // Then, change all other uses of unfrozen operand to use frozen operand.
  12613. DAG.ReplaceAllUsesOfValueWith(MaybePoisonOperand, FrozenMaybePoisonOperand);
  12614. if (FrozenMaybePoisonOperand.getOpcode() == ISD::FREEZE &&
  12615. FrozenMaybePoisonOperand.getOperand(0) == FrozenMaybePoisonOperand) {
  12616. // But, that also updated the use in the freeze we just created, thus
  12617. // creating a cycle in a DAG. Let's undo that by mutating the freeze.
  12618. DAG.UpdateNodeOperands(FrozenMaybePoisonOperand.getNode(),
  12619. MaybePoisonOperand);
  12620. }
  12621. }
  12622. // The whole node may have been updated, so the value we were holding
  12623. // may no longer be valid. Re-fetch the operand we're `freeze`ing.
  12624. N0 = N->getOperand(0);
  12625. // Finally, recreate the node, it's operands were updated to use
  12626. // frozen operands, so we just need to use it's "original" operands.
  12627. SmallVector<SDValue> Ops(N0->op_begin(), N0->op_end());
  12628. // Special-handle ISD::UNDEF, each single one of them can be it's own thing.
  12629. for (SDValue &Op : Ops) {
  12630. if (Op.getOpcode() == ISD::UNDEF)
  12631. Op = DAG.getFreeze(Op);
  12632. }
  12633. // NOTE: this strips poison generating flags.
  12634. SDValue R = DAG.getNode(N0.getOpcode(), SDLoc(N0), N0->getVTList(), Ops);
  12635. assert(DAG.isGuaranteedNotToBeUndefOrPoison(R, /*PoisonOnly*/ false) &&
  12636. "Can't create node that may be undef/poison!");
  12637. return R;
  12638. }
  12639. /// We know that BV is a build_vector node with Constant, ConstantFP or Undef
  12640. /// operands. DstEltVT indicates the destination element value type.
  12641. SDValue DAGCombiner::
  12642. ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
  12643. EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
  12644. // If this is already the right type, we're done.
  12645. if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
  12646. unsigned SrcBitSize = SrcEltVT.getSizeInBits();
  12647. unsigned DstBitSize = DstEltVT.getSizeInBits();
  12648. // If this is a conversion of N elements of one type to N elements of another
  12649. // type, convert each element. This handles FP<->INT cases.
  12650. if (SrcBitSize == DstBitSize) {
  12651. SmallVector<SDValue, 8> Ops;
  12652. for (SDValue Op : BV->op_values()) {
  12653. // If the vector element type is not legal, the BUILD_VECTOR operands
  12654. // are promoted and implicitly truncated. Make that explicit here.
  12655. if (Op.getValueType() != SrcEltVT)
  12656. Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
  12657. Ops.push_back(DAG.getBitcast(DstEltVT, Op));
  12658. AddToWorklist(Ops.back().getNode());
  12659. }
  12660. EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
  12661. BV->getValueType(0).getVectorNumElements());
  12662. return DAG.getBuildVector(VT, SDLoc(BV), Ops);
  12663. }
  12664. // Otherwise, we're growing or shrinking the elements. To avoid having to
  12665. // handle annoying details of growing/shrinking FP values, we convert them to
  12666. // int first.
  12667. if (SrcEltVT.isFloatingPoint()) {
  12668. // Convert the input float vector to a int vector where the elements are the
  12669. // same sizes.
  12670. EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
  12671. BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
  12672. SrcEltVT = IntVT;
  12673. }
  12674. // Now we know the input is an integer vector. If the output is a FP type,
  12675. // convert to integer first, then to FP of the right size.
  12676. if (DstEltVT.isFloatingPoint()) {
  12677. EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
  12678. SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
  12679. // Next, convert to FP elements of the same size.
  12680. return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
  12681. }
  12682. // Okay, we know the src/dst types are both integers of differing types.
  12683. assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
  12684. // TODO: Should ConstantFoldBITCASTofBUILD_VECTOR always take a
  12685. // BuildVectorSDNode?
  12686. auto *BVN = cast<BuildVectorSDNode>(BV);
  12687. // Extract the constant raw bit data.
  12688. BitVector UndefElements;
  12689. SmallVector<APInt> RawBits;
  12690. bool IsLE = DAG.getDataLayout().isLittleEndian();
  12691. if (!BVN->getConstantRawBits(IsLE, DstBitSize, RawBits, UndefElements))
  12692. return SDValue();
  12693. SDLoc DL(BV);
  12694. SmallVector<SDValue, 8> Ops;
  12695. for (unsigned I = 0, E = RawBits.size(); I != E; ++I) {
  12696. if (UndefElements[I])
  12697. Ops.push_back(DAG.getUNDEF(DstEltVT));
  12698. else
  12699. Ops.push_back(DAG.getConstant(RawBits[I], DL, DstEltVT));
  12700. }
  12701. EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
  12702. return DAG.getBuildVector(VT, DL, Ops);
  12703. }
  12704. // Returns true if floating point contraction is allowed on the FMUL-SDValue
  12705. // `N`
  12706. static bool isContractableFMUL(const TargetOptions &Options, SDValue N) {
  12707. assert(N.getOpcode() == ISD::FMUL);
  12708. return Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath ||
  12709. N->getFlags().hasAllowContract();
  12710. }
  12711. // Returns true if `N` can assume no infinities involved in its computation.
  12712. static bool hasNoInfs(const TargetOptions &Options, SDValue N) {
  12713. return Options.NoInfsFPMath || N->getFlags().hasNoInfs();
  12714. }
  12715. /// Try to perform FMA combining on a given FADD node.
  12716. SDValue DAGCombiner::visitFADDForFMACombine(SDNode *N) {
  12717. SDValue N0 = N->getOperand(0);
  12718. SDValue N1 = N->getOperand(1);
  12719. EVT VT = N->getValueType(0);
  12720. SDLoc SL(N);
  12721. const TargetOptions &Options = DAG.getTarget().Options;
  12722. // Floating-point multiply-add with intermediate rounding.
  12723. bool HasFMAD = (LegalOperations && TLI.isFMADLegal(DAG, N));
  12724. // Floating-point multiply-add without intermediate rounding.
  12725. bool HasFMA =
  12726. TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT) &&
  12727. (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
  12728. // No valid opcode, do not combine.
  12729. if (!HasFMAD && !HasFMA)
  12730. return SDValue();
  12731. bool CanReassociate =
  12732. Options.UnsafeFPMath || N->getFlags().hasAllowReassociation();
  12733. bool AllowFusionGlobally = (Options.AllowFPOpFusion == FPOpFusion::Fast ||
  12734. Options.UnsafeFPMath || HasFMAD);
  12735. // If the addition is not contractable, do not combine.
  12736. if (!AllowFusionGlobally && !N->getFlags().hasAllowContract())
  12737. return SDValue();
  12738. if (TLI.generateFMAsInMachineCombiner(VT, OptLevel))
  12739. return SDValue();
  12740. // Always prefer FMAD to FMA for precision.
  12741. unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
  12742. bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
  12743. auto isFusedOp = [&](SDValue N) {
  12744. unsigned Opcode = N.getOpcode();
  12745. return Opcode == ISD::FMA || Opcode == ISD::FMAD;
  12746. };
  12747. // Is the node an FMUL and contractable either due to global flags or
  12748. // SDNodeFlags.
  12749. auto isContractableFMUL = [AllowFusionGlobally](SDValue N) {
  12750. if (N.getOpcode() != ISD::FMUL)
  12751. return false;
  12752. return AllowFusionGlobally || N->getFlags().hasAllowContract();
  12753. };
  12754. // If we have two choices trying to fold (fadd (fmul u, v), (fmul x, y)),
  12755. // prefer to fold the multiply with fewer uses.
  12756. if (Aggressive && isContractableFMUL(N0) && isContractableFMUL(N1)) {
  12757. if (N0->use_size() > N1->use_size())
  12758. std::swap(N0, N1);
  12759. }
  12760. // fold (fadd (fmul x, y), z) -> (fma x, y, z)
  12761. if (isContractableFMUL(N0) && (Aggressive || N0->hasOneUse())) {
  12762. return DAG.getNode(PreferredFusedOpcode, SL, VT, N0.getOperand(0),
  12763. N0.getOperand(1), N1);
  12764. }
  12765. // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
  12766. // Note: Commutes FADD operands.
  12767. if (isContractableFMUL(N1) && (Aggressive || N1->hasOneUse())) {
  12768. return DAG.getNode(PreferredFusedOpcode, SL, VT, N1.getOperand(0),
  12769. N1.getOperand(1), N0);
  12770. }
  12771. // fadd (fma A, B, (fmul C, D)), E --> fma A, B, (fma C, D, E)
  12772. // fadd E, (fma A, B, (fmul C, D)) --> fma A, B, (fma C, D, E)
  12773. // This also works with nested fma instructions:
  12774. // fadd (fma A, B, (fma (C, D, (fmul (E, F))))), G -->
  12775. // fma A, B, (fma C, D, fma (E, F, G))
  12776. // fadd (G, (fma A, B, (fma (C, D, (fmul (E, F)))))) -->
  12777. // fma A, B, (fma C, D, fma (E, F, G)).
  12778. // This requires reassociation because it changes the order of operations.
  12779. if (CanReassociate) {
  12780. SDValue FMA, E;
  12781. if (isFusedOp(N0) && N0.hasOneUse()) {
  12782. FMA = N0;
  12783. E = N1;
  12784. } else if (isFusedOp(N1) && N1.hasOneUse()) {
  12785. FMA = N1;
  12786. E = N0;
  12787. }
  12788. SDValue TmpFMA = FMA;
  12789. while (E && isFusedOp(TmpFMA) && TmpFMA.hasOneUse()) {
  12790. SDValue FMul = TmpFMA->getOperand(2);
  12791. if (FMul.getOpcode() == ISD::FMUL && FMul.hasOneUse()) {
  12792. SDValue C = FMul.getOperand(0);
  12793. SDValue D = FMul.getOperand(1);
  12794. SDValue CDE = DAG.getNode(PreferredFusedOpcode, SL, VT, C, D, E);
  12795. DAG.ReplaceAllUsesOfValueWith(FMul, CDE);
  12796. // Replacing the inner FMul could cause the outer FMA to be simplified
  12797. // away.
  12798. return FMA.getOpcode() == ISD::DELETED_NODE ? SDValue() : FMA;
  12799. }
  12800. TmpFMA = TmpFMA->getOperand(2);
  12801. }
  12802. }
  12803. // Look through FP_EXTEND nodes to do more combining.
  12804. // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z)
  12805. if (N0.getOpcode() == ISD::FP_EXTEND) {
  12806. SDValue N00 = N0.getOperand(0);
  12807. if (isContractableFMUL(N00) &&
  12808. TLI.isFPExtFoldable(DAG, PreferredFusedOpcode, VT,
  12809. N00.getValueType())) {
  12810. return DAG.getNode(PreferredFusedOpcode, SL, VT,
  12811. DAG.getNode(ISD::FP_EXTEND, SL, VT, N00.getOperand(0)),
  12812. DAG.getNode(ISD::FP_EXTEND, SL, VT, N00.getOperand(1)),
  12813. N1);
  12814. }
  12815. }
  12816. // fold (fadd x, (fpext (fmul y, z))) -> (fma (fpext y), (fpext z), x)
  12817. // Note: Commutes FADD operands.
  12818. if (N1.getOpcode() == ISD::FP_EXTEND) {
  12819. SDValue N10 = N1.getOperand(0);
  12820. if (isContractableFMUL(N10) &&
  12821. TLI.isFPExtFoldable(DAG, PreferredFusedOpcode, VT,
  12822. N10.getValueType())) {
  12823. return DAG.getNode(PreferredFusedOpcode, SL, VT,
  12824. DAG.getNode(ISD::FP_EXTEND, SL, VT, N10.getOperand(0)),
  12825. DAG.getNode(ISD::FP_EXTEND, SL, VT, N10.getOperand(1)),
  12826. N0);
  12827. }
  12828. }
  12829. // More folding opportunities when target permits.
  12830. if (Aggressive) {
  12831. // fold (fadd (fma x, y, (fpext (fmul u, v))), z)
  12832. // -> (fma x, y, (fma (fpext u), (fpext v), z))
  12833. auto FoldFAddFMAFPExtFMul = [&](SDValue X, SDValue Y, SDValue U, SDValue V,
  12834. SDValue Z) {
  12835. return DAG.getNode(PreferredFusedOpcode, SL, VT, X, Y,
  12836. DAG.getNode(PreferredFusedOpcode, SL, VT,
  12837. DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
  12838. DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
  12839. Z));
  12840. };
  12841. if (isFusedOp(N0)) {
  12842. SDValue N02 = N0.getOperand(2);
  12843. if (N02.getOpcode() == ISD::FP_EXTEND) {
  12844. SDValue N020 = N02.getOperand(0);
  12845. if (isContractableFMUL(N020) &&
  12846. TLI.isFPExtFoldable(DAG, PreferredFusedOpcode, VT,
  12847. N020.getValueType())) {
  12848. return FoldFAddFMAFPExtFMul(N0.getOperand(0), N0.getOperand(1),
  12849. N020.getOperand(0), N020.getOperand(1),
  12850. N1);
  12851. }
  12852. }
  12853. }
  12854. // fold (fadd (fpext (fma x, y, (fmul u, v))), z)
  12855. // -> (fma (fpext x), (fpext y), (fma (fpext u), (fpext v), z))
  12856. // FIXME: This turns two single-precision and one double-precision
  12857. // operation into two double-precision operations, which might not be
  12858. // interesting for all targets, especially GPUs.
  12859. auto FoldFAddFPExtFMAFMul = [&](SDValue X, SDValue Y, SDValue U, SDValue V,
  12860. SDValue Z) {
  12861. return DAG.getNode(
  12862. PreferredFusedOpcode, SL, VT, DAG.getNode(ISD::FP_EXTEND, SL, VT, X),
  12863. DAG.getNode(ISD::FP_EXTEND, SL, VT, Y),
  12864. DAG.getNode(PreferredFusedOpcode, SL, VT,
  12865. DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
  12866. DAG.getNode(ISD::FP_EXTEND, SL, VT, V), Z));
  12867. };
  12868. if (N0.getOpcode() == ISD::FP_EXTEND) {
  12869. SDValue N00 = N0.getOperand(0);
  12870. if (isFusedOp(N00)) {
  12871. SDValue N002 = N00.getOperand(2);
  12872. if (isContractableFMUL(N002) &&
  12873. TLI.isFPExtFoldable(DAG, PreferredFusedOpcode, VT,
  12874. N00.getValueType())) {
  12875. return FoldFAddFPExtFMAFMul(N00.getOperand(0), N00.getOperand(1),
  12876. N002.getOperand(0), N002.getOperand(1),
  12877. N1);
  12878. }
  12879. }
  12880. }
  12881. // fold (fadd x, (fma y, z, (fpext (fmul u, v)))
  12882. // -> (fma y, z, (fma (fpext u), (fpext v), x))
  12883. if (isFusedOp(N1)) {
  12884. SDValue N12 = N1.getOperand(2);
  12885. if (N12.getOpcode() == ISD::FP_EXTEND) {
  12886. SDValue N120 = N12.getOperand(0);
  12887. if (isContractableFMUL(N120) &&
  12888. TLI.isFPExtFoldable(DAG, PreferredFusedOpcode, VT,
  12889. N120.getValueType())) {
  12890. return FoldFAddFMAFPExtFMul(N1.getOperand(0), N1.getOperand(1),
  12891. N120.getOperand(0), N120.getOperand(1),
  12892. N0);
  12893. }
  12894. }
  12895. }
  12896. // fold (fadd x, (fpext (fma y, z, (fmul u, v)))
  12897. // -> (fma (fpext y), (fpext z), (fma (fpext u), (fpext v), x))
  12898. // FIXME: This turns two single-precision and one double-precision
  12899. // operation into two double-precision operations, which might not be
  12900. // interesting for all targets, especially GPUs.
  12901. if (N1.getOpcode() == ISD::FP_EXTEND) {
  12902. SDValue N10 = N1.getOperand(0);
  12903. if (isFusedOp(N10)) {
  12904. SDValue N102 = N10.getOperand(2);
  12905. if (isContractableFMUL(N102) &&
  12906. TLI.isFPExtFoldable(DAG, PreferredFusedOpcode, VT,
  12907. N10.getValueType())) {
  12908. return FoldFAddFPExtFMAFMul(N10.getOperand(0), N10.getOperand(1),
  12909. N102.getOperand(0), N102.getOperand(1),
  12910. N0);
  12911. }
  12912. }
  12913. }
  12914. }
  12915. return SDValue();
  12916. }
  12917. /// Try to perform FMA combining on a given FSUB node.
  12918. SDValue DAGCombiner::visitFSUBForFMACombine(SDNode *N) {
  12919. SDValue N0 = N->getOperand(0);
  12920. SDValue N1 = N->getOperand(1);
  12921. EVT VT = N->getValueType(0);
  12922. SDLoc SL(N);
  12923. const TargetOptions &Options = DAG.getTarget().Options;
  12924. // Floating-point multiply-add with intermediate rounding.
  12925. bool HasFMAD = (LegalOperations && TLI.isFMADLegal(DAG, N));
  12926. // Floating-point multiply-add without intermediate rounding.
  12927. bool HasFMA =
  12928. TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT) &&
  12929. (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
  12930. // No valid opcode, do not combine.
  12931. if (!HasFMAD && !HasFMA)
  12932. return SDValue();
  12933. const SDNodeFlags Flags = N->getFlags();
  12934. bool AllowFusionGlobally = (Options.AllowFPOpFusion == FPOpFusion::Fast ||
  12935. Options.UnsafeFPMath || HasFMAD);
  12936. // If the subtraction is not contractable, do not combine.
  12937. if (!AllowFusionGlobally && !N->getFlags().hasAllowContract())
  12938. return SDValue();
  12939. if (TLI.generateFMAsInMachineCombiner(VT, OptLevel))
  12940. return SDValue();
  12941. // Always prefer FMAD to FMA for precision.
  12942. unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
  12943. bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
  12944. bool NoSignedZero = Options.NoSignedZerosFPMath || Flags.hasNoSignedZeros();
  12945. // Is the node an FMUL and contractable either due to global flags or
  12946. // SDNodeFlags.
  12947. auto isContractableFMUL = [AllowFusionGlobally](SDValue N) {
  12948. if (N.getOpcode() != ISD::FMUL)
  12949. return false;
  12950. return AllowFusionGlobally || N->getFlags().hasAllowContract();
  12951. };
  12952. // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
  12953. auto tryToFoldXYSubZ = [&](SDValue XY, SDValue Z) {
  12954. if (isContractableFMUL(XY) && (Aggressive || XY->hasOneUse())) {
  12955. return DAG.getNode(PreferredFusedOpcode, SL, VT, XY.getOperand(0),
  12956. XY.getOperand(1), DAG.getNode(ISD::FNEG, SL, VT, Z));
  12957. }
  12958. return SDValue();
  12959. };
  12960. // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
  12961. // Note: Commutes FSUB operands.
  12962. auto tryToFoldXSubYZ = [&](SDValue X, SDValue YZ) {
  12963. if (isContractableFMUL(YZ) && (Aggressive || YZ->hasOneUse())) {
  12964. return DAG.getNode(PreferredFusedOpcode, SL, VT,
  12965. DAG.getNode(ISD::FNEG, SL, VT, YZ.getOperand(0)),
  12966. YZ.getOperand(1), X);
  12967. }
  12968. return SDValue();
  12969. };
  12970. // If we have two choices trying to fold (fsub (fmul u, v), (fmul x, y)),
  12971. // prefer to fold the multiply with fewer uses.
  12972. if (isContractableFMUL(N0) && isContractableFMUL(N1) &&
  12973. (N0->use_size() > N1->use_size())) {
  12974. // fold (fsub (fmul a, b), (fmul c, d)) -> (fma (fneg c), d, (fmul a, b))
  12975. if (SDValue V = tryToFoldXSubYZ(N0, N1))
  12976. return V;
  12977. // fold (fsub (fmul a, b), (fmul c, d)) -> (fma a, b, (fneg (fmul c, d)))
  12978. if (SDValue V = tryToFoldXYSubZ(N0, N1))
  12979. return V;
  12980. } else {
  12981. // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
  12982. if (SDValue V = tryToFoldXYSubZ(N0, N1))
  12983. return V;
  12984. // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
  12985. if (SDValue V = tryToFoldXSubYZ(N0, N1))
  12986. return V;
  12987. }
  12988. // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
  12989. if (N0.getOpcode() == ISD::FNEG && isContractableFMUL(N0.getOperand(0)) &&
  12990. (Aggressive || (N0->hasOneUse() && N0.getOperand(0).hasOneUse()))) {
  12991. SDValue N00 = N0.getOperand(0).getOperand(0);
  12992. SDValue N01 = N0.getOperand(0).getOperand(1);
  12993. return DAG.getNode(PreferredFusedOpcode, SL, VT,
  12994. DAG.getNode(ISD::FNEG, SL, VT, N00), N01,
  12995. DAG.getNode(ISD::FNEG, SL, VT, N1));
  12996. }
  12997. // Look through FP_EXTEND nodes to do more combining.
  12998. // fold (fsub (fpext (fmul x, y)), z)
  12999. // -> (fma (fpext x), (fpext y), (fneg z))
  13000. if (N0.getOpcode() == ISD::FP_EXTEND) {
  13001. SDValue N00 = N0.getOperand(0);
  13002. if (isContractableFMUL(N00) &&
  13003. TLI.isFPExtFoldable(DAG, PreferredFusedOpcode, VT,
  13004. N00.getValueType())) {
  13005. return DAG.getNode(PreferredFusedOpcode, SL, VT,
  13006. DAG.getNode(ISD::FP_EXTEND, SL, VT, N00.getOperand(0)),
  13007. DAG.getNode(ISD::FP_EXTEND, SL, VT, N00.getOperand(1)),
  13008. DAG.getNode(ISD::FNEG, SL, VT, N1));
  13009. }
  13010. }
  13011. // fold (fsub x, (fpext (fmul y, z)))
  13012. // -> (fma (fneg (fpext y)), (fpext z), x)
  13013. // Note: Commutes FSUB operands.
  13014. if (N1.getOpcode() == ISD::FP_EXTEND) {
  13015. SDValue N10 = N1.getOperand(0);
  13016. if (isContractableFMUL(N10) &&
  13017. TLI.isFPExtFoldable(DAG, PreferredFusedOpcode, VT,
  13018. N10.getValueType())) {
  13019. return DAG.getNode(
  13020. PreferredFusedOpcode, SL, VT,
  13021. DAG.getNode(ISD::FNEG, SL, VT,
  13022. DAG.getNode(ISD::FP_EXTEND, SL, VT, N10.getOperand(0))),
  13023. DAG.getNode(ISD::FP_EXTEND, SL, VT, N10.getOperand(1)), N0);
  13024. }
  13025. }
  13026. // fold (fsub (fpext (fneg (fmul, x, y))), z)
  13027. // -> (fneg (fma (fpext x), (fpext y), z))
  13028. // Note: This could be removed with appropriate canonicalization of the
  13029. // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
  13030. // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
  13031. // from implementing the canonicalization in visitFSUB.
  13032. if (N0.getOpcode() == ISD::FP_EXTEND) {
  13033. SDValue N00 = N0.getOperand(0);
  13034. if (N00.getOpcode() == ISD::FNEG) {
  13035. SDValue N000 = N00.getOperand(0);
  13036. if (isContractableFMUL(N000) &&
  13037. TLI.isFPExtFoldable(DAG, PreferredFusedOpcode, VT,
  13038. N00.getValueType())) {
  13039. return DAG.getNode(
  13040. ISD::FNEG, SL, VT,
  13041. DAG.getNode(PreferredFusedOpcode, SL, VT,
  13042. DAG.getNode(ISD::FP_EXTEND, SL, VT, N000.getOperand(0)),
  13043. DAG.getNode(ISD::FP_EXTEND, SL, VT, N000.getOperand(1)),
  13044. N1));
  13045. }
  13046. }
  13047. }
  13048. // fold (fsub (fneg (fpext (fmul, x, y))), z)
  13049. // -> (fneg (fma (fpext x)), (fpext y), z)
  13050. // Note: This could be removed with appropriate canonicalization of the
  13051. // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
  13052. // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
  13053. // from implementing the canonicalization in visitFSUB.
  13054. if (N0.getOpcode() == ISD::FNEG) {
  13055. SDValue N00 = N0.getOperand(0);
  13056. if (N00.getOpcode() == ISD::FP_EXTEND) {
  13057. SDValue N000 = N00.getOperand(0);
  13058. if (isContractableFMUL(N000) &&
  13059. TLI.isFPExtFoldable(DAG, PreferredFusedOpcode, VT,
  13060. N000.getValueType())) {
  13061. return DAG.getNode(
  13062. ISD::FNEG, SL, VT,
  13063. DAG.getNode(PreferredFusedOpcode, SL, VT,
  13064. DAG.getNode(ISD::FP_EXTEND, SL, VT, N000.getOperand(0)),
  13065. DAG.getNode(ISD::FP_EXTEND, SL, VT, N000.getOperand(1)),
  13066. N1));
  13067. }
  13068. }
  13069. }
  13070. auto isReassociable = [Options](SDNode *N) {
  13071. return Options.UnsafeFPMath || N->getFlags().hasAllowReassociation();
  13072. };
  13073. auto isContractableAndReassociableFMUL = [&isContractableFMUL,
  13074. &isReassociable](SDValue N) {
  13075. return isContractableFMUL(N) && isReassociable(N.getNode());
  13076. };
  13077. auto isFusedOp = [&](SDValue N) {
  13078. unsigned Opcode = N.getOpcode();
  13079. return Opcode == ISD::FMA || Opcode == ISD::FMAD;
  13080. };
  13081. // More folding opportunities when target permits.
  13082. if (Aggressive && isReassociable(N)) {
  13083. bool CanFuse = Options.UnsafeFPMath || N->getFlags().hasAllowContract();
  13084. // fold (fsub (fma x, y, (fmul u, v)), z)
  13085. // -> (fma x, y (fma u, v, (fneg z)))
  13086. if (CanFuse && isFusedOp(N0) &&
  13087. isContractableAndReassociableFMUL(N0.getOperand(2)) &&
  13088. N0->hasOneUse() && N0.getOperand(2)->hasOneUse()) {
  13089. return DAG.getNode(PreferredFusedOpcode, SL, VT, N0.getOperand(0),
  13090. N0.getOperand(1),
  13091. DAG.getNode(PreferredFusedOpcode, SL, VT,
  13092. N0.getOperand(2).getOperand(0),
  13093. N0.getOperand(2).getOperand(1),
  13094. DAG.getNode(ISD::FNEG, SL, VT, N1)));
  13095. }
  13096. // fold (fsub x, (fma y, z, (fmul u, v)))
  13097. // -> (fma (fneg y), z, (fma (fneg u), v, x))
  13098. if (CanFuse && isFusedOp(N1) &&
  13099. isContractableAndReassociableFMUL(N1.getOperand(2)) &&
  13100. N1->hasOneUse() && NoSignedZero) {
  13101. SDValue N20 = N1.getOperand(2).getOperand(0);
  13102. SDValue N21 = N1.getOperand(2).getOperand(1);
  13103. return DAG.getNode(
  13104. PreferredFusedOpcode, SL, VT,
  13105. DAG.getNode(ISD::FNEG, SL, VT, N1.getOperand(0)), N1.getOperand(1),
  13106. DAG.getNode(PreferredFusedOpcode, SL, VT,
  13107. DAG.getNode(ISD::FNEG, SL, VT, N20), N21, N0));
  13108. }
  13109. // fold (fsub (fma x, y, (fpext (fmul u, v))), z)
  13110. // -> (fma x, y (fma (fpext u), (fpext v), (fneg z)))
  13111. if (isFusedOp(N0) && N0->hasOneUse()) {
  13112. SDValue N02 = N0.getOperand(2);
  13113. if (N02.getOpcode() == ISD::FP_EXTEND) {
  13114. SDValue N020 = N02.getOperand(0);
  13115. if (isContractableAndReassociableFMUL(N020) &&
  13116. TLI.isFPExtFoldable(DAG, PreferredFusedOpcode, VT,
  13117. N020.getValueType())) {
  13118. return DAG.getNode(
  13119. PreferredFusedOpcode, SL, VT, N0.getOperand(0), N0.getOperand(1),
  13120. DAG.getNode(
  13121. PreferredFusedOpcode, SL, VT,
  13122. DAG.getNode(ISD::FP_EXTEND, SL, VT, N020.getOperand(0)),
  13123. DAG.getNode(ISD::FP_EXTEND, SL, VT, N020.getOperand(1)),
  13124. DAG.getNode(ISD::FNEG, SL, VT, N1)));
  13125. }
  13126. }
  13127. }
  13128. // fold (fsub (fpext (fma x, y, (fmul u, v))), z)
  13129. // -> (fma (fpext x), (fpext y),
  13130. // (fma (fpext u), (fpext v), (fneg z)))
  13131. // FIXME: This turns two single-precision and one double-precision
  13132. // operation into two double-precision operations, which might not be
  13133. // interesting for all targets, especially GPUs.
  13134. if (N0.getOpcode() == ISD::FP_EXTEND) {
  13135. SDValue N00 = N0.getOperand(0);
  13136. if (isFusedOp(N00)) {
  13137. SDValue N002 = N00.getOperand(2);
  13138. if (isContractableAndReassociableFMUL(N002) &&
  13139. TLI.isFPExtFoldable(DAG, PreferredFusedOpcode, VT,
  13140. N00.getValueType())) {
  13141. return DAG.getNode(
  13142. PreferredFusedOpcode, SL, VT,
  13143. DAG.getNode(ISD::FP_EXTEND, SL, VT, N00.getOperand(0)),
  13144. DAG.getNode(ISD::FP_EXTEND, SL, VT, N00.getOperand(1)),
  13145. DAG.getNode(
  13146. PreferredFusedOpcode, SL, VT,
  13147. DAG.getNode(ISD::FP_EXTEND, SL, VT, N002.getOperand(0)),
  13148. DAG.getNode(ISD::FP_EXTEND, SL, VT, N002.getOperand(1)),
  13149. DAG.getNode(ISD::FNEG, SL, VT, N1)));
  13150. }
  13151. }
  13152. }
  13153. // fold (fsub x, (fma y, z, (fpext (fmul u, v))))
  13154. // -> (fma (fneg y), z, (fma (fneg (fpext u)), (fpext v), x))
  13155. if (isFusedOp(N1) && N1.getOperand(2).getOpcode() == ISD::FP_EXTEND &&
  13156. N1->hasOneUse()) {
  13157. SDValue N120 = N1.getOperand(2).getOperand(0);
  13158. if (isContractableAndReassociableFMUL(N120) &&
  13159. TLI.isFPExtFoldable(DAG, PreferredFusedOpcode, VT,
  13160. N120.getValueType())) {
  13161. SDValue N1200 = N120.getOperand(0);
  13162. SDValue N1201 = N120.getOperand(1);
  13163. return DAG.getNode(
  13164. PreferredFusedOpcode, SL, VT,
  13165. DAG.getNode(ISD::FNEG, SL, VT, N1.getOperand(0)), N1.getOperand(1),
  13166. DAG.getNode(PreferredFusedOpcode, SL, VT,
  13167. DAG.getNode(ISD::FNEG, SL, VT,
  13168. DAG.getNode(ISD::FP_EXTEND, SL, VT, N1200)),
  13169. DAG.getNode(ISD::FP_EXTEND, SL, VT, N1201), N0));
  13170. }
  13171. }
  13172. // fold (fsub x, (fpext (fma y, z, (fmul u, v))))
  13173. // -> (fma (fneg (fpext y)), (fpext z),
  13174. // (fma (fneg (fpext u)), (fpext v), x))
  13175. // FIXME: This turns two single-precision and one double-precision
  13176. // operation into two double-precision operations, which might not be
  13177. // interesting for all targets, especially GPUs.
  13178. if (N1.getOpcode() == ISD::FP_EXTEND && isFusedOp(N1.getOperand(0))) {
  13179. SDValue CvtSrc = N1.getOperand(0);
  13180. SDValue N100 = CvtSrc.getOperand(0);
  13181. SDValue N101 = CvtSrc.getOperand(1);
  13182. SDValue N102 = CvtSrc.getOperand(2);
  13183. if (isContractableAndReassociableFMUL(N102) &&
  13184. TLI.isFPExtFoldable(DAG, PreferredFusedOpcode, VT,
  13185. CvtSrc.getValueType())) {
  13186. SDValue N1020 = N102.getOperand(0);
  13187. SDValue N1021 = N102.getOperand(1);
  13188. return DAG.getNode(
  13189. PreferredFusedOpcode, SL, VT,
  13190. DAG.getNode(ISD::FNEG, SL, VT,
  13191. DAG.getNode(ISD::FP_EXTEND, SL, VT, N100)),
  13192. DAG.getNode(ISD::FP_EXTEND, SL, VT, N101),
  13193. DAG.getNode(PreferredFusedOpcode, SL, VT,
  13194. DAG.getNode(ISD::FNEG, SL, VT,
  13195. DAG.getNode(ISD::FP_EXTEND, SL, VT, N1020)),
  13196. DAG.getNode(ISD::FP_EXTEND, SL, VT, N1021), N0));
  13197. }
  13198. }
  13199. }
  13200. return SDValue();
  13201. }
  13202. /// Try to perform FMA combining on a given FMUL node based on the distributive
  13203. /// law x * (y + 1) = x * y + x and variants thereof (commuted versions,
  13204. /// subtraction instead of addition).
  13205. SDValue DAGCombiner::visitFMULForFMADistributiveCombine(SDNode *N) {
  13206. SDValue N0 = N->getOperand(0);
  13207. SDValue N1 = N->getOperand(1);
  13208. EVT VT = N->getValueType(0);
  13209. SDLoc SL(N);
  13210. assert(N->getOpcode() == ISD::FMUL && "Expected FMUL Operation");
  13211. const TargetOptions &Options = DAG.getTarget().Options;
  13212. // The transforms below are incorrect when x == 0 and y == inf, because the
  13213. // intermediate multiplication produces a nan.
  13214. SDValue FAdd = N0.getOpcode() == ISD::FADD ? N0 : N1;
  13215. if (!hasNoInfs(Options, FAdd))
  13216. return SDValue();
  13217. // Floating-point multiply-add without intermediate rounding.
  13218. bool HasFMA =
  13219. isContractableFMUL(Options, SDValue(N, 0)) &&
  13220. TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT) &&
  13221. (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
  13222. // Floating-point multiply-add with intermediate rounding. This can result
  13223. // in a less precise result due to the changed rounding order.
  13224. bool HasFMAD = Options.UnsafeFPMath &&
  13225. (LegalOperations && TLI.isFMADLegal(DAG, N));
  13226. // No valid opcode, do not combine.
  13227. if (!HasFMAD && !HasFMA)
  13228. return SDValue();
  13229. // Always prefer FMAD to FMA for precision.
  13230. unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
  13231. bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
  13232. // fold (fmul (fadd x0, +1.0), y) -> (fma x0, y, y)
  13233. // fold (fmul (fadd x0, -1.0), y) -> (fma x0, y, (fneg y))
  13234. auto FuseFADD = [&](SDValue X, SDValue Y) {
  13235. if (X.getOpcode() == ISD::FADD && (Aggressive || X->hasOneUse())) {
  13236. if (auto *C = isConstOrConstSplatFP(X.getOperand(1), true)) {
  13237. if (C->isExactlyValue(+1.0))
  13238. return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y,
  13239. Y);
  13240. if (C->isExactlyValue(-1.0))
  13241. return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y,
  13242. DAG.getNode(ISD::FNEG, SL, VT, Y));
  13243. }
  13244. }
  13245. return SDValue();
  13246. };
  13247. if (SDValue FMA = FuseFADD(N0, N1))
  13248. return FMA;
  13249. if (SDValue FMA = FuseFADD(N1, N0))
  13250. return FMA;
  13251. // fold (fmul (fsub +1.0, x1), y) -> (fma (fneg x1), y, y)
  13252. // fold (fmul (fsub -1.0, x1), y) -> (fma (fneg x1), y, (fneg y))
  13253. // fold (fmul (fsub x0, +1.0), y) -> (fma x0, y, (fneg y))
  13254. // fold (fmul (fsub x0, -1.0), y) -> (fma x0, y, y)
  13255. auto FuseFSUB = [&](SDValue X, SDValue Y) {
  13256. if (X.getOpcode() == ISD::FSUB && (Aggressive || X->hasOneUse())) {
  13257. if (auto *C0 = isConstOrConstSplatFP(X.getOperand(0), true)) {
  13258. if (C0->isExactlyValue(+1.0))
  13259. return DAG.getNode(PreferredFusedOpcode, SL, VT,
  13260. DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y,
  13261. Y);
  13262. if (C0->isExactlyValue(-1.0))
  13263. return DAG.getNode(PreferredFusedOpcode, SL, VT,
  13264. DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y,
  13265. DAG.getNode(ISD::FNEG, SL, VT, Y));
  13266. }
  13267. if (auto *C1 = isConstOrConstSplatFP(X.getOperand(1), true)) {
  13268. if (C1->isExactlyValue(+1.0))
  13269. return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y,
  13270. DAG.getNode(ISD::FNEG, SL, VT, Y));
  13271. if (C1->isExactlyValue(-1.0))
  13272. return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y,
  13273. Y);
  13274. }
  13275. }
  13276. return SDValue();
  13277. };
  13278. if (SDValue FMA = FuseFSUB(N0, N1))
  13279. return FMA;
  13280. if (SDValue FMA = FuseFSUB(N1, N0))
  13281. return FMA;
  13282. return SDValue();
  13283. }
  13284. SDValue DAGCombiner::visitFADD(SDNode *N) {
  13285. SDValue N0 = N->getOperand(0);
  13286. SDValue N1 = N->getOperand(1);
  13287. SDNode *N0CFP = DAG.isConstantFPBuildVectorOrConstantFP(N0);
  13288. SDNode *N1CFP = DAG.isConstantFPBuildVectorOrConstantFP(N1);
  13289. EVT VT = N->getValueType(0);
  13290. SDLoc DL(N);
  13291. const TargetOptions &Options = DAG.getTarget().Options;
  13292. SDNodeFlags Flags = N->getFlags();
  13293. SelectionDAG::FlagInserter FlagsInserter(DAG, N);
  13294. if (SDValue R = DAG.simplifyFPBinop(N->getOpcode(), N0, N1, Flags))
  13295. return R;
  13296. // fold (fadd c1, c2) -> c1 + c2
  13297. if (SDValue C = DAG.FoldConstantArithmetic(ISD::FADD, DL, VT, {N0, N1}))
  13298. return C;
  13299. // canonicalize constant to RHS
  13300. if (N0CFP && !N1CFP)
  13301. return DAG.getNode(ISD::FADD, DL, VT, N1, N0);
  13302. // fold vector ops
  13303. if (VT.isVector())
  13304. if (SDValue FoldedVOp = SimplifyVBinOp(N, DL))
  13305. return FoldedVOp;
  13306. // N0 + -0.0 --> N0 (also allowed with +0.0 and fast-math)
  13307. ConstantFPSDNode *N1C = isConstOrConstSplatFP(N1, true);
  13308. if (N1C && N1C->isZero())
  13309. if (N1C->isNegative() || Options.NoSignedZerosFPMath || Flags.hasNoSignedZeros())
  13310. return N0;
  13311. if (SDValue NewSel = foldBinOpIntoSelect(N))
  13312. return NewSel;
  13313. // fold (fadd A, (fneg B)) -> (fsub A, B)
  13314. if (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT))
  13315. if (SDValue NegN1 = TLI.getCheaperNegatedExpression(
  13316. N1, DAG, LegalOperations, ForCodeSize))
  13317. return DAG.getNode(ISD::FSUB, DL, VT, N0, NegN1);
  13318. // fold (fadd (fneg A), B) -> (fsub B, A)
  13319. if (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT))
  13320. if (SDValue NegN0 = TLI.getCheaperNegatedExpression(
  13321. N0, DAG, LegalOperations, ForCodeSize))
  13322. return DAG.getNode(ISD::FSUB, DL, VT, N1, NegN0);
  13323. auto isFMulNegTwo = [](SDValue FMul) {
  13324. if (!FMul.hasOneUse() || FMul.getOpcode() != ISD::FMUL)
  13325. return false;
  13326. auto *C = isConstOrConstSplatFP(FMul.getOperand(1), true);
  13327. return C && C->isExactlyValue(-2.0);
  13328. };
  13329. // fadd (fmul B, -2.0), A --> fsub A, (fadd B, B)
  13330. if (isFMulNegTwo(N0)) {
  13331. SDValue B = N0.getOperand(0);
  13332. SDValue Add = DAG.getNode(ISD::FADD, DL, VT, B, B);
  13333. return DAG.getNode(ISD::FSUB, DL, VT, N1, Add);
  13334. }
  13335. // fadd A, (fmul B, -2.0) --> fsub A, (fadd B, B)
  13336. if (isFMulNegTwo(N1)) {
  13337. SDValue B = N1.getOperand(0);
  13338. SDValue Add = DAG.getNode(ISD::FADD, DL, VT, B, B);
  13339. return DAG.getNode(ISD::FSUB, DL, VT, N0, Add);
  13340. }
  13341. // No FP constant should be created after legalization as Instruction
  13342. // Selection pass has a hard time dealing with FP constants.
  13343. bool AllowNewConst = (Level < AfterLegalizeDAG);
  13344. // If nnan is enabled, fold lots of things.
  13345. if ((Options.NoNaNsFPMath || Flags.hasNoNaNs()) && AllowNewConst) {
  13346. // If allowed, fold (fadd (fneg x), x) -> 0.0
  13347. if (N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
  13348. return DAG.getConstantFP(0.0, DL, VT);
  13349. // If allowed, fold (fadd x, (fneg x)) -> 0.0
  13350. if (N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
  13351. return DAG.getConstantFP(0.0, DL, VT);
  13352. }
  13353. // If 'unsafe math' or reassoc and nsz, fold lots of things.
  13354. // TODO: break out portions of the transformations below for which Unsafe is
  13355. // considered and which do not require both nsz and reassoc
  13356. if (((Options.UnsafeFPMath && Options.NoSignedZerosFPMath) ||
  13357. (Flags.hasAllowReassociation() && Flags.hasNoSignedZeros())) &&
  13358. AllowNewConst) {
  13359. // fadd (fadd x, c1), c2 -> fadd x, c1 + c2
  13360. if (N1CFP && N0.getOpcode() == ISD::FADD &&
  13361. DAG.isConstantFPBuildVectorOrConstantFP(N0.getOperand(1))) {
  13362. SDValue NewC = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), N1);
  13363. return DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(0), NewC);
  13364. }
  13365. // We can fold chains of FADD's of the same value into multiplications.
  13366. // This transform is not safe in general because we are reducing the number
  13367. // of rounding steps.
  13368. if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) {
  13369. if (N0.getOpcode() == ISD::FMUL) {
  13370. SDNode *CFP00 =
  13371. DAG.isConstantFPBuildVectorOrConstantFP(N0.getOperand(0));
  13372. SDNode *CFP01 =
  13373. DAG.isConstantFPBuildVectorOrConstantFP(N0.getOperand(1));
  13374. // (fadd (fmul x, c), x) -> (fmul x, c+1)
  13375. if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
  13376. SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1),
  13377. DAG.getConstantFP(1.0, DL, VT));
  13378. return DAG.getNode(ISD::FMUL, DL, VT, N1, NewCFP);
  13379. }
  13380. // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
  13381. if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
  13382. N1.getOperand(0) == N1.getOperand(1) &&
  13383. N0.getOperand(0) == N1.getOperand(0)) {
  13384. SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1),
  13385. DAG.getConstantFP(2.0, DL, VT));
  13386. return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), NewCFP);
  13387. }
  13388. }
  13389. if (N1.getOpcode() == ISD::FMUL) {
  13390. SDNode *CFP10 =
  13391. DAG.isConstantFPBuildVectorOrConstantFP(N1.getOperand(0));
  13392. SDNode *CFP11 =
  13393. DAG.isConstantFPBuildVectorOrConstantFP(N1.getOperand(1));
  13394. // (fadd x, (fmul x, c)) -> (fmul x, c+1)
  13395. if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
  13396. SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1),
  13397. DAG.getConstantFP(1.0, DL, VT));
  13398. return DAG.getNode(ISD::FMUL, DL, VT, N0, NewCFP);
  13399. }
  13400. // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
  13401. if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
  13402. N0.getOperand(0) == N0.getOperand(1) &&
  13403. N1.getOperand(0) == N0.getOperand(0)) {
  13404. SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1),
  13405. DAG.getConstantFP(2.0, DL, VT));
  13406. return DAG.getNode(ISD::FMUL, DL, VT, N1.getOperand(0), NewCFP);
  13407. }
  13408. }
  13409. if (N0.getOpcode() == ISD::FADD) {
  13410. SDNode *CFP00 =
  13411. DAG.isConstantFPBuildVectorOrConstantFP(N0.getOperand(0));
  13412. // (fadd (fadd x, x), x) -> (fmul x, 3.0)
  13413. if (!CFP00 && N0.getOperand(0) == N0.getOperand(1) &&
  13414. (N0.getOperand(0) == N1)) {
  13415. return DAG.getNode(ISD::FMUL, DL, VT, N1,
  13416. DAG.getConstantFP(3.0, DL, VT));
  13417. }
  13418. }
  13419. if (N1.getOpcode() == ISD::FADD) {
  13420. SDNode *CFP10 =
  13421. DAG.isConstantFPBuildVectorOrConstantFP(N1.getOperand(0));
  13422. // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
  13423. if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
  13424. N1.getOperand(0) == N0) {
  13425. return DAG.getNode(ISD::FMUL, DL, VT, N0,
  13426. DAG.getConstantFP(3.0, DL, VT));
  13427. }
  13428. }
  13429. // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
  13430. if (N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
  13431. N0.getOperand(0) == N0.getOperand(1) &&
  13432. N1.getOperand(0) == N1.getOperand(1) &&
  13433. N0.getOperand(0) == N1.getOperand(0)) {
  13434. return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0),
  13435. DAG.getConstantFP(4.0, DL, VT));
  13436. }
  13437. }
  13438. } // enable-unsafe-fp-math
  13439. // FADD -> FMA combines:
  13440. if (SDValue Fused = visitFADDForFMACombine(N)) {
  13441. AddToWorklist(Fused.getNode());
  13442. return Fused;
  13443. }
  13444. return SDValue();
  13445. }
  13446. SDValue DAGCombiner::visitSTRICT_FADD(SDNode *N) {
  13447. SDValue Chain = N->getOperand(0);
  13448. SDValue N0 = N->getOperand(1);
  13449. SDValue N1 = N->getOperand(2);
  13450. EVT VT = N->getValueType(0);
  13451. EVT ChainVT = N->getValueType(1);
  13452. SDLoc DL(N);
  13453. SelectionDAG::FlagInserter FlagsInserter(DAG, N);
  13454. // fold (strict_fadd A, (fneg B)) -> (strict_fsub A, B)
  13455. if (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::STRICT_FSUB, VT))
  13456. if (SDValue NegN1 = TLI.getCheaperNegatedExpression(
  13457. N1, DAG, LegalOperations, ForCodeSize)) {
  13458. return DAG.getNode(ISD::STRICT_FSUB, DL, DAG.getVTList(VT, ChainVT),
  13459. {Chain, N0, NegN1});
  13460. }
  13461. // fold (strict_fadd (fneg A), B) -> (strict_fsub B, A)
  13462. if (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::STRICT_FSUB, VT))
  13463. if (SDValue NegN0 = TLI.getCheaperNegatedExpression(
  13464. N0, DAG, LegalOperations, ForCodeSize)) {
  13465. return DAG.getNode(ISD::STRICT_FSUB, DL, DAG.getVTList(VT, ChainVT),
  13466. {Chain, N1, NegN0});
  13467. }
  13468. return SDValue();
  13469. }
  13470. SDValue DAGCombiner::visitFSUB(SDNode *N) {
  13471. SDValue N0 = N->getOperand(0);
  13472. SDValue N1 = N->getOperand(1);
  13473. ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0, true);
  13474. ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1, true);
  13475. EVT VT = N->getValueType(0);
  13476. SDLoc DL(N);
  13477. const TargetOptions &Options = DAG.getTarget().Options;
  13478. const SDNodeFlags Flags = N->getFlags();
  13479. SelectionDAG::FlagInserter FlagsInserter(DAG, N);
  13480. if (SDValue R = DAG.simplifyFPBinop(N->getOpcode(), N0, N1, Flags))
  13481. return R;
  13482. // fold (fsub c1, c2) -> c1-c2
  13483. if (SDValue C = DAG.FoldConstantArithmetic(ISD::FSUB, DL, VT, {N0, N1}))
  13484. return C;
  13485. // fold vector ops
  13486. if (VT.isVector())
  13487. if (SDValue FoldedVOp = SimplifyVBinOp(N, DL))
  13488. return FoldedVOp;
  13489. if (SDValue NewSel = foldBinOpIntoSelect(N))
  13490. return NewSel;
  13491. // (fsub A, 0) -> A
  13492. if (N1CFP && N1CFP->isZero()) {
  13493. if (!N1CFP->isNegative() || Options.NoSignedZerosFPMath ||
  13494. Flags.hasNoSignedZeros()) {
  13495. return N0;
  13496. }
  13497. }
  13498. if (N0 == N1) {
  13499. // (fsub x, x) -> 0.0
  13500. if (Options.NoNaNsFPMath || Flags.hasNoNaNs())
  13501. return DAG.getConstantFP(0.0f, DL, VT);
  13502. }
  13503. // (fsub -0.0, N1) -> -N1
  13504. if (N0CFP && N0CFP->isZero()) {
  13505. if (N0CFP->isNegative() ||
  13506. (Options.NoSignedZerosFPMath || Flags.hasNoSignedZeros())) {
  13507. // We cannot replace an FSUB(+-0.0,X) with FNEG(X) when denormals are
  13508. // flushed to zero, unless all users treat denorms as zero (DAZ).
  13509. // FIXME: This transform will change the sign of a NaN and the behavior
  13510. // of a signaling NaN. It is only valid when a NoNaN flag is present.
  13511. DenormalMode DenormMode = DAG.getDenormalMode(VT);
  13512. if (DenormMode == DenormalMode::getIEEE()) {
  13513. if (SDValue NegN1 =
  13514. TLI.getNegatedExpression(N1, DAG, LegalOperations, ForCodeSize))
  13515. return NegN1;
  13516. if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
  13517. return DAG.getNode(ISD::FNEG, DL, VT, N1);
  13518. }
  13519. }
  13520. }
  13521. if (((Options.UnsafeFPMath && Options.NoSignedZerosFPMath) ||
  13522. (Flags.hasAllowReassociation() && Flags.hasNoSignedZeros())) &&
  13523. N1.getOpcode() == ISD::FADD) {
  13524. // X - (X + Y) -> -Y
  13525. if (N0 == N1->getOperand(0))
  13526. return DAG.getNode(ISD::FNEG, DL, VT, N1->getOperand(1));
  13527. // X - (Y + X) -> -Y
  13528. if (N0 == N1->getOperand(1))
  13529. return DAG.getNode(ISD::FNEG, DL, VT, N1->getOperand(0));
  13530. }
  13531. // fold (fsub A, (fneg B)) -> (fadd A, B)
  13532. if (SDValue NegN1 =
  13533. TLI.getNegatedExpression(N1, DAG, LegalOperations, ForCodeSize))
  13534. return DAG.getNode(ISD::FADD, DL, VT, N0, NegN1);
  13535. // FSUB -> FMA combines:
  13536. if (SDValue Fused = visitFSUBForFMACombine(N)) {
  13537. AddToWorklist(Fused.getNode());
  13538. return Fused;
  13539. }
  13540. return SDValue();
  13541. }
  13542. SDValue DAGCombiner::visitFMUL(SDNode *N) {
  13543. SDValue N0 = N->getOperand(0);
  13544. SDValue N1 = N->getOperand(1);
  13545. ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1, true);
  13546. EVT VT = N->getValueType(0);
  13547. SDLoc DL(N);
  13548. const TargetOptions &Options = DAG.getTarget().Options;
  13549. const SDNodeFlags Flags = N->getFlags();
  13550. SelectionDAG::FlagInserter FlagsInserter(DAG, N);
  13551. if (SDValue R = DAG.simplifyFPBinop(N->getOpcode(), N0, N1, Flags))
  13552. return R;
  13553. // fold (fmul c1, c2) -> c1*c2
  13554. if (SDValue C = DAG.FoldConstantArithmetic(ISD::FMUL, DL, VT, {N0, N1}))
  13555. return C;
  13556. // canonicalize constant to RHS
  13557. if (DAG.isConstantFPBuildVectorOrConstantFP(N0) &&
  13558. !DAG.isConstantFPBuildVectorOrConstantFP(N1))
  13559. return DAG.getNode(ISD::FMUL, DL, VT, N1, N0);
  13560. // fold vector ops
  13561. if (VT.isVector())
  13562. if (SDValue FoldedVOp = SimplifyVBinOp(N, DL))
  13563. return FoldedVOp;
  13564. if (SDValue NewSel = foldBinOpIntoSelect(N))
  13565. return NewSel;
  13566. if (Options.UnsafeFPMath || Flags.hasAllowReassociation()) {
  13567. // fmul (fmul X, C1), C2 -> fmul X, C1 * C2
  13568. if (DAG.isConstantFPBuildVectorOrConstantFP(N1) &&
  13569. N0.getOpcode() == ISD::FMUL) {
  13570. SDValue N00 = N0.getOperand(0);
  13571. SDValue N01 = N0.getOperand(1);
  13572. // Avoid an infinite loop by making sure that N00 is not a constant
  13573. // (the inner multiply has not been constant folded yet).
  13574. if (DAG.isConstantFPBuildVectorOrConstantFP(N01) &&
  13575. !DAG.isConstantFPBuildVectorOrConstantFP(N00)) {
  13576. SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, N01, N1);
  13577. return DAG.getNode(ISD::FMUL, DL, VT, N00, MulConsts);
  13578. }
  13579. }
  13580. // Match a special-case: we convert X * 2.0 into fadd.
  13581. // fmul (fadd X, X), C -> fmul X, 2.0 * C
  13582. if (N0.getOpcode() == ISD::FADD && N0.hasOneUse() &&
  13583. N0.getOperand(0) == N0.getOperand(1)) {
  13584. const SDValue Two = DAG.getConstantFP(2.0, DL, VT);
  13585. SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, Two, N1);
  13586. return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), MulConsts);
  13587. }
  13588. }
  13589. // fold (fmul X, 2.0) -> (fadd X, X)
  13590. if (N1CFP && N1CFP->isExactlyValue(+2.0))
  13591. return DAG.getNode(ISD::FADD, DL, VT, N0, N0);
  13592. // fold (fmul X, -1.0) -> (fsub -0.0, X)
  13593. if (N1CFP && N1CFP->isExactlyValue(-1.0)) {
  13594. if (!LegalOperations || TLI.isOperationLegal(ISD::FSUB, VT)) {
  13595. return DAG.getNode(ISD::FSUB, DL, VT,
  13596. DAG.getConstantFP(-0.0, DL, VT), N0, Flags);
  13597. }
  13598. }
  13599. // -N0 * -N1 --> N0 * N1
  13600. TargetLowering::NegatibleCost CostN0 =
  13601. TargetLowering::NegatibleCost::Expensive;
  13602. TargetLowering::NegatibleCost CostN1 =
  13603. TargetLowering::NegatibleCost::Expensive;
  13604. SDValue NegN0 =
  13605. TLI.getNegatedExpression(N0, DAG, LegalOperations, ForCodeSize, CostN0);
  13606. if (NegN0) {
  13607. HandleSDNode NegN0Handle(NegN0);
  13608. SDValue NegN1 =
  13609. TLI.getNegatedExpression(N1, DAG, LegalOperations, ForCodeSize, CostN1);
  13610. if (NegN1 && (CostN0 == TargetLowering::NegatibleCost::Cheaper ||
  13611. CostN1 == TargetLowering::NegatibleCost::Cheaper))
  13612. return DAG.getNode(ISD::FMUL, DL, VT, NegN0, NegN1);
  13613. }
  13614. // fold (fmul X, (select (fcmp X > 0.0), -1.0, 1.0)) -> (fneg (fabs X))
  13615. // fold (fmul X, (select (fcmp X > 0.0), 1.0, -1.0)) -> (fabs X)
  13616. if (Flags.hasNoNaNs() && Flags.hasNoSignedZeros() &&
  13617. (N0.getOpcode() == ISD::SELECT || N1.getOpcode() == ISD::SELECT) &&
  13618. TLI.isOperationLegal(ISD::FABS, VT)) {
  13619. SDValue Select = N0, X = N1;
  13620. if (Select.getOpcode() != ISD::SELECT)
  13621. std::swap(Select, X);
  13622. SDValue Cond = Select.getOperand(0);
  13623. auto TrueOpnd = dyn_cast<ConstantFPSDNode>(Select.getOperand(1));
  13624. auto FalseOpnd = dyn_cast<ConstantFPSDNode>(Select.getOperand(2));
  13625. if (TrueOpnd && FalseOpnd &&
  13626. Cond.getOpcode() == ISD::SETCC && Cond.getOperand(0) == X &&
  13627. isa<ConstantFPSDNode>(Cond.getOperand(1)) &&
  13628. cast<ConstantFPSDNode>(Cond.getOperand(1))->isExactlyValue(0.0)) {
  13629. ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
  13630. switch (CC) {
  13631. default: break;
  13632. case ISD::SETOLT:
  13633. case ISD::SETULT:
  13634. case ISD::SETOLE:
  13635. case ISD::SETULE:
  13636. case ISD::SETLT:
  13637. case ISD::SETLE:
  13638. std::swap(TrueOpnd, FalseOpnd);
  13639. [[fallthrough]];
  13640. case ISD::SETOGT:
  13641. case ISD::SETUGT:
  13642. case ISD::SETOGE:
  13643. case ISD::SETUGE:
  13644. case ISD::SETGT:
  13645. case ISD::SETGE:
  13646. if (TrueOpnd->isExactlyValue(-1.0) && FalseOpnd->isExactlyValue(1.0) &&
  13647. TLI.isOperationLegal(ISD::FNEG, VT))
  13648. return DAG.getNode(ISD::FNEG, DL, VT,
  13649. DAG.getNode(ISD::FABS, DL, VT, X));
  13650. if (TrueOpnd->isExactlyValue(1.0) && FalseOpnd->isExactlyValue(-1.0))
  13651. return DAG.getNode(ISD::FABS, DL, VT, X);
  13652. break;
  13653. }
  13654. }
  13655. }
  13656. // FMUL -> FMA combines:
  13657. if (SDValue Fused = visitFMULForFMADistributiveCombine(N)) {
  13658. AddToWorklist(Fused.getNode());
  13659. return Fused;
  13660. }
  13661. return SDValue();
  13662. }
  13663. SDValue DAGCombiner::visitFMA(SDNode *N) {
  13664. SDValue N0 = N->getOperand(0);
  13665. SDValue N1 = N->getOperand(1);
  13666. SDValue N2 = N->getOperand(2);
  13667. ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
  13668. ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
  13669. EVT VT = N->getValueType(0);
  13670. SDLoc DL(N);
  13671. const TargetOptions &Options = DAG.getTarget().Options;
  13672. // FMA nodes have flags that propagate to the created nodes.
  13673. SelectionDAG::FlagInserter FlagsInserter(DAG, N);
  13674. bool CanReassociate =
  13675. Options.UnsafeFPMath || N->getFlags().hasAllowReassociation();
  13676. // Constant fold FMA.
  13677. if (isa<ConstantFPSDNode>(N0) &&
  13678. isa<ConstantFPSDNode>(N1) &&
  13679. isa<ConstantFPSDNode>(N2)) {
  13680. return DAG.getNode(ISD::FMA, DL, VT, N0, N1, N2);
  13681. }
  13682. // (-N0 * -N1) + N2 --> (N0 * N1) + N2
  13683. TargetLowering::NegatibleCost CostN0 =
  13684. TargetLowering::NegatibleCost::Expensive;
  13685. TargetLowering::NegatibleCost CostN1 =
  13686. TargetLowering::NegatibleCost::Expensive;
  13687. SDValue NegN0 =
  13688. TLI.getNegatedExpression(N0, DAG, LegalOperations, ForCodeSize, CostN0);
  13689. if (NegN0) {
  13690. HandleSDNode NegN0Handle(NegN0);
  13691. SDValue NegN1 =
  13692. TLI.getNegatedExpression(N1, DAG, LegalOperations, ForCodeSize, CostN1);
  13693. if (NegN1 && (CostN0 == TargetLowering::NegatibleCost::Cheaper ||
  13694. CostN1 == TargetLowering::NegatibleCost::Cheaper))
  13695. return DAG.getNode(ISD::FMA, DL, VT, NegN0, NegN1, N2);
  13696. }
  13697. // FIXME: use fast math flags instead of Options.UnsafeFPMath
  13698. if (Options.UnsafeFPMath) {
  13699. if (N0CFP && N0CFP->isZero())
  13700. return N2;
  13701. if (N1CFP && N1CFP->isZero())
  13702. return N2;
  13703. }
  13704. if (N0CFP && N0CFP->isExactlyValue(1.0))
  13705. return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
  13706. if (N1CFP && N1CFP->isExactlyValue(1.0))
  13707. return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
  13708. // Canonicalize (fma c, x, y) -> (fma x, c, y)
  13709. if (DAG.isConstantFPBuildVectorOrConstantFP(N0) &&
  13710. !DAG.isConstantFPBuildVectorOrConstantFP(N1))
  13711. return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
  13712. if (CanReassociate) {
  13713. // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
  13714. if (N2.getOpcode() == ISD::FMUL && N0 == N2.getOperand(0) &&
  13715. DAG.isConstantFPBuildVectorOrConstantFP(N1) &&
  13716. DAG.isConstantFPBuildVectorOrConstantFP(N2.getOperand(1))) {
  13717. return DAG.getNode(ISD::FMUL, DL, VT, N0,
  13718. DAG.getNode(ISD::FADD, DL, VT, N1, N2.getOperand(1)));
  13719. }
  13720. // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
  13721. if (N0.getOpcode() == ISD::FMUL &&
  13722. DAG.isConstantFPBuildVectorOrConstantFP(N1) &&
  13723. DAG.isConstantFPBuildVectorOrConstantFP(N0.getOperand(1))) {
  13724. return DAG.getNode(ISD::FMA, DL, VT, N0.getOperand(0),
  13725. DAG.getNode(ISD::FMUL, DL, VT, N1, N0.getOperand(1)),
  13726. N2);
  13727. }
  13728. }
  13729. // (fma x, -1, y) -> (fadd (fneg x), y)
  13730. if (N1CFP) {
  13731. if (N1CFP->isExactlyValue(1.0))
  13732. return DAG.getNode(ISD::FADD, DL, VT, N0, N2);
  13733. if (N1CFP->isExactlyValue(-1.0) &&
  13734. (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
  13735. SDValue RHSNeg = DAG.getNode(ISD::FNEG, DL, VT, N0);
  13736. AddToWorklist(RHSNeg.getNode());
  13737. return DAG.getNode(ISD::FADD, DL, VT, N2, RHSNeg);
  13738. }
  13739. // fma (fneg x), K, y -> fma x -K, y
  13740. if (N0.getOpcode() == ISD::FNEG &&
  13741. (TLI.isOperationLegal(ISD::ConstantFP, VT) ||
  13742. (N1.hasOneUse() && !TLI.isFPImmLegal(N1CFP->getValueAPF(), VT,
  13743. ForCodeSize)))) {
  13744. return DAG.getNode(ISD::FMA, DL, VT, N0.getOperand(0),
  13745. DAG.getNode(ISD::FNEG, DL, VT, N1), N2);
  13746. }
  13747. }
  13748. if (CanReassociate) {
  13749. // (fma x, c, x) -> (fmul x, (c+1))
  13750. if (N1CFP && N0 == N2) {
  13751. return DAG.getNode(
  13752. ISD::FMUL, DL, VT, N0,
  13753. DAG.getNode(ISD::FADD, DL, VT, N1, DAG.getConstantFP(1.0, DL, VT)));
  13754. }
  13755. // (fma x, c, (fneg x)) -> (fmul x, (c-1))
  13756. if (N1CFP && N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0) {
  13757. return DAG.getNode(
  13758. ISD::FMUL, DL, VT, N0,
  13759. DAG.getNode(ISD::FADD, DL, VT, N1, DAG.getConstantFP(-1.0, DL, VT)));
  13760. }
  13761. }
  13762. // fold ((fma (fneg X), Y, (fneg Z)) -> fneg (fma X, Y, Z))
  13763. // fold ((fma X, (fneg Y), (fneg Z)) -> fneg (fma X, Y, Z))
  13764. if (!TLI.isFNegFree(VT))
  13765. if (SDValue Neg = TLI.getCheaperNegatedExpression(
  13766. SDValue(N, 0), DAG, LegalOperations, ForCodeSize))
  13767. return DAG.getNode(ISD::FNEG, DL, VT, Neg);
  13768. return SDValue();
  13769. }
  13770. // Combine multiple FDIVs with the same divisor into multiple FMULs by the
  13771. // reciprocal.
  13772. // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip)
  13773. // Notice that this is not always beneficial. One reason is different targets
  13774. // may have different costs for FDIV and FMUL, so sometimes the cost of two
  13775. // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason
  13776. // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL".
  13777. SDValue DAGCombiner::combineRepeatedFPDivisors(SDNode *N) {
  13778. // TODO: Limit this transform based on optsize/minsize - it always creates at
  13779. // least 1 extra instruction. But the perf win may be substantial enough
  13780. // that only minsize should restrict this.
  13781. bool UnsafeMath = DAG.getTarget().Options.UnsafeFPMath;
  13782. const SDNodeFlags Flags = N->getFlags();
  13783. if (LegalDAG || (!UnsafeMath && !Flags.hasAllowReciprocal()))
  13784. return SDValue();
  13785. // Skip if current node is a reciprocal/fneg-reciprocal.
  13786. SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
  13787. ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0, /* AllowUndefs */ true);
  13788. if (N0CFP && (N0CFP->isExactlyValue(1.0) || N0CFP->isExactlyValue(-1.0)))
  13789. return SDValue();
  13790. // Exit early if the target does not want this transform or if there can't
  13791. // possibly be enough uses of the divisor to make the transform worthwhile.
  13792. unsigned MinUses = TLI.combineRepeatedFPDivisors();
  13793. // For splat vectors, scale the number of uses by the splat factor. If we can
  13794. // convert the division into a scalar op, that will likely be much faster.
  13795. unsigned NumElts = 1;
  13796. EVT VT = N->getValueType(0);
  13797. if (VT.isVector() && DAG.isSplatValue(N1))
  13798. NumElts = VT.getVectorMinNumElements();
  13799. if (!MinUses || (N1->use_size() * NumElts) < MinUses)
  13800. return SDValue();
  13801. // Find all FDIV users of the same divisor.
  13802. // Use a set because duplicates may be present in the user list.
  13803. SetVector<SDNode *> Users;
  13804. for (auto *U : N1->uses()) {
  13805. if (U->getOpcode() == ISD::FDIV && U->getOperand(1) == N1) {
  13806. // Skip X/sqrt(X) that has not been simplified to sqrt(X) yet.
  13807. if (U->getOperand(1).getOpcode() == ISD::FSQRT &&
  13808. U->getOperand(0) == U->getOperand(1).getOperand(0) &&
  13809. U->getFlags().hasAllowReassociation() &&
  13810. U->getFlags().hasNoSignedZeros())
  13811. continue;
  13812. // This division is eligible for optimization only if global unsafe math
  13813. // is enabled or if this division allows reciprocal formation.
  13814. if (UnsafeMath || U->getFlags().hasAllowReciprocal())
  13815. Users.insert(U);
  13816. }
  13817. }
  13818. // Now that we have the actual number of divisor uses, make sure it meets
  13819. // the minimum threshold specified by the target.
  13820. if ((Users.size() * NumElts) < MinUses)
  13821. return SDValue();
  13822. SDLoc DL(N);
  13823. SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
  13824. SDValue Reciprocal = DAG.getNode(ISD::FDIV, DL, VT, FPOne, N1, Flags);
  13825. // Dividend / Divisor -> Dividend * Reciprocal
  13826. for (auto *U : Users) {
  13827. SDValue Dividend = U->getOperand(0);
  13828. if (Dividend != FPOne) {
  13829. SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(U), VT, Dividend,
  13830. Reciprocal, Flags);
  13831. CombineTo(U, NewNode);
  13832. } else if (U != Reciprocal.getNode()) {
  13833. // In the absence of fast-math-flags, this user node is always the
  13834. // same node as Reciprocal, but with FMF they may be different nodes.
  13835. CombineTo(U, Reciprocal);
  13836. }
  13837. }
  13838. return SDValue(N, 0); // N was replaced.
  13839. }
  13840. SDValue DAGCombiner::visitFDIV(SDNode *N) {
  13841. SDValue N0 = N->getOperand(0);
  13842. SDValue N1 = N->getOperand(1);
  13843. EVT VT = N->getValueType(0);
  13844. SDLoc DL(N);
  13845. const TargetOptions &Options = DAG.getTarget().Options;
  13846. SDNodeFlags Flags = N->getFlags();
  13847. SelectionDAG::FlagInserter FlagsInserter(DAG, N);
  13848. if (SDValue R = DAG.simplifyFPBinop(N->getOpcode(), N0, N1, Flags))
  13849. return R;
  13850. // fold (fdiv c1, c2) -> c1/c2
  13851. if (SDValue C = DAG.FoldConstantArithmetic(ISD::FDIV, DL, VT, {N0, N1}))
  13852. return C;
  13853. // fold vector ops
  13854. if (VT.isVector())
  13855. if (SDValue FoldedVOp = SimplifyVBinOp(N, DL))
  13856. return FoldedVOp;
  13857. if (SDValue NewSel = foldBinOpIntoSelect(N))
  13858. return NewSel;
  13859. if (SDValue V = combineRepeatedFPDivisors(N))
  13860. return V;
  13861. if (Options.UnsafeFPMath || Flags.hasAllowReciprocal()) {
  13862. // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
  13863. if (auto *N1CFP = dyn_cast<ConstantFPSDNode>(N1)) {
  13864. // Compute the reciprocal 1.0 / c2.
  13865. const APFloat &N1APF = N1CFP->getValueAPF();
  13866. APFloat Recip(N1APF.getSemantics(), 1); // 1.0
  13867. APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
  13868. // Only do the transform if the reciprocal is a legal fp immediate that
  13869. // isn't too nasty (eg NaN, denormal, ...).
  13870. if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
  13871. (!LegalOperations ||
  13872. // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
  13873. // backend)... we should handle this gracefully after Legalize.
  13874. // TLI.isOperationLegalOrCustom(ISD::ConstantFP, VT) ||
  13875. TLI.isOperationLegal(ISD::ConstantFP, VT) ||
  13876. TLI.isFPImmLegal(Recip, VT, ForCodeSize)))
  13877. return DAG.getNode(ISD::FMUL, DL, VT, N0,
  13878. DAG.getConstantFP(Recip, DL, VT));
  13879. }
  13880. // If this FDIV is part of a reciprocal square root, it may be folded
  13881. // into a target-specific square root estimate instruction.
  13882. if (N1.getOpcode() == ISD::FSQRT) {
  13883. if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0), Flags))
  13884. return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
  13885. } else if (N1.getOpcode() == ISD::FP_EXTEND &&
  13886. N1.getOperand(0).getOpcode() == ISD::FSQRT) {
  13887. if (SDValue RV =
  13888. buildRsqrtEstimate(N1.getOperand(0).getOperand(0), Flags)) {
  13889. RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV);
  13890. AddToWorklist(RV.getNode());
  13891. return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
  13892. }
  13893. } else if (N1.getOpcode() == ISD::FP_ROUND &&
  13894. N1.getOperand(0).getOpcode() == ISD::FSQRT) {
  13895. if (SDValue RV =
  13896. buildRsqrtEstimate(N1.getOperand(0).getOperand(0), Flags)) {
  13897. RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1));
  13898. AddToWorklist(RV.getNode());
  13899. return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
  13900. }
  13901. } else if (N1.getOpcode() == ISD::FMUL) {
  13902. // Look through an FMUL. Even though this won't remove the FDIV directly,
  13903. // it's still worthwhile to get rid of the FSQRT if possible.
  13904. SDValue Sqrt, Y;
  13905. if (N1.getOperand(0).getOpcode() == ISD::FSQRT) {
  13906. Sqrt = N1.getOperand(0);
  13907. Y = N1.getOperand(1);
  13908. } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) {
  13909. Sqrt = N1.getOperand(1);
  13910. Y = N1.getOperand(0);
  13911. }
  13912. if (Sqrt.getNode()) {
  13913. // If the other multiply operand is known positive, pull it into the
  13914. // sqrt. That will eliminate the division if we convert to an estimate.
  13915. if (Flags.hasAllowReassociation() && N1.hasOneUse() &&
  13916. N1->getFlags().hasAllowReassociation() && Sqrt.hasOneUse()) {
  13917. SDValue A;
  13918. if (Y.getOpcode() == ISD::FABS && Y.hasOneUse())
  13919. A = Y.getOperand(0);
  13920. else if (Y == Sqrt.getOperand(0))
  13921. A = Y;
  13922. if (A) {
  13923. // X / (fabs(A) * sqrt(Z)) --> X / sqrt(A*A*Z) --> X * rsqrt(A*A*Z)
  13924. // X / (A * sqrt(A)) --> X / sqrt(A*A*A) --> X * rsqrt(A*A*A)
  13925. SDValue AA = DAG.getNode(ISD::FMUL, DL, VT, A, A);
  13926. SDValue AAZ =
  13927. DAG.getNode(ISD::FMUL, DL, VT, AA, Sqrt.getOperand(0));
  13928. if (SDValue Rsqrt = buildRsqrtEstimate(AAZ, Flags))
  13929. return DAG.getNode(ISD::FMUL, DL, VT, N0, Rsqrt);
  13930. // Estimate creation failed. Clean up speculatively created nodes.
  13931. recursivelyDeleteUnusedNodes(AAZ.getNode());
  13932. }
  13933. }
  13934. // We found a FSQRT, so try to make this fold:
  13935. // X / (Y * sqrt(Z)) -> X * (rsqrt(Z) / Y)
  13936. if (SDValue Rsqrt = buildRsqrtEstimate(Sqrt.getOperand(0), Flags)) {
  13937. SDValue Div = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, Rsqrt, Y);
  13938. AddToWorklist(Div.getNode());
  13939. return DAG.getNode(ISD::FMUL, DL, VT, N0, Div);
  13940. }
  13941. }
  13942. }
  13943. // Fold into a reciprocal estimate and multiply instead of a real divide.
  13944. if (Options.NoInfsFPMath || Flags.hasNoInfs())
  13945. if (SDValue RV = BuildDivEstimate(N0, N1, Flags))
  13946. return RV;
  13947. }
  13948. // Fold X/Sqrt(X) -> Sqrt(X)
  13949. if ((Options.NoSignedZerosFPMath || Flags.hasNoSignedZeros()) &&
  13950. (Options.UnsafeFPMath || Flags.hasAllowReassociation()))
  13951. if (N1.getOpcode() == ISD::FSQRT && N0 == N1.getOperand(0))
  13952. return N1;
  13953. // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
  13954. TargetLowering::NegatibleCost CostN0 =
  13955. TargetLowering::NegatibleCost::Expensive;
  13956. TargetLowering::NegatibleCost CostN1 =
  13957. TargetLowering::NegatibleCost::Expensive;
  13958. SDValue NegN0 =
  13959. TLI.getNegatedExpression(N0, DAG, LegalOperations, ForCodeSize, CostN0);
  13960. if (NegN0) {
  13961. HandleSDNode NegN0Handle(NegN0);
  13962. SDValue NegN1 =
  13963. TLI.getNegatedExpression(N1, DAG, LegalOperations, ForCodeSize, CostN1);
  13964. if (NegN1 && (CostN0 == TargetLowering::NegatibleCost::Cheaper ||
  13965. CostN1 == TargetLowering::NegatibleCost::Cheaper))
  13966. return DAG.getNode(ISD::FDIV, SDLoc(N), VT, NegN0, NegN1);
  13967. }
  13968. return SDValue();
  13969. }
  13970. SDValue DAGCombiner::visitFREM(SDNode *N) {
  13971. SDValue N0 = N->getOperand(0);
  13972. SDValue N1 = N->getOperand(1);
  13973. EVT VT = N->getValueType(0);
  13974. SDNodeFlags Flags = N->getFlags();
  13975. SelectionDAG::FlagInserter FlagsInserter(DAG, N);
  13976. if (SDValue R = DAG.simplifyFPBinop(N->getOpcode(), N0, N1, Flags))
  13977. return R;
  13978. // fold (frem c1, c2) -> fmod(c1,c2)
  13979. if (SDValue C = DAG.FoldConstantArithmetic(ISD::FREM, SDLoc(N), VT, {N0, N1}))
  13980. return C;
  13981. if (SDValue NewSel = foldBinOpIntoSelect(N))
  13982. return NewSel;
  13983. return SDValue();
  13984. }
  13985. SDValue DAGCombiner::visitFSQRT(SDNode *N) {
  13986. SDNodeFlags Flags = N->getFlags();
  13987. const TargetOptions &Options = DAG.getTarget().Options;
  13988. // Require 'ninf' flag since sqrt(+Inf) = +Inf, but the estimation goes as:
  13989. // sqrt(+Inf) == rsqrt(+Inf) * +Inf = 0 * +Inf = NaN
  13990. if (!Flags.hasApproximateFuncs() ||
  13991. (!Options.NoInfsFPMath && !Flags.hasNoInfs()))
  13992. return SDValue();
  13993. SDValue N0 = N->getOperand(0);
  13994. if (TLI.isFsqrtCheap(N0, DAG))
  13995. return SDValue();
  13996. // FSQRT nodes have flags that propagate to the created nodes.
  13997. // TODO: If this is N0/sqrt(N0), and we reach this node before trying to
  13998. // transform the fdiv, we may produce a sub-optimal estimate sequence
  13999. // because the reciprocal calculation may not have to filter out a
  14000. // 0.0 input.
  14001. return buildSqrtEstimate(N0, Flags);
  14002. }
  14003. /// copysign(x, fp_extend(y)) -> copysign(x, y)
  14004. /// copysign(x, fp_round(y)) -> copysign(x, y)
  14005. static inline bool CanCombineFCOPYSIGN_EXTEND_ROUND(SDNode *N) {
  14006. SDValue N1 = N->getOperand(1);
  14007. if ((N1.getOpcode() == ISD::FP_EXTEND ||
  14008. N1.getOpcode() == ISD::FP_ROUND)) {
  14009. EVT N1VT = N1->getValueType(0);
  14010. EVT N1Op0VT = N1->getOperand(0).getValueType();
  14011. // Always fold no-op FP casts.
  14012. if (N1VT == N1Op0VT)
  14013. return true;
  14014. // Do not optimize out type conversion of f128 type yet.
  14015. // For some targets like x86_64, configuration is changed to keep one f128
  14016. // value in one SSE register, but instruction selection cannot handle
  14017. // FCOPYSIGN on SSE registers yet.
  14018. if (N1Op0VT == MVT::f128)
  14019. return false;
  14020. return !N1Op0VT.isVector() || EnableVectorFCopySignExtendRound;
  14021. }
  14022. return false;
  14023. }
  14024. SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
  14025. SDValue N0 = N->getOperand(0);
  14026. SDValue N1 = N->getOperand(1);
  14027. EVT VT = N->getValueType(0);
  14028. // fold (fcopysign c1, c2) -> fcopysign(c1,c2)
  14029. if (SDValue C =
  14030. DAG.FoldConstantArithmetic(ISD::FCOPYSIGN, SDLoc(N), VT, {N0, N1}))
  14031. return C;
  14032. if (ConstantFPSDNode *N1C = isConstOrConstSplatFP(N->getOperand(1))) {
  14033. const APFloat &V = N1C->getValueAPF();
  14034. // copysign(x, c1) -> fabs(x) iff ispos(c1)
  14035. // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
  14036. if (!V.isNegative()) {
  14037. if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
  14038. return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
  14039. } else {
  14040. if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
  14041. return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
  14042. DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
  14043. }
  14044. }
  14045. // copysign(fabs(x), y) -> copysign(x, y)
  14046. // copysign(fneg(x), y) -> copysign(x, y)
  14047. // copysign(copysign(x,z), y) -> copysign(x, y)
  14048. if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
  14049. N0.getOpcode() == ISD::FCOPYSIGN)
  14050. return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0.getOperand(0), N1);
  14051. // copysign(x, abs(y)) -> abs(x)
  14052. if (N1.getOpcode() == ISD::FABS)
  14053. return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
  14054. // copysign(x, copysign(y,z)) -> copysign(x, z)
  14055. if (N1.getOpcode() == ISD::FCOPYSIGN)
  14056. return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1.getOperand(1));
  14057. // copysign(x, fp_extend(y)) -> copysign(x, y)
  14058. // copysign(x, fp_round(y)) -> copysign(x, y)
  14059. if (CanCombineFCOPYSIGN_EXTEND_ROUND(N))
  14060. return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1.getOperand(0));
  14061. return SDValue();
  14062. }
  14063. SDValue DAGCombiner::visitFPOW(SDNode *N) {
  14064. ConstantFPSDNode *ExponentC = isConstOrConstSplatFP(N->getOperand(1));
  14065. if (!ExponentC)
  14066. return SDValue();
  14067. SelectionDAG::FlagInserter FlagsInserter(DAG, N);
  14068. // Try to convert x ** (1/3) into cube root.
  14069. // TODO: Handle the various flavors of long double.
  14070. // TODO: Since we're approximating, we don't need an exact 1/3 exponent.
  14071. // Some range near 1/3 should be fine.
  14072. EVT VT = N->getValueType(0);
  14073. if ((VT == MVT::f32 && ExponentC->getValueAPF().isExactlyValue(1.0f/3.0f)) ||
  14074. (VT == MVT::f64 && ExponentC->getValueAPF().isExactlyValue(1.0/3.0))) {
  14075. // pow(-0.0, 1/3) = +0.0; cbrt(-0.0) = -0.0.
  14076. // pow(-inf, 1/3) = +inf; cbrt(-inf) = -inf.
  14077. // pow(-val, 1/3) = nan; cbrt(-val) = -num.
  14078. // For regular numbers, rounding may cause the results to differ.
  14079. // Therefore, we require { nsz ninf nnan afn } for this transform.
  14080. // TODO: We could select out the special cases if we don't have nsz/ninf.
  14081. SDNodeFlags Flags = N->getFlags();
  14082. if (!Flags.hasNoSignedZeros() || !Flags.hasNoInfs() || !Flags.hasNoNaNs() ||
  14083. !Flags.hasApproximateFuncs())
  14084. return SDValue();
  14085. // Do not create a cbrt() libcall if the target does not have it, and do not
  14086. // turn a pow that has lowering support into a cbrt() libcall.
  14087. if (!DAG.getLibInfo().has(LibFunc_cbrt) ||
  14088. (!DAG.getTargetLoweringInfo().isOperationExpand(ISD::FPOW, VT) &&
  14089. DAG.getTargetLoweringInfo().isOperationExpand(ISD::FCBRT, VT)))
  14090. return SDValue();
  14091. return DAG.getNode(ISD::FCBRT, SDLoc(N), VT, N->getOperand(0));
  14092. }
  14093. // Try to convert x ** (1/4) and x ** (3/4) into square roots.
  14094. // x ** (1/2) is canonicalized to sqrt, so we do not bother with that case.
  14095. // TODO: This could be extended (using a target hook) to handle smaller
  14096. // power-of-2 fractional exponents.
  14097. bool ExponentIs025 = ExponentC->getValueAPF().isExactlyValue(0.25);
  14098. bool ExponentIs075 = ExponentC->getValueAPF().isExactlyValue(0.75);
  14099. if (ExponentIs025 || ExponentIs075) {
  14100. // pow(-0.0, 0.25) = +0.0; sqrt(sqrt(-0.0)) = -0.0.
  14101. // pow(-inf, 0.25) = +inf; sqrt(sqrt(-inf)) = NaN.
  14102. // pow(-0.0, 0.75) = +0.0; sqrt(-0.0) * sqrt(sqrt(-0.0)) = +0.0.
  14103. // pow(-inf, 0.75) = +inf; sqrt(-inf) * sqrt(sqrt(-inf)) = NaN.
  14104. // For regular numbers, rounding may cause the results to differ.
  14105. // Therefore, we require { nsz ninf afn } for this transform.
  14106. // TODO: We could select out the special cases if we don't have nsz/ninf.
  14107. SDNodeFlags Flags = N->getFlags();
  14108. // We only need no signed zeros for the 0.25 case.
  14109. if ((!Flags.hasNoSignedZeros() && ExponentIs025) || !Flags.hasNoInfs() ||
  14110. !Flags.hasApproximateFuncs())
  14111. return SDValue();
  14112. // Don't double the number of libcalls. We are trying to inline fast code.
  14113. if (!DAG.getTargetLoweringInfo().isOperationLegalOrCustom(ISD::FSQRT, VT))
  14114. return SDValue();
  14115. // Assume that libcalls are the smallest code.
  14116. // TODO: This restriction should probably be lifted for vectors.
  14117. if (ForCodeSize)
  14118. return SDValue();
  14119. // pow(X, 0.25) --> sqrt(sqrt(X))
  14120. SDLoc DL(N);
  14121. SDValue Sqrt = DAG.getNode(ISD::FSQRT, DL, VT, N->getOperand(0));
  14122. SDValue SqrtSqrt = DAG.getNode(ISD::FSQRT, DL, VT, Sqrt);
  14123. if (ExponentIs025)
  14124. return SqrtSqrt;
  14125. // pow(X, 0.75) --> sqrt(X) * sqrt(sqrt(X))
  14126. return DAG.getNode(ISD::FMUL, DL, VT, Sqrt, SqrtSqrt);
  14127. }
  14128. return SDValue();
  14129. }
  14130. static SDValue foldFPToIntToFP(SDNode *N, SelectionDAG &DAG,
  14131. const TargetLowering &TLI) {
  14132. // We only do this if the target has legal ftrunc. Otherwise, we'd likely be
  14133. // replacing casts with a libcall. We also must be allowed to ignore -0.0
  14134. // because FTRUNC will return -0.0 for (-1.0, -0.0), but using integer
  14135. // conversions would return +0.0.
  14136. // FIXME: We should be able to use node-level FMF here.
  14137. // TODO: If strict math, should we use FABS (+ range check for signed cast)?
  14138. EVT VT = N->getValueType(0);
  14139. if (!TLI.isOperationLegal(ISD::FTRUNC, VT) ||
  14140. !DAG.getTarget().Options.NoSignedZerosFPMath)
  14141. return SDValue();
  14142. // fptosi/fptoui round towards zero, so converting from FP to integer and
  14143. // back is the same as an 'ftrunc': [us]itofp (fpto[us]i X) --> ftrunc X
  14144. SDValue N0 = N->getOperand(0);
  14145. if (N->getOpcode() == ISD::SINT_TO_FP && N0.getOpcode() == ISD::FP_TO_SINT &&
  14146. N0.getOperand(0).getValueType() == VT)
  14147. return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0.getOperand(0));
  14148. if (N->getOpcode() == ISD::UINT_TO_FP && N0.getOpcode() == ISD::FP_TO_UINT &&
  14149. N0.getOperand(0).getValueType() == VT)
  14150. return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0.getOperand(0));
  14151. return SDValue();
  14152. }
  14153. SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
  14154. SDValue N0 = N->getOperand(0);
  14155. EVT VT = N->getValueType(0);
  14156. EVT OpVT = N0.getValueType();
  14157. // [us]itofp(undef) = 0, because the result value is bounded.
  14158. if (N0.isUndef())
  14159. return DAG.getConstantFP(0.0, SDLoc(N), VT);
  14160. // fold (sint_to_fp c1) -> c1fp
  14161. if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
  14162. // ...but only if the target supports immediate floating-point values
  14163. (!LegalOperations ||
  14164. TLI.isOperationLegalOrCustom(ISD::ConstantFP, VT)))
  14165. return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
  14166. // If the input is a legal type, and SINT_TO_FP is not legal on this target,
  14167. // but UINT_TO_FP is legal on this target, try to convert.
  14168. if (!hasOperation(ISD::SINT_TO_FP, OpVT) &&
  14169. hasOperation(ISD::UINT_TO_FP, OpVT)) {
  14170. // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
  14171. if (DAG.SignBitIsZero(N0))
  14172. return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
  14173. }
  14174. // The next optimizations are desirable only if SELECT_CC can be lowered.
  14175. // fold (sint_to_fp (setcc x, y, cc)) -> (select (setcc x, y, cc), -1.0, 0.0)
  14176. if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
  14177. !VT.isVector() &&
  14178. (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::ConstantFP, VT))) {
  14179. SDLoc DL(N);
  14180. return DAG.getSelect(DL, VT, N0, DAG.getConstantFP(-1.0, DL, VT),
  14181. DAG.getConstantFP(0.0, DL, VT));
  14182. }
  14183. // fold (sint_to_fp (zext (setcc x, y, cc))) ->
  14184. // (select (setcc x, y, cc), 1.0, 0.0)
  14185. if (N0.getOpcode() == ISD::ZERO_EXTEND &&
  14186. N0.getOperand(0).getOpcode() == ISD::SETCC && !VT.isVector() &&
  14187. (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::ConstantFP, VT))) {
  14188. SDLoc DL(N);
  14189. return DAG.getSelect(DL, VT, N0.getOperand(0),
  14190. DAG.getConstantFP(1.0, DL, VT),
  14191. DAG.getConstantFP(0.0, DL, VT));
  14192. }
  14193. if (SDValue FTrunc = foldFPToIntToFP(N, DAG, TLI))
  14194. return FTrunc;
  14195. return SDValue();
  14196. }
  14197. SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
  14198. SDValue N0 = N->getOperand(0);
  14199. EVT VT = N->getValueType(0);
  14200. EVT OpVT = N0.getValueType();
  14201. // [us]itofp(undef) = 0, because the result value is bounded.
  14202. if (N0.isUndef())
  14203. return DAG.getConstantFP(0.0, SDLoc(N), VT);
  14204. // fold (uint_to_fp c1) -> c1fp
  14205. if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
  14206. // ...but only if the target supports immediate floating-point values
  14207. (!LegalOperations ||
  14208. TLI.isOperationLegalOrCustom(ISD::ConstantFP, VT)))
  14209. return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
  14210. // If the input is a legal type, and UINT_TO_FP is not legal on this target,
  14211. // but SINT_TO_FP is legal on this target, try to convert.
  14212. if (!hasOperation(ISD::UINT_TO_FP, OpVT) &&
  14213. hasOperation(ISD::SINT_TO_FP, OpVT)) {
  14214. // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
  14215. if (DAG.SignBitIsZero(N0))
  14216. return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
  14217. }
  14218. // fold (uint_to_fp (setcc x, y, cc)) -> (select (setcc x, y, cc), 1.0, 0.0)
  14219. if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
  14220. (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::ConstantFP, VT))) {
  14221. SDLoc DL(N);
  14222. return DAG.getSelect(DL, VT, N0, DAG.getConstantFP(1.0, DL, VT),
  14223. DAG.getConstantFP(0.0, DL, VT));
  14224. }
  14225. if (SDValue FTrunc = foldFPToIntToFP(N, DAG, TLI))
  14226. return FTrunc;
  14227. return SDValue();
  14228. }
  14229. // Fold (fp_to_{s/u}int ({s/u}int_to_fpx)) -> zext x, sext x, trunc x, or x
  14230. static SDValue FoldIntToFPToInt(SDNode *N, SelectionDAG &DAG) {
  14231. SDValue N0 = N->getOperand(0);
  14232. EVT VT = N->getValueType(0);
  14233. if (N0.getOpcode() != ISD::UINT_TO_FP && N0.getOpcode() != ISD::SINT_TO_FP)
  14234. return SDValue();
  14235. SDValue Src = N0.getOperand(0);
  14236. EVT SrcVT = Src.getValueType();
  14237. bool IsInputSigned = N0.getOpcode() == ISD::SINT_TO_FP;
  14238. bool IsOutputSigned = N->getOpcode() == ISD::FP_TO_SINT;
  14239. // We can safely assume the conversion won't overflow the output range,
  14240. // because (for example) (uint8_t)18293.f is undefined behavior.
  14241. // Since we can assume the conversion won't overflow, our decision as to
  14242. // whether the input will fit in the float should depend on the minimum
  14243. // of the input range and output range.
  14244. // This means this is also safe for a signed input and unsigned output, since
  14245. // a negative input would lead to undefined behavior.
  14246. unsigned InputSize = (int)SrcVT.getScalarSizeInBits() - IsInputSigned;
  14247. unsigned OutputSize = (int)VT.getScalarSizeInBits();
  14248. unsigned ActualSize = std::min(InputSize, OutputSize);
  14249. const fltSemantics &sem = DAG.EVTToAPFloatSemantics(N0.getValueType());
  14250. // We can only fold away the float conversion if the input range can be
  14251. // represented exactly in the float range.
  14252. if (APFloat::semanticsPrecision(sem) >= ActualSize) {
  14253. if (VT.getScalarSizeInBits() > SrcVT.getScalarSizeInBits()) {
  14254. unsigned ExtOp = IsInputSigned && IsOutputSigned ? ISD::SIGN_EXTEND
  14255. : ISD::ZERO_EXTEND;
  14256. return DAG.getNode(ExtOp, SDLoc(N), VT, Src);
  14257. }
  14258. if (VT.getScalarSizeInBits() < SrcVT.getScalarSizeInBits())
  14259. return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Src);
  14260. return DAG.getBitcast(VT, Src);
  14261. }
  14262. return SDValue();
  14263. }
  14264. SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
  14265. SDValue N0 = N->getOperand(0);
  14266. EVT VT = N->getValueType(0);
  14267. // fold (fp_to_sint undef) -> undef
  14268. if (N0.isUndef())
  14269. return DAG.getUNDEF(VT);
  14270. // fold (fp_to_sint c1fp) -> c1
  14271. if (DAG.isConstantFPBuildVectorOrConstantFP(N0))
  14272. return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
  14273. return FoldIntToFPToInt(N, DAG);
  14274. }
  14275. SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
  14276. SDValue N0 = N->getOperand(0);
  14277. EVT VT = N->getValueType(0);
  14278. // fold (fp_to_uint undef) -> undef
  14279. if (N0.isUndef())
  14280. return DAG.getUNDEF(VT);
  14281. // fold (fp_to_uint c1fp) -> c1
  14282. if (DAG.isConstantFPBuildVectorOrConstantFP(N0))
  14283. return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
  14284. return FoldIntToFPToInt(N, DAG);
  14285. }
  14286. SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
  14287. SDValue N0 = N->getOperand(0);
  14288. SDValue N1 = N->getOperand(1);
  14289. EVT VT = N->getValueType(0);
  14290. // fold (fp_round c1fp) -> c1fp
  14291. if (SDValue C =
  14292. DAG.FoldConstantArithmetic(ISD::FP_ROUND, SDLoc(N), VT, {N0, N1}))
  14293. return C;
  14294. // fold (fp_round (fp_extend x)) -> x
  14295. if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
  14296. return N0.getOperand(0);
  14297. // fold (fp_round (fp_round x)) -> (fp_round x)
  14298. if (N0.getOpcode() == ISD::FP_ROUND) {
  14299. const bool NIsTrunc = N->getConstantOperandVal(1) == 1;
  14300. const bool N0IsTrunc = N0.getConstantOperandVal(1) == 1;
  14301. // Skip this folding if it results in an fp_round from f80 to f16.
  14302. //
  14303. // f80 to f16 always generates an expensive (and as yet, unimplemented)
  14304. // libcall to __truncxfhf2 instead of selecting native f16 conversion
  14305. // instructions from f32 or f64. Moreover, the first (value-preserving)
  14306. // fp_round from f80 to either f32 or f64 may become a NOP in platforms like
  14307. // x86.
  14308. if (N0.getOperand(0).getValueType() == MVT::f80 && VT == MVT::f16)
  14309. return SDValue();
  14310. // If the first fp_round isn't a value preserving truncation, it might
  14311. // introduce a tie in the second fp_round, that wouldn't occur in the
  14312. // single-step fp_round we want to fold to.
  14313. // In other words, double rounding isn't the same as rounding.
  14314. // Also, this is a value preserving truncation iff both fp_round's are.
  14315. if (DAG.getTarget().Options.UnsafeFPMath || N0IsTrunc) {
  14316. SDLoc DL(N);
  14317. return DAG.getNode(
  14318. ISD::FP_ROUND, DL, VT, N0.getOperand(0),
  14319. DAG.getIntPtrConstant(NIsTrunc && N0IsTrunc, DL, /*isTarget=*/true));
  14320. }
  14321. }
  14322. // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
  14323. if (N0.getOpcode() == ISD::FCOPYSIGN && N0->hasOneUse()) {
  14324. SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
  14325. N0.getOperand(0), N1);
  14326. AddToWorklist(Tmp.getNode());
  14327. return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
  14328. Tmp, N0.getOperand(1));
  14329. }
  14330. if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N))
  14331. return NewVSel;
  14332. return SDValue();
  14333. }
  14334. SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
  14335. SDValue N0 = N->getOperand(0);
  14336. EVT VT = N->getValueType(0);
  14337. if (VT.isVector())
  14338. if (SDValue FoldedVOp = SimplifyVCastOp(N, SDLoc(N)))
  14339. return FoldedVOp;
  14340. // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
  14341. if (N->hasOneUse() &&
  14342. N->use_begin()->getOpcode() == ISD::FP_ROUND)
  14343. return SDValue();
  14344. // fold (fp_extend c1fp) -> c1fp
  14345. if (DAG.isConstantFPBuildVectorOrConstantFP(N0))
  14346. return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
  14347. // fold (fp_extend (fp16_to_fp op)) -> (fp16_to_fp op)
  14348. if (N0.getOpcode() == ISD::FP16_TO_FP &&
  14349. TLI.getOperationAction(ISD::FP16_TO_FP, VT) == TargetLowering::Legal)
  14350. return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), VT, N0.getOperand(0));
  14351. // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
  14352. // value of X.
  14353. if (N0.getOpcode() == ISD::FP_ROUND
  14354. && N0.getConstantOperandVal(1) == 1) {
  14355. SDValue In = N0.getOperand(0);
  14356. if (In.getValueType() == VT) return In;
  14357. if (VT.bitsLT(In.getValueType()))
  14358. return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
  14359. In, N0.getOperand(1));
  14360. return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
  14361. }
  14362. // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
  14363. if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
  14364. TLI.isLoadExtLegalOrCustom(ISD::EXTLOAD, VT, N0.getValueType())) {
  14365. LoadSDNode *LN0 = cast<LoadSDNode>(N0);
  14366. SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
  14367. LN0->getChain(),
  14368. LN0->getBasePtr(), N0.getValueType(),
  14369. LN0->getMemOperand());
  14370. CombineTo(N, ExtLoad);
  14371. CombineTo(
  14372. N0.getNode(),
  14373. DAG.getNode(ISD::FP_ROUND, SDLoc(N0), N0.getValueType(), ExtLoad,
  14374. DAG.getIntPtrConstant(1, SDLoc(N0), /*isTarget=*/true)),
  14375. ExtLoad.getValue(1));
  14376. return SDValue(N, 0); // Return N so it doesn't get rechecked!
  14377. }
  14378. if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N))
  14379. return NewVSel;
  14380. return SDValue();
  14381. }
  14382. SDValue DAGCombiner::visitFCEIL(SDNode *N) {
  14383. SDValue N0 = N->getOperand(0);
  14384. EVT VT = N->getValueType(0);
  14385. // fold (fceil c1) -> fceil(c1)
  14386. if (DAG.isConstantFPBuildVectorOrConstantFP(N0))
  14387. return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
  14388. return SDValue();
  14389. }
  14390. SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
  14391. SDValue N0 = N->getOperand(0);
  14392. EVT VT = N->getValueType(0);
  14393. // fold (ftrunc c1) -> ftrunc(c1)
  14394. if (DAG.isConstantFPBuildVectorOrConstantFP(N0))
  14395. return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
  14396. // fold ftrunc (known rounded int x) -> x
  14397. // ftrunc is a part of fptosi/fptoui expansion on some targets, so this is
  14398. // likely to be generated to extract integer from a rounded floating value.
  14399. switch (N0.getOpcode()) {
  14400. default: break;
  14401. case ISD::FRINT:
  14402. case ISD::FTRUNC:
  14403. case ISD::FNEARBYINT:
  14404. case ISD::FFLOOR:
  14405. case ISD::FCEIL:
  14406. return N0;
  14407. }
  14408. return SDValue();
  14409. }
  14410. SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
  14411. SDValue N0 = N->getOperand(0);
  14412. EVT VT = N->getValueType(0);
  14413. // fold (ffloor c1) -> ffloor(c1)
  14414. if (DAG.isConstantFPBuildVectorOrConstantFP(N0))
  14415. return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
  14416. return SDValue();
  14417. }
  14418. SDValue DAGCombiner::visitFNEG(SDNode *N) {
  14419. SDValue N0 = N->getOperand(0);
  14420. EVT VT = N->getValueType(0);
  14421. SelectionDAG::FlagInserter FlagsInserter(DAG, N);
  14422. // Constant fold FNEG.
  14423. if (DAG.isConstantFPBuildVectorOrConstantFP(N0))
  14424. return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
  14425. if (SDValue NegN0 =
  14426. TLI.getNegatedExpression(N0, DAG, LegalOperations, ForCodeSize))
  14427. return NegN0;
  14428. // -(X-Y) -> (Y-X) is unsafe because when X==Y, -0.0 != +0.0
  14429. // FIXME: This is duplicated in getNegatibleCost, but getNegatibleCost doesn't
  14430. // know it was called from a context with a nsz flag if the input fsub does
  14431. // not.
  14432. if (N0.getOpcode() == ISD::FSUB &&
  14433. (DAG.getTarget().Options.NoSignedZerosFPMath ||
  14434. N->getFlags().hasNoSignedZeros()) && N0.hasOneUse()) {
  14435. return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0.getOperand(1),
  14436. N0.getOperand(0));
  14437. }
  14438. if (SDValue Cast = foldSignChangeInBitcast(N))
  14439. return Cast;
  14440. return SDValue();
  14441. }
  14442. SDValue DAGCombiner::visitFMinMax(SDNode *N) {
  14443. SDValue N0 = N->getOperand(0);
  14444. SDValue N1 = N->getOperand(1);
  14445. EVT VT = N->getValueType(0);
  14446. const SDNodeFlags Flags = N->getFlags();
  14447. unsigned Opc = N->getOpcode();
  14448. bool PropagatesNaN = Opc == ISD::FMINIMUM || Opc == ISD::FMAXIMUM;
  14449. bool IsMin = Opc == ISD::FMINNUM || Opc == ISD::FMINIMUM;
  14450. SelectionDAG::FlagInserter FlagsInserter(DAG, N);
  14451. // Constant fold.
  14452. if (SDValue C = DAG.FoldConstantArithmetic(Opc, SDLoc(N), VT, {N0, N1}))
  14453. return C;
  14454. // Canonicalize to constant on RHS.
  14455. if (DAG.isConstantFPBuildVectorOrConstantFP(N0) &&
  14456. !DAG.isConstantFPBuildVectorOrConstantFP(N1))
  14457. return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N1, N0);
  14458. if (const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1)) {
  14459. const APFloat &AF = N1CFP->getValueAPF();
  14460. // minnum(X, nan) -> X
  14461. // maxnum(X, nan) -> X
  14462. // minimum(X, nan) -> nan
  14463. // maximum(X, nan) -> nan
  14464. if (AF.isNaN())
  14465. return PropagatesNaN ? N->getOperand(1) : N->getOperand(0);
  14466. // In the following folds, inf can be replaced with the largest finite
  14467. // float, if the ninf flag is set.
  14468. if (AF.isInfinity() || (Flags.hasNoInfs() && AF.isLargest())) {
  14469. // minnum(X, -inf) -> -inf
  14470. // maxnum(X, +inf) -> +inf
  14471. // minimum(X, -inf) -> -inf if nnan
  14472. // maximum(X, +inf) -> +inf if nnan
  14473. if (IsMin == AF.isNegative() && (!PropagatesNaN || Flags.hasNoNaNs()))
  14474. return N->getOperand(1);
  14475. // minnum(X, +inf) -> X if nnan
  14476. // maxnum(X, -inf) -> X if nnan
  14477. // minimum(X, +inf) -> X
  14478. // maximum(X, -inf) -> X
  14479. if (IsMin != AF.isNegative() && (PropagatesNaN || Flags.hasNoNaNs()))
  14480. return N->getOperand(0);
  14481. }
  14482. }
  14483. return SDValue();
  14484. }
  14485. SDValue DAGCombiner::visitFABS(SDNode *N) {
  14486. SDValue N0 = N->getOperand(0);
  14487. EVT VT = N->getValueType(0);
  14488. // fold (fabs c1) -> fabs(c1)
  14489. if (DAG.isConstantFPBuildVectorOrConstantFP(N0))
  14490. return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
  14491. // fold (fabs (fabs x)) -> (fabs x)
  14492. if (N0.getOpcode() == ISD::FABS)
  14493. return N->getOperand(0);
  14494. // fold (fabs (fneg x)) -> (fabs x)
  14495. // fold (fabs (fcopysign x, y)) -> (fabs x)
  14496. if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
  14497. return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
  14498. if (SDValue Cast = foldSignChangeInBitcast(N))
  14499. return Cast;
  14500. return SDValue();
  14501. }
  14502. SDValue DAGCombiner::visitBRCOND(SDNode *N) {
  14503. SDValue Chain = N->getOperand(0);
  14504. SDValue N1 = N->getOperand(1);
  14505. SDValue N2 = N->getOperand(2);
  14506. // BRCOND(FREEZE(cond)) is equivalent to BRCOND(cond) (both are
  14507. // nondeterministic jumps).
  14508. if (N1->getOpcode() == ISD::FREEZE && N1.hasOneUse()) {
  14509. return DAG.getNode(ISD::BRCOND, SDLoc(N), MVT::Other, Chain,
  14510. N1->getOperand(0), N2);
  14511. }
  14512. // If N is a constant we could fold this into a fallthrough or unconditional
  14513. // branch. However that doesn't happen very often in normal code, because
  14514. // Instcombine/SimplifyCFG should have handled the available opportunities.
  14515. // If we did this folding here, it would be necessary to update the
  14516. // MachineBasicBlock CFG, which is awkward.
  14517. // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
  14518. // on the target.
  14519. if (N1.getOpcode() == ISD::SETCC &&
  14520. TLI.isOperationLegalOrCustom(ISD::BR_CC,
  14521. N1.getOperand(0).getValueType())) {
  14522. return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
  14523. Chain, N1.getOperand(2),
  14524. N1.getOperand(0), N1.getOperand(1), N2);
  14525. }
  14526. if (N1.hasOneUse()) {
  14527. // rebuildSetCC calls visitXor which may change the Chain when there is a
  14528. // STRICT_FSETCC/STRICT_FSETCCS involved. Use a handle to track changes.
  14529. HandleSDNode ChainHandle(Chain);
  14530. if (SDValue NewN1 = rebuildSetCC(N1))
  14531. return DAG.getNode(ISD::BRCOND, SDLoc(N), MVT::Other,
  14532. ChainHandle.getValue(), NewN1, N2);
  14533. }
  14534. return SDValue();
  14535. }
  14536. SDValue DAGCombiner::rebuildSetCC(SDValue N) {
  14537. if (N.getOpcode() == ISD::SRL ||
  14538. (N.getOpcode() == ISD::TRUNCATE &&
  14539. (N.getOperand(0).hasOneUse() &&
  14540. N.getOperand(0).getOpcode() == ISD::SRL))) {
  14541. // Look pass the truncate.
  14542. if (N.getOpcode() == ISD::TRUNCATE)
  14543. N = N.getOperand(0);
  14544. // Match this pattern so that we can generate simpler code:
  14545. //
  14546. // %a = ...
  14547. // %b = and i32 %a, 2
  14548. // %c = srl i32 %b, 1
  14549. // brcond i32 %c ...
  14550. //
  14551. // into
  14552. //
  14553. // %a = ...
  14554. // %b = and i32 %a, 2
  14555. // %c = setcc eq %b, 0
  14556. // brcond %c ...
  14557. //
  14558. // This applies only when the AND constant value has one bit set and the
  14559. // SRL constant is equal to the log2 of the AND constant. The back-end is
  14560. // smart enough to convert the result into a TEST/JMP sequence.
  14561. SDValue Op0 = N.getOperand(0);
  14562. SDValue Op1 = N.getOperand(1);
  14563. if (Op0.getOpcode() == ISD::AND && Op1.getOpcode() == ISD::Constant) {
  14564. SDValue AndOp1 = Op0.getOperand(1);
  14565. if (AndOp1.getOpcode() == ISD::Constant) {
  14566. const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
  14567. if (AndConst.isPowerOf2() &&
  14568. cast<ConstantSDNode>(Op1)->getAPIntValue() == AndConst.logBase2()) {
  14569. SDLoc DL(N);
  14570. return DAG.getSetCC(DL, getSetCCResultType(Op0.getValueType()),
  14571. Op0, DAG.getConstant(0, DL, Op0.getValueType()),
  14572. ISD::SETNE);
  14573. }
  14574. }
  14575. }
  14576. }
  14577. // Transform (brcond (xor x, y)) -> (brcond (setcc, x, y, ne))
  14578. // Transform (brcond (xor (xor x, y), -1)) -> (brcond (setcc, x, y, eq))
  14579. if (N.getOpcode() == ISD::XOR) {
  14580. // Because we may call this on a speculatively constructed
  14581. // SimplifiedSetCC Node, we need to simplify this node first.
  14582. // Ideally this should be folded into SimplifySetCC and not
  14583. // here. For now, grab a handle to N so we don't lose it from
  14584. // replacements interal to the visit.
  14585. HandleSDNode XORHandle(N);
  14586. while (N.getOpcode() == ISD::XOR) {
  14587. SDValue Tmp = visitXOR(N.getNode());
  14588. // No simplification done.
  14589. if (!Tmp.getNode())
  14590. break;
  14591. // Returning N is form in-visit replacement that may invalidated
  14592. // N. Grab value from Handle.
  14593. if (Tmp.getNode() == N.getNode())
  14594. N = XORHandle.getValue();
  14595. else // Node simplified. Try simplifying again.
  14596. N = Tmp;
  14597. }
  14598. if (N.getOpcode() != ISD::XOR)
  14599. return N;
  14600. SDValue Op0 = N->getOperand(0);
  14601. SDValue Op1 = N->getOperand(1);
  14602. if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
  14603. bool Equal = false;
  14604. // (brcond (xor (xor x, y), -1)) -> (brcond (setcc x, y, eq))
  14605. if (isBitwiseNot(N) && Op0.hasOneUse() && Op0.getOpcode() == ISD::XOR &&
  14606. Op0.getValueType() == MVT::i1) {
  14607. N = Op0;
  14608. Op0 = N->getOperand(0);
  14609. Op1 = N->getOperand(1);
  14610. Equal = true;
  14611. }
  14612. EVT SetCCVT = N.getValueType();
  14613. if (LegalTypes)
  14614. SetCCVT = getSetCCResultType(SetCCVT);
  14615. // Replace the uses of XOR with SETCC
  14616. return DAG.getSetCC(SDLoc(N), SetCCVT, Op0, Op1,
  14617. Equal ? ISD::SETEQ : ISD::SETNE);
  14618. }
  14619. }
  14620. return SDValue();
  14621. }
  14622. // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
  14623. //
  14624. SDValue DAGCombiner::visitBR_CC(SDNode *N) {
  14625. CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
  14626. SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
  14627. // If N is a constant we could fold this into a fallthrough or unconditional
  14628. // branch. However that doesn't happen very often in normal code, because
  14629. // Instcombine/SimplifyCFG should have handled the available opportunities.
  14630. // If we did this folding here, it would be necessary to update the
  14631. // MachineBasicBlock CFG, which is awkward.
  14632. // Use SimplifySetCC to simplify SETCC's.
  14633. SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
  14634. CondLHS, CondRHS, CC->get(), SDLoc(N),
  14635. false);
  14636. if (Simp.getNode()) AddToWorklist(Simp.getNode());
  14637. // fold to a simpler setcc
  14638. if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
  14639. return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
  14640. N->getOperand(0), Simp.getOperand(2),
  14641. Simp.getOperand(0), Simp.getOperand(1),
  14642. N->getOperand(4));
  14643. return SDValue();
  14644. }
  14645. static bool getCombineLoadStoreParts(SDNode *N, unsigned Inc, unsigned Dec,
  14646. bool &IsLoad, bool &IsMasked, SDValue &Ptr,
  14647. const TargetLowering &TLI) {
  14648. if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
  14649. if (LD->isIndexed())
  14650. return false;
  14651. EVT VT = LD->getMemoryVT();
  14652. if (!TLI.isIndexedLoadLegal(Inc, VT) && !TLI.isIndexedLoadLegal(Dec, VT))
  14653. return false;
  14654. Ptr = LD->getBasePtr();
  14655. } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
  14656. if (ST->isIndexed())
  14657. return false;
  14658. EVT VT = ST->getMemoryVT();
  14659. if (!TLI.isIndexedStoreLegal(Inc, VT) && !TLI.isIndexedStoreLegal(Dec, VT))
  14660. return false;
  14661. Ptr = ST->getBasePtr();
  14662. IsLoad = false;
  14663. } else if (MaskedLoadSDNode *LD = dyn_cast<MaskedLoadSDNode>(N)) {
  14664. if (LD->isIndexed())
  14665. return false;
  14666. EVT VT = LD->getMemoryVT();
  14667. if (!TLI.isIndexedMaskedLoadLegal(Inc, VT) &&
  14668. !TLI.isIndexedMaskedLoadLegal(Dec, VT))
  14669. return false;
  14670. Ptr = LD->getBasePtr();
  14671. IsMasked = true;
  14672. } else if (MaskedStoreSDNode *ST = dyn_cast<MaskedStoreSDNode>(N)) {
  14673. if (ST->isIndexed())
  14674. return false;
  14675. EVT VT = ST->getMemoryVT();
  14676. if (!TLI.isIndexedMaskedStoreLegal(Inc, VT) &&
  14677. !TLI.isIndexedMaskedStoreLegal(Dec, VT))
  14678. return false;
  14679. Ptr = ST->getBasePtr();
  14680. IsLoad = false;
  14681. IsMasked = true;
  14682. } else {
  14683. return false;
  14684. }
  14685. return true;
  14686. }
  14687. /// Try turning a load/store into a pre-indexed load/store when the base
  14688. /// pointer is an add or subtract and it has other uses besides the load/store.
  14689. /// After the transformation, the new indexed load/store has effectively folded
  14690. /// the add/subtract in and all of its other uses are redirected to the
  14691. /// new load/store.
  14692. bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
  14693. if (Level < AfterLegalizeDAG)
  14694. return false;
  14695. bool IsLoad = true;
  14696. bool IsMasked = false;
  14697. SDValue Ptr;
  14698. if (!getCombineLoadStoreParts(N, ISD::PRE_INC, ISD::PRE_DEC, IsLoad, IsMasked,
  14699. Ptr, TLI))
  14700. return false;
  14701. // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
  14702. // out. There is no reason to make this a preinc/predec.
  14703. if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
  14704. Ptr->hasOneUse())
  14705. return false;
  14706. // Ask the target to do addressing mode selection.
  14707. SDValue BasePtr;
  14708. SDValue Offset;
  14709. ISD::MemIndexedMode AM = ISD::UNINDEXED;
  14710. if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
  14711. return false;
  14712. // Backends without true r+i pre-indexed forms may need to pass a
  14713. // constant base with a variable offset so that constant coercion
  14714. // will work with the patterns in canonical form.
  14715. bool Swapped = false;
  14716. if (isa<ConstantSDNode>(BasePtr)) {
  14717. std::swap(BasePtr, Offset);
  14718. Swapped = true;
  14719. }
  14720. // Don't create a indexed load / store with zero offset.
  14721. if (isNullConstant(Offset))
  14722. return false;
  14723. // Try turning it into a pre-indexed load / store except when:
  14724. // 1) The new base ptr is a frame index.
  14725. // 2) If N is a store and the new base ptr is either the same as or is a
  14726. // predecessor of the value being stored.
  14727. // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
  14728. // that would create a cycle.
  14729. // 4) All uses are load / store ops that use it as old base ptr.
  14730. // Check #1. Preinc'ing a frame index would require copying the stack pointer
  14731. // (plus the implicit offset) to a register to preinc anyway.
  14732. if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
  14733. return false;
  14734. // Check #2.
  14735. if (!IsLoad) {
  14736. SDValue Val = IsMasked ? cast<MaskedStoreSDNode>(N)->getValue()
  14737. : cast<StoreSDNode>(N)->getValue();
  14738. // Would require a copy.
  14739. if (Val == BasePtr)
  14740. return false;
  14741. // Would create a cycle.
  14742. if (Val == Ptr || Ptr->isPredecessorOf(Val.getNode()))
  14743. return false;
  14744. }
  14745. // Caches for hasPredecessorHelper.
  14746. SmallPtrSet<const SDNode *, 32> Visited;
  14747. SmallVector<const SDNode *, 16> Worklist;
  14748. Worklist.push_back(N);
  14749. // If the offset is a constant, there may be other adds of constants that
  14750. // can be folded with this one. We should do this to avoid having to keep
  14751. // a copy of the original base pointer.
  14752. SmallVector<SDNode *, 16> OtherUses;
  14753. if (isa<ConstantSDNode>(Offset))
  14754. for (SDNode::use_iterator UI = BasePtr->use_begin(),
  14755. UE = BasePtr->use_end();
  14756. UI != UE; ++UI) {
  14757. SDUse &Use = UI.getUse();
  14758. // Skip the use that is Ptr and uses of other results from BasePtr's
  14759. // node (important for nodes that return multiple results).
  14760. if (Use.getUser() == Ptr.getNode() || Use != BasePtr)
  14761. continue;
  14762. if (SDNode::hasPredecessorHelper(Use.getUser(), Visited, Worklist))
  14763. continue;
  14764. if (Use.getUser()->getOpcode() != ISD::ADD &&
  14765. Use.getUser()->getOpcode() != ISD::SUB) {
  14766. OtherUses.clear();
  14767. break;
  14768. }
  14769. SDValue Op1 = Use.getUser()->getOperand((UI.getOperandNo() + 1) & 1);
  14770. if (!isa<ConstantSDNode>(Op1)) {
  14771. OtherUses.clear();
  14772. break;
  14773. }
  14774. // FIXME: In some cases, we can be smarter about this.
  14775. if (Op1.getValueType() != Offset.getValueType()) {
  14776. OtherUses.clear();
  14777. break;
  14778. }
  14779. OtherUses.push_back(Use.getUser());
  14780. }
  14781. if (Swapped)
  14782. std::swap(BasePtr, Offset);
  14783. // Now check for #3 and #4.
  14784. bool RealUse = false;
  14785. for (SDNode *Use : Ptr->uses()) {
  14786. if (Use == N)
  14787. continue;
  14788. if (SDNode::hasPredecessorHelper(Use, Visited, Worklist))
  14789. return false;
  14790. // If Ptr may be folded in addressing mode of other use, then it's
  14791. // not profitable to do this transformation.
  14792. if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
  14793. RealUse = true;
  14794. }
  14795. if (!RealUse)
  14796. return false;
  14797. SDValue Result;
  14798. if (!IsMasked) {
  14799. if (IsLoad)
  14800. Result = DAG.getIndexedLoad(SDValue(N, 0), SDLoc(N), BasePtr, Offset, AM);
  14801. else
  14802. Result =
  14803. DAG.getIndexedStore(SDValue(N, 0), SDLoc(N), BasePtr, Offset, AM);
  14804. } else {
  14805. if (IsLoad)
  14806. Result = DAG.getIndexedMaskedLoad(SDValue(N, 0), SDLoc(N), BasePtr,
  14807. Offset, AM);
  14808. else
  14809. Result = DAG.getIndexedMaskedStore(SDValue(N, 0), SDLoc(N), BasePtr,
  14810. Offset, AM);
  14811. }
  14812. ++PreIndexedNodes;
  14813. ++NodesCombined;
  14814. LLVM_DEBUG(dbgs() << "\nReplacing.4 "; N->dump(&DAG); dbgs() << "\nWith: ";
  14815. Result.dump(&DAG); dbgs() << '\n');
  14816. WorklistRemover DeadNodes(*this);
  14817. if (IsLoad) {
  14818. DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
  14819. DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
  14820. } else {
  14821. DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
  14822. }
  14823. // Finally, since the node is now dead, remove it from the graph.
  14824. deleteAndRecombine(N);
  14825. if (Swapped)
  14826. std::swap(BasePtr, Offset);
  14827. // Replace other uses of BasePtr that can be updated to use Ptr
  14828. for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
  14829. unsigned OffsetIdx = 1;
  14830. if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
  14831. OffsetIdx = 0;
  14832. assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
  14833. BasePtr.getNode() && "Expected BasePtr operand");
  14834. // We need to replace ptr0 in the following expression:
  14835. // x0 * offset0 + y0 * ptr0 = t0
  14836. // knowing that
  14837. // x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
  14838. //
  14839. // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
  14840. // indexed load/store and the expression that needs to be re-written.
  14841. //
  14842. // Therefore, we have:
  14843. // t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
  14844. auto *CN = cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
  14845. const APInt &Offset0 = CN->getAPIntValue();
  14846. const APInt &Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
  14847. int X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
  14848. int Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
  14849. int X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
  14850. int Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
  14851. unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
  14852. APInt CNV = Offset0;
  14853. if (X0 < 0) CNV = -CNV;
  14854. if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
  14855. else CNV = CNV - Offset1;
  14856. SDLoc DL(OtherUses[i]);
  14857. // We can now generate the new expression.
  14858. SDValue NewOp1 = DAG.getConstant(CNV, DL, CN->getValueType(0));
  14859. SDValue NewOp2 = Result.getValue(IsLoad ? 1 : 0);
  14860. SDValue NewUse = DAG.getNode(Opcode,
  14861. DL,
  14862. OtherUses[i]->getValueType(0), NewOp1, NewOp2);
  14863. DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
  14864. deleteAndRecombine(OtherUses[i]);
  14865. }
  14866. // Replace the uses of Ptr with uses of the updated base value.
  14867. DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(IsLoad ? 1 : 0));
  14868. deleteAndRecombine(Ptr.getNode());
  14869. AddToWorklist(Result.getNode());
  14870. return true;
  14871. }
  14872. static bool shouldCombineToPostInc(SDNode *N, SDValue Ptr, SDNode *PtrUse,
  14873. SDValue &BasePtr, SDValue &Offset,
  14874. ISD::MemIndexedMode &AM,
  14875. SelectionDAG &DAG,
  14876. const TargetLowering &TLI) {
  14877. if (PtrUse == N ||
  14878. (PtrUse->getOpcode() != ISD::ADD && PtrUse->getOpcode() != ISD::SUB))
  14879. return false;
  14880. if (!TLI.getPostIndexedAddressParts(N, PtrUse, BasePtr, Offset, AM, DAG))
  14881. return false;
  14882. // Don't create a indexed load / store with zero offset.
  14883. if (isNullConstant(Offset))
  14884. return false;
  14885. if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
  14886. return false;
  14887. SmallPtrSet<const SDNode *, 32> Visited;
  14888. for (SDNode *Use : BasePtr->uses()) {
  14889. if (Use == Ptr.getNode())
  14890. continue;
  14891. // No if there's a later user which could perform the index instead.
  14892. if (isa<MemSDNode>(Use)) {
  14893. bool IsLoad = true;
  14894. bool IsMasked = false;
  14895. SDValue OtherPtr;
  14896. if (getCombineLoadStoreParts(Use, ISD::POST_INC, ISD::POST_DEC, IsLoad,
  14897. IsMasked, OtherPtr, TLI)) {
  14898. SmallVector<const SDNode *, 2> Worklist;
  14899. Worklist.push_back(Use);
  14900. if (SDNode::hasPredecessorHelper(N, Visited, Worklist))
  14901. return false;
  14902. }
  14903. }
  14904. // If all the uses are load / store addresses, then don't do the
  14905. // transformation.
  14906. if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB) {
  14907. for (SDNode *UseUse : Use->uses())
  14908. if (canFoldInAddressingMode(Use, UseUse, DAG, TLI))
  14909. return false;
  14910. }
  14911. }
  14912. return true;
  14913. }
  14914. static SDNode *getPostIndexedLoadStoreOp(SDNode *N, bool &IsLoad,
  14915. bool &IsMasked, SDValue &Ptr,
  14916. SDValue &BasePtr, SDValue &Offset,
  14917. ISD::MemIndexedMode &AM,
  14918. SelectionDAG &DAG,
  14919. const TargetLowering &TLI) {
  14920. if (!getCombineLoadStoreParts(N, ISD::POST_INC, ISD::POST_DEC, IsLoad,
  14921. IsMasked, Ptr, TLI) ||
  14922. Ptr->hasOneUse())
  14923. return nullptr;
  14924. // Try turning it into a post-indexed load / store except when
  14925. // 1) All uses are load / store ops that use it as base ptr (and
  14926. // it may be folded as addressing mmode).
  14927. // 2) Op must be independent of N, i.e. Op is neither a predecessor
  14928. // nor a successor of N. Otherwise, if Op is folded that would
  14929. // create a cycle.
  14930. for (SDNode *Op : Ptr->uses()) {
  14931. // Check for #1.
  14932. if (!shouldCombineToPostInc(N, Ptr, Op, BasePtr, Offset, AM, DAG, TLI))
  14933. continue;
  14934. // Check for #2.
  14935. SmallPtrSet<const SDNode *, 32> Visited;
  14936. SmallVector<const SDNode *, 8> Worklist;
  14937. // Ptr is predecessor to both N and Op.
  14938. Visited.insert(Ptr.getNode());
  14939. Worklist.push_back(N);
  14940. Worklist.push_back(Op);
  14941. if (!SDNode::hasPredecessorHelper(N, Visited, Worklist) &&
  14942. !SDNode::hasPredecessorHelper(Op, Visited, Worklist))
  14943. return Op;
  14944. }
  14945. return nullptr;
  14946. }
  14947. /// Try to combine a load/store with a add/sub of the base pointer node into a
  14948. /// post-indexed load/store. The transformation folded the add/subtract into the
  14949. /// new indexed load/store effectively and all of its uses are redirected to the
  14950. /// new load/store.
  14951. bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
  14952. if (Level < AfterLegalizeDAG)
  14953. return false;
  14954. bool IsLoad = true;
  14955. bool IsMasked = false;
  14956. SDValue Ptr;
  14957. SDValue BasePtr;
  14958. SDValue Offset;
  14959. ISD::MemIndexedMode AM = ISD::UNINDEXED;
  14960. SDNode *Op = getPostIndexedLoadStoreOp(N, IsLoad, IsMasked, Ptr, BasePtr,
  14961. Offset, AM, DAG, TLI);
  14962. if (!Op)
  14963. return false;
  14964. SDValue Result;
  14965. if (!IsMasked)
  14966. Result = IsLoad ? DAG.getIndexedLoad(SDValue(N, 0), SDLoc(N), BasePtr,
  14967. Offset, AM)
  14968. : DAG.getIndexedStore(SDValue(N, 0), SDLoc(N),
  14969. BasePtr, Offset, AM);
  14970. else
  14971. Result = IsLoad ? DAG.getIndexedMaskedLoad(SDValue(N, 0), SDLoc(N),
  14972. BasePtr, Offset, AM)
  14973. : DAG.getIndexedMaskedStore(SDValue(N, 0), SDLoc(N),
  14974. BasePtr, Offset, AM);
  14975. ++PostIndexedNodes;
  14976. ++NodesCombined;
  14977. LLVM_DEBUG(dbgs() << "\nReplacing.5 "; N->dump(&DAG); dbgs() << "\nWith: ";
  14978. Result.dump(&DAG); dbgs() << '\n');
  14979. WorklistRemover DeadNodes(*this);
  14980. if (IsLoad) {
  14981. DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
  14982. DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
  14983. } else {
  14984. DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
  14985. }
  14986. // Finally, since the node is now dead, remove it from the graph.
  14987. deleteAndRecombine(N);
  14988. // Replace the uses of Use with uses of the updated base value.
  14989. DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
  14990. Result.getValue(IsLoad ? 1 : 0));
  14991. deleteAndRecombine(Op);
  14992. return true;
  14993. }
  14994. /// Return the base-pointer arithmetic from an indexed \p LD.
  14995. SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) {
  14996. ISD::MemIndexedMode AM = LD->getAddressingMode();
  14997. assert(AM != ISD::UNINDEXED);
  14998. SDValue BP = LD->getOperand(1);
  14999. SDValue Inc = LD->getOperand(2);
  15000. // Some backends use TargetConstants for load offsets, but don't expect
  15001. // TargetConstants in general ADD nodes. We can convert these constants into
  15002. // regular Constants (if the constant is not opaque).
  15003. assert((Inc.getOpcode() != ISD::TargetConstant ||
  15004. !cast<ConstantSDNode>(Inc)->isOpaque()) &&
  15005. "Cannot split out indexing using opaque target constants");
  15006. if (Inc.getOpcode() == ISD::TargetConstant) {
  15007. ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc);
  15008. Inc = DAG.getConstant(*ConstInc->getConstantIntValue(), SDLoc(Inc),
  15009. ConstInc->getValueType(0));
  15010. }
  15011. unsigned Opc =
  15012. (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB);
  15013. return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc);
  15014. }
  15015. static inline ElementCount numVectorEltsOrZero(EVT T) {
  15016. return T.isVector() ? T.getVectorElementCount() : ElementCount::getFixed(0);
  15017. }
  15018. bool DAGCombiner::getTruncatedStoreValue(StoreSDNode *ST, SDValue &Val) {
  15019. EVT STType = Val.getValueType();
  15020. EVT STMemType = ST->getMemoryVT();
  15021. if (STType == STMemType)
  15022. return true;
  15023. if (isTypeLegal(STMemType))
  15024. return false; // fail.
  15025. if (STType.isFloatingPoint() && STMemType.isFloatingPoint() &&
  15026. TLI.isOperationLegal(ISD::FTRUNC, STMemType)) {
  15027. Val = DAG.getNode(ISD::FTRUNC, SDLoc(ST), STMemType, Val);
  15028. return true;
  15029. }
  15030. if (numVectorEltsOrZero(STType) == numVectorEltsOrZero(STMemType) &&
  15031. STType.isInteger() && STMemType.isInteger()) {
  15032. Val = DAG.getNode(ISD::TRUNCATE, SDLoc(ST), STMemType, Val);
  15033. return true;
  15034. }
  15035. if (STType.getSizeInBits() == STMemType.getSizeInBits()) {
  15036. Val = DAG.getBitcast(STMemType, Val);
  15037. return true;
  15038. }
  15039. return false; // fail.
  15040. }
  15041. bool DAGCombiner::extendLoadedValueToExtension(LoadSDNode *LD, SDValue &Val) {
  15042. EVT LDMemType = LD->getMemoryVT();
  15043. EVT LDType = LD->getValueType(0);
  15044. assert(Val.getValueType() == LDMemType &&
  15045. "Attempting to extend value of non-matching type");
  15046. if (LDType == LDMemType)
  15047. return true;
  15048. if (LDMemType.isInteger() && LDType.isInteger()) {
  15049. switch (LD->getExtensionType()) {
  15050. case ISD::NON_EXTLOAD:
  15051. Val = DAG.getBitcast(LDType, Val);
  15052. return true;
  15053. case ISD::EXTLOAD:
  15054. Val = DAG.getNode(ISD::ANY_EXTEND, SDLoc(LD), LDType, Val);
  15055. return true;
  15056. case ISD::SEXTLOAD:
  15057. Val = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(LD), LDType, Val);
  15058. return true;
  15059. case ISD::ZEXTLOAD:
  15060. Val = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(LD), LDType, Val);
  15061. return true;
  15062. }
  15063. }
  15064. return false;
  15065. }
  15066. SDValue DAGCombiner::ForwardStoreValueToDirectLoad(LoadSDNode *LD) {
  15067. if (OptLevel == CodeGenOpt::None || !LD->isSimple())
  15068. return SDValue();
  15069. SDValue Chain = LD->getOperand(0);
  15070. StoreSDNode *ST = dyn_cast<StoreSDNode>(Chain.getNode());
  15071. // TODO: Relax this restriction for unordered atomics (see D66309)
  15072. if (!ST || !ST->isSimple() || ST->getAddressSpace() != LD->getAddressSpace())
  15073. return SDValue();
  15074. EVT LDType = LD->getValueType(0);
  15075. EVT LDMemType = LD->getMemoryVT();
  15076. EVT STMemType = ST->getMemoryVT();
  15077. EVT STType = ST->getValue().getValueType();
  15078. // There are two cases to consider here:
  15079. // 1. The store is fixed width and the load is scalable. In this case we
  15080. // don't know at compile time if the store completely envelops the load
  15081. // so we abandon the optimisation.
  15082. // 2. The store is scalable and the load is fixed width. We could
  15083. // potentially support a limited number of cases here, but there has been
  15084. // no cost-benefit analysis to prove it's worth it.
  15085. bool LdStScalable = LDMemType.isScalableVector();
  15086. if (LdStScalable != STMemType.isScalableVector())
  15087. return SDValue();
  15088. // If we are dealing with scalable vectors on a big endian platform the
  15089. // calculation of offsets below becomes trickier, since we do not know at
  15090. // compile time the absolute size of the vector. Until we've done more
  15091. // analysis on big-endian platforms it seems better to bail out for now.
  15092. if (LdStScalable && DAG.getDataLayout().isBigEndian())
  15093. return SDValue();
  15094. BaseIndexOffset BasePtrLD = BaseIndexOffset::match(LD, DAG);
  15095. BaseIndexOffset BasePtrST = BaseIndexOffset::match(ST, DAG);
  15096. int64_t Offset;
  15097. if (!BasePtrST.equalBaseIndex(BasePtrLD, DAG, Offset))
  15098. return SDValue();
  15099. // Normalize for Endianness. After this Offset=0 will denote that the least
  15100. // significant bit in the loaded value maps to the least significant bit in
  15101. // the stored value). With Offset=n (for n > 0) the loaded value starts at the
  15102. // n:th least significant byte of the stored value.
  15103. int64_t OrigOffset = Offset;
  15104. if (DAG.getDataLayout().isBigEndian())
  15105. Offset = ((int64_t)STMemType.getStoreSizeInBits().getFixedValue() -
  15106. (int64_t)LDMemType.getStoreSizeInBits().getFixedValue()) /
  15107. 8 -
  15108. Offset;
  15109. // Check that the stored value cover all bits that are loaded.
  15110. bool STCoversLD;
  15111. TypeSize LdMemSize = LDMemType.getSizeInBits();
  15112. TypeSize StMemSize = STMemType.getSizeInBits();
  15113. if (LdStScalable)
  15114. STCoversLD = (Offset == 0) && LdMemSize == StMemSize;
  15115. else
  15116. STCoversLD = (Offset >= 0) && (Offset * 8 + LdMemSize.getFixedValue() <=
  15117. StMemSize.getFixedValue());
  15118. auto ReplaceLd = [&](LoadSDNode *LD, SDValue Val, SDValue Chain) -> SDValue {
  15119. if (LD->isIndexed()) {
  15120. // Cannot handle opaque target constants and we must respect the user's
  15121. // request not to split indexes from loads.
  15122. if (!canSplitIdx(LD))
  15123. return SDValue();
  15124. SDValue Idx = SplitIndexingFromLoad(LD);
  15125. SDValue Ops[] = {Val, Idx, Chain};
  15126. return CombineTo(LD, Ops, 3);
  15127. }
  15128. return CombineTo(LD, Val, Chain);
  15129. };
  15130. if (!STCoversLD)
  15131. return SDValue();
  15132. // Memory as copy space (potentially masked).
  15133. if (Offset == 0 && LDType == STType && STMemType == LDMemType) {
  15134. // Simple case: Direct non-truncating forwarding
  15135. if (LDType.getSizeInBits() == LdMemSize)
  15136. return ReplaceLd(LD, ST->getValue(), Chain);
  15137. // Can we model the truncate and extension with an and mask?
  15138. if (STType.isInteger() && LDMemType.isInteger() && !STType.isVector() &&
  15139. !LDMemType.isVector() && LD->getExtensionType() != ISD::SEXTLOAD) {
  15140. // Mask to size of LDMemType
  15141. auto Mask =
  15142. DAG.getConstant(APInt::getLowBitsSet(STType.getFixedSizeInBits(),
  15143. StMemSize.getFixedValue()),
  15144. SDLoc(ST), STType);
  15145. auto Val = DAG.getNode(ISD::AND, SDLoc(LD), LDType, ST->getValue(), Mask);
  15146. return ReplaceLd(LD, Val, Chain);
  15147. }
  15148. }
  15149. // Handle some cases for big-endian that would be Offset 0 and handled for
  15150. // little-endian.
  15151. SDValue Val = ST->getValue();
  15152. if (DAG.getDataLayout().isBigEndian() && Offset > 0 && OrigOffset == 0) {
  15153. if (STType.isInteger() && !STType.isVector() && LDType.isInteger() &&
  15154. !LDType.isVector() && isTypeLegal(STType) &&
  15155. TLI.isOperationLegal(ISD::SRL, STType)) {
  15156. Val = DAG.getNode(ISD::SRL, SDLoc(LD), STType, Val,
  15157. DAG.getConstant(Offset * 8, SDLoc(LD), STType));
  15158. Offset = 0;
  15159. }
  15160. }
  15161. // TODO: Deal with nonzero offset.
  15162. if (LD->getBasePtr().isUndef() || Offset != 0)
  15163. return SDValue();
  15164. // Model necessary truncations / extenstions.
  15165. // Truncate Value To Stored Memory Size.
  15166. do {
  15167. if (!getTruncatedStoreValue(ST, Val))
  15168. continue;
  15169. if (!isTypeLegal(LDMemType))
  15170. continue;
  15171. if (STMemType != LDMemType) {
  15172. // TODO: Support vectors? This requires extract_subvector/bitcast.
  15173. if (!STMemType.isVector() && !LDMemType.isVector() &&
  15174. STMemType.isInteger() && LDMemType.isInteger())
  15175. Val = DAG.getNode(ISD::TRUNCATE, SDLoc(LD), LDMemType, Val);
  15176. else
  15177. continue;
  15178. }
  15179. if (!extendLoadedValueToExtension(LD, Val))
  15180. continue;
  15181. return ReplaceLd(LD, Val, Chain);
  15182. } while (false);
  15183. // On failure, cleanup dead nodes we may have created.
  15184. if (Val->use_empty())
  15185. deleteAndRecombine(Val.getNode());
  15186. return SDValue();
  15187. }
  15188. SDValue DAGCombiner::visitLOAD(SDNode *N) {
  15189. LoadSDNode *LD = cast<LoadSDNode>(N);
  15190. SDValue Chain = LD->getChain();
  15191. SDValue Ptr = LD->getBasePtr();
  15192. // If load is not volatile and there are no uses of the loaded value (and
  15193. // the updated indexed value in case of indexed loads), change uses of the
  15194. // chain value into uses of the chain input (i.e. delete the dead load).
  15195. // TODO: Allow this for unordered atomics (see D66309)
  15196. if (LD->isSimple()) {
  15197. if (N->getValueType(1) == MVT::Other) {
  15198. // Unindexed loads.
  15199. if (!N->hasAnyUseOfValue(0)) {
  15200. // It's not safe to use the two value CombineTo variant here. e.g.
  15201. // v1, chain2 = load chain1, loc
  15202. // v2, chain3 = load chain2, loc
  15203. // v3 = add v2, c
  15204. // Now we replace use of chain2 with chain1. This makes the second load
  15205. // isomorphic to the one we are deleting, and thus makes this load live.
  15206. LLVM_DEBUG(dbgs() << "\nReplacing.6 "; N->dump(&DAG);
  15207. dbgs() << "\nWith chain: "; Chain.dump(&DAG);
  15208. dbgs() << "\n");
  15209. WorklistRemover DeadNodes(*this);
  15210. DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
  15211. AddUsersToWorklist(Chain.getNode());
  15212. if (N->use_empty())
  15213. deleteAndRecombine(N);
  15214. return SDValue(N, 0); // Return N so it doesn't get rechecked!
  15215. }
  15216. } else {
  15217. // Indexed loads.
  15218. assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
  15219. // If this load has an opaque TargetConstant offset, then we cannot split
  15220. // the indexing into an add/sub directly (that TargetConstant may not be
  15221. // valid for a different type of node, and we cannot convert an opaque
  15222. // target constant into a regular constant).
  15223. bool CanSplitIdx = canSplitIdx(LD);
  15224. if (!N->hasAnyUseOfValue(0) && (CanSplitIdx || !N->hasAnyUseOfValue(1))) {
  15225. SDValue Undef = DAG.getUNDEF(N->getValueType(0));
  15226. SDValue Index;
  15227. if (N->hasAnyUseOfValue(1) && CanSplitIdx) {
  15228. Index = SplitIndexingFromLoad(LD);
  15229. // Try to fold the base pointer arithmetic into subsequent loads and
  15230. // stores.
  15231. AddUsersToWorklist(N);
  15232. } else
  15233. Index = DAG.getUNDEF(N->getValueType(1));
  15234. LLVM_DEBUG(dbgs() << "\nReplacing.7 "; N->dump(&DAG);
  15235. dbgs() << "\nWith: "; Undef.dump(&DAG);
  15236. dbgs() << " and 2 other values\n");
  15237. WorklistRemover DeadNodes(*this);
  15238. DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
  15239. DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index);
  15240. DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
  15241. deleteAndRecombine(N);
  15242. return SDValue(N, 0); // Return N so it doesn't get rechecked!
  15243. }
  15244. }
  15245. }
  15246. // If this load is directly stored, replace the load value with the stored
  15247. // value.
  15248. if (auto V = ForwardStoreValueToDirectLoad(LD))
  15249. return V;
  15250. // Try to infer better alignment information than the load already has.
  15251. if (OptLevel != CodeGenOpt::None && LD->isUnindexed() && !LD->isAtomic()) {
  15252. if (MaybeAlign Alignment = DAG.InferPtrAlign(Ptr)) {
  15253. if (*Alignment > LD->getAlign() &&
  15254. isAligned(*Alignment, LD->getSrcValueOffset())) {
  15255. SDValue NewLoad = DAG.getExtLoad(
  15256. LD->getExtensionType(), SDLoc(N), LD->getValueType(0), Chain, Ptr,
  15257. LD->getPointerInfo(), LD->getMemoryVT(), *Alignment,
  15258. LD->getMemOperand()->getFlags(), LD->getAAInfo());
  15259. // NewLoad will always be N as we are only refining the alignment
  15260. assert(NewLoad.getNode() == N);
  15261. (void)NewLoad;
  15262. }
  15263. }
  15264. }
  15265. if (LD->isUnindexed()) {
  15266. // Walk up chain skipping non-aliasing memory nodes.
  15267. SDValue BetterChain = FindBetterChain(LD, Chain);
  15268. // If there is a better chain.
  15269. if (Chain != BetterChain) {
  15270. SDValue ReplLoad;
  15271. // Replace the chain to void dependency.
  15272. if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
  15273. ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
  15274. BetterChain, Ptr, LD->getMemOperand());
  15275. } else {
  15276. ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
  15277. LD->getValueType(0),
  15278. BetterChain, Ptr, LD->getMemoryVT(),
  15279. LD->getMemOperand());
  15280. }
  15281. // Create token factor to keep old chain connected.
  15282. SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
  15283. MVT::Other, Chain, ReplLoad.getValue(1));
  15284. // Replace uses with load result and token factor
  15285. return CombineTo(N, ReplLoad.getValue(0), Token);
  15286. }
  15287. }
  15288. // Try transforming N to an indexed load.
  15289. if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
  15290. return SDValue(N, 0);
  15291. // Try to slice up N to more direct loads if the slices are mapped to
  15292. // different register banks or pairing can take place.
  15293. if (SliceUpLoad(N))
  15294. return SDValue(N, 0);
  15295. return SDValue();
  15296. }
  15297. namespace {
  15298. /// Helper structure used to slice a load in smaller loads.
  15299. /// Basically a slice is obtained from the following sequence:
  15300. /// Origin = load Ty1, Base
  15301. /// Shift = srl Ty1 Origin, CstTy Amount
  15302. /// Inst = trunc Shift to Ty2
  15303. ///
  15304. /// Then, it will be rewritten into:
  15305. /// Slice = load SliceTy, Base + SliceOffset
  15306. /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
  15307. ///
  15308. /// SliceTy is deduced from the number of bits that are actually used to
  15309. /// build Inst.
  15310. struct LoadedSlice {
  15311. /// Helper structure used to compute the cost of a slice.
  15312. struct Cost {
  15313. /// Are we optimizing for code size.
  15314. bool ForCodeSize = false;
  15315. /// Various cost.
  15316. unsigned Loads = 0;
  15317. unsigned Truncates = 0;
  15318. unsigned CrossRegisterBanksCopies = 0;
  15319. unsigned ZExts = 0;
  15320. unsigned Shift = 0;
  15321. explicit Cost(bool ForCodeSize) : ForCodeSize(ForCodeSize) {}
  15322. /// Get the cost of one isolated slice.
  15323. Cost(const LoadedSlice &LS, bool ForCodeSize)
  15324. : ForCodeSize(ForCodeSize), Loads(1) {
  15325. EVT TruncType = LS.Inst->getValueType(0);
  15326. EVT LoadedType = LS.getLoadedType();
  15327. if (TruncType != LoadedType &&
  15328. !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
  15329. ZExts = 1;
  15330. }
  15331. /// Account for slicing gain in the current cost.
  15332. /// Slicing provide a few gains like removing a shift or a
  15333. /// truncate. This method allows to grow the cost of the original
  15334. /// load with the gain from this slice.
  15335. void addSliceGain(const LoadedSlice &LS) {
  15336. // Each slice saves a truncate.
  15337. const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
  15338. if (!TLI.isTruncateFree(LS.Inst->getOperand(0).getValueType(),
  15339. LS.Inst->getValueType(0)))
  15340. ++Truncates;
  15341. // If there is a shift amount, this slice gets rid of it.
  15342. if (LS.Shift)
  15343. ++Shift;
  15344. // If this slice can merge a cross register bank copy, account for it.
  15345. if (LS.canMergeExpensiveCrossRegisterBankCopy())
  15346. ++CrossRegisterBanksCopies;
  15347. }
  15348. Cost &operator+=(const Cost &RHS) {
  15349. Loads += RHS.Loads;
  15350. Truncates += RHS.Truncates;
  15351. CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
  15352. ZExts += RHS.ZExts;
  15353. Shift += RHS.Shift;
  15354. return *this;
  15355. }
  15356. bool operator==(const Cost &RHS) const {
  15357. return Loads == RHS.Loads && Truncates == RHS.Truncates &&
  15358. CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
  15359. ZExts == RHS.ZExts && Shift == RHS.Shift;
  15360. }
  15361. bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
  15362. bool operator<(const Cost &RHS) const {
  15363. // Assume cross register banks copies are as expensive as loads.
  15364. // FIXME: Do we want some more target hooks?
  15365. unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
  15366. unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
  15367. // Unless we are optimizing for code size, consider the
  15368. // expensive operation first.
  15369. if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
  15370. return ExpensiveOpsLHS < ExpensiveOpsRHS;
  15371. return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
  15372. (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
  15373. }
  15374. bool operator>(const Cost &RHS) const { return RHS < *this; }
  15375. bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
  15376. bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
  15377. };
  15378. // The last instruction that represent the slice. This should be a
  15379. // truncate instruction.
  15380. SDNode *Inst;
  15381. // The original load instruction.
  15382. LoadSDNode *Origin;
  15383. // The right shift amount in bits from the original load.
  15384. unsigned Shift;
  15385. // The DAG from which Origin came from.
  15386. // This is used to get some contextual information about legal types, etc.
  15387. SelectionDAG *DAG;
  15388. LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
  15389. unsigned Shift = 0, SelectionDAG *DAG = nullptr)
  15390. : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
  15391. /// Get the bits used in a chunk of bits \p BitWidth large.
  15392. /// \return Result is \p BitWidth and has used bits set to 1 and
  15393. /// not used bits set to 0.
  15394. APInt getUsedBits() const {
  15395. // Reproduce the trunc(lshr) sequence:
  15396. // - Start from the truncated value.
  15397. // - Zero extend to the desired bit width.
  15398. // - Shift left.
  15399. assert(Origin && "No original load to compare against.");
  15400. unsigned BitWidth = Origin->getValueSizeInBits(0);
  15401. assert(Inst && "This slice is not bound to an instruction");
  15402. assert(Inst->getValueSizeInBits(0) <= BitWidth &&
  15403. "Extracted slice is bigger than the whole type!");
  15404. APInt UsedBits(Inst->getValueSizeInBits(0), 0);
  15405. UsedBits.setAllBits();
  15406. UsedBits = UsedBits.zext(BitWidth);
  15407. UsedBits <<= Shift;
  15408. return UsedBits;
  15409. }
  15410. /// Get the size of the slice to be loaded in bytes.
  15411. unsigned getLoadedSize() const {
  15412. unsigned SliceSize = getUsedBits().countPopulation();
  15413. assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
  15414. return SliceSize / 8;
  15415. }
  15416. /// Get the type that will be loaded for this slice.
  15417. /// Note: This may not be the final type for the slice.
  15418. EVT getLoadedType() const {
  15419. assert(DAG && "Missing context");
  15420. LLVMContext &Ctxt = *DAG->getContext();
  15421. return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
  15422. }
  15423. /// Get the alignment of the load used for this slice.
  15424. Align getAlign() const {
  15425. Align Alignment = Origin->getAlign();
  15426. uint64_t Offset = getOffsetFromBase();
  15427. if (Offset != 0)
  15428. Alignment = commonAlignment(Alignment, Alignment.value() + Offset);
  15429. return Alignment;
  15430. }
  15431. /// Check if this slice can be rewritten with legal operations.
  15432. bool isLegal() const {
  15433. // An invalid slice is not legal.
  15434. if (!Origin || !Inst || !DAG)
  15435. return false;
  15436. // Offsets are for indexed load only, we do not handle that.
  15437. if (!Origin->getOffset().isUndef())
  15438. return false;
  15439. const TargetLowering &TLI = DAG->getTargetLoweringInfo();
  15440. // Check that the type is legal.
  15441. EVT SliceType = getLoadedType();
  15442. if (!TLI.isTypeLegal(SliceType))
  15443. return false;
  15444. // Check that the load is legal for this type.
  15445. if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
  15446. return false;
  15447. // Check that the offset can be computed.
  15448. // 1. Check its type.
  15449. EVT PtrType = Origin->getBasePtr().getValueType();
  15450. if (PtrType == MVT::Untyped || PtrType.isExtended())
  15451. return false;
  15452. // 2. Check that it fits in the immediate.
  15453. if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
  15454. return false;
  15455. // 3. Check that the computation is legal.
  15456. if (!TLI.isOperationLegal(ISD::ADD, PtrType))
  15457. return false;
  15458. // Check that the zext is legal if it needs one.
  15459. EVT TruncateType = Inst->getValueType(0);
  15460. if (TruncateType != SliceType &&
  15461. !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
  15462. return false;
  15463. return true;
  15464. }
  15465. /// Get the offset in bytes of this slice in the original chunk of
  15466. /// bits.
  15467. /// \pre DAG != nullptr.
  15468. uint64_t getOffsetFromBase() const {
  15469. assert(DAG && "Missing context.");
  15470. bool IsBigEndian = DAG->getDataLayout().isBigEndian();
  15471. assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
  15472. uint64_t Offset = Shift / 8;
  15473. unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
  15474. assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
  15475. "The size of the original loaded type is not a multiple of a"
  15476. " byte.");
  15477. // If Offset is bigger than TySizeInBytes, it means we are loading all
  15478. // zeros. This should have been optimized before in the process.
  15479. assert(TySizeInBytes > Offset &&
  15480. "Invalid shift amount for given loaded size");
  15481. if (IsBigEndian)
  15482. Offset = TySizeInBytes - Offset - getLoadedSize();
  15483. return Offset;
  15484. }
  15485. /// Generate the sequence of instructions to load the slice
  15486. /// represented by this object and redirect the uses of this slice to
  15487. /// this new sequence of instructions.
  15488. /// \pre this->Inst && this->Origin are valid Instructions and this
  15489. /// object passed the legal check: LoadedSlice::isLegal returned true.
  15490. /// \return The last instruction of the sequence used to load the slice.
  15491. SDValue loadSlice() const {
  15492. assert(Inst && Origin && "Unable to replace a non-existing slice.");
  15493. const SDValue &OldBaseAddr = Origin->getBasePtr();
  15494. SDValue BaseAddr = OldBaseAddr;
  15495. // Get the offset in that chunk of bytes w.r.t. the endianness.
  15496. int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
  15497. assert(Offset >= 0 && "Offset too big to fit in int64_t!");
  15498. if (Offset) {
  15499. // BaseAddr = BaseAddr + Offset.
  15500. EVT ArithType = BaseAddr.getValueType();
  15501. SDLoc DL(Origin);
  15502. BaseAddr = DAG->getNode(ISD::ADD, DL, ArithType, BaseAddr,
  15503. DAG->getConstant(Offset, DL, ArithType));
  15504. }
  15505. // Create the type of the loaded slice according to its size.
  15506. EVT SliceType = getLoadedType();
  15507. // Create the load for the slice.
  15508. SDValue LastInst =
  15509. DAG->getLoad(SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
  15510. Origin->getPointerInfo().getWithOffset(Offset), getAlign(),
  15511. Origin->getMemOperand()->getFlags());
  15512. // If the final type is not the same as the loaded type, this means that
  15513. // we have to pad with zero. Create a zero extend for that.
  15514. EVT FinalType = Inst->getValueType(0);
  15515. if (SliceType != FinalType)
  15516. LastInst =
  15517. DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
  15518. return LastInst;
  15519. }
  15520. /// Check if this slice can be merged with an expensive cross register
  15521. /// bank copy. E.g.,
  15522. /// i = load i32
  15523. /// f = bitcast i32 i to float
  15524. bool canMergeExpensiveCrossRegisterBankCopy() const {
  15525. if (!Inst || !Inst->hasOneUse())
  15526. return false;
  15527. SDNode *Use = *Inst->use_begin();
  15528. if (Use->getOpcode() != ISD::BITCAST)
  15529. return false;
  15530. assert(DAG && "Missing context");
  15531. const TargetLowering &TLI = DAG->getTargetLoweringInfo();
  15532. EVT ResVT = Use->getValueType(0);
  15533. const TargetRegisterClass *ResRC =
  15534. TLI.getRegClassFor(ResVT.getSimpleVT(), Use->isDivergent());
  15535. const TargetRegisterClass *ArgRC =
  15536. TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT(),
  15537. Use->getOperand(0)->isDivergent());
  15538. if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
  15539. return false;
  15540. // At this point, we know that we perform a cross-register-bank copy.
  15541. // Check if it is expensive.
  15542. const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo();
  15543. // Assume bitcasts are cheap, unless both register classes do not
  15544. // explicitly share a common sub class.
  15545. if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
  15546. return false;
  15547. // Check if it will be merged with the load.
  15548. // 1. Check the alignment / fast memory access constraint.
  15549. unsigned IsFast = 0;
  15550. if (!TLI.allowsMemoryAccess(*DAG->getContext(), DAG->getDataLayout(), ResVT,
  15551. Origin->getAddressSpace(), getAlign(),
  15552. Origin->getMemOperand()->getFlags(), &IsFast) ||
  15553. !IsFast)
  15554. return false;
  15555. // 2. Check that the load is a legal operation for that type.
  15556. if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
  15557. return false;
  15558. // 3. Check that we do not have a zext in the way.
  15559. if (Inst->getValueType(0) != getLoadedType())
  15560. return false;
  15561. return true;
  15562. }
  15563. };
  15564. } // end anonymous namespace
  15565. /// Check that all bits set in \p UsedBits form a dense region, i.e.,
  15566. /// \p UsedBits looks like 0..0 1..1 0..0.
  15567. static bool areUsedBitsDense(const APInt &UsedBits) {
  15568. // If all the bits are one, this is dense!
  15569. if (UsedBits.isAllOnes())
  15570. return true;
  15571. // Get rid of the unused bits on the right.
  15572. APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
  15573. // Get rid of the unused bits on the left.
  15574. if (NarrowedUsedBits.countLeadingZeros())
  15575. NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
  15576. // Check that the chunk of bits is completely used.
  15577. return NarrowedUsedBits.isAllOnes();
  15578. }
  15579. /// Check whether or not \p First and \p Second are next to each other
  15580. /// in memory. This means that there is no hole between the bits loaded
  15581. /// by \p First and the bits loaded by \p Second.
  15582. static bool areSlicesNextToEachOther(const LoadedSlice &First,
  15583. const LoadedSlice &Second) {
  15584. assert(First.Origin == Second.Origin && First.Origin &&
  15585. "Unable to match different memory origins.");
  15586. APInt UsedBits = First.getUsedBits();
  15587. assert((UsedBits & Second.getUsedBits()) == 0 &&
  15588. "Slices are not supposed to overlap.");
  15589. UsedBits |= Second.getUsedBits();
  15590. return areUsedBitsDense(UsedBits);
  15591. }
  15592. /// Adjust the \p GlobalLSCost according to the target
  15593. /// paring capabilities and the layout of the slices.
  15594. /// \pre \p GlobalLSCost should account for at least as many loads as
  15595. /// there is in the slices in \p LoadedSlices.
  15596. static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
  15597. LoadedSlice::Cost &GlobalLSCost) {
  15598. unsigned NumberOfSlices = LoadedSlices.size();
  15599. // If there is less than 2 elements, no pairing is possible.
  15600. if (NumberOfSlices < 2)
  15601. return;
  15602. // Sort the slices so that elements that are likely to be next to each
  15603. // other in memory are next to each other in the list.
  15604. llvm::sort(LoadedSlices, [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
  15605. assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
  15606. return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
  15607. });
  15608. const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
  15609. // First (resp. Second) is the first (resp. Second) potentially candidate
  15610. // to be placed in a paired load.
  15611. const LoadedSlice *First = nullptr;
  15612. const LoadedSlice *Second = nullptr;
  15613. for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
  15614. // Set the beginning of the pair.
  15615. First = Second) {
  15616. Second = &LoadedSlices[CurrSlice];
  15617. // If First is NULL, it means we start a new pair.
  15618. // Get to the next slice.
  15619. if (!First)
  15620. continue;
  15621. EVT LoadedType = First->getLoadedType();
  15622. // If the types of the slices are different, we cannot pair them.
  15623. if (LoadedType != Second->getLoadedType())
  15624. continue;
  15625. // Check if the target supplies paired loads for this type.
  15626. Align RequiredAlignment;
  15627. if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
  15628. // move to the next pair, this type is hopeless.
  15629. Second = nullptr;
  15630. continue;
  15631. }
  15632. // Check if we meet the alignment requirement.
  15633. if (First->getAlign() < RequiredAlignment)
  15634. continue;
  15635. // Check that both loads are next to each other in memory.
  15636. if (!areSlicesNextToEachOther(*First, *Second))
  15637. continue;
  15638. assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
  15639. --GlobalLSCost.Loads;
  15640. // Move to the next pair.
  15641. Second = nullptr;
  15642. }
  15643. }
  15644. /// Check the profitability of all involved LoadedSlice.
  15645. /// Currently, it is considered profitable if there is exactly two
  15646. /// involved slices (1) which are (2) next to each other in memory, and
  15647. /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
  15648. ///
  15649. /// Note: The order of the elements in \p LoadedSlices may be modified, but not
  15650. /// the elements themselves.
  15651. ///
  15652. /// FIXME: When the cost model will be mature enough, we can relax
  15653. /// constraints (1) and (2).
  15654. static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
  15655. const APInt &UsedBits, bool ForCodeSize) {
  15656. unsigned NumberOfSlices = LoadedSlices.size();
  15657. if (StressLoadSlicing)
  15658. return NumberOfSlices > 1;
  15659. // Check (1).
  15660. if (NumberOfSlices != 2)
  15661. return false;
  15662. // Check (2).
  15663. if (!areUsedBitsDense(UsedBits))
  15664. return false;
  15665. // Check (3).
  15666. LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
  15667. // The original code has one big load.
  15668. OrigCost.Loads = 1;
  15669. for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
  15670. const LoadedSlice &LS = LoadedSlices[CurrSlice];
  15671. // Accumulate the cost of all the slices.
  15672. LoadedSlice::Cost SliceCost(LS, ForCodeSize);
  15673. GlobalSlicingCost += SliceCost;
  15674. // Account as cost in the original configuration the gain obtained
  15675. // with the current slices.
  15676. OrigCost.addSliceGain(LS);
  15677. }
  15678. // If the target supports paired load, adjust the cost accordingly.
  15679. adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
  15680. return OrigCost > GlobalSlicingCost;
  15681. }
  15682. /// If the given load, \p LI, is used only by trunc or trunc(lshr)
  15683. /// operations, split it in the various pieces being extracted.
  15684. ///
  15685. /// This sort of thing is introduced by SROA.
  15686. /// This slicing takes care not to insert overlapping loads.
  15687. /// \pre LI is a simple load (i.e., not an atomic or volatile load).
  15688. bool DAGCombiner::SliceUpLoad(SDNode *N) {
  15689. if (Level < AfterLegalizeDAG)
  15690. return false;
  15691. LoadSDNode *LD = cast<LoadSDNode>(N);
  15692. if (!LD->isSimple() || !ISD::isNormalLoad(LD) ||
  15693. !LD->getValueType(0).isInteger())
  15694. return false;
  15695. // The algorithm to split up a load of a scalable vector into individual
  15696. // elements currently requires knowing the length of the loaded type,
  15697. // so will need adjusting to work on scalable vectors.
  15698. if (LD->getValueType(0).isScalableVector())
  15699. return false;
  15700. // Keep track of already used bits to detect overlapping values.
  15701. // In that case, we will just abort the transformation.
  15702. APInt UsedBits(LD->getValueSizeInBits(0), 0);
  15703. SmallVector<LoadedSlice, 4> LoadedSlices;
  15704. // Check if this load is used as several smaller chunks of bits.
  15705. // Basically, look for uses in trunc or trunc(lshr) and record a new chain
  15706. // of computation for each trunc.
  15707. for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
  15708. UI != UIEnd; ++UI) {
  15709. // Skip the uses of the chain.
  15710. if (UI.getUse().getResNo() != 0)
  15711. continue;
  15712. SDNode *User = *UI;
  15713. unsigned Shift = 0;
  15714. // Check if this is a trunc(lshr).
  15715. if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
  15716. isa<ConstantSDNode>(User->getOperand(1))) {
  15717. Shift = User->getConstantOperandVal(1);
  15718. User = *User->use_begin();
  15719. }
  15720. // At this point, User is a Truncate, iff we encountered, trunc or
  15721. // trunc(lshr).
  15722. if (User->getOpcode() != ISD::TRUNCATE)
  15723. return false;
  15724. // The width of the type must be a power of 2 and greater than 8-bits.
  15725. // Otherwise the load cannot be represented in LLVM IR.
  15726. // Moreover, if we shifted with a non-8-bits multiple, the slice
  15727. // will be across several bytes. We do not support that.
  15728. unsigned Width = User->getValueSizeInBits(0);
  15729. if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
  15730. return false;
  15731. // Build the slice for this chain of computations.
  15732. LoadedSlice LS(User, LD, Shift, &DAG);
  15733. APInt CurrentUsedBits = LS.getUsedBits();
  15734. // Check if this slice overlaps with another.
  15735. if ((CurrentUsedBits & UsedBits) != 0)
  15736. return false;
  15737. // Update the bits used globally.
  15738. UsedBits |= CurrentUsedBits;
  15739. // Check if the new slice would be legal.
  15740. if (!LS.isLegal())
  15741. return false;
  15742. // Record the slice.
  15743. LoadedSlices.push_back(LS);
  15744. }
  15745. // Abort slicing if it does not seem to be profitable.
  15746. if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
  15747. return false;
  15748. ++SlicedLoads;
  15749. // Rewrite each chain to use an independent load.
  15750. // By construction, each chain can be represented by a unique load.
  15751. // Prepare the argument for the new token factor for all the slices.
  15752. SmallVector<SDValue, 8> ArgChains;
  15753. for (const LoadedSlice &LS : LoadedSlices) {
  15754. SDValue SliceInst = LS.loadSlice();
  15755. CombineTo(LS.Inst, SliceInst, true);
  15756. if (SliceInst.getOpcode() != ISD::LOAD)
  15757. SliceInst = SliceInst.getOperand(0);
  15758. assert(SliceInst->getOpcode() == ISD::LOAD &&
  15759. "It takes more than a zext to get to the loaded slice!!");
  15760. ArgChains.push_back(SliceInst.getValue(1));
  15761. }
  15762. SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
  15763. ArgChains);
  15764. DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
  15765. AddToWorklist(Chain.getNode());
  15766. return true;
  15767. }
  15768. /// Check to see if V is (and load (ptr), imm), where the load is having
  15769. /// specific bytes cleared out. If so, return the byte size being masked out
  15770. /// and the shift amount.
  15771. static std::pair<unsigned, unsigned>
  15772. CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
  15773. std::pair<unsigned, unsigned> Result(0, 0);
  15774. // Check for the structure we're looking for.
  15775. if (V->getOpcode() != ISD::AND ||
  15776. !isa<ConstantSDNode>(V->getOperand(1)) ||
  15777. !ISD::isNormalLoad(V->getOperand(0).getNode()))
  15778. return Result;
  15779. // Check the chain and pointer.
  15780. LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
  15781. if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer.
  15782. // This only handles simple types.
  15783. if (V.getValueType() != MVT::i16 &&
  15784. V.getValueType() != MVT::i32 &&
  15785. V.getValueType() != MVT::i64)
  15786. return Result;
  15787. // Check the constant mask. Invert it so that the bits being masked out are
  15788. // 0 and the bits being kept are 1. Use getSExtValue so that leading bits
  15789. // follow the sign bit for uniformity.
  15790. uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
  15791. unsigned NotMaskLZ = countLeadingZeros(NotMask);
  15792. if (NotMaskLZ & 7) return Result; // Must be multiple of a byte.
  15793. unsigned NotMaskTZ = countTrailingZeros(NotMask);
  15794. if (NotMaskTZ & 7) return Result; // Must be multiple of a byte.
  15795. if (NotMaskLZ == 64) return Result; // All zero mask.
  15796. // See if we have a continuous run of bits. If so, we have 0*1+0*
  15797. if (countTrailingOnes(NotMask >> NotMaskTZ) + NotMaskTZ + NotMaskLZ != 64)
  15798. return Result;
  15799. // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
  15800. if (V.getValueType() != MVT::i64 && NotMaskLZ)
  15801. NotMaskLZ -= 64-V.getValueSizeInBits();
  15802. unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
  15803. switch (MaskedBytes) {
  15804. case 1:
  15805. case 2:
  15806. case 4: break;
  15807. default: return Result; // All one mask, or 5-byte mask.
  15808. }
  15809. // Verify that the first bit starts at a multiple of mask so that the access
  15810. // is aligned the same as the access width.
  15811. if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
  15812. // For narrowing to be valid, it must be the case that the load the
  15813. // immediately preceding memory operation before the store.
  15814. if (LD == Chain.getNode())
  15815. ; // ok.
  15816. else if (Chain->getOpcode() == ISD::TokenFactor &&
  15817. SDValue(LD, 1).hasOneUse()) {
  15818. // LD has only 1 chain use so they are no indirect dependencies.
  15819. if (!LD->isOperandOf(Chain.getNode()))
  15820. return Result;
  15821. } else
  15822. return Result; // Fail.
  15823. Result.first = MaskedBytes;
  15824. Result.second = NotMaskTZ/8;
  15825. return Result;
  15826. }
  15827. /// Check to see if IVal is something that provides a value as specified by
  15828. /// MaskInfo. If so, replace the specified store with a narrower store of
  15829. /// truncated IVal.
  15830. static SDValue
  15831. ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
  15832. SDValue IVal, StoreSDNode *St,
  15833. DAGCombiner *DC) {
  15834. unsigned NumBytes = MaskInfo.first;
  15835. unsigned ByteShift = MaskInfo.second;
  15836. SelectionDAG &DAG = DC->getDAG();
  15837. // Check to see if IVal is all zeros in the part being masked in by the 'or'
  15838. // that uses this. If not, this is not a replacement.
  15839. APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
  15840. ByteShift*8, (ByteShift+NumBytes)*8);
  15841. if (!DAG.MaskedValueIsZero(IVal, Mask)) return SDValue();
  15842. // Check that it is legal on the target to do this. It is legal if the new
  15843. // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
  15844. // legalization. If the source type is legal, but the store type isn't, see
  15845. // if we can use a truncating store.
  15846. MVT VT = MVT::getIntegerVT(NumBytes * 8);
  15847. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  15848. bool UseTruncStore;
  15849. if (DC->isTypeLegal(VT))
  15850. UseTruncStore = false;
  15851. else if (TLI.isTypeLegal(IVal.getValueType()) &&
  15852. TLI.isTruncStoreLegal(IVal.getValueType(), VT))
  15853. UseTruncStore = true;
  15854. else
  15855. return SDValue();
  15856. // Check that the target doesn't think this is a bad idea.
  15857. if (St->getMemOperand() &&
  15858. !TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT,
  15859. *St->getMemOperand()))
  15860. return SDValue();
  15861. // Okay, we can do this! Replace the 'St' store with a store of IVal that is
  15862. // shifted by ByteShift and truncated down to NumBytes.
  15863. if (ByteShift) {
  15864. SDLoc DL(IVal);
  15865. IVal = DAG.getNode(ISD::SRL, DL, IVal.getValueType(), IVal,
  15866. DAG.getConstant(ByteShift*8, DL,
  15867. DC->getShiftAmountTy(IVal.getValueType())));
  15868. }
  15869. // Figure out the offset for the store and the alignment of the access.
  15870. unsigned StOffset;
  15871. if (DAG.getDataLayout().isLittleEndian())
  15872. StOffset = ByteShift;
  15873. else
  15874. StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
  15875. SDValue Ptr = St->getBasePtr();
  15876. if (StOffset) {
  15877. SDLoc DL(IVal);
  15878. Ptr = DAG.getMemBasePlusOffset(Ptr, TypeSize::Fixed(StOffset), DL);
  15879. }
  15880. ++OpsNarrowed;
  15881. if (UseTruncStore)
  15882. return DAG.getTruncStore(St->getChain(), SDLoc(St), IVal, Ptr,
  15883. St->getPointerInfo().getWithOffset(StOffset),
  15884. VT, St->getOriginalAlign());
  15885. // Truncate down to the new size.
  15886. IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
  15887. return DAG
  15888. .getStore(St->getChain(), SDLoc(St), IVal, Ptr,
  15889. St->getPointerInfo().getWithOffset(StOffset),
  15890. St->getOriginalAlign());
  15891. }
  15892. /// Look for sequence of load / op / store where op is one of 'or', 'xor', and
  15893. /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try
  15894. /// narrowing the load and store if it would end up being a win for performance
  15895. /// or code size.
  15896. SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
  15897. StoreSDNode *ST = cast<StoreSDNode>(N);
  15898. if (!ST->isSimple())
  15899. return SDValue();
  15900. SDValue Chain = ST->getChain();
  15901. SDValue Value = ST->getValue();
  15902. SDValue Ptr = ST->getBasePtr();
  15903. EVT VT = Value.getValueType();
  15904. if (ST->isTruncatingStore() || VT.isVector())
  15905. return SDValue();
  15906. unsigned Opc = Value.getOpcode();
  15907. if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
  15908. !Value.hasOneUse())
  15909. return SDValue();
  15910. // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
  15911. // is a byte mask indicating a consecutive number of bytes, check to see if
  15912. // Y is known to provide just those bytes. If so, we try to replace the
  15913. // load + replace + store sequence with a single (narrower) store, which makes
  15914. // the load dead.
  15915. if (Opc == ISD::OR && EnableShrinkLoadReplaceStoreWithStore) {
  15916. std::pair<unsigned, unsigned> MaskedLoad;
  15917. MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
  15918. if (MaskedLoad.first)
  15919. if (SDValue NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
  15920. Value.getOperand(1), ST,this))
  15921. return NewST;
  15922. // Or is commutative, so try swapping X and Y.
  15923. MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
  15924. if (MaskedLoad.first)
  15925. if (SDValue NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
  15926. Value.getOperand(0), ST,this))
  15927. return NewST;
  15928. }
  15929. if (!EnableReduceLoadOpStoreWidth)
  15930. return SDValue();
  15931. if (Value.getOperand(1).getOpcode() != ISD::Constant)
  15932. return SDValue();
  15933. SDValue N0 = Value.getOperand(0);
  15934. if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
  15935. Chain == SDValue(N0.getNode(), 1)) {
  15936. LoadSDNode *LD = cast<LoadSDNode>(N0);
  15937. if (LD->getBasePtr() != Ptr ||
  15938. LD->getPointerInfo().getAddrSpace() !=
  15939. ST->getPointerInfo().getAddrSpace())
  15940. return SDValue();
  15941. // Find the type to narrow it the load / op / store to.
  15942. SDValue N1 = Value.getOperand(1);
  15943. unsigned BitWidth = N1.getValueSizeInBits();
  15944. APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
  15945. if (Opc == ISD::AND)
  15946. Imm ^= APInt::getAllOnes(BitWidth);
  15947. if (Imm == 0 || Imm.isAllOnes())
  15948. return SDValue();
  15949. unsigned ShAmt = Imm.countTrailingZeros();
  15950. unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
  15951. unsigned NewBW = NextPowerOf2(MSB - ShAmt);
  15952. EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
  15953. // The narrowing should be profitable, the load/store operation should be
  15954. // legal (or custom) and the store size should be equal to the NewVT width.
  15955. while (NewBW < BitWidth &&
  15956. (NewVT.getStoreSizeInBits() != NewBW ||
  15957. !TLI.isOperationLegalOrCustom(Opc, NewVT) ||
  15958. !TLI.isNarrowingProfitable(VT, NewVT))) {
  15959. NewBW = NextPowerOf2(NewBW);
  15960. NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
  15961. }
  15962. if (NewBW >= BitWidth)
  15963. return SDValue();
  15964. // If the lsb changed does not start at the type bitwidth boundary,
  15965. // start at the previous one.
  15966. if (ShAmt % NewBW)
  15967. ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
  15968. APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
  15969. std::min(BitWidth, ShAmt + NewBW));
  15970. if ((Imm & Mask) == Imm) {
  15971. APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
  15972. if (Opc == ISD::AND)
  15973. NewImm ^= APInt::getAllOnes(NewBW);
  15974. uint64_t PtrOff = ShAmt / 8;
  15975. // For big endian targets, we need to adjust the offset to the pointer to
  15976. // load the correct bytes.
  15977. if (DAG.getDataLayout().isBigEndian())
  15978. PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
  15979. unsigned IsFast = 0;
  15980. Align NewAlign = commonAlignment(LD->getAlign(), PtrOff);
  15981. if (!TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), NewVT,
  15982. LD->getAddressSpace(), NewAlign,
  15983. LD->getMemOperand()->getFlags(), &IsFast) ||
  15984. !IsFast)
  15985. return SDValue();
  15986. SDValue NewPtr =
  15987. DAG.getMemBasePlusOffset(Ptr, TypeSize::Fixed(PtrOff), SDLoc(LD));
  15988. SDValue NewLD =
  15989. DAG.getLoad(NewVT, SDLoc(N0), LD->getChain(), NewPtr,
  15990. LD->getPointerInfo().getWithOffset(PtrOff), NewAlign,
  15991. LD->getMemOperand()->getFlags(), LD->getAAInfo());
  15992. SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
  15993. DAG.getConstant(NewImm, SDLoc(Value),
  15994. NewVT));
  15995. SDValue NewST =
  15996. DAG.getStore(Chain, SDLoc(N), NewVal, NewPtr,
  15997. ST->getPointerInfo().getWithOffset(PtrOff), NewAlign);
  15998. AddToWorklist(NewPtr.getNode());
  15999. AddToWorklist(NewLD.getNode());
  16000. AddToWorklist(NewVal.getNode());
  16001. WorklistRemover DeadNodes(*this);
  16002. DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
  16003. ++OpsNarrowed;
  16004. return NewST;
  16005. }
  16006. }
  16007. return SDValue();
  16008. }
  16009. /// For a given floating point load / store pair, if the load value isn't used
  16010. /// by any other operations, then consider transforming the pair to integer
  16011. /// load / store operations if the target deems the transformation profitable.
  16012. SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
  16013. StoreSDNode *ST = cast<StoreSDNode>(N);
  16014. SDValue Value = ST->getValue();
  16015. if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
  16016. Value.hasOneUse()) {
  16017. LoadSDNode *LD = cast<LoadSDNode>(Value);
  16018. EVT VT = LD->getMemoryVT();
  16019. if (!VT.isFloatingPoint() ||
  16020. VT != ST->getMemoryVT() ||
  16021. LD->isNonTemporal() ||
  16022. ST->isNonTemporal() ||
  16023. LD->getPointerInfo().getAddrSpace() != 0 ||
  16024. ST->getPointerInfo().getAddrSpace() != 0)
  16025. return SDValue();
  16026. TypeSize VTSize = VT.getSizeInBits();
  16027. // We don't know the size of scalable types at compile time so we cannot
  16028. // create an integer of the equivalent size.
  16029. if (VTSize.isScalable())
  16030. return SDValue();
  16031. unsigned FastLD = 0, FastST = 0;
  16032. EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VTSize.getFixedValue());
  16033. if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
  16034. !TLI.isOperationLegal(ISD::STORE, IntVT) ||
  16035. !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
  16036. !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT) ||
  16037. !TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), IntVT,
  16038. *LD->getMemOperand(), &FastLD) ||
  16039. !TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), IntVT,
  16040. *ST->getMemOperand(), &FastST) ||
  16041. !FastLD || !FastST)
  16042. return SDValue();
  16043. SDValue NewLD =
  16044. DAG.getLoad(IntVT, SDLoc(Value), LD->getChain(), LD->getBasePtr(),
  16045. LD->getPointerInfo(), LD->getAlign());
  16046. SDValue NewST =
  16047. DAG.getStore(ST->getChain(), SDLoc(N), NewLD, ST->getBasePtr(),
  16048. ST->getPointerInfo(), ST->getAlign());
  16049. AddToWorklist(NewLD.getNode());
  16050. AddToWorklist(NewST.getNode());
  16051. WorklistRemover DeadNodes(*this);
  16052. DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
  16053. ++LdStFP2Int;
  16054. return NewST;
  16055. }
  16056. return SDValue();
  16057. }
  16058. // This is a helper function for visitMUL to check the profitability
  16059. // of folding (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2).
  16060. // MulNode is the original multiply, AddNode is (add x, c1),
  16061. // and ConstNode is c2.
  16062. //
  16063. // If the (add x, c1) has multiple uses, we could increase
  16064. // the number of adds if we make this transformation.
  16065. // It would only be worth doing this if we can remove a
  16066. // multiply in the process. Check for that here.
  16067. // To illustrate:
  16068. // (A + c1) * c3
  16069. // (A + c2) * c3
  16070. // We're checking for cases where we have common "c3 * A" expressions.
  16071. bool DAGCombiner::isMulAddWithConstProfitable(SDNode *MulNode, SDValue AddNode,
  16072. SDValue ConstNode) {
  16073. APInt Val;
  16074. // If the add only has one use, and the target thinks the folding is
  16075. // profitable or does not lead to worse code, this would be OK to do.
  16076. if (AddNode->hasOneUse() &&
  16077. TLI.isMulAddWithConstProfitable(AddNode, ConstNode))
  16078. return true;
  16079. // Walk all the users of the constant with which we're multiplying.
  16080. for (SDNode *Use : ConstNode->uses()) {
  16081. if (Use == MulNode) // This use is the one we're on right now. Skip it.
  16082. continue;
  16083. if (Use->getOpcode() == ISD::MUL) { // We have another multiply use.
  16084. SDNode *OtherOp;
  16085. SDNode *MulVar = AddNode.getOperand(0).getNode();
  16086. // OtherOp is what we're multiplying against the constant.
  16087. if (Use->getOperand(0) == ConstNode)
  16088. OtherOp = Use->getOperand(1).getNode();
  16089. else
  16090. OtherOp = Use->getOperand(0).getNode();
  16091. // Check to see if multiply is with the same operand of our "add".
  16092. //
  16093. // ConstNode = CONST
  16094. // Use = ConstNode * A <-- visiting Use. OtherOp is A.
  16095. // ...
  16096. // AddNode = (A + c1) <-- MulVar is A.
  16097. // = AddNode * ConstNode <-- current visiting instruction.
  16098. //
  16099. // If we make this transformation, we will have a common
  16100. // multiply (ConstNode * A) that we can save.
  16101. if (OtherOp == MulVar)
  16102. return true;
  16103. // Now check to see if a future expansion will give us a common
  16104. // multiply.
  16105. //
  16106. // ConstNode = CONST
  16107. // AddNode = (A + c1)
  16108. // ... = AddNode * ConstNode <-- current visiting instruction.
  16109. // ...
  16110. // OtherOp = (A + c2)
  16111. // Use = OtherOp * ConstNode <-- visiting Use.
  16112. //
  16113. // If we make this transformation, we will have a common
  16114. // multiply (CONST * A) after we also do the same transformation
  16115. // to the "t2" instruction.
  16116. if (OtherOp->getOpcode() == ISD::ADD &&
  16117. DAG.isConstantIntBuildVectorOrConstantInt(OtherOp->getOperand(1)) &&
  16118. OtherOp->getOperand(0).getNode() == MulVar)
  16119. return true;
  16120. }
  16121. }
  16122. // Didn't find a case where this would be profitable.
  16123. return false;
  16124. }
  16125. SDValue DAGCombiner::getMergeStoreChains(SmallVectorImpl<MemOpLink> &StoreNodes,
  16126. unsigned NumStores) {
  16127. SmallVector<SDValue, 8> Chains;
  16128. SmallPtrSet<const SDNode *, 8> Visited;
  16129. SDLoc StoreDL(StoreNodes[0].MemNode);
  16130. for (unsigned i = 0; i < NumStores; ++i) {
  16131. Visited.insert(StoreNodes[i].MemNode);
  16132. }
  16133. // don't include nodes that are children or repeated nodes.
  16134. for (unsigned i = 0; i < NumStores; ++i) {
  16135. if (Visited.insert(StoreNodes[i].MemNode->getChain().getNode()).second)
  16136. Chains.push_back(StoreNodes[i].MemNode->getChain());
  16137. }
  16138. assert(Chains.size() > 0 && "Chain should have generated a chain");
  16139. return DAG.getTokenFactor(StoreDL, Chains);
  16140. }
  16141. bool DAGCombiner::mergeStoresOfConstantsOrVecElts(
  16142. SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT, unsigned NumStores,
  16143. bool IsConstantSrc, bool UseVector, bool UseTrunc) {
  16144. // Make sure we have something to merge.
  16145. if (NumStores < 2)
  16146. return false;
  16147. assert((!UseTrunc || !UseVector) &&
  16148. "This optimization cannot emit a vector truncating store");
  16149. // The latest Node in the DAG.
  16150. SDLoc DL(StoreNodes[0].MemNode);
  16151. TypeSize ElementSizeBits = MemVT.getStoreSizeInBits();
  16152. unsigned SizeInBits = NumStores * ElementSizeBits;
  16153. unsigned NumMemElts = MemVT.isVector() ? MemVT.getVectorNumElements() : 1;
  16154. std::optional<MachineMemOperand::Flags> Flags;
  16155. AAMDNodes AAInfo;
  16156. for (unsigned I = 0; I != NumStores; ++I) {
  16157. StoreSDNode *St = cast<StoreSDNode>(StoreNodes[I].MemNode);
  16158. if (!Flags) {
  16159. Flags = St->getMemOperand()->getFlags();
  16160. AAInfo = St->getAAInfo();
  16161. continue;
  16162. }
  16163. // Skip merging if there's an inconsistent flag.
  16164. if (Flags != St->getMemOperand()->getFlags())
  16165. return false;
  16166. // Concatenate AA metadata.
  16167. AAInfo = AAInfo.concat(St->getAAInfo());
  16168. }
  16169. EVT StoreTy;
  16170. if (UseVector) {
  16171. unsigned Elts = NumStores * NumMemElts;
  16172. // Get the type for the merged vector store.
  16173. StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts);
  16174. } else
  16175. StoreTy = EVT::getIntegerVT(*DAG.getContext(), SizeInBits);
  16176. SDValue StoredVal;
  16177. if (UseVector) {
  16178. if (IsConstantSrc) {
  16179. SmallVector<SDValue, 8> BuildVector;
  16180. for (unsigned I = 0; I != NumStores; ++I) {
  16181. StoreSDNode *St = cast<StoreSDNode>(StoreNodes[I].MemNode);
  16182. SDValue Val = St->getValue();
  16183. // If constant is of the wrong type, convert it now.
  16184. if (MemVT != Val.getValueType()) {
  16185. Val = peekThroughBitcasts(Val);
  16186. // Deal with constants of wrong size.
  16187. if (ElementSizeBits != Val.getValueSizeInBits()) {
  16188. EVT IntMemVT =
  16189. EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits());
  16190. if (isa<ConstantFPSDNode>(Val)) {
  16191. // Not clear how to truncate FP values.
  16192. return false;
  16193. }
  16194. if (auto *C = dyn_cast<ConstantSDNode>(Val))
  16195. Val = DAG.getConstant(C->getAPIntValue()
  16196. .zextOrTrunc(Val.getValueSizeInBits())
  16197. .zextOrTrunc(ElementSizeBits),
  16198. SDLoc(C), IntMemVT);
  16199. }
  16200. // Make sure correctly size type is the correct type.
  16201. Val = DAG.getBitcast(MemVT, Val);
  16202. }
  16203. BuildVector.push_back(Val);
  16204. }
  16205. StoredVal = DAG.getNode(MemVT.isVector() ? ISD::CONCAT_VECTORS
  16206. : ISD::BUILD_VECTOR,
  16207. DL, StoreTy, BuildVector);
  16208. } else {
  16209. SmallVector<SDValue, 8> Ops;
  16210. for (unsigned i = 0; i < NumStores; ++i) {
  16211. StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
  16212. SDValue Val = peekThroughBitcasts(St->getValue());
  16213. // All operands of BUILD_VECTOR / CONCAT_VECTOR must be of
  16214. // type MemVT. If the underlying value is not the correct
  16215. // type, but it is an extraction of an appropriate vector we
  16216. // can recast Val to be of the correct type. This may require
  16217. // converting between EXTRACT_VECTOR_ELT and
  16218. // EXTRACT_SUBVECTOR.
  16219. if ((MemVT != Val.getValueType()) &&
  16220. (Val.getOpcode() == ISD::EXTRACT_VECTOR_ELT ||
  16221. Val.getOpcode() == ISD::EXTRACT_SUBVECTOR)) {
  16222. EVT MemVTScalarTy = MemVT.getScalarType();
  16223. // We may need to add a bitcast here to get types to line up.
  16224. if (MemVTScalarTy != Val.getValueType().getScalarType()) {
  16225. Val = DAG.getBitcast(MemVT, Val);
  16226. } else if (MemVT.isVector() &&
  16227. Val.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
  16228. Val = DAG.getNode(ISD::BUILD_VECTOR, DL, MemVT, Val);
  16229. } else {
  16230. unsigned OpC = MemVT.isVector() ? ISD::EXTRACT_SUBVECTOR
  16231. : ISD::EXTRACT_VECTOR_ELT;
  16232. SDValue Vec = Val.getOperand(0);
  16233. SDValue Idx = Val.getOperand(1);
  16234. Val = DAG.getNode(OpC, SDLoc(Val), MemVT, Vec, Idx);
  16235. }
  16236. }
  16237. Ops.push_back(Val);
  16238. }
  16239. // Build the extracted vector elements back into a vector.
  16240. StoredVal = DAG.getNode(MemVT.isVector() ? ISD::CONCAT_VECTORS
  16241. : ISD::BUILD_VECTOR,
  16242. DL, StoreTy, Ops);
  16243. }
  16244. } else {
  16245. // We should always use a vector store when merging extracted vector
  16246. // elements, so this path implies a store of constants.
  16247. assert(IsConstantSrc && "Merged vector elements should use vector store");
  16248. APInt StoreInt(SizeInBits, 0);
  16249. // Construct a single integer constant which is made of the smaller
  16250. // constant inputs.
  16251. bool IsLE = DAG.getDataLayout().isLittleEndian();
  16252. for (unsigned i = 0; i < NumStores; ++i) {
  16253. unsigned Idx = IsLE ? (NumStores - 1 - i) : i;
  16254. StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
  16255. SDValue Val = St->getValue();
  16256. Val = peekThroughBitcasts(Val);
  16257. StoreInt <<= ElementSizeBits;
  16258. if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
  16259. StoreInt |= C->getAPIntValue()
  16260. .zextOrTrunc(ElementSizeBits)
  16261. .zextOrTrunc(SizeInBits);
  16262. } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
  16263. StoreInt |= C->getValueAPF()
  16264. .bitcastToAPInt()
  16265. .zextOrTrunc(ElementSizeBits)
  16266. .zextOrTrunc(SizeInBits);
  16267. // If fp truncation is necessary give up for now.
  16268. if (MemVT.getSizeInBits() != ElementSizeBits)
  16269. return false;
  16270. } else {
  16271. llvm_unreachable("Invalid constant element type");
  16272. }
  16273. }
  16274. // Create the new Load and Store operations.
  16275. StoredVal = DAG.getConstant(StoreInt, DL, StoreTy);
  16276. }
  16277. LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
  16278. SDValue NewChain = getMergeStoreChains(StoreNodes, NumStores);
  16279. // make sure we use trunc store if it's necessary to be legal.
  16280. SDValue NewStore;
  16281. if (!UseTrunc) {
  16282. NewStore = DAG.getStore(NewChain, DL, StoredVal, FirstInChain->getBasePtr(),
  16283. FirstInChain->getPointerInfo(),
  16284. FirstInChain->getAlign(), *Flags, AAInfo);
  16285. } else { // Must be realized as a trunc store
  16286. EVT LegalizedStoredValTy =
  16287. TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
  16288. unsigned LegalizedStoreSize = LegalizedStoredValTy.getSizeInBits();
  16289. ConstantSDNode *C = cast<ConstantSDNode>(StoredVal);
  16290. SDValue ExtendedStoreVal =
  16291. DAG.getConstant(C->getAPIntValue().zextOrTrunc(LegalizedStoreSize), DL,
  16292. LegalizedStoredValTy);
  16293. NewStore = DAG.getTruncStore(
  16294. NewChain, DL, ExtendedStoreVal, FirstInChain->getBasePtr(),
  16295. FirstInChain->getPointerInfo(), StoredVal.getValueType() /*TVT*/,
  16296. FirstInChain->getAlign(), *Flags, AAInfo);
  16297. }
  16298. // Replace all merged stores with the new store.
  16299. for (unsigned i = 0; i < NumStores; ++i)
  16300. CombineTo(StoreNodes[i].MemNode, NewStore);
  16301. AddToWorklist(NewChain.getNode());
  16302. return true;
  16303. }
  16304. void DAGCombiner::getStoreMergeCandidates(
  16305. StoreSDNode *St, SmallVectorImpl<MemOpLink> &StoreNodes,
  16306. SDNode *&RootNode) {
  16307. // This holds the base pointer, index, and the offset in bytes from the base
  16308. // pointer. We must have a base and an offset. Do not handle stores to undef
  16309. // base pointers.
  16310. BaseIndexOffset BasePtr = BaseIndexOffset::match(St, DAG);
  16311. if (!BasePtr.getBase().getNode() || BasePtr.getBase().isUndef())
  16312. return;
  16313. SDValue Val = peekThroughBitcasts(St->getValue());
  16314. StoreSource StoreSrc = getStoreSource(Val);
  16315. assert(StoreSrc != StoreSource::Unknown && "Expected known source for store");
  16316. // Match on loadbaseptr if relevant.
  16317. EVT MemVT = St->getMemoryVT();
  16318. BaseIndexOffset LBasePtr;
  16319. EVT LoadVT;
  16320. if (StoreSrc == StoreSource::Load) {
  16321. auto *Ld = cast<LoadSDNode>(Val);
  16322. LBasePtr = BaseIndexOffset::match(Ld, DAG);
  16323. LoadVT = Ld->getMemoryVT();
  16324. // Load and store should be the same type.
  16325. if (MemVT != LoadVT)
  16326. return;
  16327. // Loads must only have one use.
  16328. if (!Ld->hasNUsesOfValue(1, 0))
  16329. return;
  16330. // The memory operands must not be volatile/indexed/atomic.
  16331. // TODO: May be able to relax for unordered atomics (see D66309)
  16332. if (!Ld->isSimple() || Ld->isIndexed())
  16333. return;
  16334. }
  16335. auto CandidateMatch = [&](StoreSDNode *Other, BaseIndexOffset &Ptr,
  16336. int64_t &Offset) -> bool {
  16337. // The memory operands must not be volatile/indexed/atomic.
  16338. // TODO: May be able to relax for unordered atomics (see D66309)
  16339. if (!Other->isSimple() || Other->isIndexed())
  16340. return false;
  16341. // Don't mix temporal stores with non-temporal stores.
  16342. if (St->isNonTemporal() != Other->isNonTemporal())
  16343. return false;
  16344. SDValue OtherBC = peekThroughBitcasts(Other->getValue());
  16345. // Allow merging constants of different types as integers.
  16346. bool NoTypeMatch = (MemVT.isInteger()) ? !MemVT.bitsEq(Other->getMemoryVT())
  16347. : Other->getMemoryVT() != MemVT;
  16348. switch (StoreSrc) {
  16349. case StoreSource::Load: {
  16350. if (NoTypeMatch)
  16351. return false;
  16352. // The Load's Base Ptr must also match.
  16353. auto *OtherLd = dyn_cast<LoadSDNode>(OtherBC);
  16354. if (!OtherLd)
  16355. return false;
  16356. BaseIndexOffset LPtr = BaseIndexOffset::match(OtherLd, DAG);
  16357. if (LoadVT != OtherLd->getMemoryVT())
  16358. return false;
  16359. // Loads must only have one use.
  16360. if (!OtherLd->hasNUsesOfValue(1, 0))
  16361. return false;
  16362. // The memory operands must not be volatile/indexed/atomic.
  16363. // TODO: May be able to relax for unordered atomics (see D66309)
  16364. if (!OtherLd->isSimple() || OtherLd->isIndexed())
  16365. return false;
  16366. // Don't mix temporal loads with non-temporal loads.
  16367. if (cast<LoadSDNode>(Val)->isNonTemporal() != OtherLd->isNonTemporal())
  16368. return false;
  16369. if (!(LBasePtr.equalBaseIndex(LPtr, DAG)))
  16370. return false;
  16371. break;
  16372. }
  16373. case StoreSource::Constant:
  16374. if (NoTypeMatch)
  16375. return false;
  16376. if (!isIntOrFPConstant(OtherBC))
  16377. return false;
  16378. break;
  16379. case StoreSource::Extract:
  16380. // Do not merge truncated stores here.
  16381. if (Other->isTruncatingStore())
  16382. return false;
  16383. if (!MemVT.bitsEq(OtherBC.getValueType()))
  16384. return false;
  16385. if (OtherBC.getOpcode() != ISD::EXTRACT_VECTOR_ELT &&
  16386. OtherBC.getOpcode() != ISD::EXTRACT_SUBVECTOR)
  16387. return false;
  16388. break;
  16389. default:
  16390. llvm_unreachable("Unhandled store source for merging");
  16391. }
  16392. Ptr = BaseIndexOffset::match(Other, DAG);
  16393. return (BasePtr.equalBaseIndex(Ptr, DAG, Offset));
  16394. };
  16395. // Check if the pair of StoreNode and the RootNode already bail out many
  16396. // times which is over the limit in dependence check.
  16397. auto OverLimitInDependenceCheck = [&](SDNode *StoreNode,
  16398. SDNode *RootNode) -> bool {
  16399. auto RootCount = StoreRootCountMap.find(StoreNode);
  16400. return RootCount != StoreRootCountMap.end() &&
  16401. RootCount->second.first == RootNode &&
  16402. RootCount->second.second > StoreMergeDependenceLimit;
  16403. };
  16404. auto TryToAddCandidate = [&](SDNode::use_iterator UseIter) {
  16405. // This must be a chain use.
  16406. if (UseIter.getOperandNo() != 0)
  16407. return;
  16408. if (auto *OtherStore = dyn_cast<StoreSDNode>(*UseIter)) {
  16409. BaseIndexOffset Ptr;
  16410. int64_t PtrDiff;
  16411. if (CandidateMatch(OtherStore, Ptr, PtrDiff) &&
  16412. !OverLimitInDependenceCheck(OtherStore, RootNode))
  16413. StoreNodes.push_back(MemOpLink(OtherStore, PtrDiff));
  16414. }
  16415. };
  16416. // We looking for a root node which is an ancestor to all mergable
  16417. // stores. We search up through a load, to our root and then down
  16418. // through all children. For instance we will find Store{1,2,3} if
  16419. // St is Store1, Store2. or Store3 where the root is not a load
  16420. // which always true for nonvolatile ops. TODO: Expand
  16421. // the search to find all valid candidates through multiple layers of loads.
  16422. //
  16423. // Root
  16424. // |-------|-------|
  16425. // Load Load Store3
  16426. // | |
  16427. // Store1 Store2
  16428. //
  16429. // FIXME: We should be able to climb and
  16430. // descend TokenFactors to find candidates as well.
  16431. RootNode = St->getChain().getNode();
  16432. unsigned NumNodesExplored = 0;
  16433. const unsigned MaxSearchNodes = 1024;
  16434. if (auto *Ldn = dyn_cast<LoadSDNode>(RootNode)) {
  16435. RootNode = Ldn->getChain().getNode();
  16436. for (auto I = RootNode->use_begin(), E = RootNode->use_end();
  16437. I != E && NumNodesExplored < MaxSearchNodes; ++I, ++NumNodesExplored) {
  16438. if (I.getOperandNo() == 0 && isa<LoadSDNode>(*I)) { // walk down chain
  16439. for (auto I2 = (*I)->use_begin(), E2 = (*I)->use_end(); I2 != E2; ++I2)
  16440. TryToAddCandidate(I2);
  16441. }
  16442. // Check stores that depend on the root (e.g. Store 3 in the chart above).
  16443. if (I.getOperandNo() == 0 && isa<StoreSDNode>(*I)) {
  16444. TryToAddCandidate(I);
  16445. }
  16446. }
  16447. } else {
  16448. for (auto I = RootNode->use_begin(), E = RootNode->use_end();
  16449. I != E && NumNodesExplored < MaxSearchNodes; ++I, ++NumNodesExplored)
  16450. TryToAddCandidate(I);
  16451. }
  16452. }
  16453. // We need to check that merging these stores does not cause a loop in the
  16454. // DAG. Any store candidate may depend on another candidate indirectly through
  16455. // its operands. Check in parallel by searching up from operands of candidates.
  16456. bool DAGCombiner::checkMergeStoreCandidatesForDependencies(
  16457. SmallVectorImpl<MemOpLink> &StoreNodes, unsigned NumStores,
  16458. SDNode *RootNode) {
  16459. // FIXME: We should be able to truncate a full search of
  16460. // predecessors by doing a BFS and keeping tabs the originating
  16461. // stores from which worklist nodes come from in a similar way to
  16462. // TokenFactor simplfication.
  16463. SmallPtrSet<const SDNode *, 32> Visited;
  16464. SmallVector<const SDNode *, 8> Worklist;
  16465. // RootNode is a predecessor to all candidates so we need not search
  16466. // past it. Add RootNode (peeking through TokenFactors). Do not count
  16467. // these towards size check.
  16468. Worklist.push_back(RootNode);
  16469. while (!Worklist.empty()) {
  16470. auto N = Worklist.pop_back_val();
  16471. if (!Visited.insert(N).second)
  16472. continue; // Already present in Visited.
  16473. if (N->getOpcode() == ISD::TokenFactor) {
  16474. for (SDValue Op : N->ops())
  16475. Worklist.push_back(Op.getNode());
  16476. }
  16477. }
  16478. // Don't count pruning nodes towards max.
  16479. unsigned int Max = 1024 + Visited.size();
  16480. // Search Ops of store candidates.
  16481. for (unsigned i = 0; i < NumStores; ++i) {
  16482. SDNode *N = StoreNodes[i].MemNode;
  16483. // Of the 4 Store Operands:
  16484. // * Chain (Op 0) -> We have already considered these
  16485. // in candidate selection, but only by following the
  16486. // chain dependencies. We could still have a chain
  16487. // dependency to a load, that has a non-chain dep to
  16488. // another load, that depends on a store, etc. So it is
  16489. // possible to have dependencies that consist of a mix
  16490. // of chain and non-chain deps, and we need to include
  16491. // chain operands in the analysis here..
  16492. // * Value (Op 1) -> Cycles may happen (e.g. through load chains)
  16493. // * Address (Op 2) -> Merged addresses may only vary by a fixed constant,
  16494. // but aren't necessarily fromt the same base node, so
  16495. // cycles possible (e.g. via indexed store).
  16496. // * (Op 3) -> Represents the pre or post-indexing offset (or undef for
  16497. // non-indexed stores). Not constant on all targets (e.g. ARM)
  16498. // and so can participate in a cycle.
  16499. for (unsigned j = 0; j < N->getNumOperands(); ++j)
  16500. Worklist.push_back(N->getOperand(j).getNode());
  16501. }
  16502. // Search through DAG. We can stop early if we find a store node.
  16503. for (unsigned i = 0; i < NumStores; ++i)
  16504. if (SDNode::hasPredecessorHelper(StoreNodes[i].MemNode, Visited, Worklist,
  16505. Max)) {
  16506. // If the searching bail out, record the StoreNode and RootNode in the
  16507. // StoreRootCountMap. If we have seen the pair many times over a limit,
  16508. // we won't add the StoreNode into StoreNodes set again.
  16509. if (Visited.size() >= Max) {
  16510. auto &RootCount = StoreRootCountMap[StoreNodes[i].MemNode];
  16511. if (RootCount.first == RootNode)
  16512. RootCount.second++;
  16513. else
  16514. RootCount = {RootNode, 1};
  16515. }
  16516. return false;
  16517. }
  16518. return true;
  16519. }
  16520. unsigned
  16521. DAGCombiner::getConsecutiveStores(SmallVectorImpl<MemOpLink> &StoreNodes,
  16522. int64_t ElementSizeBytes) const {
  16523. while (true) {
  16524. // Find a store past the width of the first store.
  16525. size_t StartIdx = 0;
  16526. while ((StartIdx + 1 < StoreNodes.size()) &&
  16527. StoreNodes[StartIdx].OffsetFromBase + ElementSizeBytes !=
  16528. StoreNodes[StartIdx + 1].OffsetFromBase)
  16529. ++StartIdx;
  16530. // Bail if we don't have enough candidates to merge.
  16531. if (StartIdx + 1 >= StoreNodes.size())
  16532. return 0;
  16533. // Trim stores that overlapped with the first store.
  16534. if (StartIdx)
  16535. StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + StartIdx);
  16536. // Scan the memory operations on the chain and find the first
  16537. // non-consecutive store memory address.
  16538. unsigned NumConsecutiveStores = 1;
  16539. int64_t StartAddress = StoreNodes[0].OffsetFromBase;
  16540. // Check that the addresses are consecutive starting from the second
  16541. // element in the list of stores.
  16542. for (unsigned i = 1, e = StoreNodes.size(); i < e; ++i) {
  16543. int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
  16544. if (CurrAddress - StartAddress != (ElementSizeBytes * i))
  16545. break;
  16546. NumConsecutiveStores = i + 1;
  16547. }
  16548. if (NumConsecutiveStores > 1)
  16549. return NumConsecutiveStores;
  16550. // There are no consecutive stores at the start of the list.
  16551. // Remove the first store and try again.
  16552. StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + 1);
  16553. }
  16554. }
  16555. bool DAGCombiner::tryStoreMergeOfConstants(
  16556. SmallVectorImpl<MemOpLink> &StoreNodes, unsigned NumConsecutiveStores,
  16557. EVT MemVT, SDNode *RootNode, bool AllowVectors) {
  16558. LLVMContext &Context = *DAG.getContext();
  16559. const DataLayout &DL = DAG.getDataLayout();
  16560. int64_t ElementSizeBytes = MemVT.getStoreSize();
  16561. unsigned NumMemElts = MemVT.isVector() ? MemVT.getVectorNumElements() : 1;
  16562. bool MadeChange = false;
  16563. // Store the constants into memory as one consecutive store.
  16564. while (NumConsecutiveStores >= 2) {
  16565. LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
  16566. unsigned FirstStoreAS = FirstInChain->getAddressSpace();
  16567. Align FirstStoreAlign = FirstInChain->getAlign();
  16568. unsigned LastLegalType = 1;
  16569. unsigned LastLegalVectorType = 1;
  16570. bool LastIntegerTrunc = false;
  16571. bool NonZero = false;
  16572. unsigned FirstZeroAfterNonZero = NumConsecutiveStores;
  16573. for (unsigned i = 0; i < NumConsecutiveStores; ++i) {
  16574. StoreSDNode *ST = cast<StoreSDNode>(StoreNodes[i].MemNode);
  16575. SDValue StoredVal = ST->getValue();
  16576. bool IsElementZero = false;
  16577. if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal))
  16578. IsElementZero = C->isZero();
  16579. else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal))
  16580. IsElementZero = C->getConstantFPValue()->isNullValue();
  16581. if (IsElementZero) {
  16582. if (NonZero && FirstZeroAfterNonZero == NumConsecutiveStores)
  16583. FirstZeroAfterNonZero = i;
  16584. }
  16585. NonZero |= !IsElementZero;
  16586. // Find a legal type for the constant store.
  16587. unsigned SizeInBits = (i + 1) * ElementSizeBytes * 8;
  16588. EVT StoreTy = EVT::getIntegerVT(Context, SizeInBits);
  16589. unsigned IsFast = 0;
  16590. // Break early when size is too large to be legal.
  16591. if (StoreTy.getSizeInBits() > MaximumLegalStoreInBits)
  16592. break;
  16593. if (TLI.isTypeLegal(StoreTy) &&
  16594. TLI.canMergeStoresTo(FirstStoreAS, StoreTy,
  16595. DAG.getMachineFunction()) &&
  16596. TLI.allowsMemoryAccess(Context, DL, StoreTy,
  16597. *FirstInChain->getMemOperand(), &IsFast) &&
  16598. IsFast) {
  16599. LastIntegerTrunc = false;
  16600. LastLegalType = i + 1;
  16601. // Or check whether a truncstore is legal.
  16602. } else if (TLI.getTypeAction(Context, StoreTy) ==
  16603. TargetLowering::TypePromoteInteger) {
  16604. EVT LegalizedStoredValTy =
  16605. TLI.getTypeToTransformTo(Context, StoredVal.getValueType());
  16606. if (TLI.isTruncStoreLegal(LegalizedStoredValTy, StoreTy) &&
  16607. TLI.canMergeStoresTo(FirstStoreAS, LegalizedStoredValTy,
  16608. DAG.getMachineFunction()) &&
  16609. TLI.allowsMemoryAccess(Context, DL, StoreTy,
  16610. *FirstInChain->getMemOperand(), &IsFast) &&
  16611. IsFast) {
  16612. LastIntegerTrunc = true;
  16613. LastLegalType = i + 1;
  16614. }
  16615. }
  16616. // We only use vectors if the constant is known to be zero or the
  16617. // target allows it and the function is not marked with the
  16618. // noimplicitfloat attribute.
  16619. if ((!NonZero ||
  16620. TLI.storeOfVectorConstantIsCheap(MemVT, i + 1, FirstStoreAS)) &&
  16621. AllowVectors) {
  16622. // Find a legal type for the vector store.
  16623. unsigned Elts = (i + 1) * NumMemElts;
  16624. EVT Ty = EVT::getVectorVT(Context, MemVT.getScalarType(), Elts);
  16625. if (TLI.isTypeLegal(Ty) && TLI.isTypeLegal(MemVT) &&
  16626. TLI.canMergeStoresTo(FirstStoreAS, Ty, DAG.getMachineFunction()) &&
  16627. TLI.allowsMemoryAccess(Context, DL, Ty,
  16628. *FirstInChain->getMemOperand(), &IsFast) &&
  16629. IsFast)
  16630. LastLegalVectorType = i + 1;
  16631. }
  16632. }
  16633. bool UseVector = (LastLegalVectorType > LastLegalType) && AllowVectors;
  16634. unsigned NumElem = (UseVector) ? LastLegalVectorType : LastLegalType;
  16635. bool UseTrunc = LastIntegerTrunc && !UseVector;
  16636. // Check if we found a legal integer type that creates a meaningful
  16637. // merge.
  16638. if (NumElem < 2) {
  16639. // We know that candidate stores are in order and of correct
  16640. // shape. While there is no mergeable sequence from the
  16641. // beginning one may start later in the sequence. The only
  16642. // reason a merge of size N could have failed where another of
  16643. // the same size would not have, is if the alignment has
  16644. // improved or we've dropped a non-zero value. Drop as many
  16645. // candidates as we can here.
  16646. unsigned NumSkip = 1;
  16647. while ((NumSkip < NumConsecutiveStores) &&
  16648. (NumSkip < FirstZeroAfterNonZero) &&
  16649. (StoreNodes[NumSkip].MemNode->getAlign() <= FirstStoreAlign))
  16650. NumSkip++;
  16651. StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumSkip);
  16652. NumConsecutiveStores -= NumSkip;
  16653. continue;
  16654. }
  16655. // Check that we can merge these candidates without causing a cycle.
  16656. if (!checkMergeStoreCandidatesForDependencies(StoreNodes, NumElem,
  16657. RootNode)) {
  16658. StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumElem);
  16659. NumConsecutiveStores -= NumElem;
  16660. continue;
  16661. }
  16662. MadeChange |= mergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
  16663. /*IsConstantSrc*/ true,
  16664. UseVector, UseTrunc);
  16665. // Remove merged stores for next iteration.
  16666. StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumElem);
  16667. NumConsecutiveStores -= NumElem;
  16668. }
  16669. return MadeChange;
  16670. }
  16671. bool DAGCombiner::tryStoreMergeOfExtracts(
  16672. SmallVectorImpl<MemOpLink> &StoreNodes, unsigned NumConsecutiveStores,
  16673. EVT MemVT, SDNode *RootNode) {
  16674. LLVMContext &Context = *DAG.getContext();
  16675. const DataLayout &DL = DAG.getDataLayout();
  16676. unsigned NumMemElts = MemVT.isVector() ? MemVT.getVectorNumElements() : 1;
  16677. bool MadeChange = false;
  16678. // Loop on Consecutive Stores on success.
  16679. while (NumConsecutiveStores >= 2) {
  16680. LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
  16681. unsigned FirstStoreAS = FirstInChain->getAddressSpace();
  16682. Align FirstStoreAlign = FirstInChain->getAlign();
  16683. unsigned NumStoresToMerge = 1;
  16684. for (unsigned i = 0; i < NumConsecutiveStores; ++i) {
  16685. // Find a legal type for the vector store.
  16686. unsigned Elts = (i + 1) * NumMemElts;
  16687. EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts);
  16688. unsigned IsFast = 0;
  16689. // Break early when size is too large to be legal.
  16690. if (Ty.getSizeInBits() > MaximumLegalStoreInBits)
  16691. break;
  16692. if (TLI.isTypeLegal(Ty) &&
  16693. TLI.canMergeStoresTo(FirstStoreAS, Ty, DAG.getMachineFunction()) &&
  16694. TLI.allowsMemoryAccess(Context, DL, Ty,
  16695. *FirstInChain->getMemOperand(), &IsFast) &&
  16696. IsFast)
  16697. NumStoresToMerge = i + 1;
  16698. }
  16699. // Check if we found a legal integer type creating a meaningful
  16700. // merge.
  16701. if (NumStoresToMerge < 2) {
  16702. // We know that candidate stores are in order and of correct
  16703. // shape. While there is no mergeable sequence from the
  16704. // beginning one may start later in the sequence. The only
  16705. // reason a merge of size N could have failed where another of
  16706. // the same size would not have, is if the alignment has
  16707. // improved. Drop as many candidates as we can here.
  16708. unsigned NumSkip = 1;
  16709. while ((NumSkip < NumConsecutiveStores) &&
  16710. (StoreNodes[NumSkip].MemNode->getAlign() <= FirstStoreAlign))
  16711. NumSkip++;
  16712. StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumSkip);
  16713. NumConsecutiveStores -= NumSkip;
  16714. continue;
  16715. }
  16716. // Check that we can merge these candidates without causing a cycle.
  16717. if (!checkMergeStoreCandidatesForDependencies(StoreNodes, NumStoresToMerge,
  16718. RootNode)) {
  16719. StoreNodes.erase(StoreNodes.begin(),
  16720. StoreNodes.begin() + NumStoresToMerge);
  16721. NumConsecutiveStores -= NumStoresToMerge;
  16722. continue;
  16723. }
  16724. MadeChange |= mergeStoresOfConstantsOrVecElts(
  16725. StoreNodes, MemVT, NumStoresToMerge, /*IsConstantSrc*/ false,
  16726. /*UseVector*/ true, /*UseTrunc*/ false);
  16727. StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumStoresToMerge);
  16728. NumConsecutiveStores -= NumStoresToMerge;
  16729. }
  16730. return MadeChange;
  16731. }
  16732. bool DAGCombiner::tryStoreMergeOfLoads(SmallVectorImpl<MemOpLink> &StoreNodes,
  16733. unsigned NumConsecutiveStores, EVT MemVT,
  16734. SDNode *RootNode, bool AllowVectors,
  16735. bool IsNonTemporalStore,
  16736. bool IsNonTemporalLoad) {
  16737. LLVMContext &Context = *DAG.getContext();
  16738. const DataLayout &DL = DAG.getDataLayout();
  16739. int64_t ElementSizeBytes = MemVT.getStoreSize();
  16740. unsigned NumMemElts = MemVT.isVector() ? MemVT.getVectorNumElements() : 1;
  16741. bool MadeChange = false;
  16742. // Look for load nodes which are used by the stored values.
  16743. SmallVector<MemOpLink, 8> LoadNodes;
  16744. // Find acceptable loads. Loads need to have the same chain (token factor),
  16745. // must not be zext, volatile, indexed, and they must be consecutive.
  16746. BaseIndexOffset LdBasePtr;
  16747. for (unsigned i = 0; i < NumConsecutiveStores; ++i) {
  16748. StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
  16749. SDValue Val = peekThroughBitcasts(St->getValue());
  16750. LoadSDNode *Ld = cast<LoadSDNode>(Val);
  16751. BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld, DAG);
  16752. // If this is not the first ptr that we check.
  16753. int64_t LdOffset = 0;
  16754. if (LdBasePtr.getBase().getNode()) {
  16755. // The base ptr must be the same.
  16756. if (!LdBasePtr.equalBaseIndex(LdPtr, DAG, LdOffset))
  16757. break;
  16758. } else {
  16759. // Check that all other base pointers are the same as this one.
  16760. LdBasePtr = LdPtr;
  16761. }
  16762. // We found a potential memory operand to merge.
  16763. LoadNodes.push_back(MemOpLink(Ld, LdOffset));
  16764. }
  16765. while (NumConsecutiveStores >= 2 && LoadNodes.size() >= 2) {
  16766. Align RequiredAlignment;
  16767. bool NeedRotate = false;
  16768. if (LoadNodes.size() == 2) {
  16769. // If we have load/store pair instructions and we only have two values,
  16770. // don't bother merging.
  16771. if (TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
  16772. StoreNodes[0].MemNode->getAlign() >= RequiredAlignment) {
  16773. StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + 2);
  16774. LoadNodes.erase(LoadNodes.begin(), LoadNodes.begin() + 2);
  16775. break;
  16776. }
  16777. // If the loads are reversed, see if we can rotate the halves into place.
  16778. int64_t Offset0 = LoadNodes[0].OffsetFromBase;
  16779. int64_t Offset1 = LoadNodes[1].OffsetFromBase;
  16780. EVT PairVT = EVT::getIntegerVT(Context, ElementSizeBytes * 8 * 2);
  16781. if (Offset0 - Offset1 == ElementSizeBytes &&
  16782. (hasOperation(ISD::ROTL, PairVT) ||
  16783. hasOperation(ISD::ROTR, PairVT))) {
  16784. std::swap(LoadNodes[0], LoadNodes[1]);
  16785. NeedRotate = true;
  16786. }
  16787. }
  16788. LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
  16789. unsigned FirstStoreAS = FirstInChain->getAddressSpace();
  16790. Align FirstStoreAlign = FirstInChain->getAlign();
  16791. LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
  16792. // Scan the memory operations on the chain and find the first
  16793. // non-consecutive load memory address. These variables hold the index in
  16794. // the store node array.
  16795. unsigned LastConsecutiveLoad = 1;
  16796. // This variable refers to the size and not index in the array.
  16797. unsigned LastLegalVectorType = 1;
  16798. unsigned LastLegalIntegerType = 1;
  16799. bool isDereferenceable = true;
  16800. bool DoIntegerTruncate = false;
  16801. int64_t StartAddress = LoadNodes[0].OffsetFromBase;
  16802. SDValue LoadChain = FirstLoad->getChain();
  16803. for (unsigned i = 1; i < LoadNodes.size(); ++i) {
  16804. // All loads must share the same chain.
  16805. if (LoadNodes[i].MemNode->getChain() != LoadChain)
  16806. break;
  16807. int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
  16808. if (CurrAddress - StartAddress != (ElementSizeBytes * i))
  16809. break;
  16810. LastConsecutiveLoad = i;
  16811. if (isDereferenceable && !LoadNodes[i].MemNode->isDereferenceable())
  16812. isDereferenceable = false;
  16813. // Find a legal type for the vector store.
  16814. unsigned Elts = (i + 1) * NumMemElts;
  16815. EVT StoreTy = EVT::getVectorVT(Context, MemVT.getScalarType(), Elts);
  16816. // Break early when size is too large to be legal.
  16817. if (StoreTy.getSizeInBits() > MaximumLegalStoreInBits)
  16818. break;
  16819. unsigned IsFastSt = 0;
  16820. unsigned IsFastLd = 0;
  16821. // Don't try vector types if we need a rotate. We may still fail the
  16822. // legality checks for the integer type, but we can't handle the rotate
  16823. // case with vectors.
  16824. // FIXME: We could use a shuffle in place of the rotate.
  16825. if (!NeedRotate && TLI.isTypeLegal(StoreTy) &&
  16826. TLI.canMergeStoresTo(FirstStoreAS, StoreTy,
  16827. DAG.getMachineFunction()) &&
  16828. TLI.allowsMemoryAccess(Context, DL, StoreTy,
  16829. *FirstInChain->getMemOperand(), &IsFastSt) &&
  16830. IsFastSt &&
  16831. TLI.allowsMemoryAccess(Context, DL, StoreTy,
  16832. *FirstLoad->getMemOperand(), &IsFastLd) &&
  16833. IsFastLd) {
  16834. LastLegalVectorType = i + 1;
  16835. }
  16836. // Find a legal type for the integer store.
  16837. unsigned SizeInBits = (i + 1) * ElementSizeBytes * 8;
  16838. StoreTy = EVT::getIntegerVT(Context, SizeInBits);
  16839. if (TLI.isTypeLegal(StoreTy) &&
  16840. TLI.canMergeStoresTo(FirstStoreAS, StoreTy,
  16841. DAG.getMachineFunction()) &&
  16842. TLI.allowsMemoryAccess(Context, DL, StoreTy,
  16843. *FirstInChain->getMemOperand(), &IsFastSt) &&
  16844. IsFastSt &&
  16845. TLI.allowsMemoryAccess(Context, DL, StoreTy,
  16846. *FirstLoad->getMemOperand(), &IsFastLd) &&
  16847. IsFastLd) {
  16848. LastLegalIntegerType = i + 1;
  16849. DoIntegerTruncate = false;
  16850. // Or check whether a truncstore and extload is legal.
  16851. } else if (TLI.getTypeAction(Context, StoreTy) ==
  16852. TargetLowering::TypePromoteInteger) {
  16853. EVT LegalizedStoredValTy = TLI.getTypeToTransformTo(Context, StoreTy);
  16854. if (TLI.isTruncStoreLegal(LegalizedStoredValTy, StoreTy) &&
  16855. TLI.canMergeStoresTo(FirstStoreAS, LegalizedStoredValTy,
  16856. DAG.getMachineFunction()) &&
  16857. TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValTy, StoreTy) &&
  16858. TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValTy, StoreTy) &&
  16859. TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValTy, StoreTy) &&
  16860. TLI.allowsMemoryAccess(Context, DL, StoreTy,
  16861. *FirstInChain->getMemOperand(), &IsFastSt) &&
  16862. IsFastSt &&
  16863. TLI.allowsMemoryAccess(Context, DL, StoreTy,
  16864. *FirstLoad->getMemOperand(), &IsFastLd) &&
  16865. IsFastLd) {
  16866. LastLegalIntegerType = i + 1;
  16867. DoIntegerTruncate = true;
  16868. }
  16869. }
  16870. }
  16871. // Only use vector types if the vector type is larger than the integer
  16872. // type. If they are the same, use integers.
  16873. bool UseVectorTy =
  16874. LastLegalVectorType > LastLegalIntegerType && AllowVectors;
  16875. unsigned LastLegalType =
  16876. std::max(LastLegalVectorType, LastLegalIntegerType);
  16877. // We add +1 here because the LastXXX variables refer to location while
  16878. // the NumElem refers to array/index size.
  16879. unsigned NumElem = std::min(NumConsecutiveStores, LastConsecutiveLoad + 1);
  16880. NumElem = std::min(LastLegalType, NumElem);
  16881. Align FirstLoadAlign = FirstLoad->getAlign();
  16882. if (NumElem < 2) {
  16883. // We know that candidate stores are in order and of correct
  16884. // shape. While there is no mergeable sequence from the
  16885. // beginning one may start later in the sequence. The only
  16886. // reason a merge of size N could have failed where another of
  16887. // the same size would not have is if the alignment or either
  16888. // the load or store has improved. Drop as many candidates as we
  16889. // can here.
  16890. unsigned NumSkip = 1;
  16891. while ((NumSkip < LoadNodes.size()) &&
  16892. (LoadNodes[NumSkip].MemNode->getAlign() <= FirstLoadAlign) &&
  16893. (StoreNodes[NumSkip].MemNode->getAlign() <= FirstStoreAlign))
  16894. NumSkip++;
  16895. StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumSkip);
  16896. LoadNodes.erase(LoadNodes.begin(), LoadNodes.begin() + NumSkip);
  16897. NumConsecutiveStores -= NumSkip;
  16898. continue;
  16899. }
  16900. // Check that we can merge these candidates without causing a cycle.
  16901. if (!checkMergeStoreCandidatesForDependencies(StoreNodes, NumElem,
  16902. RootNode)) {
  16903. StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumElem);
  16904. LoadNodes.erase(LoadNodes.begin(), LoadNodes.begin() + NumElem);
  16905. NumConsecutiveStores -= NumElem;
  16906. continue;
  16907. }
  16908. // Find if it is better to use vectors or integers to load and store
  16909. // to memory.
  16910. EVT JointMemOpVT;
  16911. if (UseVectorTy) {
  16912. // Find a legal type for the vector store.
  16913. unsigned Elts = NumElem * NumMemElts;
  16914. JointMemOpVT = EVT::getVectorVT(Context, MemVT.getScalarType(), Elts);
  16915. } else {
  16916. unsigned SizeInBits = NumElem * ElementSizeBytes * 8;
  16917. JointMemOpVT = EVT::getIntegerVT(Context, SizeInBits);
  16918. }
  16919. SDLoc LoadDL(LoadNodes[0].MemNode);
  16920. SDLoc StoreDL(StoreNodes[0].MemNode);
  16921. // The merged loads are required to have the same incoming chain, so
  16922. // using the first's chain is acceptable.
  16923. SDValue NewStoreChain = getMergeStoreChains(StoreNodes, NumElem);
  16924. AddToWorklist(NewStoreChain.getNode());
  16925. MachineMemOperand::Flags LdMMOFlags =
  16926. isDereferenceable ? MachineMemOperand::MODereferenceable
  16927. : MachineMemOperand::MONone;
  16928. if (IsNonTemporalLoad)
  16929. LdMMOFlags |= MachineMemOperand::MONonTemporal;
  16930. MachineMemOperand::Flags StMMOFlags = IsNonTemporalStore
  16931. ? MachineMemOperand::MONonTemporal
  16932. : MachineMemOperand::MONone;
  16933. SDValue NewLoad, NewStore;
  16934. if (UseVectorTy || !DoIntegerTruncate) {
  16935. NewLoad = DAG.getLoad(
  16936. JointMemOpVT, LoadDL, FirstLoad->getChain(), FirstLoad->getBasePtr(),
  16937. FirstLoad->getPointerInfo(), FirstLoadAlign, LdMMOFlags);
  16938. SDValue StoreOp = NewLoad;
  16939. if (NeedRotate) {
  16940. unsigned LoadWidth = ElementSizeBytes * 8 * 2;
  16941. assert(JointMemOpVT == EVT::getIntegerVT(Context, LoadWidth) &&
  16942. "Unexpected type for rotate-able load pair");
  16943. SDValue RotAmt =
  16944. DAG.getShiftAmountConstant(LoadWidth / 2, JointMemOpVT, LoadDL);
  16945. // Target can convert to the identical ROTR if it does not have ROTL.
  16946. StoreOp = DAG.getNode(ISD::ROTL, LoadDL, JointMemOpVT, NewLoad, RotAmt);
  16947. }
  16948. NewStore = DAG.getStore(
  16949. NewStoreChain, StoreDL, StoreOp, FirstInChain->getBasePtr(),
  16950. FirstInChain->getPointerInfo(), FirstStoreAlign, StMMOFlags);
  16951. } else { // This must be the truncstore/extload case
  16952. EVT ExtendedTy =
  16953. TLI.getTypeToTransformTo(*DAG.getContext(), JointMemOpVT);
  16954. NewLoad = DAG.getExtLoad(ISD::EXTLOAD, LoadDL, ExtendedTy,
  16955. FirstLoad->getChain(), FirstLoad->getBasePtr(),
  16956. FirstLoad->getPointerInfo(), JointMemOpVT,
  16957. FirstLoadAlign, LdMMOFlags);
  16958. NewStore = DAG.getTruncStore(
  16959. NewStoreChain, StoreDL, NewLoad, FirstInChain->getBasePtr(),
  16960. FirstInChain->getPointerInfo(), JointMemOpVT,
  16961. FirstInChain->getAlign(), FirstInChain->getMemOperand()->getFlags());
  16962. }
  16963. // Transfer chain users from old loads to the new load.
  16964. for (unsigned i = 0; i < NumElem; ++i) {
  16965. LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
  16966. DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
  16967. SDValue(NewLoad.getNode(), 1));
  16968. }
  16969. // Replace all stores with the new store. Recursively remove corresponding
  16970. // values if they are no longer used.
  16971. for (unsigned i = 0; i < NumElem; ++i) {
  16972. SDValue Val = StoreNodes[i].MemNode->getOperand(1);
  16973. CombineTo(StoreNodes[i].MemNode, NewStore);
  16974. if (Val->use_empty())
  16975. recursivelyDeleteUnusedNodes(Val.getNode());
  16976. }
  16977. MadeChange = true;
  16978. StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumElem);
  16979. LoadNodes.erase(LoadNodes.begin(), LoadNodes.begin() + NumElem);
  16980. NumConsecutiveStores -= NumElem;
  16981. }
  16982. return MadeChange;
  16983. }
  16984. bool DAGCombiner::mergeConsecutiveStores(StoreSDNode *St) {
  16985. if (OptLevel == CodeGenOpt::None || !EnableStoreMerging)
  16986. return false;
  16987. // TODO: Extend this function to merge stores of scalable vectors.
  16988. // (i.e. two <vscale x 8 x i8> stores can be merged to one <vscale x 16 x i8>
  16989. // store since we know <vscale x 16 x i8> is exactly twice as large as
  16990. // <vscale x 8 x i8>). Until then, bail out for scalable vectors.
  16991. EVT MemVT = St->getMemoryVT();
  16992. if (MemVT.isScalableVector())
  16993. return false;
  16994. if (!MemVT.isSimple() || MemVT.getSizeInBits() * 2 > MaximumLegalStoreInBits)
  16995. return false;
  16996. // This function cannot currently deal with non-byte-sized memory sizes.
  16997. int64_t ElementSizeBytes = MemVT.getStoreSize();
  16998. if (ElementSizeBytes * 8 != (int64_t)MemVT.getSizeInBits())
  16999. return false;
  17000. // Do not bother looking at stored values that are not constants, loads, or
  17001. // extracted vector elements.
  17002. SDValue StoredVal = peekThroughBitcasts(St->getValue());
  17003. const StoreSource StoreSrc = getStoreSource(StoredVal);
  17004. if (StoreSrc == StoreSource::Unknown)
  17005. return false;
  17006. SmallVector<MemOpLink, 8> StoreNodes;
  17007. SDNode *RootNode;
  17008. // Find potential store merge candidates by searching through chain sub-DAG
  17009. getStoreMergeCandidates(St, StoreNodes, RootNode);
  17010. // Check if there is anything to merge.
  17011. if (StoreNodes.size() < 2)
  17012. return false;
  17013. // Sort the memory operands according to their distance from the
  17014. // base pointer.
  17015. llvm::sort(StoreNodes, [](MemOpLink LHS, MemOpLink RHS) {
  17016. return LHS.OffsetFromBase < RHS.OffsetFromBase;
  17017. });
  17018. bool AllowVectors = !DAG.getMachineFunction().getFunction().hasFnAttribute(
  17019. Attribute::NoImplicitFloat);
  17020. bool IsNonTemporalStore = St->isNonTemporal();
  17021. bool IsNonTemporalLoad = StoreSrc == StoreSource::Load &&
  17022. cast<LoadSDNode>(StoredVal)->isNonTemporal();
  17023. // Store Merge attempts to merge the lowest stores. This generally
  17024. // works out as if successful, as the remaining stores are checked
  17025. // after the first collection of stores is merged. However, in the
  17026. // case that a non-mergeable store is found first, e.g., {p[-2],
  17027. // p[0], p[1], p[2], p[3]}, we would fail and miss the subsequent
  17028. // mergeable cases. To prevent this, we prune such stores from the
  17029. // front of StoreNodes here.
  17030. bool MadeChange = false;
  17031. while (StoreNodes.size() > 1) {
  17032. unsigned NumConsecutiveStores =
  17033. getConsecutiveStores(StoreNodes, ElementSizeBytes);
  17034. // There are no more stores in the list to examine.
  17035. if (NumConsecutiveStores == 0)
  17036. return MadeChange;
  17037. // We have at least 2 consecutive stores. Try to merge them.
  17038. assert(NumConsecutiveStores >= 2 && "Expected at least 2 stores");
  17039. switch (StoreSrc) {
  17040. case StoreSource::Constant:
  17041. MadeChange |= tryStoreMergeOfConstants(StoreNodes, NumConsecutiveStores,
  17042. MemVT, RootNode, AllowVectors);
  17043. break;
  17044. case StoreSource::Extract:
  17045. MadeChange |= tryStoreMergeOfExtracts(StoreNodes, NumConsecutiveStores,
  17046. MemVT, RootNode);
  17047. break;
  17048. case StoreSource::Load:
  17049. MadeChange |= tryStoreMergeOfLoads(StoreNodes, NumConsecutiveStores,
  17050. MemVT, RootNode, AllowVectors,
  17051. IsNonTemporalStore, IsNonTemporalLoad);
  17052. break;
  17053. default:
  17054. llvm_unreachable("Unhandled store source type");
  17055. }
  17056. }
  17057. return MadeChange;
  17058. }
  17059. SDValue DAGCombiner::replaceStoreChain(StoreSDNode *ST, SDValue BetterChain) {
  17060. SDLoc SL(ST);
  17061. SDValue ReplStore;
  17062. // Replace the chain to avoid dependency.
  17063. if (ST->isTruncatingStore()) {
  17064. ReplStore = DAG.getTruncStore(BetterChain, SL, ST->getValue(),
  17065. ST->getBasePtr(), ST->getMemoryVT(),
  17066. ST->getMemOperand());
  17067. } else {
  17068. ReplStore = DAG.getStore(BetterChain, SL, ST->getValue(), ST->getBasePtr(),
  17069. ST->getMemOperand());
  17070. }
  17071. // Create token to keep both nodes around.
  17072. SDValue Token = DAG.getNode(ISD::TokenFactor, SL,
  17073. MVT::Other, ST->getChain(), ReplStore);
  17074. // Make sure the new and old chains are cleaned up.
  17075. AddToWorklist(Token.getNode());
  17076. // Don't add users to work list.
  17077. return CombineTo(ST, Token, false);
  17078. }
  17079. SDValue DAGCombiner::replaceStoreOfFPConstant(StoreSDNode *ST) {
  17080. SDValue Value = ST->getValue();
  17081. if (Value.getOpcode() == ISD::TargetConstantFP)
  17082. return SDValue();
  17083. if (!ISD::isNormalStore(ST))
  17084. return SDValue();
  17085. SDLoc DL(ST);
  17086. SDValue Chain = ST->getChain();
  17087. SDValue Ptr = ST->getBasePtr();
  17088. const ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Value);
  17089. // NOTE: If the original store is volatile, this transform must not increase
  17090. // the number of stores. For example, on x86-32 an f64 can be stored in one
  17091. // processor operation but an i64 (which is not legal) requires two. So the
  17092. // transform should not be done in this case.
  17093. SDValue Tmp;
  17094. switch (CFP->getSimpleValueType(0).SimpleTy) {
  17095. default:
  17096. llvm_unreachable("Unknown FP type");
  17097. case MVT::f16: // We don't do this for these yet.
  17098. case MVT::bf16:
  17099. case MVT::f80:
  17100. case MVT::f128:
  17101. case MVT::ppcf128:
  17102. return SDValue();
  17103. case MVT::f32:
  17104. if ((isTypeLegal(MVT::i32) && !LegalOperations && ST->isSimple()) ||
  17105. TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
  17106. Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
  17107. bitcastToAPInt().getZExtValue(), SDLoc(CFP),
  17108. MVT::i32);
  17109. return DAG.getStore(Chain, DL, Tmp, Ptr, ST->getMemOperand());
  17110. }
  17111. return SDValue();
  17112. case MVT::f64:
  17113. if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
  17114. ST->isSimple()) ||
  17115. TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
  17116. Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
  17117. getZExtValue(), SDLoc(CFP), MVT::i64);
  17118. return DAG.getStore(Chain, DL, Tmp,
  17119. Ptr, ST->getMemOperand());
  17120. }
  17121. if (ST->isSimple() &&
  17122. TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
  17123. // Many FP stores are not made apparent until after legalize, e.g. for
  17124. // argument passing. Since this is so common, custom legalize the
  17125. // 64-bit integer store into two 32-bit stores.
  17126. uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
  17127. SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, SDLoc(CFP), MVT::i32);
  17128. SDValue Hi = DAG.getConstant(Val >> 32, SDLoc(CFP), MVT::i32);
  17129. if (DAG.getDataLayout().isBigEndian())
  17130. std::swap(Lo, Hi);
  17131. MachineMemOperand::Flags MMOFlags = ST->getMemOperand()->getFlags();
  17132. AAMDNodes AAInfo = ST->getAAInfo();
  17133. SDValue St0 = DAG.getStore(Chain, DL, Lo, Ptr, ST->getPointerInfo(),
  17134. ST->getOriginalAlign(), MMOFlags, AAInfo);
  17135. Ptr = DAG.getMemBasePlusOffset(Ptr, TypeSize::Fixed(4), DL);
  17136. SDValue St1 = DAG.getStore(Chain, DL, Hi, Ptr,
  17137. ST->getPointerInfo().getWithOffset(4),
  17138. ST->getOriginalAlign(), MMOFlags, AAInfo);
  17139. return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
  17140. St0, St1);
  17141. }
  17142. return SDValue();
  17143. }
  17144. }
  17145. SDValue DAGCombiner::visitSTORE(SDNode *N) {
  17146. StoreSDNode *ST = cast<StoreSDNode>(N);
  17147. SDValue Chain = ST->getChain();
  17148. SDValue Value = ST->getValue();
  17149. SDValue Ptr = ST->getBasePtr();
  17150. // If this is a store of a bit convert, store the input value if the
  17151. // resultant store does not need a higher alignment than the original.
  17152. if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
  17153. ST->isUnindexed()) {
  17154. EVT SVT = Value.getOperand(0).getValueType();
  17155. // If the store is volatile, we only want to change the store type if the
  17156. // resulting store is legal. Otherwise we might increase the number of
  17157. // memory accesses. We don't care if the original type was legal or not
  17158. // as we assume software couldn't rely on the number of accesses of an
  17159. // illegal type.
  17160. // TODO: May be able to relax for unordered atomics (see D66309)
  17161. if (((!LegalOperations && ST->isSimple()) ||
  17162. TLI.isOperationLegal(ISD::STORE, SVT)) &&
  17163. TLI.isStoreBitCastBeneficial(Value.getValueType(), SVT,
  17164. DAG, *ST->getMemOperand())) {
  17165. return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0), Ptr,
  17166. ST->getMemOperand());
  17167. }
  17168. }
  17169. // Turn 'store undef, Ptr' -> nothing.
  17170. if (Value.isUndef() && ST->isUnindexed())
  17171. return Chain;
  17172. // Try to infer better alignment information than the store already has.
  17173. if (OptLevel != CodeGenOpt::None && ST->isUnindexed() && !ST->isAtomic()) {
  17174. if (MaybeAlign Alignment = DAG.InferPtrAlign(Ptr)) {
  17175. if (*Alignment > ST->getAlign() &&
  17176. isAligned(*Alignment, ST->getSrcValueOffset())) {
  17177. SDValue NewStore =
  17178. DAG.getTruncStore(Chain, SDLoc(N), Value, Ptr, ST->getPointerInfo(),
  17179. ST->getMemoryVT(), *Alignment,
  17180. ST->getMemOperand()->getFlags(), ST->getAAInfo());
  17181. // NewStore will always be N as we are only refining the alignment
  17182. assert(NewStore.getNode() == N);
  17183. (void)NewStore;
  17184. }
  17185. }
  17186. }
  17187. // Try transforming a pair floating point load / store ops to integer
  17188. // load / store ops.
  17189. if (SDValue NewST = TransformFPLoadStorePair(N))
  17190. return NewST;
  17191. // Try transforming several stores into STORE (BSWAP).
  17192. if (SDValue Store = mergeTruncStores(ST))
  17193. return Store;
  17194. if (ST->isUnindexed()) {
  17195. // Walk up chain skipping non-aliasing memory nodes, on this store and any
  17196. // adjacent stores.
  17197. if (findBetterNeighborChains(ST)) {
  17198. // replaceStoreChain uses CombineTo, which handled all of the worklist
  17199. // manipulation. Return the original node to not do anything else.
  17200. return SDValue(ST, 0);
  17201. }
  17202. Chain = ST->getChain();
  17203. }
  17204. // FIXME: is there such a thing as a truncating indexed store?
  17205. if (ST->isTruncatingStore() && ST->isUnindexed() &&
  17206. Value.getValueType().isInteger() &&
  17207. (!isa<ConstantSDNode>(Value) ||
  17208. !cast<ConstantSDNode>(Value)->isOpaque())) {
  17209. // Convert a truncating store of a extension into a standard store.
  17210. if ((Value.getOpcode() == ISD::ZERO_EXTEND ||
  17211. Value.getOpcode() == ISD::SIGN_EXTEND ||
  17212. Value.getOpcode() == ISD::ANY_EXTEND) &&
  17213. Value.getOperand(0).getValueType() == ST->getMemoryVT() &&
  17214. TLI.isOperationLegalOrCustom(ISD::STORE, ST->getMemoryVT()))
  17215. return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0), Ptr,
  17216. ST->getMemOperand());
  17217. APInt TruncDemandedBits =
  17218. APInt::getLowBitsSet(Value.getScalarValueSizeInBits(),
  17219. ST->getMemoryVT().getScalarSizeInBits());
  17220. // See if we can simplify the operation with SimplifyDemandedBits, which
  17221. // only works if the value has a single use.
  17222. AddToWorklist(Value.getNode());
  17223. if (SimplifyDemandedBits(Value, TruncDemandedBits)) {
  17224. // Re-visit the store if anything changed and the store hasn't been merged
  17225. // with another node (N is deleted) SimplifyDemandedBits will add Value's
  17226. // node back to the worklist if necessary, but we also need to re-visit
  17227. // the Store node itself.
  17228. if (N->getOpcode() != ISD::DELETED_NODE)
  17229. AddToWorklist(N);
  17230. return SDValue(N, 0);
  17231. }
  17232. // Otherwise, see if we can simplify the input to this truncstore with
  17233. // knowledge that only the low bits are being used. For example:
  17234. // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8"
  17235. if (SDValue Shorter =
  17236. TLI.SimplifyMultipleUseDemandedBits(Value, TruncDemandedBits, DAG))
  17237. return DAG.getTruncStore(Chain, SDLoc(N), Shorter, Ptr, ST->getMemoryVT(),
  17238. ST->getMemOperand());
  17239. // If we're storing a truncated constant, see if we can simplify it.
  17240. // TODO: Move this to targetShrinkDemandedConstant?
  17241. if (auto *Cst = dyn_cast<ConstantSDNode>(Value))
  17242. if (!Cst->isOpaque()) {
  17243. const APInt &CValue = Cst->getAPIntValue();
  17244. APInt NewVal = CValue & TruncDemandedBits;
  17245. if (NewVal != CValue) {
  17246. SDValue Shorter =
  17247. DAG.getConstant(NewVal, SDLoc(N), Value.getValueType());
  17248. return DAG.getTruncStore(Chain, SDLoc(N), Shorter, Ptr,
  17249. ST->getMemoryVT(), ST->getMemOperand());
  17250. }
  17251. }
  17252. }
  17253. // If this is a load followed by a store to the same location, then the store
  17254. // is dead/noop.
  17255. // TODO: Can relax for unordered atomics (see D66309)
  17256. if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
  17257. if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
  17258. ST->isUnindexed() && ST->isSimple() &&
  17259. Ld->getAddressSpace() == ST->getAddressSpace() &&
  17260. // There can't be any side effects between the load and store, such as
  17261. // a call or store.
  17262. Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
  17263. // The store is dead, remove it.
  17264. return Chain;
  17265. }
  17266. }
  17267. // TODO: Can relax for unordered atomics (see D66309)
  17268. if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) {
  17269. if (ST->isUnindexed() && ST->isSimple() &&
  17270. ST1->isUnindexed() && ST1->isSimple()) {
  17271. if (OptLevel != CodeGenOpt::None && ST1->getBasePtr() == Ptr &&
  17272. ST1->getValue() == Value && ST->getMemoryVT() == ST1->getMemoryVT() &&
  17273. ST->getAddressSpace() == ST1->getAddressSpace()) {
  17274. // If this is a store followed by a store with the same value to the
  17275. // same location, then the store is dead/noop.
  17276. return Chain;
  17277. }
  17278. if (OptLevel != CodeGenOpt::None && ST1->hasOneUse() &&
  17279. !ST1->getBasePtr().isUndef() &&
  17280. // BaseIndexOffset and the code below requires knowing the size
  17281. // of a vector, so bail out if MemoryVT is scalable.
  17282. !ST->getMemoryVT().isScalableVector() &&
  17283. !ST1->getMemoryVT().isScalableVector() &&
  17284. ST->getAddressSpace() == ST1->getAddressSpace()) {
  17285. const BaseIndexOffset STBase = BaseIndexOffset::match(ST, DAG);
  17286. const BaseIndexOffset ChainBase = BaseIndexOffset::match(ST1, DAG);
  17287. unsigned STBitSize = ST->getMemoryVT().getFixedSizeInBits();
  17288. unsigned ChainBitSize = ST1->getMemoryVT().getFixedSizeInBits();
  17289. // If this is a store who's preceding store to a subset of the current
  17290. // location and no one other node is chained to that store we can
  17291. // effectively drop the store. Do not remove stores to undef as they may
  17292. // be used as data sinks.
  17293. if (STBase.contains(DAG, STBitSize, ChainBase, ChainBitSize)) {
  17294. CombineTo(ST1, ST1->getChain());
  17295. return SDValue();
  17296. }
  17297. }
  17298. }
  17299. }
  17300. // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
  17301. // truncating store. We can do this even if this is already a truncstore.
  17302. if ((Value.getOpcode() == ISD::FP_ROUND ||
  17303. Value.getOpcode() == ISD::TRUNCATE) &&
  17304. Value->hasOneUse() && ST->isUnindexed() &&
  17305. TLI.canCombineTruncStore(Value.getOperand(0).getValueType(),
  17306. ST->getMemoryVT(), LegalOperations)) {
  17307. return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
  17308. Ptr, ST->getMemoryVT(), ST->getMemOperand());
  17309. }
  17310. // Always perform this optimization before types are legal. If the target
  17311. // prefers, also try this after legalization to catch stores that were created
  17312. // by intrinsics or other nodes.
  17313. if (!LegalTypes || (TLI.mergeStoresAfterLegalization(ST->getMemoryVT()))) {
  17314. while (true) {
  17315. // There can be multiple store sequences on the same chain.
  17316. // Keep trying to merge store sequences until we are unable to do so
  17317. // or until we merge the last store on the chain.
  17318. bool Changed = mergeConsecutiveStores(ST);
  17319. if (!Changed) break;
  17320. // Return N as merge only uses CombineTo and no worklist clean
  17321. // up is necessary.
  17322. if (N->getOpcode() == ISD::DELETED_NODE || !isa<StoreSDNode>(N))
  17323. return SDValue(N, 0);
  17324. }
  17325. }
  17326. // Try transforming N to an indexed store.
  17327. if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
  17328. return SDValue(N, 0);
  17329. // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
  17330. //
  17331. // Make sure to do this only after attempting to merge stores in order to
  17332. // avoid changing the types of some subset of stores due to visit order,
  17333. // preventing their merging.
  17334. if (isa<ConstantFPSDNode>(ST->getValue())) {
  17335. if (SDValue NewSt = replaceStoreOfFPConstant(ST))
  17336. return NewSt;
  17337. }
  17338. if (SDValue NewSt = splitMergedValStore(ST))
  17339. return NewSt;
  17340. return ReduceLoadOpStoreWidth(N);
  17341. }
  17342. SDValue DAGCombiner::visitLIFETIME_END(SDNode *N) {
  17343. const auto *LifetimeEnd = cast<LifetimeSDNode>(N);
  17344. if (!LifetimeEnd->hasOffset())
  17345. return SDValue();
  17346. const BaseIndexOffset LifetimeEndBase(N->getOperand(1), SDValue(),
  17347. LifetimeEnd->getOffset(), false);
  17348. // We walk up the chains to find stores.
  17349. SmallVector<SDValue, 8> Chains = {N->getOperand(0)};
  17350. while (!Chains.empty()) {
  17351. SDValue Chain = Chains.pop_back_val();
  17352. if (!Chain.hasOneUse())
  17353. continue;
  17354. switch (Chain.getOpcode()) {
  17355. case ISD::TokenFactor:
  17356. for (unsigned Nops = Chain.getNumOperands(); Nops;)
  17357. Chains.push_back(Chain.getOperand(--Nops));
  17358. break;
  17359. case ISD::LIFETIME_START:
  17360. case ISD::LIFETIME_END:
  17361. // We can forward past any lifetime start/end that can be proven not to
  17362. // alias the node.
  17363. if (!mayAlias(Chain.getNode(), N))
  17364. Chains.push_back(Chain.getOperand(0));
  17365. break;
  17366. case ISD::STORE: {
  17367. StoreSDNode *ST = dyn_cast<StoreSDNode>(Chain);
  17368. // TODO: Can relax for unordered atomics (see D66309)
  17369. if (!ST->isSimple() || ST->isIndexed())
  17370. continue;
  17371. const TypeSize StoreSize = ST->getMemoryVT().getStoreSize();
  17372. // The bounds of a scalable store are not known until runtime, so this
  17373. // store cannot be elided.
  17374. if (StoreSize.isScalable())
  17375. continue;
  17376. const BaseIndexOffset StoreBase = BaseIndexOffset::match(ST, DAG);
  17377. // If we store purely within object bounds just before its lifetime ends,
  17378. // we can remove the store.
  17379. if (LifetimeEndBase.contains(DAG, LifetimeEnd->getSize() * 8, StoreBase,
  17380. StoreSize.getFixedValue() * 8)) {
  17381. LLVM_DEBUG(dbgs() << "\nRemoving store:"; StoreBase.dump();
  17382. dbgs() << "\nwithin LIFETIME_END of : ";
  17383. LifetimeEndBase.dump(); dbgs() << "\n");
  17384. CombineTo(ST, ST->getChain());
  17385. return SDValue(N, 0);
  17386. }
  17387. }
  17388. }
  17389. }
  17390. return SDValue();
  17391. }
  17392. /// For the instruction sequence of store below, F and I values
  17393. /// are bundled together as an i64 value before being stored into memory.
  17394. /// Sometimes it is more efficent to generate separate stores for F and I,
  17395. /// which can remove the bitwise instructions or sink them to colder places.
  17396. ///
  17397. /// (store (or (zext (bitcast F to i32) to i64),
  17398. /// (shl (zext I to i64), 32)), addr) -->
  17399. /// (store F, addr) and (store I, addr+4)
  17400. ///
  17401. /// Similarly, splitting for other merged store can also be beneficial, like:
  17402. /// For pair of {i32, i32}, i64 store --> two i32 stores.
  17403. /// For pair of {i32, i16}, i64 store --> two i32 stores.
  17404. /// For pair of {i16, i16}, i32 store --> two i16 stores.
  17405. /// For pair of {i16, i8}, i32 store --> two i16 stores.
  17406. /// For pair of {i8, i8}, i16 store --> two i8 stores.
  17407. ///
  17408. /// We allow each target to determine specifically which kind of splitting is
  17409. /// supported.
  17410. ///
  17411. /// The store patterns are commonly seen from the simple code snippet below
  17412. /// if only std::make_pair(...) is sroa transformed before inlined into hoo.
  17413. /// void goo(const std::pair<int, float> &);
  17414. /// hoo() {
  17415. /// ...
  17416. /// goo(std::make_pair(tmp, ftmp));
  17417. /// ...
  17418. /// }
  17419. ///
  17420. SDValue DAGCombiner::splitMergedValStore(StoreSDNode *ST) {
  17421. if (OptLevel == CodeGenOpt::None)
  17422. return SDValue();
  17423. // Can't change the number of memory accesses for a volatile store or break
  17424. // atomicity for an atomic one.
  17425. if (!ST->isSimple())
  17426. return SDValue();
  17427. SDValue Val = ST->getValue();
  17428. SDLoc DL(ST);
  17429. // Match OR operand.
  17430. if (!Val.getValueType().isScalarInteger() || Val.getOpcode() != ISD::OR)
  17431. return SDValue();
  17432. // Match SHL operand and get Lower and Higher parts of Val.
  17433. SDValue Op1 = Val.getOperand(0);
  17434. SDValue Op2 = Val.getOperand(1);
  17435. SDValue Lo, Hi;
  17436. if (Op1.getOpcode() != ISD::SHL) {
  17437. std::swap(Op1, Op2);
  17438. if (Op1.getOpcode() != ISD::SHL)
  17439. return SDValue();
  17440. }
  17441. Lo = Op2;
  17442. Hi = Op1.getOperand(0);
  17443. if (!Op1.hasOneUse())
  17444. return SDValue();
  17445. // Match shift amount to HalfValBitSize.
  17446. unsigned HalfValBitSize = Val.getValueSizeInBits() / 2;
  17447. ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(Op1.getOperand(1));
  17448. if (!ShAmt || ShAmt->getAPIntValue() != HalfValBitSize)
  17449. return SDValue();
  17450. // Lo and Hi are zero-extended from int with size less equal than 32
  17451. // to i64.
  17452. if (Lo.getOpcode() != ISD::ZERO_EXTEND || !Lo.hasOneUse() ||
  17453. !Lo.getOperand(0).getValueType().isScalarInteger() ||
  17454. Lo.getOperand(0).getValueSizeInBits() > HalfValBitSize ||
  17455. Hi.getOpcode() != ISD::ZERO_EXTEND || !Hi.hasOneUse() ||
  17456. !Hi.getOperand(0).getValueType().isScalarInteger() ||
  17457. Hi.getOperand(0).getValueSizeInBits() > HalfValBitSize)
  17458. return SDValue();
  17459. // Use the EVT of low and high parts before bitcast as the input
  17460. // of target query.
  17461. EVT LowTy = (Lo.getOperand(0).getOpcode() == ISD::BITCAST)
  17462. ? Lo.getOperand(0).getValueType()
  17463. : Lo.getValueType();
  17464. EVT HighTy = (Hi.getOperand(0).getOpcode() == ISD::BITCAST)
  17465. ? Hi.getOperand(0).getValueType()
  17466. : Hi.getValueType();
  17467. if (!TLI.isMultiStoresCheaperThanBitsMerge(LowTy, HighTy))
  17468. return SDValue();
  17469. // Start to split store.
  17470. MachineMemOperand::Flags MMOFlags = ST->getMemOperand()->getFlags();
  17471. AAMDNodes AAInfo = ST->getAAInfo();
  17472. // Change the sizes of Lo and Hi's value types to HalfValBitSize.
  17473. EVT VT = EVT::getIntegerVT(*DAG.getContext(), HalfValBitSize);
  17474. Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Lo.getOperand(0));
  17475. Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Hi.getOperand(0));
  17476. SDValue Chain = ST->getChain();
  17477. SDValue Ptr = ST->getBasePtr();
  17478. // Lower value store.
  17479. SDValue St0 = DAG.getStore(Chain, DL, Lo, Ptr, ST->getPointerInfo(),
  17480. ST->getOriginalAlign(), MMOFlags, AAInfo);
  17481. Ptr = DAG.getMemBasePlusOffset(Ptr, TypeSize::Fixed(HalfValBitSize / 8), DL);
  17482. // Higher value store.
  17483. SDValue St1 = DAG.getStore(
  17484. St0, DL, Hi, Ptr, ST->getPointerInfo().getWithOffset(HalfValBitSize / 8),
  17485. ST->getOriginalAlign(), MMOFlags, AAInfo);
  17486. return St1;
  17487. }
  17488. // Merge an insertion into an existing shuffle:
  17489. // (insert_vector_elt (vector_shuffle X, Y, Mask),
  17490. // .(extract_vector_elt X, N), InsIndex)
  17491. // --> (vector_shuffle X, Y, NewMask)
  17492. // and variations where shuffle operands may be CONCAT_VECTORS.
  17493. static bool mergeEltWithShuffle(SDValue &X, SDValue &Y, ArrayRef<int> Mask,
  17494. SmallVectorImpl<int> &NewMask, SDValue Elt,
  17495. unsigned InsIndex) {
  17496. if (Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
  17497. !isa<ConstantSDNode>(Elt.getOperand(1)))
  17498. return false;
  17499. // Vec's operand 0 is using indices from 0 to N-1 and
  17500. // operand 1 from N to 2N - 1, where N is the number of
  17501. // elements in the vectors.
  17502. SDValue InsertVal0 = Elt.getOperand(0);
  17503. int ElementOffset = -1;
  17504. // We explore the inputs of the shuffle in order to see if we find the
  17505. // source of the extract_vector_elt. If so, we can use it to modify the
  17506. // shuffle rather than perform an insert_vector_elt.
  17507. SmallVector<std::pair<int, SDValue>, 8> ArgWorkList;
  17508. ArgWorkList.emplace_back(Mask.size(), Y);
  17509. ArgWorkList.emplace_back(0, X);
  17510. while (!ArgWorkList.empty()) {
  17511. int ArgOffset;
  17512. SDValue ArgVal;
  17513. std::tie(ArgOffset, ArgVal) = ArgWorkList.pop_back_val();
  17514. if (ArgVal == InsertVal0) {
  17515. ElementOffset = ArgOffset;
  17516. break;
  17517. }
  17518. // Peek through concat_vector.
  17519. if (ArgVal.getOpcode() == ISD::CONCAT_VECTORS) {
  17520. int CurrentArgOffset =
  17521. ArgOffset + ArgVal.getValueType().getVectorNumElements();
  17522. int Step = ArgVal.getOperand(0).getValueType().getVectorNumElements();
  17523. for (SDValue Op : reverse(ArgVal->ops())) {
  17524. CurrentArgOffset -= Step;
  17525. ArgWorkList.emplace_back(CurrentArgOffset, Op);
  17526. }
  17527. // Make sure we went through all the elements and did not screw up index
  17528. // computation.
  17529. assert(CurrentArgOffset == ArgOffset);
  17530. }
  17531. }
  17532. // If we failed to find a match, see if we can replace an UNDEF shuffle
  17533. // operand.
  17534. if (ElementOffset == -1) {
  17535. if (!Y.isUndef() || InsertVal0.getValueType() != Y.getValueType())
  17536. return false;
  17537. ElementOffset = Mask.size();
  17538. Y = InsertVal0;
  17539. }
  17540. NewMask.assign(Mask.begin(), Mask.end());
  17541. NewMask[InsIndex] = ElementOffset + Elt.getConstantOperandVal(1);
  17542. assert(NewMask[InsIndex] < (int)(2 * Mask.size()) && NewMask[InsIndex] >= 0 &&
  17543. "NewMask[InsIndex] is out of bound");
  17544. return true;
  17545. }
  17546. // Merge an insertion into an existing shuffle:
  17547. // (insert_vector_elt (vector_shuffle X, Y), (extract_vector_elt X, N),
  17548. // InsIndex)
  17549. // --> (vector_shuffle X, Y) and variations where shuffle operands may be
  17550. // CONCAT_VECTORS.
  17551. SDValue DAGCombiner::mergeInsertEltWithShuffle(SDNode *N, unsigned InsIndex) {
  17552. assert(N->getOpcode() == ISD::INSERT_VECTOR_ELT &&
  17553. "Expected extract_vector_elt");
  17554. SDValue InsertVal = N->getOperand(1);
  17555. SDValue Vec = N->getOperand(0);
  17556. auto *SVN = dyn_cast<ShuffleVectorSDNode>(Vec);
  17557. if (!SVN || !Vec.hasOneUse())
  17558. return SDValue();
  17559. ArrayRef<int> Mask = SVN->getMask();
  17560. SDValue X = Vec.getOperand(0);
  17561. SDValue Y = Vec.getOperand(1);
  17562. SmallVector<int, 16> NewMask(Mask);
  17563. if (mergeEltWithShuffle(X, Y, Mask, NewMask, InsertVal, InsIndex)) {
  17564. SDValue LegalShuffle = TLI.buildLegalVectorShuffle(
  17565. Vec.getValueType(), SDLoc(N), X, Y, NewMask, DAG);
  17566. if (LegalShuffle)
  17567. return LegalShuffle;
  17568. }
  17569. return SDValue();
  17570. }
  17571. // Convert a disguised subvector insertion into a shuffle:
  17572. // insert_vector_elt V, (bitcast X from vector type), IdxC -->
  17573. // bitcast(shuffle (bitcast V), (extended X), Mask)
  17574. // Note: We do not use an insert_subvector node because that requires a
  17575. // legal subvector type.
  17576. SDValue DAGCombiner::combineInsertEltToShuffle(SDNode *N, unsigned InsIndex) {
  17577. assert(N->getOpcode() == ISD::INSERT_VECTOR_ELT &&
  17578. "Expected extract_vector_elt");
  17579. SDValue InsertVal = N->getOperand(1);
  17580. if (InsertVal.getOpcode() != ISD::BITCAST || !InsertVal.hasOneUse() ||
  17581. !InsertVal.getOperand(0).getValueType().isVector())
  17582. return SDValue();
  17583. SDValue SubVec = InsertVal.getOperand(0);
  17584. SDValue DestVec = N->getOperand(0);
  17585. EVT SubVecVT = SubVec.getValueType();
  17586. EVT VT = DestVec.getValueType();
  17587. unsigned NumSrcElts = SubVecVT.getVectorNumElements();
  17588. // If the source only has a single vector element, the cost of creating adding
  17589. // it to a vector is likely to exceed the cost of a insert_vector_elt.
  17590. if (NumSrcElts == 1)
  17591. return SDValue();
  17592. unsigned ExtendRatio = VT.getSizeInBits() / SubVecVT.getSizeInBits();
  17593. unsigned NumMaskVals = ExtendRatio * NumSrcElts;
  17594. // Step 1: Create a shuffle mask that implements this insert operation. The
  17595. // vector that we are inserting into will be operand 0 of the shuffle, so
  17596. // those elements are just 'i'. The inserted subvector is in the first
  17597. // positions of operand 1 of the shuffle. Example:
  17598. // insert v4i32 V, (v2i16 X), 2 --> shuffle v8i16 V', X', {0,1,2,3,8,9,6,7}
  17599. SmallVector<int, 16> Mask(NumMaskVals);
  17600. for (unsigned i = 0; i != NumMaskVals; ++i) {
  17601. if (i / NumSrcElts == InsIndex)
  17602. Mask[i] = (i % NumSrcElts) + NumMaskVals;
  17603. else
  17604. Mask[i] = i;
  17605. }
  17606. // Bail out if the target can not handle the shuffle we want to create.
  17607. EVT SubVecEltVT = SubVecVT.getVectorElementType();
  17608. EVT ShufVT = EVT::getVectorVT(*DAG.getContext(), SubVecEltVT, NumMaskVals);
  17609. if (!TLI.isShuffleMaskLegal(Mask, ShufVT))
  17610. return SDValue();
  17611. // Step 2: Create a wide vector from the inserted source vector by appending
  17612. // undefined elements. This is the same size as our destination vector.
  17613. SDLoc DL(N);
  17614. SmallVector<SDValue, 8> ConcatOps(ExtendRatio, DAG.getUNDEF(SubVecVT));
  17615. ConcatOps[0] = SubVec;
  17616. SDValue PaddedSubV = DAG.getNode(ISD::CONCAT_VECTORS, DL, ShufVT, ConcatOps);
  17617. // Step 3: Shuffle in the padded subvector.
  17618. SDValue DestVecBC = DAG.getBitcast(ShufVT, DestVec);
  17619. SDValue Shuf = DAG.getVectorShuffle(ShufVT, DL, DestVecBC, PaddedSubV, Mask);
  17620. AddToWorklist(PaddedSubV.getNode());
  17621. AddToWorklist(DestVecBC.getNode());
  17622. AddToWorklist(Shuf.getNode());
  17623. return DAG.getBitcast(VT, Shuf);
  17624. }
  17625. SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
  17626. SDValue InVec = N->getOperand(0);
  17627. SDValue InVal = N->getOperand(1);
  17628. SDValue EltNo = N->getOperand(2);
  17629. SDLoc DL(N);
  17630. EVT VT = InVec.getValueType();
  17631. auto *IndexC = dyn_cast<ConstantSDNode>(EltNo);
  17632. // Insert into out-of-bounds element is undefined.
  17633. if (IndexC && VT.isFixedLengthVector() &&
  17634. IndexC->getZExtValue() >= VT.getVectorNumElements())
  17635. return DAG.getUNDEF(VT);
  17636. // Remove redundant insertions:
  17637. // (insert_vector_elt x (extract_vector_elt x idx) idx) -> x
  17638. if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
  17639. InVec == InVal.getOperand(0) && EltNo == InVal.getOperand(1))
  17640. return InVec;
  17641. if (!IndexC) {
  17642. // If this is variable insert to undef vector, it might be better to splat:
  17643. // inselt undef, InVal, EltNo --> build_vector < InVal, InVal, ... >
  17644. if (InVec.isUndef() && TLI.shouldSplatInsEltVarIndex(VT))
  17645. return DAG.getSplat(VT, DL, InVal);
  17646. return SDValue();
  17647. }
  17648. if (VT.isScalableVector())
  17649. return SDValue();
  17650. unsigned NumElts = VT.getVectorNumElements();
  17651. // We must know which element is being inserted for folds below here.
  17652. unsigned Elt = IndexC->getZExtValue();
  17653. // Handle <1 x ???> vector insertion special cases.
  17654. if (NumElts == 1) {
  17655. // insert_vector_elt(x, extract_vector_elt(y, 0), 0) -> y
  17656. if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
  17657. InVal.getOperand(0).getValueType() == VT &&
  17658. isNullConstant(InVal.getOperand(1)))
  17659. return InVal.getOperand(0);
  17660. }
  17661. // Canonicalize insert_vector_elt dag nodes.
  17662. // Example:
  17663. // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
  17664. // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
  17665. //
  17666. // Do this only if the child insert_vector node has one use; also
  17667. // do this only if indices are both constants and Idx1 < Idx0.
  17668. if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
  17669. && isa<ConstantSDNode>(InVec.getOperand(2))) {
  17670. unsigned OtherElt = InVec.getConstantOperandVal(2);
  17671. if (Elt < OtherElt) {
  17672. // Swap nodes.
  17673. SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT,
  17674. InVec.getOperand(0), InVal, EltNo);
  17675. AddToWorklist(NewOp.getNode());
  17676. return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
  17677. VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
  17678. }
  17679. }
  17680. if (SDValue Shuf = mergeInsertEltWithShuffle(N, Elt))
  17681. return Shuf;
  17682. if (SDValue Shuf = combineInsertEltToShuffle(N, Elt))
  17683. return Shuf;
  17684. // Attempt to convert an insert_vector_elt chain into a legal build_vector.
  17685. if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)) {
  17686. // vXi1 vector - we don't need to recurse.
  17687. if (NumElts == 1)
  17688. return DAG.getBuildVector(VT, DL, {InVal});
  17689. // If we haven't already collected the element, insert into the op list.
  17690. EVT MaxEltVT = InVal.getValueType();
  17691. auto AddBuildVectorOp = [&](SmallVectorImpl<SDValue> &Ops, SDValue Elt,
  17692. unsigned Idx) {
  17693. if (!Ops[Idx]) {
  17694. Ops[Idx] = Elt;
  17695. if (VT.isInteger()) {
  17696. EVT EltVT = Elt.getValueType();
  17697. MaxEltVT = MaxEltVT.bitsGE(EltVT) ? MaxEltVT : EltVT;
  17698. }
  17699. }
  17700. };
  17701. // Ensure all the operands are the same value type, fill any missing
  17702. // operands with UNDEF and create the BUILD_VECTOR.
  17703. auto CanonicalizeBuildVector = [&](SmallVectorImpl<SDValue> &Ops) {
  17704. assert(Ops.size() == NumElts && "Unexpected vector size");
  17705. for (SDValue &Op : Ops) {
  17706. if (Op)
  17707. Op = VT.isInteger() ? DAG.getAnyExtOrTrunc(Op, DL, MaxEltVT) : Op;
  17708. else
  17709. Op = DAG.getUNDEF(MaxEltVT);
  17710. }
  17711. return DAG.getBuildVector(VT, DL, Ops);
  17712. };
  17713. SmallVector<SDValue, 8> Ops(NumElts, SDValue());
  17714. Ops[Elt] = InVal;
  17715. // Recurse up a INSERT_VECTOR_ELT chain to build a BUILD_VECTOR.
  17716. for (SDValue CurVec = InVec; CurVec;) {
  17717. // UNDEF - build new BUILD_VECTOR from already inserted operands.
  17718. if (CurVec.isUndef())
  17719. return CanonicalizeBuildVector(Ops);
  17720. // BUILD_VECTOR - insert unused operands and build new BUILD_VECTOR.
  17721. if (CurVec.getOpcode() == ISD::BUILD_VECTOR && CurVec.hasOneUse()) {
  17722. for (unsigned I = 0; I != NumElts; ++I)
  17723. AddBuildVectorOp(Ops, CurVec.getOperand(I), I);
  17724. return CanonicalizeBuildVector(Ops);
  17725. }
  17726. // SCALAR_TO_VECTOR - insert unused scalar and build new BUILD_VECTOR.
  17727. if (CurVec.getOpcode() == ISD::SCALAR_TO_VECTOR && CurVec.hasOneUse()) {
  17728. AddBuildVectorOp(Ops, CurVec.getOperand(0), 0);
  17729. return CanonicalizeBuildVector(Ops);
  17730. }
  17731. // INSERT_VECTOR_ELT - insert operand and continue up the chain.
  17732. if (CurVec.getOpcode() == ISD::INSERT_VECTOR_ELT && CurVec.hasOneUse())
  17733. if (auto *CurIdx = dyn_cast<ConstantSDNode>(CurVec.getOperand(2)))
  17734. if (CurIdx->getAPIntValue().ult(NumElts)) {
  17735. unsigned Idx = CurIdx->getZExtValue();
  17736. AddBuildVectorOp(Ops, CurVec.getOperand(1), Idx);
  17737. // Found entire BUILD_VECTOR.
  17738. if (all_of(Ops, [](SDValue Op) { return !!Op; }))
  17739. return CanonicalizeBuildVector(Ops);
  17740. CurVec = CurVec->getOperand(0);
  17741. continue;
  17742. }
  17743. // VECTOR_SHUFFLE - if all the operands match the shuffle's sources,
  17744. // update the shuffle mask (and second operand if we started with unary
  17745. // shuffle) and create a new legal shuffle.
  17746. if (CurVec.getOpcode() == ISD::VECTOR_SHUFFLE && CurVec.hasOneUse()) {
  17747. auto *SVN = cast<ShuffleVectorSDNode>(CurVec);
  17748. SDValue LHS = SVN->getOperand(0);
  17749. SDValue RHS = SVN->getOperand(1);
  17750. SmallVector<int, 16> Mask(SVN->getMask());
  17751. bool Merged = true;
  17752. for (auto I : enumerate(Ops)) {
  17753. SDValue &Op = I.value();
  17754. if (Op) {
  17755. SmallVector<int, 16> NewMask;
  17756. if (!mergeEltWithShuffle(LHS, RHS, Mask, NewMask, Op, I.index())) {
  17757. Merged = false;
  17758. break;
  17759. }
  17760. Mask = std::move(NewMask);
  17761. }
  17762. }
  17763. if (Merged)
  17764. if (SDValue NewShuffle =
  17765. TLI.buildLegalVectorShuffle(VT, DL, LHS, RHS, Mask, DAG))
  17766. return NewShuffle;
  17767. }
  17768. // Failed to find a match in the chain - bail.
  17769. break;
  17770. }
  17771. // See if we can fill in the missing constant elements as zeros.
  17772. // TODO: Should we do this for any constant?
  17773. APInt DemandedZeroElts = APInt::getZero(NumElts);
  17774. for (unsigned I = 0; I != NumElts; ++I)
  17775. if (!Ops[I])
  17776. DemandedZeroElts.setBit(I);
  17777. if (DAG.MaskedVectorIsZero(InVec, DemandedZeroElts)) {
  17778. SDValue Zero = VT.isInteger() ? DAG.getConstant(0, DL, MaxEltVT)
  17779. : DAG.getConstantFP(0, DL, MaxEltVT);
  17780. for (unsigned I = 0; I != NumElts; ++I)
  17781. if (!Ops[I])
  17782. Ops[I] = Zero;
  17783. return CanonicalizeBuildVector(Ops);
  17784. }
  17785. }
  17786. return SDValue();
  17787. }
  17788. SDValue DAGCombiner::scalarizeExtractedVectorLoad(SDNode *EVE, EVT InVecVT,
  17789. SDValue EltNo,
  17790. LoadSDNode *OriginalLoad) {
  17791. assert(OriginalLoad->isSimple());
  17792. EVT ResultVT = EVE->getValueType(0);
  17793. EVT VecEltVT = InVecVT.getVectorElementType();
  17794. // If the vector element type is not a multiple of a byte then we are unable
  17795. // to correctly compute an address to load only the extracted element as a
  17796. // scalar.
  17797. if (!VecEltVT.isByteSized())
  17798. return SDValue();
  17799. ISD::LoadExtType ExtTy =
  17800. ResultVT.bitsGT(VecEltVT) ? ISD::NON_EXTLOAD : ISD::EXTLOAD;
  17801. if (!TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT) ||
  17802. !TLI.shouldReduceLoadWidth(OriginalLoad, ExtTy, VecEltVT))
  17803. return SDValue();
  17804. Align Alignment = OriginalLoad->getAlign();
  17805. MachinePointerInfo MPI;
  17806. SDLoc DL(EVE);
  17807. if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
  17808. int Elt = ConstEltNo->getZExtValue();
  17809. unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
  17810. MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
  17811. Alignment = commonAlignment(Alignment, PtrOff);
  17812. } else {
  17813. // Discard the pointer info except the address space because the memory
  17814. // operand can't represent this new access since the offset is variable.
  17815. MPI = MachinePointerInfo(OriginalLoad->getPointerInfo().getAddrSpace());
  17816. Alignment = commonAlignment(Alignment, VecEltVT.getSizeInBits() / 8);
  17817. }
  17818. unsigned IsFast = 0;
  17819. if (!TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VecEltVT,
  17820. OriginalLoad->getAddressSpace(), Alignment,
  17821. OriginalLoad->getMemOperand()->getFlags(),
  17822. &IsFast) ||
  17823. !IsFast)
  17824. return SDValue();
  17825. SDValue NewPtr = TLI.getVectorElementPointer(DAG, OriginalLoad->getBasePtr(),
  17826. InVecVT, EltNo);
  17827. // We are replacing a vector load with a scalar load. The new load must have
  17828. // identical memory op ordering to the original.
  17829. SDValue Load;
  17830. if (ResultVT.bitsGT(VecEltVT)) {
  17831. // If the result type of vextract is wider than the load, then issue an
  17832. // extending load instead.
  17833. ISD::LoadExtType ExtType =
  17834. TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT, VecEltVT) ? ISD::ZEXTLOAD
  17835. : ISD::EXTLOAD;
  17836. Load = DAG.getExtLoad(ExtType, DL, ResultVT, OriginalLoad->getChain(),
  17837. NewPtr, MPI, VecEltVT, Alignment,
  17838. OriginalLoad->getMemOperand()->getFlags(),
  17839. OriginalLoad->getAAInfo());
  17840. DAG.makeEquivalentMemoryOrdering(OriginalLoad, Load);
  17841. } else {
  17842. // The result type is narrower or the same width as the vector element
  17843. Load = DAG.getLoad(VecEltVT, DL, OriginalLoad->getChain(), NewPtr, MPI,
  17844. Alignment, OriginalLoad->getMemOperand()->getFlags(),
  17845. OriginalLoad->getAAInfo());
  17846. DAG.makeEquivalentMemoryOrdering(OriginalLoad, Load);
  17847. if (ResultVT.bitsLT(VecEltVT))
  17848. Load = DAG.getNode(ISD::TRUNCATE, DL, ResultVT, Load);
  17849. else
  17850. Load = DAG.getBitcast(ResultVT, Load);
  17851. }
  17852. ++OpsNarrowed;
  17853. return Load;
  17854. }
  17855. /// Transform a vector binary operation into a scalar binary operation by moving
  17856. /// the math/logic after an extract element of a vector.
  17857. static SDValue scalarizeExtractedBinop(SDNode *ExtElt, SelectionDAG &DAG,
  17858. bool LegalOperations) {
  17859. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  17860. SDValue Vec = ExtElt->getOperand(0);
  17861. SDValue Index = ExtElt->getOperand(1);
  17862. auto *IndexC = dyn_cast<ConstantSDNode>(Index);
  17863. if (!IndexC || !TLI.isBinOp(Vec.getOpcode()) || !Vec.hasOneUse() ||
  17864. Vec->getNumValues() != 1)
  17865. return SDValue();
  17866. // Targets may want to avoid this to prevent an expensive register transfer.
  17867. if (!TLI.shouldScalarizeBinop(Vec))
  17868. return SDValue();
  17869. // Extracting an element of a vector constant is constant-folded, so this
  17870. // transform is just replacing a vector op with a scalar op while moving the
  17871. // extract.
  17872. SDValue Op0 = Vec.getOperand(0);
  17873. SDValue Op1 = Vec.getOperand(1);
  17874. APInt SplatVal;
  17875. if (isAnyConstantBuildVector(Op0, true) ||
  17876. ISD::isConstantSplatVector(Op0.getNode(), SplatVal) ||
  17877. isAnyConstantBuildVector(Op1, true) ||
  17878. ISD::isConstantSplatVector(Op1.getNode(), SplatVal)) {
  17879. // extractelt (binop X, C), IndexC --> binop (extractelt X, IndexC), C'
  17880. // extractelt (binop C, X), IndexC --> binop C', (extractelt X, IndexC)
  17881. SDLoc DL(ExtElt);
  17882. EVT VT = ExtElt->getValueType(0);
  17883. SDValue Ext0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, Op0, Index);
  17884. SDValue Ext1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, Op1, Index);
  17885. return DAG.getNode(Vec.getOpcode(), DL, VT, Ext0, Ext1);
  17886. }
  17887. return SDValue();
  17888. }
  17889. // Given a ISD::EXTRACT_VECTOR_ELT, which is a glorified bit sequence extract,
  17890. // recursively analyse all of it's users. and try to model themselves as
  17891. // bit sequence extractions. If all of them agree on the new, narrower element
  17892. // type, and all of them can be modelled as ISD::EXTRACT_VECTOR_ELT's of that
  17893. // new element type, do so now.
  17894. // This is mainly useful to recover from legalization that scalarized
  17895. // the vector as wide elements, but tries to rebuild it with narrower elements.
  17896. //
  17897. // Some more nodes could be modelled if that helps cover interesting patterns.
  17898. bool DAGCombiner::refineExtractVectorEltIntoMultipleNarrowExtractVectorElts(
  17899. SDNode *N) {
  17900. // We perform this optimization post type-legalization because
  17901. // the type-legalizer often scalarizes integer-promoted vectors.
  17902. // Performing this optimization before may cause legalizaton cycles.
  17903. if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
  17904. return false;
  17905. // TODO: Add support for big-endian.
  17906. if (DAG.getDataLayout().isBigEndian())
  17907. return false;
  17908. SDValue VecOp = N->getOperand(0);
  17909. EVT VecVT = VecOp.getValueType();
  17910. assert(!VecVT.isScalableVector() && "Only for fixed vectors.");
  17911. // We must start with a constant extraction index.
  17912. auto *IndexC = dyn_cast<ConstantSDNode>(N->getOperand(1));
  17913. if (!IndexC)
  17914. return false;
  17915. assert(IndexC->getZExtValue() < VecVT.getVectorNumElements() &&
  17916. "Original ISD::EXTRACT_VECTOR_ELT is undefinend?");
  17917. // TODO: deal with the case of implicit anyext of the extraction.
  17918. unsigned VecEltBitWidth = VecVT.getScalarSizeInBits();
  17919. EVT ScalarVT = N->getValueType(0);
  17920. if (VecVT.getScalarType() != ScalarVT)
  17921. return false;
  17922. // TODO: deal with the cases other than everything being integer-typed.
  17923. if (!ScalarVT.isScalarInteger())
  17924. return false;
  17925. struct Entry {
  17926. SDNode *Producer;
  17927. // Which bits of VecOp does it contain?
  17928. unsigned BitPos;
  17929. int NumBits;
  17930. // NOTE: the actual width of \p Producer may be wider than NumBits!
  17931. Entry(Entry &&) = default;
  17932. Entry(SDNode *Producer_, unsigned BitPos_, int NumBits_)
  17933. : Producer(Producer_), BitPos(BitPos_), NumBits(NumBits_) {}
  17934. Entry() = delete;
  17935. Entry(const Entry &) = delete;
  17936. Entry &operator=(const Entry &) = delete;
  17937. Entry &operator=(Entry &&) = delete;
  17938. };
  17939. SmallVector<Entry, 32> Worklist;
  17940. SmallVector<Entry, 32> Leafs;
  17941. // We start at the "root" ISD::EXTRACT_VECTOR_ELT.
  17942. Worklist.emplace_back(N, /*BitPos=*/VecEltBitWidth * IndexC->getZExtValue(),
  17943. /*NumBits=*/VecEltBitWidth);
  17944. while (!Worklist.empty()) {
  17945. Entry E = Worklist.pop_back_val();
  17946. // Does the node not even use any of the VecOp bits?
  17947. if (!(E.NumBits > 0 && E.BitPos < VecVT.getSizeInBits() &&
  17948. E.BitPos + E.NumBits <= VecVT.getSizeInBits()))
  17949. return false; // Let's allow the other combines clean this up first.
  17950. // Did we fail to model any of the users of the Producer?
  17951. bool ProducerIsLeaf = false;
  17952. // Look at each user of this Producer.
  17953. for (SDNode *User : E.Producer->uses()) {
  17954. switch (User->getOpcode()) {
  17955. // TODO: support ISD::BITCAST
  17956. // TODO: support ISD::ANY_EXTEND
  17957. // TODO: support ISD::ZERO_EXTEND
  17958. // TODO: support ISD::SIGN_EXTEND
  17959. case ISD::TRUNCATE:
  17960. // Truncation simply means we keep position, but extract less bits.
  17961. Worklist.emplace_back(User, E.BitPos,
  17962. /*NumBits=*/User->getValueSizeInBits(0));
  17963. break;
  17964. // TODO: support ISD::SRA
  17965. // TODO: support ISD::SHL
  17966. case ISD::SRL:
  17967. // We should be shifting the Producer by a constant amount.
  17968. if (auto *ShAmtC = dyn_cast<ConstantSDNode>(User->getOperand(1));
  17969. User->getOperand(0).getNode() == E.Producer && ShAmtC) {
  17970. // Logical right-shift means that we start extraction later,
  17971. // but stop it at the same position we did previously.
  17972. unsigned ShAmt = ShAmtC->getZExtValue();
  17973. Worklist.emplace_back(User, E.BitPos + ShAmt, E.NumBits - ShAmt);
  17974. break;
  17975. }
  17976. [[fallthrough]];
  17977. default:
  17978. // We can not model this user of the Producer.
  17979. // Which means the current Producer will be a ISD::EXTRACT_VECTOR_ELT.
  17980. ProducerIsLeaf = true;
  17981. // Profitability check: all users that we can not model
  17982. // must be ISD::BUILD_VECTOR's.
  17983. if (User->getOpcode() != ISD::BUILD_VECTOR)
  17984. return false;
  17985. break;
  17986. }
  17987. }
  17988. if (ProducerIsLeaf)
  17989. Leafs.emplace_back(std::move(E));
  17990. }
  17991. unsigned NewVecEltBitWidth = Leafs.front().NumBits;
  17992. // If we are still at the same element granularity, give up,
  17993. if (NewVecEltBitWidth == VecEltBitWidth)
  17994. return false;
  17995. // The vector width must be a multiple of the new element width.
  17996. if (VecVT.getSizeInBits() % NewVecEltBitWidth != 0)
  17997. return false;
  17998. // All leafs must agree on the new element width.
  17999. // All leafs must not expect any "padding" bits ontop of that width.
  18000. // All leafs must start extraction from multiple of that width.
  18001. if (!all_of(Leafs, [NewVecEltBitWidth](const Entry &E) {
  18002. return (unsigned)E.NumBits == NewVecEltBitWidth &&
  18003. E.Producer->getValueSizeInBits(0) == NewVecEltBitWidth &&
  18004. E.BitPos % NewVecEltBitWidth == 0;
  18005. }))
  18006. return false;
  18007. EVT NewScalarVT = EVT::getIntegerVT(*DAG.getContext(), NewVecEltBitWidth);
  18008. EVT NewVecVT = EVT::getVectorVT(*DAG.getContext(), NewScalarVT,
  18009. VecVT.getSizeInBits() / NewVecEltBitWidth);
  18010. if (LegalTypes &&
  18011. !(TLI.isTypeLegal(NewScalarVT) && TLI.isTypeLegal(NewVecVT)))
  18012. return false;
  18013. if (LegalOperations &&
  18014. !(TLI.isOperationLegalOrCustom(ISD::BITCAST, NewVecVT) &&
  18015. TLI.isOperationLegalOrCustom(ISD::EXTRACT_VECTOR_ELT, NewVecVT)))
  18016. return false;
  18017. SDValue NewVecOp = DAG.getBitcast(NewVecVT, VecOp);
  18018. for (const Entry &E : Leafs) {
  18019. SDLoc DL(E.Producer);
  18020. unsigned NewIndex = E.BitPos / NewVecEltBitWidth;
  18021. assert(NewIndex < NewVecVT.getVectorNumElements() &&
  18022. "Creating out-of-bounds ISD::EXTRACT_VECTOR_ELT?");
  18023. SDValue V = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, NewScalarVT, NewVecOp,
  18024. DAG.getVectorIdxConstant(NewIndex, DL));
  18025. CombineTo(E.Producer, V);
  18026. }
  18027. return true;
  18028. }
  18029. SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
  18030. SDValue VecOp = N->getOperand(0);
  18031. SDValue Index = N->getOperand(1);
  18032. EVT ScalarVT = N->getValueType(0);
  18033. EVT VecVT = VecOp.getValueType();
  18034. if (VecOp.isUndef())
  18035. return DAG.getUNDEF(ScalarVT);
  18036. // extract_vector_elt (insert_vector_elt vec, val, idx), idx) -> val
  18037. //
  18038. // This only really matters if the index is non-constant since other combines
  18039. // on the constant elements already work.
  18040. SDLoc DL(N);
  18041. if (VecOp.getOpcode() == ISD::INSERT_VECTOR_ELT &&
  18042. Index == VecOp.getOperand(2)) {
  18043. SDValue Elt = VecOp.getOperand(1);
  18044. return VecVT.isInteger() ? DAG.getAnyExtOrTrunc(Elt, DL, ScalarVT) : Elt;
  18045. }
  18046. // (vextract (scalar_to_vector val, 0) -> val
  18047. if (VecOp.getOpcode() == ISD::SCALAR_TO_VECTOR) {
  18048. // Only 0'th element of SCALAR_TO_VECTOR is defined.
  18049. if (DAG.isKnownNeverZero(Index))
  18050. return DAG.getUNDEF(ScalarVT);
  18051. // Check if the result type doesn't match the inserted element type. A
  18052. // SCALAR_TO_VECTOR may truncate the inserted element and the
  18053. // EXTRACT_VECTOR_ELT may widen the extracted vector.
  18054. SDValue InOp = VecOp.getOperand(0);
  18055. if (InOp.getValueType() != ScalarVT) {
  18056. assert(InOp.getValueType().isInteger() && ScalarVT.isInteger() &&
  18057. InOp.getValueType().bitsGT(ScalarVT));
  18058. return DAG.getNode(ISD::TRUNCATE, DL, ScalarVT, InOp);
  18059. }
  18060. return InOp;
  18061. }
  18062. // extract_vector_elt of out-of-bounds element -> UNDEF
  18063. auto *IndexC = dyn_cast<ConstantSDNode>(Index);
  18064. if (IndexC && VecVT.isFixedLengthVector() &&
  18065. IndexC->getAPIntValue().uge(VecVT.getVectorNumElements()))
  18066. return DAG.getUNDEF(ScalarVT);
  18067. // extract_vector_elt(freeze(x)), idx -> freeze(extract_vector_elt(x)), idx
  18068. if (VecOp.hasOneUse() && VecOp.getOpcode() == ISD::FREEZE) {
  18069. return DAG.getFreeze(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ScalarVT,
  18070. VecOp.getOperand(0), Index));
  18071. }
  18072. // extract_vector_elt (build_vector x, y), 1 -> y
  18073. if (((IndexC && VecOp.getOpcode() == ISD::BUILD_VECTOR) ||
  18074. VecOp.getOpcode() == ISD::SPLAT_VECTOR) &&
  18075. TLI.isTypeLegal(VecVT) &&
  18076. (VecOp.hasOneUse() || TLI.aggressivelyPreferBuildVectorSources(VecVT))) {
  18077. assert((VecOp.getOpcode() != ISD::BUILD_VECTOR ||
  18078. VecVT.isFixedLengthVector()) &&
  18079. "BUILD_VECTOR used for scalable vectors");
  18080. unsigned IndexVal =
  18081. VecOp.getOpcode() == ISD::BUILD_VECTOR ? IndexC->getZExtValue() : 0;
  18082. SDValue Elt = VecOp.getOperand(IndexVal);
  18083. EVT InEltVT = Elt.getValueType();
  18084. // Sometimes build_vector's scalar input types do not match result type.
  18085. if (ScalarVT == InEltVT)
  18086. return Elt;
  18087. // TODO: It may be useful to truncate if free if the build_vector implicitly
  18088. // converts.
  18089. }
  18090. if (SDValue BO = scalarizeExtractedBinop(N, DAG, LegalOperations))
  18091. return BO;
  18092. if (VecVT.isScalableVector())
  18093. return SDValue();
  18094. // All the code from this point onwards assumes fixed width vectors, but it's
  18095. // possible that some of the combinations could be made to work for scalable
  18096. // vectors too.
  18097. unsigned NumElts = VecVT.getVectorNumElements();
  18098. unsigned VecEltBitWidth = VecVT.getScalarSizeInBits();
  18099. // TODO: These transforms should not require the 'hasOneUse' restriction, but
  18100. // there are regressions on multiple targets without it. We can end up with a
  18101. // mess of scalar and vector code if we reduce only part of the DAG to scalar.
  18102. if (IndexC && VecOp.getOpcode() == ISD::BITCAST && VecVT.isInteger() &&
  18103. VecOp.hasOneUse()) {
  18104. // The vector index of the LSBs of the source depend on the endian-ness.
  18105. bool IsLE = DAG.getDataLayout().isLittleEndian();
  18106. unsigned ExtractIndex = IndexC->getZExtValue();
  18107. // extract_elt (v2i32 (bitcast i64:x)), BCTruncElt -> i32 (trunc i64:x)
  18108. unsigned BCTruncElt = IsLE ? 0 : NumElts - 1;
  18109. SDValue BCSrc = VecOp.getOperand(0);
  18110. if (ExtractIndex == BCTruncElt && BCSrc.getValueType().isScalarInteger())
  18111. return DAG.getAnyExtOrTrunc(BCSrc, DL, ScalarVT);
  18112. if (LegalTypes && BCSrc.getValueType().isInteger() &&
  18113. BCSrc.getOpcode() == ISD::SCALAR_TO_VECTOR) {
  18114. // ext_elt (bitcast (scalar_to_vec i64 X to v2i64) to v4i32), TruncElt -->
  18115. // trunc i64 X to i32
  18116. SDValue X = BCSrc.getOperand(0);
  18117. assert(X.getValueType().isScalarInteger() && ScalarVT.isScalarInteger() &&
  18118. "Extract element and scalar to vector can't change element type "
  18119. "from FP to integer.");
  18120. unsigned XBitWidth = X.getValueSizeInBits();
  18121. BCTruncElt = IsLE ? 0 : XBitWidth / VecEltBitWidth - 1;
  18122. // An extract element return value type can be wider than its vector
  18123. // operand element type. In that case, the high bits are undefined, so
  18124. // it's possible that we may need to extend rather than truncate.
  18125. if (ExtractIndex == BCTruncElt && XBitWidth > VecEltBitWidth) {
  18126. assert(XBitWidth % VecEltBitWidth == 0 &&
  18127. "Scalar bitwidth must be a multiple of vector element bitwidth");
  18128. return DAG.getAnyExtOrTrunc(X, DL, ScalarVT);
  18129. }
  18130. }
  18131. }
  18132. // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
  18133. // We only perform this optimization before the op legalization phase because
  18134. // we may introduce new vector instructions which are not backed by TD
  18135. // patterns. For example on AVX, extracting elements from a wide vector
  18136. // without using extract_subvector. However, if we can find an underlying
  18137. // scalar value, then we can always use that.
  18138. if (IndexC && VecOp.getOpcode() == ISD::VECTOR_SHUFFLE) {
  18139. auto *Shuf = cast<ShuffleVectorSDNode>(VecOp);
  18140. // Find the new index to extract from.
  18141. int OrigElt = Shuf->getMaskElt(IndexC->getZExtValue());
  18142. // Extracting an undef index is undef.
  18143. if (OrigElt == -1)
  18144. return DAG.getUNDEF(ScalarVT);
  18145. // Select the right vector half to extract from.
  18146. SDValue SVInVec;
  18147. if (OrigElt < (int)NumElts) {
  18148. SVInVec = VecOp.getOperand(0);
  18149. } else {
  18150. SVInVec = VecOp.getOperand(1);
  18151. OrigElt -= NumElts;
  18152. }
  18153. if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
  18154. SDValue InOp = SVInVec.getOperand(OrigElt);
  18155. if (InOp.getValueType() != ScalarVT) {
  18156. assert(InOp.getValueType().isInteger() && ScalarVT.isInteger());
  18157. InOp = DAG.getSExtOrTrunc(InOp, DL, ScalarVT);
  18158. }
  18159. return InOp;
  18160. }
  18161. // FIXME: We should handle recursing on other vector shuffles and
  18162. // scalar_to_vector here as well.
  18163. if (!LegalOperations ||
  18164. // FIXME: Should really be just isOperationLegalOrCustom.
  18165. TLI.isOperationLegal(ISD::EXTRACT_VECTOR_ELT, VecVT) ||
  18166. TLI.isOperationExpand(ISD::VECTOR_SHUFFLE, VecVT)) {
  18167. return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ScalarVT, SVInVec,
  18168. DAG.getVectorIdxConstant(OrigElt, DL));
  18169. }
  18170. }
  18171. // If only EXTRACT_VECTOR_ELT nodes use the source vector we can
  18172. // simplify it based on the (valid) extraction indices.
  18173. if (llvm::all_of(VecOp->uses(), [&](SDNode *Use) {
  18174. return Use->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
  18175. Use->getOperand(0) == VecOp &&
  18176. isa<ConstantSDNode>(Use->getOperand(1));
  18177. })) {
  18178. APInt DemandedElts = APInt::getZero(NumElts);
  18179. for (SDNode *Use : VecOp->uses()) {
  18180. auto *CstElt = cast<ConstantSDNode>(Use->getOperand(1));
  18181. if (CstElt->getAPIntValue().ult(NumElts))
  18182. DemandedElts.setBit(CstElt->getZExtValue());
  18183. }
  18184. if (SimplifyDemandedVectorElts(VecOp, DemandedElts, true)) {
  18185. // We simplified the vector operand of this extract element. If this
  18186. // extract is not dead, visit it again so it is folded properly.
  18187. if (N->getOpcode() != ISD::DELETED_NODE)
  18188. AddToWorklist(N);
  18189. return SDValue(N, 0);
  18190. }
  18191. APInt DemandedBits = APInt::getAllOnes(VecEltBitWidth);
  18192. if (SimplifyDemandedBits(VecOp, DemandedBits, DemandedElts, true)) {
  18193. // We simplified the vector operand of this extract element. If this
  18194. // extract is not dead, visit it again so it is folded properly.
  18195. if (N->getOpcode() != ISD::DELETED_NODE)
  18196. AddToWorklist(N);
  18197. return SDValue(N, 0);
  18198. }
  18199. }
  18200. if (refineExtractVectorEltIntoMultipleNarrowExtractVectorElts(N))
  18201. return SDValue(N, 0);
  18202. // Everything under here is trying to match an extract of a loaded value.
  18203. // If the result of load has to be truncated, then it's not necessarily
  18204. // profitable.
  18205. bool BCNumEltsChanged = false;
  18206. EVT ExtVT = VecVT.getVectorElementType();
  18207. EVT LVT = ExtVT;
  18208. if (ScalarVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, ScalarVT))
  18209. return SDValue();
  18210. if (VecOp.getOpcode() == ISD::BITCAST) {
  18211. // Don't duplicate a load with other uses.
  18212. if (!VecOp.hasOneUse())
  18213. return SDValue();
  18214. EVT BCVT = VecOp.getOperand(0).getValueType();
  18215. if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
  18216. return SDValue();
  18217. if (NumElts != BCVT.getVectorNumElements())
  18218. BCNumEltsChanged = true;
  18219. VecOp = VecOp.getOperand(0);
  18220. ExtVT = BCVT.getVectorElementType();
  18221. }
  18222. // extract (vector load $addr), i --> load $addr + i * size
  18223. if (!LegalOperations && !IndexC && VecOp.hasOneUse() &&
  18224. ISD::isNormalLoad(VecOp.getNode()) &&
  18225. !Index->hasPredecessor(VecOp.getNode())) {
  18226. auto *VecLoad = dyn_cast<LoadSDNode>(VecOp);
  18227. if (VecLoad && VecLoad->isSimple())
  18228. return scalarizeExtractedVectorLoad(N, VecVT, Index, VecLoad);
  18229. }
  18230. // Perform only after legalization to ensure build_vector / vector_shuffle
  18231. // optimizations have already been done.
  18232. if (!LegalOperations || !IndexC)
  18233. return SDValue();
  18234. // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
  18235. // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
  18236. // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
  18237. int Elt = IndexC->getZExtValue();
  18238. LoadSDNode *LN0 = nullptr;
  18239. if (ISD::isNormalLoad(VecOp.getNode())) {
  18240. LN0 = cast<LoadSDNode>(VecOp);
  18241. } else if (VecOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
  18242. VecOp.getOperand(0).getValueType() == ExtVT &&
  18243. ISD::isNormalLoad(VecOp.getOperand(0).getNode())) {
  18244. // Don't duplicate a load with other uses.
  18245. if (!VecOp.hasOneUse())
  18246. return SDValue();
  18247. LN0 = cast<LoadSDNode>(VecOp.getOperand(0));
  18248. }
  18249. if (auto *Shuf = dyn_cast<ShuffleVectorSDNode>(VecOp)) {
  18250. // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
  18251. // =>
  18252. // (load $addr+1*size)
  18253. // Don't duplicate a load with other uses.
  18254. if (!VecOp.hasOneUse())
  18255. return SDValue();
  18256. // If the bit convert changed the number of elements, it is unsafe
  18257. // to examine the mask.
  18258. if (BCNumEltsChanged)
  18259. return SDValue();
  18260. // Select the input vector, guarding against out of range extract vector.
  18261. int Idx = (Elt > (int)NumElts) ? -1 : Shuf->getMaskElt(Elt);
  18262. VecOp = (Idx < (int)NumElts) ? VecOp.getOperand(0) : VecOp.getOperand(1);
  18263. if (VecOp.getOpcode() == ISD::BITCAST) {
  18264. // Don't duplicate a load with other uses.
  18265. if (!VecOp.hasOneUse())
  18266. return SDValue();
  18267. VecOp = VecOp.getOperand(0);
  18268. }
  18269. if (ISD::isNormalLoad(VecOp.getNode())) {
  18270. LN0 = cast<LoadSDNode>(VecOp);
  18271. Elt = (Idx < (int)NumElts) ? Idx : Idx - (int)NumElts;
  18272. Index = DAG.getConstant(Elt, DL, Index.getValueType());
  18273. }
  18274. } else if (VecOp.getOpcode() == ISD::CONCAT_VECTORS && !BCNumEltsChanged &&
  18275. VecVT.getVectorElementType() == ScalarVT &&
  18276. (!LegalTypes ||
  18277. TLI.isTypeLegal(
  18278. VecOp.getOperand(0).getValueType().getVectorElementType()))) {
  18279. // extract_vector_elt (concat_vectors v2i16:a, v2i16:b), 0
  18280. // -> extract_vector_elt a, 0
  18281. // extract_vector_elt (concat_vectors v2i16:a, v2i16:b), 1
  18282. // -> extract_vector_elt a, 1
  18283. // extract_vector_elt (concat_vectors v2i16:a, v2i16:b), 2
  18284. // -> extract_vector_elt b, 0
  18285. // extract_vector_elt (concat_vectors v2i16:a, v2i16:b), 3
  18286. // -> extract_vector_elt b, 1
  18287. SDLoc SL(N);
  18288. EVT ConcatVT = VecOp.getOperand(0).getValueType();
  18289. unsigned ConcatNumElts = ConcatVT.getVectorNumElements();
  18290. SDValue NewIdx = DAG.getConstant(Elt % ConcatNumElts, SL,
  18291. Index.getValueType());
  18292. SDValue ConcatOp = VecOp.getOperand(Elt / ConcatNumElts);
  18293. SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL,
  18294. ConcatVT.getVectorElementType(),
  18295. ConcatOp, NewIdx);
  18296. return DAG.getNode(ISD::BITCAST, SL, ScalarVT, Elt);
  18297. }
  18298. // Make sure we found a non-volatile load and the extractelement is
  18299. // the only use.
  18300. if (!LN0 || !LN0->hasNUsesOfValue(1,0) || !LN0->isSimple())
  18301. return SDValue();
  18302. // If Idx was -1 above, Elt is going to be -1, so just return undef.
  18303. if (Elt == -1)
  18304. return DAG.getUNDEF(LVT);
  18305. return scalarizeExtractedVectorLoad(N, VecVT, Index, LN0);
  18306. }
  18307. // Simplify (build_vec (ext )) to (bitcast (build_vec ))
  18308. SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
  18309. // We perform this optimization post type-legalization because
  18310. // the type-legalizer often scalarizes integer-promoted vectors.
  18311. // Performing this optimization before may create bit-casts which
  18312. // will be type-legalized to complex code sequences.
  18313. // We perform this optimization only before the operation legalizer because we
  18314. // may introduce illegal operations.
  18315. if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
  18316. return SDValue();
  18317. unsigned NumInScalars = N->getNumOperands();
  18318. SDLoc DL(N);
  18319. EVT VT = N->getValueType(0);
  18320. // Check to see if this is a BUILD_VECTOR of a bunch of values
  18321. // which come from any_extend or zero_extend nodes. If so, we can create
  18322. // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
  18323. // optimizations. We do not handle sign-extend because we can't fill the sign
  18324. // using shuffles.
  18325. EVT SourceType = MVT::Other;
  18326. bool AllAnyExt = true;
  18327. for (unsigned i = 0; i != NumInScalars; ++i) {
  18328. SDValue In = N->getOperand(i);
  18329. // Ignore undef inputs.
  18330. if (In.isUndef()) continue;
  18331. bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND;
  18332. bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
  18333. // Abort if the element is not an extension.
  18334. if (!ZeroExt && !AnyExt) {
  18335. SourceType = MVT::Other;
  18336. break;
  18337. }
  18338. // The input is a ZeroExt or AnyExt. Check the original type.
  18339. EVT InTy = In.getOperand(0).getValueType();
  18340. // Check that all of the widened source types are the same.
  18341. if (SourceType == MVT::Other)
  18342. // First time.
  18343. SourceType = InTy;
  18344. else if (InTy != SourceType) {
  18345. // Multiple income types. Abort.
  18346. SourceType = MVT::Other;
  18347. break;
  18348. }
  18349. // Check if all of the extends are ANY_EXTENDs.
  18350. AllAnyExt &= AnyExt;
  18351. }
  18352. // In order to have valid types, all of the inputs must be extended from the
  18353. // same source type and all of the inputs must be any or zero extend.
  18354. // Scalar sizes must be a power of two.
  18355. EVT OutScalarTy = VT.getScalarType();
  18356. bool ValidTypes = SourceType != MVT::Other &&
  18357. isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
  18358. isPowerOf2_32(SourceType.getSizeInBits());
  18359. // Create a new simpler BUILD_VECTOR sequence which other optimizations can
  18360. // turn into a single shuffle instruction.
  18361. if (!ValidTypes)
  18362. return SDValue();
  18363. // If we already have a splat buildvector, then don't fold it if it means
  18364. // introducing zeros.
  18365. if (!AllAnyExt && DAG.isSplatValue(SDValue(N, 0), /*AllowUndefs*/ true))
  18366. return SDValue();
  18367. bool isLE = DAG.getDataLayout().isLittleEndian();
  18368. unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
  18369. assert(ElemRatio > 1 && "Invalid element size ratio");
  18370. SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
  18371. DAG.getConstant(0, DL, SourceType);
  18372. unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
  18373. SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
  18374. // Populate the new build_vector
  18375. for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
  18376. SDValue Cast = N->getOperand(i);
  18377. assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
  18378. Cast.getOpcode() == ISD::ZERO_EXTEND ||
  18379. Cast.isUndef()) && "Invalid cast opcode");
  18380. SDValue In;
  18381. if (Cast.isUndef())
  18382. In = DAG.getUNDEF(SourceType);
  18383. else
  18384. In = Cast->getOperand(0);
  18385. unsigned Index = isLE ? (i * ElemRatio) :
  18386. (i * ElemRatio + (ElemRatio - 1));
  18387. assert(Index < Ops.size() && "Invalid index");
  18388. Ops[Index] = In;
  18389. }
  18390. // The type of the new BUILD_VECTOR node.
  18391. EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
  18392. assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
  18393. "Invalid vector size");
  18394. // Check if the new vector type is legal.
  18395. if (!isTypeLegal(VecVT) ||
  18396. (!TLI.isOperationLegal(ISD::BUILD_VECTOR, VecVT) &&
  18397. TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)))
  18398. return SDValue();
  18399. // Make the new BUILD_VECTOR.
  18400. SDValue BV = DAG.getBuildVector(VecVT, DL, Ops);
  18401. // The new BUILD_VECTOR node has the potential to be further optimized.
  18402. AddToWorklist(BV.getNode());
  18403. // Bitcast to the desired type.
  18404. return DAG.getBitcast(VT, BV);
  18405. }
  18406. // Simplify (build_vec (trunc $1)
  18407. // (trunc (srl $1 half-width))
  18408. // (trunc (srl $1 (2 * half-width))))
  18409. // to (bitcast $1)
  18410. SDValue DAGCombiner::reduceBuildVecTruncToBitCast(SDNode *N) {
  18411. assert(N->getOpcode() == ISD::BUILD_VECTOR && "Expected build vector");
  18412. // Only for little endian
  18413. if (!DAG.getDataLayout().isLittleEndian())
  18414. return SDValue();
  18415. SDLoc DL(N);
  18416. EVT VT = N->getValueType(0);
  18417. EVT OutScalarTy = VT.getScalarType();
  18418. uint64_t ScalarTypeBitsize = OutScalarTy.getSizeInBits();
  18419. // Only for power of two types to be sure that bitcast works well
  18420. if (!isPowerOf2_64(ScalarTypeBitsize))
  18421. return SDValue();
  18422. unsigned NumInScalars = N->getNumOperands();
  18423. // Look through bitcasts
  18424. auto PeekThroughBitcast = [](SDValue Op) {
  18425. if (Op.getOpcode() == ISD::BITCAST)
  18426. return Op.getOperand(0);
  18427. return Op;
  18428. };
  18429. // The source value where all the parts are extracted.
  18430. SDValue Src;
  18431. for (unsigned i = 0; i != NumInScalars; ++i) {
  18432. SDValue In = PeekThroughBitcast(N->getOperand(i));
  18433. // Ignore undef inputs.
  18434. if (In.isUndef()) continue;
  18435. if (In.getOpcode() != ISD::TRUNCATE)
  18436. return SDValue();
  18437. In = PeekThroughBitcast(In.getOperand(0));
  18438. if (In.getOpcode() != ISD::SRL) {
  18439. // For now only build_vec without shuffling, handle shifts here in the
  18440. // future.
  18441. if (i != 0)
  18442. return SDValue();
  18443. Src = In;
  18444. } else {
  18445. // In is SRL
  18446. SDValue part = PeekThroughBitcast(In.getOperand(0));
  18447. if (!Src) {
  18448. Src = part;
  18449. } else if (Src != part) {
  18450. // Vector parts do not stem from the same variable
  18451. return SDValue();
  18452. }
  18453. SDValue ShiftAmtVal = In.getOperand(1);
  18454. if (!isa<ConstantSDNode>(ShiftAmtVal))
  18455. return SDValue();
  18456. uint64_t ShiftAmt = In.getConstantOperandVal(1);
  18457. // The extracted value is not extracted at the right position
  18458. if (ShiftAmt != i * ScalarTypeBitsize)
  18459. return SDValue();
  18460. }
  18461. }
  18462. // Only cast if the size is the same
  18463. if (Src.getValueType().getSizeInBits() != VT.getSizeInBits())
  18464. return SDValue();
  18465. return DAG.getBitcast(VT, Src);
  18466. }
  18467. SDValue DAGCombiner::createBuildVecShuffle(const SDLoc &DL, SDNode *N,
  18468. ArrayRef<int> VectorMask,
  18469. SDValue VecIn1, SDValue VecIn2,
  18470. unsigned LeftIdx, bool DidSplitVec) {
  18471. SDValue ZeroIdx = DAG.getVectorIdxConstant(0, DL);
  18472. EVT VT = N->getValueType(0);
  18473. EVT InVT1 = VecIn1.getValueType();
  18474. EVT InVT2 = VecIn2.getNode() ? VecIn2.getValueType() : InVT1;
  18475. unsigned NumElems = VT.getVectorNumElements();
  18476. unsigned ShuffleNumElems = NumElems;
  18477. // If we artificially split a vector in two already, then the offsets in the
  18478. // operands will all be based off of VecIn1, even those in VecIn2.
  18479. unsigned Vec2Offset = DidSplitVec ? 0 : InVT1.getVectorNumElements();
  18480. uint64_t VTSize = VT.getFixedSizeInBits();
  18481. uint64_t InVT1Size = InVT1.getFixedSizeInBits();
  18482. uint64_t InVT2Size = InVT2.getFixedSizeInBits();
  18483. assert(InVT2Size <= InVT1Size &&
  18484. "Inputs must be sorted to be in non-increasing vector size order.");
  18485. // We can't generate a shuffle node with mismatched input and output types.
  18486. // Try to make the types match the type of the output.
  18487. if (InVT1 != VT || InVT2 != VT) {
  18488. if ((VTSize % InVT1Size == 0) && InVT1 == InVT2) {
  18489. // If the output vector length is a multiple of both input lengths,
  18490. // we can concatenate them and pad the rest with undefs.
  18491. unsigned NumConcats = VTSize / InVT1Size;
  18492. assert(NumConcats >= 2 && "Concat needs at least two inputs!");
  18493. SmallVector<SDValue, 2> ConcatOps(NumConcats, DAG.getUNDEF(InVT1));
  18494. ConcatOps[0] = VecIn1;
  18495. ConcatOps[1] = VecIn2 ? VecIn2 : DAG.getUNDEF(InVT1);
  18496. VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps);
  18497. VecIn2 = SDValue();
  18498. } else if (InVT1Size == VTSize * 2) {
  18499. if (!TLI.isExtractSubvectorCheap(VT, InVT1, NumElems))
  18500. return SDValue();
  18501. if (!VecIn2.getNode()) {
  18502. // If we only have one input vector, and it's twice the size of the
  18503. // output, split it in two.
  18504. VecIn2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, VecIn1,
  18505. DAG.getVectorIdxConstant(NumElems, DL));
  18506. VecIn1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, VecIn1, ZeroIdx);
  18507. // Since we now have shorter input vectors, adjust the offset of the
  18508. // second vector's start.
  18509. Vec2Offset = NumElems;
  18510. } else {
  18511. assert(InVT2Size <= InVT1Size &&
  18512. "Second input is not going to be larger than the first one.");
  18513. // VecIn1 is wider than the output, and we have another, possibly
  18514. // smaller input. Pad the smaller input with undefs, shuffle at the
  18515. // input vector width, and extract the output.
  18516. // The shuffle type is different than VT, so check legality again.
  18517. if (LegalOperations &&
  18518. !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, InVT1))
  18519. return SDValue();
  18520. // Legalizing INSERT_SUBVECTOR is tricky - you basically have to
  18521. // lower it back into a BUILD_VECTOR. So if the inserted type is
  18522. // illegal, don't even try.
  18523. if (InVT1 != InVT2) {
  18524. if (!TLI.isTypeLegal(InVT2))
  18525. return SDValue();
  18526. VecIn2 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, InVT1,
  18527. DAG.getUNDEF(InVT1), VecIn2, ZeroIdx);
  18528. }
  18529. ShuffleNumElems = NumElems * 2;
  18530. }
  18531. } else if (InVT2Size * 2 == VTSize && InVT1Size == VTSize) {
  18532. SmallVector<SDValue, 2> ConcatOps(2, DAG.getUNDEF(InVT2));
  18533. ConcatOps[0] = VecIn2;
  18534. VecIn2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps);
  18535. } else if (InVT1Size / VTSize > 1 && InVT1Size % VTSize == 0) {
  18536. if (!TLI.isExtractSubvectorCheap(VT, InVT1, NumElems) ||
  18537. !TLI.isTypeLegal(InVT1) || !TLI.isTypeLegal(InVT2))
  18538. return SDValue();
  18539. // If dest vector has less than two elements, then use shuffle and extract
  18540. // from larger regs will cost even more.
  18541. if (VT.getVectorNumElements() <= 2 || !VecIn2.getNode())
  18542. return SDValue();
  18543. assert(InVT2Size <= InVT1Size &&
  18544. "Second input is not going to be larger than the first one.");
  18545. // VecIn1 is wider than the output, and we have another, possibly
  18546. // smaller input. Pad the smaller input with undefs, shuffle at the
  18547. // input vector width, and extract the output.
  18548. // The shuffle type is different than VT, so check legality again.
  18549. if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, InVT1))
  18550. return SDValue();
  18551. if (InVT1 != InVT2) {
  18552. VecIn2 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, InVT1,
  18553. DAG.getUNDEF(InVT1), VecIn2, ZeroIdx);
  18554. }
  18555. ShuffleNumElems = InVT1Size / VTSize * NumElems;
  18556. } else {
  18557. // TODO: Support cases where the length mismatch isn't exactly by a
  18558. // factor of 2.
  18559. // TODO: Move this check upwards, so that if we have bad type
  18560. // mismatches, we don't create any DAG nodes.
  18561. return SDValue();
  18562. }
  18563. }
  18564. // Initialize mask to undef.
  18565. SmallVector<int, 8> Mask(ShuffleNumElems, -1);
  18566. // Only need to run up to the number of elements actually used, not the
  18567. // total number of elements in the shuffle - if we are shuffling a wider
  18568. // vector, the high lanes should be set to undef.
  18569. for (unsigned i = 0; i != NumElems; ++i) {
  18570. if (VectorMask[i] <= 0)
  18571. continue;
  18572. unsigned ExtIndex = N->getOperand(i).getConstantOperandVal(1);
  18573. if (VectorMask[i] == (int)LeftIdx) {
  18574. Mask[i] = ExtIndex;
  18575. } else if (VectorMask[i] == (int)LeftIdx + 1) {
  18576. Mask[i] = Vec2Offset + ExtIndex;
  18577. }
  18578. }
  18579. // The type the input vectors may have changed above.
  18580. InVT1 = VecIn1.getValueType();
  18581. // If we already have a VecIn2, it should have the same type as VecIn1.
  18582. // If we don't, get an undef/zero vector of the appropriate type.
  18583. VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(InVT1);
  18584. assert(InVT1 == VecIn2.getValueType() && "Unexpected second input type.");
  18585. SDValue Shuffle = DAG.getVectorShuffle(InVT1, DL, VecIn1, VecIn2, Mask);
  18586. if (ShuffleNumElems > NumElems)
  18587. Shuffle = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Shuffle, ZeroIdx);
  18588. return Shuffle;
  18589. }
  18590. static SDValue reduceBuildVecToShuffleWithZero(SDNode *BV, SelectionDAG &DAG) {
  18591. assert(BV->getOpcode() == ISD::BUILD_VECTOR && "Expected build vector");
  18592. // First, determine where the build vector is not undef.
  18593. // TODO: We could extend this to handle zero elements as well as undefs.
  18594. int NumBVOps = BV->getNumOperands();
  18595. int ZextElt = -1;
  18596. for (int i = 0; i != NumBVOps; ++i) {
  18597. SDValue Op = BV->getOperand(i);
  18598. if (Op.isUndef())
  18599. continue;
  18600. if (ZextElt == -1)
  18601. ZextElt = i;
  18602. else
  18603. return SDValue();
  18604. }
  18605. // Bail out if there's no non-undef element.
  18606. if (ZextElt == -1)
  18607. return SDValue();
  18608. // The build vector contains some number of undef elements and exactly
  18609. // one other element. That other element must be a zero-extended scalar
  18610. // extracted from a vector at a constant index to turn this into a shuffle.
  18611. // Also, require that the build vector does not implicitly truncate/extend
  18612. // its elements.
  18613. // TODO: This could be enhanced to allow ANY_EXTEND as well as ZERO_EXTEND.
  18614. EVT VT = BV->getValueType(0);
  18615. SDValue Zext = BV->getOperand(ZextElt);
  18616. if (Zext.getOpcode() != ISD::ZERO_EXTEND || !Zext.hasOneUse() ||
  18617. Zext.getOperand(0).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
  18618. !isa<ConstantSDNode>(Zext.getOperand(0).getOperand(1)) ||
  18619. Zext.getValueSizeInBits() != VT.getScalarSizeInBits())
  18620. return SDValue();
  18621. // The zero-extend must be a multiple of the source size, and we must be
  18622. // building a vector of the same size as the source of the extract element.
  18623. SDValue Extract = Zext.getOperand(0);
  18624. unsigned DestSize = Zext.getValueSizeInBits();
  18625. unsigned SrcSize = Extract.getValueSizeInBits();
  18626. if (DestSize % SrcSize != 0 ||
  18627. Extract.getOperand(0).getValueSizeInBits() != VT.getSizeInBits())
  18628. return SDValue();
  18629. // Create a shuffle mask that will combine the extracted element with zeros
  18630. // and undefs.
  18631. int ZextRatio = DestSize / SrcSize;
  18632. int NumMaskElts = NumBVOps * ZextRatio;
  18633. SmallVector<int, 32> ShufMask(NumMaskElts, -1);
  18634. for (int i = 0; i != NumMaskElts; ++i) {
  18635. if (i / ZextRatio == ZextElt) {
  18636. // The low bits of the (potentially translated) extracted element map to
  18637. // the source vector. The high bits map to zero. We will use a zero vector
  18638. // as the 2nd source operand of the shuffle, so use the 1st element of
  18639. // that vector (mask value is number-of-elements) for the high bits.
  18640. if (i % ZextRatio == 0)
  18641. ShufMask[i] = Extract.getConstantOperandVal(1);
  18642. else
  18643. ShufMask[i] = NumMaskElts;
  18644. }
  18645. // Undef elements of the build vector remain undef because we initialize
  18646. // the shuffle mask with -1.
  18647. }
  18648. // buildvec undef, ..., (zext (extractelt V, IndexC)), undef... -->
  18649. // bitcast (shuffle V, ZeroVec, VectorMask)
  18650. SDLoc DL(BV);
  18651. EVT VecVT = Extract.getOperand(0).getValueType();
  18652. SDValue ZeroVec = DAG.getConstant(0, DL, VecVT);
  18653. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  18654. SDValue Shuf = TLI.buildLegalVectorShuffle(VecVT, DL, Extract.getOperand(0),
  18655. ZeroVec, ShufMask, DAG);
  18656. if (!Shuf)
  18657. return SDValue();
  18658. return DAG.getBitcast(VT, Shuf);
  18659. }
  18660. // FIXME: promote to STLExtras.
  18661. template <typename R, typename T>
  18662. static auto getFirstIndexOf(R &&Range, const T &Val) {
  18663. auto I = find(Range, Val);
  18664. if (I == Range.end())
  18665. return static_cast<decltype(std::distance(Range.begin(), I))>(-1);
  18666. return std::distance(Range.begin(), I);
  18667. }
  18668. // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
  18669. // operations. If the types of the vectors we're extracting from allow it,
  18670. // turn this into a vector_shuffle node.
  18671. SDValue DAGCombiner::reduceBuildVecToShuffle(SDNode *N) {
  18672. SDLoc DL(N);
  18673. EVT VT = N->getValueType(0);
  18674. // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
  18675. if (!isTypeLegal(VT))
  18676. return SDValue();
  18677. if (SDValue V = reduceBuildVecToShuffleWithZero(N, DAG))
  18678. return V;
  18679. // May only combine to shuffle after legalize if shuffle is legal.
  18680. if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT))
  18681. return SDValue();
  18682. bool UsesZeroVector = false;
  18683. unsigned NumElems = N->getNumOperands();
  18684. // Record, for each element of the newly built vector, which input vector
  18685. // that element comes from. -1 stands for undef, 0 for the zero vector,
  18686. // and positive values for the input vectors.
  18687. // VectorMask maps each element to its vector number, and VecIn maps vector
  18688. // numbers to their initial SDValues.
  18689. SmallVector<int, 8> VectorMask(NumElems, -1);
  18690. SmallVector<SDValue, 8> VecIn;
  18691. VecIn.push_back(SDValue());
  18692. for (unsigned i = 0; i != NumElems; ++i) {
  18693. SDValue Op = N->getOperand(i);
  18694. if (Op.isUndef())
  18695. continue;
  18696. // See if we can use a blend with a zero vector.
  18697. // TODO: Should we generalize this to a blend with an arbitrary constant
  18698. // vector?
  18699. if (isNullConstant(Op) || isNullFPConstant(Op)) {
  18700. UsesZeroVector = true;
  18701. VectorMask[i] = 0;
  18702. continue;
  18703. }
  18704. // Not an undef or zero. If the input is something other than an
  18705. // EXTRACT_VECTOR_ELT with an in-range constant index, bail out.
  18706. if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
  18707. !isa<ConstantSDNode>(Op.getOperand(1)))
  18708. return SDValue();
  18709. SDValue ExtractedFromVec = Op.getOperand(0);
  18710. if (ExtractedFromVec.getValueType().isScalableVector())
  18711. return SDValue();
  18712. const APInt &ExtractIdx = Op.getConstantOperandAPInt(1);
  18713. if (ExtractIdx.uge(ExtractedFromVec.getValueType().getVectorNumElements()))
  18714. return SDValue();
  18715. // All inputs must have the same element type as the output.
  18716. if (VT.getVectorElementType() !=
  18717. ExtractedFromVec.getValueType().getVectorElementType())
  18718. return SDValue();
  18719. // Have we seen this input vector before?
  18720. // The vectors are expected to be tiny (usually 1 or 2 elements), so using
  18721. // a map back from SDValues to numbers isn't worth it.
  18722. int Idx = getFirstIndexOf(VecIn, ExtractedFromVec);
  18723. if (Idx == -1) { // A new source vector?
  18724. Idx = VecIn.size();
  18725. VecIn.push_back(ExtractedFromVec);
  18726. }
  18727. VectorMask[i] = Idx;
  18728. }
  18729. // If we didn't find at least one input vector, bail out.
  18730. if (VecIn.size() < 2)
  18731. return SDValue();
  18732. // If all the Operands of BUILD_VECTOR extract from same
  18733. // vector, then split the vector efficiently based on the maximum
  18734. // vector access index and adjust the VectorMask and
  18735. // VecIn accordingly.
  18736. bool DidSplitVec = false;
  18737. if (VecIn.size() == 2) {
  18738. unsigned MaxIndex = 0;
  18739. unsigned NearestPow2 = 0;
  18740. SDValue Vec = VecIn.back();
  18741. EVT InVT = Vec.getValueType();
  18742. SmallVector<unsigned, 8> IndexVec(NumElems, 0);
  18743. for (unsigned i = 0; i < NumElems; i++) {
  18744. if (VectorMask[i] <= 0)
  18745. continue;
  18746. unsigned Index = N->getOperand(i).getConstantOperandVal(1);
  18747. IndexVec[i] = Index;
  18748. MaxIndex = std::max(MaxIndex, Index);
  18749. }
  18750. NearestPow2 = PowerOf2Ceil(MaxIndex);
  18751. if (InVT.isSimple() && NearestPow2 > 2 && MaxIndex < NearestPow2 &&
  18752. NumElems * 2 < NearestPow2) {
  18753. unsigned SplitSize = NearestPow2 / 2;
  18754. EVT SplitVT = EVT::getVectorVT(*DAG.getContext(),
  18755. InVT.getVectorElementType(), SplitSize);
  18756. if (TLI.isTypeLegal(SplitVT) &&
  18757. SplitSize + SplitVT.getVectorNumElements() <=
  18758. InVT.getVectorNumElements()) {
  18759. SDValue VecIn2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, Vec,
  18760. DAG.getVectorIdxConstant(SplitSize, DL));
  18761. SDValue VecIn1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, Vec,
  18762. DAG.getVectorIdxConstant(0, DL));
  18763. VecIn.pop_back();
  18764. VecIn.push_back(VecIn1);
  18765. VecIn.push_back(VecIn2);
  18766. DidSplitVec = true;
  18767. for (unsigned i = 0; i < NumElems; i++) {
  18768. if (VectorMask[i] <= 0)
  18769. continue;
  18770. VectorMask[i] = (IndexVec[i] < SplitSize) ? 1 : 2;
  18771. }
  18772. }
  18773. }
  18774. }
  18775. // Sort input vectors by decreasing vector element count,
  18776. // while preserving the relative order of equally-sized vectors.
  18777. // Note that we keep the first "implicit zero vector as-is.
  18778. SmallVector<SDValue, 8> SortedVecIn(VecIn);
  18779. llvm::stable_sort(MutableArrayRef<SDValue>(SortedVecIn).drop_front(),
  18780. [](const SDValue &a, const SDValue &b) {
  18781. return a.getValueType().getVectorNumElements() >
  18782. b.getValueType().getVectorNumElements();
  18783. });
  18784. // We now also need to rebuild the VectorMask, because it referenced element
  18785. // order in VecIn, and we just sorted them.
  18786. for (int &SourceVectorIndex : VectorMask) {
  18787. if (SourceVectorIndex <= 0)
  18788. continue;
  18789. unsigned Idx = getFirstIndexOf(SortedVecIn, VecIn[SourceVectorIndex]);
  18790. assert(Idx > 0 && Idx < SortedVecIn.size() &&
  18791. VecIn[SourceVectorIndex] == SortedVecIn[Idx] && "Remapping failure");
  18792. SourceVectorIndex = Idx;
  18793. }
  18794. VecIn = std::move(SortedVecIn);
  18795. // TODO: Should this fire if some of the input vectors has illegal type (like
  18796. // it does now), or should we let legalization run its course first?
  18797. // Shuffle phase:
  18798. // Take pairs of vectors, and shuffle them so that the result has elements
  18799. // from these vectors in the correct places.
  18800. // For example, given:
  18801. // t10: i32 = extract_vector_elt t1, Constant:i64<0>
  18802. // t11: i32 = extract_vector_elt t2, Constant:i64<0>
  18803. // t12: i32 = extract_vector_elt t3, Constant:i64<0>
  18804. // t13: i32 = extract_vector_elt t1, Constant:i64<1>
  18805. // t14: v4i32 = BUILD_VECTOR t10, t11, t12, t13
  18806. // We will generate:
  18807. // t20: v4i32 = vector_shuffle<0,4,u,1> t1, t2
  18808. // t21: v4i32 = vector_shuffle<u,u,0,u> t3, undef
  18809. SmallVector<SDValue, 4> Shuffles;
  18810. for (unsigned In = 0, Len = (VecIn.size() / 2); In < Len; ++In) {
  18811. unsigned LeftIdx = 2 * In + 1;
  18812. SDValue VecLeft = VecIn[LeftIdx];
  18813. SDValue VecRight =
  18814. (LeftIdx + 1) < VecIn.size() ? VecIn[LeftIdx + 1] : SDValue();
  18815. if (SDValue Shuffle = createBuildVecShuffle(DL, N, VectorMask, VecLeft,
  18816. VecRight, LeftIdx, DidSplitVec))
  18817. Shuffles.push_back(Shuffle);
  18818. else
  18819. return SDValue();
  18820. }
  18821. // If we need the zero vector as an "ingredient" in the blend tree, add it
  18822. // to the list of shuffles.
  18823. if (UsesZeroVector)
  18824. Shuffles.push_back(VT.isInteger() ? DAG.getConstant(0, DL, VT)
  18825. : DAG.getConstantFP(0.0, DL, VT));
  18826. // If we only have one shuffle, we're done.
  18827. if (Shuffles.size() == 1)
  18828. return Shuffles[0];
  18829. // Update the vector mask to point to the post-shuffle vectors.
  18830. for (int &Vec : VectorMask)
  18831. if (Vec == 0)
  18832. Vec = Shuffles.size() - 1;
  18833. else
  18834. Vec = (Vec - 1) / 2;
  18835. // More than one shuffle. Generate a binary tree of blends, e.g. if from
  18836. // the previous step we got the set of shuffles t10, t11, t12, t13, we will
  18837. // generate:
  18838. // t10: v8i32 = vector_shuffle<0,8,u,u,u,u,u,u> t1, t2
  18839. // t11: v8i32 = vector_shuffle<u,u,0,8,u,u,u,u> t3, t4
  18840. // t12: v8i32 = vector_shuffle<u,u,u,u,0,8,u,u> t5, t6
  18841. // t13: v8i32 = vector_shuffle<u,u,u,u,u,u,0,8> t7, t8
  18842. // t20: v8i32 = vector_shuffle<0,1,10,11,u,u,u,u> t10, t11
  18843. // t21: v8i32 = vector_shuffle<u,u,u,u,4,5,14,15> t12, t13
  18844. // t30: v8i32 = vector_shuffle<0,1,2,3,12,13,14,15> t20, t21
  18845. // Make sure the initial size of the shuffle list is even.
  18846. if (Shuffles.size() % 2)
  18847. Shuffles.push_back(DAG.getUNDEF(VT));
  18848. for (unsigned CurSize = Shuffles.size(); CurSize > 1; CurSize /= 2) {
  18849. if (CurSize % 2) {
  18850. Shuffles[CurSize] = DAG.getUNDEF(VT);
  18851. CurSize++;
  18852. }
  18853. for (unsigned In = 0, Len = CurSize / 2; In < Len; ++In) {
  18854. int Left = 2 * In;
  18855. int Right = 2 * In + 1;
  18856. SmallVector<int, 8> Mask(NumElems, -1);
  18857. SDValue L = Shuffles[Left];
  18858. ArrayRef<int> LMask;
  18859. bool IsLeftShuffle = L.getOpcode() == ISD::VECTOR_SHUFFLE &&
  18860. L.use_empty() && L.getOperand(1).isUndef() &&
  18861. L.getOperand(0).getValueType() == L.getValueType();
  18862. if (IsLeftShuffle) {
  18863. LMask = cast<ShuffleVectorSDNode>(L.getNode())->getMask();
  18864. L = L.getOperand(0);
  18865. }
  18866. SDValue R = Shuffles[Right];
  18867. ArrayRef<int> RMask;
  18868. bool IsRightShuffle = R.getOpcode() == ISD::VECTOR_SHUFFLE &&
  18869. R.use_empty() && R.getOperand(1).isUndef() &&
  18870. R.getOperand(0).getValueType() == R.getValueType();
  18871. if (IsRightShuffle) {
  18872. RMask = cast<ShuffleVectorSDNode>(R.getNode())->getMask();
  18873. R = R.getOperand(0);
  18874. }
  18875. for (unsigned I = 0; I != NumElems; ++I) {
  18876. if (VectorMask[I] == Left) {
  18877. Mask[I] = I;
  18878. if (IsLeftShuffle)
  18879. Mask[I] = LMask[I];
  18880. VectorMask[I] = In;
  18881. } else if (VectorMask[I] == Right) {
  18882. Mask[I] = I + NumElems;
  18883. if (IsRightShuffle)
  18884. Mask[I] = RMask[I] + NumElems;
  18885. VectorMask[I] = In;
  18886. }
  18887. }
  18888. Shuffles[In] = DAG.getVectorShuffle(VT, DL, L, R, Mask);
  18889. }
  18890. }
  18891. return Shuffles[0];
  18892. }
  18893. // Try to turn a build vector of zero extends of extract vector elts into a
  18894. // a vector zero extend and possibly an extract subvector.
  18895. // TODO: Support sign extend?
  18896. // TODO: Allow undef elements?
  18897. SDValue DAGCombiner::convertBuildVecZextToZext(SDNode *N) {
  18898. if (LegalOperations)
  18899. return SDValue();
  18900. EVT VT = N->getValueType(0);
  18901. bool FoundZeroExtend = false;
  18902. SDValue Op0 = N->getOperand(0);
  18903. auto checkElem = [&](SDValue Op) -> int64_t {
  18904. unsigned Opc = Op.getOpcode();
  18905. FoundZeroExtend |= (Opc == ISD::ZERO_EXTEND);
  18906. if ((Opc == ISD::ZERO_EXTEND || Opc == ISD::ANY_EXTEND) &&
  18907. Op.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
  18908. Op0.getOperand(0).getOperand(0) == Op.getOperand(0).getOperand(0))
  18909. if (auto *C = dyn_cast<ConstantSDNode>(Op.getOperand(0).getOperand(1)))
  18910. return C->getZExtValue();
  18911. return -1;
  18912. };
  18913. // Make sure the first element matches
  18914. // (zext (extract_vector_elt X, C))
  18915. // Offset must be a constant multiple of the
  18916. // known-minimum vector length of the result type.
  18917. int64_t Offset = checkElem(Op0);
  18918. if (Offset < 0 || (Offset % VT.getVectorNumElements()) != 0)
  18919. return SDValue();
  18920. unsigned NumElems = N->getNumOperands();
  18921. SDValue In = Op0.getOperand(0).getOperand(0);
  18922. EVT InSVT = In.getValueType().getScalarType();
  18923. EVT InVT = EVT::getVectorVT(*DAG.getContext(), InSVT, NumElems);
  18924. // Don't create an illegal input type after type legalization.
  18925. if (LegalTypes && !TLI.isTypeLegal(InVT))
  18926. return SDValue();
  18927. // Ensure all the elements come from the same vector and are adjacent.
  18928. for (unsigned i = 1; i != NumElems; ++i) {
  18929. if ((Offset + i) != checkElem(N->getOperand(i)))
  18930. return SDValue();
  18931. }
  18932. SDLoc DL(N);
  18933. In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InVT, In,
  18934. Op0.getOperand(0).getOperand(1));
  18935. return DAG.getNode(FoundZeroExtend ? ISD::ZERO_EXTEND : ISD::ANY_EXTEND, DL,
  18936. VT, In);
  18937. }
  18938. // If this is a very simple BUILD_VECTOR with first element being a ZERO_EXTEND,
  18939. // and all other elements being constant zero's, granularize the BUILD_VECTOR's
  18940. // element width, absorbing the ZERO_EXTEND, turning it into a constant zero op.
  18941. // This patten can appear during legalization.
  18942. //
  18943. // NOTE: This can be generalized to allow more than a single
  18944. // non-constant-zero op, UNDEF's, and to be KnownBits-based,
  18945. SDValue DAGCombiner::convertBuildVecZextToBuildVecWithZeros(SDNode *N) {
  18946. // Don't run this after legalization. Targets may have other preferences.
  18947. if (Level >= AfterLegalizeDAG)
  18948. return SDValue();
  18949. // FIXME: support big-endian.
  18950. if (DAG.getDataLayout().isBigEndian())
  18951. return SDValue();
  18952. EVT VT = N->getValueType(0);
  18953. EVT OpVT = N->getOperand(0).getValueType();
  18954. assert(!VT.isScalableVector() && "Encountered scalable BUILD_VECTOR?");
  18955. EVT OpIntVT = EVT::getIntegerVT(*DAG.getContext(), OpVT.getSizeInBits());
  18956. if (!TLI.isTypeLegal(OpIntVT) ||
  18957. (LegalOperations && !TLI.isOperationLegalOrCustom(ISD::BITCAST, OpIntVT)))
  18958. return SDValue();
  18959. unsigned EltBitwidth = VT.getScalarSizeInBits();
  18960. // NOTE: the actual width of operands may be wider than that!
  18961. // Analyze all operands of this BUILD_VECTOR. What is the largest number of
  18962. // active bits they all have? We'll want to truncate them all to that width.
  18963. unsigned ActiveBits = 0;
  18964. APInt KnownZeroOps(VT.getVectorNumElements(), 0);
  18965. for (auto I : enumerate(N->ops())) {
  18966. SDValue Op = I.value();
  18967. // FIXME: support UNDEF elements?
  18968. if (auto *Cst = dyn_cast<ConstantSDNode>(Op)) {
  18969. unsigned OpActiveBits =
  18970. Cst->getAPIntValue().trunc(EltBitwidth).getActiveBits();
  18971. if (OpActiveBits == 0) {
  18972. KnownZeroOps.setBit(I.index());
  18973. continue;
  18974. }
  18975. // Profitability check: don't allow non-zero constant operands.
  18976. return SDValue();
  18977. }
  18978. // Profitability check: there must only be a single non-zero operand,
  18979. // and it must be the first operand of the BUILD_VECTOR.
  18980. if (I.index() != 0)
  18981. return SDValue();
  18982. // The operand must be a zero-extension itself.
  18983. // FIXME: this could be generalized to known leading zeros check.
  18984. if (Op.getOpcode() != ISD::ZERO_EXTEND)
  18985. return SDValue();
  18986. unsigned CurrActiveBits =
  18987. Op.getOperand(0).getValueSizeInBits().getFixedValue();
  18988. assert(!ActiveBits && "Already encountered non-constant-zero operand?");
  18989. ActiveBits = CurrActiveBits;
  18990. // We want to at least halve the element size.
  18991. if (2 * ActiveBits > EltBitwidth)
  18992. return SDValue();
  18993. }
  18994. // This BUILD_VECTOR must have at least one non-constant-zero operand.
  18995. if (ActiveBits == 0)
  18996. return SDValue();
  18997. // We have EltBitwidth bits, the *minimal* chunk size is ActiveBits,
  18998. // into how many chunks can we split our element width?
  18999. EVT NewScalarIntVT, NewIntVT;
  19000. std::optional<unsigned> Factor;
  19001. // We can split the element into at least two chunks, but not into more
  19002. // than |_ EltBitwidth / ActiveBits _| chunks. Find a largest split factor
  19003. // for which the element width is a multiple of it,
  19004. // and the resulting types/operations on that chunk width are legal.
  19005. assert(2 * ActiveBits <= EltBitwidth &&
  19006. "We know that half or less bits of the element are active.");
  19007. for (unsigned Scale = EltBitwidth / ActiveBits; Scale >= 2; --Scale) {
  19008. if (EltBitwidth % Scale != 0)
  19009. continue;
  19010. unsigned ChunkBitwidth = EltBitwidth / Scale;
  19011. assert(ChunkBitwidth >= ActiveBits && "As per starting point.");
  19012. NewScalarIntVT = EVT::getIntegerVT(*DAG.getContext(), ChunkBitwidth);
  19013. NewIntVT = EVT::getVectorVT(*DAG.getContext(), NewScalarIntVT,
  19014. Scale * N->getNumOperands());
  19015. if (!TLI.isTypeLegal(NewScalarIntVT) || !TLI.isTypeLegal(NewIntVT) ||
  19016. (LegalOperations &&
  19017. !(TLI.isOperationLegalOrCustom(ISD::TRUNCATE, NewScalarIntVT) &&
  19018. TLI.isOperationLegalOrCustom(ISD::BUILD_VECTOR, NewIntVT))))
  19019. continue;
  19020. Factor = Scale;
  19021. break;
  19022. }
  19023. if (!Factor)
  19024. return SDValue();
  19025. SDLoc DL(N);
  19026. SDValue ZeroOp = DAG.getConstant(0, DL, NewScalarIntVT);
  19027. // Recreate the BUILD_VECTOR, with elements now being Factor times smaller.
  19028. SmallVector<SDValue, 16> NewOps;
  19029. NewOps.reserve(NewIntVT.getVectorNumElements());
  19030. for (auto I : enumerate(N->ops())) {
  19031. SDValue Op = I.value();
  19032. assert(!Op.isUndef() && "FIXME: after allowing UNDEF's, handle them here.");
  19033. unsigned SrcOpIdx = I.index();
  19034. if (KnownZeroOps[SrcOpIdx]) {
  19035. NewOps.append(*Factor, ZeroOp);
  19036. continue;
  19037. }
  19038. Op = DAG.getBitcast(OpIntVT, Op);
  19039. Op = DAG.getNode(ISD::TRUNCATE, DL, NewScalarIntVT, Op);
  19040. NewOps.emplace_back(Op);
  19041. NewOps.append(*Factor - 1, ZeroOp);
  19042. }
  19043. assert(NewOps.size() == NewIntVT.getVectorNumElements());
  19044. SDValue NewBV = DAG.getBuildVector(NewIntVT, DL, NewOps);
  19045. NewBV = DAG.getBitcast(VT, NewBV);
  19046. return NewBV;
  19047. }
  19048. SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
  19049. EVT VT = N->getValueType(0);
  19050. // A vector built entirely of undefs is undef.
  19051. if (ISD::allOperandsUndef(N))
  19052. return DAG.getUNDEF(VT);
  19053. // If this is a splat of a bitcast from another vector, change to a
  19054. // concat_vector.
  19055. // For example:
  19056. // (build_vector (i64 (bitcast (v2i32 X))), (i64 (bitcast (v2i32 X)))) ->
  19057. // (v2i64 (bitcast (concat_vectors (v2i32 X), (v2i32 X))))
  19058. //
  19059. // If X is a build_vector itself, the concat can become a larger build_vector.
  19060. // TODO: Maybe this is useful for non-splat too?
  19061. if (!LegalOperations) {
  19062. if (SDValue Splat = cast<BuildVectorSDNode>(N)->getSplatValue()) {
  19063. Splat = peekThroughBitcasts(Splat);
  19064. EVT SrcVT = Splat.getValueType();
  19065. if (SrcVT.isVector()) {
  19066. unsigned NumElts = N->getNumOperands() * SrcVT.getVectorNumElements();
  19067. EVT NewVT = EVT::getVectorVT(*DAG.getContext(),
  19068. SrcVT.getVectorElementType(), NumElts);
  19069. if (!LegalTypes || TLI.isTypeLegal(NewVT)) {
  19070. SmallVector<SDValue, 8> Ops(N->getNumOperands(), Splat);
  19071. SDValue Concat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N),
  19072. NewVT, Ops);
  19073. return DAG.getBitcast(VT, Concat);
  19074. }
  19075. }
  19076. }
  19077. }
  19078. // Check if we can express BUILD VECTOR via subvector extract.
  19079. if (!LegalTypes && (N->getNumOperands() > 1)) {
  19080. SDValue Op0 = N->getOperand(0);
  19081. auto checkElem = [&](SDValue Op) -> uint64_t {
  19082. if ((Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT) &&
  19083. (Op0.getOperand(0) == Op.getOperand(0)))
  19084. if (auto CNode = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
  19085. return CNode->getZExtValue();
  19086. return -1;
  19087. };
  19088. int Offset = checkElem(Op0);
  19089. for (unsigned i = 0; i < N->getNumOperands(); ++i) {
  19090. if (Offset + i != checkElem(N->getOperand(i))) {
  19091. Offset = -1;
  19092. break;
  19093. }
  19094. }
  19095. if ((Offset == 0) &&
  19096. (Op0.getOperand(0).getValueType() == N->getValueType(0)))
  19097. return Op0.getOperand(0);
  19098. if ((Offset != -1) &&
  19099. ((Offset % N->getValueType(0).getVectorNumElements()) ==
  19100. 0)) // IDX must be multiple of output size.
  19101. return DAG.getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(N), N->getValueType(0),
  19102. Op0.getOperand(0), Op0.getOperand(1));
  19103. }
  19104. if (SDValue V = convertBuildVecZextToZext(N))
  19105. return V;
  19106. if (SDValue V = convertBuildVecZextToBuildVecWithZeros(N))
  19107. return V;
  19108. if (SDValue V = reduceBuildVecExtToExtBuildVec(N))
  19109. return V;
  19110. if (SDValue V = reduceBuildVecTruncToBitCast(N))
  19111. return V;
  19112. if (SDValue V = reduceBuildVecToShuffle(N))
  19113. return V;
  19114. // A splat of a single element is a SPLAT_VECTOR if supported on the target.
  19115. // Do this late as some of the above may replace the splat.
  19116. if (TLI.getOperationAction(ISD::SPLAT_VECTOR, VT) != TargetLowering::Expand)
  19117. if (SDValue V = cast<BuildVectorSDNode>(N)->getSplatValue()) {
  19118. assert(!V.isUndef() && "Splat of undef should have been handled earlier");
  19119. return DAG.getNode(ISD::SPLAT_VECTOR, SDLoc(N), VT, V);
  19120. }
  19121. return SDValue();
  19122. }
  19123. static SDValue combineConcatVectorOfScalars(SDNode *N, SelectionDAG &DAG) {
  19124. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  19125. EVT OpVT = N->getOperand(0).getValueType();
  19126. // If the operands are legal vectors, leave them alone.
  19127. if (TLI.isTypeLegal(OpVT))
  19128. return SDValue();
  19129. SDLoc DL(N);
  19130. EVT VT = N->getValueType(0);
  19131. SmallVector<SDValue, 8> Ops;
  19132. EVT SVT = EVT::getIntegerVT(*DAG.getContext(), OpVT.getSizeInBits());
  19133. SDValue ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
  19134. // Keep track of what we encounter.
  19135. bool AnyInteger = false;
  19136. bool AnyFP = false;
  19137. for (const SDValue &Op : N->ops()) {
  19138. if (ISD::BITCAST == Op.getOpcode() &&
  19139. !Op.getOperand(0).getValueType().isVector())
  19140. Ops.push_back(Op.getOperand(0));
  19141. else if (ISD::UNDEF == Op.getOpcode())
  19142. Ops.push_back(ScalarUndef);
  19143. else
  19144. return SDValue();
  19145. // Note whether we encounter an integer or floating point scalar.
  19146. // If it's neither, bail out, it could be something weird like x86mmx.
  19147. EVT LastOpVT = Ops.back().getValueType();
  19148. if (LastOpVT.isFloatingPoint())
  19149. AnyFP = true;
  19150. else if (LastOpVT.isInteger())
  19151. AnyInteger = true;
  19152. else
  19153. return SDValue();
  19154. }
  19155. // If any of the operands is a floating point scalar bitcast to a vector,
  19156. // use floating point types throughout, and bitcast everything.
  19157. // Replace UNDEFs by another scalar UNDEF node, of the final desired type.
  19158. if (AnyFP) {
  19159. SVT = EVT::getFloatingPointVT(OpVT.getSizeInBits());
  19160. ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
  19161. if (AnyInteger) {
  19162. for (SDValue &Op : Ops) {
  19163. if (Op.getValueType() == SVT)
  19164. continue;
  19165. if (Op.isUndef())
  19166. Op = ScalarUndef;
  19167. else
  19168. Op = DAG.getBitcast(SVT, Op);
  19169. }
  19170. }
  19171. }
  19172. EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SVT,
  19173. VT.getSizeInBits() / SVT.getSizeInBits());
  19174. return DAG.getBitcast(VT, DAG.getBuildVector(VecVT, DL, Ops));
  19175. }
  19176. // Attempt to merge nested concat_vectors/undefs.
  19177. // Fold concat_vectors(concat_vectors(x,y,z,w),u,u,concat_vectors(a,b,c,d))
  19178. // --> concat_vectors(x,y,z,w,u,u,u,u,u,u,u,u,a,b,c,d)
  19179. static SDValue combineConcatVectorOfConcatVectors(SDNode *N,
  19180. SelectionDAG &DAG) {
  19181. EVT VT = N->getValueType(0);
  19182. // Ensure we're concatenating UNDEF and CONCAT_VECTORS nodes of similar types.
  19183. EVT SubVT;
  19184. SDValue FirstConcat;
  19185. for (const SDValue &Op : N->ops()) {
  19186. if (Op.isUndef())
  19187. continue;
  19188. if (Op.getOpcode() != ISD::CONCAT_VECTORS)
  19189. return SDValue();
  19190. if (!FirstConcat) {
  19191. SubVT = Op.getOperand(0).getValueType();
  19192. if (!DAG.getTargetLoweringInfo().isTypeLegal(SubVT))
  19193. return SDValue();
  19194. FirstConcat = Op;
  19195. continue;
  19196. }
  19197. if (SubVT != Op.getOperand(0).getValueType())
  19198. return SDValue();
  19199. }
  19200. assert(FirstConcat && "Concat of all-undefs found");
  19201. SmallVector<SDValue> ConcatOps;
  19202. for (const SDValue &Op : N->ops()) {
  19203. if (Op.isUndef()) {
  19204. ConcatOps.append(FirstConcat->getNumOperands(), DAG.getUNDEF(SubVT));
  19205. continue;
  19206. }
  19207. ConcatOps.append(Op->op_begin(), Op->op_end());
  19208. }
  19209. return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, ConcatOps);
  19210. }
  19211. // Check to see if this is a CONCAT_VECTORS of a bunch of EXTRACT_SUBVECTOR
  19212. // operations. If so, and if the EXTRACT_SUBVECTOR vector inputs come from at
  19213. // most two distinct vectors the same size as the result, attempt to turn this
  19214. // into a legal shuffle.
  19215. static SDValue combineConcatVectorOfExtracts(SDNode *N, SelectionDAG &DAG) {
  19216. EVT VT = N->getValueType(0);
  19217. EVT OpVT = N->getOperand(0).getValueType();
  19218. // We currently can't generate an appropriate shuffle for a scalable vector.
  19219. if (VT.isScalableVector())
  19220. return SDValue();
  19221. int NumElts = VT.getVectorNumElements();
  19222. int NumOpElts = OpVT.getVectorNumElements();
  19223. SDValue SV0 = DAG.getUNDEF(VT), SV1 = DAG.getUNDEF(VT);
  19224. SmallVector<int, 8> Mask;
  19225. for (SDValue Op : N->ops()) {
  19226. Op = peekThroughBitcasts(Op);
  19227. // UNDEF nodes convert to UNDEF shuffle mask values.
  19228. if (Op.isUndef()) {
  19229. Mask.append((unsigned)NumOpElts, -1);
  19230. continue;
  19231. }
  19232. if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
  19233. return SDValue();
  19234. // What vector are we extracting the subvector from and at what index?
  19235. SDValue ExtVec = Op.getOperand(0);
  19236. int ExtIdx = Op.getConstantOperandVal(1);
  19237. // We want the EVT of the original extraction to correctly scale the
  19238. // extraction index.
  19239. EVT ExtVT = ExtVec.getValueType();
  19240. ExtVec = peekThroughBitcasts(ExtVec);
  19241. // UNDEF nodes convert to UNDEF shuffle mask values.
  19242. if (ExtVec.isUndef()) {
  19243. Mask.append((unsigned)NumOpElts, -1);
  19244. continue;
  19245. }
  19246. // Ensure that we are extracting a subvector from a vector the same
  19247. // size as the result.
  19248. if (ExtVT.getSizeInBits() != VT.getSizeInBits())
  19249. return SDValue();
  19250. // Scale the subvector index to account for any bitcast.
  19251. int NumExtElts = ExtVT.getVectorNumElements();
  19252. if (0 == (NumExtElts % NumElts))
  19253. ExtIdx /= (NumExtElts / NumElts);
  19254. else if (0 == (NumElts % NumExtElts))
  19255. ExtIdx *= (NumElts / NumExtElts);
  19256. else
  19257. return SDValue();
  19258. // At most we can reference 2 inputs in the final shuffle.
  19259. if (SV0.isUndef() || SV0 == ExtVec) {
  19260. SV0 = ExtVec;
  19261. for (int i = 0; i != NumOpElts; ++i)
  19262. Mask.push_back(i + ExtIdx);
  19263. } else if (SV1.isUndef() || SV1 == ExtVec) {
  19264. SV1 = ExtVec;
  19265. for (int i = 0; i != NumOpElts; ++i)
  19266. Mask.push_back(i + ExtIdx + NumElts);
  19267. } else {
  19268. return SDValue();
  19269. }
  19270. }
  19271. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  19272. return TLI.buildLegalVectorShuffle(VT, SDLoc(N), DAG.getBitcast(VT, SV0),
  19273. DAG.getBitcast(VT, SV1), Mask, DAG);
  19274. }
  19275. static SDValue combineConcatVectorOfCasts(SDNode *N, SelectionDAG &DAG) {
  19276. unsigned CastOpcode = N->getOperand(0).getOpcode();
  19277. switch (CastOpcode) {
  19278. case ISD::SINT_TO_FP:
  19279. case ISD::UINT_TO_FP:
  19280. case ISD::FP_TO_SINT:
  19281. case ISD::FP_TO_UINT:
  19282. // TODO: Allow more opcodes?
  19283. // case ISD::BITCAST:
  19284. // case ISD::TRUNCATE:
  19285. // case ISD::ZERO_EXTEND:
  19286. // case ISD::SIGN_EXTEND:
  19287. // case ISD::FP_EXTEND:
  19288. break;
  19289. default:
  19290. return SDValue();
  19291. }
  19292. EVT SrcVT = N->getOperand(0).getOperand(0).getValueType();
  19293. if (!SrcVT.isVector())
  19294. return SDValue();
  19295. // All operands of the concat must be the same kind of cast from the same
  19296. // source type.
  19297. SmallVector<SDValue, 4> SrcOps;
  19298. for (SDValue Op : N->ops()) {
  19299. if (Op.getOpcode() != CastOpcode || !Op.hasOneUse() ||
  19300. Op.getOperand(0).getValueType() != SrcVT)
  19301. return SDValue();
  19302. SrcOps.push_back(Op.getOperand(0));
  19303. }
  19304. // The wider cast must be supported by the target. This is unusual because
  19305. // the operation support type parameter depends on the opcode. In addition,
  19306. // check the other type in the cast to make sure this is really legal.
  19307. EVT VT = N->getValueType(0);
  19308. EVT SrcEltVT = SrcVT.getVectorElementType();
  19309. ElementCount NumElts = SrcVT.getVectorElementCount() * N->getNumOperands();
  19310. EVT ConcatSrcVT = EVT::getVectorVT(*DAG.getContext(), SrcEltVT, NumElts);
  19311. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  19312. switch (CastOpcode) {
  19313. case ISD::SINT_TO_FP:
  19314. case ISD::UINT_TO_FP:
  19315. if (!TLI.isOperationLegalOrCustom(CastOpcode, ConcatSrcVT) ||
  19316. !TLI.isTypeLegal(VT))
  19317. return SDValue();
  19318. break;
  19319. case ISD::FP_TO_SINT:
  19320. case ISD::FP_TO_UINT:
  19321. if (!TLI.isOperationLegalOrCustom(CastOpcode, VT) ||
  19322. !TLI.isTypeLegal(ConcatSrcVT))
  19323. return SDValue();
  19324. break;
  19325. default:
  19326. llvm_unreachable("Unexpected cast opcode");
  19327. }
  19328. // concat (cast X), (cast Y)... -> cast (concat X, Y...)
  19329. SDLoc DL(N);
  19330. SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, DL, ConcatSrcVT, SrcOps);
  19331. return DAG.getNode(CastOpcode, DL, VT, NewConcat);
  19332. }
  19333. // See if this is a simple CONCAT_VECTORS with no UNDEF operands, and if one of
  19334. // the operands is a SHUFFLE_VECTOR, and all other operands are also operands
  19335. // to that SHUFFLE_VECTOR, create wider SHUFFLE_VECTOR.
  19336. static SDValue combineConcatVectorOfShuffleAndItsOperands(
  19337. SDNode *N, SelectionDAG &DAG, const TargetLowering &TLI, bool LegalTypes,
  19338. bool LegalOperations) {
  19339. EVT VT = N->getValueType(0);
  19340. EVT OpVT = N->getOperand(0).getValueType();
  19341. if (VT.isScalableVector())
  19342. return SDValue();
  19343. // For now, only allow simple 2-operand concatenations.
  19344. if (N->getNumOperands() != 2)
  19345. return SDValue();
  19346. // Don't create illegal types/shuffles when not allowed to.
  19347. if ((LegalTypes && !TLI.isTypeLegal(VT)) ||
  19348. (LegalOperations &&
  19349. !TLI.isOperationLegalOrCustom(ISD::VECTOR_SHUFFLE, VT)))
  19350. return SDValue();
  19351. // Analyze all of the operands of the CONCAT_VECTORS. Out of all of them,
  19352. // we want to find one that is: (1) a SHUFFLE_VECTOR (2) only used by us,
  19353. // and (3) all operands of CONCAT_VECTORS must be either that SHUFFLE_VECTOR,
  19354. // or one of the operands of that SHUFFLE_VECTOR (but not UNDEF!).
  19355. // (4) and for now, the SHUFFLE_VECTOR must be unary.
  19356. ShuffleVectorSDNode *SVN = nullptr;
  19357. for (SDValue Op : N->ops()) {
  19358. if (auto *CurSVN = dyn_cast<ShuffleVectorSDNode>(Op);
  19359. CurSVN && CurSVN->getOperand(1).isUndef() && N->isOnlyUserOf(CurSVN) &&
  19360. all_of(N->ops(), [CurSVN](SDValue Op) {
  19361. // FIXME: can we allow UNDEF operands?
  19362. return !Op.isUndef() &&
  19363. (Op.getNode() == CurSVN || is_contained(CurSVN->ops(), Op));
  19364. })) {
  19365. SVN = CurSVN;
  19366. break;
  19367. }
  19368. }
  19369. if (!SVN)
  19370. return SDValue();
  19371. // We are going to pad the shuffle operands, so any indice, that was picking
  19372. // from the second operand, must be adjusted.
  19373. SmallVector<int, 16> AdjustedMask;
  19374. AdjustedMask.reserve(SVN->getMask().size());
  19375. assert(SVN->getOperand(1).isUndef() && "Expected unary shuffle!");
  19376. append_range(AdjustedMask, SVN->getMask());
  19377. // Identity masks for the operands of the (padded) shuffle.
  19378. SmallVector<int, 32> IdentityMask(2 * OpVT.getVectorNumElements());
  19379. MutableArrayRef<int> FirstShufOpIdentityMask =
  19380. MutableArrayRef<int>(IdentityMask)
  19381. .take_front(OpVT.getVectorNumElements());
  19382. MutableArrayRef<int> SecondShufOpIdentityMask =
  19383. MutableArrayRef<int>(IdentityMask).take_back(OpVT.getVectorNumElements());
  19384. std::iota(FirstShufOpIdentityMask.begin(), FirstShufOpIdentityMask.end(), 0);
  19385. std::iota(SecondShufOpIdentityMask.begin(), SecondShufOpIdentityMask.end(),
  19386. VT.getVectorNumElements());
  19387. // New combined shuffle mask.
  19388. SmallVector<int, 32> Mask;
  19389. Mask.reserve(VT.getVectorNumElements());
  19390. for (SDValue Op : N->ops()) {
  19391. assert(!Op.isUndef() && "Not expecting to concatenate UNDEF.");
  19392. if (Op.getNode() == SVN) {
  19393. append_range(Mask, AdjustedMask);
  19394. continue;
  19395. }
  19396. if (Op == SVN->getOperand(0)) {
  19397. append_range(Mask, FirstShufOpIdentityMask);
  19398. continue;
  19399. }
  19400. if (Op == SVN->getOperand(1)) {
  19401. append_range(Mask, SecondShufOpIdentityMask);
  19402. continue;
  19403. }
  19404. llvm_unreachable("Unexpected operand!");
  19405. }
  19406. // Don't create illegal shuffle masks.
  19407. if (!TLI.isShuffleMaskLegal(Mask, VT))
  19408. return SDValue();
  19409. // Pad the shuffle operands with UNDEF.
  19410. SDLoc dl(N);
  19411. std::array<SDValue, 2> ShufOps;
  19412. for (auto I : zip(SVN->ops(), ShufOps)) {
  19413. SDValue ShufOp = std::get<0>(I);
  19414. SDValue &NewShufOp = std::get<1>(I);
  19415. if (ShufOp.isUndef())
  19416. NewShufOp = DAG.getUNDEF(VT);
  19417. else {
  19418. SmallVector<SDValue, 2> ShufOpParts(N->getNumOperands(),
  19419. DAG.getUNDEF(OpVT));
  19420. ShufOpParts[0] = ShufOp;
  19421. NewShufOp = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, ShufOpParts);
  19422. }
  19423. }
  19424. // Finally, create the new wide shuffle.
  19425. return DAG.getVectorShuffle(VT, dl, ShufOps[0], ShufOps[1], Mask);
  19426. }
  19427. SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
  19428. // If we only have one input vector, we don't need to do any concatenation.
  19429. if (N->getNumOperands() == 1)
  19430. return N->getOperand(0);
  19431. // Check if all of the operands are undefs.
  19432. EVT VT = N->getValueType(0);
  19433. if (ISD::allOperandsUndef(N))
  19434. return DAG.getUNDEF(VT);
  19435. // Optimize concat_vectors where all but the first of the vectors are undef.
  19436. if (all_of(drop_begin(N->ops()),
  19437. [](const SDValue &Op) { return Op.isUndef(); })) {
  19438. SDValue In = N->getOperand(0);
  19439. assert(In.getValueType().isVector() && "Must concat vectors");
  19440. // If the input is a concat_vectors, just make a larger concat by padding
  19441. // with smaller undefs.
  19442. if (In.getOpcode() == ISD::CONCAT_VECTORS && In.hasOneUse()) {
  19443. unsigned NumOps = N->getNumOperands() * In.getNumOperands();
  19444. SmallVector<SDValue, 4> Ops(In->op_begin(), In->op_end());
  19445. Ops.resize(NumOps, DAG.getUNDEF(Ops[0].getValueType()));
  19446. return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
  19447. }
  19448. SDValue Scalar = peekThroughOneUseBitcasts(In);
  19449. // concat_vectors(scalar_to_vector(scalar), undef) ->
  19450. // scalar_to_vector(scalar)
  19451. if (!LegalOperations && Scalar.getOpcode() == ISD::SCALAR_TO_VECTOR &&
  19452. Scalar.hasOneUse()) {
  19453. EVT SVT = Scalar.getValueType().getVectorElementType();
  19454. if (SVT == Scalar.getOperand(0).getValueType())
  19455. Scalar = Scalar.getOperand(0);
  19456. }
  19457. // concat_vectors(scalar, undef) -> scalar_to_vector(scalar)
  19458. if (!Scalar.getValueType().isVector()) {
  19459. // If the bitcast type isn't legal, it might be a trunc of a legal type;
  19460. // look through the trunc so we can still do the transform:
  19461. // concat_vectors(trunc(scalar), undef) -> scalar_to_vector(scalar)
  19462. if (Scalar->getOpcode() == ISD::TRUNCATE &&
  19463. !TLI.isTypeLegal(Scalar.getValueType()) &&
  19464. TLI.isTypeLegal(Scalar->getOperand(0).getValueType()))
  19465. Scalar = Scalar->getOperand(0);
  19466. EVT SclTy = Scalar.getValueType();
  19467. if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
  19468. return SDValue();
  19469. // Bail out if the vector size is not a multiple of the scalar size.
  19470. if (VT.getSizeInBits() % SclTy.getSizeInBits())
  19471. return SDValue();
  19472. unsigned VNTNumElms = VT.getSizeInBits() / SclTy.getSizeInBits();
  19473. if (VNTNumElms < 2)
  19474. return SDValue();
  19475. EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy, VNTNumElms);
  19476. if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
  19477. return SDValue();
  19478. SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(N), NVT, Scalar);
  19479. return DAG.getBitcast(VT, Res);
  19480. }
  19481. }
  19482. // Fold any combination of BUILD_VECTOR or UNDEF nodes into one BUILD_VECTOR.
  19483. // We have already tested above for an UNDEF only concatenation.
  19484. // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
  19485. // -> (BUILD_VECTOR A, B, ..., C, D, ...)
  19486. auto IsBuildVectorOrUndef = [](const SDValue &Op) {
  19487. return ISD::UNDEF == Op.getOpcode() || ISD::BUILD_VECTOR == Op.getOpcode();
  19488. };
  19489. if (llvm::all_of(N->ops(), IsBuildVectorOrUndef)) {
  19490. SmallVector<SDValue, 8> Opnds;
  19491. EVT SVT = VT.getScalarType();
  19492. EVT MinVT = SVT;
  19493. if (!SVT.isFloatingPoint()) {
  19494. // If BUILD_VECTOR are from built from integer, they may have different
  19495. // operand types. Get the smallest type and truncate all operands to it.
  19496. bool FoundMinVT = false;
  19497. for (const SDValue &Op : N->ops())
  19498. if (ISD::BUILD_VECTOR == Op.getOpcode()) {
  19499. EVT OpSVT = Op.getOperand(0).getValueType();
  19500. MinVT = (!FoundMinVT || OpSVT.bitsLE(MinVT)) ? OpSVT : MinVT;
  19501. FoundMinVT = true;
  19502. }
  19503. assert(FoundMinVT && "Concat vector type mismatch");
  19504. }
  19505. for (const SDValue &Op : N->ops()) {
  19506. EVT OpVT = Op.getValueType();
  19507. unsigned NumElts = OpVT.getVectorNumElements();
  19508. if (ISD::UNDEF == Op.getOpcode())
  19509. Opnds.append(NumElts, DAG.getUNDEF(MinVT));
  19510. if (ISD::BUILD_VECTOR == Op.getOpcode()) {
  19511. if (SVT.isFloatingPoint()) {
  19512. assert(SVT == OpVT.getScalarType() && "Concat vector type mismatch");
  19513. Opnds.append(Op->op_begin(), Op->op_begin() + NumElts);
  19514. } else {
  19515. for (unsigned i = 0; i != NumElts; ++i)
  19516. Opnds.push_back(
  19517. DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinVT, Op.getOperand(i)));
  19518. }
  19519. }
  19520. }
  19521. assert(VT.getVectorNumElements() == Opnds.size() &&
  19522. "Concat vector type mismatch");
  19523. return DAG.getBuildVector(VT, SDLoc(N), Opnds);
  19524. }
  19525. // Fold CONCAT_VECTORS of only bitcast scalars (or undef) to BUILD_VECTOR.
  19526. // FIXME: Add support for concat_vectors(bitcast(vec0),bitcast(vec1),...).
  19527. if (SDValue V = combineConcatVectorOfScalars(N, DAG))
  19528. return V;
  19529. if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT)) {
  19530. // Fold CONCAT_VECTORS of CONCAT_VECTORS (or undef) to VECTOR_SHUFFLE.
  19531. if (SDValue V = combineConcatVectorOfConcatVectors(N, DAG))
  19532. return V;
  19533. // Fold CONCAT_VECTORS of EXTRACT_SUBVECTOR (or undef) to VECTOR_SHUFFLE.
  19534. if (SDValue V = combineConcatVectorOfExtracts(N, DAG))
  19535. return V;
  19536. }
  19537. if (SDValue V = combineConcatVectorOfCasts(N, DAG))
  19538. return V;
  19539. if (SDValue V = combineConcatVectorOfShuffleAndItsOperands(
  19540. N, DAG, TLI, LegalTypes, LegalOperations))
  19541. return V;
  19542. // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
  19543. // nodes often generate nop CONCAT_VECTOR nodes. Scan the CONCAT_VECTOR
  19544. // operands and look for a CONCAT operations that place the incoming vectors
  19545. // at the exact same location.
  19546. //
  19547. // For scalable vectors, EXTRACT_SUBVECTOR indexes are implicitly scaled.
  19548. SDValue SingleSource = SDValue();
  19549. unsigned PartNumElem =
  19550. N->getOperand(0).getValueType().getVectorMinNumElements();
  19551. for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
  19552. SDValue Op = N->getOperand(i);
  19553. if (Op.isUndef())
  19554. continue;
  19555. // Check if this is the identity extract:
  19556. if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
  19557. return SDValue();
  19558. // Find the single incoming vector for the extract_subvector.
  19559. if (SingleSource.getNode()) {
  19560. if (Op.getOperand(0) != SingleSource)
  19561. return SDValue();
  19562. } else {
  19563. SingleSource = Op.getOperand(0);
  19564. // Check the source type is the same as the type of the result.
  19565. // If not, this concat may extend the vector, so we can not
  19566. // optimize it away.
  19567. if (SingleSource.getValueType() != N->getValueType(0))
  19568. return SDValue();
  19569. }
  19570. // Check that we are reading from the identity index.
  19571. unsigned IdentityIndex = i * PartNumElem;
  19572. if (Op.getConstantOperandAPInt(1) != IdentityIndex)
  19573. return SDValue();
  19574. }
  19575. if (SingleSource.getNode())
  19576. return SingleSource;
  19577. return SDValue();
  19578. }
  19579. // Helper that peeks through INSERT_SUBVECTOR/CONCAT_VECTORS to find
  19580. // if the subvector can be sourced for free.
  19581. static SDValue getSubVectorSrc(SDValue V, SDValue Index, EVT SubVT) {
  19582. if (V.getOpcode() == ISD::INSERT_SUBVECTOR &&
  19583. V.getOperand(1).getValueType() == SubVT && V.getOperand(2) == Index) {
  19584. return V.getOperand(1);
  19585. }
  19586. auto *IndexC = dyn_cast<ConstantSDNode>(Index);
  19587. if (IndexC && V.getOpcode() == ISD::CONCAT_VECTORS &&
  19588. V.getOperand(0).getValueType() == SubVT &&
  19589. (IndexC->getZExtValue() % SubVT.getVectorMinNumElements()) == 0) {
  19590. uint64_t SubIdx = IndexC->getZExtValue() / SubVT.getVectorMinNumElements();
  19591. return V.getOperand(SubIdx);
  19592. }
  19593. return SDValue();
  19594. }
  19595. static SDValue narrowInsertExtractVectorBinOp(SDNode *Extract,
  19596. SelectionDAG &DAG,
  19597. bool LegalOperations) {
  19598. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  19599. SDValue BinOp = Extract->getOperand(0);
  19600. unsigned BinOpcode = BinOp.getOpcode();
  19601. if (!TLI.isBinOp(BinOpcode) || BinOp->getNumValues() != 1)
  19602. return SDValue();
  19603. EVT VecVT = BinOp.getValueType();
  19604. SDValue Bop0 = BinOp.getOperand(0), Bop1 = BinOp.getOperand(1);
  19605. if (VecVT != Bop0.getValueType() || VecVT != Bop1.getValueType())
  19606. return SDValue();
  19607. SDValue Index = Extract->getOperand(1);
  19608. EVT SubVT = Extract->getValueType(0);
  19609. if (!TLI.isOperationLegalOrCustom(BinOpcode, SubVT, LegalOperations))
  19610. return SDValue();
  19611. SDValue Sub0 = getSubVectorSrc(Bop0, Index, SubVT);
  19612. SDValue Sub1 = getSubVectorSrc(Bop1, Index, SubVT);
  19613. // TODO: We could handle the case where only 1 operand is being inserted by
  19614. // creating an extract of the other operand, but that requires checking
  19615. // number of uses and/or costs.
  19616. if (!Sub0 || !Sub1)
  19617. return SDValue();
  19618. // We are inserting both operands of the wide binop only to extract back
  19619. // to the narrow vector size. Eliminate all of the insert/extract:
  19620. // ext (binop (ins ?, X, Index), (ins ?, Y, Index)), Index --> binop X, Y
  19621. return DAG.getNode(BinOpcode, SDLoc(Extract), SubVT, Sub0, Sub1,
  19622. BinOp->getFlags());
  19623. }
  19624. /// If we are extracting a subvector produced by a wide binary operator try
  19625. /// to use a narrow binary operator and/or avoid concatenation and extraction.
  19626. static SDValue narrowExtractedVectorBinOp(SDNode *Extract, SelectionDAG &DAG,
  19627. bool LegalOperations) {
  19628. // TODO: Refactor with the caller (visitEXTRACT_SUBVECTOR), so we can share
  19629. // some of these bailouts with other transforms.
  19630. if (SDValue V = narrowInsertExtractVectorBinOp(Extract, DAG, LegalOperations))
  19631. return V;
  19632. // The extract index must be a constant, so we can map it to a concat operand.
  19633. auto *ExtractIndexC = dyn_cast<ConstantSDNode>(Extract->getOperand(1));
  19634. if (!ExtractIndexC)
  19635. return SDValue();
  19636. // We are looking for an optionally bitcasted wide vector binary operator
  19637. // feeding an extract subvector.
  19638. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  19639. SDValue BinOp = peekThroughBitcasts(Extract->getOperand(0));
  19640. unsigned BOpcode = BinOp.getOpcode();
  19641. if (!TLI.isBinOp(BOpcode) || BinOp->getNumValues() != 1)
  19642. return SDValue();
  19643. // Exclude the fake form of fneg (fsub -0.0, x) because that is likely to be
  19644. // reduced to the unary fneg when it is visited, and we probably want to deal
  19645. // with fneg in a target-specific way.
  19646. if (BOpcode == ISD::FSUB) {
  19647. auto *C = isConstOrConstSplatFP(BinOp.getOperand(0), /*AllowUndefs*/ true);
  19648. if (C && C->getValueAPF().isNegZero())
  19649. return SDValue();
  19650. }
  19651. // The binop must be a vector type, so we can extract some fraction of it.
  19652. EVT WideBVT = BinOp.getValueType();
  19653. // The optimisations below currently assume we are dealing with fixed length
  19654. // vectors. It is possible to add support for scalable vectors, but at the
  19655. // moment we've done no analysis to prove whether they are profitable or not.
  19656. if (!WideBVT.isFixedLengthVector())
  19657. return SDValue();
  19658. EVT VT = Extract->getValueType(0);
  19659. unsigned ExtractIndex = ExtractIndexC->getZExtValue();
  19660. assert(ExtractIndex % VT.getVectorNumElements() == 0 &&
  19661. "Extract index is not a multiple of the vector length.");
  19662. // Bail out if this is not a proper multiple width extraction.
  19663. unsigned WideWidth = WideBVT.getSizeInBits();
  19664. unsigned NarrowWidth = VT.getSizeInBits();
  19665. if (WideWidth % NarrowWidth != 0)
  19666. return SDValue();
  19667. // Bail out if we are extracting a fraction of a single operation. This can
  19668. // occur because we potentially looked through a bitcast of the binop.
  19669. unsigned NarrowingRatio = WideWidth / NarrowWidth;
  19670. unsigned WideNumElts = WideBVT.getVectorNumElements();
  19671. if (WideNumElts % NarrowingRatio != 0)
  19672. return SDValue();
  19673. // Bail out if the target does not support a narrower version of the binop.
  19674. EVT NarrowBVT = EVT::getVectorVT(*DAG.getContext(), WideBVT.getScalarType(),
  19675. WideNumElts / NarrowingRatio);
  19676. if (!TLI.isOperationLegalOrCustomOrPromote(BOpcode, NarrowBVT))
  19677. return SDValue();
  19678. // If extraction is cheap, we don't need to look at the binop operands
  19679. // for concat ops. The narrow binop alone makes this transform profitable.
  19680. // We can't just reuse the original extract index operand because we may have
  19681. // bitcasted.
  19682. unsigned ConcatOpNum = ExtractIndex / VT.getVectorNumElements();
  19683. unsigned ExtBOIdx = ConcatOpNum * NarrowBVT.getVectorNumElements();
  19684. if (TLI.isExtractSubvectorCheap(NarrowBVT, WideBVT, ExtBOIdx) &&
  19685. BinOp.hasOneUse() && Extract->getOperand(0)->hasOneUse()) {
  19686. // extract (binop B0, B1), N --> binop (extract B0, N), (extract B1, N)
  19687. SDLoc DL(Extract);
  19688. SDValue NewExtIndex = DAG.getVectorIdxConstant(ExtBOIdx, DL);
  19689. SDValue X = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, NarrowBVT,
  19690. BinOp.getOperand(0), NewExtIndex);
  19691. SDValue Y = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, NarrowBVT,
  19692. BinOp.getOperand(1), NewExtIndex);
  19693. SDValue NarrowBinOp =
  19694. DAG.getNode(BOpcode, DL, NarrowBVT, X, Y, BinOp->getFlags());
  19695. return DAG.getBitcast(VT, NarrowBinOp);
  19696. }
  19697. // Only handle the case where we are doubling and then halving. A larger ratio
  19698. // may require more than two narrow binops to replace the wide binop.
  19699. if (NarrowingRatio != 2)
  19700. return SDValue();
  19701. // TODO: The motivating case for this transform is an x86 AVX1 target. That
  19702. // target has temptingly almost legal versions of bitwise logic ops in 256-bit
  19703. // flavors, but no other 256-bit integer support. This could be extended to
  19704. // handle any binop, but that may require fixing/adding other folds to avoid
  19705. // codegen regressions.
  19706. if (BOpcode != ISD::AND && BOpcode != ISD::OR && BOpcode != ISD::XOR)
  19707. return SDValue();
  19708. // We need at least one concatenation operation of a binop operand to make
  19709. // this transform worthwhile. The concat must double the input vector sizes.
  19710. auto GetSubVector = [ConcatOpNum](SDValue V) -> SDValue {
  19711. if (V.getOpcode() == ISD::CONCAT_VECTORS && V.getNumOperands() == 2)
  19712. return V.getOperand(ConcatOpNum);
  19713. return SDValue();
  19714. };
  19715. SDValue SubVecL = GetSubVector(peekThroughBitcasts(BinOp.getOperand(0)));
  19716. SDValue SubVecR = GetSubVector(peekThroughBitcasts(BinOp.getOperand(1)));
  19717. if (SubVecL || SubVecR) {
  19718. // If a binop operand was not the result of a concat, we must extract a
  19719. // half-sized operand for our new narrow binop:
  19720. // extract (binop (concat X1, X2), (concat Y1, Y2)), N --> binop XN, YN
  19721. // extract (binop (concat X1, X2), Y), N --> binop XN, (extract Y, IndexC)
  19722. // extract (binop X, (concat Y1, Y2)), N --> binop (extract X, IndexC), YN
  19723. SDLoc DL(Extract);
  19724. SDValue IndexC = DAG.getVectorIdxConstant(ExtBOIdx, DL);
  19725. SDValue X = SubVecL ? DAG.getBitcast(NarrowBVT, SubVecL)
  19726. : DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, NarrowBVT,
  19727. BinOp.getOperand(0), IndexC);
  19728. SDValue Y = SubVecR ? DAG.getBitcast(NarrowBVT, SubVecR)
  19729. : DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, NarrowBVT,
  19730. BinOp.getOperand(1), IndexC);
  19731. SDValue NarrowBinOp = DAG.getNode(BOpcode, DL, NarrowBVT, X, Y);
  19732. return DAG.getBitcast(VT, NarrowBinOp);
  19733. }
  19734. return SDValue();
  19735. }
  19736. /// If we are extracting a subvector from a wide vector load, convert to a
  19737. /// narrow load to eliminate the extraction:
  19738. /// (extract_subvector (load wide vector)) --> (load narrow vector)
  19739. static SDValue narrowExtractedVectorLoad(SDNode *Extract, SelectionDAG &DAG) {
  19740. // TODO: Add support for big-endian. The offset calculation must be adjusted.
  19741. if (DAG.getDataLayout().isBigEndian())
  19742. return SDValue();
  19743. auto *Ld = dyn_cast<LoadSDNode>(Extract->getOperand(0));
  19744. if (!Ld || Ld->getExtensionType() || !Ld->isSimple())
  19745. return SDValue();
  19746. // Allow targets to opt-out.
  19747. EVT VT = Extract->getValueType(0);
  19748. // We can only create byte sized loads.
  19749. if (!VT.isByteSized())
  19750. return SDValue();
  19751. unsigned Index = Extract->getConstantOperandVal(1);
  19752. unsigned NumElts = VT.getVectorMinNumElements();
  19753. // The definition of EXTRACT_SUBVECTOR states that the index must be a
  19754. // multiple of the minimum number of elements in the result type.
  19755. assert(Index % NumElts == 0 && "The extract subvector index is not a "
  19756. "multiple of the result's element count");
  19757. // It's fine to use TypeSize here as we know the offset will not be negative.
  19758. TypeSize Offset = VT.getStoreSize() * (Index / NumElts);
  19759. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  19760. if (!TLI.shouldReduceLoadWidth(Ld, Ld->getExtensionType(), VT))
  19761. return SDValue();
  19762. // The narrow load will be offset from the base address of the old load if
  19763. // we are extracting from something besides index 0 (little-endian).
  19764. SDLoc DL(Extract);
  19765. // TODO: Use "BaseIndexOffset" to make this more effective.
  19766. SDValue NewAddr = DAG.getMemBasePlusOffset(Ld->getBasePtr(), Offset, DL);
  19767. uint64_t StoreSize = MemoryLocation::getSizeOrUnknown(VT.getStoreSize());
  19768. MachineFunction &MF = DAG.getMachineFunction();
  19769. MachineMemOperand *MMO;
  19770. if (Offset.isScalable()) {
  19771. MachinePointerInfo MPI =
  19772. MachinePointerInfo(Ld->getPointerInfo().getAddrSpace());
  19773. MMO = MF.getMachineMemOperand(Ld->getMemOperand(), MPI, StoreSize);
  19774. } else
  19775. MMO = MF.getMachineMemOperand(Ld->getMemOperand(), Offset.getFixedValue(),
  19776. StoreSize);
  19777. SDValue NewLd = DAG.getLoad(VT, DL, Ld->getChain(), NewAddr, MMO);
  19778. DAG.makeEquivalentMemoryOrdering(Ld, NewLd);
  19779. return NewLd;
  19780. }
  19781. /// Given EXTRACT_SUBVECTOR(VECTOR_SHUFFLE(Op0, Op1, Mask)),
  19782. /// try to produce VECTOR_SHUFFLE(EXTRACT_SUBVECTOR(Op?, ?),
  19783. /// EXTRACT_SUBVECTOR(Op?, ?),
  19784. /// Mask'))
  19785. /// iff it is legal and profitable to do so. Notably, the trimmed mask
  19786. /// (containing only the elements that are extracted)
  19787. /// must reference at most two subvectors.
  19788. static SDValue foldExtractSubvectorFromShuffleVector(SDNode *N,
  19789. SelectionDAG &DAG,
  19790. const TargetLowering &TLI,
  19791. bool LegalOperations) {
  19792. assert(N->getOpcode() == ISD::EXTRACT_SUBVECTOR &&
  19793. "Must only be called on EXTRACT_SUBVECTOR's");
  19794. SDValue N0 = N->getOperand(0);
  19795. // Only deal with non-scalable vectors.
  19796. EVT NarrowVT = N->getValueType(0);
  19797. EVT WideVT = N0.getValueType();
  19798. if (!NarrowVT.isFixedLengthVector() || !WideVT.isFixedLengthVector())
  19799. return SDValue();
  19800. // The operand must be a shufflevector.
  19801. auto *WideShuffleVector = dyn_cast<ShuffleVectorSDNode>(N0);
  19802. if (!WideShuffleVector)
  19803. return SDValue();
  19804. // The old shuffleneeds to go away.
  19805. if (!WideShuffleVector->hasOneUse())
  19806. return SDValue();
  19807. // And the narrow shufflevector that we'll form must be legal.
  19808. if (LegalOperations &&
  19809. !TLI.isOperationLegalOrCustom(ISD::VECTOR_SHUFFLE, NarrowVT))
  19810. return SDValue();
  19811. uint64_t FirstExtractedEltIdx = N->getConstantOperandVal(1);
  19812. int NumEltsExtracted = NarrowVT.getVectorNumElements();
  19813. assert((FirstExtractedEltIdx % NumEltsExtracted) == 0 &&
  19814. "Extract index is not a multiple of the output vector length.");
  19815. int WideNumElts = WideVT.getVectorNumElements();
  19816. SmallVector<int, 16> NewMask;
  19817. NewMask.reserve(NumEltsExtracted);
  19818. SmallSetVector<std::pair<SDValue /*Op*/, int /*SubvectorIndex*/>, 2>
  19819. DemandedSubvectors;
  19820. // Try to decode the wide mask into narrow mask from at most two subvectors.
  19821. for (int M : WideShuffleVector->getMask().slice(FirstExtractedEltIdx,
  19822. NumEltsExtracted)) {
  19823. assert((M >= -1) && (M < (2 * WideNumElts)) &&
  19824. "Out-of-bounds shuffle mask?");
  19825. if (M < 0) {
  19826. // Does not depend on operands, does not require adjustment.
  19827. NewMask.emplace_back(M);
  19828. continue;
  19829. }
  19830. // From which operand of the shuffle does this shuffle mask element pick?
  19831. int WideShufOpIdx = M / WideNumElts;
  19832. // Which element of that operand is picked?
  19833. int OpEltIdx = M % WideNumElts;
  19834. assert((OpEltIdx + WideShufOpIdx * WideNumElts) == M &&
  19835. "Shuffle mask vector decomposition failure.");
  19836. // And which NumEltsExtracted-sized subvector of that operand is that?
  19837. int OpSubvecIdx = OpEltIdx / NumEltsExtracted;
  19838. // And which element within that subvector of that operand is that?
  19839. int OpEltIdxInSubvec = OpEltIdx % NumEltsExtracted;
  19840. assert((OpEltIdxInSubvec + OpSubvecIdx * NumEltsExtracted) == OpEltIdx &&
  19841. "Shuffle mask subvector decomposition failure.");
  19842. assert((OpEltIdxInSubvec + OpSubvecIdx * NumEltsExtracted +
  19843. WideShufOpIdx * WideNumElts) == M &&
  19844. "Shuffle mask full decomposition failure.");
  19845. SDValue Op = WideShuffleVector->getOperand(WideShufOpIdx);
  19846. if (Op.isUndef()) {
  19847. // Picking from an undef operand. Let's adjust mask instead.
  19848. NewMask.emplace_back(-1);
  19849. continue;
  19850. }
  19851. // Profitability check: only deal with extractions from the first subvector.
  19852. if (OpSubvecIdx != 0)
  19853. return SDValue();
  19854. const std::pair<SDValue, int> DemandedSubvector =
  19855. std::make_pair(Op, OpSubvecIdx);
  19856. if (DemandedSubvectors.insert(DemandedSubvector)) {
  19857. if (DemandedSubvectors.size() > 2)
  19858. return SDValue(); // We can't handle more than two subvectors.
  19859. // How many elements into the WideVT does this subvector start?
  19860. int Index = NumEltsExtracted * OpSubvecIdx;
  19861. // Bail out if the extraction isn't going to be cheap.
  19862. if (!TLI.isExtractSubvectorCheap(NarrowVT, WideVT, Index))
  19863. return SDValue();
  19864. }
  19865. // Ok, but from which operand of the new shuffle will this element pick?
  19866. int NewOpIdx =
  19867. getFirstIndexOf(DemandedSubvectors.getArrayRef(), DemandedSubvector);
  19868. assert((NewOpIdx == 0 || NewOpIdx == 1) && "Unexpected operand index.");
  19869. int AdjM = OpEltIdxInSubvec + NewOpIdx * NumEltsExtracted;
  19870. NewMask.emplace_back(AdjM);
  19871. }
  19872. assert(NewMask.size() == (unsigned)NumEltsExtracted && "Produced bad mask.");
  19873. assert(DemandedSubvectors.size() <= 2 &&
  19874. "Should have ended up demanding at most two subvectors.");
  19875. // Did we discover that the shuffle does not actually depend on operands?
  19876. if (DemandedSubvectors.empty())
  19877. return DAG.getUNDEF(NarrowVT);
  19878. // We still perform the exact same EXTRACT_SUBVECTOR, just on different
  19879. // operand[s]/index[es], so there is no point in checking for it's legality.
  19880. // Do not turn a legal shuffle into an illegal one.
  19881. if (TLI.isShuffleMaskLegal(WideShuffleVector->getMask(), WideVT) &&
  19882. !TLI.isShuffleMaskLegal(NewMask, NarrowVT))
  19883. return SDValue();
  19884. SDLoc DL(N);
  19885. SmallVector<SDValue, 2> NewOps;
  19886. for (const std::pair<SDValue /*Op*/, int /*SubvectorIndex*/>
  19887. &DemandedSubvector : DemandedSubvectors) {
  19888. // How many elements into the WideVT does this subvector start?
  19889. int Index = NumEltsExtracted * DemandedSubvector.second;
  19890. SDValue IndexC = DAG.getVectorIdxConstant(Index, DL);
  19891. NewOps.emplace_back(DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, NarrowVT,
  19892. DemandedSubvector.first, IndexC));
  19893. }
  19894. assert((NewOps.size() == 1 || NewOps.size() == 2) &&
  19895. "Should end up with either one or two ops");
  19896. // If we ended up with only one operand, pad with an undef.
  19897. if (NewOps.size() == 1)
  19898. NewOps.emplace_back(DAG.getUNDEF(NarrowVT));
  19899. return DAG.getVectorShuffle(NarrowVT, DL, NewOps[0], NewOps[1], NewMask);
  19900. }
  19901. SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode *N) {
  19902. EVT NVT = N->getValueType(0);
  19903. SDValue V = N->getOperand(0);
  19904. uint64_t ExtIdx = N->getConstantOperandVal(1);
  19905. // Extract from UNDEF is UNDEF.
  19906. if (V.isUndef())
  19907. return DAG.getUNDEF(NVT);
  19908. if (TLI.isOperationLegalOrCustomOrPromote(ISD::LOAD, NVT))
  19909. if (SDValue NarrowLoad = narrowExtractedVectorLoad(N, DAG))
  19910. return NarrowLoad;
  19911. // Combine an extract of an extract into a single extract_subvector.
  19912. // ext (ext X, C), 0 --> ext X, C
  19913. if (ExtIdx == 0 && V.getOpcode() == ISD::EXTRACT_SUBVECTOR && V.hasOneUse()) {
  19914. if (TLI.isExtractSubvectorCheap(NVT, V.getOperand(0).getValueType(),
  19915. V.getConstantOperandVal(1)) &&
  19916. TLI.isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, NVT)) {
  19917. return DAG.getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(N), NVT, V.getOperand(0),
  19918. V.getOperand(1));
  19919. }
  19920. }
  19921. // ty1 extract_vector(ty2 splat(V))) -> ty1 splat(V)
  19922. if (V.getOpcode() == ISD::SPLAT_VECTOR)
  19923. if (DAG.isConstantValueOfAnyType(V.getOperand(0)) || V.hasOneUse())
  19924. if (!LegalOperations || TLI.isOperationLegal(ISD::SPLAT_VECTOR, NVT))
  19925. return DAG.getSplatVector(NVT, SDLoc(N), V.getOperand(0));
  19926. // Try to move vector bitcast after extract_subv by scaling extraction index:
  19927. // extract_subv (bitcast X), Index --> bitcast (extract_subv X, Index')
  19928. if (V.getOpcode() == ISD::BITCAST &&
  19929. V.getOperand(0).getValueType().isVector() &&
  19930. (!LegalOperations || TLI.isOperationLegal(ISD::BITCAST, NVT))) {
  19931. SDValue SrcOp = V.getOperand(0);
  19932. EVT SrcVT = SrcOp.getValueType();
  19933. unsigned SrcNumElts = SrcVT.getVectorMinNumElements();
  19934. unsigned DestNumElts = V.getValueType().getVectorMinNumElements();
  19935. if ((SrcNumElts % DestNumElts) == 0) {
  19936. unsigned SrcDestRatio = SrcNumElts / DestNumElts;
  19937. ElementCount NewExtEC = NVT.getVectorElementCount() * SrcDestRatio;
  19938. EVT NewExtVT = EVT::getVectorVT(*DAG.getContext(), SrcVT.getScalarType(),
  19939. NewExtEC);
  19940. if (TLI.isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, NewExtVT)) {
  19941. SDLoc DL(N);
  19942. SDValue NewIndex = DAG.getVectorIdxConstant(ExtIdx * SrcDestRatio, DL);
  19943. SDValue NewExtract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, NewExtVT,
  19944. V.getOperand(0), NewIndex);
  19945. return DAG.getBitcast(NVT, NewExtract);
  19946. }
  19947. }
  19948. if ((DestNumElts % SrcNumElts) == 0) {
  19949. unsigned DestSrcRatio = DestNumElts / SrcNumElts;
  19950. if (NVT.getVectorElementCount().isKnownMultipleOf(DestSrcRatio)) {
  19951. ElementCount NewExtEC =
  19952. NVT.getVectorElementCount().divideCoefficientBy(DestSrcRatio);
  19953. EVT ScalarVT = SrcVT.getScalarType();
  19954. if ((ExtIdx % DestSrcRatio) == 0) {
  19955. SDLoc DL(N);
  19956. unsigned IndexValScaled = ExtIdx / DestSrcRatio;
  19957. EVT NewExtVT =
  19958. EVT::getVectorVT(*DAG.getContext(), ScalarVT, NewExtEC);
  19959. if (TLI.isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, NewExtVT)) {
  19960. SDValue NewIndex = DAG.getVectorIdxConstant(IndexValScaled, DL);
  19961. SDValue NewExtract =
  19962. DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, NewExtVT,
  19963. V.getOperand(0), NewIndex);
  19964. return DAG.getBitcast(NVT, NewExtract);
  19965. }
  19966. if (NewExtEC.isScalar() &&
  19967. TLI.isOperationLegalOrCustom(ISD::EXTRACT_VECTOR_ELT, ScalarVT)) {
  19968. SDValue NewIndex = DAG.getVectorIdxConstant(IndexValScaled, DL);
  19969. SDValue NewExtract =
  19970. DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ScalarVT,
  19971. V.getOperand(0), NewIndex);
  19972. return DAG.getBitcast(NVT, NewExtract);
  19973. }
  19974. }
  19975. }
  19976. }
  19977. }
  19978. if (V.getOpcode() == ISD::CONCAT_VECTORS) {
  19979. unsigned ExtNumElts = NVT.getVectorMinNumElements();
  19980. EVT ConcatSrcVT = V.getOperand(0).getValueType();
  19981. assert(ConcatSrcVT.getVectorElementType() == NVT.getVectorElementType() &&
  19982. "Concat and extract subvector do not change element type");
  19983. assert((ExtIdx % ExtNumElts) == 0 &&
  19984. "Extract index is not a multiple of the input vector length.");
  19985. unsigned ConcatSrcNumElts = ConcatSrcVT.getVectorMinNumElements();
  19986. unsigned ConcatOpIdx = ExtIdx / ConcatSrcNumElts;
  19987. // If the concatenated source types match this extract, it's a direct
  19988. // simplification:
  19989. // extract_subvec (concat V1, V2, ...), i --> Vi
  19990. if (NVT.getVectorElementCount() == ConcatSrcVT.getVectorElementCount())
  19991. return V.getOperand(ConcatOpIdx);
  19992. // If the concatenated source vectors are a multiple length of this extract,
  19993. // then extract a fraction of one of those source vectors directly from a
  19994. // concat operand. Example:
  19995. // v2i8 extract_subvec (v16i8 concat (v8i8 X), (v8i8 Y), 14 -->
  19996. // v2i8 extract_subvec v8i8 Y, 6
  19997. if (NVT.isFixedLengthVector() && ConcatSrcVT.isFixedLengthVector() &&
  19998. ConcatSrcNumElts % ExtNumElts == 0) {
  19999. SDLoc DL(N);
  20000. unsigned NewExtIdx = ExtIdx - ConcatOpIdx * ConcatSrcNumElts;
  20001. assert(NewExtIdx + ExtNumElts <= ConcatSrcNumElts &&
  20002. "Trying to extract from >1 concat operand?");
  20003. assert(NewExtIdx % ExtNumElts == 0 &&
  20004. "Extract index is not a multiple of the input vector length.");
  20005. SDValue NewIndexC = DAG.getVectorIdxConstant(NewExtIdx, DL);
  20006. return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, NVT,
  20007. V.getOperand(ConcatOpIdx), NewIndexC);
  20008. }
  20009. }
  20010. if (SDValue V =
  20011. foldExtractSubvectorFromShuffleVector(N, DAG, TLI, LegalOperations))
  20012. return V;
  20013. V = peekThroughBitcasts(V);
  20014. // If the input is a build vector. Try to make a smaller build vector.
  20015. if (V.getOpcode() == ISD::BUILD_VECTOR) {
  20016. EVT InVT = V.getValueType();
  20017. unsigned ExtractSize = NVT.getSizeInBits();
  20018. unsigned EltSize = InVT.getScalarSizeInBits();
  20019. // Only do this if we won't split any elements.
  20020. if (ExtractSize % EltSize == 0) {
  20021. unsigned NumElems = ExtractSize / EltSize;
  20022. EVT EltVT = InVT.getVectorElementType();
  20023. EVT ExtractVT =
  20024. NumElems == 1 ? EltVT
  20025. : EVT::getVectorVT(*DAG.getContext(), EltVT, NumElems);
  20026. if ((Level < AfterLegalizeDAG ||
  20027. (NumElems == 1 ||
  20028. TLI.isOperationLegal(ISD::BUILD_VECTOR, ExtractVT))) &&
  20029. (!LegalTypes || TLI.isTypeLegal(ExtractVT))) {
  20030. unsigned IdxVal = (ExtIdx * NVT.getScalarSizeInBits()) / EltSize;
  20031. if (NumElems == 1) {
  20032. SDValue Src = V->getOperand(IdxVal);
  20033. if (EltVT != Src.getValueType())
  20034. Src = DAG.getNode(ISD::TRUNCATE, SDLoc(N), InVT, Src);
  20035. return DAG.getBitcast(NVT, Src);
  20036. }
  20037. // Extract the pieces from the original build_vector.
  20038. SDValue BuildVec = DAG.getBuildVector(ExtractVT, SDLoc(N),
  20039. V->ops().slice(IdxVal, NumElems));
  20040. return DAG.getBitcast(NVT, BuildVec);
  20041. }
  20042. }
  20043. }
  20044. if (V.getOpcode() == ISD::INSERT_SUBVECTOR) {
  20045. // Handle only simple case where vector being inserted and vector
  20046. // being extracted are of same size.
  20047. EVT SmallVT = V.getOperand(1).getValueType();
  20048. if (!NVT.bitsEq(SmallVT))
  20049. return SDValue();
  20050. // Combine:
  20051. // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
  20052. // Into:
  20053. // indices are equal or bit offsets are equal => V1
  20054. // otherwise => (extract_subvec V1, ExtIdx)
  20055. uint64_t InsIdx = V.getConstantOperandVal(2);
  20056. if (InsIdx * SmallVT.getScalarSizeInBits() ==
  20057. ExtIdx * NVT.getScalarSizeInBits()) {
  20058. if (LegalOperations && !TLI.isOperationLegal(ISD::BITCAST, NVT))
  20059. return SDValue();
  20060. return DAG.getBitcast(NVT, V.getOperand(1));
  20061. }
  20062. return DAG.getNode(
  20063. ISD::EXTRACT_SUBVECTOR, SDLoc(N), NVT,
  20064. DAG.getBitcast(N->getOperand(0).getValueType(), V.getOperand(0)),
  20065. N->getOperand(1));
  20066. }
  20067. if (SDValue NarrowBOp = narrowExtractedVectorBinOp(N, DAG, LegalOperations))
  20068. return NarrowBOp;
  20069. if (SimplifyDemandedVectorElts(SDValue(N, 0)))
  20070. return SDValue(N, 0);
  20071. return SDValue();
  20072. }
  20073. /// Try to convert a wide shuffle of concatenated vectors into 2 narrow shuffles
  20074. /// followed by concatenation. Narrow vector ops may have better performance
  20075. /// than wide ops, and this can unlock further narrowing of other vector ops.
  20076. /// Targets can invert this transform later if it is not profitable.
  20077. static SDValue foldShuffleOfConcatUndefs(ShuffleVectorSDNode *Shuf,
  20078. SelectionDAG &DAG) {
  20079. SDValue N0 = Shuf->getOperand(0), N1 = Shuf->getOperand(1);
  20080. if (N0.getOpcode() != ISD::CONCAT_VECTORS || N0.getNumOperands() != 2 ||
  20081. N1.getOpcode() != ISD::CONCAT_VECTORS || N1.getNumOperands() != 2 ||
  20082. !N0.getOperand(1).isUndef() || !N1.getOperand(1).isUndef())
  20083. return SDValue();
  20084. // Split the wide shuffle mask into halves. Any mask element that is accessing
  20085. // operand 1 is offset down to account for narrowing of the vectors.
  20086. ArrayRef<int> Mask = Shuf->getMask();
  20087. EVT VT = Shuf->getValueType(0);
  20088. unsigned NumElts = VT.getVectorNumElements();
  20089. unsigned HalfNumElts = NumElts / 2;
  20090. SmallVector<int, 16> Mask0(HalfNumElts, -1);
  20091. SmallVector<int, 16> Mask1(HalfNumElts, -1);
  20092. for (unsigned i = 0; i != NumElts; ++i) {
  20093. if (Mask[i] == -1)
  20094. continue;
  20095. // If we reference the upper (undef) subvector then the element is undef.
  20096. if ((Mask[i] % NumElts) >= HalfNumElts)
  20097. continue;
  20098. int M = Mask[i] < (int)NumElts ? Mask[i] : Mask[i] - (int)HalfNumElts;
  20099. if (i < HalfNumElts)
  20100. Mask0[i] = M;
  20101. else
  20102. Mask1[i - HalfNumElts] = M;
  20103. }
  20104. // Ask the target if this is a valid transform.
  20105. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  20106. EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
  20107. HalfNumElts);
  20108. if (!TLI.isShuffleMaskLegal(Mask0, HalfVT) ||
  20109. !TLI.isShuffleMaskLegal(Mask1, HalfVT))
  20110. return SDValue();
  20111. // shuffle (concat X, undef), (concat Y, undef), Mask -->
  20112. // concat (shuffle X, Y, Mask0), (shuffle X, Y, Mask1)
  20113. SDValue X = N0.getOperand(0), Y = N1.getOperand(0);
  20114. SDLoc DL(Shuf);
  20115. SDValue Shuf0 = DAG.getVectorShuffle(HalfVT, DL, X, Y, Mask0);
  20116. SDValue Shuf1 = DAG.getVectorShuffle(HalfVT, DL, X, Y, Mask1);
  20117. return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Shuf0, Shuf1);
  20118. }
  20119. // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat,
  20120. // or turn a shuffle of a single concat into simpler shuffle then concat.
  20121. static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
  20122. EVT VT = N->getValueType(0);
  20123. unsigned NumElts = VT.getVectorNumElements();
  20124. SDValue N0 = N->getOperand(0);
  20125. SDValue N1 = N->getOperand(1);
  20126. ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
  20127. ArrayRef<int> Mask = SVN->getMask();
  20128. SmallVector<SDValue, 4> Ops;
  20129. EVT ConcatVT = N0.getOperand(0).getValueType();
  20130. unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
  20131. unsigned NumConcats = NumElts / NumElemsPerConcat;
  20132. auto IsUndefMaskElt = [](int i) { return i == -1; };
  20133. // Special case: shuffle(concat(A,B)) can be more efficiently represented
  20134. // as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high
  20135. // half vector elements.
  20136. if (NumElemsPerConcat * 2 == NumElts && N1.isUndef() &&
  20137. llvm::all_of(Mask.slice(NumElemsPerConcat, NumElemsPerConcat),
  20138. IsUndefMaskElt)) {
  20139. N0 = DAG.getVectorShuffle(ConcatVT, SDLoc(N), N0.getOperand(0),
  20140. N0.getOperand(1),
  20141. Mask.slice(0, NumElemsPerConcat));
  20142. N1 = DAG.getUNDEF(ConcatVT);
  20143. return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0, N1);
  20144. }
  20145. // Look at every vector that's inserted. We're looking for exact
  20146. // subvector-sized copies from a concatenated vector
  20147. for (unsigned I = 0; I != NumConcats; ++I) {
  20148. unsigned Begin = I * NumElemsPerConcat;
  20149. ArrayRef<int> SubMask = Mask.slice(Begin, NumElemsPerConcat);
  20150. // Make sure we're dealing with a copy.
  20151. if (llvm::all_of(SubMask, IsUndefMaskElt)) {
  20152. Ops.push_back(DAG.getUNDEF(ConcatVT));
  20153. continue;
  20154. }
  20155. int OpIdx = -1;
  20156. for (int i = 0; i != (int)NumElemsPerConcat; ++i) {
  20157. if (IsUndefMaskElt(SubMask[i]))
  20158. continue;
  20159. if ((SubMask[i] % (int)NumElemsPerConcat) != i)
  20160. return SDValue();
  20161. int EltOpIdx = SubMask[i] / NumElemsPerConcat;
  20162. if (0 <= OpIdx && EltOpIdx != OpIdx)
  20163. return SDValue();
  20164. OpIdx = EltOpIdx;
  20165. }
  20166. assert(0 <= OpIdx && "Unknown concat_vectors op");
  20167. if (OpIdx < (int)N0.getNumOperands())
  20168. Ops.push_back(N0.getOperand(OpIdx));
  20169. else
  20170. Ops.push_back(N1.getOperand(OpIdx - N0.getNumOperands()));
  20171. }
  20172. return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
  20173. }
  20174. // Attempt to combine a shuffle of 2 inputs of 'scalar sources' -
  20175. // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR.
  20176. //
  20177. // SHUFFLE(BUILD_VECTOR(), BUILD_VECTOR()) -> BUILD_VECTOR() is always
  20178. // a simplification in some sense, but it isn't appropriate in general: some
  20179. // BUILD_VECTORs are substantially cheaper than others. The general case
  20180. // of a BUILD_VECTOR requires inserting each element individually (or
  20181. // performing the equivalent in a temporary stack variable). A BUILD_VECTOR of
  20182. // all constants is a single constant pool load. A BUILD_VECTOR where each
  20183. // element is identical is a splat. A BUILD_VECTOR where most of the operands
  20184. // are undef lowers to a small number of element insertions.
  20185. //
  20186. // To deal with this, we currently use a bunch of mostly arbitrary heuristics.
  20187. // We don't fold shuffles where one side is a non-zero constant, and we don't
  20188. // fold shuffles if the resulting (non-splat) BUILD_VECTOR would have duplicate
  20189. // non-constant operands. This seems to work out reasonably well in practice.
  20190. static SDValue combineShuffleOfScalars(ShuffleVectorSDNode *SVN,
  20191. SelectionDAG &DAG,
  20192. const TargetLowering &TLI) {
  20193. EVT VT = SVN->getValueType(0);
  20194. unsigned NumElts = VT.getVectorNumElements();
  20195. SDValue N0 = SVN->getOperand(0);
  20196. SDValue N1 = SVN->getOperand(1);
  20197. if (!N0->hasOneUse())
  20198. return SDValue();
  20199. // If only one of N1,N2 is constant, bail out if it is not ALL_ZEROS as
  20200. // discussed above.
  20201. if (!N1.isUndef()) {
  20202. if (!N1->hasOneUse())
  20203. return SDValue();
  20204. bool N0AnyConst = isAnyConstantBuildVector(N0);
  20205. bool N1AnyConst = isAnyConstantBuildVector(N1);
  20206. if (N0AnyConst && !N1AnyConst && !ISD::isBuildVectorAllZeros(N0.getNode()))
  20207. return SDValue();
  20208. if (!N0AnyConst && N1AnyConst && !ISD::isBuildVectorAllZeros(N1.getNode()))
  20209. return SDValue();
  20210. }
  20211. // If both inputs are splats of the same value then we can safely merge this
  20212. // to a single BUILD_VECTOR with undef elements based on the shuffle mask.
  20213. bool IsSplat = false;
  20214. auto *BV0 = dyn_cast<BuildVectorSDNode>(N0);
  20215. auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
  20216. if (BV0 && BV1)
  20217. if (SDValue Splat0 = BV0->getSplatValue())
  20218. IsSplat = (Splat0 == BV1->getSplatValue());
  20219. SmallVector<SDValue, 8> Ops;
  20220. SmallSet<SDValue, 16> DuplicateOps;
  20221. for (int M : SVN->getMask()) {
  20222. SDValue Op = DAG.getUNDEF(VT.getScalarType());
  20223. if (M >= 0) {
  20224. int Idx = M < (int)NumElts ? M : M - NumElts;
  20225. SDValue &S = (M < (int)NumElts ? N0 : N1);
  20226. if (S.getOpcode() == ISD::BUILD_VECTOR) {
  20227. Op = S.getOperand(Idx);
  20228. } else if (S.getOpcode() == ISD::SCALAR_TO_VECTOR) {
  20229. SDValue Op0 = S.getOperand(0);
  20230. Op = Idx == 0 ? Op0 : DAG.getUNDEF(Op0.getValueType());
  20231. } else {
  20232. // Operand can't be combined - bail out.
  20233. return SDValue();
  20234. }
  20235. }
  20236. // Don't duplicate a non-constant BUILD_VECTOR operand unless we're
  20237. // generating a splat; semantically, this is fine, but it's likely to
  20238. // generate low-quality code if the target can't reconstruct an appropriate
  20239. // shuffle.
  20240. if (!Op.isUndef() && !isIntOrFPConstant(Op))
  20241. if (!IsSplat && !DuplicateOps.insert(Op).second)
  20242. return SDValue();
  20243. Ops.push_back(Op);
  20244. }
  20245. // BUILD_VECTOR requires all inputs to be of the same type, find the
  20246. // maximum type and extend them all.
  20247. EVT SVT = VT.getScalarType();
  20248. if (SVT.isInteger())
  20249. for (SDValue &Op : Ops)
  20250. SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
  20251. if (SVT != VT.getScalarType())
  20252. for (SDValue &Op : Ops)
  20253. Op = Op.isUndef() ? DAG.getUNDEF(SVT)
  20254. : (TLI.isZExtFree(Op.getValueType(), SVT)
  20255. ? DAG.getZExtOrTrunc(Op, SDLoc(SVN), SVT)
  20256. : DAG.getSExtOrTrunc(Op, SDLoc(SVN), SVT));
  20257. return DAG.getBuildVector(VT, SDLoc(SVN), Ops);
  20258. }
  20259. // Match shuffles that can be converted to *_vector_extend_in_reg.
  20260. // This is often generated during legalization.
  20261. // e.g. v4i32 <0,u,1,u> -> (v2i64 any_vector_extend_in_reg(v4i32 src)),
  20262. // and returns the EVT to which the extension should be performed.
  20263. // NOTE: this assumes that the src is the first operand of the shuffle.
  20264. static std::optional<EVT> canCombineShuffleToExtendVectorInreg(
  20265. unsigned Opcode, EVT VT, std::function<bool(unsigned)> Match,
  20266. SelectionDAG &DAG, const TargetLowering &TLI, bool LegalTypes,
  20267. bool LegalOperations) {
  20268. bool IsBigEndian = DAG.getDataLayout().isBigEndian();
  20269. // TODO Add support for big-endian when we have a test case.
  20270. if (!VT.isInteger() || IsBigEndian)
  20271. return std::nullopt;
  20272. unsigned NumElts = VT.getVectorNumElements();
  20273. unsigned EltSizeInBits = VT.getScalarSizeInBits();
  20274. // Attempt to match a '*_extend_vector_inreg' shuffle, we just search for
  20275. // power-of-2 extensions as they are the most likely.
  20276. // FIXME: should try Scale == NumElts case too,
  20277. for (unsigned Scale = 2; Scale < NumElts; Scale *= 2) {
  20278. // The vector width must be a multiple of Scale.
  20279. if (NumElts % Scale != 0)
  20280. continue;
  20281. EVT OutSVT = EVT::getIntegerVT(*DAG.getContext(), EltSizeInBits * Scale);
  20282. EVT OutVT = EVT::getVectorVT(*DAG.getContext(), OutSVT, NumElts / Scale);
  20283. if ((LegalTypes && !TLI.isTypeLegal(OutVT)) ||
  20284. (LegalOperations && !TLI.isOperationLegalOrCustom(Opcode, OutVT)))
  20285. continue;
  20286. if (Match(Scale))
  20287. return OutVT;
  20288. }
  20289. return std::nullopt;
  20290. }
  20291. // Match shuffles that can be converted to any_vector_extend_in_reg.
  20292. // This is often generated during legalization.
  20293. // e.g. v4i32 <0,u,1,u> -> (v2i64 any_vector_extend_in_reg(v4i32 src))
  20294. static SDValue combineShuffleToAnyExtendVectorInreg(ShuffleVectorSDNode *SVN,
  20295. SelectionDAG &DAG,
  20296. const TargetLowering &TLI,
  20297. bool LegalOperations) {
  20298. EVT VT = SVN->getValueType(0);
  20299. bool IsBigEndian = DAG.getDataLayout().isBigEndian();
  20300. // TODO Add support for big-endian when we have a test case.
  20301. if (!VT.isInteger() || IsBigEndian)
  20302. return SDValue();
  20303. // shuffle<0,-1,1,-1> == (v2i64 anyextend_vector_inreg(v4i32))
  20304. auto isAnyExtend = [NumElts = VT.getVectorNumElements(),
  20305. Mask = SVN->getMask()](unsigned Scale) {
  20306. for (unsigned i = 0; i != NumElts; ++i) {
  20307. if (Mask[i] < 0)
  20308. continue;
  20309. if ((i % Scale) == 0 && Mask[i] == (int)(i / Scale))
  20310. continue;
  20311. return false;
  20312. }
  20313. return true;
  20314. };
  20315. unsigned Opcode = ISD::ANY_EXTEND_VECTOR_INREG;
  20316. SDValue N0 = SVN->getOperand(0);
  20317. // Never create an illegal type. Only create unsupported operations if we
  20318. // are pre-legalization.
  20319. std::optional<EVT> OutVT = canCombineShuffleToExtendVectorInreg(
  20320. Opcode, VT, isAnyExtend, DAG, TLI, /*LegalTypes=*/true, LegalOperations);
  20321. if (!OutVT)
  20322. return SDValue();
  20323. return DAG.getBitcast(VT, DAG.getNode(Opcode, SDLoc(SVN), *OutVT, N0));
  20324. }
  20325. // Match shuffles that can be converted to zero_extend_vector_inreg.
  20326. // This is often generated during legalization.
  20327. // e.g. v4i32 <0,z,1,u> -> (v2i64 zero_extend_vector_inreg(v4i32 src))
  20328. static SDValue combineShuffleToZeroExtendVectorInReg(ShuffleVectorSDNode *SVN,
  20329. SelectionDAG &DAG,
  20330. const TargetLowering &TLI,
  20331. bool LegalOperations) {
  20332. bool LegalTypes = true;
  20333. EVT VT = SVN->getValueType(0);
  20334. assert(!VT.isScalableVector() && "Encountered scalable shuffle?");
  20335. unsigned NumElts = VT.getVectorNumElements();
  20336. unsigned EltSizeInBits = VT.getScalarSizeInBits();
  20337. // TODO: add support for big-endian when we have a test case.
  20338. bool IsBigEndian = DAG.getDataLayout().isBigEndian();
  20339. if (!VT.isInteger() || IsBigEndian)
  20340. return SDValue();
  20341. SmallVector<int, 16> Mask(SVN->getMask().begin(), SVN->getMask().end());
  20342. auto ForEachDecomposedIndice = [NumElts, &Mask](auto Fn) {
  20343. for (int &Indice : Mask) {
  20344. if (Indice < 0)
  20345. continue;
  20346. int OpIdx = (unsigned)Indice < NumElts ? 0 : 1;
  20347. int OpEltIdx = (unsigned)Indice < NumElts ? Indice : Indice - NumElts;
  20348. Fn(Indice, OpIdx, OpEltIdx);
  20349. }
  20350. };
  20351. // Which elements of which operand does this shuffle demand?
  20352. std::array<APInt, 2> OpsDemandedElts;
  20353. for (APInt &OpDemandedElts : OpsDemandedElts)
  20354. OpDemandedElts = APInt::getZero(NumElts);
  20355. ForEachDecomposedIndice(
  20356. [&OpsDemandedElts](int &Indice, int OpIdx, int OpEltIdx) {
  20357. OpsDemandedElts[OpIdx].setBit(OpEltIdx);
  20358. });
  20359. // Element-wise(!), which of these demanded elements are know to be zero?
  20360. std::array<APInt, 2> OpsKnownZeroElts;
  20361. for (auto I : zip(SVN->ops(), OpsDemandedElts, OpsKnownZeroElts))
  20362. std::get<2>(I) =
  20363. DAG.computeVectorKnownZeroElements(std::get<0>(I), std::get<1>(I));
  20364. // Manifest zeroable element knowledge in the shuffle mask.
  20365. // NOTE: we don't have 'zeroable' sentinel value in generic DAG,
  20366. // this is a local invention, but it won't leak into DAG.
  20367. // FIXME: should we not manifest them, but just check when matching?
  20368. bool HadZeroableElts = false;
  20369. ForEachDecomposedIndice([&OpsKnownZeroElts, &HadZeroableElts](
  20370. int &Indice, int OpIdx, int OpEltIdx) {
  20371. if (OpsKnownZeroElts[OpIdx][OpEltIdx]) {
  20372. Indice = -2; // Zeroable element.
  20373. HadZeroableElts = true;
  20374. }
  20375. });
  20376. // Don't proceed unless we've refined at least one zeroable mask indice.
  20377. // If we didn't, then we are still trying to match the same shuffle mask
  20378. // we previously tried to match as ISD::ANY_EXTEND_VECTOR_INREG,
  20379. // and evidently failed. Proceeding will lead to endless combine loops.
  20380. if (!HadZeroableElts)
  20381. return SDValue();
  20382. // The shuffle may be more fine-grained than we want. Widen elements first.
  20383. // FIXME: should we do this before manifesting zeroable shuffle mask indices?
  20384. SmallVector<int, 16> ScaledMask;
  20385. getShuffleMaskWithWidestElts(Mask, ScaledMask);
  20386. assert(Mask.size() >= ScaledMask.size() &&
  20387. Mask.size() % ScaledMask.size() == 0 && "Unexpected mask widening.");
  20388. int Prescale = Mask.size() / ScaledMask.size();
  20389. NumElts = ScaledMask.size();
  20390. EltSizeInBits *= Prescale;
  20391. EVT PrescaledVT = EVT::getVectorVT(
  20392. *DAG.getContext(), EVT::getIntegerVT(*DAG.getContext(), EltSizeInBits),
  20393. NumElts);
  20394. if (LegalTypes && !TLI.isTypeLegal(PrescaledVT) && TLI.isTypeLegal(VT))
  20395. return SDValue();
  20396. // For example,
  20397. // shuffle<0,z,1,-1> == (v2i64 zero_extend_vector_inreg(v4i32))
  20398. // But not shuffle<z,z,1,-1> and not shuffle<0,z,z,-1> ! (for same types)
  20399. auto isZeroExtend = [NumElts, &ScaledMask](unsigned Scale) {
  20400. assert(Scale >= 2 && Scale <= NumElts && NumElts % Scale == 0 &&
  20401. "Unexpected mask scaling factor.");
  20402. ArrayRef<int> Mask = ScaledMask;
  20403. for (unsigned SrcElt = 0, NumSrcElts = NumElts / Scale;
  20404. SrcElt != NumSrcElts; ++SrcElt) {
  20405. // Analyze the shuffle mask in Scale-sized chunks.
  20406. ArrayRef<int> MaskChunk = Mask.take_front(Scale);
  20407. assert(MaskChunk.size() == Scale && "Unexpected mask size.");
  20408. Mask = Mask.drop_front(MaskChunk.size());
  20409. // The first indice in this chunk must be SrcElt, but not zero!
  20410. // FIXME: undef should be fine, but that results in more-defined result.
  20411. if (int FirstIndice = MaskChunk[0]; (unsigned)FirstIndice != SrcElt)
  20412. return false;
  20413. // The rest of the indices in this chunk must be zeros.
  20414. // FIXME: undef should be fine, but that results in more-defined result.
  20415. if (!all_of(MaskChunk.drop_front(1),
  20416. [](int Indice) { return Indice == -2; }))
  20417. return false;
  20418. }
  20419. assert(Mask.empty() && "Did not process the whole mask?");
  20420. return true;
  20421. };
  20422. unsigned Opcode = ISD::ZERO_EXTEND_VECTOR_INREG;
  20423. for (bool Commuted : {false, true}) {
  20424. SDValue Op = SVN->getOperand(!Commuted ? 0 : 1);
  20425. if (Commuted)
  20426. ShuffleVectorSDNode::commuteMask(ScaledMask);
  20427. std::optional<EVT> OutVT = canCombineShuffleToExtendVectorInreg(
  20428. Opcode, PrescaledVT, isZeroExtend, DAG, TLI, LegalTypes,
  20429. LegalOperations);
  20430. if (OutVT)
  20431. return DAG.getBitcast(VT, DAG.getNode(Opcode, SDLoc(SVN), *OutVT,
  20432. DAG.getBitcast(PrescaledVT, Op)));
  20433. }
  20434. return SDValue();
  20435. }
  20436. // Detect 'truncate_vector_inreg' style shuffles that pack the lower parts of
  20437. // each source element of a large type into the lowest elements of a smaller
  20438. // destination type. This is often generated during legalization.
  20439. // If the source node itself was a '*_extend_vector_inreg' node then we should
  20440. // then be able to remove it.
  20441. static SDValue combineTruncationShuffle(ShuffleVectorSDNode *SVN,
  20442. SelectionDAG &DAG) {
  20443. EVT VT = SVN->getValueType(0);
  20444. bool IsBigEndian = DAG.getDataLayout().isBigEndian();
  20445. // TODO Add support for big-endian when we have a test case.
  20446. if (!VT.isInteger() || IsBigEndian)
  20447. return SDValue();
  20448. SDValue N0 = peekThroughBitcasts(SVN->getOperand(0));
  20449. unsigned Opcode = N0.getOpcode();
  20450. if (Opcode != ISD::ANY_EXTEND_VECTOR_INREG &&
  20451. Opcode != ISD::SIGN_EXTEND_VECTOR_INREG &&
  20452. Opcode != ISD::ZERO_EXTEND_VECTOR_INREG)
  20453. return SDValue();
  20454. SDValue N00 = N0.getOperand(0);
  20455. ArrayRef<int> Mask = SVN->getMask();
  20456. unsigned NumElts = VT.getVectorNumElements();
  20457. unsigned EltSizeInBits = VT.getScalarSizeInBits();
  20458. unsigned ExtSrcSizeInBits = N00.getScalarValueSizeInBits();
  20459. unsigned ExtDstSizeInBits = N0.getScalarValueSizeInBits();
  20460. if (ExtDstSizeInBits % ExtSrcSizeInBits != 0)
  20461. return SDValue();
  20462. unsigned ExtScale = ExtDstSizeInBits / ExtSrcSizeInBits;
  20463. // (v4i32 truncate_vector_inreg(v2i64)) == shuffle<0,2-1,-1>
  20464. // (v8i16 truncate_vector_inreg(v4i32)) == shuffle<0,2,4,6,-1,-1,-1,-1>
  20465. // (v8i16 truncate_vector_inreg(v2i64)) == shuffle<0,4,-1,-1,-1,-1,-1,-1>
  20466. auto isTruncate = [&Mask, &NumElts](unsigned Scale) {
  20467. for (unsigned i = 0; i != NumElts; ++i) {
  20468. if (Mask[i] < 0)
  20469. continue;
  20470. if ((i * Scale) < NumElts && Mask[i] == (int)(i * Scale))
  20471. continue;
  20472. return false;
  20473. }
  20474. return true;
  20475. };
  20476. // At the moment we just handle the case where we've truncated back to the
  20477. // same size as before the extension.
  20478. // TODO: handle more extension/truncation cases as cases arise.
  20479. if (EltSizeInBits != ExtSrcSizeInBits)
  20480. return SDValue();
  20481. // We can remove *extend_vector_inreg only if the truncation happens at
  20482. // the same scale as the extension.
  20483. if (isTruncate(ExtScale))
  20484. return DAG.getBitcast(VT, N00);
  20485. return SDValue();
  20486. }
  20487. // Combine shuffles of splat-shuffles of the form:
  20488. // shuffle (shuffle V, undef, splat-mask), undef, M
  20489. // If splat-mask contains undef elements, we need to be careful about
  20490. // introducing undef's in the folded mask which are not the result of composing
  20491. // the masks of the shuffles.
  20492. static SDValue combineShuffleOfSplatVal(ShuffleVectorSDNode *Shuf,
  20493. SelectionDAG &DAG) {
  20494. EVT VT = Shuf->getValueType(0);
  20495. unsigned NumElts = VT.getVectorNumElements();
  20496. if (!Shuf->getOperand(1).isUndef())
  20497. return SDValue();
  20498. // See if this unary non-splat shuffle actually *is* a splat shuffle,
  20499. // in disguise, with all demanded elements being identical.
  20500. // FIXME: this can be done per-operand.
  20501. if (!Shuf->isSplat()) {
  20502. APInt DemandedElts(NumElts, 0);
  20503. for (int Idx : Shuf->getMask()) {
  20504. if (Idx < 0)
  20505. continue; // Ignore sentinel indices.
  20506. assert((unsigned)Idx < NumElts && "Out-of-bounds shuffle indice?");
  20507. DemandedElts.setBit(Idx);
  20508. }
  20509. assert(DemandedElts.countPopulation() > 1 && "Is a splat shuffle already?");
  20510. APInt UndefElts;
  20511. if (DAG.isSplatValue(Shuf->getOperand(0), DemandedElts, UndefElts)) {
  20512. // Even if all demanded elements are splat, some of them could be undef.
  20513. // Which lowest demanded element is *not* known-undef?
  20514. std::optional<unsigned> MinNonUndefIdx;
  20515. for (int Idx : Shuf->getMask()) {
  20516. if (Idx < 0 || UndefElts[Idx])
  20517. continue; // Ignore sentinel indices, and undef elements.
  20518. MinNonUndefIdx = std::min<unsigned>(Idx, MinNonUndefIdx.value_or(~0U));
  20519. }
  20520. if (!MinNonUndefIdx)
  20521. return DAG.getUNDEF(VT); // All undef - result is undef.
  20522. assert(*MinNonUndefIdx < NumElts && "Expected valid element index.");
  20523. SmallVector<int, 8> SplatMask(Shuf->getMask().begin(),
  20524. Shuf->getMask().end());
  20525. for (int &Idx : SplatMask) {
  20526. if (Idx < 0)
  20527. continue; // Passthrough sentinel indices.
  20528. // Otherwise, just pick the lowest demanded non-undef element.
  20529. // Or sentinel undef, if we know we'd pick a known-undef element.
  20530. Idx = UndefElts[Idx] ? -1 : *MinNonUndefIdx;
  20531. }
  20532. assert(SplatMask != Shuf->getMask() && "Expected mask to change!");
  20533. return DAG.getVectorShuffle(VT, SDLoc(Shuf), Shuf->getOperand(0),
  20534. Shuf->getOperand(1), SplatMask);
  20535. }
  20536. }
  20537. // If the inner operand is a known splat with no undefs, just return that directly.
  20538. // TODO: Create DemandedElts mask from Shuf's mask.
  20539. // TODO: Allow undef elements and merge with the shuffle code below.
  20540. if (DAG.isSplatValue(Shuf->getOperand(0), /*AllowUndefs*/ false))
  20541. return Shuf->getOperand(0);
  20542. auto *Splat = dyn_cast<ShuffleVectorSDNode>(Shuf->getOperand(0));
  20543. if (!Splat || !Splat->isSplat())
  20544. return SDValue();
  20545. ArrayRef<int> ShufMask = Shuf->getMask();
  20546. ArrayRef<int> SplatMask = Splat->getMask();
  20547. assert(ShufMask.size() == SplatMask.size() && "Mask length mismatch");
  20548. // Prefer simplifying to the splat-shuffle, if possible. This is legal if
  20549. // every undef mask element in the splat-shuffle has a corresponding undef
  20550. // element in the user-shuffle's mask or if the composition of mask elements
  20551. // would result in undef.
  20552. // Examples for (shuffle (shuffle v, undef, SplatMask), undef, UserMask):
  20553. // * UserMask=[0,2,u,u], SplatMask=[2,u,2,u] -> [2,2,u,u]
  20554. // In this case it is not legal to simplify to the splat-shuffle because we
  20555. // may be exposing the users of the shuffle an undef element at index 1
  20556. // which was not there before the combine.
  20557. // * UserMask=[0,u,2,u], SplatMask=[2,u,2,u] -> [2,u,2,u]
  20558. // In this case the composition of masks yields SplatMask, so it's ok to
  20559. // simplify to the splat-shuffle.
  20560. // * UserMask=[3,u,2,u], SplatMask=[2,u,2,u] -> [u,u,2,u]
  20561. // In this case the composed mask includes all undef elements of SplatMask
  20562. // and in addition sets element zero to undef. It is safe to simplify to
  20563. // the splat-shuffle.
  20564. auto CanSimplifyToExistingSplat = [](ArrayRef<int> UserMask,
  20565. ArrayRef<int> SplatMask) {
  20566. for (unsigned i = 0, e = UserMask.size(); i != e; ++i)
  20567. if (UserMask[i] != -1 && SplatMask[i] == -1 &&
  20568. SplatMask[UserMask[i]] != -1)
  20569. return false;
  20570. return true;
  20571. };
  20572. if (CanSimplifyToExistingSplat(ShufMask, SplatMask))
  20573. return Shuf->getOperand(0);
  20574. // Create a new shuffle with a mask that is composed of the two shuffles'
  20575. // masks.
  20576. SmallVector<int, 32> NewMask;
  20577. for (int Idx : ShufMask)
  20578. NewMask.push_back(Idx == -1 ? -1 : SplatMask[Idx]);
  20579. return DAG.getVectorShuffle(Splat->getValueType(0), SDLoc(Splat),
  20580. Splat->getOperand(0), Splat->getOperand(1),
  20581. NewMask);
  20582. }
  20583. // Combine shuffles of bitcasts into a shuffle of the bitcast type, providing
  20584. // the mask can be treated as a larger type.
  20585. static SDValue combineShuffleOfBitcast(ShuffleVectorSDNode *SVN,
  20586. SelectionDAG &DAG,
  20587. const TargetLowering &TLI,
  20588. bool LegalOperations) {
  20589. SDValue Op0 = SVN->getOperand(0);
  20590. SDValue Op1 = SVN->getOperand(1);
  20591. EVT VT = SVN->getValueType(0);
  20592. if (Op0.getOpcode() != ISD::BITCAST)
  20593. return SDValue();
  20594. EVT InVT = Op0.getOperand(0).getValueType();
  20595. if (!InVT.isVector() ||
  20596. (!Op1.isUndef() && (Op1.getOpcode() != ISD::BITCAST ||
  20597. Op1.getOperand(0).getValueType() != InVT)))
  20598. return SDValue();
  20599. if (isAnyConstantBuildVector(Op0.getOperand(0)) &&
  20600. (Op1.isUndef() || isAnyConstantBuildVector(Op1.getOperand(0))))
  20601. return SDValue();
  20602. int VTLanes = VT.getVectorNumElements();
  20603. int InLanes = InVT.getVectorNumElements();
  20604. if (VTLanes <= InLanes || VTLanes % InLanes != 0 ||
  20605. (LegalOperations &&
  20606. !TLI.isOperationLegalOrCustom(ISD::VECTOR_SHUFFLE, InVT)))
  20607. return SDValue();
  20608. int Factor = VTLanes / InLanes;
  20609. // Check that each group of lanes in the mask are either undef or make a valid
  20610. // mask for the wider lane type.
  20611. ArrayRef<int> Mask = SVN->getMask();
  20612. SmallVector<int> NewMask;
  20613. if (!widenShuffleMaskElts(Factor, Mask, NewMask))
  20614. return SDValue();
  20615. if (!TLI.isShuffleMaskLegal(NewMask, InVT))
  20616. return SDValue();
  20617. // Create the new shuffle with the new mask and bitcast it back to the
  20618. // original type.
  20619. SDLoc DL(SVN);
  20620. Op0 = Op0.getOperand(0);
  20621. Op1 = Op1.isUndef() ? DAG.getUNDEF(InVT) : Op1.getOperand(0);
  20622. SDValue NewShuf = DAG.getVectorShuffle(InVT, DL, Op0, Op1, NewMask);
  20623. return DAG.getBitcast(VT, NewShuf);
  20624. }
  20625. /// Combine shuffle of shuffle of the form:
  20626. /// shuf (shuf X, undef, InnerMask), undef, OuterMask --> splat X
  20627. static SDValue formSplatFromShuffles(ShuffleVectorSDNode *OuterShuf,
  20628. SelectionDAG &DAG) {
  20629. if (!OuterShuf->getOperand(1).isUndef())
  20630. return SDValue();
  20631. auto *InnerShuf = dyn_cast<ShuffleVectorSDNode>(OuterShuf->getOperand(0));
  20632. if (!InnerShuf || !InnerShuf->getOperand(1).isUndef())
  20633. return SDValue();
  20634. ArrayRef<int> OuterMask = OuterShuf->getMask();
  20635. ArrayRef<int> InnerMask = InnerShuf->getMask();
  20636. unsigned NumElts = OuterMask.size();
  20637. assert(NumElts == InnerMask.size() && "Mask length mismatch");
  20638. SmallVector<int, 32> CombinedMask(NumElts, -1);
  20639. int SplatIndex = -1;
  20640. for (unsigned i = 0; i != NumElts; ++i) {
  20641. // Undef lanes remain undef.
  20642. int OuterMaskElt = OuterMask[i];
  20643. if (OuterMaskElt == -1)
  20644. continue;
  20645. // Peek through the shuffle masks to get the underlying source element.
  20646. int InnerMaskElt = InnerMask[OuterMaskElt];
  20647. if (InnerMaskElt == -1)
  20648. continue;
  20649. // Initialize the splatted element.
  20650. if (SplatIndex == -1)
  20651. SplatIndex = InnerMaskElt;
  20652. // Non-matching index - this is not a splat.
  20653. if (SplatIndex != InnerMaskElt)
  20654. return SDValue();
  20655. CombinedMask[i] = InnerMaskElt;
  20656. }
  20657. assert((all_of(CombinedMask, [](int M) { return M == -1; }) ||
  20658. getSplatIndex(CombinedMask) != -1) &&
  20659. "Expected a splat mask");
  20660. // TODO: The transform may be a win even if the mask is not legal.
  20661. EVT VT = OuterShuf->getValueType(0);
  20662. assert(VT == InnerShuf->getValueType(0) && "Expected matching shuffle types");
  20663. if (!DAG.getTargetLoweringInfo().isShuffleMaskLegal(CombinedMask, VT))
  20664. return SDValue();
  20665. return DAG.getVectorShuffle(VT, SDLoc(OuterShuf), InnerShuf->getOperand(0),
  20666. InnerShuf->getOperand(1), CombinedMask);
  20667. }
  20668. /// If the shuffle mask is taking exactly one element from the first vector
  20669. /// operand and passing through all other elements from the second vector
  20670. /// operand, return the index of the mask element that is choosing an element
  20671. /// from the first operand. Otherwise, return -1.
  20672. static int getShuffleMaskIndexOfOneElementFromOp0IntoOp1(ArrayRef<int> Mask) {
  20673. int MaskSize = Mask.size();
  20674. int EltFromOp0 = -1;
  20675. // TODO: This does not match if there are undef elements in the shuffle mask.
  20676. // Should we ignore undefs in the shuffle mask instead? The trade-off is
  20677. // removing an instruction (a shuffle), but losing the knowledge that some
  20678. // vector lanes are not needed.
  20679. for (int i = 0; i != MaskSize; ++i) {
  20680. if (Mask[i] >= 0 && Mask[i] < MaskSize) {
  20681. // We're looking for a shuffle of exactly one element from operand 0.
  20682. if (EltFromOp0 != -1)
  20683. return -1;
  20684. EltFromOp0 = i;
  20685. } else if (Mask[i] != i + MaskSize) {
  20686. // Nothing from operand 1 can change lanes.
  20687. return -1;
  20688. }
  20689. }
  20690. return EltFromOp0;
  20691. }
  20692. /// If a shuffle inserts exactly one element from a source vector operand into
  20693. /// another vector operand and we can access the specified element as a scalar,
  20694. /// then we can eliminate the shuffle.
  20695. static SDValue replaceShuffleOfInsert(ShuffleVectorSDNode *Shuf,
  20696. SelectionDAG &DAG) {
  20697. // First, check if we are taking one element of a vector and shuffling that
  20698. // element into another vector.
  20699. ArrayRef<int> Mask = Shuf->getMask();
  20700. SmallVector<int, 16> CommutedMask(Mask);
  20701. SDValue Op0 = Shuf->getOperand(0);
  20702. SDValue Op1 = Shuf->getOperand(1);
  20703. int ShufOp0Index = getShuffleMaskIndexOfOneElementFromOp0IntoOp1(Mask);
  20704. if (ShufOp0Index == -1) {
  20705. // Commute mask and check again.
  20706. ShuffleVectorSDNode::commuteMask(CommutedMask);
  20707. ShufOp0Index = getShuffleMaskIndexOfOneElementFromOp0IntoOp1(CommutedMask);
  20708. if (ShufOp0Index == -1)
  20709. return SDValue();
  20710. // Commute operands to match the commuted shuffle mask.
  20711. std::swap(Op0, Op1);
  20712. Mask = CommutedMask;
  20713. }
  20714. // The shuffle inserts exactly one element from operand 0 into operand 1.
  20715. // Now see if we can access that element as a scalar via a real insert element
  20716. // instruction.
  20717. // TODO: We can try harder to locate the element as a scalar. Examples: it
  20718. // could be an operand of SCALAR_TO_VECTOR, BUILD_VECTOR, or a constant.
  20719. assert(Mask[ShufOp0Index] >= 0 && Mask[ShufOp0Index] < (int)Mask.size() &&
  20720. "Shuffle mask value must be from operand 0");
  20721. if (Op0.getOpcode() != ISD::INSERT_VECTOR_ELT)
  20722. return SDValue();
  20723. auto *InsIndexC = dyn_cast<ConstantSDNode>(Op0.getOperand(2));
  20724. if (!InsIndexC || InsIndexC->getSExtValue() != Mask[ShufOp0Index])
  20725. return SDValue();
  20726. // There's an existing insertelement with constant insertion index, so we
  20727. // don't need to check the legality/profitability of a replacement operation
  20728. // that differs at most in the constant value. The target should be able to
  20729. // lower any of those in a similar way. If not, legalization will expand this
  20730. // to a scalar-to-vector plus shuffle.
  20731. //
  20732. // Note that the shuffle may move the scalar from the position that the insert
  20733. // element used. Therefore, our new insert element occurs at the shuffle's
  20734. // mask index value, not the insert's index value.
  20735. // shuffle (insertelt v1, x, C), v2, mask --> insertelt v2, x, C'
  20736. SDValue NewInsIndex = DAG.getVectorIdxConstant(ShufOp0Index, SDLoc(Shuf));
  20737. return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(Shuf), Op0.getValueType(),
  20738. Op1, Op0.getOperand(1), NewInsIndex);
  20739. }
  20740. /// If we have a unary shuffle of a shuffle, see if it can be folded away
  20741. /// completely. This has the potential to lose undef knowledge because the first
  20742. /// shuffle may not have an undef mask element where the second one does. So
  20743. /// only call this after doing simplifications based on demanded elements.
  20744. static SDValue simplifyShuffleOfShuffle(ShuffleVectorSDNode *Shuf) {
  20745. // shuf (shuf0 X, Y, Mask0), undef, Mask
  20746. auto *Shuf0 = dyn_cast<ShuffleVectorSDNode>(Shuf->getOperand(0));
  20747. if (!Shuf0 || !Shuf->getOperand(1).isUndef())
  20748. return SDValue();
  20749. ArrayRef<int> Mask = Shuf->getMask();
  20750. ArrayRef<int> Mask0 = Shuf0->getMask();
  20751. for (int i = 0, e = (int)Mask.size(); i != e; ++i) {
  20752. // Ignore undef elements.
  20753. if (Mask[i] == -1)
  20754. continue;
  20755. assert(Mask[i] >= 0 && Mask[i] < e && "Unexpected shuffle mask value");
  20756. // Is the element of the shuffle operand chosen by this shuffle the same as
  20757. // the element chosen by the shuffle operand itself?
  20758. if (Mask0[Mask[i]] != Mask0[i])
  20759. return SDValue();
  20760. }
  20761. // Every element of this shuffle is identical to the result of the previous
  20762. // shuffle, so we can replace this value.
  20763. return Shuf->getOperand(0);
  20764. }
  20765. SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
  20766. EVT VT = N->getValueType(0);
  20767. unsigned NumElts = VT.getVectorNumElements();
  20768. SDValue N0 = N->getOperand(0);
  20769. SDValue N1 = N->getOperand(1);
  20770. assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
  20771. // Canonicalize shuffle undef, undef -> undef
  20772. if (N0.isUndef() && N1.isUndef())
  20773. return DAG.getUNDEF(VT);
  20774. ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
  20775. // Canonicalize shuffle v, v -> v, undef
  20776. if (N0 == N1)
  20777. return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
  20778. createUnaryMask(SVN->getMask(), NumElts));
  20779. // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
  20780. if (N0.isUndef())
  20781. return DAG.getCommutedVectorShuffle(*SVN);
  20782. // Remove references to rhs if it is undef
  20783. if (N1.isUndef()) {
  20784. bool Changed = false;
  20785. SmallVector<int, 8> NewMask;
  20786. for (unsigned i = 0; i != NumElts; ++i) {
  20787. int Idx = SVN->getMaskElt(i);
  20788. if (Idx >= (int)NumElts) {
  20789. Idx = -1;
  20790. Changed = true;
  20791. }
  20792. NewMask.push_back(Idx);
  20793. }
  20794. if (Changed)
  20795. return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, NewMask);
  20796. }
  20797. if (SDValue InsElt = replaceShuffleOfInsert(SVN, DAG))
  20798. return InsElt;
  20799. // A shuffle of a single vector that is a splatted value can always be folded.
  20800. if (SDValue V = combineShuffleOfSplatVal(SVN, DAG))
  20801. return V;
  20802. if (SDValue V = formSplatFromShuffles(SVN, DAG))
  20803. return V;
  20804. // If it is a splat, check if the argument vector is another splat or a
  20805. // build_vector.
  20806. if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
  20807. int SplatIndex = SVN->getSplatIndex();
  20808. if (N0.hasOneUse() && TLI.isExtractVecEltCheap(VT, SplatIndex) &&
  20809. TLI.isBinOp(N0.getOpcode()) && N0->getNumValues() == 1) {
  20810. // splat (vector_bo L, R), Index -->
  20811. // splat (scalar_bo (extelt L, Index), (extelt R, Index))
  20812. SDValue L = N0.getOperand(0), R = N0.getOperand(1);
  20813. SDLoc DL(N);
  20814. EVT EltVT = VT.getScalarType();
  20815. SDValue Index = DAG.getVectorIdxConstant(SplatIndex, DL);
  20816. SDValue ExtL = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, L, Index);
  20817. SDValue ExtR = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, R, Index);
  20818. SDValue NewBO =
  20819. DAG.getNode(N0.getOpcode(), DL, EltVT, ExtL, ExtR, N0->getFlags());
  20820. SDValue Insert = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VT, NewBO);
  20821. SmallVector<int, 16> ZeroMask(VT.getVectorNumElements(), 0);
  20822. return DAG.getVectorShuffle(VT, DL, Insert, DAG.getUNDEF(VT), ZeroMask);
  20823. }
  20824. // splat(scalar_to_vector(x), 0) -> build_vector(x,...,x)
  20825. // splat(insert_vector_elt(v, x, c), c) -> build_vector(x,...,x)
  20826. if ((!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)) &&
  20827. N0.hasOneUse()) {
  20828. if (N0.getOpcode() == ISD::SCALAR_TO_VECTOR && SplatIndex == 0)
  20829. return DAG.getSplatBuildVector(VT, SDLoc(N), N0.getOperand(0));
  20830. if (N0.getOpcode() == ISD::INSERT_VECTOR_ELT)
  20831. if (auto *Idx = dyn_cast<ConstantSDNode>(N0.getOperand(2)))
  20832. if (Idx->getAPIntValue() == SplatIndex)
  20833. return DAG.getSplatBuildVector(VT, SDLoc(N), N0.getOperand(1));
  20834. // Look through a bitcast if LE and splatting lane 0, through to a
  20835. // scalar_to_vector or a build_vector.
  20836. if (N0.getOpcode() == ISD::BITCAST && N0.getOperand(0).hasOneUse() &&
  20837. SplatIndex == 0 && DAG.getDataLayout().isLittleEndian() &&
  20838. (N0.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR ||
  20839. N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR)) {
  20840. EVT N00VT = N0.getOperand(0).getValueType();
  20841. if (VT.getScalarSizeInBits() <= N00VT.getScalarSizeInBits() &&
  20842. VT.isInteger() && N00VT.isInteger()) {
  20843. EVT InVT =
  20844. TLI.getTypeToTransformTo(*DAG.getContext(), VT.getScalarType());
  20845. SDValue Op = DAG.getZExtOrTrunc(N0.getOperand(0).getOperand(0),
  20846. SDLoc(N), InVT);
  20847. return DAG.getSplatBuildVector(VT, SDLoc(N), Op);
  20848. }
  20849. }
  20850. }
  20851. // If this is a bit convert that changes the element type of the vector but
  20852. // not the number of vector elements, look through it. Be careful not to
  20853. // look though conversions that change things like v4f32 to v2f64.
  20854. SDNode *V = N0.getNode();
  20855. if (V->getOpcode() == ISD::BITCAST) {
  20856. SDValue ConvInput = V->getOperand(0);
  20857. if (ConvInput.getValueType().isVector() &&
  20858. ConvInput.getValueType().getVectorNumElements() == NumElts)
  20859. V = ConvInput.getNode();
  20860. }
  20861. if (V->getOpcode() == ISD::BUILD_VECTOR) {
  20862. assert(V->getNumOperands() == NumElts &&
  20863. "BUILD_VECTOR has wrong number of operands");
  20864. SDValue Base;
  20865. bool AllSame = true;
  20866. for (unsigned i = 0; i != NumElts; ++i) {
  20867. if (!V->getOperand(i).isUndef()) {
  20868. Base = V->getOperand(i);
  20869. break;
  20870. }
  20871. }
  20872. // Splat of <u, u, u, u>, return <u, u, u, u>
  20873. if (!Base.getNode())
  20874. return N0;
  20875. for (unsigned i = 0; i != NumElts; ++i) {
  20876. if (V->getOperand(i) != Base) {
  20877. AllSame = false;
  20878. break;
  20879. }
  20880. }
  20881. // Splat of <x, x, x, x>, return <x, x, x, x>
  20882. if (AllSame)
  20883. return N0;
  20884. // Canonicalize any other splat as a build_vector.
  20885. SDValue Splatted = V->getOperand(SplatIndex);
  20886. SmallVector<SDValue, 8> Ops(NumElts, Splatted);
  20887. SDValue NewBV = DAG.getBuildVector(V->getValueType(0), SDLoc(N), Ops);
  20888. // We may have jumped through bitcasts, so the type of the
  20889. // BUILD_VECTOR may not match the type of the shuffle.
  20890. if (V->getValueType(0) != VT)
  20891. NewBV = DAG.getBitcast(VT, NewBV);
  20892. return NewBV;
  20893. }
  20894. }
  20895. // Simplify source operands based on shuffle mask.
  20896. if (SimplifyDemandedVectorElts(SDValue(N, 0)))
  20897. return SDValue(N, 0);
  20898. // This is intentionally placed after demanded elements simplification because
  20899. // it could eliminate knowledge of undef elements created by this shuffle.
  20900. if (SDValue ShufOp = simplifyShuffleOfShuffle(SVN))
  20901. return ShufOp;
  20902. // Match shuffles that can be converted to any_vector_extend_in_reg.
  20903. if (SDValue V =
  20904. combineShuffleToAnyExtendVectorInreg(SVN, DAG, TLI, LegalOperations))
  20905. return V;
  20906. // Combine "truncate_vector_in_reg" style shuffles.
  20907. if (SDValue V = combineTruncationShuffle(SVN, DAG))
  20908. return V;
  20909. if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
  20910. Level < AfterLegalizeVectorOps &&
  20911. (N1.isUndef() ||
  20912. (N1.getOpcode() == ISD::CONCAT_VECTORS &&
  20913. N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
  20914. if (SDValue V = partitionShuffleOfConcats(N, DAG))
  20915. return V;
  20916. }
  20917. // A shuffle of a concat of the same narrow vector can be reduced to use
  20918. // only low-half elements of a concat with undef:
  20919. // shuf (concat X, X), undef, Mask --> shuf (concat X, undef), undef, Mask'
  20920. if (N0.getOpcode() == ISD::CONCAT_VECTORS && N1.isUndef() &&
  20921. N0.getNumOperands() == 2 &&
  20922. N0.getOperand(0) == N0.getOperand(1)) {
  20923. int HalfNumElts = (int)NumElts / 2;
  20924. SmallVector<int, 8> NewMask;
  20925. for (unsigned i = 0; i != NumElts; ++i) {
  20926. int Idx = SVN->getMaskElt(i);
  20927. if (Idx >= HalfNumElts) {
  20928. assert(Idx < (int)NumElts && "Shuffle mask chooses undef op");
  20929. Idx -= HalfNumElts;
  20930. }
  20931. NewMask.push_back(Idx);
  20932. }
  20933. if (TLI.isShuffleMaskLegal(NewMask, VT)) {
  20934. SDValue UndefVec = DAG.getUNDEF(N0.getOperand(0).getValueType());
  20935. SDValue NewCat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
  20936. N0.getOperand(0), UndefVec);
  20937. return DAG.getVectorShuffle(VT, SDLoc(N), NewCat, N1, NewMask);
  20938. }
  20939. }
  20940. // See if we can replace a shuffle with an insert_subvector.
  20941. // e.g. v2i32 into v8i32:
  20942. // shuffle(lhs,concat(rhs0,rhs1,rhs2,rhs3),0,1,2,3,10,11,6,7).
  20943. // --> insert_subvector(lhs,rhs1,4).
  20944. if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT) &&
  20945. TLI.isOperationLegalOrCustom(ISD::INSERT_SUBVECTOR, VT)) {
  20946. auto ShuffleToInsert = [&](SDValue LHS, SDValue RHS, ArrayRef<int> Mask) {
  20947. // Ensure RHS subvectors are legal.
  20948. assert(RHS.getOpcode() == ISD::CONCAT_VECTORS && "Can't find subvectors");
  20949. EVT SubVT = RHS.getOperand(0).getValueType();
  20950. int NumSubVecs = RHS.getNumOperands();
  20951. int NumSubElts = SubVT.getVectorNumElements();
  20952. assert((NumElts % NumSubElts) == 0 && "Subvector mismatch");
  20953. if (!TLI.isTypeLegal(SubVT))
  20954. return SDValue();
  20955. // Don't bother if we have an unary shuffle (matches undef + LHS elts).
  20956. if (all_of(Mask, [NumElts](int M) { return M < (int)NumElts; }))
  20957. return SDValue();
  20958. // Search [NumSubElts] spans for RHS sequence.
  20959. // TODO: Can we avoid nested loops to increase performance?
  20960. SmallVector<int> InsertionMask(NumElts);
  20961. for (int SubVec = 0; SubVec != NumSubVecs; ++SubVec) {
  20962. for (int SubIdx = 0; SubIdx != (int)NumElts; SubIdx += NumSubElts) {
  20963. // Reset mask to identity.
  20964. std::iota(InsertionMask.begin(), InsertionMask.end(), 0);
  20965. // Add subvector insertion.
  20966. std::iota(InsertionMask.begin() + SubIdx,
  20967. InsertionMask.begin() + SubIdx + NumSubElts,
  20968. NumElts + (SubVec * NumSubElts));
  20969. // See if the shuffle mask matches the reference insertion mask.
  20970. bool MatchingShuffle = true;
  20971. for (int i = 0; i != (int)NumElts; ++i) {
  20972. int ExpectIdx = InsertionMask[i];
  20973. int ActualIdx = Mask[i];
  20974. if (0 <= ActualIdx && ExpectIdx != ActualIdx) {
  20975. MatchingShuffle = false;
  20976. break;
  20977. }
  20978. }
  20979. if (MatchingShuffle)
  20980. return DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N), VT, LHS,
  20981. RHS.getOperand(SubVec),
  20982. DAG.getVectorIdxConstant(SubIdx, SDLoc(N)));
  20983. }
  20984. }
  20985. return SDValue();
  20986. };
  20987. ArrayRef<int> Mask = SVN->getMask();
  20988. if (N1.getOpcode() == ISD::CONCAT_VECTORS)
  20989. if (SDValue InsertN1 = ShuffleToInsert(N0, N1, Mask))
  20990. return InsertN1;
  20991. if (N0.getOpcode() == ISD::CONCAT_VECTORS) {
  20992. SmallVector<int> CommuteMask(Mask);
  20993. ShuffleVectorSDNode::commuteMask(CommuteMask);
  20994. if (SDValue InsertN0 = ShuffleToInsert(N1, N0, CommuteMask))
  20995. return InsertN0;
  20996. }
  20997. }
  20998. // If we're not performing a select/blend shuffle, see if we can convert the
  20999. // shuffle into a AND node, with all the out-of-lane elements are known zero.
  21000. if (Level < AfterLegalizeDAG && TLI.isTypeLegal(VT)) {
  21001. bool IsInLaneMask = true;
  21002. ArrayRef<int> Mask = SVN->getMask();
  21003. SmallVector<int, 16> ClearMask(NumElts, -1);
  21004. APInt DemandedLHS = APInt::getNullValue(NumElts);
  21005. APInt DemandedRHS = APInt::getNullValue(NumElts);
  21006. for (int I = 0; I != (int)NumElts; ++I) {
  21007. int M = Mask[I];
  21008. if (M < 0)
  21009. continue;
  21010. ClearMask[I] = M == I ? I : (I + NumElts);
  21011. IsInLaneMask &= (M == I) || (M == (int)(I + NumElts));
  21012. if (M != I) {
  21013. APInt &Demanded = M < (int)NumElts ? DemandedLHS : DemandedRHS;
  21014. Demanded.setBit(M % NumElts);
  21015. }
  21016. }
  21017. // TODO: Should we try to mask with N1 as well?
  21018. if (!IsInLaneMask &&
  21019. (!DemandedLHS.isNullValue() || !DemandedRHS.isNullValue()) &&
  21020. (DemandedLHS.isNullValue() ||
  21021. DAG.MaskedVectorIsZero(N0, DemandedLHS)) &&
  21022. (DemandedRHS.isNullValue() ||
  21023. DAG.MaskedVectorIsZero(N1, DemandedRHS))) {
  21024. SDLoc DL(N);
  21025. EVT IntVT = VT.changeVectorElementTypeToInteger();
  21026. EVT IntSVT = VT.getVectorElementType().changeTypeToInteger();
  21027. // Transform the type to a legal type so that the buildvector constant
  21028. // elements are not illegal. Make sure that the result is larger than the
  21029. // original type, incase the value is split into two (eg i64->i32).
  21030. if (!TLI.isTypeLegal(IntSVT) && LegalTypes)
  21031. IntSVT = TLI.getTypeToTransformTo(*DAG.getContext(), IntSVT);
  21032. if (IntSVT.getSizeInBits() >= IntVT.getScalarSizeInBits()) {
  21033. SDValue ZeroElt = DAG.getConstant(0, DL, IntSVT);
  21034. SDValue AllOnesElt = DAG.getAllOnesConstant(DL, IntSVT);
  21035. SmallVector<SDValue, 16> AndMask(NumElts, DAG.getUNDEF(IntSVT));
  21036. for (int I = 0; I != (int)NumElts; ++I)
  21037. if (0 <= Mask[I])
  21038. AndMask[I] = Mask[I] == I ? AllOnesElt : ZeroElt;
  21039. // See if a clear mask is legal instead of going via
  21040. // XformToShuffleWithZero which loses UNDEF mask elements.
  21041. if (TLI.isVectorClearMaskLegal(ClearMask, IntVT))
  21042. return DAG.getBitcast(
  21043. VT, DAG.getVectorShuffle(IntVT, DL, DAG.getBitcast(IntVT, N0),
  21044. DAG.getConstant(0, DL, IntVT), ClearMask));
  21045. if (TLI.isOperationLegalOrCustom(ISD::AND, IntVT))
  21046. return DAG.getBitcast(
  21047. VT, DAG.getNode(ISD::AND, DL, IntVT, DAG.getBitcast(IntVT, N0),
  21048. DAG.getBuildVector(IntVT, DL, AndMask)));
  21049. }
  21050. }
  21051. }
  21052. // Attempt to combine a shuffle of 2 inputs of 'scalar sources' -
  21053. // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR.
  21054. if (Level < AfterLegalizeDAG && TLI.isTypeLegal(VT))
  21055. if (SDValue Res = combineShuffleOfScalars(SVN, DAG, TLI))
  21056. return Res;
  21057. // If this shuffle only has a single input that is a bitcasted shuffle,
  21058. // attempt to merge the 2 shuffles and suitably bitcast the inputs/output
  21059. // back to their original types.
  21060. if (N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
  21061. N1.isUndef() && Level < AfterLegalizeVectorOps &&
  21062. TLI.isTypeLegal(VT)) {
  21063. SDValue BC0 = peekThroughOneUseBitcasts(N0);
  21064. if (BC0.getOpcode() == ISD::VECTOR_SHUFFLE && BC0.hasOneUse()) {
  21065. EVT SVT = VT.getScalarType();
  21066. EVT InnerVT = BC0->getValueType(0);
  21067. EVT InnerSVT = InnerVT.getScalarType();
  21068. // Determine which shuffle works with the smaller scalar type.
  21069. EVT ScaleVT = SVT.bitsLT(InnerSVT) ? VT : InnerVT;
  21070. EVT ScaleSVT = ScaleVT.getScalarType();
  21071. if (TLI.isTypeLegal(ScaleVT) &&
  21072. 0 == (InnerSVT.getSizeInBits() % ScaleSVT.getSizeInBits()) &&
  21073. 0 == (SVT.getSizeInBits() % ScaleSVT.getSizeInBits())) {
  21074. int InnerScale = InnerSVT.getSizeInBits() / ScaleSVT.getSizeInBits();
  21075. int OuterScale = SVT.getSizeInBits() / ScaleSVT.getSizeInBits();
  21076. // Scale the shuffle masks to the smaller scalar type.
  21077. ShuffleVectorSDNode *InnerSVN = cast<ShuffleVectorSDNode>(BC0);
  21078. SmallVector<int, 8> InnerMask;
  21079. SmallVector<int, 8> OuterMask;
  21080. narrowShuffleMaskElts(InnerScale, InnerSVN->getMask(), InnerMask);
  21081. narrowShuffleMaskElts(OuterScale, SVN->getMask(), OuterMask);
  21082. // Merge the shuffle masks.
  21083. SmallVector<int, 8> NewMask;
  21084. for (int M : OuterMask)
  21085. NewMask.push_back(M < 0 ? -1 : InnerMask[M]);
  21086. // Test for shuffle mask legality over both commutations.
  21087. SDValue SV0 = BC0->getOperand(0);
  21088. SDValue SV1 = BC0->getOperand(1);
  21089. bool LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
  21090. if (!LegalMask) {
  21091. std::swap(SV0, SV1);
  21092. ShuffleVectorSDNode::commuteMask(NewMask);
  21093. LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
  21094. }
  21095. if (LegalMask) {
  21096. SV0 = DAG.getBitcast(ScaleVT, SV0);
  21097. SV1 = DAG.getBitcast(ScaleVT, SV1);
  21098. return DAG.getBitcast(
  21099. VT, DAG.getVectorShuffle(ScaleVT, SDLoc(N), SV0, SV1, NewMask));
  21100. }
  21101. }
  21102. }
  21103. }
  21104. // Match shuffles of bitcasts, so long as the mask can be treated as the
  21105. // larger type.
  21106. if (SDValue V = combineShuffleOfBitcast(SVN, DAG, TLI, LegalOperations))
  21107. return V;
  21108. // Compute the combined shuffle mask for a shuffle with SV0 as the first
  21109. // operand, and SV1 as the second operand.
  21110. // i.e. Merge SVN(OtherSVN, N1) -> shuffle(SV0, SV1, Mask) iff Commute = false
  21111. // Merge SVN(N1, OtherSVN) -> shuffle(SV0, SV1, Mask') iff Commute = true
  21112. auto MergeInnerShuffle =
  21113. [NumElts, &VT](bool Commute, ShuffleVectorSDNode *SVN,
  21114. ShuffleVectorSDNode *OtherSVN, SDValue N1,
  21115. const TargetLowering &TLI, SDValue &SV0, SDValue &SV1,
  21116. SmallVectorImpl<int> &Mask) -> bool {
  21117. // Don't try to fold splats; they're likely to simplify somehow, or they
  21118. // might be free.
  21119. if (OtherSVN->isSplat())
  21120. return false;
  21121. SV0 = SV1 = SDValue();
  21122. Mask.clear();
  21123. for (unsigned i = 0; i != NumElts; ++i) {
  21124. int Idx = SVN->getMaskElt(i);
  21125. if (Idx < 0) {
  21126. // Propagate Undef.
  21127. Mask.push_back(Idx);
  21128. continue;
  21129. }
  21130. if (Commute)
  21131. Idx = (Idx < (int)NumElts) ? (Idx + NumElts) : (Idx - NumElts);
  21132. SDValue CurrentVec;
  21133. if (Idx < (int)NumElts) {
  21134. // This shuffle index refers to the inner shuffle N0. Lookup the inner
  21135. // shuffle mask to identify which vector is actually referenced.
  21136. Idx = OtherSVN->getMaskElt(Idx);
  21137. if (Idx < 0) {
  21138. // Propagate Undef.
  21139. Mask.push_back(Idx);
  21140. continue;
  21141. }
  21142. CurrentVec = (Idx < (int)NumElts) ? OtherSVN->getOperand(0)
  21143. : OtherSVN->getOperand(1);
  21144. } else {
  21145. // This shuffle index references an element within N1.
  21146. CurrentVec = N1;
  21147. }
  21148. // Simple case where 'CurrentVec' is UNDEF.
  21149. if (CurrentVec.isUndef()) {
  21150. Mask.push_back(-1);
  21151. continue;
  21152. }
  21153. // Canonicalize the shuffle index. We don't know yet if CurrentVec
  21154. // will be the first or second operand of the combined shuffle.
  21155. Idx = Idx % NumElts;
  21156. if (!SV0.getNode() || SV0 == CurrentVec) {
  21157. // Ok. CurrentVec is the left hand side.
  21158. // Update the mask accordingly.
  21159. SV0 = CurrentVec;
  21160. Mask.push_back(Idx);
  21161. continue;
  21162. }
  21163. if (!SV1.getNode() || SV1 == CurrentVec) {
  21164. // Ok. CurrentVec is the right hand side.
  21165. // Update the mask accordingly.
  21166. SV1 = CurrentVec;
  21167. Mask.push_back(Idx + NumElts);
  21168. continue;
  21169. }
  21170. // Last chance - see if the vector is another shuffle and if it
  21171. // uses one of the existing candidate shuffle ops.
  21172. if (auto *CurrentSVN = dyn_cast<ShuffleVectorSDNode>(CurrentVec)) {
  21173. int InnerIdx = CurrentSVN->getMaskElt(Idx);
  21174. if (InnerIdx < 0) {
  21175. Mask.push_back(-1);
  21176. continue;
  21177. }
  21178. SDValue InnerVec = (InnerIdx < (int)NumElts)
  21179. ? CurrentSVN->getOperand(0)
  21180. : CurrentSVN->getOperand(1);
  21181. if (InnerVec.isUndef()) {
  21182. Mask.push_back(-1);
  21183. continue;
  21184. }
  21185. InnerIdx %= NumElts;
  21186. if (InnerVec == SV0) {
  21187. Mask.push_back(InnerIdx);
  21188. continue;
  21189. }
  21190. if (InnerVec == SV1) {
  21191. Mask.push_back(InnerIdx + NumElts);
  21192. continue;
  21193. }
  21194. }
  21195. // Bail out if we cannot convert the shuffle pair into a single shuffle.
  21196. return false;
  21197. }
  21198. if (llvm::all_of(Mask, [](int M) { return M < 0; }))
  21199. return true;
  21200. // Avoid introducing shuffles with illegal mask.
  21201. // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
  21202. // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
  21203. // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
  21204. // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2)
  21205. // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2)
  21206. // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2)
  21207. if (TLI.isShuffleMaskLegal(Mask, VT))
  21208. return true;
  21209. std::swap(SV0, SV1);
  21210. ShuffleVectorSDNode::commuteMask(Mask);
  21211. return TLI.isShuffleMaskLegal(Mask, VT);
  21212. };
  21213. if (Level < AfterLegalizeDAG && TLI.isTypeLegal(VT)) {
  21214. // Canonicalize shuffles according to rules:
  21215. // shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
  21216. // shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
  21217. // shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
  21218. if (N1.getOpcode() == ISD::VECTOR_SHUFFLE &&
  21219. N0.getOpcode() != ISD::VECTOR_SHUFFLE) {
  21220. // The incoming shuffle must be of the same type as the result of the
  21221. // current shuffle.
  21222. assert(N1->getOperand(0).getValueType() == VT &&
  21223. "Shuffle types don't match");
  21224. SDValue SV0 = N1->getOperand(0);
  21225. SDValue SV1 = N1->getOperand(1);
  21226. bool HasSameOp0 = N0 == SV0;
  21227. bool IsSV1Undef = SV1.isUndef();
  21228. if (HasSameOp0 || IsSV1Undef || N0 == SV1)
  21229. // Commute the operands of this shuffle so merging below will trigger.
  21230. return DAG.getCommutedVectorShuffle(*SVN);
  21231. }
  21232. // Canonicalize splat shuffles to the RHS to improve merging below.
  21233. // shuffle(splat(A,u), shuffle(C,D)) -> shuffle'(shuffle(C,D), splat(A,u))
  21234. if (N0.getOpcode() == ISD::VECTOR_SHUFFLE &&
  21235. N1.getOpcode() == ISD::VECTOR_SHUFFLE &&
  21236. cast<ShuffleVectorSDNode>(N0)->isSplat() &&
  21237. !cast<ShuffleVectorSDNode>(N1)->isSplat()) {
  21238. return DAG.getCommutedVectorShuffle(*SVN);
  21239. }
  21240. // Try to fold according to rules:
  21241. // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
  21242. // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
  21243. // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
  21244. // Don't try to fold shuffles with illegal type.
  21245. // Only fold if this shuffle is the only user of the other shuffle.
  21246. // Try matching shuffle(C,shuffle(A,B)) commutted patterns as well.
  21247. for (int i = 0; i != 2; ++i) {
  21248. if (N->getOperand(i).getOpcode() == ISD::VECTOR_SHUFFLE &&
  21249. N->isOnlyUserOf(N->getOperand(i).getNode())) {
  21250. // The incoming shuffle must be of the same type as the result of the
  21251. // current shuffle.
  21252. auto *OtherSV = cast<ShuffleVectorSDNode>(N->getOperand(i));
  21253. assert(OtherSV->getOperand(0).getValueType() == VT &&
  21254. "Shuffle types don't match");
  21255. SDValue SV0, SV1;
  21256. SmallVector<int, 4> Mask;
  21257. if (MergeInnerShuffle(i != 0, SVN, OtherSV, N->getOperand(1 - i), TLI,
  21258. SV0, SV1, Mask)) {
  21259. // Check if all indices in Mask are Undef. In case, propagate Undef.
  21260. if (llvm::all_of(Mask, [](int M) { return M < 0; }))
  21261. return DAG.getUNDEF(VT);
  21262. return DAG.getVectorShuffle(VT, SDLoc(N),
  21263. SV0 ? SV0 : DAG.getUNDEF(VT),
  21264. SV1 ? SV1 : DAG.getUNDEF(VT), Mask);
  21265. }
  21266. }
  21267. }
  21268. // Merge shuffles through binops if we are able to merge it with at least
  21269. // one other shuffles.
  21270. // shuffle(bop(shuffle(x,y),shuffle(z,w)),undef)
  21271. // shuffle(bop(shuffle(x,y),shuffle(z,w)),bop(shuffle(a,b),shuffle(c,d)))
  21272. unsigned SrcOpcode = N0.getOpcode();
  21273. if (TLI.isBinOp(SrcOpcode) && N->isOnlyUserOf(N0.getNode()) &&
  21274. (N1.isUndef() ||
  21275. (SrcOpcode == N1.getOpcode() && N->isOnlyUserOf(N1.getNode())))) {
  21276. // Get binop source ops, or just pass on the undef.
  21277. SDValue Op00 = N0.getOperand(0);
  21278. SDValue Op01 = N0.getOperand(1);
  21279. SDValue Op10 = N1.isUndef() ? N1 : N1.getOperand(0);
  21280. SDValue Op11 = N1.isUndef() ? N1 : N1.getOperand(1);
  21281. // TODO: We might be able to relax the VT check but we don't currently
  21282. // have any isBinOp() that has different result/ops VTs so play safe until
  21283. // we have test coverage.
  21284. if (Op00.getValueType() == VT && Op10.getValueType() == VT &&
  21285. Op01.getValueType() == VT && Op11.getValueType() == VT &&
  21286. (Op00.getOpcode() == ISD::VECTOR_SHUFFLE ||
  21287. Op10.getOpcode() == ISD::VECTOR_SHUFFLE ||
  21288. Op01.getOpcode() == ISD::VECTOR_SHUFFLE ||
  21289. Op11.getOpcode() == ISD::VECTOR_SHUFFLE)) {
  21290. auto CanMergeInnerShuffle = [&](SDValue &SV0, SDValue &SV1,
  21291. SmallVectorImpl<int> &Mask, bool LeftOp,
  21292. bool Commute) {
  21293. SDValue InnerN = Commute ? N1 : N0;
  21294. SDValue Op0 = LeftOp ? Op00 : Op01;
  21295. SDValue Op1 = LeftOp ? Op10 : Op11;
  21296. if (Commute)
  21297. std::swap(Op0, Op1);
  21298. // Only accept the merged shuffle if we don't introduce undef elements,
  21299. // or the inner shuffle already contained undef elements.
  21300. auto *SVN0 = dyn_cast<ShuffleVectorSDNode>(Op0);
  21301. return SVN0 && InnerN->isOnlyUserOf(SVN0) &&
  21302. MergeInnerShuffle(Commute, SVN, SVN0, Op1, TLI, SV0, SV1,
  21303. Mask) &&
  21304. (llvm::any_of(SVN0->getMask(), [](int M) { return M < 0; }) ||
  21305. llvm::none_of(Mask, [](int M) { return M < 0; }));
  21306. };
  21307. // Ensure we don't increase the number of shuffles - we must merge a
  21308. // shuffle from at least one of the LHS and RHS ops.
  21309. bool MergedLeft = false;
  21310. SDValue LeftSV0, LeftSV1;
  21311. SmallVector<int, 4> LeftMask;
  21312. if (CanMergeInnerShuffle(LeftSV0, LeftSV1, LeftMask, true, false) ||
  21313. CanMergeInnerShuffle(LeftSV0, LeftSV1, LeftMask, true, true)) {
  21314. MergedLeft = true;
  21315. } else {
  21316. LeftMask.assign(SVN->getMask().begin(), SVN->getMask().end());
  21317. LeftSV0 = Op00, LeftSV1 = Op10;
  21318. }
  21319. bool MergedRight = false;
  21320. SDValue RightSV0, RightSV1;
  21321. SmallVector<int, 4> RightMask;
  21322. if (CanMergeInnerShuffle(RightSV0, RightSV1, RightMask, false, false) ||
  21323. CanMergeInnerShuffle(RightSV0, RightSV1, RightMask, false, true)) {
  21324. MergedRight = true;
  21325. } else {
  21326. RightMask.assign(SVN->getMask().begin(), SVN->getMask().end());
  21327. RightSV0 = Op01, RightSV1 = Op11;
  21328. }
  21329. if (MergedLeft || MergedRight) {
  21330. SDLoc DL(N);
  21331. SDValue LHS = DAG.getVectorShuffle(
  21332. VT, DL, LeftSV0 ? LeftSV0 : DAG.getUNDEF(VT),
  21333. LeftSV1 ? LeftSV1 : DAG.getUNDEF(VT), LeftMask);
  21334. SDValue RHS = DAG.getVectorShuffle(
  21335. VT, DL, RightSV0 ? RightSV0 : DAG.getUNDEF(VT),
  21336. RightSV1 ? RightSV1 : DAG.getUNDEF(VT), RightMask);
  21337. return DAG.getNode(SrcOpcode, DL, VT, LHS, RHS);
  21338. }
  21339. }
  21340. }
  21341. }
  21342. if (SDValue V = foldShuffleOfConcatUndefs(SVN, DAG))
  21343. return V;
  21344. // Match shuffles that can be converted to ISD::ZERO_EXTEND_VECTOR_INREG.
  21345. // Perform this really late, because it could eliminate knowledge
  21346. // of undef elements created by this shuffle.
  21347. if (Level < AfterLegalizeTypes)
  21348. if (SDValue V = combineShuffleToZeroExtendVectorInReg(SVN, DAG, TLI,
  21349. LegalOperations))
  21350. return V;
  21351. return SDValue();
  21352. }
  21353. SDValue DAGCombiner::visitSCALAR_TO_VECTOR(SDNode *N) {
  21354. EVT VT = N->getValueType(0);
  21355. if (!VT.isFixedLengthVector())
  21356. return SDValue();
  21357. // Try to convert a scalar binop with an extracted vector element to a vector
  21358. // binop. This is intended to reduce potentially expensive register moves.
  21359. // TODO: Check if both operands are extracted.
  21360. // TODO: Generalize this, so it can be called from visitINSERT_VECTOR_ELT().
  21361. SDValue Scalar = N->getOperand(0);
  21362. unsigned Opcode = Scalar.getOpcode();
  21363. EVT VecEltVT = VT.getScalarType();
  21364. if (Scalar.hasOneUse() && Scalar->getNumValues() == 1 &&
  21365. TLI.isBinOp(Opcode) && Scalar.getValueType() == VecEltVT &&
  21366. Scalar.getOperand(0).getValueType() == VecEltVT &&
  21367. Scalar.getOperand(1).getValueType() == VecEltVT &&
  21368. DAG.isSafeToSpeculativelyExecute(Opcode) && hasOperation(Opcode, VT)) {
  21369. // Match an extract element and get a shuffle mask equivalent.
  21370. SmallVector<int, 8> ShufMask(VT.getVectorNumElements(), -1);
  21371. for (int i : {0, 1}) {
  21372. // s2v (bo (extelt V, Idx), C) --> shuffle (bo V, C'), {Idx, -1, -1...}
  21373. // s2v (bo C, (extelt V, Idx)) --> shuffle (bo C', V), {Idx, -1, -1...}
  21374. SDValue EE = Scalar.getOperand(i);
  21375. auto *C = dyn_cast<ConstantSDNode>(Scalar.getOperand(i ? 0 : 1));
  21376. if (C && EE.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
  21377. EE.getOperand(0).getValueType() == VT &&
  21378. isa<ConstantSDNode>(EE.getOperand(1))) {
  21379. // Mask = {ExtractIndex, undef, undef....}
  21380. ShufMask[0] = EE.getConstantOperandVal(1);
  21381. // Make sure the shuffle is legal if we are crossing lanes.
  21382. if (TLI.isShuffleMaskLegal(ShufMask, VT)) {
  21383. SDLoc DL(N);
  21384. SDValue V[] = {EE.getOperand(0),
  21385. DAG.getConstant(C->getAPIntValue(), DL, VT)};
  21386. SDValue VecBO = DAG.getNode(Opcode, DL, VT, V[i], V[1 - i]);
  21387. return DAG.getVectorShuffle(VT, DL, VecBO, DAG.getUNDEF(VT),
  21388. ShufMask);
  21389. }
  21390. }
  21391. }
  21392. }
  21393. // Replace a SCALAR_TO_VECTOR(EXTRACT_VECTOR_ELT(V,C0)) pattern
  21394. // with a VECTOR_SHUFFLE and possible truncate.
  21395. if (Opcode != ISD::EXTRACT_VECTOR_ELT ||
  21396. !Scalar.getOperand(0).getValueType().isFixedLengthVector())
  21397. return SDValue();
  21398. // If we have an implicit truncate, truncate here if it is legal.
  21399. if (VecEltVT != Scalar.getValueType() &&
  21400. Scalar.getValueType().isScalarInteger() && isTypeLegal(VecEltVT)) {
  21401. SDValue Val = DAG.getNode(ISD::TRUNCATE, SDLoc(Scalar), VecEltVT, Scalar);
  21402. return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(N), VT, Val);
  21403. }
  21404. auto *ExtIndexC = dyn_cast<ConstantSDNode>(Scalar.getOperand(1));
  21405. if (!ExtIndexC)
  21406. return SDValue();
  21407. SDValue SrcVec = Scalar.getOperand(0);
  21408. EVT SrcVT = SrcVec.getValueType();
  21409. unsigned SrcNumElts = SrcVT.getVectorNumElements();
  21410. unsigned VTNumElts = VT.getVectorNumElements();
  21411. if (VecEltVT == SrcVT.getScalarType() && VTNumElts <= SrcNumElts) {
  21412. // Create a shuffle equivalent for scalar-to-vector: {ExtIndex, -1, -1, ...}
  21413. SmallVector<int, 8> Mask(SrcNumElts, -1);
  21414. Mask[0] = ExtIndexC->getZExtValue();
  21415. SDValue LegalShuffle = TLI.buildLegalVectorShuffle(
  21416. SrcVT, SDLoc(N), SrcVec, DAG.getUNDEF(SrcVT), Mask, DAG);
  21417. if (!LegalShuffle)
  21418. return SDValue();
  21419. // If the initial vector is the same size, the shuffle is the result.
  21420. if (VT == SrcVT)
  21421. return LegalShuffle;
  21422. // If not, shorten the shuffled vector.
  21423. if (VTNumElts != SrcNumElts) {
  21424. SDValue ZeroIdx = DAG.getVectorIdxConstant(0, SDLoc(N));
  21425. EVT SubVT = EVT::getVectorVT(*DAG.getContext(),
  21426. SrcVT.getVectorElementType(), VTNumElts);
  21427. return DAG.getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(N), SubVT, LegalShuffle,
  21428. ZeroIdx);
  21429. }
  21430. }
  21431. return SDValue();
  21432. }
  21433. SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
  21434. EVT VT = N->getValueType(0);
  21435. SDValue N0 = N->getOperand(0);
  21436. SDValue N1 = N->getOperand(1);
  21437. SDValue N2 = N->getOperand(2);
  21438. uint64_t InsIdx = N->getConstantOperandVal(2);
  21439. // If inserting an UNDEF, just return the original vector.
  21440. if (N1.isUndef())
  21441. return N0;
  21442. // If this is an insert of an extracted vector into an undef vector, we can
  21443. // just use the input to the extract.
  21444. if (N0.isUndef() && N1.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
  21445. N1.getOperand(1) == N2 && N1.getOperand(0).getValueType() == VT)
  21446. return N1.getOperand(0);
  21447. // Simplify scalar inserts into an undef vector:
  21448. // insert_subvector undef, (splat X), N2 -> splat X
  21449. if (N0.isUndef() && N1.getOpcode() == ISD::SPLAT_VECTOR)
  21450. return DAG.getNode(ISD::SPLAT_VECTOR, SDLoc(N), VT, N1.getOperand(0));
  21451. // If we are inserting a bitcast value into an undef, with the same
  21452. // number of elements, just use the bitcast input of the extract.
  21453. // i.e. INSERT_SUBVECTOR UNDEF (BITCAST N1) N2 ->
  21454. // BITCAST (INSERT_SUBVECTOR UNDEF N1 N2)
  21455. if (N0.isUndef() && N1.getOpcode() == ISD::BITCAST &&
  21456. N1.getOperand(0).getOpcode() == ISD::EXTRACT_SUBVECTOR &&
  21457. N1.getOperand(0).getOperand(1) == N2 &&
  21458. N1.getOperand(0).getOperand(0).getValueType().getVectorElementCount() ==
  21459. VT.getVectorElementCount() &&
  21460. N1.getOperand(0).getOperand(0).getValueType().getSizeInBits() ==
  21461. VT.getSizeInBits()) {
  21462. return DAG.getBitcast(VT, N1.getOperand(0).getOperand(0));
  21463. }
  21464. // If both N1 and N2 are bitcast values on which insert_subvector
  21465. // would makes sense, pull the bitcast through.
  21466. // i.e. INSERT_SUBVECTOR (BITCAST N0) (BITCAST N1) N2 ->
  21467. // BITCAST (INSERT_SUBVECTOR N0 N1 N2)
  21468. if (N0.getOpcode() == ISD::BITCAST && N1.getOpcode() == ISD::BITCAST) {
  21469. SDValue CN0 = N0.getOperand(0);
  21470. SDValue CN1 = N1.getOperand(0);
  21471. EVT CN0VT = CN0.getValueType();
  21472. EVT CN1VT = CN1.getValueType();
  21473. if (CN0VT.isVector() && CN1VT.isVector() &&
  21474. CN0VT.getVectorElementType() == CN1VT.getVectorElementType() &&
  21475. CN0VT.getVectorElementCount() == VT.getVectorElementCount()) {
  21476. SDValue NewINSERT = DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N),
  21477. CN0.getValueType(), CN0, CN1, N2);
  21478. return DAG.getBitcast(VT, NewINSERT);
  21479. }
  21480. }
  21481. // Combine INSERT_SUBVECTORs where we are inserting to the same index.
  21482. // INSERT_SUBVECTOR( INSERT_SUBVECTOR( Vec, SubOld, Idx ), SubNew, Idx )
  21483. // --> INSERT_SUBVECTOR( Vec, SubNew, Idx )
  21484. if (N0.getOpcode() == ISD::INSERT_SUBVECTOR &&
  21485. N0.getOperand(1).getValueType() == N1.getValueType() &&
  21486. N0.getOperand(2) == N2)
  21487. return DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N), VT, N0.getOperand(0),
  21488. N1, N2);
  21489. // Eliminate an intermediate insert into an undef vector:
  21490. // insert_subvector undef, (insert_subvector undef, X, 0), N2 -->
  21491. // insert_subvector undef, X, N2
  21492. if (N0.isUndef() && N1.getOpcode() == ISD::INSERT_SUBVECTOR &&
  21493. N1.getOperand(0).isUndef() && isNullConstant(N1.getOperand(2)))
  21494. return DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N), VT, N0,
  21495. N1.getOperand(1), N2);
  21496. // Push subvector bitcasts to the output, adjusting the index as we go.
  21497. // insert_subvector(bitcast(v), bitcast(s), c1)
  21498. // -> bitcast(insert_subvector(v, s, c2))
  21499. if ((N0.isUndef() || N0.getOpcode() == ISD::BITCAST) &&
  21500. N1.getOpcode() == ISD::BITCAST) {
  21501. SDValue N0Src = peekThroughBitcasts(N0);
  21502. SDValue N1Src = peekThroughBitcasts(N1);
  21503. EVT N0SrcSVT = N0Src.getValueType().getScalarType();
  21504. EVT N1SrcSVT = N1Src.getValueType().getScalarType();
  21505. if ((N0.isUndef() || N0SrcSVT == N1SrcSVT) &&
  21506. N0Src.getValueType().isVector() && N1Src.getValueType().isVector()) {
  21507. EVT NewVT;
  21508. SDLoc DL(N);
  21509. SDValue NewIdx;
  21510. LLVMContext &Ctx = *DAG.getContext();
  21511. ElementCount NumElts = VT.getVectorElementCount();
  21512. unsigned EltSizeInBits = VT.getScalarSizeInBits();
  21513. if ((EltSizeInBits % N1SrcSVT.getSizeInBits()) == 0) {
  21514. unsigned Scale = EltSizeInBits / N1SrcSVT.getSizeInBits();
  21515. NewVT = EVT::getVectorVT(Ctx, N1SrcSVT, NumElts * Scale);
  21516. NewIdx = DAG.getVectorIdxConstant(InsIdx * Scale, DL);
  21517. } else if ((N1SrcSVT.getSizeInBits() % EltSizeInBits) == 0) {
  21518. unsigned Scale = N1SrcSVT.getSizeInBits() / EltSizeInBits;
  21519. if (NumElts.isKnownMultipleOf(Scale) && (InsIdx % Scale) == 0) {
  21520. NewVT = EVT::getVectorVT(Ctx, N1SrcSVT,
  21521. NumElts.divideCoefficientBy(Scale));
  21522. NewIdx = DAG.getVectorIdxConstant(InsIdx / Scale, DL);
  21523. }
  21524. }
  21525. if (NewIdx && hasOperation(ISD::INSERT_SUBVECTOR, NewVT)) {
  21526. SDValue Res = DAG.getBitcast(NewVT, N0Src);
  21527. Res = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, NewVT, Res, N1Src, NewIdx);
  21528. return DAG.getBitcast(VT, Res);
  21529. }
  21530. }
  21531. }
  21532. // Canonicalize insert_subvector dag nodes.
  21533. // Example:
  21534. // (insert_subvector (insert_subvector A, Idx0), Idx1)
  21535. // -> (insert_subvector (insert_subvector A, Idx1), Idx0)
  21536. if (N0.getOpcode() == ISD::INSERT_SUBVECTOR && N0.hasOneUse() &&
  21537. N1.getValueType() == N0.getOperand(1).getValueType()) {
  21538. unsigned OtherIdx = N0.getConstantOperandVal(2);
  21539. if (InsIdx < OtherIdx) {
  21540. // Swap nodes.
  21541. SDValue NewOp = DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N), VT,
  21542. N0.getOperand(0), N1, N2);
  21543. AddToWorklist(NewOp.getNode());
  21544. return DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N0.getNode()),
  21545. VT, NewOp, N0.getOperand(1), N0.getOperand(2));
  21546. }
  21547. }
  21548. // If the input vector is a concatenation, and the insert replaces
  21549. // one of the pieces, we can optimize into a single concat_vectors.
  21550. if (N0.getOpcode() == ISD::CONCAT_VECTORS && N0.hasOneUse() &&
  21551. N0.getOperand(0).getValueType() == N1.getValueType() &&
  21552. N0.getOperand(0).getValueType().isScalableVector() ==
  21553. N1.getValueType().isScalableVector()) {
  21554. unsigned Factor = N1.getValueType().getVectorMinNumElements();
  21555. SmallVector<SDValue, 8> Ops(N0->op_begin(), N0->op_end());
  21556. Ops[InsIdx / Factor] = N1;
  21557. return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
  21558. }
  21559. // Simplify source operands based on insertion.
  21560. if (SimplifyDemandedVectorElts(SDValue(N, 0)))
  21561. return SDValue(N, 0);
  21562. return SDValue();
  21563. }
  21564. SDValue DAGCombiner::visitFP_TO_FP16(SDNode *N) {
  21565. SDValue N0 = N->getOperand(0);
  21566. // fold (fp_to_fp16 (fp16_to_fp op)) -> op
  21567. if (N0->getOpcode() == ISD::FP16_TO_FP)
  21568. return N0->getOperand(0);
  21569. return SDValue();
  21570. }
  21571. SDValue DAGCombiner::visitFP16_TO_FP(SDNode *N) {
  21572. SDValue N0 = N->getOperand(0);
  21573. // fold fp16_to_fp(op & 0xffff) -> fp16_to_fp(op)
  21574. if (!TLI.shouldKeepZExtForFP16Conv() && N0->getOpcode() == ISD::AND) {
  21575. ConstantSDNode *AndConst = getAsNonOpaqueConstant(N0.getOperand(1));
  21576. if (AndConst && AndConst->getAPIntValue() == 0xffff) {
  21577. return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), N->getValueType(0),
  21578. N0.getOperand(0));
  21579. }
  21580. }
  21581. return SDValue();
  21582. }
  21583. SDValue DAGCombiner::visitFP_TO_BF16(SDNode *N) {
  21584. SDValue N0 = N->getOperand(0);
  21585. // fold (fp_to_bf16 (bf16_to_fp op)) -> op
  21586. if (N0->getOpcode() == ISD::BF16_TO_FP)
  21587. return N0->getOperand(0);
  21588. return SDValue();
  21589. }
  21590. SDValue DAGCombiner::visitVECREDUCE(SDNode *N) {
  21591. SDValue N0 = N->getOperand(0);
  21592. EVT VT = N0.getValueType();
  21593. unsigned Opcode = N->getOpcode();
  21594. // VECREDUCE over 1-element vector is just an extract.
  21595. if (VT.getVectorElementCount().isScalar()) {
  21596. SDLoc dl(N);
  21597. SDValue Res =
  21598. DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT.getVectorElementType(), N0,
  21599. DAG.getVectorIdxConstant(0, dl));
  21600. if (Res.getValueType() != N->getValueType(0))
  21601. Res = DAG.getNode(ISD::ANY_EXTEND, dl, N->getValueType(0), Res);
  21602. return Res;
  21603. }
  21604. // On an boolean vector an and/or reduction is the same as a umin/umax
  21605. // reduction. Convert them if the latter is legal while the former isn't.
  21606. if (Opcode == ISD::VECREDUCE_AND || Opcode == ISD::VECREDUCE_OR) {
  21607. unsigned NewOpcode = Opcode == ISD::VECREDUCE_AND
  21608. ? ISD::VECREDUCE_UMIN : ISD::VECREDUCE_UMAX;
  21609. if (!TLI.isOperationLegalOrCustom(Opcode, VT) &&
  21610. TLI.isOperationLegalOrCustom(NewOpcode, VT) &&
  21611. DAG.ComputeNumSignBits(N0) == VT.getScalarSizeInBits())
  21612. return DAG.getNode(NewOpcode, SDLoc(N), N->getValueType(0), N0);
  21613. }
  21614. // vecreduce_or(insert_subvector(zero or undef, val)) -> vecreduce_or(val)
  21615. // vecreduce_and(insert_subvector(ones or undef, val)) -> vecreduce_and(val)
  21616. if (N0.getOpcode() == ISD::INSERT_SUBVECTOR &&
  21617. TLI.isTypeLegal(N0.getOperand(1).getValueType())) {
  21618. SDValue Vec = N0.getOperand(0);
  21619. SDValue Subvec = N0.getOperand(1);
  21620. if ((Opcode == ISD::VECREDUCE_OR &&
  21621. (N0.getOperand(0).isUndef() || isNullOrNullSplat(Vec))) ||
  21622. (Opcode == ISD::VECREDUCE_AND &&
  21623. (N0.getOperand(0).isUndef() || isAllOnesOrAllOnesSplat(Vec))))
  21624. return DAG.getNode(Opcode, SDLoc(N), N->getValueType(0), Subvec);
  21625. }
  21626. return SDValue();
  21627. }
  21628. SDValue DAGCombiner::visitVPOp(SDNode *N) {
  21629. if (N->getOpcode() == ISD::VP_GATHER)
  21630. if (SDValue SD = visitVPGATHER(N))
  21631. return SD;
  21632. if (N->getOpcode() == ISD::VP_SCATTER)
  21633. if (SDValue SD = visitVPSCATTER(N))
  21634. return SD;
  21635. // VP operations in which all vector elements are disabled - either by
  21636. // determining that the mask is all false or that the EVL is 0 - can be
  21637. // eliminated.
  21638. bool AreAllEltsDisabled = false;
  21639. if (auto EVLIdx = ISD::getVPExplicitVectorLengthIdx(N->getOpcode()))
  21640. AreAllEltsDisabled |= isNullConstant(N->getOperand(*EVLIdx));
  21641. if (auto MaskIdx = ISD::getVPMaskIdx(N->getOpcode()))
  21642. AreAllEltsDisabled |=
  21643. ISD::isConstantSplatVectorAllZeros(N->getOperand(*MaskIdx).getNode());
  21644. // This is the only generic VP combine we support for now.
  21645. if (!AreAllEltsDisabled)
  21646. return SDValue();
  21647. // Binary operations can be replaced by UNDEF.
  21648. if (ISD::isVPBinaryOp(N->getOpcode()))
  21649. return DAG.getUNDEF(N->getValueType(0));
  21650. // VP Memory operations can be replaced by either the chain (stores) or the
  21651. // chain + undef (loads).
  21652. if (const auto *MemSD = dyn_cast<MemSDNode>(N)) {
  21653. if (MemSD->writeMem())
  21654. return MemSD->getChain();
  21655. return CombineTo(N, DAG.getUNDEF(N->getValueType(0)), MemSD->getChain());
  21656. }
  21657. // Reduction operations return the start operand when no elements are active.
  21658. if (ISD::isVPReduction(N->getOpcode()))
  21659. return N->getOperand(0);
  21660. return SDValue();
  21661. }
  21662. /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle
  21663. /// with the destination vector and a zero vector.
  21664. /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
  21665. /// vector_shuffle V, Zero, <0, 4, 2, 4>
  21666. SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
  21667. assert(N->getOpcode() == ISD::AND && "Unexpected opcode!");
  21668. EVT VT = N->getValueType(0);
  21669. SDValue LHS = N->getOperand(0);
  21670. SDValue RHS = peekThroughBitcasts(N->getOperand(1));
  21671. SDLoc DL(N);
  21672. // Make sure we're not running after operation legalization where it
  21673. // may have custom lowered the vector shuffles.
  21674. if (LegalOperations)
  21675. return SDValue();
  21676. if (RHS.getOpcode() != ISD::BUILD_VECTOR)
  21677. return SDValue();
  21678. EVT RVT = RHS.getValueType();
  21679. unsigned NumElts = RHS.getNumOperands();
  21680. // Attempt to create a valid clear mask, splitting the mask into
  21681. // sub elements and checking to see if each is
  21682. // all zeros or all ones - suitable for shuffle masking.
  21683. auto BuildClearMask = [&](int Split) {
  21684. int NumSubElts = NumElts * Split;
  21685. int NumSubBits = RVT.getScalarSizeInBits() / Split;
  21686. SmallVector<int, 8> Indices;
  21687. for (int i = 0; i != NumSubElts; ++i) {
  21688. int EltIdx = i / Split;
  21689. int SubIdx = i % Split;
  21690. SDValue Elt = RHS.getOperand(EltIdx);
  21691. // X & undef --> 0 (not undef). So this lane must be converted to choose
  21692. // from the zero constant vector (same as if the element had all 0-bits).
  21693. if (Elt.isUndef()) {
  21694. Indices.push_back(i + NumSubElts);
  21695. continue;
  21696. }
  21697. APInt Bits;
  21698. if (isa<ConstantSDNode>(Elt))
  21699. Bits = cast<ConstantSDNode>(Elt)->getAPIntValue();
  21700. else if (isa<ConstantFPSDNode>(Elt))
  21701. Bits = cast<ConstantFPSDNode>(Elt)->getValueAPF().bitcastToAPInt();
  21702. else
  21703. return SDValue();
  21704. // Extract the sub element from the constant bit mask.
  21705. if (DAG.getDataLayout().isBigEndian())
  21706. Bits = Bits.extractBits(NumSubBits, (Split - SubIdx - 1) * NumSubBits);
  21707. else
  21708. Bits = Bits.extractBits(NumSubBits, SubIdx * NumSubBits);
  21709. if (Bits.isAllOnes())
  21710. Indices.push_back(i);
  21711. else if (Bits == 0)
  21712. Indices.push_back(i + NumSubElts);
  21713. else
  21714. return SDValue();
  21715. }
  21716. // Let's see if the target supports this vector_shuffle.
  21717. EVT ClearSVT = EVT::getIntegerVT(*DAG.getContext(), NumSubBits);
  21718. EVT ClearVT = EVT::getVectorVT(*DAG.getContext(), ClearSVT, NumSubElts);
  21719. if (!TLI.isVectorClearMaskLegal(Indices, ClearVT))
  21720. return SDValue();
  21721. SDValue Zero = DAG.getConstant(0, DL, ClearVT);
  21722. return DAG.getBitcast(VT, DAG.getVectorShuffle(ClearVT, DL,
  21723. DAG.getBitcast(ClearVT, LHS),
  21724. Zero, Indices));
  21725. };
  21726. // Determine maximum split level (byte level masking).
  21727. int MaxSplit = 1;
  21728. if (RVT.getScalarSizeInBits() % 8 == 0)
  21729. MaxSplit = RVT.getScalarSizeInBits() / 8;
  21730. for (int Split = 1; Split <= MaxSplit; ++Split)
  21731. if (RVT.getScalarSizeInBits() % Split == 0)
  21732. if (SDValue S = BuildClearMask(Split))
  21733. return S;
  21734. return SDValue();
  21735. }
  21736. /// If a vector binop is performed on splat values, it may be profitable to
  21737. /// extract, scalarize, and insert/splat.
  21738. static SDValue scalarizeBinOpOfSplats(SDNode *N, SelectionDAG &DAG,
  21739. const SDLoc &DL) {
  21740. SDValue N0 = N->getOperand(0);
  21741. SDValue N1 = N->getOperand(1);
  21742. unsigned Opcode = N->getOpcode();
  21743. EVT VT = N->getValueType(0);
  21744. EVT EltVT = VT.getVectorElementType();
  21745. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  21746. // TODO: Remove/replace the extract cost check? If the elements are available
  21747. // as scalars, then there may be no extract cost. Should we ask if
  21748. // inserting a scalar back into a vector is cheap instead?
  21749. int Index0, Index1;
  21750. SDValue Src0 = DAG.getSplatSourceVector(N0, Index0);
  21751. SDValue Src1 = DAG.getSplatSourceVector(N1, Index1);
  21752. // Extract element from splat_vector should be free.
  21753. // TODO: use DAG.isSplatValue instead?
  21754. bool IsBothSplatVector = N0.getOpcode() == ISD::SPLAT_VECTOR &&
  21755. N1.getOpcode() == ISD::SPLAT_VECTOR;
  21756. if (!Src0 || !Src1 || Index0 != Index1 ||
  21757. Src0.getValueType().getVectorElementType() != EltVT ||
  21758. Src1.getValueType().getVectorElementType() != EltVT ||
  21759. !(IsBothSplatVector || TLI.isExtractVecEltCheap(VT, Index0)) ||
  21760. !TLI.isOperationLegalOrCustom(Opcode, EltVT))
  21761. return SDValue();
  21762. SDValue IndexC = DAG.getVectorIdxConstant(Index0, DL);
  21763. SDValue X = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Src0, IndexC);
  21764. SDValue Y = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Src1, IndexC);
  21765. SDValue ScalarBO = DAG.getNode(Opcode, DL, EltVT, X, Y, N->getFlags());
  21766. // If all lanes but 1 are undefined, no need to splat the scalar result.
  21767. // TODO: Keep track of undefs and use that info in the general case.
  21768. if (N0.getOpcode() == ISD::BUILD_VECTOR && N0.getOpcode() == N1.getOpcode() &&
  21769. count_if(N0->ops(), [](SDValue V) { return !V.isUndef(); }) == 1 &&
  21770. count_if(N1->ops(), [](SDValue V) { return !V.isUndef(); }) == 1) {
  21771. // bo (build_vec ..undef, X, undef...), (build_vec ..undef, Y, undef...) -->
  21772. // build_vec ..undef, (bo X, Y), undef...
  21773. SmallVector<SDValue, 8> Ops(VT.getVectorNumElements(), DAG.getUNDEF(EltVT));
  21774. Ops[Index0] = ScalarBO;
  21775. return DAG.getBuildVector(VT, DL, Ops);
  21776. }
  21777. // bo (splat X, Index), (splat Y, Index) --> splat (bo X, Y), Index
  21778. return DAG.getSplat(VT, DL, ScalarBO);
  21779. }
  21780. /// Visit a vector cast operation, like FP_EXTEND.
  21781. SDValue DAGCombiner::SimplifyVCastOp(SDNode *N, const SDLoc &DL) {
  21782. EVT VT = N->getValueType(0);
  21783. assert(VT.isVector() && "SimplifyVCastOp only works on vectors!");
  21784. EVT EltVT = VT.getVectorElementType();
  21785. unsigned Opcode = N->getOpcode();
  21786. SDValue N0 = N->getOperand(0);
  21787. EVT SrcVT = N0->getValueType(0);
  21788. EVT SrcEltVT = SrcVT.getVectorElementType();
  21789. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  21790. // TODO: promote operation might be also good here?
  21791. int Index0;
  21792. SDValue Src0 = DAG.getSplatSourceVector(N0, Index0);
  21793. if (Src0 &&
  21794. (N0.getOpcode() == ISD::SPLAT_VECTOR ||
  21795. TLI.isExtractVecEltCheap(VT, Index0)) &&
  21796. TLI.isOperationLegalOrCustom(Opcode, EltVT) &&
  21797. TLI.preferScalarizeSplat(Opcode)) {
  21798. SDValue IndexC = DAG.getVectorIdxConstant(Index0, DL);
  21799. SDValue Elt =
  21800. DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, SrcEltVT, Src0, IndexC);
  21801. SDValue ScalarBO = DAG.getNode(Opcode, DL, EltVT, Elt, N->getFlags());
  21802. if (VT.isScalableVector())
  21803. return DAG.getSplatVector(VT, DL, ScalarBO);
  21804. SmallVector<SDValue, 8> Ops(VT.getVectorNumElements(), ScalarBO);
  21805. return DAG.getBuildVector(VT, DL, Ops);
  21806. }
  21807. return SDValue();
  21808. }
  21809. /// Visit a binary vector operation, like ADD.
  21810. SDValue DAGCombiner::SimplifyVBinOp(SDNode *N, const SDLoc &DL) {
  21811. EVT VT = N->getValueType(0);
  21812. assert(VT.isVector() && "SimplifyVBinOp only works on vectors!");
  21813. SDValue LHS = N->getOperand(0);
  21814. SDValue RHS = N->getOperand(1);
  21815. unsigned Opcode = N->getOpcode();
  21816. SDNodeFlags Flags = N->getFlags();
  21817. // Move unary shuffles with identical masks after a vector binop:
  21818. // VBinOp (shuffle A, Undef, Mask), (shuffle B, Undef, Mask))
  21819. // --> shuffle (VBinOp A, B), Undef, Mask
  21820. // This does not require type legality checks because we are creating the
  21821. // same types of operations that are in the original sequence. We do have to
  21822. // restrict ops like integer div that have immediate UB (eg, div-by-zero)
  21823. // though. This code is adapted from the identical transform in instcombine.
  21824. if (DAG.isSafeToSpeculativelyExecute(Opcode)) {
  21825. auto *Shuf0 = dyn_cast<ShuffleVectorSDNode>(LHS);
  21826. auto *Shuf1 = dyn_cast<ShuffleVectorSDNode>(RHS);
  21827. if (Shuf0 && Shuf1 && Shuf0->getMask().equals(Shuf1->getMask()) &&
  21828. LHS.getOperand(1).isUndef() && RHS.getOperand(1).isUndef() &&
  21829. (LHS.hasOneUse() || RHS.hasOneUse() || LHS == RHS)) {
  21830. SDValue NewBinOp = DAG.getNode(Opcode, DL, VT, LHS.getOperand(0),
  21831. RHS.getOperand(0), Flags);
  21832. SDValue UndefV = LHS.getOperand(1);
  21833. return DAG.getVectorShuffle(VT, DL, NewBinOp, UndefV, Shuf0->getMask());
  21834. }
  21835. // Try to sink a splat shuffle after a binop with a uniform constant.
  21836. // This is limited to cases where neither the shuffle nor the constant have
  21837. // undefined elements because that could be poison-unsafe or inhibit
  21838. // demanded elements analysis. It is further limited to not change a splat
  21839. // of an inserted scalar because that may be optimized better by
  21840. // load-folding or other target-specific behaviors.
  21841. if (isConstOrConstSplat(RHS) && Shuf0 && all_equal(Shuf0->getMask()) &&
  21842. Shuf0->hasOneUse() && Shuf0->getOperand(1).isUndef() &&
  21843. Shuf0->getOperand(0).getOpcode() != ISD::INSERT_VECTOR_ELT) {
  21844. // binop (splat X), (splat C) --> splat (binop X, C)
  21845. SDValue X = Shuf0->getOperand(0);
  21846. SDValue NewBinOp = DAG.getNode(Opcode, DL, VT, X, RHS, Flags);
  21847. return DAG.getVectorShuffle(VT, DL, NewBinOp, DAG.getUNDEF(VT),
  21848. Shuf0->getMask());
  21849. }
  21850. if (isConstOrConstSplat(LHS) && Shuf1 && all_equal(Shuf1->getMask()) &&
  21851. Shuf1->hasOneUse() && Shuf1->getOperand(1).isUndef() &&
  21852. Shuf1->getOperand(0).getOpcode() != ISD::INSERT_VECTOR_ELT) {
  21853. // binop (splat C), (splat X) --> splat (binop C, X)
  21854. SDValue X = Shuf1->getOperand(0);
  21855. SDValue NewBinOp = DAG.getNode(Opcode, DL, VT, LHS, X, Flags);
  21856. return DAG.getVectorShuffle(VT, DL, NewBinOp, DAG.getUNDEF(VT),
  21857. Shuf1->getMask());
  21858. }
  21859. }
  21860. // The following pattern is likely to emerge with vector reduction ops. Moving
  21861. // the binary operation ahead of insertion may allow using a narrower vector
  21862. // instruction that has better performance than the wide version of the op:
  21863. // VBinOp (ins undef, X, Z), (ins undef, Y, Z) --> ins VecC, (VBinOp X, Y), Z
  21864. if (LHS.getOpcode() == ISD::INSERT_SUBVECTOR && LHS.getOperand(0).isUndef() &&
  21865. RHS.getOpcode() == ISD::INSERT_SUBVECTOR && RHS.getOperand(0).isUndef() &&
  21866. LHS.getOperand(2) == RHS.getOperand(2) &&
  21867. (LHS.hasOneUse() || RHS.hasOneUse())) {
  21868. SDValue X = LHS.getOperand(1);
  21869. SDValue Y = RHS.getOperand(1);
  21870. SDValue Z = LHS.getOperand(2);
  21871. EVT NarrowVT = X.getValueType();
  21872. if (NarrowVT == Y.getValueType() &&
  21873. TLI.isOperationLegalOrCustomOrPromote(Opcode, NarrowVT,
  21874. LegalOperations)) {
  21875. // (binop undef, undef) may not return undef, so compute that result.
  21876. SDValue VecC =
  21877. DAG.getNode(Opcode, DL, VT, DAG.getUNDEF(VT), DAG.getUNDEF(VT));
  21878. SDValue NarrowBO = DAG.getNode(Opcode, DL, NarrowVT, X, Y);
  21879. return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, VecC, NarrowBO, Z);
  21880. }
  21881. }
  21882. // Make sure all but the first op are undef or constant.
  21883. auto ConcatWithConstantOrUndef = [](SDValue Concat) {
  21884. return Concat.getOpcode() == ISD::CONCAT_VECTORS &&
  21885. all_of(drop_begin(Concat->ops()), [](const SDValue &Op) {
  21886. return Op.isUndef() ||
  21887. ISD::isBuildVectorOfConstantSDNodes(Op.getNode());
  21888. });
  21889. };
  21890. // The following pattern is likely to emerge with vector reduction ops. Moving
  21891. // the binary operation ahead of the concat may allow using a narrower vector
  21892. // instruction that has better performance than the wide version of the op:
  21893. // VBinOp (concat X, undef/constant), (concat Y, undef/constant) -->
  21894. // concat (VBinOp X, Y), VecC
  21895. if (ConcatWithConstantOrUndef(LHS) && ConcatWithConstantOrUndef(RHS) &&
  21896. (LHS.hasOneUse() || RHS.hasOneUse())) {
  21897. EVT NarrowVT = LHS.getOperand(0).getValueType();
  21898. if (NarrowVT == RHS.getOperand(0).getValueType() &&
  21899. TLI.isOperationLegalOrCustomOrPromote(Opcode, NarrowVT)) {
  21900. unsigned NumOperands = LHS.getNumOperands();
  21901. SmallVector<SDValue, 4> ConcatOps;
  21902. for (unsigned i = 0; i != NumOperands; ++i) {
  21903. // This constant fold for operands 1 and up.
  21904. ConcatOps.push_back(DAG.getNode(Opcode, DL, NarrowVT, LHS.getOperand(i),
  21905. RHS.getOperand(i)));
  21906. }
  21907. return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps);
  21908. }
  21909. }
  21910. if (SDValue V = scalarizeBinOpOfSplats(N, DAG, DL))
  21911. return V;
  21912. return SDValue();
  21913. }
  21914. SDValue DAGCombiner::SimplifySelect(const SDLoc &DL, SDValue N0, SDValue N1,
  21915. SDValue N2) {
  21916. assert(N0.getOpcode() == ISD::SETCC &&
  21917. "First argument must be a SetCC node!");
  21918. SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
  21919. cast<CondCodeSDNode>(N0.getOperand(2))->get());
  21920. // If we got a simplified select_cc node back from SimplifySelectCC, then
  21921. // break it down into a new SETCC node, and a new SELECT node, and then return
  21922. // the SELECT node, since we were called with a SELECT node.
  21923. if (SCC.getNode()) {
  21924. // Check to see if we got a select_cc back (to turn into setcc/select).
  21925. // Otherwise, just return whatever node we got back, like fabs.
  21926. if (SCC.getOpcode() == ISD::SELECT_CC) {
  21927. const SDNodeFlags Flags = N0->getFlags();
  21928. SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
  21929. N0.getValueType(),
  21930. SCC.getOperand(0), SCC.getOperand(1),
  21931. SCC.getOperand(4), Flags);
  21932. AddToWorklist(SETCC.getNode());
  21933. SDValue SelectNode = DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
  21934. SCC.getOperand(2), SCC.getOperand(3));
  21935. SelectNode->setFlags(Flags);
  21936. return SelectNode;
  21937. }
  21938. return SCC;
  21939. }
  21940. return SDValue();
  21941. }
  21942. /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values
  21943. /// being selected between, see if we can simplify the select. Callers of this
  21944. /// should assume that TheSelect is deleted if this returns true. As such, they
  21945. /// should return the appropriate thing (e.g. the node) back to the top-level of
  21946. /// the DAG combiner loop to avoid it being looked at.
  21947. bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
  21948. SDValue RHS) {
  21949. // fold (select (setcc x, [+-]0.0, *lt), NaN, (fsqrt x))
  21950. // The select + setcc is redundant, because fsqrt returns NaN for X < 0.
  21951. if (const ConstantFPSDNode *NaN = isConstOrConstSplatFP(LHS)) {
  21952. if (NaN->isNaN() && RHS.getOpcode() == ISD::FSQRT) {
  21953. // We have: (select (setcc ?, ?, ?), NaN, (fsqrt ?))
  21954. SDValue Sqrt = RHS;
  21955. ISD::CondCode CC;
  21956. SDValue CmpLHS;
  21957. const ConstantFPSDNode *Zero = nullptr;
  21958. if (TheSelect->getOpcode() == ISD::SELECT_CC) {
  21959. CC = cast<CondCodeSDNode>(TheSelect->getOperand(4))->get();
  21960. CmpLHS = TheSelect->getOperand(0);
  21961. Zero = isConstOrConstSplatFP(TheSelect->getOperand(1));
  21962. } else {
  21963. // SELECT or VSELECT
  21964. SDValue Cmp = TheSelect->getOperand(0);
  21965. if (Cmp.getOpcode() == ISD::SETCC) {
  21966. CC = cast<CondCodeSDNode>(Cmp.getOperand(2))->get();
  21967. CmpLHS = Cmp.getOperand(0);
  21968. Zero = isConstOrConstSplatFP(Cmp.getOperand(1));
  21969. }
  21970. }
  21971. if (Zero && Zero->isZero() &&
  21972. Sqrt.getOperand(0) == CmpLHS && (CC == ISD::SETOLT ||
  21973. CC == ISD::SETULT || CC == ISD::SETLT)) {
  21974. // We have: (select (setcc x, [+-]0.0, *lt), NaN, (fsqrt x))
  21975. CombineTo(TheSelect, Sqrt);
  21976. return true;
  21977. }
  21978. }
  21979. }
  21980. // Cannot simplify select with vector condition
  21981. if (TheSelect->getOperand(0).getValueType().isVector()) return false;
  21982. // If this is a select from two identical things, try to pull the operation
  21983. // through the select.
  21984. if (LHS.getOpcode() != RHS.getOpcode() ||
  21985. !LHS.hasOneUse() || !RHS.hasOneUse())
  21986. return false;
  21987. // If this is a load and the token chain is identical, replace the select
  21988. // of two loads with a load through a select of the address to load from.
  21989. // This triggers in things like "select bool X, 10.0, 123.0" after the FP
  21990. // constants have been dropped into the constant pool.
  21991. if (LHS.getOpcode() == ISD::LOAD) {
  21992. LoadSDNode *LLD = cast<LoadSDNode>(LHS);
  21993. LoadSDNode *RLD = cast<LoadSDNode>(RHS);
  21994. // Token chains must be identical.
  21995. if (LHS.getOperand(0) != RHS.getOperand(0) ||
  21996. // Do not let this transformation reduce the number of volatile loads.
  21997. // Be conservative for atomics for the moment
  21998. // TODO: This does appear to be legal for unordered atomics (see D66309)
  21999. !LLD->isSimple() || !RLD->isSimple() ||
  22000. // FIXME: If either is a pre/post inc/dec load,
  22001. // we'd need to split out the address adjustment.
  22002. LLD->isIndexed() || RLD->isIndexed() ||
  22003. // If this is an EXTLOAD, the VT's must match.
  22004. LLD->getMemoryVT() != RLD->getMemoryVT() ||
  22005. // If this is an EXTLOAD, the kind of extension must match.
  22006. (LLD->getExtensionType() != RLD->getExtensionType() &&
  22007. // The only exception is if one of the extensions is anyext.
  22008. LLD->getExtensionType() != ISD::EXTLOAD &&
  22009. RLD->getExtensionType() != ISD::EXTLOAD) ||
  22010. // FIXME: this discards src value information. This is
  22011. // over-conservative. It would be beneficial to be able to remember
  22012. // both potential memory locations. Since we are discarding
  22013. // src value info, don't do the transformation if the memory
  22014. // locations are not in the default address space.
  22015. LLD->getPointerInfo().getAddrSpace() != 0 ||
  22016. RLD->getPointerInfo().getAddrSpace() != 0 ||
  22017. // We can't produce a CMOV of a TargetFrameIndex since we won't
  22018. // generate the address generation required.
  22019. LLD->getBasePtr().getOpcode() == ISD::TargetFrameIndex ||
  22020. RLD->getBasePtr().getOpcode() == ISD::TargetFrameIndex ||
  22021. !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
  22022. LLD->getBasePtr().getValueType()))
  22023. return false;
  22024. // The loads must not depend on one another.
  22025. if (LLD->isPredecessorOf(RLD) || RLD->isPredecessorOf(LLD))
  22026. return false;
  22027. // Check that the select condition doesn't reach either load. If so,
  22028. // folding this will induce a cycle into the DAG. If not, this is safe to
  22029. // xform, so create a select of the addresses.
  22030. SmallPtrSet<const SDNode *, 32> Visited;
  22031. SmallVector<const SDNode *, 16> Worklist;
  22032. // Always fail if LLD and RLD are not independent. TheSelect is a
  22033. // predecessor to all Nodes in question so we need not search past it.
  22034. Visited.insert(TheSelect);
  22035. Worklist.push_back(LLD);
  22036. Worklist.push_back(RLD);
  22037. if (SDNode::hasPredecessorHelper(LLD, Visited, Worklist) ||
  22038. SDNode::hasPredecessorHelper(RLD, Visited, Worklist))
  22039. return false;
  22040. SDValue Addr;
  22041. if (TheSelect->getOpcode() == ISD::SELECT) {
  22042. // We cannot do this optimization if any pair of {RLD, LLD} is a
  22043. // predecessor to {RLD, LLD, CondNode}. As we've already compared the
  22044. // Loads, we only need to check if CondNode is a successor to one of the
  22045. // loads. We can further avoid this if there's no use of their chain
  22046. // value.
  22047. SDNode *CondNode = TheSelect->getOperand(0).getNode();
  22048. Worklist.push_back(CondNode);
  22049. if ((LLD->hasAnyUseOfValue(1) &&
  22050. SDNode::hasPredecessorHelper(LLD, Visited, Worklist)) ||
  22051. (RLD->hasAnyUseOfValue(1) &&
  22052. SDNode::hasPredecessorHelper(RLD, Visited, Worklist)))
  22053. return false;
  22054. Addr = DAG.getSelect(SDLoc(TheSelect),
  22055. LLD->getBasePtr().getValueType(),
  22056. TheSelect->getOperand(0), LLD->getBasePtr(),
  22057. RLD->getBasePtr());
  22058. } else { // Otherwise SELECT_CC
  22059. // We cannot do this optimization if any pair of {RLD, LLD} is a
  22060. // predecessor to {RLD, LLD, CondLHS, CondRHS}. As we've already compared
  22061. // the Loads, we only need to check if CondLHS/CondRHS is a successor to
  22062. // one of the loads. We can further avoid this if there's no use of their
  22063. // chain value.
  22064. SDNode *CondLHS = TheSelect->getOperand(0).getNode();
  22065. SDNode *CondRHS = TheSelect->getOperand(1).getNode();
  22066. Worklist.push_back(CondLHS);
  22067. Worklist.push_back(CondRHS);
  22068. if ((LLD->hasAnyUseOfValue(1) &&
  22069. SDNode::hasPredecessorHelper(LLD, Visited, Worklist)) ||
  22070. (RLD->hasAnyUseOfValue(1) &&
  22071. SDNode::hasPredecessorHelper(RLD, Visited, Worklist)))
  22072. return false;
  22073. Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
  22074. LLD->getBasePtr().getValueType(),
  22075. TheSelect->getOperand(0),
  22076. TheSelect->getOperand(1),
  22077. LLD->getBasePtr(), RLD->getBasePtr(),
  22078. TheSelect->getOperand(4));
  22079. }
  22080. SDValue Load;
  22081. // It is safe to replace the two loads if they have different alignments,
  22082. // but the new load must be the minimum (most restrictive) alignment of the
  22083. // inputs.
  22084. Align Alignment = std::min(LLD->getAlign(), RLD->getAlign());
  22085. MachineMemOperand::Flags MMOFlags = LLD->getMemOperand()->getFlags();
  22086. if (!RLD->isInvariant())
  22087. MMOFlags &= ~MachineMemOperand::MOInvariant;
  22088. if (!RLD->isDereferenceable())
  22089. MMOFlags &= ~MachineMemOperand::MODereferenceable;
  22090. if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
  22091. // FIXME: Discards pointer and AA info.
  22092. Load = DAG.getLoad(TheSelect->getValueType(0), SDLoc(TheSelect),
  22093. LLD->getChain(), Addr, MachinePointerInfo(), Alignment,
  22094. MMOFlags);
  22095. } else {
  22096. // FIXME: Discards pointer and AA info.
  22097. Load = DAG.getExtLoad(
  22098. LLD->getExtensionType() == ISD::EXTLOAD ? RLD->getExtensionType()
  22099. : LLD->getExtensionType(),
  22100. SDLoc(TheSelect), TheSelect->getValueType(0), LLD->getChain(), Addr,
  22101. MachinePointerInfo(), LLD->getMemoryVT(), Alignment, MMOFlags);
  22102. }
  22103. // Users of the select now use the result of the load.
  22104. CombineTo(TheSelect, Load);
  22105. // Users of the old loads now use the new load's chain. We know the
  22106. // old-load value is dead now.
  22107. CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
  22108. CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
  22109. return true;
  22110. }
  22111. return false;
  22112. }
  22113. /// Try to fold an expression of the form (N0 cond N1) ? N2 : N3 to a shift and
  22114. /// bitwise 'and'.
  22115. SDValue DAGCombiner::foldSelectCCToShiftAnd(const SDLoc &DL, SDValue N0,
  22116. SDValue N1, SDValue N2, SDValue N3,
  22117. ISD::CondCode CC) {
  22118. // If this is a select where the false operand is zero and the compare is a
  22119. // check of the sign bit, see if we can perform the "gzip trick":
  22120. // select_cc setlt X, 0, A, 0 -> and (sra X, size(X)-1), A
  22121. // select_cc setgt X, 0, A, 0 -> and (not (sra X, size(X)-1)), A
  22122. EVT XType = N0.getValueType();
  22123. EVT AType = N2.getValueType();
  22124. if (!isNullConstant(N3) || !XType.bitsGE(AType))
  22125. return SDValue();
  22126. // If the comparison is testing for a positive value, we have to invert
  22127. // the sign bit mask, so only do that transform if the target has a bitwise
  22128. // 'and not' instruction (the invert is free).
  22129. if (CC == ISD::SETGT && TLI.hasAndNot(N2)) {
  22130. // (X > -1) ? A : 0
  22131. // (X > 0) ? X : 0 <-- This is canonical signed max.
  22132. if (!(isAllOnesConstant(N1) || (isNullConstant(N1) && N0 == N2)))
  22133. return SDValue();
  22134. } else if (CC == ISD::SETLT) {
  22135. // (X < 0) ? A : 0
  22136. // (X < 1) ? X : 0 <-- This is un-canonicalized signed min.
  22137. if (!(isNullConstant(N1) || (isOneConstant(N1) && N0 == N2)))
  22138. return SDValue();
  22139. } else {
  22140. return SDValue();
  22141. }
  22142. // and (sra X, size(X)-1), A -> "and (srl X, C2), A" iff A is a single-bit
  22143. // constant.
  22144. EVT ShiftAmtTy = getShiftAmountTy(N0.getValueType());
  22145. auto *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
  22146. if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue() - 1)) == 0)) {
  22147. unsigned ShCt = XType.getSizeInBits() - N2C->getAPIntValue().logBase2() - 1;
  22148. if (!TLI.shouldAvoidTransformToShift(XType, ShCt)) {
  22149. SDValue ShiftAmt = DAG.getConstant(ShCt, DL, ShiftAmtTy);
  22150. SDValue Shift = DAG.getNode(ISD::SRL, DL, XType, N0, ShiftAmt);
  22151. AddToWorklist(Shift.getNode());
  22152. if (XType.bitsGT(AType)) {
  22153. Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
  22154. AddToWorklist(Shift.getNode());
  22155. }
  22156. if (CC == ISD::SETGT)
  22157. Shift = DAG.getNOT(DL, Shift, AType);
  22158. return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
  22159. }
  22160. }
  22161. unsigned ShCt = XType.getSizeInBits() - 1;
  22162. if (TLI.shouldAvoidTransformToShift(XType, ShCt))
  22163. return SDValue();
  22164. SDValue ShiftAmt = DAG.getConstant(ShCt, DL, ShiftAmtTy);
  22165. SDValue Shift = DAG.getNode(ISD::SRA, DL, XType, N0, ShiftAmt);
  22166. AddToWorklist(Shift.getNode());
  22167. if (XType.bitsGT(AType)) {
  22168. Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
  22169. AddToWorklist(Shift.getNode());
  22170. }
  22171. if (CC == ISD::SETGT)
  22172. Shift = DAG.getNOT(DL, Shift, AType);
  22173. return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
  22174. }
  22175. // Fold select(cc, binop(), binop()) -> binop(select(), select()) etc.
  22176. SDValue DAGCombiner::foldSelectOfBinops(SDNode *N) {
  22177. SDValue N0 = N->getOperand(0);
  22178. SDValue N1 = N->getOperand(1);
  22179. SDValue N2 = N->getOperand(2);
  22180. EVT VT = N->getValueType(0);
  22181. SDLoc DL(N);
  22182. unsigned BinOpc = N1.getOpcode();
  22183. if (!TLI.isBinOp(BinOpc) || (N2.getOpcode() != BinOpc))
  22184. return SDValue();
  22185. // The use checks are intentionally on SDNode because we may be dealing
  22186. // with opcodes that produce more than one SDValue.
  22187. // TODO: Do we really need to check N0 (the condition operand of the select)?
  22188. // But removing that clause could cause an infinite loop...
  22189. if (!N0->hasOneUse() || !N1->hasOneUse() || !N2->hasOneUse())
  22190. return SDValue();
  22191. // Binops may include opcodes that return multiple values, so all values
  22192. // must be created/propagated from the newly created binops below.
  22193. SDVTList OpVTs = N1->getVTList();
  22194. // Fold select(cond, binop(x, y), binop(z, y))
  22195. // --> binop(select(cond, x, z), y)
  22196. if (N1.getOperand(1) == N2.getOperand(1)) {
  22197. SDValue NewSel =
  22198. DAG.getSelect(DL, VT, N0, N1.getOperand(0), N2.getOperand(0));
  22199. SDValue NewBinOp = DAG.getNode(BinOpc, DL, OpVTs, NewSel, N1.getOperand(1));
  22200. NewBinOp->setFlags(N1->getFlags());
  22201. NewBinOp->intersectFlagsWith(N2->getFlags());
  22202. return NewBinOp;
  22203. }
  22204. // Fold select(cond, binop(x, y), binop(x, z))
  22205. // --> binop(x, select(cond, y, z))
  22206. // Second op VT might be different (e.g. shift amount type)
  22207. if (N1.getOperand(0) == N2.getOperand(0) &&
  22208. VT == N1.getOperand(1).getValueType() &&
  22209. VT == N2.getOperand(1).getValueType()) {
  22210. SDValue NewSel =
  22211. DAG.getSelect(DL, VT, N0, N1.getOperand(1), N2.getOperand(1));
  22212. SDValue NewBinOp = DAG.getNode(BinOpc, DL, OpVTs, N1.getOperand(0), NewSel);
  22213. NewBinOp->setFlags(N1->getFlags());
  22214. NewBinOp->intersectFlagsWith(N2->getFlags());
  22215. return NewBinOp;
  22216. }
  22217. // TODO: Handle isCommutativeBinOp patterns as well?
  22218. return SDValue();
  22219. }
  22220. // Transform (fneg/fabs (bitconvert x)) to avoid loading constant pool values.
  22221. SDValue DAGCombiner::foldSignChangeInBitcast(SDNode *N) {
  22222. SDValue N0 = N->getOperand(0);
  22223. EVT VT = N->getValueType(0);
  22224. bool IsFabs = N->getOpcode() == ISD::FABS;
  22225. bool IsFree = IsFabs ? TLI.isFAbsFree(VT) : TLI.isFNegFree(VT);
  22226. if (IsFree || N0.getOpcode() != ISD::BITCAST || !N0.hasOneUse())
  22227. return SDValue();
  22228. SDValue Int = N0.getOperand(0);
  22229. EVT IntVT = Int.getValueType();
  22230. // The operand to cast should be integer.
  22231. if (!IntVT.isInteger() || IntVT.isVector())
  22232. return SDValue();
  22233. // (fneg (bitconvert x)) -> (bitconvert (xor x sign))
  22234. // (fabs (bitconvert x)) -> (bitconvert (and x ~sign))
  22235. APInt SignMask;
  22236. if (N0.getValueType().isVector()) {
  22237. // For vector, create a sign mask (0x80...) or its inverse (for fabs,
  22238. // 0x7f...) per element and splat it.
  22239. SignMask = APInt::getSignMask(N0.getScalarValueSizeInBits());
  22240. if (IsFabs)
  22241. SignMask = ~SignMask;
  22242. SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
  22243. } else {
  22244. // For scalar, just use the sign mask (0x80... or the inverse, 0x7f...)
  22245. SignMask = APInt::getSignMask(IntVT.getSizeInBits());
  22246. if (IsFabs)
  22247. SignMask = ~SignMask;
  22248. }
  22249. SDLoc DL(N0);
  22250. Int = DAG.getNode(IsFabs ? ISD::AND : ISD::XOR, DL, IntVT, Int,
  22251. DAG.getConstant(SignMask, DL, IntVT));
  22252. AddToWorklist(Int.getNode());
  22253. return DAG.getBitcast(VT, Int);
  22254. }
  22255. /// Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
  22256. /// where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
  22257. /// in it. This may be a win when the constant is not otherwise available
  22258. /// because it replaces two constant pool loads with one.
  22259. SDValue DAGCombiner::convertSelectOfFPConstantsToLoadOffset(
  22260. const SDLoc &DL, SDValue N0, SDValue N1, SDValue N2, SDValue N3,
  22261. ISD::CondCode CC) {
  22262. if (!TLI.reduceSelectOfFPConstantLoads(N0.getValueType()))
  22263. return SDValue();
  22264. // If we are before legalize types, we want the other legalization to happen
  22265. // first (for example, to avoid messing with soft float).
  22266. auto *TV = dyn_cast<ConstantFPSDNode>(N2);
  22267. auto *FV = dyn_cast<ConstantFPSDNode>(N3);
  22268. EVT VT = N2.getValueType();
  22269. if (!TV || !FV || !TLI.isTypeLegal(VT))
  22270. return SDValue();
  22271. // If a constant can be materialized without loads, this does not make sense.
  22272. if (TLI.getOperationAction(ISD::ConstantFP, VT) == TargetLowering::Legal ||
  22273. TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0), ForCodeSize) ||
  22274. TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0), ForCodeSize))
  22275. return SDValue();
  22276. // If both constants have multiple uses, then we won't need to do an extra
  22277. // load. The values are likely around in registers for other users.
  22278. if (!TV->hasOneUse() && !FV->hasOneUse())
  22279. return SDValue();
  22280. Constant *Elts[] = { const_cast<ConstantFP*>(FV->getConstantFPValue()),
  22281. const_cast<ConstantFP*>(TV->getConstantFPValue()) };
  22282. Type *FPTy = Elts[0]->getType();
  22283. const DataLayout &TD = DAG.getDataLayout();
  22284. // Create a ConstantArray of the two constants.
  22285. Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
  22286. SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(DAG.getDataLayout()),
  22287. TD.getPrefTypeAlign(FPTy));
  22288. Align Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlign();
  22289. // Get offsets to the 0 and 1 elements of the array, so we can select between
  22290. // them.
  22291. SDValue Zero = DAG.getIntPtrConstant(0, DL);
  22292. unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
  22293. SDValue One = DAG.getIntPtrConstant(EltSize, SDLoc(FV));
  22294. SDValue Cond =
  22295. DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()), N0, N1, CC);
  22296. AddToWorklist(Cond.getNode());
  22297. SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(), Cond, One, Zero);
  22298. AddToWorklist(CstOffset.getNode());
  22299. CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx, CstOffset);
  22300. AddToWorklist(CPIdx.getNode());
  22301. return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
  22302. MachinePointerInfo::getConstantPool(
  22303. DAG.getMachineFunction()), Alignment);
  22304. }
  22305. /// Simplify an expression of the form (N0 cond N1) ? N2 : N3
  22306. /// where 'cond' is the comparison specified by CC.
  22307. SDValue DAGCombiner::SimplifySelectCC(const SDLoc &DL, SDValue N0, SDValue N1,
  22308. SDValue N2, SDValue N3, ISD::CondCode CC,
  22309. bool NotExtCompare) {
  22310. // (x ? y : y) -> y.
  22311. if (N2 == N3) return N2;
  22312. EVT CmpOpVT = N0.getValueType();
  22313. EVT CmpResVT = getSetCCResultType(CmpOpVT);
  22314. EVT VT = N2.getValueType();
  22315. auto *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
  22316. auto *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
  22317. auto *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
  22318. // Determine if the condition we're dealing with is constant.
  22319. if (SDValue SCC = DAG.FoldSetCC(CmpResVT, N0, N1, CC, DL)) {
  22320. AddToWorklist(SCC.getNode());
  22321. if (auto *SCCC = dyn_cast<ConstantSDNode>(SCC)) {
  22322. // fold select_cc true, x, y -> x
  22323. // fold select_cc false, x, y -> y
  22324. return !(SCCC->isZero()) ? N2 : N3;
  22325. }
  22326. }
  22327. if (SDValue V =
  22328. convertSelectOfFPConstantsToLoadOffset(DL, N0, N1, N2, N3, CC))
  22329. return V;
  22330. if (SDValue V = foldSelectCCToShiftAnd(DL, N0, N1, N2, N3, CC))
  22331. return V;
  22332. // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (sra (shl x)) A)
  22333. // where y is has a single bit set.
  22334. // A plaintext description would be, we can turn the SELECT_CC into an AND
  22335. // when the condition can be materialized as an all-ones register. Any
  22336. // single bit-test can be materialized as an all-ones register with
  22337. // shift-left and shift-right-arith.
  22338. if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
  22339. N0->getValueType(0) == VT && isNullConstant(N1) && isNullConstant(N2)) {
  22340. SDValue AndLHS = N0->getOperand(0);
  22341. auto *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
  22342. if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
  22343. // Shift the tested bit over the sign bit.
  22344. const APInt &AndMask = ConstAndRHS->getAPIntValue();
  22345. unsigned ShCt = AndMask.getBitWidth() - 1;
  22346. if (!TLI.shouldAvoidTransformToShift(VT, ShCt)) {
  22347. SDValue ShlAmt =
  22348. DAG.getConstant(AndMask.countLeadingZeros(), SDLoc(AndLHS),
  22349. getShiftAmountTy(AndLHS.getValueType()));
  22350. SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
  22351. // Now arithmetic right shift it all the way over, so the result is
  22352. // either all-ones, or zero.
  22353. SDValue ShrAmt =
  22354. DAG.getConstant(ShCt, SDLoc(Shl),
  22355. getShiftAmountTy(Shl.getValueType()));
  22356. SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
  22357. return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
  22358. }
  22359. }
  22360. }
  22361. // fold select C, 16, 0 -> shl C, 4
  22362. bool Fold = N2C && isNullConstant(N3) && N2C->getAPIntValue().isPowerOf2();
  22363. bool Swap = N3C && isNullConstant(N2) && N3C->getAPIntValue().isPowerOf2();
  22364. if ((Fold || Swap) &&
  22365. TLI.getBooleanContents(CmpOpVT) ==
  22366. TargetLowering::ZeroOrOneBooleanContent &&
  22367. (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, CmpOpVT))) {
  22368. if (Swap) {
  22369. CC = ISD::getSetCCInverse(CC, CmpOpVT);
  22370. std::swap(N2C, N3C);
  22371. }
  22372. // If the caller doesn't want us to simplify this into a zext of a compare,
  22373. // don't do it.
  22374. if (NotExtCompare && N2C->isOne())
  22375. return SDValue();
  22376. SDValue Temp, SCC;
  22377. // zext (setcc n0, n1)
  22378. if (LegalTypes) {
  22379. SCC = DAG.getSetCC(DL, CmpResVT, N0, N1, CC);
  22380. if (VT.bitsLT(SCC.getValueType()))
  22381. Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2), VT);
  22382. else
  22383. Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2), VT, SCC);
  22384. } else {
  22385. SCC = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
  22386. Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2), VT, SCC);
  22387. }
  22388. AddToWorklist(SCC.getNode());
  22389. AddToWorklist(Temp.getNode());
  22390. if (N2C->isOne())
  22391. return Temp;
  22392. unsigned ShCt = N2C->getAPIntValue().logBase2();
  22393. if (TLI.shouldAvoidTransformToShift(VT, ShCt))
  22394. return SDValue();
  22395. // shl setcc result by log2 n2c
  22396. return DAG.getNode(ISD::SHL, DL, N2.getValueType(), Temp,
  22397. DAG.getConstant(ShCt, SDLoc(Temp),
  22398. getShiftAmountTy(Temp.getValueType())));
  22399. }
  22400. // select_cc seteq X, 0, sizeof(X), ctlz(X) -> ctlz(X)
  22401. // select_cc seteq X, 0, sizeof(X), ctlz_zero_undef(X) -> ctlz(X)
  22402. // select_cc seteq X, 0, sizeof(X), cttz(X) -> cttz(X)
  22403. // select_cc seteq X, 0, sizeof(X), cttz_zero_undef(X) -> cttz(X)
  22404. // select_cc setne X, 0, ctlz(X), sizeof(X) -> ctlz(X)
  22405. // select_cc setne X, 0, ctlz_zero_undef(X), sizeof(X) -> ctlz(X)
  22406. // select_cc setne X, 0, cttz(X), sizeof(X) -> cttz(X)
  22407. // select_cc setne X, 0, cttz_zero_undef(X), sizeof(X) -> cttz(X)
  22408. if (N1C && N1C->isZero() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
  22409. SDValue ValueOnZero = N2;
  22410. SDValue Count = N3;
  22411. // If the condition is NE instead of E, swap the operands.
  22412. if (CC == ISD::SETNE)
  22413. std::swap(ValueOnZero, Count);
  22414. // Check if the value on zero is a constant equal to the bits in the type.
  22415. if (auto *ValueOnZeroC = dyn_cast<ConstantSDNode>(ValueOnZero)) {
  22416. if (ValueOnZeroC->getAPIntValue() == VT.getSizeInBits()) {
  22417. // If the other operand is cttz/cttz_zero_undef of N0, and cttz is
  22418. // legal, combine to just cttz.
  22419. if ((Count.getOpcode() == ISD::CTTZ ||
  22420. Count.getOpcode() == ISD::CTTZ_ZERO_UNDEF) &&
  22421. N0 == Count.getOperand(0) &&
  22422. (!LegalOperations || TLI.isOperationLegal(ISD::CTTZ, VT)))
  22423. return DAG.getNode(ISD::CTTZ, DL, VT, N0);
  22424. // If the other operand is ctlz/ctlz_zero_undef of N0, and ctlz is
  22425. // legal, combine to just ctlz.
  22426. if ((Count.getOpcode() == ISD::CTLZ ||
  22427. Count.getOpcode() == ISD::CTLZ_ZERO_UNDEF) &&
  22428. N0 == Count.getOperand(0) &&
  22429. (!LegalOperations || TLI.isOperationLegal(ISD::CTLZ, VT)))
  22430. return DAG.getNode(ISD::CTLZ, DL, VT, N0);
  22431. }
  22432. }
  22433. }
  22434. // Fold select_cc setgt X, -1, C, ~C -> xor (ashr X, BW-1), C
  22435. // Fold select_cc setlt X, 0, C, ~C -> xor (ashr X, BW-1), ~C
  22436. if (!NotExtCompare && N1C && N2C && N3C &&
  22437. N2C->getAPIntValue() == ~N3C->getAPIntValue() &&
  22438. ((N1C->isAllOnes() && CC == ISD::SETGT) ||
  22439. (N1C->isZero() && CC == ISD::SETLT)) &&
  22440. !TLI.shouldAvoidTransformToShift(VT, CmpOpVT.getScalarSizeInBits() - 1)) {
  22441. SDValue ASR = DAG.getNode(
  22442. ISD::SRA, DL, CmpOpVT, N0,
  22443. DAG.getConstant(CmpOpVT.getScalarSizeInBits() - 1, DL, CmpOpVT));
  22444. return DAG.getNode(ISD::XOR, DL, VT, DAG.getSExtOrTrunc(ASR, DL, VT),
  22445. DAG.getSExtOrTrunc(CC == ISD::SETLT ? N3 : N2, DL, VT));
  22446. }
  22447. if (SDValue S = PerformMinMaxFpToSatCombine(N0, N1, N2, N3, CC, DAG))
  22448. return S;
  22449. if (SDValue S = PerformUMinFpToSatCombine(N0, N1, N2, N3, CC, DAG))
  22450. return S;
  22451. return SDValue();
  22452. }
  22453. /// This is a stub for TargetLowering::SimplifySetCC.
  22454. SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0, SDValue N1,
  22455. ISD::CondCode Cond, const SDLoc &DL,
  22456. bool foldBooleans) {
  22457. TargetLowering::DAGCombinerInfo
  22458. DagCombineInfo(DAG, Level, false, this);
  22459. return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
  22460. }
  22461. /// Given an ISD::SDIV node expressing a divide by constant, return
  22462. /// a DAG expression to select that will generate the same value by multiplying
  22463. /// by a magic number.
  22464. /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
  22465. SDValue DAGCombiner::BuildSDIV(SDNode *N) {
  22466. // when optimising for minimum size, we don't want to expand a div to a mul
  22467. // and a shift.
  22468. if (DAG.getMachineFunction().getFunction().hasMinSize())
  22469. return SDValue();
  22470. SmallVector<SDNode *, 8> Built;
  22471. if (SDValue S = TLI.BuildSDIV(N, DAG, LegalOperations, Built)) {
  22472. for (SDNode *N : Built)
  22473. AddToWorklist(N);
  22474. return S;
  22475. }
  22476. return SDValue();
  22477. }
  22478. /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a
  22479. /// DAG expression that will generate the same value by right shifting.
  22480. SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
  22481. ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
  22482. if (!C)
  22483. return SDValue();
  22484. // Avoid division by zero.
  22485. if (C->isZero())
  22486. return SDValue();
  22487. SmallVector<SDNode *, 8> Built;
  22488. if (SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, Built)) {
  22489. for (SDNode *N : Built)
  22490. AddToWorklist(N);
  22491. return S;
  22492. }
  22493. return SDValue();
  22494. }
  22495. /// Given an ISD::UDIV node expressing a divide by constant, return a DAG
  22496. /// expression that will generate the same value by multiplying by a magic
  22497. /// number.
  22498. /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
  22499. SDValue DAGCombiner::BuildUDIV(SDNode *N) {
  22500. // when optimising for minimum size, we don't want to expand a div to a mul
  22501. // and a shift.
  22502. if (DAG.getMachineFunction().getFunction().hasMinSize())
  22503. return SDValue();
  22504. SmallVector<SDNode *, 8> Built;
  22505. if (SDValue S = TLI.BuildUDIV(N, DAG, LegalOperations, Built)) {
  22506. for (SDNode *N : Built)
  22507. AddToWorklist(N);
  22508. return S;
  22509. }
  22510. return SDValue();
  22511. }
  22512. /// Given an ISD::SREM node expressing a remainder by constant power of 2,
  22513. /// return a DAG expression that will generate the same value.
  22514. SDValue DAGCombiner::BuildSREMPow2(SDNode *N) {
  22515. ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
  22516. if (!C)
  22517. return SDValue();
  22518. // Avoid division by zero.
  22519. if (C->isZero())
  22520. return SDValue();
  22521. SmallVector<SDNode *, 8> Built;
  22522. if (SDValue S = TLI.BuildSREMPow2(N, C->getAPIntValue(), DAG, Built)) {
  22523. for (SDNode *N : Built)
  22524. AddToWorklist(N);
  22525. return S;
  22526. }
  22527. return SDValue();
  22528. }
  22529. /// Determines the LogBase2 value for a non-null input value using the
  22530. /// transform: LogBase2(V) = (EltBits - 1) - ctlz(V).
  22531. SDValue DAGCombiner::BuildLogBase2(SDValue V, const SDLoc &DL) {
  22532. EVT VT = V.getValueType();
  22533. SDValue Ctlz = DAG.getNode(ISD::CTLZ, DL, VT, V);
  22534. SDValue Base = DAG.getConstant(VT.getScalarSizeInBits() - 1, DL, VT);
  22535. SDValue LogBase2 = DAG.getNode(ISD::SUB, DL, VT, Base, Ctlz);
  22536. return LogBase2;
  22537. }
  22538. /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
  22539. /// For the reciprocal, we need to find the zero of the function:
  22540. /// F(X) = 1/X - A [which has a zero at X = 1/A]
  22541. /// =>
  22542. /// X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
  22543. /// does not require additional intermediate precision]
  22544. /// For the last iteration, put numerator N into it to gain more precision:
  22545. /// Result = N X_i + X_i (N - N A X_i)
  22546. SDValue DAGCombiner::BuildDivEstimate(SDValue N, SDValue Op,
  22547. SDNodeFlags Flags) {
  22548. if (LegalDAG)
  22549. return SDValue();
  22550. // TODO: Handle extended types?
  22551. EVT VT = Op.getValueType();
  22552. if (VT.getScalarType() != MVT::f16 && VT.getScalarType() != MVT::f32 &&
  22553. VT.getScalarType() != MVT::f64)
  22554. return SDValue();
  22555. // If estimates are explicitly disabled for this function, we're done.
  22556. MachineFunction &MF = DAG.getMachineFunction();
  22557. int Enabled = TLI.getRecipEstimateDivEnabled(VT, MF);
  22558. if (Enabled == TLI.ReciprocalEstimate::Disabled)
  22559. return SDValue();
  22560. // Estimates may be explicitly enabled for this type with a custom number of
  22561. // refinement steps.
  22562. int Iterations = TLI.getDivRefinementSteps(VT, MF);
  22563. if (SDValue Est = TLI.getRecipEstimate(Op, DAG, Enabled, Iterations)) {
  22564. AddToWorklist(Est.getNode());
  22565. SDLoc DL(Op);
  22566. if (Iterations) {
  22567. SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
  22568. // Newton iterations: Est = Est + Est (N - Arg * Est)
  22569. // If this is the last iteration, also multiply by the numerator.
  22570. for (int i = 0; i < Iterations; ++i) {
  22571. SDValue MulEst = Est;
  22572. if (i == Iterations - 1) {
  22573. MulEst = DAG.getNode(ISD::FMUL, DL, VT, N, Est, Flags);
  22574. AddToWorklist(MulEst.getNode());
  22575. }
  22576. SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, MulEst, Flags);
  22577. AddToWorklist(NewEst.getNode());
  22578. NewEst = DAG.getNode(ISD::FSUB, DL, VT,
  22579. (i == Iterations - 1 ? N : FPOne), NewEst, Flags);
  22580. AddToWorklist(NewEst.getNode());
  22581. NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags);
  22582. AddToWorklist(NewEst.getNode());
  22583. Est = DAG.getNode(ISD::FADD, DL, VT, MulEst, NewEst, Flags);
  22584. AddToWorklist(Est.getNode());
  22585. }
  22586. } else {
  22587. // If no iterations are available, multiply with N.
  22588. Est = DAG.getNode(ISD::FMUL, DL, VT, Est, N, Flags);
  22589. AddToWorklist(Est.getNode());
  22590. }
  22591. return Est;
  22592. }
  22593. return SDValue();
  22594. }
  22595. /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
  22596. /// For the reciprocal sqrt, we need to find the zero of the function:
  22597. /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
  22598. /// =>
  22599. /// X_{i+1} = X_i (1.5 - A X_i^2 / 2)
  22600. /// As a result, we precompute A/2 prior to the iteration loop.
  22601. SDValue DAGCombiner::buildSqrtNROneConst(SDValue Arg, SDValue Est,
  22602. unsigned Iterations,
  22603. SDNodeFlags Flags, bool Reciprocal) {
  22604. EVT VT = Arg.getValueType();
  22605. SDLoc DL(Arg);
  22606. SDValue ThreeHalves = DAG.getConstantFP(1.5, DL, VT);
  22607. // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that
  22608. // this entire sequence requires only one FP constant.
  22609. SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg, Flags);
  22610. HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg, Flags);
  22611. // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
  22612. for (unsigned i = 0; i < Iterations; ++i) {
  22613. SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est, Flags);
  22614. NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst, Flags);
  22615. NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst, Flags);
  22616. Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags);
  22617. }
  22618. // If non-reciprocal square root is requested, multiply the result by Arg.
  22619. if (!Reciprocal)
  22620. Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg, Flags);
  22621. return Est;
  22622. }
  22623. /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
  22624. /// For the reciprocal sqrt, we need to find the zero of the function:
  22625. /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
  22626. /// =>
  22627. /// X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0))
  22628. SDValue DAGCombiner::buildSqrtNRTwoConst(SDValue Arg, SDValue Est,
  22629. unsigned Iterations,
  22630. SDNodeFlags Flags, bool Reciprocal) {
  22631. EVT VT = Arg.getValueType();
  22632. SDLoc DL(Arg);
  22633. SDValue MinusThree = DAG.getConstantFP(-3.0, DL, VT);
  22634. SDValue MinusHalf = DAG.getConstantFP(-0.5, DL, VT);
  22635. // This routine must enter the loop below to work correctly
  22636. // when (Reciprocal == false).
  22637. assert(Iterations > 0);
  22638. // Newton iterations for reciprocal square root:
  22639. // E = (E * -0.5) * ((A * E) * E + -3.0)
  22640. for (unsigned i = 0; i < Iterations; ++i) {
  22641. SDValue AE = DAG.getNode(ISD::FMUL, DL, VT, Arg, Est, Flags);
  22642. SDValue AEE = DAG.getNode(ISD::FMUL, DL, VT, AE, Est, Flags);
  22643. SDValue RHS = DAG.getNode(ISD::FADD, DL, VT, AEE, MinusThree, Flags);
  22644. // When calculating a square root at the last iteration build:
  22645. // S = ((A * E) * -0.5) * ((A * E) * E + -3.0)
  22646. // (notice a common subexpression)
  22647. SDValue LHS;
  22648. if (Reciprocal || (i + 1) < Iterations) {
  22649. // RSQRT: LHS = (E * -0.5)
  22650. LHS = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf, Flags);
  22651. } else {
  22652. // SQRT: LHS = (A * E) * -0.5
  22653. LHS = DAG.getNode(ISD::FMUL, DL, VT, AE, MinusHalf, Flags);
  22654. }
  22655. Est = DAG.getNode(ISD::FMUL, DL, VT, LHS, RHS, Flags);
  22656. }
  22657. return Est;
  22658. }
  22659. /// Build code to calculate either rsqrt(Op) or sqrt(Op). In the latter case
  22660. /// Op*rsqrt(Op) is actually computed, so additional postprocessing is needed if
  22661. /// Op can be zero.
  22662. SDValue DAGCombiner::buildSqrtEstimateImpl(SDValue Op, SDNodeFlags Flags,
  22663. bool Reciprocal) {
  22664. if (LegalDAG)
  22665. return SDValue();
  22666. // TODO: Handle extended types?
  22667. EVT VT = Op.getValueType();
  22668. if (VT.getScalarType() != MVT::f16 && VT.getScalarType() != MVT::f32 &&
  22669. VT.getScalarType() != MVT::f64)
  22670. return SDValue();
  22671. // If estimates are explicitly disabled for this function, we're done.
  22672. MachineFunction &MF = DAG.getMachineFunction();
  22673. int Enabled = TLI.getRecipEstimateSqrtEnabled(VT, MF);
  22674. if (Enabled == TLI.ReciprocalEstimate::Disabled)
  22675. return SDValue();
  22676. // Estimates may be explicitly enabled for this type with a custom number of
  22677. // refinement steps.
  22678. int Iterations = TLI.getSqrtRefinementSteps(VT, MF);
  22679. bool UseOneConstNR = false;
  22680. if (SDValue Est =
  22681. TLI.getSqrtEstimate(Op, DAG, Enabled, Iterations, UseOneConstNR,
  22682. Reciprocal)) {
  22683. AddToWorklist(Est.getNode());
  22684. if (Iterations)
  22685. Est = UseOneConstNR
  22686. ? buildSqrtNROneConst(Op, Est, Iterations, Flags, Reciprocal)
  22687. : buildSqrtNRTwoConst(Op, Est, Iterations, Flags, Reciprocal);
  22688. if (!Reciprocal) {
  22689. SDLoc DL(Op);
  22690. // Try the target specific test first.
  22691. SDValue Test = TLI.getSqrtInputTest(Op, DAG, DAG.getDenormalMode(VT));
  22692. // The estimate is now completely wrong if the input was exactly 0.0 or
  22693. // possibly a denormal. Force the answer to 0.0 or value provided by
  22694. // target for those cases.
  22695. Est = DAG.getNode(
  22696. Test.getValueType().isVector() ? ISD::VSELECT : ISD::SELECT, DL, VT,
  22697. Test, TLI.getSqrtResultForDenormInput(Op, DAG), Est);
  22698. }
  22699. return Est;
  22700. }
  22701. return SDValue();
  22702. }
  22703. SDValue DAGCombiner::buildRsqrtEstimate(SDValue Op, SDNodeFlags Flags) {
  22704. return buildSqrtEstimateImpl(Op, Flags, true);
  22705. }
  22706. SDValue DAGCombiner::buildSqrtEstimate(SDValue Op, SDNodeFlags Flags) {
  22707. return buildSqrtEstimateImpl(Op, Flags, false);
  22708. }
  22709. /// Return true if there is any possibility that the two addresses overlap.
  22710. bool DAGCombiner::mayAlias(SDNode *Op0, SDNode *Op1) const {
  22711. struct MemUseCharacteristics {
  22712. bool IsVolatile;
  22713. bool IsAtomic;
  22714. SDValue BasePtr;
  22715. int64_t Offset;
  22716. std::optional<int64_t> NumBytes;
  22717. MachineMemOperand *MMO;
  22718. };
  22719. auto getCharacteristics = [](SDNode *N) -> MemUseCharacteristics {
  22720. if (const auto *LSN = dyn_cast<LSBaseSDNode>(N)) {
  22721. int64_t Offset = 0;
  22722. if (auto *C = dyn_cast<ConstantSDNode>(LSN->getOffset()))
  22723. Offset = (LSN->getAddressingMode() == ISD::PRE_INC)
  22724. ? C->getSExtValue()
  22725. : (LSN->getAddressingMode() == ISD::PRE_DEC)
  22726. ? -1 * C->getSExtValue()
  22727. : 0;
  22728. uint64_t Size =
  22729. MemoryLocation::getSizeOrUnknown(LSN->getMemoryVT().getStoreSize());
  22730. return {LSN->isVolatile(),
  22731. LSN->isAtomic(),
  22732. LSN->getBasePtr(),
  22733. Offset /*base offset*/,
  22734. std::optional<int64_t>(Size),
  22735. LSN->getMemOperand()};
  22736. }
  22737. if (const auto *LN = cast<LifetimeSDNode>(N))
  22738. return {false /*isVolatile*/,
  22739. /*isAtomic*/ false,
  22740. LN->getOperand(1),
  22741. (LN->hasOffset()) ? LN->getOffset() : 0,
  22742. (LN->hasOffset()) ? std::optional<int64_t>(LN->getSize())
  22743. : std::optional<int64_t>(),
  22744. (MachineMemOperand *)nullptr};
  22745. // Default.
  22746. return {false /*isvolatile*/,
  22747. /*isAtomic*/ false, SDValue(),
  22748. (int64_t)0 /*offset*/, std::optional<int64_t>() /*size*/,
  22749. (MachineMemOperand *)nullptr};
  22750. };
  22751. MemUseCharacteristics MUC0 = getCharacteristics(Op0),
  22752. MUC1 = getCharacteristics(Op1);
  22753. // If they are to the same address, then they must be aliases.
  22754. if (MUC0.BasePtr.getNode() && MUC0.BasePtr == MUC1.BasePtr &&
  22755. MUC0.Offset == MUC1.Offset)
  22756. return true;
  22757. // If they are both volatile then they cannot be reordered.
  22758. if (MUC0.IsVolatile && MUC1.IsVolatile)
  22759. return true;
  22760. // Be conservative about atomics for the moment
  22761. // TODO: This is way overconservative for unordered atomics (see D66309)
  22762. if (MUC0.IsAtomic && MUC1.IsAtomic)
  22763. return true;
  22764. if (MUC0.MMO && MUC1.MMO) {
  22765. if ((MUC0.MMO->isInvariant() && MUC1.MMO->isStore()) ||
  22766. (MUC1.MMO->isInvariant() && MUC0.MMO->isStore()))
  22767. return false;
  22768. }
  22769. // Try to prove that there is aliasing, or that there is no aliasing. Either
  22770. // way, we can return now. If nothing can be proved, proceed with more tests.
  22771. bool IsAlias;
  22772. if (BaseIndexOffset::computeAliasing(Op0, MUC0.NumBytes, Op1, MUC1.NumBytes,
  22773. DAG, IsAlias))
  22774. return IsAlias;
  22775. // The following all rely on MMO0 and MMO1 being valid. Fail conservatively if
  22776. // either are not known.
  22777. if (!MUC0.MMO || !MUC1.MMO)
  22778. return true;
  22779. // If one operation reads from invariant memory, and the other may store, they
  22780. // cannot alias. These should really be checking the equivalent of mayWrite,
  22781. // but it only matters for memory nodes other than load /store.
  22782. if ((MUC0.MMO->isInvariant() && MUC1.MMO->isStore()) ||
  22783. (MUC1.MMO->isInvariant() && MUC0.MMO->isStore()))
  22784. return false;
  22785. // If we know required SrcValue1 and SrcValue2 have relatively large
  22786. // alignment compared to the size and offset of the access, we may be able
  22787. // to prove they do not alias. This check is conservative for now to catch
  22788. // cases created by splitting vector types, it only works when the offsets are
  22789. // multiples of the size of the data.
  22790. int64_t SrcValOffset0 = MUC0.MMO->getOffset();
  22791. int64_t SrcValOffset1 = MUC1.MMO->getOffset();
  22792. Align OrigAlignment0 = MUC0.MMO->getBaseAlign();
  22793. Align OrigAlignment1 = MUC1.MMO->getBaseAlign();
  22794. auto &Size0 = MUC0.NumBytes;
  22795. auto &Size1 = MUC1.NumBytes;
  22796. if (OrigAlignment0 == OrigAlignment1 && SrcValOffset0 != SrcValOffset1 &&
  22797. Size0.has_value() && Size1.has_value() && *Size0 == *Size1 &&
  22798. OrigAlignment0 > *Size0 && SrcValOffset0 % *Size0 == 0 &&
  22799. SrcValOffset1 % *Size1 == 0) {
  22800. int64_t OffAlign0 = SrcValOffset0 % OrigAlignment0.value();
  22801. int64_t OffAlign1 = SrcValOffset1 % OrigAlignment1.value();
  22802. // There is no overlap between these relatively aligned accesses of
  22803. // similar size. Return no alias.
  22804. if ((OffAlign0 + *Size0) <= OffAlign1 || (OffAlign1 + *Size1) <= OffAlign0)
  22805. return false;
  22806. }
  22807. bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0
  22808. ? CombinerGlobalAA
  22809. : DAG.getSubtarget().useAA();
  22810. #ifndef NDEBUG
  22811. if (CombinerAAOnlyFunc.getNumOccurrences() &&
  22812. CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
  22813. UseAA = false;
  22814. #endif
  22815. if (UseAA && AA && MUC0.MMO->getValue() && MUC1.MMO->getValue() && Size0 &&
  22816. Size1) {
  22817. // Use alias analysis information.
  22818. int64_t MinOffset = std::min(SrcValOffset0, SrcValOffset1);
  22819. int64_t Overlap0 = *Size0 + SrcValOffset0 - MinOffset;
  22820. int64_t Overlap1 = *Size1 + SrcValOffset1 - MinOffset;
  22821. if (AA->isNoAlias(
  22822. MemoryLocation(MUC0.MMO->getValue(), Overlap0,
  22823. UseTBAA ? MUC0.MMO->getAAInfo() : AAMDNodes()),
  22824. MemoryLocation(MUC1.MMO->getValue(), Overlap1,
  22825. UseTBAA ? MUC1.MMO->getAAInfo() : AAMDNodes())))
  22826. return false;
  22827. }
  22828. // Otherwise we have to assume they alias.
  22829. return true;
  22830. }
  22831. /// Walk up chain skipping non-aliasing memory nodes,
  22832. /// looking for aliasing nodes and adding them to the Aliases vector.
  22833. void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
  22834. SmallVectorImpl<SDValue> &Aliases) {
  22835. SmallVector<SDValue, 8> Chains; // List of chains to visit.
  22836. SmallPtrSet<SDNode *, 16> Visited; // Visited node set.
  22837. // Get alias information for node.
  22838. // TODO: relax aliasing for unordered atomics (see D66309)
  22839. const bool IsLoad = isa<LoadSDNode>(N) && cast<LoadSDNode>(N)->isSimple();
  22840. // Starting off.
  22841. Chains.push_back(OriginalChain);
  22842. unsigned Depth = 0;
  22843. // Attempt to improve chain by a single step
  22844. auto ImproveChain = [&](SDValue &C) -> bool {
  22845. switch (C.getOpcode()) {
  22846. case ISD::EntryToken:
  22847. // No need to mark EntryToken.
  22848. C = SDValue();
  22849. return true;
  22850. case ISD::LOAD:
  22851. case ISD::STORE: {
  22852. // Get alias information for C.
  22853. // TODO: Relax aliasing for unordered atomics (see D66309)
  22854. bool IsOpLoad = isa<LoadSDNode>(C.getNode()) &&
  22855. cast<LSBaseSDNode>(C.getNode())->isSimple();
  22856. if ((IsLoad && IsOpLoad) || !mayAlias(N, C.getNode())) {
  22857. // Look further up the chain.
  22858. C = C.getOperand(0);
  22859. return true;
  22860. }
  22861. // Alias, so stop here.
  22862. return false;
  22863. }
  22864. case ISD::CopyFromReg:
  22865. // Always forward past past CopyFromReg.
  22866. C = C.getOperand(0);
  22867. return true;
  22868. case ISD::LIFETIME_START:
  22869. case ISD::LIFETIME_END: {
  22870. // We can forward past any lifetime start/end that can be proven not to
  22871. // alias the memory access.
  22872. if (!mayAlias(N, C.getNode())) {
  22873. // Look further up the chain.
  22874. C = C.getOperand(0);
  22875. return true;
  22876. }
  22877. return false;
  22878. }
  22879. default:
  22880. return false;
  22881. }
  22882. };
  22883. // Look at each chain and determine if it is an alias. If so, add it to the
  22884. // aliases list. If not, then continue up the chain looking for the next
  22885. // candidate.
  22886. while (!Chains.empty()) {
  22887. SDValue Chain = Chains.pop_back_val();
  22888. // Don't bother if we've seen Chain before.
  22889. if (!Visited.insert(Chain.getNode()).second)
  22890. continue;
  22891. // For TokenFactor nodes, look at each operand and only continue up the
  22892. // chain until we reach the depth limit.
  22893. //
  22894. // FIXME: The depth check could be made to return the last non-aliasing
  22895. // chain we found before we hit a tokenfactor rather than the original
  22896. // chain.
  22897. if (Depth > TLI.getGatherAllAliasesMaxDepth()) {
  22898. Aliases.clear();
  22899. Aliases.push_back(OriginalChain);
  22900. return;
  22901. }
  22902. if (Chain.getOpcode() == ISD::TokenFactor) {
  22903. // We have to check each of the operands of the token factor for "small"
  22904. // token factors, so we queue them up. Adding the operands to the queue
  22905. // (stack) in reverse order maintains the original order and increases the
  22906. // likelihood that getNode will find a matching token factor (CSE.)
  22907. if (Chain.getNumOperands() > 16) {
  22908. Aliases.push_back(Chain);
  22909. continue;
  22910. }
  22911. for (unsigned n = Chain.getNumOperands(); n;)
  22912. Chains.push_back(Chain.getOperand(--n));
  22913. ++Depth;
  22914. continue;
  22915. }
  22916. // Everything else
  22917. if (ImproveChain(Chain)) {
  22918. // Updated Chain Found, Consider new chain if one exists.
  22919. if (Chain.getNode())
  22920. Chains.push_back(Chain);
  22921. ++Depth;
  22922. continue;
  22923. }
  22924. // No Improved Chain Possible, treat as Alias.
  22925. Aliases.push_back(Chain);
  22926. }
  22927. }
  22928. /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain
  22929. /// (aliasing node.)
  22930. SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
  22931. if (OptLevel == CodeGenOpt::None)
  22932. return OldChain;
  22933. // Ops for replacing token factor.
  22934. SmallVector<SDValue, 8> Aliases;
  22935. // Accumulate all the aliases to this node.
  22936. GatherAllAliases(N, OldChain, Aliases);
  22937. // If no operands then chain to entry token.
  22938. if (Aliases.size() == 0)
  22939. return DAG.getEntryNode();
  22940. // If a single operand then chain to it. We don't need to revisit it.
  22941. if (Aliases.size() == 1)
  22942. return Aliases[0];
  22943. // Construct a custom tailored token factor.
  22944. return DAG.getTokenFactor(SDLoc(N), Aliases);
  22945. }
  22946. // This function tries to collect a bunch of potentially interesting
  22947. // nodes to improve the chains of, all at once. This might seem
  22948. // redundant, as this function gets called when visiting every store
  22949. // node, so why not let the work be done on each store as it's visited?
  22950. //
  22951. // I believe this is mainly important because mergeConsecutiveStores
  22952. // is unable to deal with merging stores of different sizes, so unless
  22953. // we improve the chains of all the potential candidates up-front
  22954. // before running mergeConsecutiveStores, it might only see some of
  22955. // the nodes that will eventually be candidates, and then not be able
  22956. // to go from a partially-merged state to the desired final
  22957. // fully-merged state.
  22958. bool DAGCombiner::parallelizeChainedStores(StoreSDNode *St) {
  22959. SmallVector<StoreSDNode *, 8> ChainedStores;
  22960. StoreSDNode *STChain = St;
  22961. // Intervals records which offsets from BaseIndex have been covered. In
  22962. // the common case, every store writes to the immediately previous address
  22963. // space and thus merged with the previous interval at insertion time.
  22964. using IMap = llvm::IntervalMap<int64_t, std::monostate, 8,
  22965. IntervalMapHalfOpenInfo<int64_t>>;
  22966. IMap::Allocator A;
  22967. IMap Intervals(A);
  22968. // This holds the base pointer, index, and the offset in bytes from the base
  22969. // pointer.
  22970. const BaseIndexOffset BasePtr = BaseIndexOffset::match(St, DAG);
  22971. // We must have a base and an offset.
  22972. if (!BasePtr.getBase().getNode())
  22973. return false;
  22974. // Do not handle stores to undef base pointers.
  22975. if (BasePtr.getBase().isUndef())
  22976. return false;
  22977. // Do not handle stores to opaque types
  22978. if (St->getMemoryVT().isZeroSized())
  22979. return false;
  22980. // BaseIndexOffset assumes that offsets are fixed-size, which
  22981. // is not valid for scalable vectors where the offsets are
  22982. // scaled by `vscale`, so bail out early.
  22983. if (St->getMemoryVT().isScalableVector())
  22984. return false;
  22985. // Add ST's interval.
  22986. Intervals.insert(0, (St->getMemoryVT().getSizeInBits() + 7) / 8,
  22987. std::monostate{});
  22988. while (StoreSDNode *Chain = dyn_cast<StoreSDNode>(STChain->getChain())) {
  22989. if (Chain->getMemoryVT().isScalableVector())
  22990. return false;
  22991. // If the chain has more than one use, then we can't reorder the mem ops.
  22992. if (!SDValue(Chain, 0)->hasOneUse())
  22993. break;
  22994. // TODO: Relax for unordered atomics (see D66309)
  22995. if (!Chain->isSimple() || Chain->isIndexed())
  22996. break;
  22997. // Find the base pointer and offset for this memory node.
  22998. const BaseIndexOffset Ptr = BaseIndexOffset::match(Chain, DAG);
  22999. // Check that the base pointer is the same as the original one.
  23000. int64_t Offset;
  23001. if (!BasePtr.equalBaseIndex(Ptr, DAG, Offset))
  23002. break;
  23003. int64_t Length = (Chain->getMemoryVT().getSizeInBits() + 7) / 8;
  23004. // Make sure we don't overlap with other intervals by checking the ones to
  23005. // the left or right before inserting.
  23006. auto I = Intervals.find(Offset);
  23007. // If there's a next interval, we should end before it.
  23008. if (I != Intervals.end() && I.start() < (Offset + Length))
  23009. break;
  23010. // If there's a previous interval, we should start after it.
  23011. if (I != Intervals.begin() && (--I).stop() <= Offset)
  23012. break;
  23013. Intervals.insert(Offset, Offset + Length, std::monostate{});
  23014. ChainedStores.push_back(Chain);
  23015. STChain = Chain;
  23016. }
  23017. // If we didn't find a chained store, exit.
  23018. if (ChainedStores.size() == 0)
  23019. return false;
  23020. // Improve all chained stores (St and ChainedStores members) starting from
  23021. // where the store chain ended and return single TokenFactor.
  23022. SDValue NewChain = STChain->getChain();
  23023. SmallVector<SDValue, 8> TFOps;
  23024. for (unsigned I = ChainedStores.size(); I;) {
  23025. StoreSDNode *S = ChainedStores[--I];
  23026. SDValue BetterChain = FindBetterChain(S, NewChain);
  23027. S = cast<StoreSDNode>(DAG.UpdateNodeOperands(
  23028. S, BetterChain, S->getOperand(1), S->getOperand(2), S->getOperand(3)));
  23029. TFOps.push_back(SDValue(S, 0));
  23030. ChainedStores[I] = S;
  23031. }
  23032. // Improve St's chain. Use a new node to avoid creating a loop from CombineTo.
  23033. SDValue BetterChain = FindBetterChain(St, NewChain);
  23034. SDValue NewST;
  23035. if (St->isTruncatingStore())
  23036. NewST = DAG.getTruncStore(BetterChain, SDLoc(St), St->getValue(),
  23037. St->getBasePtr(), St->getMemoryVT(),
  23038. St->getMemOperand());
  23039. else
  23040. NewST = DAG.getStore(BetterChain, SDLoc(St), St->getValue(),
  23041. St->getBasePtr(), St->getMemOperand());
  23042. TFOps.push_back(NewST);
  23043. // If we improved every element of TFOps, then we've lost the dependence on
  23044. // NewChain to successors of St and we need to add it back to TFOps. Do so at
  23045. // the beginning to keep relative order consistent with FindBetterChains.
  23046. auto hasImprovedChain = [&](SDValue ST) -> bool {
  23047. return ST->getOperand(0) != NewChain;
  23048. };
  23049. bool AddNewChain = llvm::all_of(TFOps, hasImprovedChain);
  23050. if (AddNewChain)
  23051. TFOps.insert(TFOps.begin(), NewChain);
  23052. SDValue TF = DAG.getTokenFactor(SDLoc(STChain), TFOps);
  23053. CombineTo(St, TF);
  23054. // Add TF and its operands to the worklist.
  23055. AddToWorklist(TF.getNode());
  23056. for (const SDValue &Op : TF->ops())
  23057. AddToWorklist(Op.getNode());
  23058. AddToWorklist(STChain);
  23059. return true;
  23060. }
  23061. bool DAGCombiner::findBetterNeighborChains(StoreSDNode *St) {
  23062. if (OptLevel == CodeGenOpt::None)
  23063. return false;
  23064. const BaseIndexOffset BasePtr = BaseIndexOffset::match(St, DAG);
  23065. // We must have a base and an offset.
  23066. if (!BasePtr.getBase().getNode())
  23067. return false;
  23068. // Do not handle stores to undef base pointers.
  23069. if (BasePtr.getBase().isUndef())
  23070. return false;
  23071. // Directly improve a chain of disjoint stores starting at St.
  23072. if (parallelizeChainedStores(St))
  23073. return true;
  23074. // Improve St's Chain..
  23075. SDValue BetterChain = FindBetterChain(St, St->getChain());
  23076. if (St->getChain() != BetterChain) {
  23077. replaceStoreChain(St, BetterChain);
  23078. return true;
  23079. }
  23080. return false;
  23081. }
  23082. /// This is the entry point for the file.
  23083. void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis *AA,
  23084. CodeGenOpt::Level OptLevel) {
  23085. /// This is the main entry point to this class.
  23086. DAGCombiner(*this, AA, OptLevel).Run(Level);
  23087. }