SelectionDAG.cpp 451 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210
  1. //===- SelectionDAG.cpp - Implement the SelectionDAG data structures ------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This implements the SelectionDAG class.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "llvm/CodeGen/SelectionDAG.h"
  13. #include "SDNodeDbgValue.h"
  14. #include "llvm/ADT/APFloat.h"
  15. #include "llvm/ADT/APInt.h"
  16. #include "llvm/ADT/APSInt.h"
  17. #include "llvm/ADT/ArrayRef.h"
  18. #include "llvm/ADT/BitVector.h"
  19. #include "llvm/ADT/FoldingSet.h"
  20. #include "llvm/ADT/STLExtras.h"
  21. #include "llvm/ADT/SmallPtrSet.h"
  22. #include "llvm/ADT/SmallVector.h"
  23. #include "llvm/ADT/Triple.h"
  24. #include "llvm/ADT/Twine.h"
  25. #include "llvm/Analysis/AliasAnalysis.h"
  26. #include "llvm/Analysis/MemoryLocation.h"
  27. #include "llvm/Analysis/ValueTracking.h"
  28. #include "llvm/Analysis/VectorUtils.h"
  29. #include "llvm/CodeGen/Analysis.h"
  30. #include "llvm/CodeGen/FunctionLoweringInfo.h"
  31. #include "llvm/CodeGen/ISDOpcodes.h"
  32. #include "llvm/CodeGen/MachineBasicBlock.h"
  33. #include "llvm/CodeGen/MachineConstantPool.h"
  34. #include "llvm/CodeGen/MachineFrameInfo.h"
  35. #include "llvm/CodeGen/MachineFunction.h"
  36. #include "llvm/CodeGen/MachineMemOperand.h"
  37. #include "llvm/CodeGen/RuntimeLibcalls.h"
  38. #include "llvm/CodeGen/SelectionDAGAddressAnalysis.h"
  39. #include "llvm/CodeGen/SelectionDAGNodes.h"
  40. #include "llvm/CodeGen/SelectionDAGTargetInfo.h"
  41. #include "llvm/CodeGen/TargetFrameLowering.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/Constant.h"
  47. #include "llvm/IR/ConstantRange.h"
  48. #include "llvm/IR/Constants.h"
  49. #include "llvm/IR/DataLayout.h"
  50. #include "llvm/IR/DebugInfoMetadata.h"
  51. #include "llvm/IR/DebugLoc.h"
  52. #include "llvm/IR/DerivedTypes.h"
  53. #include "llvm/IR/Function.h"
  54. #include "llvm/IR/GlobalValue.h"
  55. #include "llvm/IR/Metadata.h"
  56. #include "llvm/IR/Type.h"
  57. #include "llvm/Support/Casting.h"
  58. #include "llvm/Support/CodeGen.h"
  59. #include "llvm/Support/Compiler.h"
  60. #include "llvm/Support/Debug.h"
  61. #include "llvm/Support/ErrorHandling.h"
  62. #include "llvm/Support/KnownBits.h"
  63. #include "llvm/Support/MachineValueType.h"
  64. #include "llvm/Support/MathExtras.h"
  65. #include "llvm/Support/Mutex.h"
  66. #include "llvm/Support/raw_ostream.h"
  67. #include "llvm/Target/TargetMachine.h"
  68. #include "llvm/Target/TargetOptions.h"
  69. #include "llvm/Transforms/Utils/SizeOpts.h"
  70. #include <algorithm>
  71. #include <cassert>
  72. #include <cstdint>
  73. #include <cstdlib>
  74. #include <limits>
  75. #include <set>
  76. #include <string>
  77. #include <utility>
  78. #include <vector>
  79. using namespace llvm;
  80. /// makeVTList - Return an instance of the SDVTList struct initialized with the
  81. /// specified members.
  82. static SDVTList makeVTList(const EVT *VTs, unsigned NumVTs) {
  83. SDVTList Res = {VTs, NumVTs};
  84. return Res;
  85. }
  86. // Default null implementations of the callbacks.
  87. void SelectionDAG::DAGUpdateListener::NodeDeleted(SDNode*, SDNode*) {}
  88. void SelectionDAG::DAGUpdateListener::NodeUpdated(SDNode*) {}
  89. void SelectionDAG::DAGUpdateListener::NodeInserted(SDNode *) {}
  90. void SelectionDAG::DAGNodeDeletedListener::anchor() {}
  91. void SelectionDAG::DAGNodeInsertedListener::anchor() {}
  92. #define DEBUG_TYPE "selectiondag"
  93. static cl::opt<bool> EnableMemCpyDAGOpt("enable-memcpy-dag-opt",
  94. cl::Hidden, cl::init(true),
  95. cl::desc("Gang up loads and stores generated by inlining of memcpy"));
  96. static cl::opt<int> MaxLdStGlue("ldstmemcpy-glue-max",
  97. cl::desc("Number limit for gluing ld/st of memcpy."),
  98. cl::Hidden, cl::init(0));
  99. static void NewSDValueDbgMsg(SDValue V, StringRef Msg, SelectionDAG *G) {
  100. LLVM_DEBUG(dbgs() << Msg; V.getNode()->dump(G););
  101. }
  102. //===----------------------------------------------------------------------===//
  103. // ConstantFPSDNode Class
  104. //===----------------------------------------------------------------------===//
  105. /// isExactlyValue - We don't rely on operator== working on double values, as
  106. /// it returns true for things that are clearly not equal, like -0.0 and 0.0.
  107. /// As such, this method can be used to do an exact bit-for-bit comparison of
  108. /// two floating point values.
  109. bool ConstantFPSDNode::isExactlyValue(const APFloat& V) const {
  110. return getValueAPF().bitwiseIsEqual(V);
  111. }
  112. bool ConstantFPSDNode::isValueValidForType(EVT VT,
  113. const APFloat& Val) {
  114. assert(VT.isFloatingPoint() && "Can only convert between FP types");
  115. // convert modifies in place, so make a copy.
  116. APFloat Val2 = APFloat(Val);
  117. bool losesInfo;
  118. (void) Val2.convert(SelectionDAG::EVTToAPFloatSemantics(VT),
  119. APFloat::rmNearestTiesToEven,
  120. &losesInfo);
  121. return !losesInfo;
  122. }
  123. //===----------------------------------------------------------------------===//
  124. // ISD Namespace
  125. //===----------------------------------------------------------------------===//
  126. bool ISD::isConstantSplatVector(const SDNode *N, APInt &SplatVal) {
  127. if (N->getOpcode() == ISD::SPLAT_VECTOR) {
  128. unsigned EltSize =
  129. N->getValueType(0).getVectorElementType().getSizeInBits();
  130. if (auto *Op0 = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
  131. SplatVal = Op0->getAPIntValue().trunc(EltSize);
  132. return true;
  133. }
  134. if (auto *Op0 = dyn_cast<ConstantFPSDNode>(N->getOperand(0))) {
  135. SplatVal = Op0->getValueAPF().bitcastToAPInt().trunc(EltSize);
  136. return true;
  137. }
  138. }
  139. auto *BV = dyn_cast<BuildVectorSDNode>(N);
  140. if (!BV)
  141. return false;
  142. APInt SplatUndef;
  143. unsigned SplatBitSize;
  144. bool HasUndefs;
  145. unsigned EltSize = N->getValueType(0).getVectorElementType().getSizeInBits();
  146. return BV->isConstantSplat(SplatVal, SplatUndef, SplatBitSize, HasUndefs,
  147. EltSize) &&
  148. EltSize == SplatBitSize;
  149. }
  150. // FIXME: AllOnes and AllZeros duplicate a lot of code. Could these be
  151. // specializations of the more general isConstantSplatVector()?
  152. bool ISD::isConstantSplatVectorAllOnes(const SDNode *N, bool BuildVectorOnly) {
  153. // Look through a bit convert.
  154. while (N->getOpcode() == ISD::BITCAST)
  155. N = N->getOperand(0).getNode();
  156. if (!BuildVectorOnly && N->getOpcode() == ISD::SPLAT_VECTOR) {
  157. APInt SplatVal;
  158. return isConstantSplatVector(N, SplatVal) && SplatVal.isAllOnes();
  159. }
  160. if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
  161. unsigned i = 0, e = N->getNumOperands();
  162. // Skip over all of the undef values.
  163. while (i != e && N->getOperand(i).isUndef())
  164. ++i;
  165. // Do not accept an all-undef vector.
  166. if (i == e) return false;
  167. // Do not accept build_vectors that aren't all constants or which have non-~0
  168. // elements. We have to be a bit careful here, as the type of the constant
  169. // may not be the same as the type of the vector elements due to type
  170. // legalization (the elements are promoted to a legal type for the target and
  171. // a vector of a type may be legal when the base element type is not).
  172. // We only want to check enough bits to cover the vector elements, because
  173. // we care if the resultant vector is all ones, not whether the individual
  174. // constants are.
  175. SDValue NotZero = N->getOperand(i);
  176. unsigned EltSize = N->getValueType(0).getScalarSizeInBits();
  177. if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(NotZero)) {
  178. if (CN->getAPIntValue().countTrailingOnes() < EltSize)
  179. return false;
  180. } else if (ConstantFPSDNode *CFPN = dyn_cast<ConstantFPSDNode>(NotZero)) {
  181. if (CFPN->getValueAPF().bitcastToAPInt().countTrailingOnes() < EltSize)
  182. return false;
  183. } else
  184. return false;
  185. // Okay, we have at least one ~0 value, check to see if the rest match or are
  186. // undefs. Even with the above element type twiddling, this should be OK, as
  187. // the same type legalization should have applied to all the elements.
  188. for (++i; i != e; ++i)
  189. if (N->getOperand(i) != NotZero && !N->getOperand(i).isUndef())
  190. return false;
  191. return true;
  192. }
  193. bool ISD::isConstantSplatVectorAllZeros(const SDNode *N, bool BuildVectorOnly) {
  194. // Look through a bit convert.
  195. while (N->getOpcode() == ISD::BITCAST)
  196. N = N->getOperand(0).getNode();
  197. if (!BuildVectorOnly && N->getOpcode() == ISD::SPLAT_VECTOR) {
  198. APInt SplatVal;
  199. return isConstantSplatVector(N, SplatVal) && SplatVal.isZero();
  200. }
  201. if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
  202. bool IsAllUndef = true;
  203. for (const SDValue &Op : N->op_values()) {
  204. if (Op.isUndef())
  205. continue;
  206. IsAllUndef = false;
  207. // Do not accept build_vectors that aren't all constants or which have non-0
  208. // elements. We have to be a bit careful here, as the type of the constant
  209. // may not be the same as the type of the vector elements due to type
  210. // legalization (the elements are promoted to a legal type for the target
  211. // and a vector of a type may be legal when the base element type is not).
  212. // We only want to check enough bits to cover the vector elements, because
  213. // we care if the resultant vector is all zeros, not whether the individual
  214. // constants are.
  215. unsigned EltSize = N->getValueType(0).getScalarSizeInBits();
  216. if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Op)) {
  217. if (CN->getAPIntValue().countTrailingZeros() < EltSize)
  218. return false;
  219. } else if (ConstantFPSDNode *CFPN = dyn_cast<ConstantFPSDNode>(Op)) {
  220. if (CFPN->getValueAPF().bitcastToAPInt().countTrailingZeros() < EltSize)
  221. return false;
  222. } else
  223. return false;
  224. }
  225. // Do not accept an all-undef vector.
  226. if (IsAllUndef)
  227. return false;
  228. return true;
  229. }
  230. bool ISD::isBuildVectorAllOnes(const SDNode *N) {
  231. return isConstantSplatVectorAllOnes(N, /*BuildVectorOnly*/ true);
  232. }
  233. bool ISD::isBuildVectorAllZeros(const SDNode *N) {
  234. return isConstantSplatVectorAllZeros(N, /*BuildVectorOnly*/ true);
  235. }
  236. bool ISD::isBuildVectorOfConstantSDNodes(const SDNode *N) {
  237. if (N->getOpcode() != ISD::BUILD_VECTOR)
  238. return false;
  239. for (const SDValue &Op : N->op_values()) {
  240. if (Op.isUndef())
  241. continue;
  242. if (!isa<ConstantSDNode>(Op))
  243. return false;
  244. }
  245. return true;
  246. }
  247. bool ISD::isBuildVectorOfConstantFPSDNodes(const SDNode *N) {
  248. if (N->getOpcode() != ISD::BUILD_VECTOR)
  249. return false;
  250. for (const SDValue &Op : N->op_values()) {
  251. if (Op.isUndef())
  252. continue;
  253. if (!isa<ConstantFPSDNode>(Op))
  254. return false;
  255. }
  256. return true;
  257. }
  258. bool ISD::isVectorShrinkable(const SDNode *N, unsigned NewEltSize,
  259. bool Signed) {
  260. assert(N->getValueType(0).isVector() && "Expected a vector!");
  261. unsigned EltSize = N->getValueType(0).getScalarSizeInBits();
  262. if (EltSize <= NewEltSize)
  263. return false;
  264. if (N->getOpcode() == ISD::ZERO_EXTEND) {
  265. return (N->getOperand(0).getValueType().getScalarSizeInBits() <=
  266. NewEltSize) &&
  267. !Signed;
  268. }
  269. if (N->getOpcode() == ISD::SIGN_EXTEND) {
  270. return (N->getOperand(0).getValueType().getScalarSizeInBits() <=
  271. NewEltSize) &&
  272. Signed;
  273. }
  274. if (N->getOpcode() != ISD::BUILD_VECTOR)
  275. return false;
  276. for (const SDValue &Op : N->op_values()) {
  277. if (Op.isUndef())
  278. continue;
  279. if (!isa<ConstantSDNode>(Op))
  280. return false;
  281. APInt C = cast<ConstantSDNode>(Op)->getAPIntValue().trunc(EltSize);
  282. if (Signed && C.trunc(NewEltSize).sext(EltSize) != C)
  283. return false;
  284. if (!Signed && C.trunc(NewEltSize).zext(EltSize) != C)
  285. return false;
  286. }
  287. return true;
  288. }
  289. bool ISD::allOperandsUndef(const SDNode *N) {
  290. // Return false if the node has no operands.
  291. // This is "logically inconsistent" with the definition of "all" but
  292. // is probably the desired behavior.
  293. if (N->getNumOperands() == 0)
  294. return false;
  295. return all_of(N->op_values(), [](SDValue Op) { return Op.isUndef(); });
  296. }
  297. bool ISD::isFreezeUndef(const SDNode *N) {
  298. return N->getOpcode() == ISD::FREEZE && N->getOperand(0).isUndef();
  299. }
  300. bool ISD::matchUnaryPredicate(SDValue Op,
  301. std::function<bool(ConstantSDNode *)> Match,
  302. bool AllowUndefs) {
  303. // FIXME: Add support for scalar UNDEF cases?
  304. if (auto *Cst = dyn_cast<ConstantSDNode>(Op))
  305. return Match(Cst);
  306. // FIXME: Add support for vector UNDEF cases?
  307. if (ISD::BUILD_VECTOR != Op.getOpcode() &&
  308. ISD::SPLAT_VECTOR != Op.getOpcode())
  309. return false;
  310. EVT SVT = Op.getValueType().getScalarType();
  311. for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
  312. if (AllowUndefs && Op.getOperand(i).isUndef()) {
  313. if (!Match(nullptr))
  314. return false;
  315. continue;
  316. }
  317. auto *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(i));
  318. if (!Cst || Cst->getValueType(0) != SVT || !Match(Cst))
  319. return false;
  320. }
  321. return true;
  322. }
  323. bool ISD::matchBinaryPredicate(
  324. SDValue LHS, SDValue RHS,
  325. std::function<bool(ConstantSDNode *, ConstantSDNode *)> Match,
  326. bool AllowUndefs, bool AllowTypeMismatch) {
  327. if (!AllowTypeMismatch && LHS.getValueType() != RHS.getValueType())
  328. return false;
  329. // TODO: Add support for scalar UNDEF cases?
  330. if (auto *LHSCst = dyn_cast<ConstantSDNode>(LHS))
  331. if (auto *RHSCst = dyn_cast<ConstantSDNode>(RHS))
  332. return Match(LHSCst, RHSCst);
  333. // TODO: Add support for vector UNDEF cases?
  334. if (LHS.getOpcode() != RHS.getOpcode() ||
  335. (LHS.getOpcode() != ISD::BUILD_VECTOR &&
  336. LHS.getOpcode() != ISD::SPLAT_VECTOR))
  337. return false;
  338. EVT SVT = LHS.getValueType().getScalarType();
  339. for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
  340. SDValue LHSOp = LHS.getOperand(i);
  341. SDValue RHSOp = RHS.getOperand(i);
  342. bool LHSUndef = AllowUndefs && LHSOp.isUndef();
  343. bool RHSUndef = AllowUndefs && RHSOp.isUndef();
  344. auto *LHSCst = dyn_cast<ConstantSDNode>(LHSOp);
  345. auto *RHSCst = dyn_cast<ConstantSDNode>(RHSOp);
  346. if ((!LHSCst && !LHSUndef) || (!RHSCst && !RHSUndef))
  347. return false;
  348. if (!AllowTypeMismatch && (LHSOp.getValueType() != SVT ||
  349. LHSOp.getValueType() != RHSOp.getValueType()))
  350. return false;
  351. if (!Match(LHSCst, RHSCst))
  352. return false;
  353. }
  354. return true;
  355. }
  356. ISD::NodeType ISD::getVecReduceBaseOpcode(unsigned VecReduceOpcode) {
  357. switch (VecReduceOpcode) {
  358. default:
  359. llvm_unreachable("Expected VECREDUCE opcode");
  360. case ISD::VECREDUCE_FADD:
  361. case ISD::VECREDUCE_SEQ_FADD:
  362. case ISD::VP_REDUCE_FADD:
  363. case ISD::VP_REDUCE_SEQ_FADD:
  364. return ISD::FADD;
  365. case ISD::VECREDUCE_FMUL:
  366. case ISD::VECREDUCE_SEQ_FMUL:
  367. case ISD::VP_REDUCE_FMUL:
  368. case ISD::VP_REDUCE_SEQ_FMUL:
  369. return ISD::FMUL;
  370. case ISD::VECREDUCE_ADD:
  371. case ISD::VP_REDUCE_ADD:
  372. return ISD::ADD;
  373. case ISD::VECREDUCE_MUL:
  374. case ISD::VP_REDUCE_MUL:
  375. return ISD::MUL;
  376. case ISD::VECREDUCE_AND:
  377. case ISD::VP_REDUCE_AND:
  378. return ISD::AND;
  379. case ISD::VECREDUCE_OR:
  380. case ISD::VP_REDUCE_OR:
  381. return ISD::OR;
  382. case ISD::VECREDUCE_XOR:
  383. case ISD::VP_REDUCE_XOR:
  384. return ISD::XOR;
  385. case ISD::VECREDUCE_SMAX:
  386. case ISD::VP_REDUCE_SMAX:
  387. return ISD::SMAX;
  388. case ISD::VECREDUCE_SMIN:
  389. case ISD::VP_REDUCE_SMIN:
  390. return ISD::SMIN;
  391. case ISD::VECREDUCE_UMAX:
  392. case ISD::VP_REDUCE_UMAX:
  393. return ISD::UMAX;
  394. case ISD::VECREDUCE_UMIN:
  395. case ISD::VP_REDUCE_UMIN:
  396. return ISD::UMIN;
  397. case ISD::VECREDUCE_FMAX:
  398. case ISD::VP_REDUCE_FMAX:
  399. return ISD::FMAXNUM;
  400. case ISD::VECREDUCE_FMIN:
  401. case ISD::VP_REDUCE_FMIN:
  402. return ISD::FMINNUM;
  403. }
  404. }
  405. bool ISD::isVPOpcode(unsigned Opcode) {
  406. switch (Opcode) {
  407. default:
  408. return false;
  409. #define BEGIN_REGISTER_VP_SDNODE(VPSD, ...) \
  410. case ISD::VPSD: \
  411. return true;
  412. #include "llvm/IR/VPIntrinsics.def"
  413. }
  414. }
  415. bool ISD::isVPBinaryOp(unsigned Opcode) {
  416. switch (Opcode) {
  417. default:
  418. break;
  419. #define BEGIN_REGISTER_VP_SDNODE(VPSD, ...) case ISD::VPSD:
  420. #define VP_PROPERTY_BINARYOP return true;
  421. #define END_REGISTER_VP_SDNODE(VPSD) break;
  422. #include "llvm/IR/VPIntrinsics.def"
  423. }
  424. return false;
  425. }
  426. bool ISD::isVPReduction(unsigned Opcode) {
  427. switch (Opcode) {
  428. default:
  429. break;
  430. #define BEGIN_REGISTER_VP_SDNODE(VPSD, ...) case ISD::VPSD:
  431. #define VP_PROPERTY_REDUCTION(STARTPOS, ...) return true;
  432. #define END_REGISTER_VP_SDNODE(VPSD) break;
  433. #include "llvm/IR/VPIntrinsics.def"
  434. }
  435. return false;
  436. }
  437. /// The operand position of the vector mask.
  438. std::optional<unsigned> ISD::getVPMaskIdx(unsigned Opcode) {
  439. switch (Opcode) {
  440. default:
  441. return std::nullopt;
  442. #define BEGIN_REGISTER_VP_SDNODE(VPSD, LEGALPOS, TDNAME, MASKPOS, ...) \
  443. case ISD::VPSD: \
  444. return MASKPOS;
  445. #include "llvm/IR/VPIntrinsics.def"
  446. }
  447. }
  448. /// The operand position of the explicit vector length parameter.
  449. std::optional<unsigned> ISD::getVPExplicitVectorLengthIdx(unsigned Opcode) {
  450. switch (Opcode) {
  451. default:
  452. return std::nullopt;
  453. #define BEGIN_REGISTER_VP_SDNODE(VPSD, LEGALPOS, TDNAME, MASKPOS, EVLPOS) \
  454. case ISD::VPSD: \
  455. return EVLPOS;
  456. #include "llvm/IR/VPIntrinsics.def"
  457. }
  458. }
  459. ISD::NodeType ISD::getExtForLoadExtType(bool IsFP, ISD::LoadExtType ExtType) {
  460. switch (ExtType) {
  461. case ISD::EXTLOAD:
  462. return IsFP ? ISD::FP_EXTEND : ISD::ANY_EXTEND;
  463. case ISD::SEXTLOAD:
  464. return ISD::SIGN_EXTEND;
  465. case ISD::ZEXTLOAD:
  466. return ISD::ZERO_EXTEND;
  467. default:
  468. break;
  469. }
  470. llvm_unreachable("Invalid LoadExtType");
  471. }
  472. ISD::CondCode ISD::getSetCCSwappedOperands(ISD::CondCode Operation) {
  473. // To perform this operation, we just need to swap the L and G bits of the
  474. // operation.
  475. unsigned OldL = (Operation >> 2) & 1;
  476. unsigned OldG = (Operation >> 1) & 1;
  477. return ISD::CondCode((Operation & ~6) | // Keep the N, U, E bits
  478. (OldL << 1) | // New G bit
  479. (OldG << 2)); // New L bit.
  480. }
  481. static ISD::CondCode getSetCCInverseImpl(ISD::CondCode Op, bool isIntegerLike) {
  482. unsigned Operation = Op;
  483. if (isIntegerLike)
  484. Operation ^= 7; // Flip L, G, E bits, but not U.
  485. else
  486. Operation ^= 15; // Flip all of the condition bits.
  487. if (Operation > ISD::SETTRUE2)
  488. Operation &= ~8; // Don't let N and U bits get set.
  489. return ISD::CondCode(Operation);
  490. }
  491. ISD::CondCode ISD::getSetCCInverse(ISD::CondCode Op, EVT Type) {
  492. return getSetCCInverseImpl(Op, Type.isInteger());
  493. }
  494. ISD::CondCode ISD::GlobalISel::getSetCCInverse(ISD::CondCode Op,
  495. bool isIntegerLike) {
  496. return getSetCCInverseImpl(Op, isIntegerLike);
  497. }
  498. /// For an integer comparison, return 1 if the comparison is a signed operation
  499. /// and 2 if the result is an unsigned comparison. Return zero if the operation
  500. /// does not depend on the sign of the input (setne and seteq).
  501. static int isSignedOp(ISD::CondCode Opcode) {
  502. switch (Opcode) {
  503. default: llvm_unreachable("Illegal integer setcc operation!");
  504. case ISD::SETEQ:
  505. case ISD::SETNE: return 0;
  506. case ISD::SETLT:
  507. case ISD::SETLE:
  508. case ISD::SETGT:
  509. case ISD::SETGE: return 1;
  510. case ISD::SETULT:
  511. case ISD::SETULE:
  512. case ISD::SETUGT:
  513. case ISD::SETUGE: return 2;
  514. }
  515. }
  516. ISD::CondCode ISD::getSetCCOrOperation(ISD::CondCode Op1, ISD::CondCode Op2,
  517. EVT Type) {
  518. bool IsInteger = Type.isInteger();
  519. if (IsInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
  520. // Cannot fold a signed integer setcc with an unsigned integer setcc.
  521. return ISD::SETCC_INVALID;
  522. unsigned Op = Op1 | Op2; // Combine all of the condition bits.
  523. // If the N and U bits get set, then the resultant comparison DOES suddenly
  524. // care about orderedness, and it is true when ordered.
  525. if (Op > ISD::SETTRUE2)
  526. Op &= ~16; // Clear the U bit if the N bit is set.
  527. // Canonicalize illegal integer setcc's.
  528. if (IsInteger && Op == ISD::SETUNE) // e.g. SETUGT | SETULT
  529. Op = ISD::SETNE;
  530. return ISD::CondCode(Op);
  531. }
  532. ISD::CondCode ISD::getSetCCAndOperation(ISD::CondCode Op1, ISD::CondCode Op2,
  533. EVT Type) {
  534. bool IsInteger = Type.isInteger();
  535. if (IsInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
  536. // Cannot fold a signed setcc with an unsigned setcc.
  537. return ISD::SETCC_INVALID;
  538. // Combine all of the condition bits.
  539. ISD::CondCode Result = ISD::CondCode(Op1 & Op2);
  540. // Canonicalize illegal integer setcc's.
  541. if (IsInteger) {
  542. switch (Result) {
  543. default: break;
  544. case ISD::SETUO : Result = ISD::SETFALSE; break; // SETUGT & SETULT
  545. case ISD::SETOEQ: // SETEQ & SETU[LG]E
  546. case ISD::SETUEQ: Result = ISD::SETEQ ; break; // SETUGE & SETULE
  547. case ISD::SETOLT: Result = ISD::SETULT ; break; // SETULT & SETNE
  548. case ISD::SETOGT: Result = ISD::SETUGT ; break; // SETUGT & SETNE
  549. }
  550. }
  551. return Result;
  552. }
  553. //===----------------------------------------------------------------------===//
  554. // SDNode Profile Support
  555. //===----------------------------------------------------------------------===//
  556. /// AddNodeIDOpcode - Add the node opcode to the NodeID data.
  557. static void AddNodeIDOpcode(FoldingSetNodeID &ID, unsigned OpC) {
  558. ID.AddInteger(OpC);
  559. }
  560. /// AddNodeIDValueTypes - Value type lists are intern'd so we can represent them
  561. /// solely with their pointer.
  562. static void AddNodeIDValueTypes(FoldingSetNodeID &ID, SDVTList VTList) {
  563. ID.AddPointer(VTList.VTs);
  564. }
  565. /// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
  566. static void AddNodeIDOperands(FoldingSetNodeID &ID,
  567. ArrayRef<SDValue> Ops) {
  568. for (const auto &Op : Ops) {
  569. ID.AddPointer(Op.getNode());
  570. ID.AddInteger(Op.getResNo());
  571. }
  572. }
  573. /// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
  574. static void AddNodeIDOperands(FoldingSetNodeID &ID,
  575. ArrayRef<SDUse> Ops) {
  576. for (const auto &Op : Ops) {
  577. ID.AddPointer(Op.getNode());
  578. ID.AddInteger(Op.getResNo());
  579. }
  580. }
  581. static void AddNodeIDNode(FoldingSetNodeID &ID, unsigned OpC,
  582. SDVTList VTList, ArrayRef<SDValue> OpList) {
  583. AddNodeIDOpcode(ID, OpC);
  584. AddNodeIDValueTypes(ID, VTList);
  585. AddNodeIDOperands(ID, OpList);
  586. }
  587. /// If this is an SDNode with special info, add this info to the NodeID data.
  588. static void AddNodeIDCustom(FoldingSetNodeID &ID, const SDNode *N) {
  589. switch (N->getOpcode()) {
  590. case ISD::TargetExternalSymbol:
  591. case ISD::ExternalSymbol:
  592. case ISD::MCSymbol:
  593. llvm_unreachable("Should only be used on nodes with operands");
  594. default: break; // Normal nodes don't need extra info.
  595. case ISD::TargetConstant:
  596. case ISD::Constant: {
  597. const ConstantSDNode *C = cast<ConstantSDNode>(N);
  598. ID.AddPointer(C->getConstantIntValue());
  599. ID.AddBoolean(C->isOpaque());
  600. break;
  601. }
  602. case ISD::TargetConstantFP:
  603. case ISD::ConstantFP:
  604. ID.AddPointer(cast<ConstantFPSDNode>(N)->getConstantFPValue());
  605. break;
  606. case ISD::TargetGlobalAddress:
  607. case ISD::GlobalAddress:
  608. case ISD::TargetGlobalTLSAddress:
  609. case ISD::GlobalTLSAddress: {
  610. const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(N);
  611. ID.AddPointer(GA->getGlobal());
  612. ID.AddInteger(GA->getOffset());
  613. ID.AddInteger(GA->getTargetFlags());
  614. break;
  615. }
  616. case ISD::BasicBlock:
  617. ID.AddPointer(cast<BasicBlockSDNode>(N)->getBasicBlock());
  618. break;
  619. case ISD::Register:
  620. ID.AddInteger(cast<RegisterSDNode>(N)->getReg());
  621. break;
  622. case ISD::RegisterMask:
  623. ID.AddPointer(cast<RegisterMaskSDNode>(N)->getRegMask());
  624. break;
  625. case ISD::SRCVALUE:
  626. ID.AddPointer(cast<SrcValueSDNode>(N)->getValue());
  627. break;
  628. case ISD::FrameIndex:
  629. case ISD::TargetFrameIndex:
  630. ID.AddInteger(cast<FrameIndexSDNode>(N)->getIndex());
  631. break;
  632. case ISD::LIFETIME_START:
  633. case ISD::LIFETIME_END:
  634. if (cast<LifetimeSDNode>(N)->hasOffset()) {
  635. ID.AddInteger(cast<LifetimeSDNode>(N)->getSize());
  636. ID.AddInteger(cast<LifetimeSDNode>(N)->getOffset());
  637. }
  638. break;
  639. case ISD::PSEUDO_PROBE:
  640. ID.AddInteger(cast<PseudoProbeSDNode>(N)->getGuid());
  641. ID.AddInteger(cast<PseudoProbeSDNode>(N)->getIndex());
  642. ID.AddInteger(cast<PseudoProbeSDNode>(N)->getAttributes());
  643. break;
  644. case ISD::JumpTable:
  645. case ISD::TargetJumpTable:
  646. ID.AddInteger(cast<JumpTableSDNode>(N)->getIndex());
  647. ID.AddInteger(cast<JumpTableSDNode>(N)->getTargetFlags());
  648. break;
  649. case ISD::ConstantPool:
  650. case ISD::TargetConstantPool: {
  651. const ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(N);
  652. ID.AddInteger(CP->getAlign().value());
  653. ID.AddInteger(CP->getOffset());
  654. if (CP->isMachineConstantPoolEntry())
  655. CP->getMachineCPVal()->addSelectionDAGCSEId(ID);
  656. else
  657. ID.AddPointer(CP->getConstVal());
  658. ID.AddInteger(CP->getTargetFlags());
  659. break;
  660. }
  661. case ISD::TargetIndex: {
  662. const TargetIndexSDNode *TI = cast<TargetIndexSDNode>(N);
  663. ID.AddInteger(TI->getIndex());
  664. ID.AddInteger(TI->getOffset());
  665. ID.AddInteger(TI->getTargetFlags());
  666. break;
  667. }
  668. case ISD::LOAD: {
  669. const LoadSDNode *LD = cast<LoadSDNode>(N);
  670. ID.AddInteger(LD->getMemoryVT().getRawBits());
  671. ID.AddInteger(LD->getRawSubclassData());
  672. ID.AddInteger(LD->getPointerInfo().getAddrSpace());
  673. ID.AddInteger(LD->getMemOperand()->getFlags());
  674. break;
  675. }
  676. case ISD::STORE: {
  677. const StoreSDNode *ST = cast<StoreSDNode>(N);
  678. ID.AddInteger(ST->getMemoryVT().getRawBits());
  679. ID.AddInteger(ST->getRawSubclassData());
  680. ID.AddInteger(ST->getPointerInfo().getAddrSpace());
  681. ID.AddInteger(ST->getMemOperand()->getFlags());
  682. break;
  683. }
  684. case ISD::VP_LOAD: {
  685. const VPLoadSDNode *ELD = cast<VPLoadSDNode>(N);
  686. ID.AddInteger(ELD->getMemoryVT().getRawBits());
  687. ID.AddInteger(ELD->getRawSubclassData());
  688. ID.AddInteger(ELD->getPointerInfo().getAddrSpace());
  689. ID.AddInteger(ELD->getMemOperand()->getFlags());
  690. break;
  691. }
  692. case ISD::VP_STORE: {
  693. const VPStoreSDNode *EST = cast<VPStoreSDNode>(N);
  694. ID.AddInteger(EST->getMemoryVT().getRawBits());
  695. ID.AddInteger(EST->getRawSubclassData());
  696. ID.AddInteger(EST->getPointerInfo().getAddrSpace());
  697. ID.AddInteger(EST->getMemOperand()->getFlags());
  698. break;
  699. }
  700. case ISD::EXPERIMENTAL_VP_STRIDED_LOAD: {
  701. const VPStridedLoadSDNode *SLD = cast<VPStridedLoadSDNode>(N);
  702. ID.AddInteger(SLD->getMemoryVT().getRawBits());
  703. ID.AddInteger(SLD->getRawSubclassData());
  704. ID.AddInteger(SLD->getPointerInfo().getAddrSpace());
  705. break;
  706. }
  707. case ISD::EXPERIMENTAL_VP_STRIDED_STORE: {
  708. const VPStridedStoreSDNode *SST = cast<VPStridedStoreSDNode>(N);
  709. ID.AddInteger(SST->getMemoryVT().getRawBits());
  710. ID.AddInteger(SST->getRawSubclassData());
  711. ID.AddInteger(SST->getPointerInfo().getAddrSpace());
  712. break;
  713. }
  714. case ISD::VP_GATHER: {
  715. const VPGatherSDNode *EG = cast<VPGatherSDNode>(N);
  716. ID.AddInteger(EG->getMemoryVT().getRawBits());
  717. ID.AddInteger(EG->getRawSubclassData());
  718. ID.AddInteger(EG->getPointerInfo().getAddrSpace());
  719. ID.AddInteger(EG->getMemOperand()->getFlags());
  720. break;
  721. }
  722. case ISD::VP_SCATTER: {
  723. const VPScatterSDNode *ES = cast<VPScatterSDNode>(N);
  724. ID.AddInteger(ES->getMemoryVT().getRawBits());
  725. ID.AddInteger(ES->getRawSubclassData());
  726. ID.AddInteger(ES->getPointerInfo().getAddrSpace());
  727. ID.AddInteger(ES->getMemOperand()->getFlags());
  728. break;
  729. }
  730. case ISD::MLOAD: {
  731. const MaskedLoadSDNode *MLD = cast<MaskedLoadSDNode>(N);
  732. ID.AddInteger(MLD->getMemoryVT().getRawBits());
  733. ID.AddInteger(MLD->getRawSubclassData());
  734. ID.AddInteger(MLD->getPointerInfo().getAddrSpace());
  735. ID.AddInteger(MLD->getMemOperand()->getFlags());
  736. break;
  737. }
  738. case ISD::MSTORE: {
  739. const MaskedStoreSDNode *MST = cast<MaskedStoreSDNode>(N);
  740. ID.AddInteger(MST->getMemoryVT().getRawBits());
  741. ID.AddInteger(MST->getRawSubclassData());
  742. ID.AddInteger(MST->getPointerInfo().getAddrSpace());
  743. ID.AddInteger(MST->getMemOperand()->getFlags());
  744. break;
  745. }
  746. case ISD::MGATHER: {
  747. const MaskedGatherSDNode *MG = cast<MaskedGatherSDNode>(N);
  748. ID.AddInteger(MG->getMemoryVT().getRawBits());
  749. ID.AddInteger(MG->getRawSubclassData());
  750. ID.AddInteger(MG->getPointerInfo().getAddrSpace());
  751. ID.AddInteger(MG->getMemOperand()->getFlags());
  752. break;
  753. }
  754. case ISD::MSCATTER: {
  755. const MaskedScatterSDNode *MS = cast<MaskedScatterSDNode>(N);
  756. ID.AddInteger(MS->getMemoryVT().getRawBits());
  757. ID.AddInteger(MS->getRawSubclassData());
  758. ID.AddInteger(MS->getPointerInfo().getAddrSpace());
  759. ID.AddInteger(MS->getMemOperand()->getFlags());
  760. break;
  761. }
  762. case ISD::ATOMIC_CMP_SWAP:
  763. case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
  764. case ISD::ATOMIC_SWAP:
  765. case ISD::ATOMIC_LOAD_ADD:
  766. case ISD::ATOMIC_LOAD_SUB:
  767. case ISD::ATOMIC_LOAD_AND:
  768. case ISD::ATOMIC_LOAD_CLR:
  769. case ISD::ATOMIC_LOAD_OR:
  770. case ISD::ATOMIC_LOAD_XOR:
  771. case ISD::ATOMIC_LOAD_NAND:
  772. case ISD::ATOMIC_LOAD_MIN:
  773. case ISD::ATOMIC_LOAD_MAX:
  774. case ISD::ATOMIC_LOAD_UMIN:
  775. case ISD::ATOMIC_LOAD_UMAX:
  776. case ISD::ATOMIC_LOAD:
  777. case ISD::ATOMIC_STORE: {
  778. const AtomicSDNode *AT = cast<AtomicSDNode>(N);
  779. ID.AddInteger(AT->getMemoryVT().getRawBits());
  780. ID.AddInteger(AT->getRawSubclassData());
  781. ID.AddInteger(AT->getPointerInfo().getAddrSpace());
  782. ID.AddInteger(AT->getMemOperand()->getFlags());
  783. break;
  784. }
  785. case ISD::PREFETCH: {
  786. const MemSDNode *PF = cast<MemSDNode>(N);
  787. ID.AddInteger(PF->getPointerInfo().getAddrSpace());
  788. ID.AddInteger(PF->getMemOperand()->getFlags());
  789. break;
  790. }
  791. case ISD::VECTOR_SHUFFLE: {
  792. const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
  793. for (unsigned i = 0, e = N->getValueType(0).getVectorNumElements();
  794. i != e; ++i)
  795. ID.AddInteger(SVN->getMaskElt(i));
  796. break;
  797. }
  798. case ISD::TargetBlockAddress:
  799. case ISD::BlockAddress: {
  800. const BlockAddressSDNode *BA = cast<BlockAddressSDNode>(N);
  801. ID.AddPointer(BA->getBlockAddress());
  802. ID.AddInteger(BA->getOffset());
  803. ID.AddInteger(BA->getTargetFlags());
  804. break;
  805. }
  806. case ISD::AssertAlign:
  807. ID.AddInteger(cast<AssertAlignSDNode>(N)->getAlign().value());
  808. break;
  809. } // end switch (N->getOpcode())
  810. // Target specific memory nodes could also have address spaces and flags
  811. // to check.
  812. if (N->isTargetMemoryOpcode()) {
  813. const MemSDNode *MN = cast<MemSDNode>(N);
  814. ID.AddInteger(MN->getPointerInfo().getAddrSpace());
  815. ID.AddInteger(MN->getMemOperand()->getFlags());
  816. }
  817. }
  818. /// AddNodeIDNode - Generic routine for adding a nodes info to the NodeID
  819. /// data.
  820. static void AddNodeIDNode(FoldingSetNodeID &ID, const SDNode *N) {
  821. AddNodeIDOpcode(ID, N->getOpcode());
  822. // Add the return value info.
  823. AddNodeIDValueTypes(ID, N->getVTList());
  824. // Add the operand info.
  825. AddNodeIDOperands(ID, N->ops());
  826. // Handle SDNode leafs with special info.
  827. AddNodeIDCustom(ID, N);
  828. }
  829. //===----------------------------------------------------------------------===//
  830. // SelectionDAG Class
  831. //===----------------------------------------------------------------------===//
  832. /// doNotCSE - Return true if CSE should not be performed for this node.
  833. static bool doNotCSE(SDNode *N) {
  834. if (N->getValueType(0) == MVT::Glue)
  835. return true; // Never CSE anything that produces a flag.
  836. switch (N->getOpcode()) {
  837. default: break;
  838. case ISD::HANDLENODE:
  839. case ISD::EH_LABEL:
  840. return true; // Never CSE these nodes.
  841. }
  842. // Check that remaining values produced are not flags.
  843. for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
  844. if (N->getValueType(i) == MVT::Glue)
  845. return true; // Never CSE anything that produces a flag.
  846. return false;
  847. }
  848. /// RemoveDeadNodes - This method deletes all unreachable nodes in the
  849. /// SelectionDAG.
  850. void SelectionDAG::RemoveDeadNodes() {
  851. // Create a dummy node (which is not added to allnodes), that adds a reference
  852. // to the root node, preventing it from being deleted.
  853. HandleSDNode Dummy(getRoot());
  854. SmallVector<SDNode*, 128> DeadNodes;
  855. // Add all obviously-dead nodes to the DeadNodes worklist.
  856. for (SDNode &Node : allnodes())
  857. if (Node.use_empty())
  858. DeadNodes.push_back(&Node);
  859. RemoveDeadNodes(DeadNodes);
  860. // If the root changed (e.g. it was a dead load, update the root).
  861. setRoot(Dummy.getValue());
  862. }
  863. /// RemoveDeadNodes - This method deletes the unreachable nodes in the
  864. /// given list, and any nodes that become unreachable as a result.
  865. void SelectionDAG::RemoveDeadNodes(SmallVectorImpl<SDNode *> &DeadNodes) {
  866. // Process the worklist, deleting the nodes and adding their uses to the
  867. // worklist.
  868. while (!DeadNodes.empty()) {
  869. SDNode *N = DeadNodes.pop_back_val();
  870. // Skip to next node if we've already managed to delete the node. This could
  871. // happen if replacing a node causes a node previously added to the node to
  872. // be deleted.
  873. if (N->getOpcode() == ISD::DELETED_NODE)
  874. continue;
  875. for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
  876. DUL->NodeDeleted(N, nullptr);
  877. // Take the node out of the appropriate CSE map.
  878. RemoveNodeFromCSEMaps(N);
  879. // Next, brutally remove the operand list. This is safe to do, as there are
  880. // no cycles in the graph.
  881. for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
  882. SDUse &Use = *I++;
  883. SDNode *Operand = Use.getNode();
  884. Use.set(SDValue());
  885. // Now that we removed this operand, see if there are no uses of it left.
  886. if (Operand->use_empty())
  887. DeadNodes.push_back(Operand);
  888. }
  889. DeallocateNode(N);
  890. }
  891. }
  892. void SelectionDAG::RemoveDeadNode(SDNode *N){
  893. SmallVector<SDNode*, 16> DeadNodes(1, N);
  894. // Create a dummy node that adds a reference to the root node, preventing
  895. // it from being deleted. (This matters if the root is an operand of the
  896. // dead node.)
  897. HandleSDNode Dummy(getRoot());
  898. RemoveDeadNodes(DeadNodes);
  899. }
  900. void SelectionDAG::DeleteNode(SDNode *N) {
  901. // First take this out of the appropriate CSE map.
  902. RemoveNodeFromCSEMaps(N);
  903. // Finally, remove uses due to operands of this node, remove from the
  904. // AllNodes list, and delete the node.
  905. DeleteNodeNotInCSEMaps(N);
  906. }
  907. void SelectionDAG::DeleteNodeNotInCSEMaps(SDNode *N) {
  908. assert(N->getIterator() != AllNodes.begin() &&
  909. "Cannot delete the entry node!");
  910. assert(N->use_empty() && "Cannot delete a node that is not dead!");
  911. // Drop all of the operands and decrement used node's use counts.
  912. N->DropOperands();
  913. DeallocateNode(N);
  914. }
  915. void SDDbgInfo::add(SDDbgValue *V, bool isParameter) {
  916. assert(!(V->isVariadic() && isParameter));
  917. if (isParameter)
  918. ByvalParmDbgValues.push_back(V);
  919. else
  920. DbgValues.push_back(V);
  921. for (const SDNode *Node : V->getSDNodes())
  922. if (Node)
  923. DbgValMap[Node].push_back(V);
  924. }
  925. void SDDbgInfo::erase(const SDNode *Node) {
  926. DbgValMapType::iterator I = DbgValMap.find(Node);
  927. if (I == DbgValMap.end())
  928. return;
  929. for (auto &Val: I->second)
  930. Val->setIsInvalidated();
  931. DbgValMap.erase(I);
  932. }
  933. void SelectionDAG::DeallocateNode(SDNode *N) {
  934. // If we have operands, deallocate them.
  935. removeOperands(N);
  936. NodeAllocator.Deallocate(AllNodes.remove(N));
  937. // Set the opcode to DELETED_NODE to help catch bugs when node
  938. // memory is reallocated.
  939. // FIXME: There are places in SDag that have grown a dependency on the opcode
  940. // value in the released node.
  941. __asan_unpoison_memory_region(&N->NodeType, sizeof(N->NodeType));
  942. N->NodeType = ISD::DELETED_NODE;
  943. // If any of the SDDbgValue nodes refer to this SDNode, invalidate
  944. // them and forget about that node.
  945. DbgInfo->erase(N);
  946. // Invalidate extra info.
  947. SDEI.erase(N);
  948. }
  949. #ifndef NDEBUG
  950. /// VerifySDNode - Check the given SDNode. Aborts if it is invalid.
  951. static void VerifySDNode(SDNode *N) {
  952. switch (N->getOpcode()) {
  953. default:
  954. break;
  955. case ISD::BUILD_PAIR: {
  956. EVT VT = N->getValueType(0);
  957. assert(N->getNumValues() == 1 && "Too many results!");
  958. assert(!VT.isVector() && (VT.isInteger() || VT.isFloatingPoint()) &&
  959. "Wrong return type!");
  960. assert(N->getNumOperands() == 2 && "Wrong number of operands!");
  961. assert(N->getOperand(0).getValueType() == N->getOperand(1).getValueType() &&
  962. "Mismatched operand types!");
  963. assert(N->getOperand(0).getValueType().isInteger() == VT.isInteger() &&
  964. "Wrong operand type!");
  965. assert(VT.getSizeInBits() == 2 * N->getOperand(0).getValueSizeInBits() &&
  966. "Wrong return type size");
  967. break;
  968. }
  969. case ISD::BUILD_VECTOR: {
  970. assert(N->getNumValues() == 1 && "Too many results!");
  971. assert(N->getValueType(0).isVector() && "Wrong return type!");
  972. assert(N->getNumOperands() == N->getValueType(0).getVectorNumElements() &&
  973. "Wrong number of operands!");
  974. EVT EltVT = N->getValueType(0).getVectorElementType();
  975. for (const SDUse &Op : N->ops()) {
  976. assert((Op.getValueType() == EltVT ||
  977. (EltVT.isInteger() && Op.getValueType().isInteger() &&
  978. EltVT.bitsLE(Op.getValueType()))) &&
  979. "Wrong operand type!");
  980. assert(Op.getValueType() == N->getOperand(0).getValueType() &&
  981. "Operands must all have the same type");
  982. }
  983. break;
  984. }
  985. }
  986. }
  987. #endif // NDEBUG
  988. /// Insert a newly allocated node into the DAG.
  989. ///
  990. /// Handles insertion into the all nodes list and CSE map, as well as
  991. /// verification and other common operations when a new node is allocated.
  992. void SelectionDAG::InsertNode(SDNode *N) {
  993. AllNodes.push_back(N);
  994. #ifndef NDEBUG
  995. N->PersistentId = NextPersistentId++;
  996. VerifySDNode(N);
  997. #endif
  998. for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
  999. DUL->NodeInserted(N);
  1000. }
  1001. /// RemoveNodeFromCSEMaps - Take the specified node out of the CSE map that
  1002. /// correspond to it. This is useful when we're about to delete or repurpose
  1003. /// the node. We don't want future request for structurally identical nodes
  1004. /// to return N anymore.
  1005. bool SelectionDAG::RemoveNodeFromCSEMaps(SDNode *N) {
  1006. bool Erased = false;
  1007. switch (N->getOpcode()) {
  1008. case ISD::HANDLENODE: return false; // noop.
  1009. case ISD::CONDCODE:
  1010. assert(CondCodeNodes[cast<CondCodeSDNode>(N)->get()] &&
  1011. "Cond code doesn't exist!");
  1012. Erased = CondCodeNodes[cast<CondCodeSDNode>(N)->get()] != nullptr;
  1013. CondCodeNodes[cast<CondCodeSDNode>(N)->get()] = nullptr;
  1014. break;
  1015. case ISD::ExternalSymbol:
  1016. Erased = ExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol());
  1017. break;
  1018. case ISD::TargetExternalSymbol: {
  1019. ExternalSymbolSDNode *ESN = cast<ExternalSymbolSDNode>(N);
  1020. Erased = TargetExternalSymbols.erase(std::pair<std::string, unsigned>(
  1021. ESN->getSymbol(), ESN->getTargetFlags()));
  1022. break;
  1023. }
  1024. case ISD::MCSymbol: {
  1025. auto *MCSN = cast<MCSymbolSDNode>(N);
  1026. Erased = MCSymbols.erase(MCSN->getMCSymbol());
  1027. break;
  1028. }
  1029. case ISD::VALUETYPE: {
  1030. EVT VT = cast<VTSDNode>(N)->getVT();
  1031. if (VT.isExtended()) {
  1032. Erased = ExtendedValueTypeNodes.erase(VT);
  1033. } else {
  1034. Erased = ValueTypeNodes[VT.getSimpleVT().SimpleTy] != nullptr;
  1035. ValueTypeNodes[VT.getSimpleVT().SimpleTy] = nullptr;
  1036. }
  1037. break;
  1038. }
  1039. default:
  1040. // Remove it from the CSE Map.
  1041. assert(N->getOpcode() != ISD::DELETED_NODE && "DELETED_NODE in CSEMap!");
  1042. assert(N->getOpcode() != ISD::EntryToken && "EntryToken in CSEMap!");
  1043. Erased = CSEMap.RemoveNode(N);
  1044. break;
  1045. }
  1046. #ifndef NDEBUG
  1047. // Verify that the node was actually in one of the CSE maps, unless it has a
  1048. // flag result (which cannot be CSE'd) or is one of the special cases that are
  1049. // not subject to CSE.
  1050. if (!Erased && N->getValueType(N->getNumValues()-1) != MVT::Glue &&
  1051. !N->isMachineOpcode() && !doNotCSE(N)) {
  1052. N->dump(this);
  1053. dbgs() << "\n";
  1054. llvm_unreachable("Node is not in map!");
  1055. }
  1056. #endif
  1057. return Erased;
  1058. }
  1059. /// AddModifiedNodeToCSEMaps - The specified node has been removed from the CSE
  1060. /// maps and modified in place. Add it back to the CSE maps, unless an identical
  1061. /// node already exists, in which case transfer all its users to the existing
  1062. /// node. This transfer can potentially trigger recursive merging.
  1063. void
  1064. SelectionDAG::AddModifiedNodeToCSEMaps(SDNode *N) {
  1065. // For node types that aren't CSE'd, just act as if no identical node
  1066. // already exists.
  1067. if (!doNotCSE(N)) {
  1068. SDNode *Existing = CSEMap.GetOrInsertNode(N);
  1069. if (Existing != N) {
  1070. // If there was already an existing matching node, use ReplaceAllUsesWith
  1071. // to replace the dead one with the existing one. This can cause
  1072. // recursive merging of other unrelated nodes down the line.
  1073. ReplaceAllUsesWith(N, Existing);
  1074. // N is now dead. Inform the listeners and delete it.
  1075. for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
  1076. DUL->NodeDeleted(N, Existing);
  1077. DeleteNodeNotInCSEMaps(N);
  1078. return;
  1079. }
  1080. }
  1081. // If the node doesn't already exist, we updated it. Inform listeners.
  1082. for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
  1083. DUL->NodeUpdated(N);
  1084. }
  1085. /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
  1086. /// were replaced with those specified. If this node is never memoized,
  1087. /// return null, otherwise return a pointer to the slot it would take. If a
  1088. /// node already exists with these operands, the slot will be non-null.
  1089. SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, SDValue Op,
  1090. void *&InsertPos) {
  1091. if (doNotCSE(N))
  1092. return nullptr;
  1093. SDValue Ops[] = { Op };
  1094. FoldingSetNodeID ID;
  1095. AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
  1096. AddNodeIDCustom(ID, N);
  1097. SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
  1098. if (Node)
  1099. Node->intersectFlagsWith(N->getFlags());
  1100. return Node;
  1101. }
  1102. /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
  1103. /// were replaced with those specified. If this node is never memoized,
  1104. /// return null, otherwise return a pointer to the slot it would take. If a
  1105. /// node already exists with these operands, the slot will be non-null.
  1106. SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N,
  1107. SDValue Op1, SDValue Op2,
  1108. void *&InsertPos) {
  1109. if (doNotCSE(N))
  1110. return nullptr;
  1111. SDValue Ops[] = { Op1, Op2 };
  1112. FoldingSetNodeID ID;
  1113. AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
  1114. AddNodeIDCustom(ID, N);
  1115. SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
  1116. if (Node)
  1117. Node->intersectFlagsWith(N->getFlags());
  1118. return Node;
  1119. }
  1120. /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
  1121. /// were replaced with those specified. If this node is never memoized,
  1122. /// return null, otherwise return a pointer to the slot it would take. If a
  1123. /// node already exists with these operands, the slot will be non-null.
  1124. SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, ArrayRef<SDValue> Ops,
  1125. void *&InsertPos) {
  1126. if (doNotCSE(N))
  1127. return nullptr;
  1128. FoldingSetNodeID ID;
  1129. AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
  1130. AddNodeIDCustom(ID, N);
  1131. SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
  1132. if (Node)
  1133. Node->intersectFlagsWith(N->getFlags());
  1134. return Node;
  1135. }
  1136. Align SelectionDAG::getEVTAlign(EVT VT) const {
  1137. Type *Ty = VT == MVT::iPTR ?
  1138. PointerType::get(Type::getInt8Ty(*getContext()), 0) :
  1139. VT.getTypeForEVT(*getContext());
  1140. return getDataLayout().getABITypeAlign(Ty);
  1141. }
  1142. // EntryNode could meaningfully have debug info if we can find it...
  1143. SelectionDAG::SelectionDAG(const TargetMachine &tm, CodeGenOpt::Level OL)
  1144. : TM(tm), OptLevel(OL),
  1145. EntryNode(ISD::EntryToken, 0, DebugLoc(), getVTList(MVT::Other, MVT::Glue)),
  1146. Root(getEntryNode()) {
  1147. InsertNode(&EntryNode);
  1148. DbgInfo = new SDDbgInfo();
  1149. }
  1150. void SelectionDAG::init(MachineFunction &NewMF,
  1151. OptimizationRemarkEmitter &NewORE, Pass *PassPtr,
  1152. const TargetLibraryInfo *LibraryInfo,
  1153. LegacyDivergenceAnalysis *Divergence,
  1154. ProfileSummaryInfo *PSIin, BlockFrequencyInfo *BFIin,
  1155. FunctionVarLocs const *VarLocs) {
  1156. MF = &NewMF;
  1157. SDAGISelPass = PassPtr;
  1158. ORE = &NewORE;
  1159. TLI = getSubtarget().getTargetLowering();
  1160. TSI = getSubtarget().getSelectionDAGInfo();
  1161. LibInfo = LibraryInfo;
  1162. Context = &MF->getFunction().getContext();
  1163. DA = Divergence;
  1164. PSI = PSIin;
  1165. BFI = BFIin;
  1166. FnVarLocs = VarLocs;
  1167. }
  1168. SelectionDAG::~SelectionDAG() {
  1169. assert(!UpdateListeners && "Dangling registered DAGUpdateListeners");
  1170. allnodes_clear();
  1171. OperandRecycler.clear(OperandAllocator);
  1172. delete DbgInfo;
  1173. }
  1174. bool SelectionDAG::shouldOptForSize() const {
  1175. return MF->getFunction().hasOptSize() ||
  1176. llvm::shouldOptimizeForSize(FLI->MBB->getBasicBlock(), PSI, BFI);
  1177. }
  1178. void SelectionDAG::allnodes_clear() {
  1179. assert(&*AllNodes.begin() == &EntryNode);
  1180. AllNodes.remove(AllNodes.begin());
  1181. while (!AllNodes.empty())
  1182. DeallocateNode(&AllNodes.front());
  1183. #ifndef NDEBUG
  1184. NextPersistentId = 0;
  1185. #endif
  1186. }
  1187. SDNode *SelectionDAG::FindNodeOrInsertPos(const FoldingSetNodeID &ID,
  1188. void *&InsertPos) {
  1189. SDNode *N = CSEMap.FindNodeOrInsertPos(ID, InsertPos);
  1190. if (N) {
  1191. switch (N->getOpcode()) {
  1192. default: break;
  1193. case ISD::Constant:
  1194. case ISD::ConstantFP:
  1195. llvm_unreachable("Querying for Constant and ConstantFP nodes requires "
  1196. "debug location. Use another overload.");
  1197. }
  1198. }
  1199. return N;
  1200. }
  1201. SDNode *SelectionDAG::FindNodeOrInsertPos(const FoldingSetNodeID &ID,
  1202. const SDLoc &DL, void *&InsertPos) {
  1203. SDNode *N = CSEMap.FindNodeOrInsertPos(ID, InsertPos);
  1204. if (N) {
  1205. switch (N->getOpcode()) {
  1206. case ISD::Constant:
  1207. case ISD::ConstantFP:
  1208. // Erase debug location from the node if the node is used at several
  1209. // different places. Do not propagate one location to all uses as it
  1210. // will cause a worse single stepping debugging experience.
  1211. if (N->getDebugLoc() != DL.getDebugLoc())
  1212. N->setDebugLoc(DebugLoc());
  1213. break;
  1214. default:
  1215. // When the node's point of use is located earlier in the instruction
  1216. // sequence than its prior point of use, update its debug info to the
  1217. // earlier location.
  1218. if (DL.getIROrder() && DL.getIROrder() < N->getIROrder())
  1219. N->setDebugLoc(DL.getDebugLoc());
  1220. break;
  1221. }
  1222. }
  1223. return N;
  1224. }
  1225. void SelectionDAG::clear() {
  1226. allnodes_clear();
  1227. OperandRecycler.clear(OperandAllocator);
  1228. OperandAllocator.Reset();
  1229. CSEMap.clear();
  1230. ExtendedValueTypeNodes.clear();
  1231. ExternalSymbols.clear();
  1232. TargetExternalSymbols.clear();
  1233. MCSymbols.clear();
  1234. SDEI.clear();
  1235. std::fill(CondCodeNodes.begin(), CondCodeNodes.end(),
  1236. static_cast<CondCodeSDNode*>(nullptr));
  1237. std::fill(ValueTypeNodes.begin(), ValueTypeNodes.end(),
  1238. static_cast<SDNode*>(nullptr));
  1239. EntryNode.UseList = nullptr;
  1240. InsertNode(&EntryNode);
  1241. Root = getEntryNode();
  1242. DbgInfo->clear();
  1243. }
  1244. SDValue SelectionDAG::getFPExtendOrRound(SDValue Op, const SDLoc &DL, EVT VT) {
  1245. return VT.bitsGT(Op.getValueType())
  1246. ? getNode(ISD::FP_EXTEND, DL, VT, Op)
  1247. : getNode(ISD::FP_ROUND, DL, VT, Op,
  1248. getIntPtrConstant(0, DL, /*isTarget=*/true));
  1249. }
  1250. std::pair<SDValue, SDValue>
  1251. SelectionDAG::getStrictFPExtendOrRound(SDValue Op, SDValue Chain,
  1252. const SDLoc &DL, EVT VT) {
  1253. assert(!VT.bitsEq(Op.getValueType()) &&
  1254. "Strict no-op FP extend/round not allowed.");
  1255. SDValue Res =
  1256. VT.bitsGT(Op.getValueType())
  1257. ? getNode(ISD::STRICT_FP_EXTEND, DL, {VT, MVT::Other}, {Chain, Op})
  1258. : getNode(ISD::STRICT_FP_ROUND, DL, {VT, MVT::Other},
  1259. {Chain, Op, getIntPtrConstant(0, DL)});
  1260. return std::pair<SDValue, SDValue>(Res, SDValue(Res.getNode(), 1));
  1261. }
  1262. SDValue SelectionDAG::getAnyExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
  1263. return VT.bitsGT(Op.getValueType()) ?
  1264. getNode(ISD::ANY_EXTEND, DL, VT, Op) :
  1265. getNode(ISD::TRUNCATE, DL, VT, Op);
  1266. }
  1267. SDValue SelectionDAG::getSExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
  1268. return VT.bitsGT(Op.getValueType()) ?
  1269. getNode(ISD::SIGN_EXTEND, DL, VT, Op) :
  1270. getNode(ISD::TRUNCATE, DL, VT, Op);
  1271. }
  1272. SDValue SelectionDAG::getZExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
  1273. return VT.bitsGT(Op.getValueType()) ?
  1274. getNode(ISD::ZERO_EXTEND, DL, VT, Op) :
  1275. getNode(ISD::TRUNCATE, DL, VT, Op);
  1276. }
  1277. SDValue SelectionDAG::getBoolExtOrTrunc(SDValue Op, const SDLoc &SL, EVT VT,
  1278. EVT OpVT) {
  1279. if (VT.bitsLE(Op.getValueType()))
  1280. return getNode(ISD::TRUNCATE, SL, VT, Op);
  1281. TargetLowering::BooleanContent BType = TLI->getBooleanContents(OpVT);
  1282. return getNode(TLI->getExtendForContent(BType), SL, VT, Op);
  1283. }
  1284. SDValue SelectionDAG::getZeroExtendInReg(SDValue Op, const SDLoc &DL, EVT VT) {
  1285. EVT OpVT = Op.getValueType();
  1286. assert(VT.isInteger() && OpVT.isInteger() &&
  1287. "Cannot getZeroExtendInReg FP types");
  1288. assert(VT.isVector() == OpVT.isVector() &&
  1289. "getZeroExtendInReg type should be vector iff the operand "
  1290. "type is vector!");
  1291. assert((!VT.isVector() ||
  1292. VT.getVectorElementCount() == OpVT.getVectorElementCount()) &&
  1293. "Vector element counts must match in getZeroExtendInReg");
  1294. assert(VT.bitsLE(OpVT) && "Not extending!");
  1295. if (OpVT == VT)
  1296. return Op;
  1297. APInt Imm = APInt::getLowBitsSet(OpVT.getScalarSizeInBits(),
  1298. VT.getScalarSizeInBits());
  1299. return getNode(ISD::AND, DL, OpVT, Op, getConstant(Imm, DL, OpVT));
  1300. }
  1301. SDValue SelectionDAG::getPtrExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
  1302. // Only unsigned pointer semantics are supported right now. In the future this
  1303. // might delegate to TLI to check pointer signedness.
  1304. return getZExtOrTrunc(Op, DL, VT);
  1305. }
  1306. SDValue SelectionDAG::getPtrExtendInReg(SDValue Op, const SDLoc &DL, EVT VT) {
  1307. // Only unsigned pointer semantics are supported right now. In the future this
  1308. // might delegate to TLI to check pointer signedness.
  1309. return getZeroExtendInReg(Op, DL, VT);
  1310. }
  1311. SDValue SelectionDAG::getNegative(SDValue Val, const SDLoc &DL, EVT VT) {
  1312. return getNode(ISD::SUB, DL, VT, getConstant(0, DL, VT), Val);
  1313. }
  1314. /// getNOT - Create a bitwise NOT operation as (XOR Val, -1).
  1315. SDValue SelectionDAG::getNOT(const SDLoc &DL, SDValue Val, EVT VT) {
  1316. return getNode(ISD::XOR, DL, VT, Val, getAllOnesConstant(DL, VT));
  1317. }
  1318. SDValue SelectionDAG::getLogicalNOT(const SDLoc &DL, SDValue Val, EVT VT) {
  1319. SDValue TrueValue = getBoolConstant(true, DL, VT, VT);
  1320. return getNode(ISD::XOR, DL, VT, Val, TrueValue);
  1321. }
  1322. SDValue SelectionDAG::getVPLogicalNOT(const SDLoc &DL, SDValue Val,
  1323. SDValue Mask, SDValue EVL, EVT VT) {
  1324. SDValue TrueValue = getBoolConstant(true, DL, VT, VT);
  1325. return getNode(ISD::VP_XOR, DL, VT, Val, TrueValue, Mask, EVL);
  1326. }
  1327. SDValue SelectionDAG::getVPPtrExtOrTrunc(const SDLoc &DL, EVT VT, SDValue Op,
  1328. SDValue Mask, SDValue EVL) {
  1329. return getVPZExtOrTrunc(DL, VT, Op, Mask, EVL);
  1330. }
  1331. SDValue SelectionDAG::getVPZExtOrTrunc(const SDLoc &DL, EVT VT, SDValue Op,
  1332. SDValue Mask, SDValue EVL) {
  1333. if (VT.bitsGT(Op.getValueType()))
  1334. return getNode(ISD::VP_ZERO_EXTEND, DL, VT, Op, Mask, EVL);
  1335. if (VT.bitsLT(Op.getValueType()))
  1336. return getNode(ISD::VP_TRUNCATE, DL, VT, Op, Mask, EVL);
  1337. return Op;
  1338. }
  1339. SDValue SelectionDAG::getBoolConstant(bool V, const SDLoc &DL, EVT VT,
  1340. EVT OpVT) {
  1341. if (!V)
  1342. return getConstant(0, DL, VT);
  1343. switch (TLI->getBooleanContents(OpVT)) {
  1344. case TargetLowering::ZeroOrOneBooleanContent:
  1345. case TargetLowering::UndefinedBooleanContent:
  1346. return getConstant(1, DL, VT);
  1347. case TargetLowering::ZeroOrNegativeOneBooleanContent:
  1348. return getAllOnesConstant(DL, VT);
  1349. }
  1350. llvm_unreachable("Unexpected boolean content enum!");
  1351. }
  1352. SDValue SelectionDAG::getConstant(uint64_t Val, const SDLoc &DL, EVT VT,
  1353. bool isT, bool isO) {
  1354. EVT EltVT = VT.getScalarType();
  1355. assert((EltVT.getSizeInBits() >= 64 ||
  1356. (uint64_t)((int64_t)Val >> EltVT.getSizeInBits()) + 1 < 2) &&
  1357. "getConstant with a uint64_t value that doesn't fit in the type!");
  1358. return getConstant(APInt(EltVT.getSizeInBits(), Val), DL, VT, isT, isO);
  1359. }
  1360. SDValue SelectionDAG::getConstant(const APInt &Val, const SDLoc &DL, EVT VT,
  1361. bool isT, bool isO) {
  1362. return getConstant(*ConstantInt::get(*Context, Val), DL, VT, isT, isO);
  1363. }
  1364. SDValue SelectionDAG::getConstant(const ConstantInt &Val, const SDLoc &DL,
  1365. EVT VT, bool isT, bool isO) {
  1366. assert(VT.isInteger() && "Cannot create FP integer constant!");
  1367. EVT EltVT = VT.getScalarType();
  1368. const ConstantInt *Elt = &Val;
  1369. // In some cases the vector type is legal but the element type is illegal and
  1370. // needs to be promoted, for example v8i8 on ARM. In this case, promote the
  1371. // inserted value (the type does not need to match the vector element type).
  1372. // Any extra bits introduced will be truncated away.
  1373. if (VT.isVector() && TLI->getTypeAction(*getContext(), EltVT) ==
  1374. TargetLowering::TypePromoteInteger) {
  1375. EltVT = TLI->getTypeToTransformTo(*getContext(), EltVT);
  1376. APInt NewVal = Elt->getValue().zextOrTrunc(EltVT.getSizeInBits());
  1377. Elt = ConstantInt::get(*getContext(), NewVal);
  1378. }
  1379. // In other cases the element type is illegal and needs to be expanded, for
  1380. // example v2i64 on MIPS32. In this case, find the nearest legal type, split
  1381. // the value into n parts and use a vector type with n-times the elements.
  1382. // Then bitcast to the type requested.
  1383. // Legalizing constants too early makes the DAGCombiner's job harder so we
  1384. // only legalize if the DAG tells us we must produce legal types.
  1385. else if (NewNodesMustHaveLegalTypes && VT.isVector() &&
  1386. TLI->getTypeAction(*getContext(), EltVT) ==
  1387. TargetLowering::TypeExpandInteger) {
  1388. const APInt &NewVal = Elt->getValue();
  1389. EVT ViaEltVT = TLI->getTypeToTransformTo(*getContext(), EltVT);
  1390. unsigned ViaEltSizeInBits = ViaEltVT.getSizeInBits();
  1391. // For scalable vectors, try to use a SPLAT_VECTOR_PARTS node.
  1392. if (VT.isScalableVector()) {
  1393. assert(EltVT.getSizeInBits() % ViaEltSizeInBits == 0 &&
  1394. "Can only handle an even split!");
  1395. unsigned Parts = EltVT.getSizeInBits() / ViaEltSizeInBits;
  1396. SmallVector<SDValue, 2> ScalarParts;
  1397. for (unsigned i = 0; i != Parts; ++i)
  1398. ScalarParts.push_back(getConstant(
  1399. NewVal.extractBits(ViaEltSizeInBits, i * ViaEltSizeInBits), DL,
  1400. ViaEltVT, isT, isO));
  1401. return getNode(ISD::SPLAT_VECTOR_PARTS, DL, VT, ScalarParts);
  1402. }
  1403. unsigned ViaVecNumElts = VT.getSizeInBits() / ViaEltSizeInBits;
  1404. EVT ViaVecVT = EVT::getVectorVT(*getContext(), ViaEltVT, ViaVecNumElts);
  1405. // Check the temporary vector is the correct size. If this fails then
  1406. // getTypeToTransformTo() probably returned a type whose size (in bits)
  1407. // isn't a power-of-2 factor of the requested type size.
  1408. assert(ViaVecVT.getSizeInBits() == VT.getSizeInBits());
  1409. SmallVector<SDValue, 2> EltParts;
  1410. for (unsigned i = 0; i < ViaVecNumElts / VT.getVectorNumElements(); ++i)
  1411. EltParts.push_back(getConstant(
  1412. NewVal.extractBits(ViaEltSizeInBits, i * ViaEltSizeInBits), DL,
  1413. ViaEltVT, isT, isO));
  1414. // EltParts is currently in little endian order. If we actually want
  1415. // big-endian order then reverse it now.
  1416. if (getDataLayout().isBigEndian())
  1417. std::reverse(EltParts.begin(), EltParts.end());
  1418. // The elements must be reversed when the element order is different
  1419. // to the endianness of the elements (because the BITCAST is itself a
  1420. // vector shuffle in this situation). However, we do not need any code to
  1421. // perform this reversal because getConstant() is producing a vector
  1422. // splat.
  1423. // This situation occurs in MIPS MSA.
  1424. SmallVector<SDValue, 8> Ops;
  1425. for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
  1426. llvm::append_range(Ops, EltParts);
  1427. SDValue V =
  1428. getNode(ISD::BITCAST, DL, VT, getBuildVector(ViaVecVT, DL, Ops));
  1429. return V;
  1430. }
  1431. assert(Elt->getBitWidth() == EltVT.getSizeInBits() &&
  1432. "APInt size does not match type size!");
  1433. unsigned Opc = isT ? ISD::TargetConstant : ISD::Constant;
  1434. FoldingSetNodeID ID;
  1435. AddNodeIDNode(ID, Opc, getVTList(EltVT), std::nullopt);
  1436. ID.AddPointer(Elt);
  1437. ID.AddBoolean(isO);
  1438. void *IP = nullptr;
  1439. SDNode *N = nullptr;
  1440. if ((N = FindNodeOrInsertPos(ID, DL, IP)))
  1441. if (!VT.isVector())
  1442. return SDValue(N, 0);
  1443. if (!N) {
  1444. N = newSDNode<ConstantSDNode>(isT, isO, Elt, EltVT);
  1445. CSEMap.InsertNode(N, IP);
  1446. InsertNode(N);
  1447. NewSDValueDbgMsg(SDValue(N, 0), "Creating constant: ", this);
  1448. }
  1449. SDValue Result(N, 0);
  1450. if (VT.isVector())
  1451. Result = getSplat(VT, DL, Result);
  1452. return Result;
  1453. }
  1454. SDValue SelectionDAG::getIntPtrConstant(uint64_t Val, const SDLoc &DL,
  1455. bool isTarget) {
  1456. return getConstant(Val, DL, TLI->getPointerTy(getDataLayout()), isTarget);
  1457. }
  1458. SDValue SelectionDAG::getShiftAmountConstant(uint64_t Val, EVT VT,
  1459. const SDLoc &DL, bool LegalTypes) {
  1460. assert(VT.isInteger() && "Shift amount is not an integer type!");
  1461. EVT ShiftVT = TLI->getShiftAmountTy(VT, getDataLayout(), LegalTypes);
  1462. return getConstant(Val, DL, ShiftVT);
  1463. }
  1464. SDValue SelectionDAG::getVectorIdxConstant(uint64_t Val, const SDLoc &DL,
  1465. bool isTarget) {
  1466. return getConstant(Val, DL, TLI->getVectorIdxTy(getDataLayout()), isTarget);
  1467. }
  1468. SDValue SelectionDAG::getConstantFP(const APFloat &V, const SDLoc &DL, EVT VT,
  1469. bool isTarget) {
  1470. return getConstantFP(*ConstantFP::get(*getContext(), V), DL, VT, isTarget);
  1471. }
  1472. SDValue SelectionDAG::getConstantFP(const ConstantFP &V, const SDLoc &DL,
  1473. EVT VT, bool isTarget) {
  1474. assert(VT.isFloatingPoint() && "Cannot create integer FP constant!");
  1475. EVT EltVT = VT.getScalarType();
  1476. // Do the map lookup using the actual bit pattern for the floating point
  1477. // value, so that we don't have problems with 0.0 comparing equal to -0.0, and
  1478. // we don't have issues with SNANs.
  1479. unsigned Opc = isTarget ? ISD::TargetConstantFP : ISD::ConstantFP;
  1480. FoldingSetNodeID ID;
  1481. AddNodeIDNode(ID, Opc, getVTList(EltVT), std::nullopt);
  1482. ID.AddPointer(&V);
  1483. void *IP = nullptr;
  1484. SDNode *N = nullptr;
  1485. if ((N = FindNodeOrInsertPos(ID, DL, IP)))
  1486. if (!VT.isVector())
  1487. return SDValue(N, 0);
  1488. if (!N) {
  1489. N = newSDNode<ConstantFPSDNode>(isTarget, &V, EltVT);
  1490. CSEMap.InsertNode(N, IP);
  1491. InsertNode(N);
  1492. }
  1493. SDValue Result(N, 0);
  1494. if (VT.isVector())
  1495. Result = getSplat(VT, DL, Result);
  1496. NewSDValueDbgMsg(Result, "Creating fp constant: ", this);
  1497. return Result;
  1498. }
  1499. SDValue SelectionDAG::getConstantFP(double Val, const SDLoc &DL, EVT VT,
  1500. bool isTarget) {
  1501. EVT EltVT = VT.getScalarType();
  1502. if (EltVT == MVT::f32)
  1503. return getConstantFP(APFloat((float)Val), DL, VT, isTarget);
  1504. if (EltVT == MVT::f64)
  1505. return getConstantFP(APFloat(Val), DL, VT, isTarget);
  1506. if (EltVT == MVT::f80 || EltVT == MVT::f128 || EltVT == MVT::ppcf128 ||
  1507. EltVT == MVT::f16 || EltVT == MVT::bf16) {
  1508. bool Ignored;
  1509. APFloat APF = APFloat(Val);
  1510. APF.convert(EVTToAPFloatSemantics(EltVT), APFloat::rmNearestTiesToEven,
  1511. &Ignored);
  1512. return getConstantFP(APF, DL, VT, isTarget);
  1513. }
  1514. llvm_unreachable("Unsupported type in getConstantFP");
  1515. }
  1516. SDValue SelectionDAG::getGlobalAddress(const GlobalValue *GV, const SDLoc &DL,
  1517. EVT VT, int64_t Offset, bool isTargetGA,
  1518. unsigned TargetFlags) {
  1519. assert((TargetFlags == 0 || isTargetGA) &&
  1520. "Cannot set target flags on target-independent globals");
  1521. // Truncate (with sign-extension) the offset value to the pointer size.
  1522. unsigned BitWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType());
  1523. if (BitWidth < 64)
  1524. Offset = SignExtend64(Offset, BitWidth);
  1525. unsigned Opc;
  1526. if (GV->isThreadLocal())
  1527. Opc = isTargetGA ? ISD::TargetGlobalTLSAddress : ISD::GlobalTLSAddress;
  1528. else
  1529. Opc = isTargetGA ? ISD::TargetGlobalAddress : ISD::GlobalAddress;
  1530. FoldingSetNodeID ID;
  1531. AddNodeIDNode(ID, Opc, getVTList(VT), std::nullopt);
  1532. ID.AddPointer(GV);
  1533. ID.AddInteger(Offset);
  1534. ID.AddInteger(TargetFlags);
  1535. void *IP = nullptr;
  1536. if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
  1537. return SDValue(E, 0);
  1538. auto *N = newSDNode<GlobalAddressSDNode>(
  1539. Opc, DL.getIROrder(), DL.getDebugLoc(), GV, VT, Offset, TargetFlags);
  1540. CSEMap.InsertNode(N, IP);
  1541. InsertNode(N);
  1542. return SDValue(N, 0);
  1543. }
  1544. SDValue SelectionDAG::getFrameIndex(int FI, EVT VT, bool isTarget) {
  1545. unsigned Opc = isTarget ? ISD::TargetFrameIndex : ISD::FrameIndex;
  1546. FoldingSetNodeID ID;
  1547. AddNodeIDNode(ID, Opc, getVTList(VT), std::nullopt);
  1548. ID.AddInteger(FI);
  1549. void *IP = nullptr;
  1550. if (SDNode *E = FindNodeOrInsertPos(ID, IP))
  1551. return SDValue(E, 0);
  1552. auto *N = newSDNode<FrameIndexSDNode>(FI, VT, isTarget);
  1553. CSEMap.InsertNode(N, IP);
  1554. InsertNode(N);
  1555. return SDValue(N, 0);
  1556. }
  1557. SDValue SelectionDAG::getJumpTable(int JTI, EVT VT, bool isTarget,
  1558. unsigned TargetFlags) {
  1559. assert((TargetFlags == 0 || isTarget) &&
  1560. "Cannot set target flags on target-independent jump tables");
  1561. unsigned Opc = isTarget ? ISD::TargetJumpTable : ISD::JumpTable;
  1562. FoldingSetNodeID ID;
  1563. AddNodeIDNode(ID, Opc, getVTList(VT), std::nullopt);
  1564. ID.AddInteger(JTI);
  1565. ID.AddInteger(TargetFlags);
  1566. void *IP = nullptr;
  1567. if (SDNode *E = FindNodeOrInsertPos(ID, IP))
  1568. return SDValue(E, 0);
  1569. auto *N = newSDNode<JumpTableSDNode>(JTI, VT, isTarget, TargetFlags);
  1570. CSEMap.InsertNode(N, IP);
  1571. InsertNode(N);
  1572. return SDValue(N, 0);
  1573. }
  1574. SDValue SelectionDAG::getConstantPool(const Constant *C, EVT VT,
  1575. MaybeAlign Alignment, int Offset,
  1576. bool isTarget, unsigned TargetFlags) {
  1577. assert((TargetFlags == 0 || isTarget) &&
  1578. "Cannot set target flags on target-independent globals");
  1579. if (!Alignment)
  1580. Alignment = shouldOptForSize()
  1581. ? getDataLayout().getABITypeAlign(C->getType())
  1582. : getDataLayout().getPrefTypeAlign(C->getType());
  1583. unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
  1584. FoldingSetNodeID ID;
  1585. AddNodeIDNode(ID, Opc, getVTList(VT), std::nullopt);
  1586. ID.AddInteger(Alignment->value());
  1587. ID.AddInteger(Offset);
  1588. ID.AddPointer(C);
  1589. ID.AddInteger(TargetFlags);
  1590. void *IP = nullptr;
  1591. if (SDNode *E = FindNodeOrInsertPos(ID, IP))
  1592. return SDValue(E, 0);
  1593. auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VT, Offset, *Alignment,
  1594. TargetFlags);
  1595. CSEMap.InsertNode(N, IP);
  1596. InsertNode(N);
  1597. SDValue V = SDValue(N, 0);
  1598. NewSDValueDbgMsg(V, "Creating new constant pool: ", this);
  1599. return V;
  1600. }
  1601. SDValue SelectionDAG::getConstantPool(MachineConstantPoolValue *C, EVT VT,
  1602. MaybeAlign Alignment, int Offset,
  1603. bool isTarget, unsigned TargetFlags) {
  1604. assert((TargetFlags == 0 || isTarget) &&
  1605. "Cannot set target flags on target-independent globals");
  1606. if (!Alignment)
  1607. Alignment = getDataLayout().getPrefTypeAlign(C->getType());
  1608. unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
  1609. FoldingSetNodeID ID;
  1610. AddNodeIDNode(ID, Opc, getVTList(VT), std::nullopt);
  1611. ID.AddInteger(Alignment->value());
  1612. ID.AddInteger(Offset);
  1613. C->addSelectionDAGCSEId(ID);
  1614. ID.AddInteger(TargetFlags);
  1615. void *IP = nullptr;
  1616. if (SDNode *E = FindNodeOrInsertPos(ID, IP))
  1617. return SDValue(E, 0);
  1618. auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VT, Offset, *Alignment,
  1619. TargetFlags);
  1620. CSEMap.InsertNode(N, IP);
  1621. InsertNode(N);
  1622. return SDValue(N, 0);
  1623. }
  1624. SDValue SelectionDAG::getTargetIndex(int Index, EVT VT, int64_t Offset,
  1625. unsigned TargetFlags) {
  1626. FoldingSetNodeID ID;
  1627. AddNodeIDNode(ID, ISD::TargetIndex, getVTList(VT), std::nullopt);
  1628. ID.AddInteger(Index);
  1629. ID.AddInteger(Offset);
  1630. ID.AddInteger(TargetFlags);
  1631. void *IP = nullptr;
  1632. if (SDNode *E = FindNodeOrInsertPos(ID, IP))
  1633. return SDValue(E, 0);
  1634. auto *N = newSDNode<TargetIndexSDNode>(Index, VT, Offset, TargetFlags);
  1635. CSEMap.InsertNode(N, IP);
  1636. InsertNode(N);
  1637. return SDValue(N, 0);
  1638. }
  1639. SDValue SelectionDAG::getBasicBlock(MachineBasicBlock *MBB) {
  1640. FoldingSetNodeID ID;
  1641. AddNodeIDNode(ID, ISD::BasicBlock, getVTList(MVT::Other), std::nullopt);
  1642. ID.AddPointer(MBB);
  1643. void *IP = nullptr;
  1644. if (SDNode *E = FindNodeOrInsertPos(ID, IP))
  1645. return SDValue(E, 0);
  1646. auto *N = newSDNode<BasicBlockSDNode>(MBB);
  1647. CSEMap.InsertNode(N, IP);
  1648. InsertNode(N);
  1649. return SDValue(N, 0);
  1650. }
  1651. SDValue SelectionDAG::getValueType(EVT VT) {
  1652. if (VT.isSimple() && (unsigned)VT.getSimpleVT().SimpleTy >=
  1653. ValueTypeNodes.size())
  1654. ValueTypeNodes.resize(VT.getSimpleVT().SimpleTy+1);
  1655. SDNode *&N = VT.isExtended() ?
  1656. ExtendedValueTypeNodes[VT] : ValueTypeNodes[VT.getSimpleVT().SimpleTy];
  1657. if (N) return SDValue(N, 0);
  1658. N = newSDNode<VTSDNode>(VT);
  1659. InsertNode(N);
  1660. return SDValue(N, 0);
  1661. }
  1662. SDValue SelectionDAG::getExternalSymbol(const char *Sym, EVT VT) {
  1663. SDNode *&N = ExternalSymbols[Sym];
  1664. if (N) return SDValue(N, 0);
  1665. N = newSDNode<ExternalSymbolSDNode>(false, Sym, 0, VT);
  1666. InsertNode(N);
  1667. return SDValue(N, 0);
  1668. }
  1669. SDValue SelectionDAG::getMCSymbol(MCSymbol *Sym, EVT VT) {
  1670. SDNode *&N = MCSymbols[Sym];
  1671. if (N)
  1672. return SDValue(N, 0);
  1673. N = newSDNode<MCSymbolSDNode>(Sym, VT);
  1674. InsertNode(N);
  1675. return SDValue(N, 0);
  1676. }
  1677. SDValue SelectionDAG::getTargetExternalSymbol(const char *Sym, EVT VT,
  1678. unsigned TargetFlags) {
  1679. SDNode *&N =
  1680. TargetExternalSymbols[std::pair<std::string, unsigned>(Sym, TargetFlags)];
  1681. if (N) return SDValue(N, 0);
  1682. N = newSDNode<ExternalSymbolSDNode>(true, Sym, TargetFlags, VT);
  1683. InsertNode(N);
  1684. return SDValue(N, 0);
  1685. }
  1686. SDValue SelectionDAG::getCondCode(ISD::CondCode Cond) {
  1687. if ((unsigned)Cond >= CondCodeNodes.size())
  1688. CondCodeNodes.resize(Cond+1);
  1689. if (!CondCodeNodes[Cond]) {
  1690. auto *N = newSDNode<CondCodeSDNode>(Cond);
  1691. CondCodeNodes[Cond] = N;
  1692. InsertNode(N);
  1693. }
  1694. return SDValue(CondCodeNodes[Cond], 0);
  1695. }
  1696. SDValue SelectionDAG::getStepVector(const SDLoc &DL, EVT ResVT) {
  1697. APInt One(ResVT.getScalarSizeInBits(), 1);
  1698. return getStepVector(DL, ResVT, One);
  1699. }
  1700. SDValue SelectionDAG::getStepVector(const SDLoc &DL, EVT ResVT, APInt StepVal) {
  1701. assert(ResVT.getScalarSizeInBits() == StepVal.getBitWidth());
  1702. if (ResVT.isScalableVector())
  1703. return getNode(
  1704. ISD::STEP_VECTOR, DL, ResVT,
  1705. getTargetConstant(StepVal, DL, ResVT.getVectorElementType()));
  1706. SmallVector<SDValue, 16> OpsStepConstants;
  1707. for (uint64_t i = 0; i < ResVT.getVectorNumElements(); i++)
  1708. OpsStepConstants.push_back(
  1709. getConstant(StepVal * i, DL, ResVT.getVectorElementType()));
  1710. return getBuildVector(ResVT, DL, OpsStepConstants);
  1711. }
  1712. /// Swaps the values of N1 and N2. Swaps all indices in the shuffle mask M that
  1713. /// point at N1 to point at N2 and indices that point at N2 to point at N1.
  1714. static void commuteShuffle(SDValue &N1, SDValue &N2, MutableArrayRef<int> M) {
  1715. std::swap(N1, N2);
  1716. ShuffleVectorSDNode::commuteMask(M);
  1717. }
  1718. SDValue SelectionDAG::getVectorShuffle(EVT VT, const SDLoc &dl, SDValue N1,
  1719. SDValue N2, ArrayRef<int> Mask) {
  1720. assert(VT.getVectorNumElements() == Mask.size() &&
  1721. "Must have the same number of vector elements as mask elements!");
  1722. assert(VT == N1.getValueType() && VT == N2.getValueType() &&
  1723. "Invalid VECTOR_SHUFFLE");
  1724. // Canonicalize shuffle undef, undef -> undef
  1725. if (N1.isUndef() && N2.isUndef())
  1726. return getUNDEF(VT);
  1727. // Validate that all indices in Mask are within the range of the elements
  1728. // input to the shuffle.
  1729. int NElts = Mask.size();
  1730. assert(llvm::all_of(Mask,
  1731. [&](int M) { return M < (NElts * 2) && M >= -1; }) &&
  1732. "Index out of range");
  1733. // Copy the mask so we can do any needed cleanup.
  1734. SmallVector<int, 8> MaskVec(Mask);
  1735. // Canonicalize shuffle v, v -> v, undef
  1736. if (N1 == N2) {
  1737. N2 = getUNDEF(VT);
  1738. for (int i = 0; i != NElts; ++i)
  1739. if (MaskVec[i] >= NElts) MaskVec[i] -= NElts;
  1740. }
  1741. // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
  1742. if (N1.isUndef())
  1743. commuteShuffle(N1, N2, MaskVec);
  1744. if (TLI->hasVectorBlend()) {
  1745. // If shuffling a splat, try to blend the splat instead. We do this here so
  1746. // that even when this arises during lowering we don't have to re-handle it.
  1747. auto BlendSplat = [&](BuildVectorSDNode *BV, int Offset) {
  1748. BitVector UndefElements;
  1749. SDValue Splat = BV->getSplatValue(&UndefElements);
  1750. if (!Splat)
  1751. return;
  1752. for (int i = 0; i < NElts; ++i) {
  1753. if (MaskVec[i] < Offset || MaskVec[i] >= (Offset + NElts))
  1754. continue;
  1755. // If this input comes from undef, mark it as such.
  1756. if (UndefElements[MaskVec[i] - Offset]) {
  1757. MaskVec[i] = -1;
  1758. continue;
  1759. }
  1760. // If we can blend a non-undef lane, use that instead.
  1761. if (!UndefElements[i])
  1762. MaskVec[i] = i + Offset;
  1763. }
  1764. };
  1765. if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
  1766. BlendSplat(N1BV, 0);
  1767. if (auto *N2BV = dyn_cast<BuildVectorSDNode>(N2))
  1768. BlendSplat(N2BV, NElts);
  1769. }
  1770. // Canonicalize all index into lhs, -> shuffle lhs, undef
  1771. // Canonicalize all index into rhs, -> shuffle rhs, undef
  1772. bool AllLHS = true, AllRHS = true;
  1773. bool N2Undef = N2.isUndef();
  1774. for (int i = 0; i != NElts; ++i) {
  1775. if (MaskVec[i] >= NElts) {
  1776. if (N2Undef)
  1777. MaskVec[i] = -1;
  1778. else
  1779. AllLHS = false;
  1780. } else if (MaskVec[i] >= 0) {
  1781. AllRHS = false;
  1782. }
  1783. }
  1784. if (AllLHS && AllRHS)
  1785. return getUNDEF(VT);
  1786. if (AllLHS && !N2Undef)
  1787. N2 = getUNDEF(VT);
  1788. if (AllRHS) {
  1789. N1 = getUNDEF(VT);
  1790. commuteShuffle(N1, N2, MaskVec);
  1791. }
  1792. // Reset our undef status after accounting for the mask.
  1793. N2Undef = N2.isUndef();
  1794. // Re-check whether both sides ended up undef.
  1795. if (N1.isUndef() && N2Undef)
  1796. return getUNDEF(VT);
  1797. // If Identity shuffle return that node.
  1798. bool Identity = true, AllSame = true;
  1799. for (int i = 0; i != NElts; ++i) {
  1800. if (MaskVec[i] >= 0 && MaskVec[i] != i) Identity = false;
  1801. if (MaskVec[i] != MaskVec[0]) AllSame = false;
  1802. }
  1803. if (Identity && NElts)
  1804. return N1;
  1805. // Shuffling a constant splat doesn't change the result.
  1806. if (N2Undef) {
  1807. SDValue V = N1;
  1808. // Look through any bitcasts. We check that these don't change the number
  1809. // (and size) of elements and just changes their types.
  1810. while (V.getOpcode() == ISD::BITCAST)
  1811. V = V->getOperand(0);
  1812. // A splat should always show up as a build vector node.
  1813. if (auto *BV = dyn_cast<BuildVectorSDNode>(V)) {
  1814. BitVector UndefElements;
  1815. SDValue Splat = BV->getSplatValue(&UndefElements);
  1816. // If this is a splat of an undef, shuffling it is also undef.
  1817. if (Splat && Splat.isUndef())
  1818. return getUNDEF(VT);
  1819. bool SameNumElts =
  1820. V.getValueType().getVectorNumElements() == VT.getVectorNumElements();
  1821. // We only have a splat which can skip shuffles if there is a splatted
  1822. // value and no undef lanes rearranged by the shuffle.
  1823. if (Splat && UndefElements.none()) {
  1824. // Splat of <x, x, ..., x>, return <x, x, ..., x>, provided that the
  1825. // number of elements match or the value splatted is a zero constant.
  1826. if (SameNumElts)
  1827. return N1;
  1828. if (auto *C = dyn_cast<ConstantSDNode>(Splat))
  1829. if (C->isZero())
  1830. return N1;
  1831. }
  1832. // If the shuffle itself creates a splat, build the vector directly.
  1833. if (AllSame && SameNumElts) {
  1834. EVT BuildVT = BV->getValueType(0);
  1835. const SDValue &Splatted = BV->getOperand(MaskVec[0]);
  1836. SDValue NewBV = getSplatBuildVector(BuildVT, dl, Splatted);
  1837. // We may have jumped through bitcasts, so the type of the
  1838. // BUILD_VECTOR may not match the type of the shuffle.
  1839. if (BuildVT != VT)
  1840. NewBV = getNode(ISD::BITCAST, dl, VT, NewBV);
  1841. return NewBV;
  1842. }
  1843. }
  1844. }
  1845. FoldingSetNodeID ID;
  1846. SDValue Ops[2] = { N1, N2 };
  1847. AddNodeIDNode(ID, ISD::VECTOR_SHUFFLE, getVTList(VT), Ops);
  1848. for (int i = 0; i != NElts; ++i)
  1849. ID.AddInteger(MaskVec[i]);
  1850. void* IP = nullptr;
  1851. if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
  1852. return SDValue(E, 0);
  1853. // Allocate the mask array for the node out of the BumpPtrAllocator, since
  1854. // SDNode doesn't have access to it. This memory will be "leaked" when
  1855. // the node is deallocated, but recovered when the NodeAllocator is released.
  1856. int *MaskAlloc = OperandAllocator.Allocate<int>(NElts);
  1857. llvm::copy(MaskVec, MaskAlloc);
  1858. auto *N = newSDNode<ShuffleVectorSDNode>(VT, dl.getIROrder(),
  1859. dl.getDebugLoc(), MaskAlloc);
  1860. createOperands(N, Ops);
  1861. CSEMap.InsertNode(N, IP);
  1862. InsertNode(N);
  1863. SDValue V = SDValue(N, 0);
  1864. NewSDValueDbgMsg(V, "Creating new node: ", this);
  1865. return V;
  1866. }
  1867. SDValue SelectionDAG::getCommutedVectorShuffle(const ShuffleVectorSDNode &SV) {
  1868. EVT VT = SV.getValueType(0);
  1869. SmallVector<int, 8> MaskVec(SV.getMask());
  1870. ShuffleVectorSDNode::commuteMask(MaskVec);
  1871. SDValue Op0 = SV.getOperand(0);
  1872. SDValue Op1 = SV.getOperand(1);
  1873. return getVectorShuffle(VT, SDLoc(&SV), Op1, Op0, MaskVec);
  1874. }
  1875. SDValue SelectionDAG::getRegister(unsigned RegNo, EVT VT) {
  1876. FoldingSetNodeID ID;
  1877. AddNodeIDNode(ID, ISD::Register, getVTList(VT), std::nullopt);
  1878. ID.AddInteger(RegNo);
  1879. void *IP = nullptr;
  1880. if (SDNode *E = FindNodeOrInsertPos(ID, IP))
  1881. return SDValue(E, 0);
  1882. auto *N = newSDNode<RegisterSDNode>(RegNo, VT);
  1883. N->SDNodeBits.IsDivergent = TLI->isSDNodeSourceOfDivergence(N, FLI, DA);
  1884. CSEMap.InsertNode(N, IP);
  1885. InsertNode(N);
  1886. return SDValue(N, 0);
  1887. }
  1888. SDValue SelectionDAG::getRegisterMask(const uint32_t *RegMask) {
  1889. FoldingSetNodeID ID;
  1890. AddNodeIDNode(ID, ISD::RegisterMask, getVTList(MVT::Untyped), std::nullopt);
  1891. ID.AddPointer(RegMask);
  1892. void *IP = nullptr;
  1893. if (SDNode *E = FindNodeOrInsertPos(ID, IP))
  1894. return SDValue(E, 0);
  1895. auto *N = newSDNode<RegisterMaskSDNode>(RegMask);
  1896. CSEMap.InsertNode(N, IP);
  1897. InsertNode(N);
  1898. return SDValue(N, 0);
  1899. }
  1900. SDValue SelectionDAG::getEHLabel(const SDLoc &dl, SDValue Root,
  1901. MCSymbol *Label) {
  1902. return getLabelNode(ISD::EH_LABEL, dl, Root, Label);
  1903. }
  1904. SDValue SelectionDAG::getLabelNode(unsigned Opcode, const SDLoc &dl,
  1905. SDValue Root, MCSymbol *Label) {
  1906. FoldingSetNodeID ID;
  1907. SDValue Ops[] = { Root };
  1908. AddNodeIDNode(ID, Opcode, getVTList(MVT::Other), Ops);
  1909. ID.AddPointer(Label);
  1910. void *IP = nullptr;
  1911. if (SDNode *E = FindNodeOrInsertPos(ID, IP))
  1912. return SDValue(E, 0);
  1913. auto *N =
  1914. newSDNode<LabelSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), Label);
  1915. createOperands(N, Ops);
  1916. CSEMap.InsertNode(N, IP);
  1917. InsertNode(N);
  1918. return SDValue(N, 0);
  1919. }
  1920. SDValue SelectionDAG::getBlockAddress(const BlockAddress *BA, EVT VT,
  1921. int64_t Offset, bool isTarget,
  1922. unsigned TargetFlags) {
  1923. unsigned Opc = isTarget ? ISD::TargetBlockAddress : ISD::BlockAddress;
  1924. FoldingSetNodeID ID;
  1925. AddNodeIDNode(ID, Opc, getVTList(VT), std::nullopt);
  1926. ID.AddPointer(BA);
  1927. ID.AddInteger(Offset);
  1928. ID.AddInteger(TargetFlags);
  1929. void *IP = nullptr;
  1930. if (SDNode *E = FindNodeOrInsertPos(ID, IP))
  1931. return SDValue(E, 0);
  1932. auto *N = newSDNode<BlockAddressSDNode>(Opc, VT, BA, Offset, TargetFlags);
  1933. CSEMap.InsertNode(N, IP);
  1934. InsertNode(N);
  1935. return SDValue(N, 0);
  1936. }
  1937. SDValue SelectionDAG::getSrcValue(const Value *V) {
  1938. FoldingSetNodeID ID;
  1939. AddNodeIDNode(ID, ISD::SRCVALUE, getVTList(MVT::Other), std::nullopt);
  1940. ID.AddPointer(V);
  1941. void *IP = nullptr;
  1942. if (SDNode *E = FindNodeOrInsertPos(ID, IP))
  1943. return SDValue(E, 0);
  1944. auto *N = newSDNode<SrcValueSDNode>(V);
  1945. CSEMap.InsertNode(N, IP);
  1946. InsertNode(N);
  1947. return SDValue(N, 0);
  1948. }
  1949. SDValue SelectionDAG::getMDNode(const MDNode *MD) {
  1950. FoldingSetNodeID ID;
  1951. AddNodeIDNode(ID, ISD::MDNODE_SDNODE, getVTList(MVT::Other), std::nullopt);
  1952. ID.AddPointer(MD);
  1953. void *IP = nullptr;
  1954. if (SDNode *E = FindNodeOrInsertPos(ID, IP))
  1955. return SDValue(E, 0);
  1956. auto *N = newSDNode<MDNodeSDNode>(MD);
  1957. CSEMap.InsertNode(N, IP);
  1958. InsertNode(N);
  1959. return SDValue(N, 0);
  1960. }
  1961. SDValue SelectionDAG::getBitcast(EVT VT, SDValue V) {
  1962. if (VT == V.getValueType())
  1963. return V;
  1964. return getNode(ISD::BITCAST, SDLoc(V), VT, V);
  1965. }
  1966. SDValue SelectionDAG::getAddrSpaceCast(const SDLoc &dl, EVT VT, SDValue Ptr,
  1967. unsigned SrcAS, unsigned DestAS) {
  1968. SDValue Ops[] = {Ptr};
  1969. FoldingSetNodeID ID;
  1970. AddNodeIDNode(ID, ISD::ADDRSPACECAST, getVTList(VT), Ops);
  1971. ID.AddInteger(SrcAS);
  1972. ID.AddInteger(DestAS);
  1973. void *IP = nullptr;
  1974. if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
  1975. return SDValue(E, 0);
  1976. auto *N = newSDNode<AddrSpaceCastSDNode>(dl.getIROrder(), dl.getDebugLoc(),
  1977. VT, SrcAS, DestAS);
  1978. createOperands(N, Ops);
  1979. CSEMap.InsertNode(N, IP);
  1980. InsertNode(N);
  1981. return SDValue(N, 0);
  1982. }
  1983. SDValue SelectionDAG::getFreeze(SDValue V) {
  1984. return getNode(ISD::FREEZE, SDLoc(V), V.getValueType(), V);
  1985. }
  1986. /// getShiftAmountOperand - Return the specified value casted to
  1987. /// the target's desired shift amount type.
  1988. SDValue SelectionDAG::getShiftAmountOperand(EVT LHSTy, SDValue Op) {
  1989. EVT OpTy = Op.getValueType();
  1990. EVT ShTy = TLI->getShiftAmountTy(LHSTy, getDataLayout());
  1991. if (OpTy == ShTy || OpTy.isVector()) return Op;
  1992. return getZExtOrTrunc(Op, SDLoc(Op), ShTy);
  1993. }
  1994. SDValue SelectionDAG::expandVAArg(SDNode *Node) {
  1995. SDLoc dl(Node);
  1996. const TargetLowering &TLI = getTargetLoweringInfo();
  1997. const Value *V = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
  1998. EVT VT = Node->getValueType(0);
  1999. SDValue Tmp1 = Node->getOperand(0);
  2000. SDValue Tmp2 = Node->getOperand(1);
  2001. const MaybeAlign MA(Node->getConstantOperandVal(3));
  2002. SDValue VAListLoad = getLoad(TLI.getPointerTy(getDataLayout()), dl, Tmp1,
  2003. Tmp2, MachinePointerInfo(V));
  2004. SDValue VAList = VAListLoad;
  2005. if (MA && *MA > TLI.getMinStackArgumentAlignment()) {
  2006. VAList = getNode(ISD::ADD, dl, VAList.getValueType(), VAList,
  2007. getConstant(MA->value() - 1, dl, VAList.getValueType()));
  2008. VAList =
  2009. getNode(ISD::AND, dl, VAList.getValueType(), VAList,
  2010. getConstant(-(int64_t)MA->value(), dl, VAList.getValueType()));
  2011. }
  2012. // Increment the pointer, VAList, to the next vaarg
  2013. Tmp1 = getNode(ISD::ADD, dl, VAList.getValueType(), VAList,
  2014. getConstant(getDataLayout().getTypeAllocSize(
  2015. VT.getTypeForEVT(*getContext())),
  2016. dl, VAList.getValueType()));
  2017. // Store the incremented VAList to the legalized pointer
  2018. Tmp1 =
  2019. getStore(VAListLoad.getValue(1), dl, Tmp1, Tmp2, MachinePointerInfo(V));
  2020. // Load the actual argument out of the pointer VAList
  2021. return getLoad(VT, dl, Tmp1, VAList, MachinePointerInfo());
  2022. }
  2023. SDValue SelectionDAG::expandVACopy(SDNode *Node) {
  2024. SDLoc dl(Node);
  2025. const TargetLowering &TLI = getTargetLoweringInfo();
  2026. // This defaults to loading a pointer from the input and storing it to the
  2027. // output, returning the chain.
  2028. const Value *VD = cast<SrcValueSDNode>(Node->getOperand(3))->getValue();
  2029. const Value *VS = cast<SrcValueSDNode>(Node->getOperand(4))->getValue();
  2030. SDValue Tmp1 =
  2031. getLoad(TLI.getPointerTy(getDataLayout()), dl, Node->getOperand(0),
  2032. Node->getOperand(2), MachinePointerInfo(VS));
  2033. return getStore(Tmp1.getValue(1), dl, Tmp1, Node->getOperand(1),
  2034. MachinePointerInfo(VD));
  2035. }
  2036. Align SelectionDAG::getReducedAlign(EVT VT, bool UseABI) {
  2037. const DataLayout &DL = getDataLayout();
  2038. Type *Ty = VT.getTypeForEVT(*getContext());
  2039. Align RedAlign = UseABI ? DL.getABITypeAlign(Ty) : DL.getPrefTypeAlign(Ty);
  2040. if (TLI->isTypeLegal(VT) || !VT.isVector())
  2041. return RedAlign;
  2042. const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering();
  2043. const Align StackAlign = TFI->getStackAlign();
  2044. // See if we can choose a smaller ABI alignment in cases where it's an
  2045. // illegal vector type that will get broken down.
  2046. if (RedAlign > StackAlign) {
  2047. EVT IntermediateVT;
  2048. MVT RegisterVT;
  2049. unsigned NumIntermediates;
  2050. TLI->getVectorTypeBreakdown(*getContext(), VT, IntermediateVT,
  2051. NumIntermediates, RegisterVT);
  2052. Ty = IntermediateVT.getTypeForEVT(*getContext());
  2053. Align RedAlign2 = UseABI ? DL.getABITypeAlign(Ty) : DL.getPrefTypeAlign(Ty);
  2054. if (RedAlign2 < RedAlign)
  2055. RedAlign = RedAlign2;
  2056. }
  2057. return RedAlign;
  2058. }
  2059. SDValue SelectionDAG::CreateStackTemporary(TypeSize Bytes, Align Alignment) {
  2060. MachineFrameInfo &MFI = MF->getFrameInfo();
  2061. const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering();
  2062. int StackID = 0;
  2063. if (Bytes.isScalable())
  2064. StackID = TFI->getStackIDForScalableVectors();
  2065. // The stack id gives an indication of whether the object is scalable or
  2066. // not, so it's safe to pass in the minimum size here.
  2067. int FrameIdx = MFI.CreateStackObject(Bytes.getKnownMinValue(), Alignment,
  2068. false, nullptr, StackID);
  2069. return getFrameIndex(FrameIdx, TLI->getFrameIndexTy(getDataLayout()));
  2070. }
  2071. SDValue SelectionDAG::CreateStackTemporary(EVT VT, unsigned minAlign) {
  2072. Type *Ty = VT.getTypeForEVT(*getContext());
  2073. Align StackAlign =
  2074. std::max(getDataLayout().getPrefTypeAlign(Ty), Align(minAlign));
  2075. return CreateStackTemporary(VT.getStoreSize(), StackAlign);
  2076. }
  2077. SDValue SelectionDAG::CreateStackTemporary(EVT VT1, EVT VT2) {
  2078. TypeSize VT1Size = VT1.getStoreSize();
  2079. TypeSize VT2Size = VT2.getStoreSize();
  2080. assert(VT1Size.isScalable() == VT2Size.isScalable() &&
  2081. "Don't know how to choose the maximum size when creating a stack "
  2082. "temporary");
  2083. TypeSize Bytes = VT1Size.getKnownMinValue() > VT2Size.getKnownMinValue()
  2084. ? VT1Size
  2085. : VT2Size;
  2086. Type *Ty1 = VT1.getTypeForEVT(*getContext());
  2087. Type *Ty2 = VT2.getTypeForEVT(*getContext());
  2088. const DataLayout &DL = getDataLayout();
  2089. Align Align = std::max(DL.getPrefTypeAlign(Ty1), DL.getPrefTypeAlign(Ty2));
  2090. return CreateStackTemporary(Bytes, Align);
  2091. }
  2092. SDValue SelectionDAG::FoldSetCC(EVT VT, SDValue N1, SDValue N2,
  2093. ISD::CondCode Cond, const SDLoc &dl) {
  2094. EVT OpVT = N1.getValueType();
  2095. // These setcc operations always fold.
  2096. switch (Cond) {
  2097. default: break;
  2098. case ISD::SETFALSE:
  2099. case ISD::SETFALSE2: return getBoolConstant(false, dl, VT, OpVT);
  2100. case ISD::SETTRUE:
  2101. case ISD::SETTRUE2: return getBoolConstant(true, dl, VT, OpVT);
  2102. case ISD::SETOEQ:
  2103. case ISD::SETOGT:
  2104. case ISD::SETOGE:
  2105. case ISD::SETOLT:
  2106. case ISD::SETOLE:
  2107. case ISD::SETONE:
  2108. case ISD::SETO:
  2109. case ISD::SETUO:
  2110. case ISD::SETUEQ:
  2111. case ISD::SETUNE:
  2112. assert(!OpVT.isInteger() && "Illegal setcc for integer!");
  2113. break;
  2114. }
  2115. if (OpVT.isInteger()) {
  2116. // For EQ and NE, we can always pick a value for the undef to make the
  2117. // predicate pass or fail, so we can return undef.
  2118. // Matches behavior in llvm::ConstantFoldCompareInstruction.
  2119. // icmp eq/ne X, undef -> undef.
  2120. if ((N1.isUndef() || N2.isUndef()) &&
  2121. (Cond == ISD::SETEQ || Cond == ISD::SETNE))
  2122. return getUNDEF(VT);
  2123. // If both operands are undef, we can return undef for int comparison.
  2124. // icmp undef, undef -> undef.
  2125. if (N1.isUndef() && N2.isUndef())
  2126. return getUNDEF(VT);
  2127. // icmp X, X -> true/false
  2128. // icmp X, undef -> true/false because undef could be X.
  2129. if (N1 == N2)
  2130. return getBoolConstant(ISD::isTrueWhenEqual(Cond), dl, VT, OpVT);
  2131. }
  2132. if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2)) {
  2133. const APInt &C2 = N2C->getAPIntValue();
  2134. if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1)) {
  2135. const APInt &C1 = N1C->getAPIntValue();
  2136. return getBoolConstant(ICmpInst::compare(C1, C2, getICmpCondCode(Cond)),
  2137. dl, VT, OpVT);
  2138. }
  2139. }
  2140. auto *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
  2141. auto *N2CFP = dyn_cast<ConstantFPSDNode>(N2);
  2142. if (N1CFP && N2CFP) {
  2143. APFloat::cmpResult R = N1CFP->getValueAPF().compare(N2CFP->getValueAPF());
  2144. switch (Cond) {
  2145. default: break;
  2146. case ISD::SETEQ: if (R==APFloat::cmpUnordered)
  2147. return getUNDEF(VT);
  2148. [[fallthrough]];
  2149. case ISD::SETOEQ: return getBoolConstant(R==APFloat::cmpEqual, dl, VT,
  2150. OpVT);
  2151. case ISD::SETNE: if (R==APFloat::cmpUnordered)
  2152. return getUNDEF(VT);
  2153. [[fallthrough]];
  2154. case ISD::SETONE: return getBoolConstant(R==APFloat::cmpGreaterThan ||
  2155. R==APFloat::cmpLessThan, dl, VT,
  2156. OpVT);
  2157. case ISD::SETLT: if (R==APFloat::cmpUnordered)
  2158. return getUNDEF(VT);
  2159. [[fallthrough]];
  2160. case ISD::SETOLT: return getBoolConstant(R==APFloat::cmpLessThan, dl, VT,
  2161. OpVT);
  2162. case ISD::SETGT: if (R==APFloat::cmpUnordered)
  2163. return getUNDEF(VT);
  2164. [[fallthrough]];
  2165. case ISD::SETOGT: return getBoolConstant(R==APFloat::cmpGreaterThan, dl,
  2166. VT, OpVT);
  2167. case ISD::SETLE: if (R==APFloat::cmpUnordered)
  2168. return getUNDEF(VT);
  2169. [[fallthrough]];
  2170. case ISD::SETOLE: return getBoolConstant(R==APFloat::cmpLessThan ||
  2171. R==APFloat::cmpEqual, dl, VT,
  2172. OpVT);
  2173. case ISD::SETGE: if (R==APFloat::cmpUnordered)
  2174. return getUNDEF(VT);
  2175. [[fallthrough]];
  2176. case ISD::SETOGE: return getBoolConstant(R==APFloat::cmpGreaterThan ||
  2177. R==APFloat::cmpEqual, dl, VT, OpVT);
  2178. case ISD::SETO: return getBoolConstant(R!=APFloat::cmpUnordered, dl, VT,
  2179. OpVT);
  2180. case ISD::SETUO: return getBoolConstant(R==APFloat::cmpUnordered, dl, VT,
  2181. OpVT);
  2182. case ISD::SETUEQ: return getBoolConstant(R==APFloat::cmpUnordered ||
  2183. R==APFloat::cmpEqual, dl, VT,
  2184. OpVT);
  2185. case ISD::SETUNE: return getBoolConstant(R!=APFloat::cmpEqual, dl, VT,
  2186. OpVT);
  2187. case ISD::SETULT: return getBoolConstant(R==APFloat::cmpUnordered ||
  2188. R==APFloat::cmpLessThan, dl, VT,
  2189. OpVT);
  2190. case ISD::SETUGT: return getBoolConstant(R==APFloat::cmpGreaterThan ||
  2191. R==APFloat::cmpUnordered, dl, VT,
  2192. OpVT);
  2193. case ISD::SETULE: return getBoolConstant(R!=APFloat::cmpGreaterThan, dl,
  2194. VT, OpVT);
  2195. case ISD::SETUGE: return getBoolConstant(R!=APFloat::cmpLessThan, dl, VT,
  2196. OpVT);
  2197. }
  2198. } else if (N1CFP && OpVT.isSimple() && !N2.isUndef()) {
  2199. // Ensure that the constant occurs on the RHS.
  2200. ISD::CondCode SwappedCond = ISD::getSetCCSwappedOperands(Cond);
  2201. if (!TLI->isCondCodeLegal(SwappedCond, OpVT.getSimpleVT()))
  2202. return SDValue();
  2203. return getSetCC(dl, VT, N2, N1, SwappedCond);
  2204. } else if ((N2CFP && N2CFP->getValueAPF().isNaN()) ||
  2205. (OpVT.isFloatingPoint() && (N1.isUndef() || N2.isUndef()))) {
  2206. // If an operand is known to be a nan (or undef that could be a nan), we can
  2207. // fold it.
  2208. // Choosing NaN for the undef will always make unordered comparison succeed
  2209. // and ordered comparison fails.
  2210. // Matches behavior in llvm::ConstantFoldCompareInstruction.
  2211. switch (ISD::getUnorderedFlavor(Cond)) {
  2212. default:
  2213. llvm_unreachable("Unknown flavor!");
  2214. case 0: // Known false.
  2215. return getBoolConstant(false, dl, VT, OpVT);
  2216. case 1: // Known true.
  2217. return getBoolConstant(true, dl, VT, OpVT);
  2218. case 2: // Undefined.
  2219. return getUNDEF(VT);
  2220. }
  2221. }
  2222. // Could not fold it.
  2223. return SDValue();
  2224. }
  2225. /// SignBitIsZero - Return true if the sign bit of Op is known to be zero. We
  2226. /// use this predicate to simplify operations downstream.
  2227. bool SelectionDAG::SignBitIsZero(SDValue Op, unsigned Depth) const {
  2228. unsigned BitWidth = Op.getScalarValueSizeInBits();
  2229. return MaskedValueIsZero(Op, APInt::getSignMask(BitWidth), Depth);
  2230. }
  2231. /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
  2232. /// this predicate to simplify operations downstream. Mask is known to be zero
  2233. /// for bits that V cannot have.
  2234. bool SelectionDAG::MaskedValueIsZero(SDValue V, const APInt &Mask,
  2235. unsigned Depth) const {
  2236. return Mask.isSubsetOf(computeKnownBits(V, Depth).Zero);
  2237. }
  2238. /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero in
  2239. /// DemandedElts. We use this predicate to simplify operations downstream.
  2240. /// Mask is known to be zero for bits that V cannot have.
  2241. bool SelectionDAG::MaskedValueIsZero(SDValue V, const APInt &Mask,
  2242. const APInt &DemandedElts,
  2243. unsigned Depth) const {
  2244. return Mask.isSubsetOf(computeKnownBits(V, DemandedElts, Depth).Zero);
  2245. }
  2246. /// MaskedVectorIsZero - Return true if 'Op' is known to be zero in
  2247. /// DemandedElts. We use this predicate to simplify operations downstream.
  2248. bool SelectionDAG::MaskedVectorIsZero(SDValue V, const APInt &DemandedElts,
  2249. unsigned Depth /* = 0 */) const {
  2250. return computeKnownBits(V, DemandedElts, Depth).isZero();
  2251. }
  2252. /// MaskedValueIsAllOnes - Return true if '(Op & Mask) == Mask'.
  2253. bool SelectionDAG::MaskedValueIsAllOnes(SDValue V, const APInt &Mask,
  2254. unsigned Depth) const {
  2255. return Mask.isSubsetOf(computeKnownBits(V, Depth).One);
  2256. }
  2257. APInt SelectionDAG::computeVectorKnownZeroElements(SDValue Op,
  2258. const APInt &DemandedElts,
  2259. unsigned Depth) const {
  2260. EVT VT = Op.getValueType();
  2261. assert(VT.isVector() && !VT.isScalableVector() && "Only for fixed vectors!");
  2262. unsigned NumElts = VT.getVectorNumElements();
  2263. assert(DemandedElts.getBitWidth() == NumElts && "Unexpected demanded mask.");
  2264. APInt KnownZeroElements = APInt::getNullValue(NumElts);
  2265. for (unsigned EltIdx = 0; EltIdx != NumElts; ++EltIdx) {
  2266. if (!DemandedElts[EltIdx])
  2267. continue; // Don't query elements that are not demanded.
  2268. APInt Mask = APInt::getOneBitSet(NumElts, EltIdx);
  2269. if (MaskedVectorIsZero(Op, Mask, Depth))
  2270. KnownZeroElements.setBit(EltIdx);
  2271. }
  2272. return KnownZeroElements;
  2273. }
  2274. /// isSplatValue - Return true if the vector V has the same value
  2275. /// across all DemandedElts. For scalable vectors, we don't know the
  2276. /// number of lanes at compile time. Instead, we use a 1 bit APInt
  2277. /// to represent a conservative value for all lanes; that is, that
  2278. /// one bit value is implicitly splatted across all lanes.
  2279. bool SelectionDAG::isSplatValue(SDValue V, const APInt &DemandedElts,
  2280. APInt &UndefElts, unsigned Depth) const {
  2281. unsigned Opcode = V.getOpcode();
  2282. EVT VT = V.getValueType();
  2283. assert(VT.isVector() && "Vector type expected");
  2284. assert((!VT.isScalableVector() || DemandedElts.getBitWidth() == 1) &&
  2285. "scalable demanded bits are ignored");
  2286. if (!DemandedElts)
  2287. return false; // No demanded elts, better to assume we don't know anything.
  2288. if (Depth >= MaxRecursionDepth)
  2289. return false; // Limit search depth.
  2290. // Deal with some common cases here that work for both fixed and scalable
  2291. // vector types.
  2292. switch (Opcode) {
  2293. case ISD::SPLAT_VECTOR:
  2294. UndefElts = V.getOperand(0).isUndef()
  2295. ? APInt::getAllOnes(DemandedElts.getBitWidth())
  2296. : APInt(DemandedElts.getBitWidth(), 0);
  2297. return true;
  2298. case ISD::ADD:
  2299. case ISD::SUB:
  2300. case ISD::AND:
  2301. case ISD::XOR:
  2302. case ISD::OR: {
  2303. APInt UndefLHS, UndefRHS;
  2304. SDValue LHS = V.getOperand(0);
  2305. SDValue RHS = V.getOperand(1);
  2306. if (isSplatValue(LHS, DemandedElts, UndefLHS, Depth + 1) &&
  2307. isSplatValue(RHS, DemandedElts, UndefRHS, Depth + 1)) {
  2308. UndefElts = UndefLHS | UndefRHS;
  2309. return true;
  2310. }
  2311. return false;
  2312. }
  2313. case ISD::ABS:
  2314. case ISD::TRUNCATE:
  2315. case ISD::SIGN_EXTEND:
  2316. case ISD::ZERO_EXTEND:
  2317. return isSplatValue(V.getOperand(0), DemandedElts, UndefElts, Depth + 1);
  2318. default:
  2319. if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::INTRINSIC_WO_CHAIN ||
  2320. Opcode == ISD::INTRINSIC_W_CHAIN || Opcode == ISD::INTRINSIC_VOID)
  2321. return TLI->isSplatValueForTargetNode(V, DemandedElts, UndefElts, *this,
  2322. Depth);
  2323. break;
  2324. }
  2325. // We don't support other cases than those above for scalable vectors at
  2326. // the moment.
  2327. if (VT.isScalableVector())
  2328. return false;
  2329. unsigned NumElts = VT.getVectorNumElements();
  2330. assert(NumElts == DemandedElts.getBitWidth() && "Vector size mismatch");
  2331. UndefElts = APInt::getZero(NumElts);
  2332. switch (Opcode) {
  2333. case ISD::BUILD_VECTOR: {
  2334. SDValue Scl;
  2335. for (unsigned i = 0; i != NumElts; ++i) {
  2336. SDValue Op = V.getOperand(i);
  2337. if (Op.isUndef()) {
  2338. UndefElts.setBit(i);
  2339. continue;
  2340. }
  2341. if (!DemandedElts[i])
  2342. continue;
  2343. if (Scl && Scl != Op)
  2344. return false;
  2345. Scl = Op;
  2346. }
  2347. return true;
  2348. }
  2349. case ISD::VECTOR_SHUFFLE: {
  2350. // Check if this is a shuffle node doing a splat or a shuffle of a splat.
  2351. APInt DemandedLHS = APInt::getNullValue(NumElts);
  2352. APInt DemandedRHS = APInt::getNullValue(NumElts);
  2353. ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(V)->getMask();
  2354. for (int i = 0; i != (int)NumElts; ++i) {
  2355. int M = Mask[i];
  2356. if (M < 0) {
  2357. UndefElts.setBit(i);
  2358. continue;
  2359. }
  2360. if (!DemandedElts[i])
  2361. continue;
  2362. if (M < (int)NumElts)
  2363. DemandedLHS.setBit(M);
  2364. else
  2365. DemandedRHS.setBit(M - NumElts);
  2366. }
  2367. // If we aren't demanding either op, assume there's no splat.
  2368. // If we are demanding both ops, assume there's no splat.
  2369. if ((DemandedLHS.isZero() && DemandedRHS.isZero()) ||
  2370. (!DemandedLHS.isZero() && !DemandedRHS.isZero()))
  2371. return false;
  2372. // See if the demanded elts of the source op is a splat or we only demand
  2373. // one element, which should always be a splat.
  2374. // TODO: Handle source ops splats with undefs.
  2375. auto CheckSplatSrc = [&](SDValue Src, const APInt &SrcElts) {
  2376. APInt SrcUndefs;
  2377. return (SrcElts.countPopulation() == 1) ||
  2378. (isSplatValue(Src, SrcElts, SrcUndefs, Depth + 1) &&
  2379. (SrcElts & SrcUndefs).isZero());
  2380. };
  2381. if (!DemandedLHS.isZero())
  2382. return CheckSplatSrc(V.getOperand(0), DemandedLHS);
  2383. return CheckSplatSrc(V.getOperand(1), DemandedRHS);
  2384. }
  2385. case ISD::EXTRACT_SUBVECTOR: {
  2386. // Offset the demanded elts by the subvector index.
  2387. SDValue Src = V.getOperand(0);
  2388. // We don't support scalable vectors at the moment.
  2389. if (Src.getValueType().isScalableVector())
  2390. return false;
  2391. uint64_t Idx = V.getConstantOperandVal(1);
  2392. unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
  2393. APInt UndefSrcElts;
  2394. APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx);
  2395. if (isSplatValue(Src, DemandedSrcElts, UndefSrcElts, Depth + 1)) {
  2396. UndefElts = UndefSrcElts.extractBits(NumElts, Idx);
  2397. return true;
  2398. }
  2399. break;
  2400. }
  2401. case ISD::ANY_EXTEND_VECTOR_INREG:
  2402. case ISD::SIGN_EXTEND_VECTOR_INREG:
  2403. case ISD::ZERO_EXTEND_VECTOR_INREG: {
  2404. // Widen the demanded elts by the src element count.
  2405. SDValue Src = V.getOperand(0);
  2406. // We don't support scalable vectors at the moment.
  2407. if (Src.getValueType().isScalableVector())
  2408. return false;
  2409. unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
  2410. APInt UndefSrcElts;
  2411. APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts);
  2412. if (isSplatValue(Src, DemandedSrcElts, UndefSrcElts, Depth + 1)) {
  2413. UndefElts = UndefSrcElts.trunc(NumElts);
  2414. return true;
  2415. }
  2416. break;
  2417. }
  2418. case ISD::BITCAST: {
  2419. SDValue Src = V.getOperand(0);
  2420. EVT SrcVT = Src.getValueType();
  2421. unsigned SrcBitWidth = SrcVT.getScalarSizeInBits();
  2422. unsigned BitWidth = VT.getScalarSizeInBits();
  2423. // Ignore bitcasts from unsupported types.
  2424. // TODO: Add fp support?
  2425. if (!SrcVT.isVector() || !SrcVT.isInteger() || !VT.isInteger())
  2426. break;
  2427. // Bitcast 'small element' vector to 'large element' vector.
  2428. if ((BitWidth % SrcBitWidth) == 0) {
  2429. // See if each sub element is a splat.
  2430. unsigned Scale = BitWidth / SrcBitWidth;
  2431. unsigned NumSrcElts = SrcVT.getVectorNumElements();
  2432. APInt ScaledDemandedElts =
  2433. APIntOps::ScaleBitMask(DemandedElts, NumSrcElts);
  2434. for (unsigned I = 0; I != Scale; ++I) {
  2435. APInt SubUndefElts;
  2436. APInt SubDemandedElt = APInt::getOneBitSet(Scale, I);
  2437. APInt SubDemandedElts = APInt::getSplat(NumSrcElts, SubDemandedElt);
  2438. SubDemandedElts &= ScaledDemandedElts;
  2439. if (!isSplatValue(Src, SubDemandedElts, SubUndefElts, Depth + 1))
  2440. return false;
  2441. // TODO: Add support for merging sub undef elements.
  2442. if (!SubUndefElts.isZero())
  2443. return false;
  2444. }
  2445. return true;
  2446. }
  2447. break;
  2448. }
  2449. }
  2450. return false;
  2451. }
  2452. /// Helper wrapper to main isSplatValue function.
  2453. bool SelectionDAG::isSplatValue(SDValue V, bool AllowUndefs) const {
  2454. EVT VT = V.getValueType();
  2455. assert(VT.isVector() && "Vector type expected");
  2456. APInt UndefElts;
  2457. // Since the number of lanes in a scalable vector is unknown at compile time,
  2458. // we track one bit which is implicitly broadcast to all lanes. This means
  2459. // that all lanes in a scalable vector are considered demanded.
  2460. APInt DemandedElts
  2461. = APInt::getAllOnes(VT.isScalableVector() ? 1 : VT.getVectorNumElements());
  2462. return isSplatValue(V, DemandedElts, UndefElts) &&
  2463. (AllowUndefs || !UndefElts);
  2464. }
  2465. SDValue SelectionDAG::getSplatSourceVector(SDValue V, int &SplatIdx) {
  2466. V = peekThroughExtractSubvectors(V);
  2467. EVT VT = V.getValueType();
  2468. unsigned Opcode = V.getOpcode();
  2469. switch (Opcode) {
  2470. default: {
  2471. APInt UndefElts;
  2472. // Since the number of lanes in a scalable vector is unknown at compile time,
  2473. // we track one bit which is implicitly broadcast to all lanes. This means
  2474. // that all lanes in a scalable vector are considered demanded.
  2475. APInt DemandedElts
  2476. = APInt::getAllOnes(VT.isScalableVector() ? 1 : VT.getVectorNumElements());
  2477. if (isSplatValue(V, DemandedElts, UndefElts)) {
  2478. if (VT.isScalableVector()) {
  2479. // DemandedElts and UndefElts are ignored for scalable vectors, since
  2480. // the only supported cases are SPLAT_VECTOR nodes.
  2481. SplatIdx = 0;
  2482. } else {
  2483. // Handle case where all demanded elements are UNDEF.
  2484. if (DemandedElts.isSubsetOf(UndefElts)) {
  2485. SplatIdx = 0;
  2486. return getUNDEF(VT);
  2487. }
  2488. SplatIdx = (UndefElts & DemandedElts).countTrailingOnes();
  2489. }
  2490. return V;
  2491. }
  2492. break;
  2493. }
  2494. case ISD::SPLAT_VECTOR:
  2495. SplatIdx = 0;
  2496. return V;
  2497. case ISD::VECTOR_SHUFFLE: {
  2498. assert(!VT.isScalableVector());
  2499. // Check if this is a shuffle node doing a splat.
  2500. // TODO - remove this and rely purely on SelectionDAG::isSplatValue,
  2501. // getTargetVShiftNode currently struggles without the splat source.
  2502. auto *SVN = cast<ShuffleVectorSDNode>(V);
  2503. if (!SVN->isSplat())
  2504. break;
  2505. int Idx = SVN->getSplatIndex();
  2506. int NumElts = V.getValueType().getVectorNumElements();
  2507. SplatIdx = Idx % NumElts;
  2508. return V.getOperand(Idx / NumElts);
  2509. }
  2510. }
  2511. return SDValue();
  2512. }
  2513. SDValue SelectionDAG::getSplatValue(SDValue V, bool LegalTypes) {
  2514. int SplatIdx;
  2515. if (SDValue SrcVector = getSplatSourceVector(V, SplatIdx)) {
  2516. EVT SVT = SrcVector.getValueType().getScalarType();
  2517. EVT LegalSVT = SVT;
  2518. if (LegalTypes && !TLI->isTypeLegal(SVT)) {
  2519. if (!SVT.isInteger())
  2520. return SDValue();
  2521. LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT);
  2522. if (LegalSVT.bitsLT(SVT))
  2523. return SDValue();
  2524. }
  2525. return getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(V), LegalSVT, SrcVector,
  2526. getVectorIdxConstant(SplatIdx, SDLoc(V)));
  2527. }
  2528. return SDValue();
  2529. }
  2530. const APInt *
  2531. SelectionDAG::getValidShiftAmountConstant(SDValue V,
  2532. const APInt &DemandedElts) const {
  2533. assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
  2534. V.getOpcode() == ISD::SRA) &&
  2535. "Unknown shift node");
  2536. unsigned BitWidth = V.getScalarValueSizeInBits();
  2537. if (ConstantSDNode *SA = isConstOrConstSplat(V.getOperand(1), DemandedElts)) {
  2538. // Shifting more than the bitwidth is not valid.
  2539. const APInt &ShAmt = SA->getAPIntValue();
  2540. if (ShAmt.ult(BitWidth))
  2541. return &ShAmt;
  2542. }
  2543. return nullptr;
  2544. }
  2545. const APInt *SelectionDAG::getValidMinimumShiftAmountConstant(
  2546. SDValue V, const APInt &DemandedElts) const {
  2547. assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
  2548. V.getOpcode() == ISD::SRA) &&
  2549. "Unknown shift node");
  2550. if (const APInt *ValidAmt = getValidShiftAmountConstant(V, DemandedElts))
  2551. return ValidAmt;
  2552. unsigned BitWidth = V.getScalarValueSizeInBits();
  2553. auto *BV = dyn_cast<BuildVectorSDNode>(V.getOperand(1));
  2554. if (!BV)
  2555. return nullptr;
  2556. const APInt *MinShAmt = nullptr;
  2557. for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
  2558. if (!DemandedElts[i])
  2559. continue;
  2560. auto *SA = dyn_cast<ConstantSDNode>(BV->getOperand(i));
  2561. if (!SA)
  2562. return nullptr;
  2563. // Shifting more than the bitwidth is not valid.
  2564. const APInt &ShAmt = SA->getAPIntValue();
  2565. if (ShAmt.uge(BitWidth))
  2566. return nullptr;
  2567. if (MinShAmt && MinShAmt->ule(ShAmt))
  2568. continue;
  2569. MinShAmt = &ShAmt;
  2570. }
  2571. return MinShAmt;
  2572. }
  2573. const APInt *SelectionDAG::getValidMaximumShiftAmountConstant(
  2574. SDValue V, const APInt &DemandedElts) const {
  2575. assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
  2576. V.getOpcode() == ISD::SRA) &&
  2577. "Unknown shift node");
  2578. if (const APInt *ValidAmt = getValidShiftAmountConstant(V, DemandedElts))
  2579. return ValidAmt;
  2580. unsigned BitWidth = V.getScalarValueSizeInBits();
  2581. auto *BV = dyn_cast<BuildVectorSDNode>(V.getOperand(1));
  2582. if (!BV)
  2583. return nullptr;
  2584. const APInt *MaxShAmt = nullptr;
  2585. for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
  2586. if (!DemandedElts[i])
  2587. continue;
  2588. auto *SA = dyn_cast<ConstantSDNode>(BV->getOperand(i));
  2589. if (!SA)
  2590. return nullptr;
  2591. // Shifting more than the bitwidth is not valid.
  2592. const APInt &ShAmt = SA->getAPIntValue();
  2593. if (ShAmt.uge(BitWidth))
  2594. return nullptr;
  2595. if (MaxShAmt && MaxShAmt->uge(ShAmt))
  2596. continue;
  2597. MaxShAmt = &ShAmt;
  2598. }
  2599. return MaxShAmt;
  2600. }
  2601. /// Determine which bits of Op are known to be either zero or one and return
  2602. /// them in Known. For vectors, the known bits are those that are shared by
  2603. /// every vector element.
  2604. KnownBits SelectionDAG::computeKnownBits(SDValue Op, unsigned Depth) const {
  2605. EVT VT = Op.getValueType();
  2606. // Since the number of lanes in a scalable vector is unknown at compile time,
  2607. // we track one bit which is implicitly broadcast to all lanes. This means
  2608. // that all lanes in a scalable vector are considered demanded.
  2609. APInt DemandedElts = VT.isFixedLengthVector()
  2610. ? APInt::getAllOnes(VT.getVectorNumElements())
  2611. : APInt(1, 1);
  2612. return computeKnownBits(Op, DemandedElts, Depth);
  2613. }
  2614. /// Determine which bits of Op are known to be either zero or one and return
  2615. /// them in Known. The DemandedElts argument allows us to only collect the known
  2616. /// bits that are shared by the requested vector elements.
  2617. KnownBits SelectionDAG::computeKnownBits(SDValue Op, const APInt &DemandedElts,
  2618. unsigned Depth) const {
  2619. unsigned BitWidth = Op.getScalarValueSizeInBits();
  2620. KnownBits Known(BitWidth); // Don't know anything.
  2621. if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
  2622. // We know all of the bits for a constant!
  2623. return KnownBits::makeConstant(C->getAPIntValue());
  2624. }
  2625. if (auto *C = dyn_cast<ConstantFPSDNode>(Op)) {
  2626. // We know all of the bits for a constant fp!
  2627. return KnownBits::makeConstant(C->getValueAPF().bitcastToAPInt());
  2628. }
  2629. if (Depth >= MaxRecursionDepth)
  2630. return Known; // Limit search depth.
  2631. KnownBits Known2;
  2632. unsigned NumElts = DemandedElts.getBitWidth();
  2633. assert((!Op.getValueType().isFixedLengthVector() ||
  2634. NumElts == Op.getValueType().getVectorNumElements()) &&
  2635. "Unexpected vector size");
  2636. if (!DemandedElts)
  2637. return Known; // No demanded elts, better to assume we don't know anything.
  2638. unsigned Opcode = Op.getOpcode();
  2639. switch (Opcode) {
  2640. case ISD::MERGE_VALUES:
  2641. return computeKnownBits(Op.getOperand(Op.getResNo()), DemandedElts,
  2642. Depth + 1);
  2643. case ISD::SPLAT_VECTOR: {
  2644. SDValue SrcOp = Op.getOperand(0);
  2645. assert(SrcOp.getValueSizeInBits() >= BitWidth &&
  2646. "Expected SPLAT_VECTOR implicit truncation");
  2647. // Implicitly truncate the bits to match the official semantics of
  2648. // SPLAT_VECTOR.
  2649. Known = computeKnownBits(SrcOp, Depth + 1).trunc(BitWidth);
  2650. break;
  2651. }
  2652. case ISD::BUILD_VECTOR:
  2653. assert(!Op.getValueType().isScalableVector());
  2654. // Collect the known bits that are shared by every demanded vector element.
  2655. Known.Zero.setAllBits(); Known.One.setAllBits();
  2656. for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
  2657. if (!DemandedElts[i])
  2658. continue;
  2659. SDValue SrcOp = Op.getOperand(i);
  2660. Known2 = computeKnownBits(SrcOp, Depth + 1);
  2661. // BUILD_VECTOR can implicitly truncate sources, we must handle this.
  2662. if (SrcOp.getValueSizeInBits() != BitWidth) {
  2663. assert(SrcOp.getValueSizeInBits() > BitWidth &&
  2664. "Expected BUILD_VECTOR implicit truncation");
  2665. Known2 = Known2.trunc(BitWidth);
  2666. }
  2667. // Known bits are the values that are shared by every demanded element.
  2668. Known = KnownBits::commonBits(Known, Known2);
  2669. // If we don't know any bits, early out.
  2670. if (Known.isUnknown())
  2671. break;
  2672. }
  2673. break;
  2674. case ISD::VECTOR_SHUFFLE: {
  2675. assert(!Op.getValueType().isScalableVector());
  2676. // Collect the known bits that are shared by every vector element referenced
  2677. // by the shuffle.
  2678. APInt DemandedLHS, DemandedRHS;
  2679. const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
  2680. assert(NumElts == SVN->getMask().size() && "Unexpected vector size");
  2681. if (!getShuffleDemandedElts(NumElts, SVN->getMask(), DemandedElts,
  2682. DemandedLHS, DemandedRHS))
  2683. break;
  2684. // Known bits are the values that are shared by every demanded element.
  2685. Known.Zero.setAllBits(); Known.One.setAllBits();
  2686. if (!!DemandedLHS) {
  2687. SDValue LHS = Op.getOperand(0);
  2688. Known2 = computeKnownBits(LHS, DemandedLHS, Depth + 1);
  2689. Known = KnownBits::commonBits(Known, Known2);
  2690. }
  2691. // If we don't know any bits, early out.
  2692. if (Known.isUnknown())
  2693. break;
  2694. if (!!DemandedRHS) {
  2695. SDValue RHS = Op.getOperand(1);
  2696. Known2 = computeKnownBits(RHS, DemandedRHS, Depth + 1);
  2697. Known = KnownBits::commonBits(Known, Known2);
  2698. }
  2699. break;
  2700. }
  2701. case ISD::CONCAT_VECTORS: {
  2702. if (Op.getValueType().isScalableVector())
  2703. break;
  2704. // Split DemandedElts and test each of the demanded subvectors.
  2705. Known.Zero.setAllBits(); Known.One.setAllBits();
  2706. EVT SubVectorVT = Op.getOperand(0).getValueType();
  2707. unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements();
  2708. unsigned NumSubVectors = Op.getNumOperands();
  2709. for (unsigned i = 0; i != NumSubVectors; ++i) {
  2710. APInt DemandedSub =
  2711. DemandedElts.extractBits(NumSubVectorElts, i * NumSubVectorElts);
  2712. if (!!DemandedSub) {
  2713. SDValue Sub = Op.getOperand(i);
  2714. Known2 = computeKnownBits(Sub, DemandedSub, Depth + 1);
  2715. Known = KnownBits::commonBits(Known, Known2);
  2716. }
  2717. // If we don't know any bits, early out.
  2718. if (Known.isUnknown())
  2719. break;
  2720. }
  2721. break;
  2722. }
  2723. case ISD::INSERT_SUBVECTOR: {
  2724. if (Op.getValueType().isScalableVector())
  2725. break;
  2726. // Demand any elements from the subvector and the remainder from the src its
  2727. // inserted into.
  2728. SDValue Src = Op.getOperand(0);
  2729. SDValue Sub = Op.getOperand(1);
  2730. uint64_t Idx = Op.getConstantOperandVal(2);
  2731. unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
  2732. APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
  2733. APInt DemandedSrcElts = DemandedElts;
  2734. DemandedSrcElts.insertBits(APInt::getZero(NumSubElts), Idx);
  2735. Known.One.setAllBits();
  2736. Known.Zero.setAllBits();
  2737. if (!!DemandedSubElts) {
  2738. Known = computeKnownBits(Sub, DemandedSubElts, Depth + 1);
  2739. if (Known.isUnknown())
  2740. break; // early-out.
  2741. }
  2742. if (!!DemandedSrcElts) {
  2743. Known2 = computeKnownBits(Src, DemandedSrcElts, Depth + 1);
  2744. Known = KnownBits::commonBits(Known, Known2);
  2745. }
  2746. break;
  2747. }
  2748. case ISD::EXTRACT_SUBVECTOR: {
  2749. // Offset the demanded elts by the subvector index.
  2750. SDValue Src = Op.getOperand(0);
  2751. // Bail until we can represent demanded elements for scalable vectors.
  2752. if (Op.getValueType().isScalableVector() || Src.getValueType().isScalableVector())
  2753. break;
  2754. uint64_t Idx = Op.getConstantOperandVal(1);
  2755. unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
  2756. APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx);
  2757. Known = computeKnownBits(Src, DemandedSrcElts, Depth + 1);
  2758. break;
  2759. }
  2760. case ISD::SCALAR_TO_VECTOR: {
  2761. if (Op.getValueType().isScalableVector())
  2762. break;
  2763. // We know about scalar_to_vector as much as we know about it source,
  2764. // which becomes the first element of otherwise unknown vector.
  2765. if (DemandedElts != 1)
  2766. break;
  2767. SDValue N0 = Op.getOperand(0);
  2768. Known = computeKnownBits(N0, Depth + 1);
  2769. if (N0.getValueSizeInBits() != BitWidth)
  2770. Known = Known.trunc(BitWidth);
  2771. break;
  2772. }
  2773. case ISD::BITCAST: {
  2774. if (Op.getValueType().isScalableVector())
  2775. break;
  2776. SDValue N0 = Op.getOperand(0);
  2777. EVT SubVT = N0.getValueType();
  2778. unsigned SubBitWidth = SubVT.getScalarSizeInBits();
  2779. // Ignore bitcasts from unsupported types.
  2780. if (!(SubVT.isInteger() || SubVT.isFloatingPoint()))
  2781. break;
  2782. // Fast handling of 'identity' bitcasts.
  2783. if (BitWidth == SubBitWidth) {
  2784. Known = computeKnownBits(N0, DemandedElts, Depth + 1);
  2785. break;
  2786. }
  2787. bool IsLE = getDataLayout().isLittleEndian();
  2788. // Bitcast 'small element' vector to 'large element' scalar/vector.
  2789. if ((BitWidth % SubBitWidth) == 0) {
  2790. assert(N0.getValueType().isVector() && "Expected bitcast from vector");
  2791. // Collect known bits for the (larger) output by collecting the known
  2792. // bits from each set of sub elements and shift these into place.
  2793. // We need to separately call computeKnownBits for each set of
  2794. // sub elements as the knownbits for each is likely to be different.
  2795. unsigned SubScale = BitWidth / SubBitWidth;
  2796. APInt SubDemandedElts(NumElts * SubScale, 0);
  2797. for (unsigned i = 0; i != NumElts; ++i)
  2798. if (DemandedElts[i])
  2799. SubDemandedElts.setBit(i * SubScale);
  2800. for (unsigned i = 0; i != SubScale; ++i) {
  2801. Known2 = computeKnownBits(N0, SubDemandedElts.shl(i),
  2802. Depth + 1);
  2803. unsigned Shifts = IsLE ? i : SubScale - 1 - i;
  2804. Known.insertBits(Known2, SubBitWidth * Shifts);
  2805. }
  2806. }
  2807. // Bitcast 'large element' scalar/vector to 'small element' vector.
  2808. if ((SubBitWidth % BitWidth) == 0) {
  2809. assert(Op.getValueType().isVector() && "Expected bitcast to vector");
  2810. // Collect known bits for the (smaller) output by collecting the known
  2811. // bits from the overlapping larger input elements and extracting the
  2812. // sub sections we actually care about.
  2813. unsigned SubScale = SubBitWidth / BitWidth;
  2814. APInt SubDemandedElts =
  2815. APIntOps::ScaleBitMask(DemandedElts, NumElts / SubScale);
  2816. Known2 = computeKnownBits(N0, SubDemandedElts, Depth + 1);
  2817. Known.Zero.setAllBits(); Known.One.setAllBits();
  2818. for (unsigned i = 0; i != NumElts; ++i)
  2819. if (DemandedElts[i]) {
  2820. unsigned Shifts = IsLE ? i : NumElts - 1 - i;
  2821. unsigned Offset = (Shifts % SubScale) * BitWidth;
  2822. Known = KnownBits::commonBits(Known,
  2823. Known2.extractBits(BitWidth, Offset));
  2824. // If we don't know any bits, early out.
  2825. if (Known.isUnknown())
  2826. break;
  2827. }
  2828. }
  2829. break;
  2830. }
  2831. case ISD::AND:
  2832. Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
  2833. Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
  2834. Known &= Known2;
  2835. break;
  2836. case ISD::OR:
  2837. Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
  2838. Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
  2839. Known |= Known2;
  2840. break;
  2841. case ISD::XOR:
  2842. Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
  2843. Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
  2844. Known ^= Known2;
  2845. break;
  2846. case ISD::MUL: {
  2847. Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
  2848. Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
  2849. bool SelfMultiply = Op.getOperand(0) == Op.getOperand(1);
  2850. // TODO: SelfMultiply can be poison, but not undef.
  2851. if (SelfMultiply)
  2852. SelfMultiply &= isGuaranteedNotToBeUndefOrPoison(
  2853. Op.getOperand(0), DemandedElts, false, Depth + 1);
  2854. Known = KnownBits::mul(Known, Known2, SelfMultiply);
  2855. // If the multiplication is known not to overflow, the product of a number
  2856. // with itself is non-negative. Only do this if we didn't already computed
  2857. // the opposite value for the sign bit.
  2858. if (Op->getFlags().hasNoSignedWrap() &&
  2859. Op.getOperand(0) == Op.getOperand(1) &&
  2860. !Known.isNegative())
  2861. Known.makeNonNegative();
  2862. break;
  2863. }
  2864. case ISD::MULHU: {
  2865. Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
  2866. Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
  2867. Known = KnownBits::mulhu(Known, Known2);
  2868. break;
  2869. }
  2870. case ISD::MULHS: {
  2871. Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
  2872. Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
  2873. Known = KnownBits::mulhs(Known, Known2);
  2874. break;
  2875. }
  2876. case ISD::UMUL_LOHI: {
  2877. assert((Op.getResNo() == 0 || Op.getResNo() == 1) && "Unknown result");
  2878. Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
  2879. Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
  2880. bool SelfMultiply = Op.getOperand(0) == Op.getOperand(1);
  2881. if (Op.getResNo() == 0)
  2882. Known = KnownBits::mul(Known, Known2, SelfMultiply);
  2883. else
  2884. Known = KnownBits::mulhu(Known, Known2);
  2885. break;
  2886. }
  2887. case ISD::SMUL_LOHI: {
  2888. assert((Op.getResNo() == 0 || Op.getResNo() == 1) && "Unknown result");
  2889. Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
  2890. Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
  2891. bool SelfMultiply = Op.getOperand(0) == Op.getOperand(1);
  2892. if (Op.getResNo() == 0)
  2893. Known = KnownBits::mul(Known, Known2, SelfMultiply);
  2894. else
  2895. Known = KnownBits::mulhs(Known, Known2);
  2896. break;
  2897. }
  2898. case ISD::AVGCEILU: {
  2899. Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
  2900. Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
  2901. Known = Known.zext(BitWidth + 1);
  2902. Known2 = Known2.zext(BitWidth + 1);
  2903. KnownBits One = KnownBits::makeConstant(APInt(1, 1));
  2904. Known = KnownBits::computeForAddCarry(Known, Known2, One);
  2905. Known = Known.extractBits(BitWidth, 1);
  2906. break;
  2907. }
  2908. case ISD::SELECT:
  2909. case ISD::VSELECT:
  2910. Known = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1);
  2911. // If we don't know any bits, early out.
  2912. if (Known.isUnknown())
  2913. break;
  2914. Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth+1);
  2915. // Only known if known in both the LHS and RHS.
  2916. Known = KnownBits::commonBits(Known, Known2);
  2917. break;
  2918. case ISD::SELECT_CC:
  2919. Known = computeKnownBits(Op.getOperand(3), DemandedElts, Depth+1);
  2920. // If we don't know any bits, early out.
  2921. if (Known.isUnknown())
  2922. break;
  2923. Known2 = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1);
  2924. // Only known if known in both the LHS and RHS.
  2925. Known = KnownBits::commonBits(Known, Known2);
  2926. break;
  2927. case ISD::SMULO:
  2928. case ISD::UMULO:
  2929. if (Op.getResNo() != 1)
  2930. break;
  2931. // The boolean result conforms to getBooleanContents.
  2932. // If we know the result of a setcc has the top bits zero, use this info.
  2933. // We know that we have an integer-based boolean since these operations
  2934. // are only available for integer.
  2935. if (TLI->getBooleanContents(Op.getValueType().isVector(), false) ==
  2936. TargetLowering::ZeroOrOneBooleanContent &&
  2937. BitWidth > 1)
  2938. Known.Zero.setBitsFrom(1);
  2939. break;
  2940. case ISD::SETCC:
  2941. case ISD::SETCCCARRY:
  2942. case ISD::STRICT_FSETCC:
  2943. case ISD::STRICT_FSETCCS: {
  2944. unsigned OpNo = Op->isStrictFPOpcode() ? 1 : 0;
  2945. // If we know the result of a setcc has the top bits zero, use this info.
  2946. if (TLI->getBooleanContents(Op.getOperand(OpNo).getValueType()) ==
  2947. TargetLowering::ZeroOrOneBooleanContent &&
  2948. BitWidth > 1)
  2949. Known.Zero.setBitsFrom(1);
  2950. break;
  2951. }
  2952. case ISD::SHL:
  2953. Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
  2954. Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
  2955. Known = KnownBits::shl(Known, Known2);
  2956. // Minimum shift low bits are known zero.
  2957. if (const APInt *ShMinAmt =
  2958. getValidMinimumShiftAmountConstant(Op, DemandedElts))
  2959. Known.Zero.setLowBits(ShMinAmt->getZExtValue());
  2960. break;
  2961. case ISD::SRL:
  2962. Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
  2963. Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
  2964. Known = KnownBits::lshr(Known, Known2);
  2965. // Minimum shift high bits are known zero.
  2966. if (const APInt *ShMinAmt =
  2967. getValidMinimumShiftAmountConstant(Op, DemandedElts))
  2968. Known.Zero.setHighBits(ShMinAmt->getZExtValue());
  2969. break;
  2970. case ISD::SRA:
  2971. Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
  2972. Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
  2973. Known = KnownBits::ashr(Known, Known2);
  2974. // TODO: Add minimum shift high known sign bits.
  2975. break;
  2976. case ISD::FSHL:
  2977. case ISD::FSHR:
  2978. if (ConstantSDNode *C = isConstOrConstSplat(Op.getOperand(2), DemandedElts)) {
  2979. unsigned Amt = C->getAPIntValue().urem(BitWidth);
  2980. // For fshl, 0-shift returns the 1st arg.
  2981. // For fshr, 0-shift returns the 2nd arg.
  2982. if (Amt == 0) {
  2983. Known = computeKnownBits(Op.getOperand(Opcode == ISD::FSHL ? 0 : 1),
  2984. DemandedElts, Depth + 1);
  2985. break;
  2986. }
  2987. // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW)))
  2988. // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW))
  2989. Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
  2990. Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
  2991. if (Opcode == ISD::FSHL) {
  2992. Known.One <<= Amt;
  2993. Known.Zero <<= Amt;
  2994. Known2.One.lshrInPlace(BitWidth - Amt);
  2995. Known2.Zero.lshrInPlace(BitWidth - Amt);
  2996. } else {
  2997. Known.One <<= BitWidth - Amt;
  2998. Known.Zero <<= BitWidth - Amt;
  2999. Known2.One.lshrInPlace(Amt);
  3000. Known2.Zero.lshrInPlace(Amt);
  3001. }
  3002. Known.One |= Known2.One;
  3003. Known.Zero |= Known2.Zero;
  3004. }
  3005. break;
  3006. case ISD::SHL_PARTS:
  3007. case ISD::SRA_PARTS:
  3008. case ISD::SRL_PARTS: {
  3009. assert((Op.getResNo() == 0 || Op.getResNo() == 1) && "Unknown result");
  3010. // Collect lo/hi source values and concatenate.
  3011. unsigned LoBits = Op.getOperand(0).getScalarValueSizeInBits();
  3012. unsigned HiBits = Op.getOperand(1).getScalarValueSizeInBits();
  3013. Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
  3014. Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
  3015. Known = Known2.concat(Known);
  3016. // Collect shift amount.
  3017. Known2 = computeKnownBits(Op.getOperand(2), DemandedElts, Depth + 1);
  3018. if (Opcode == ISD::SHL_PARTS)
  3019. Known = KnownBits::shl(Known, Known2);
  3020. else if (Opcode == ISD::SRA_PARTS)
  3021. Known = KnownBits::ashr(Known, Known2);
  3022. else // if (Opcode == ISD::SRL_PARTS)
  3023. Known = KnownBits::lshr(Known, Known2);
  3024. // TODO: Minimum shift low/high bits are known zero.
  3025. if (Op.getResNo() == 0)
  3026. Known = Known.extractBits(LoBits, 0);
  3027. else
  3028. Known = Known.extractBits(HiBits, LoBits);
  3029. break;
  3030. }
  3031. case ISD::SIGN_EXTEND_INREG: {
  3032. Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
  3033. EVT EVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
  3034. Known = Known.sextInReg(EVT.getScalarSizeInBits());
  3035. break;
  3036. }
  3037. case ISD::CTTZ:
  3038. case ISD::CTTZ_ZERO_UNDEF: {
  3039. Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
  3040. // If we have a known 1, its position is our upper bound.
  3041. unsigned PossibleTZ = Known2.countMaxTrailingZeros();
  3042. unsigned LowBits = llvm::bit_width(PossibleTZ);
  3043. Known.Zero.setBitsFrom(LowBits);
  3044. break;
  3045. }
  3046. case ISD::CTLZ:
  3047. case ISD::CTLZ_ZERO_UNDEF: {
  3048. Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
  3049. // If we have a known 1, its position is our upper bound.
  3050. unsigned PossibleLZ = Known2.countMaxLeadingZeros();
  3051. unsigned LowBits = llvm::bit_width(PossibleLZ);
  3052. Known.Zero.setBitsFrom(LowBits);
  3053. break;
  3054. }
  3055. case ISD::CTPOP: {
  3056. Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
  3057. // If we know some of the bits are zero, they can't be one.
  3058. unsigned PossibleOnes = Known2.countMaxPopulation();
  3059. Known.Zero.setBitsFrom(llvm::bit_width(PossibleOnes));
  3060. break;
  3061. }
  3062. case ISD::PARITY: {
  3063. // Parity returns 0 everywhere but the LSB.
  3064. Known.Zero.setBitsFrom(1);
  3065. break;
  3066. }
  3067. case ISD::LOAD: {
  3068. LoadSDNode *LD = cast<LoadSDNode>(Op);
  3069. const Constant *Cst = TLI->getTargetConstantFromLoad(LD);
  3070. if (ISD::isNON_EXTLoad(LD) && Cst) {
  3071. // Determine any common known bits from the loaded constant pool value.
  3072. Type *CstTy = Cst->getType();
  3073. if ((NumElts * BitWidth) == CstTy->getPrimitiveSizeInBits() &&
  3074. !Op.getValueType().isScalableVector()) {
  3075. // If its a vector splat, then we can (quickly) reuse the scalar path.
  3076. // NOTE: We assume all elements match and none are UNDEF.
  3077. if (CstTy->isVectorTy()) {
  3078. if (const Constant *Splat = Cst->getSplatValue()) {
  3079. Cst = Splat;
  3080. CstTy = Cst->getType();
  3081. }
  3082. }
  3083. // TODO - do we need to handle different bitwidths?
  3084. if (CstTy->isVectorTy() && BitWidth == CstTy->getScalarSizeInBits()) {
  3085. // Iterate across all vector elements finding common known bits.
  3086. Known.One.setAllBits();
  3087. Known.Zero.setAllBits();
  3088. for (unsigned i = 0; i != NumElts; ++i) {
  3089. if (!DemandedElts[i])
  3090. continue;
  3091. if (Constant *Elt = Cst->getAggregateElement(i)) {
  3092. if (auto *CInt = dyn_cast<ConstantInt>(Elt)) {
  3093. const APInt &Value = CInt->getValue();
  3094. Known.One &= Value;
  3095. Known.Zero &= ~Value;
  3096. continue;
  3097. }
  3098. if (auto *CFP = dyn_cast<ConstantFP>(Elt)) {
  3099. APInt Value = CFP->getValueAPF().bitcastToAPInt();
  3100. Known.One &= Value;
  3101. Known.Zero &= ~Value;
  3102. continue;
  3103. }
  3104. }
  3105. Known.One.clearAllBits();
  3106. Known.Zero.clearAllBits();
  3107. break;
  3108. }
  3109. } else if (BitWidth == CstTy->getPrimitiveSizeInBits()) {
  3110. if (auto *CInt = dyn_cast<ConstantInt>(Cst)) {
  3111. Known = KnownBits::makeConstant(CInt->getValue());
  3112. } else if (auto *CFP = dyn_cast<ConstantFP>(Cst)) {
  3113. Known =
  3114. KnownBits::makeConstant(CFP->getValueAPF().bitcastToAPInt());
  3115. }
  3116. }
  3117. }
  3118. } else if (ISD::isZEXTLoad(Op.getNode()) && Op.getResNo() == 0) {
  3119. // If this is a ZEXTLoad and we are looking at the loaded value.
  3120. EVT VT = LD->getMemoryVT();
  3121. unsigned MemBits = VT.getScalarSizeInBits();
  3122. Known.Zero.setBitsFrom(MemBits);
  3123. } else if (const MDNode *Ranges = LD->getRanges()) {
  3124. EVT VT = LD->getValueType(0);
  3125. // TODO: Handle for extending loads
  3126. if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
  3127. if (VT.isVector()) {
  3128. // Handle truncation to the first demanded element.
  3129. // TODO: Figure out which demanded elements are covered
  3130. if (DemandedElts != 1 || !getDataLayout().isLittleEndian())
  3131. break;
  3132. // Handle the case where a load has a vector type, but scalar memory
  3133. // with an attached range.
  3134. EVT MemVT = LD->getMemoryVT();
  3135. KnownBits KnownFull(MemVT.getSizeInBits());
  3136. computeKnownBitsFromRangeMetadata(*Ranges, KnownFull);
  3137. Known = KnownFull.trunc(BitWidth);
  3138. } else
  3139. computeKnownBitsFromRangeMetadata(*Ranges, Known);
  3140. }
  3141. }
  3142. break;
  3143. }
  3144. case ISD::ZERO_EXTEND_VECTOR_INREG: {
  3145. if (Op.getValueType().isScalableVector())
  3146. break;
  3147. EVT InVT = Op.getOperand(0).getValueType();
  3148. APInt InDemandedElts = DemandedElts.zext(InVT.getVectorNumElements());
  3149. Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
  3150. Known = Known.zext(BitWidth);
  3151. break;
  3152. }
  3153. case ISD::ZERO_EXTEND: {
  3154. Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
  3155. Known = Known.zext(BitWidth);
  3156. break;
  3157. }
  3158. case ISD::SIGN_EXTEND_VECTOR_INREG: {
  3159. if (Op.getValueType().isScalableVector())
  3160. break;
  3161. EVT InVT = Op.getOperand(0).getValueType();
  3162. APInt InDemandedElts = DemandedElts.zext(InVT.getVectorNumElements());
  3163. Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
  3164. // If the sign bit is known to be zero or one, then sext will extend
  3165. // it to the top bits, else it will just zext.
  3166. Known = Known.sext(BitWidth);
  3167. break;
  3168. }
  3169. case ISD::SIGN_EXTEND: {
  3170. Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
  3171. // If the sign bit is known to be zero or one, then sext will extend
  3172. // it to the top bits, else it will just zext.
  3173. Known = Known.sext(BitWidth);
  3174. break;
  3175. }
  3176. case ISD::ANY_EXTEND_VECTOR_INREG: {
  3177. if (Op.getValueType().isScalableVector())
  3178. break;
  3179. EVT InVT = Op.getOperand(0).getValueType();
  3180. APInt InDemandedElts = DemandedElts.zext(InVT.getVectorNumElements());
  3181. Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
  3182. Known = Known.anyext(BitWidth);
  3183. break;
  3184. }
  3185. case ISD::ANY_EXTEND: {
  3186. Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
  3187. Known = Known.anyext(BitWidth);
  3188. break;
  3189. }
  3190. case ISD::TRUNCATE: {
  3191. Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
  3192. Known = Known.trunc(BitWidth);
  3193. break;
  3194. }
  3195. case ISD::AssertZext: {
  3196. EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
  3197. APInt InMask = APInt::getLowBitsSet(BitWidth, VT.getSizeInBits());
  3198. Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
  3199. Known.Zero |= (~InMask);
  3200. Known.One &= (~Known.Zero);
  3201. break;
  3202. }
  3203. case ISD::AssertAlign: {
  3204. unsigned LogOfAlign = Log2(cast<AssertAlignSDNode>(Op)->getAlign());
  3205. assert(LogOfAlign != 0);
  3206. // TODO: Should use maximum with source
  3207. // If a node is guaranteed to be aligned, set low zero bits accordingly as
  3208. // well as clearing one bits.
  3209. Known.Zero.setLowBits(LogOfAlign);
  3210. Known.One.clearLowBits(LogOfAlign);
  3211. break;
  3212. }
  3213. case ISD::FGETSIGN:
  3214. // All bits are zero except the low bit.
  3215. Known.Zero.setBitsFrom(1);
  3216. break;
  3217. case ISD::USUBO:
  3218. case ISD::SSUBO:
  3219. case ISD::SUBCARRY:
  3220. case ISD::SSUBO_CARRY:
  3221. if (Op.getResNo() == 1) {
  3222. // If we know the result of a setcc has the top bits zero, use this info.
  3223. if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
  3224. TargetLowering::ZeroOrOneBooleanContent &&
  3225. BitWidth > 1)
  3226. Known.Zero.setBitsFrom(1);
  3227. break;
  3228. }
  3229. [[fallthrough]];
  3230. case ISD::SUB:
  3231. case ISD::SUBC: {
  3232. assert(Op.getResNo() == 0 &&
  3233. "We only compute knownbits for the difference here.");
  3234. // TODO: Compute influence of the carry operand.
  3235. if (Opcode == ISD::SUBCARRY || Opcode == ISD::SSUBO_CARRY)
  3236. break;
  3237. Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
  3238. Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
  3239. Known = KnownBits::computeForAddSub(/* Add */ false, /* NSW */ false,
  3240. Known, Known2);
  3241. break;
  3242. }
  3243. case ISD::UADDO:
  3244. case ISD::SADDO:
  3245. case ISD::ADDCARRY:
  3246. case ISD::SADDO_CARRY:
  3247. if (Op.getResNo() == 1) {
  3248. // If we know the result of a setcc has the top bits zero, use this info.
  3249. if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
  3250. TargetLowering::ZeroOrOneBooleanContent &&
  3251. BitWidth > 1)
  3252. Known.Zero.setBitsFrom(1);
  3253. break;
  3254. }
  3255. [[fallthrough]];
  3256. case ISD::ADD:
  3257. case ISD::ADDC:
  3258. case ISD::ADDE: {
  3259. assert(Op.getResNo() == 0 && "We only compute knownbits for the sum here.");
  3260. // With ADDE and ADDCARRY, a carry bit may be added in.
  3261. KnownBits Carry(1);
  3262. if (Opcode == ISD::ADDE)
  3263. // Can't track carry from glue, set carry to unknown.
  3264. Carry.resetAll();
  3265. else if (Opcode == ISD::ADDCARRY || Opcode == ISD::SADDO_CARRY)
  3266. // TODO: Compute known bits for the carry operand. Not sure if it is worth
  3267. // the trouble (how often will we find a known carry bit). And I haven't
  3268. // tested this very much yet, but something like this might work:
  3269. // Carry = computeKnownBits(Op.getOperand(2), DemandedElts, Depth + 1);
  3270. // Carry = Carry.zextOrTrunc(1, false);
  3271. Carry.resetAll();
  3272. else
  3273. Carry.setAllZero();
  3274. Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
  3275. Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
  3276. Known = KnownBits::computeForAddCarry(Known, Known2, Carry);
  3277. break;
  3278. }
  3279. case ISD::UDIV: {
  3280. Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
  3281. Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
  3282. Known = KnownBits::udiv(Known, Known2);
  3283. break;
  3284. }
  3285. case ISD::SREM: {
  3286. Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
  3287. Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
  3288. Known = KnownBits::srem(Known, Known2);
  3289. break;
  3290. }
  3291. case ISD::UREM: {
  3292. Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
  3293. Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
  3294. Known = KnownBits::urem(Known, Known2);
  3295. break;
  3296. }
  3297. case ISD::EXTRACT_ELEMENT: {
  3298. Known = computeKnownBits(Op.getOperand(0), Depth+1);
  3299. const unsigned Index = Op.getConstantOperandVal(1);
  3300. const unsigned EltBitWidth = Op.getValueSizeInBits();
  3301. // Remove low part of known bits mask
  3302. Known.Zero = Known.Zero.getHiBits(Known.getBitWidth() - Index * EltBitWidth);
  3303. Known.One = Known.One.getHiBits(Known.getBitWidth() - Index * EltBitWidth);
  3304. // Remove high part of known bit mask
  3305. Known = Known.trunc(EltBitWidth);
  3306. break;
  3307. }
  3308. case ISD::EXTRACT_VECTOR_ELT: {
  3309. SDValue InVec = Op.getOperand(0);
  3310. SDValue EltNo = Op.getOperand(1);
  3311. EVT VecVT = InVec.getValueType();
  3312. // computeKnownBits not yet implemented for scalable vectors.
  3313. if (VecVT.isScalableVector())
  3314. break;
  3315. const unsigned EltBitWidth = VecVT.getScalarSizeInBits();
  3316. const unsigned NumSrcElts = VecVT.getVectorNumElements();
  3317. // If BitWidth > EltBitWidth the value is anyext:ed. So we do not know
  3318. // anything about the extended bits.
  3319. if (BitWidth > EltBitWidth)
  3320. Known = Known.trunc(EltBitWidth);
  3321. // If we know the element index, just demand that vector element, else for
  3322. // an unknown element index, ignore DemandedElts and demand them all.
  3323. APInt DemandedSrcElts = APInt::getAllOnes(NumSrcElts);
  3324. auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
  3325. if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts))
  3326. DemandedSrcElts =
  3327. APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue());
  3328. Known = computeKnownBits(InVec, DemandedSrcElts, Depth + 1);
  3329. if (BitWidth > EltBitWidth)
  3330. Known = Known.anyext(BitWidth);
  3331. break;
  3332. }
  3333. case ISD::INSERT_VECTOR_ELT: {
  3334. if (Op.getValueType().isScalableVector())
  3335. break;
  3336. // If we know the element index, split the demand between the
  3337. // source vector and the inserted element, otherwise assume we need
  3338. // the original demanded vector elements and the value.
  3339. SDValue InVec = Op.getOperand(0);
  3340. SDValue InVal = Op.getOperand(1);
  3341. SDValue EltNo = Op.getOperand(2);
  3342. bool DemandedVal = true;
  3343. APInt DemandedVecElts = DemandedElts;
  3344. auto *CEltNo = dyn_cast<ConstantSDNode>(EltNo);
  3345. if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) {
  3346. unsigned EltIdx = CEltNo->getZExtValue();
  3347. DemandedVal = !!DemandedElts[EltIdx];
  3348. DemandedVecElts.clearBit(EltIdx);
  3349. }
  3350. Known.One.setAllBits();
  3351. Known.Zero.setAllBits();
  3352. if (DemandedVal) {
  3353. Known2 = computeKnownBits(InVal, Depth + 1);
  3354. Known = KnownBits::commonBits(Known, Known2.zextOrTrunc(BitWidth));
  3355. }
  3356. if (!!DemandedVecElts) {
  3357. Known2 = computeKnownBits(InVec, DemandedVecElts, Depth + 1);
  3358. Known = KnownBits::commonBits(Known, Known2);
  3359. }
  3360. break;
  3361. }
  3362. case ISD::BITREVERSE: {
  3363. Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
  3364. Known = Known2.reverseBits();
  3365. break;
  3366. }
  3367. case ISD::BSWAP: {
  3368. Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
  3369. Known = Known2.byteSwap();
  3370. break;
  3371. }
  3372. case ISD::ABS: {
  3373. Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
  3374. Known = Known2.abs();
  3375. break;
  3376. }
  3377. case ISD::USUBSAT: {
  3378. // The result of usubsat will never be larger than the LHS.
  3379. Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
  3380. Known.Zero.setHighBits(Known2.countMinLeadingZeros());
  3381. break;
  3382. }
  3383. case ISD::UMIN: {
  3384. Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
  3385. Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
  3386. Known = KnownBits::umin(Known, Known2);
  3387. break;
  3388. }
  3389. case ISD::UMAX: {
  3390. Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
  3391. Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
  3392. Known = KnownBits::umax(Known, Known2);
  3393. break;
  3394. }
  3395. case ISD::SMIN:
  3396. case ISD::SMAX: {
  3397. // If we have a clamp pattern, we know that the number of sign bits will be
  3398. // the minimum of the clamp min/max range.
  3399. bool IsMax = (Opcode == ISD::SMAX);
  3400. ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr;
  3401. if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts)))
  3402. if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX))
  3403. CstHigh =
  3404. isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts);
  3405. if (CstLow && CstHigh) {
  3406. if (!IsMax)
  3407. std::swap(CstLow, CstHigh);
  3408. const APInt &ValueLow = CstLow->getAPIntValue();
  3409. const APInt &ValueHigh = CstHigh->getAPIntValue();
  3410. if (ValueLow.sle(ValueHigh)) {
  3411. unsigned LowSignBits = ValueLow.getNumSignBits();
  3412. unsigned HighSignBits = ValueHigh.getNumSignBits();
  3413. unsigned MinSignBits = std::min(LowSignBits, HighSignBits);
  3414. if (ValueLow.isNegative() && ValueHigh.isNegative()) {
  3415. Known.One.setHighBits(MinSignBits);
  3416. break;
  3417. }
  3418. if (ValueLow.isNonNegative() && ValueHigh.isNonNegative()) {
  3419. Known.Zero.setHighBits(MinSignBits);
  3420. break;
  3421. }
  3422. }
  3423. }
  3424. Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
  3425. Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
  3426. if (IsMax)
  3427. Known = KnownBits::smax(Known, Known2);
  3428. else
  3429. Known = KnownBits::smin(Known, Known2);
  3430. // For SMAX, if CstLow is non-negative we know the result will be
  3431. // non-negative and thus all sign bits are 0.
  3432. // TODO: There's an equivalent of this for smin with negative constant for
  3433. // known ones.
  3434. if (IsMax && CstLow) {
  3435. const APInt &ValueLow = CstLow->getAPIntValue();
  3436. if (ValueLow.isNonNegative()) {
  3437. unsigned SignBits = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
  3438. Known.Zero.setHighBits(std::min(SignBits, ValueLow.getNumSignBits()));
  3439. }
  3440. }
  3441. break;
  3442. }
  3443. case ISD::FP_TO_UINT_SAT: {
  3444. // FP_TO_UINT_SAT produces an unsigned value that fits in the saturating VT.
  3445. EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
  3446. Known.Zero |= APInt::getBitsSetFrom(BitWidth, VT.getScalarSizeInBits());
  3447. break;
  3448. }
  3449. case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
  3450. if (Op.getResNo() == 1) {
  3451. // The boolean result conforms to getBooleanContents.
  3452. // If we know the result of a setcc has the top bits zero, use this info.
  3453. // We know that we have an integer-based boolean since these operations
  3454. // are only available for integer.
  3455. if (TLI->getBooleanContents(Op.getValueType().isVector(), false) ==
  3456. TargetLowering::ZeroOrOneBooleanContent &&
  3457. BitWidth > 1)
  3458. Known.Zero.setBitsFrom(1);
  3459. break;
  3460. }
  3461. [[fallthrough]];
  3462. case ISD::ATOMIC_CMP_SWAP:
  3463. case ISD::ATOMIC_SWAP:
  3464. case ISD::ATOMIC_LOAD_ADD:
  3465. case ISD::ATOMIC_LOAD_SUB:
  3466. case ISD::ATOMIC_LOAD_AND:
  3467. case ISD::ATOMIC_LOAD_CLR:
  3468. case ISD::ATOMIC_LOAD_OR:
  3469. case ISD::ATOMIC_LOAD_XOR:
  3470. case ISD::ATOMIC_LOAD_NAND:
  3471. case ISD::ATOMIC_LOAD_MIN:
  3472. case ISD::ATOMIC_LOAD_MAX:
  3473. case ISD::ATOMIC_LOAD_UMIN:
  3474. case ISD::ATOMIC_LOAD_UMAX:
  3475. case ISD::ATOMIC_LOAD: {
  3476. unsigned MemBits =
  3477. cast<AtomicSDNode>(Op)->getMemoryVT().getScalarSizeInBits();
  3478. // If we are looking at the loaded value.
  3479. if (Op.getResNo() == 0) {
  3480. if (TLI->getExtendForAtomicOps() == ISD::ZERO_EXTEND)
  3481. Known.Zero.setBitsFrom(MemBits);
  3482. }
  3483. break;
  3484. }
  3485. case ISD::FrameIndex:
  3486. case ISD::TargetFrameIndex:
  3487. TLI->computeKnownBitsForFrameIndex(cast<FrameIndexSDNode>(Op)->getIndex(),
  3488. Known, getMachineFunction());
  3489. break;
  3490. default:
  3491. if (Opcode < ISD::BUILTIN_OP_END)
  3492. break;
  3493. [[fallthrough]];
  3494. case ISD::INTRINSIC_WO_CHAIN:
  3495. case ISD::INTRINSIC_W_CHAIN:
  3496. case ISD::INTRINSIC_VOID:
  3497. // TODO: Probably okay to remove after audit; here to reduce change size
  3498. // in initial enablement patch for scalable vectors
  3499. if (Op.getValueType().isScalableVector())
  3500. break;
  3501. // Allow the target to implement this method for its nodes.
  3502. TLI->computeKnownBitsForTargetNode(Op, Known, DemandedElts, *this, Depth);
  3503. break;
  3504. }
  3505. assert(!Known.hasConflict() && "Bits known to be one AND zero?");
  3506. return Known;
  3507. }
  3508. SelectionDAG::OverflowKind SelectionDAG::computeOverflowKind(SDValue N0,
  3509. SDValue N1) const {
  3510. // X + 0 never overflow
  3511. if (isNullConstant(N1))
  3512. return OFK_Never;
  3513. KnownBits N1Known = computeKnownBits(N1);
  3514. if (N1Known.Zero.getBoolValue()) {
  3515. KnownBits N0Known = computeKnownBits(N0);
  3516. bool overflow;
  3517. (void)N0Known.getMaxValue().uadd_ov(N1Known.getMaxValue(), overflow);
  3518. if (!overflow)
  3519. return OFK_Never;
  3520. }
  3521. // mulhi + 1 never overflow
  3522. if (N0.getOpcode() == ISD::UMUL_LOHI && N0.getResNo() == 1 &&
  3523. (N1Known.getMaxValue() & 0x01) == N1Known.getMaxValue())
  3524. return OFK_Never;
  3525. if (N1.getOpcode() == ISD::UMUL_LOHI && N1.getResNo() == 1) {
  3526. KnownBits N0Known = computeKnownBits(N0);
  3527. if ((N0Known.getMaxValue() & 0x01) == N0Known.getMaxValue())
  3528. return OFK_Never;
  3529. }
  3530. return OFK_Sometime;
  3531. }
  3532. bool SelectionDAG::isKnownToBeAPowerOfTwo(SDValue Val) const {
  3533. EVT OpVT = Val.getValueType();
  3534. unsigned BitWidth = OpVT.getScalarSizeInBits();
  3535. // Is the constant a known power of 2?
  3536. if (ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Val))
  3537. return Const->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2();
  3538. // A left-shift of a constant one will have exactly one bit set because
  3539. // shifting the bit off the end is undefined.
  3540. if (Val.getOpcode() == ISD::SHL) {
  3541. auto *C = isConstOrConstSplat(Val.getOperand(0));
  3542. if (C && C->getAPIntValue() == 1)
  3543. return true;
  3544. }
  3545. // Similarly, a logical right-shift of a constant sign-bit will have exactly
  3546. // one bit set.
  3547. if (Val.getOpcode() == ISD::SRL) {
  3548. auto *C = isConstOrConstSplat(Val.getOperand(0));
  3549. if (C && C->getAPIntValue().isSignMask())
  3550. return true;
  3551. }
  3552. // Are all operands of a build vector constant powers of two?
  3553. if (Val.getOpcode() == ISD::BUILD_VECTOR)
  3554. if (llvm::all_of(Val->ops(), [BitWidth](SDValue E) {
  3555. if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(E))
  3556. return C->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2();
  3557. return false;
  3558. }))
  3559. return true;
  3560. // Is the operand of a splat vector a constant power of two?
  3561. if (Val.getOpcode() == ISD::SPLAT_VECTOR)
  3562. if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val->getOperand(0)))
  3563. if (C->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2())
  3564. return true;
  3565. // vscale(power-of-two) is a power-of-two for some targets
  3566. if (Val.getOpcode() == ISD::VSCALE &&
  3567. getTargetLoweringInfo().isVScaleKnownToBeAPowerOfTwo() &&
  3568. isKnownToBeAPowerOfTwo(Val.getOperand(0)))
  3569. return true;
  3570. // More could be done here, though the above checks are enough
  3571. // to handle some common cases.
  3572. // Fall back to computeKnownBits to catch other known cases.
  3573. KnownBits Known = computeKnownBits(Val);
  3574. return (Known.countMaxPopulation() == 1) && (Known.countMinPopulation() == 1);
  3575. }
  3576. unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, unsigned Depth) const {
  3577. EVT VT = Op.getValueType();
  3578. // Since the number of lanes in a scalable vector is unknown at compile time,
  3579. // we track one bit which is implicitly broadcast to all lanes. This means
  3580. // that all lanes in a scalable vector are considered demanded.
  3581. APInt DemandedElts = VT.isFixedLengthVector()
  3582. ? APInt::getAllOnes(VT.getVectorNumElements())
  3583. : APInt(1, 1);
  3584. return ComputeNumSignBits(Op, DemandedElts, Depth);
  3585. }
  3586. unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, const APInt &DemandedElts,
  3587. unsigned Depth) const {
  3588. EVT VT = Op.getValueType();
  3589. assert((VT.isInteger() || VT.isFloatingPoint()) && "Invalid VT!");
  3590. unsigned VTBits = VT.getScalarSizeInBits();
  3591. unsigned NumElts = DemandedElts.getBitWidth();
  3592. unsigned Tmp, Tmp2;
  3593. unsigned FirstAnswer = 1;
  3594. if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
  3595. const APInt &Val = C->getAPIntValue();
  3596. return Val.getNumSignBits();
  3597. }
  3598. if (Depth >= MaxRecursionDepth)
  3599. return 1; // Limit search depth.
  3600. if (!DemandedElts)
  3601. return 1; // No demanded elts, better to assume we don't know anything.
  3602. unsigned Opcode = Op.getOpcode();
  3603. switch (Opcode) {
  3604. default: break;
  3605. case ISD::AssertSext:
  3606. Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
  3607. return VTBits-Tmp+1;
  3608. case ISD::AssertZext:
  3609. Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
  3610. return VTBits-Tmp;
  3611. case ISD::MERGE_VALUES:
  3612. return ComputeNumSignBits(Op.getOperand(Op.getResNo()), DemandedElts,
  3613. Depth + 1);
  3614. case ISD::SPLAT_VECTOR: {
  3615. // Check if the sign bits of source go down as far as the truncated value.
  3616. unsigned NumSrcBits = Op.getOperand(0).getValueSizeInBits();
  3617. unsigned NumSrcSignBits = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
  3618. if (NumSrcSignBits > (NumSrcBits - VTBits))
  3619. return NumSrcSignBits - (NumSrcBits - VTBits);
  3620. break;
  3621. }
  3622. case ISD::BUILD_VECTOR:
  3623. assert(!VT.isScalableVector());
  3624. Tmp = VTBits;
  3625. for (unsigned i = 0, e = Op.getNumOperands(); (i < e) && (Tmp > 1); ++i) {
  3626. if (!DemandedElts[i])
  3627. continue;
  3628. SDValue SrcOp = Op.getOperand(i);
  3629. Tmp2 = ComputeNumSignBits(SrcOp, Depth + 1);
  3630. // BUILD_VECTOR can implicitly truncate sources, we must handle this.
  3631. if (SrcOp.getValueSizeInBits() != VTBits) {
  3632. assert(SrcOp.getValueSizeInBits() > VTBits &&
  3633. "Expected BUILD_VECTOR implicit truncation");
  3634. unsigned ExtraBits = SrcOp.getValueSizeInBits() - VTBits;
  3635. Tmp2 = (Tmp2 > ExtraBits ? Tmp2 - ExtraBits : 1);
  3636. }
  3637. Tmp = std::min(Tmp, Tmp2);
  3638. }
  3639. return Tmp;
  3640. case ISD::VECTOR_SHUFFLE: {
  3641. // Collect the minimum number of sign bits that are shared by every vector
  3642. // element referenced by the shuffle.
  3643. APInt DemandedLHS, DemandedRHS;
  3644. const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
  3645. assert(NumElts == SVN->getMask().size() && "Unexpected vector size");
  3646. if (!getShuffleDemandedElts(NumElts, SVN->getMask(), DemandedElts,
  3647. DemandedLHS, DemandedRHS))
  3648. return 1;
  3649. Tmp = std::numeric_limits<unsigned>::max();
  3650. if (!!DemandedLHS)
  3651. Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedLHS, Depth + 1);
  3652. if (!!DemandedRHS) {
  3653. Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedRHS, Depth + 1);
  3654. Tmp = std::min(Tmp, Tmp2);
  3655. }
  3656. // If we don't know anything, early out and try computeKnownBits fall-back.
  3657. if (Tmp == 1)
  3658. break;
  3659. assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
  3660. return Tmp;
  3661. }
  3662. case ISD::BITCAST: {
  3663. if (VT.isScalableVector())
  3664. break;
  3665. SDValue N0 = Op.getOperand(0);
  3666. EVT SrcVT = N0.getValueType();
  3667. unsigned SrcBits = SrcVT.getScalarSizeInBits();
  3668. // Ignore bitcasts from unsupported types..
  3669. if (!(SrcVT.isInteger() || SrcVT.isFloatingPoint()))
  3670. break;
  3671. // Fast handling of 'identity' bitcasts.
  3672. if (VTBits == SrcBits)
  3673. return ComputeNumSignBits(N0, DemandedElts, Depth + 1);
  3674. bool IsLE = getDataLayout().isLittleEndian();
  3675. // Bitcast 'large element' scalar/vector to 'small element' vector.
  3676. if ((SrcBits % VTBits) == 0) {
  3677. assert(VT.isVector() && "Expected bitcast to vector");
  3678. unsigned Scale = SrcBits / VTBits;
  3679. APInt SrcDemandedElts =
  3680. APIntOps::ScaleBitMask(DemandedElts, NumElts / Scale);
  3681. // Fast case - sign splat can be simply split across the small elements.
  3682. Tmp = ComputeNumSignBits(N0, SrcDemandedElts, Depth + 1);
  3683. if (Tmp == SrcBits)
  3684. return VTBits;
  3685. // Slow case - determine how far the sign extends into each sub-element.
  3686. Tmp2 = VTBits;
  3687. for (unsigned i = 0; i != NumElts; ++i)
  3688. if (DemandedElts[i]) {
  3689. unsigned SubOffset = i % Scale;
  3690. SubOffset = (IsLE ? ((Scale - 1) - SubOffset) : SubOffset);
  3691. SubOffset = SubOffset * VTBits;
  3692. if (Tmp <= SubOffset)
  3693. return 1;
  3694. Tmp2 = std::min(Tmp2, Tmp - SubOffset);
  3695. }
  3696. return Tmp2;
  3697. }
  3698. break;
  3699. }
  3700. case ISD::FP_TO_SINT_SAT:
  3701. // FP_TO_SINT_SAT produces a signed value that fits in the saturating VT.
  3702. Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getScalarSizeInBits();
  3703. return VTBits - Tmp + 1;
  3704. case ISD::SIGN_EXTEND:
  3705. Tmp = VTBits - Op.getOperand(0).getScalarValueSizeInBits();
  3706. return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1) + Tmp;
  3707. case ISD::SIGN_EXTEND_INREG:
  3708. // Max of the input and what this extends.
  3709. Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getScalarSizeInBits();
  3710. Tmp = VTBits-Tmp+1;
  3711. Tmp2 = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1);
  3712. return std::max(Tmp, Tmp2);
  3713. case ISD::SIGN_EXTEND_VECTOR_INREG: {
  3714. if (VT.isScalableVector())
  3715. break;
  3716. SDValue Src = Op.getOperand(0);
  3717. EVT SrcVT = Src.getValueType();
  3718. APInt DemandedSrcElts = DemandedElts.zext(SrcVT.getVectorNumElements());
  3719. Tmp = VTBits - SrcVT.getScalarSizeInBits();
  3720. return ComputeNumSignBits(Src, DemandedSrcElts, Depth+1) + Tmp;
  3721. }
  3722. case ISD::SRA:
  3723. Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
  3724. // SRA X, C -> adds C sign bits.
  3725. if (const APInt *ShAmt =
  3726. getValidMinimumShiftAmountConstant(Op, DemandedElts))
  3727. Tmp = std::min<uint64_t>(Tmp + ShAmt->getZExtValue(), VTBits);
  3728. return Tmp;
  3729. case ISD::SHL:
  3730. if (const APInt *ShAmt =
  3731. getValidMaximumShiftAmountConstant(Op, DemandedElts)) {
  3732. // shl destroys sign bits, ensure it doesn't shift out all sign bits.
  3733. Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
  3734. if (ShAmt->ult(Tmp))
  3735. return Tmp - ShAmt->getZExtValue();
  3736. }
  3737. break;
  3738. case ISD::AND:
  3739. case ISD::OR:
  3740. case ISD::XOR: // NOT is handled here.
  3741. // Logical binary ops preserve the number of sign bits at the worst.
  3742. Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1);
  3743. if (Tmp != 1) {
  3744. Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1);
  3745. FirstAnswer = std::min(Tmp, Tmp2);
  3746. // We computed what we know about the sign bits as our first
  3747. // answer. Now proceed to the generic code that uses
  3748. // computeKnownBits, and pick whichever answer is better.
  3749. }
  3750. break;
  3751. case ISD::SELECT:
  3752. case ISD::VSELECT:
  3753. Tmp = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1);
  3754. if (Tmp == 1) return 1; // Early out.
  3755. Tmp2 = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1);
  3756. return std::min(Tmp, Tmp2);
  3757. case ISD::SELECT_CC:
  3758. Tmp = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1);
  3759. if (Tmp == 1) return 1; // Early out.
  3760. Tmp2 = ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth+1);
  3761. return std::min(Tmp, Tmp2);
  3762. case ISD::SMIN:
  3763. case ISD::SMAX: {
  3764. // If we have a clamp pattern, we know that the number of sign bits will be
  3765. // the minimum of the clamp min/max range.
  3766. bool IsMax = (Opcode == ISD::SMAX);
  3767. ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr;
  3768. if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts)))
  3769. if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX))
  3770. CstHigh =
  3771. isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts);
  3772. if (CstLow && CstHigh) {
  3773. if (!IsMax)
  3774. std::swap(CstLow, CstHigh);
  3775. if (CstLow->getAPIntValue().sle(CstHigh->getAPIntValue())) {
  3776. Tmp = CstLow->getAPIntValue().getNumSignBits();
  3777. Tmp2 = CstHigh->getAPIntValue().getNumSignBits();
  3778. return std::min(Tmp, Tmp2);
  3779. }
  3780. }
  3781. // Fallback - just get the minimum number of sign bits of the operands.
  3782. Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
  3783. if (Tmp == 1)
  3784. return 1; // Early out.
  3785. Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
  3786. return std::min(Tmp, Tmp2);
  3787. }
  3788. case ISD::UMIN:
  3789. case ISD::UMAX:
  3790. Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
  3791. if (Tmp == 1)
  3792. return 1; // Early out.
  3793. Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
  3794. return std::min(Tmp, Tmp2);
  3795. case ISD::SADDO:
  3796. case ISD::UADDO:
  3797. case ISD::SADDO_CARRY:
  3798. case ISD::ADDCARRY:
  3799. case ISD::SSUBO:
  3800. case ISD::USUBO:
  3801. case ISD::SSUBO_CARRY:
  3802. case ISD::SUBCARRY:
  3803. case ISD::SMULO:
  3804. case ISD::UMULO:
  3805. if (Op.getResNo() != 1)
  3806. break;
  3807. // The boolean result conforms to getBooleanContents. Fall through.
  3808. // If setcc returns 0/-1, all bits are sign bits.
  3809. // We know that we have an integer-based boolean since these operations
  3810. // are only available for integer.
  3811. if (TLI->getBooleanContents(VT.isVector(), false) ==
  3812. TargetLowering::ZeroOrNegativeOneBooleanContent)
  3813. return VTBits;
  3814. break;
  3815. case ISD::SETCC:
  3816. case ISD::SETCCCARRY:
  3817. case ISD::STRICT_FSETCC:
  3818. case ISD::STRICT_FSETCCS: {
  3819. unsigned OpNo = Op->isStrictFPOpcode() ? 1 : 0;
  3820. // If setcc returns 0/-1, all bits are sign bits.
  3821. if (TLI->getBooleanContents(Op.getOperand(OpNo).getValueType()) ==
  3822. TargetLowering::ZeroOrNegativeOneBooleanContent)
  3823. return VTBits;
  3824. break;
  3825. }
  3826. case ISD::ROTL:
  3827. case ISD::ROTR:
  3828. Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
  3829. // If we're rotating an 0/-1 value, then it stays an 0/-1 value.
  3830. if (Tmp == VTBits)
  3831. return VTBits;
  3832. if (ConstantSDNode *C =
  3833. isConstOrConstSplat(Op.getOperand(1), DemandedElts)) {
  3834. unsigned RotAmt = C->getAPIntValue().urem(VTBits);
  3835. // Handle rotate right by N like a rotate left by 32-N.
  3836. if (Opcode == ISD::ROTR)
  3837. RotAmt = (VTBits - RotAmt) % VTBits;
  3838. // If we aren't rotating out all of the known-in sign bits, return the
  3839. // number that are left. This handles rotl(sext(x), 1) for example.
  3840. if (Tmp > (RotAmt + 1)) return (Tmp - RotAmt);
  3841. }
  3842. break;
  3843. case ISD::ADD:
  3844. case ISD::ADDC:
  3845. // Add can have at most one carry bit. Thus we know that the output
  3846. // is, at worst, one more bit than the inputs.
  3847. Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
  3848. if (Tmp == 1) return 1; // Early out.
  3849. // Special case decrementing a value (ADD X, -1):
  3850. if (ConstantSDNode *CRHS =
  3851. isConstOrConstSplat(Op.getOperand(1), DemandedElts))
  3852. if (CRHS->isAllOnes()) {
  3853. KnownBits Known =
  3854. computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
  3855. // If the input is known to be 0 or 1, the output is 0/-1, which is all
  3856. // sign bits set.
  3857. if ((Known.Zero | 1).isAllOnes())
  3858. return VTBits;
  3859. // If we are subtracting one from a positive number, there is no carry
  3860. // out of the result.
  3861. if (Known.isNonNegative())
  3862. return Tmp;
  3863. }
  3864. Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
  3865. if (Tmp2 == 1) return 1; // Early out.
  3866. return std::min(Tmp, Tmp2) - 1;
  3867. case ISD::SUB:
  3868. Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
  3869. if (Tmp2 == 1) return 1; // Early out.
  3870. // Handle NEG.
  3871. if (ConstantSDNode *CLHS =
  3872. isConstOrConstSplat(Op.getOperand(0), DemandedElts))
  3873. if (CLHS->isZero()) {
  3874. KnownBits Known =
  3875. computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
  3876. // If the input is known to be 0 or 1, the output is 0/-1, which is all
  3877. // sign bits set.
  3878. if ((Known.Zero | 1).isAllOnes())
  3879. return VTBits;
  3880. // If the input is known to be positive (the sign bit is known clear),
  3881. // the output of the NEG has the same number of sign bits as the input.
  3882. if (Known.isNonNegative())
  3883. return Tmp2;
  3884. // Otherwise, we treat this like a SUB.
  3885. }
  3886. // Sub can have at most one carry bit. Thus we know that the output
  3887. // is, at worst, one more bit than the inputs.
  3888. Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
  3889. if (Tmp == 1) return 1; // Early out.
  3890. return std::min(Tmp, Tmp2) - 1;
  3891. case ISD::MUL: {
  3892. // The output of the Mul can be at most twice the valid bits in the inputs.
  3893. unsigned SignBitsOp0 = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
  3894. if (SignBitsOp0 == 1)
  3895. break;
  3896. unsigned SignBitsOp1 = ComputeNumSignBits(Op.getOperand(1), Depth + 1);
  3897. if (SignBitsOp1 == 1)
  3898. break;
  3899. unsigned OutValidBits =
  3900. (VTBits - SignBitsOp0 + 1) + (VTBits - SignBitsOp1 + 1);
  3901. return OutValidBits > VTBits ? 1 : VTBits - OutValidBits + 1;
  3902. }
  3903. case ISD::SREM:
  3904. // The sign bit is the LHS's sign bit, except when the result of the
  3905. // remainder is zero. The magnitude of the result should be less than or
  3906. // equal to the magnitude of the LHS. Therefore, the result should have
  3907. // at least as many sign bits as the left hand side.
  3908. return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
  3909. case ISD::TRUNCATE: {
  3910. // Check if the sign bits of source go down as far as the truncated value.
  3911. unsigned NumSrcBits = Op.getOperand(0).getScalarValueSizeInBits();
  3912. unsigned NumSrcSignBits = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
  3913. if (NumSrcSignBits > (NumSrcBits - VTBits))
  3914. return NumSrcSignBits - (NumSrcBits - VTBits);
  3915. break;
  3916. }
  3917. case ISD::EXTRACT_ELEMENT: {
  3918. if (VT.isScalableVector())
  3919. break;
  3920. const int KnownSign = ComputeNumSignBits(Op.getOperand(0), Depth+1);
  3921. const int BitWidth = Op.getValueSizeInBits();
  3922. const int Items = Op.getOperand(0).getValueSizeInBits() / BitWidth;
  3923. // Get reverse index (starting from 1), Op1 value indexes elements from
  3924. // little end. Sign starts at big end.
  3925. const int rIndex = Items - 1 - Op.getConstantOperandVal(1);
  3926. // If the sign portion ends in our element the subtraction gives correct
  3927. // result. Otherwise it gives either negative or > bitwidth result
  3928. return std::clamp(KnownSign - rIndex * BitWidth, 0, BitWidth);
  3929. }
  3930. case ISD::INSERT_VECTOR_ELT: {
  3931. if (VT.isScalableVector())
  3932. break;
  3933. // If we know the element index, split the demand between the
  3934. // source vector and the inserted element, otherwise assume we need
  3935. // the original demanded vector elements and the value.
  3936. SDValue InVec = Op.getOperand(0);
  3937. SDValue InVal = Op.getOperand(1);
  3938. SDValue EltNo = Op.getOperand(2);
  3939. bool DemandedVal = true;
  3940. APInt DemandedVecElts = DemandedElts;
  3941. auto *CEltNo = dyn_cast<ConstantSDNode>(EltNo);
  3942. if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) {
  3943. unsigned EltIdx = CEltNo->getZExtValue();
  3944. DemandedVal = !!DemandedElts[EltIdx];
  3945. DemandedVecElts.clearBit(EltIdx);
  3946. }
  3947. Tmp = std::numeric_limits<unsigned>::max();
  3948. if (DemandedVal) {
  3949. // TODO - handle implicit truncation of inserted elements.
  3950. if (InVal.getScalarValueSizeInBits() != VTBits)
  3951. break;
  3952. Tmp2 = ComputeNumSignBits(InVal, Depth + 1);
  3953. Tmp = std::min(Tmp, Tmp2);
  3954. }
  3955. if (!!DemandedVecElts) {
  3956. Tmp2 = ComputeNumSignBits(InVec, DemandedVecElts, Depth + 1);
  3957. Tmp = std::min(Tmp, Tmp2);
  3958. }
  3959. assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
  3960. return Tmp;
  3961. }
  3962. case ISD::EXTRACT_VECTOR_ELT: {
  3963. assert(!VT.isScalableVector());
  3964. SDValue InVec = Op.getOperand(0);
  3965. SDValue EltNo = Op.getOperand(1);
  3966. EVT VecVT = InVec.getValueType();
  3967. // ComputeNumSignBits not yet implemented for scalable vectors.
  3968. if (VecVT.isScalableVector())
  3969. break;
  3970. const unsigned BitWidth = Op.getValueSizeInBits();
  3971. const unsigned EltBitWidth = Op.getOperand(0).getScalarValueSizeInBits();
  3972. const unsigned NumSrcElts = VecVT.getVectorNumElements();
  3973. // If BitWidth > EltBitWidth the value is anyext:ed, and we do not know
  3974. // anything about sign bits. But if the sizes match we can derive knowledge
  3975. // about sign bits from the vector operand.
  3976. if (BitWidth != EltBitWidth)
  3977. break;
  3978. // If we know the element index, just demand that vector element, else for
  3979. // an unknown element index, ignore DemandedElts and demand them all.
  3980. APInt DemandedSrcElts = APInt::getAllOnes(NumSrcElts);
  3981. auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
  3982. if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts))
  3983. DemandedSrcElts =
  3984. APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue());
  3985. return ComputeNumSignBits(InVec, DemandedSrcElts, Depth + 1);
  3986. }
  3987. case ISD::EXTRACT_SUBVECTOR: {
  3988. // Offset the demanded elts by the subvector index.
  3989. SDValue Src = Op.getOperand(0);
  3990. // Bail until we can represent demanded elements for scalable vectors.
  3991. if (Src.getValueType().isScalableVector())
  3992. break;
  3993. uint64_t Idx = Op.getConstantOperandVal(1);
  3994. unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
  3995. APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx);
  3996. return ComputeNumSignBits(Src, DemandedSrcElts, Depth + 1);
  3997. }
  3998. case ISD::CONCAT_VECTORS: {
  3999. if (VT.isScalableVector())
  4000. break;
  4001. // Determine the minimum number of sign bits across all demanded
  4002. // elts of the input vectors. Early out if the result is already 1.
  4003. Tmp = std::numeric_limits<unsigned>::max();
  4004. EVT SubVectorVT = Op.getOperand(0).getValueType();
  4005. unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements();
  4006. unsigned NumSubVectors = Op.getNumOperands();
  4007. for (unsigned i = 0; (i < NumSubVectors) && (Tmp > 1); ++i) {
  4008. APInt DemandedSub =
  4009. DemandedElts.extractBits(NumSubVectorElts, i * NumSubVectorElts);
  4010. if (!DemandedSub)
  4011. continue;
  4012. Tmp2 = ComputeNumSignBits(Op.getOperand(i), DemandedSub, Depth + 1);
  4013. Tmp = std::min(Tmp, Tmp2);
  4014. }
  4015. assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
  4016. return Tmp;
  4017. }
  4018. case ISD::INSERT_SUBVECTOR: {
  4019. if (VT.isScalableVector())
  4020. break;
  4021. // Demand any elements from the subvector and the remainder from the src its
  4022. // inserted into.
  4023. SDValue Src = Op.getOperand(0);
  4024. SDValue Sub = Op.getOperand(1);
  4025. uint64_t Idx = Op.getConstantOperandVal(2);
  4026. unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
  4027. APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
  4028. APInt DemandedSrcElts = DemandedElts;
  4029. DemandedSrcElts.insertBits(APInt::getZero(NumSubElts), Idx);
  4030. Tmp = std::numeric_limits<unsigned>::max();
  4031. if (!!DemandedSubElts) {
  4032. Tmp = ComputeNumSignBits(Sub, DemandedSubElts, Depth + 1);
  4033. if (Tmp == 1)
  4034. return 1; // early-out
  4035. }
  4036. if (!!DemandedSrcElts) {
  4037. Tmp2 = ComputeNumSignBits(Src, DemandedSrcElts, Depth + 1);
  4038. Tmp = std::min(Tmp, Tmp2);
  4039. }
  4040. assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
  4041. return Tmp;
  4042. }
  4043. case ISD::LOAD: {
  4044. LoadSDNode *LD = cast<LoadSDNode>(Op);
  4045. if (const MDNode *Ranges = LD->getRanges()) {
  4046. if (DemandedElts != 1)
  4047. break;
  4048. ConstantRange CR = getConstantRangeFromMetadata(*Ranges);
  4049. if (VTBits > CR.getBitWidth()) {
  4050. switch (LD->getExtensionType()) {
  4051. case ISD::SEXTLOAD:
  4052. CR = CR.signExtend(VTBits);
  4053. break;
  4054. case ISD::ZEXTLOAD:
  4055. CR = CR.zeroExtend(VTBits);
  4056. break;
  4057. default:
  4058. break;
  4059. }
  4060. }
  4061. if (VTBits != CR.getBitWidth())
  4062. break;
  4063. return std::min(CR.getSignedMin().getNumSignBits(),
  4064. CR.getSignedMax().getNumSignBits());
  4065. }
  4066. break;
  4067. }
  4068. case ISD::ATOMIC_CMP_SWAP:
  4069. case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
  4070. case ISD::ATOMIC_SWAP:
  4071. case ISD::ATOMIC_LOAD_ADD:
  4072. case ISD::ATOMIC_LOAD_SUB:
  4073. case ISD::ATOMIC_LOAD_AND:
  4074. case ISD::ATOMIC_LOAD_CLR:
  4075. case ISD::ATOMIC_LOAD_OR:
  4076. case ISD::ATOMIC_LOAD_XOR:
  4077. case ISD::ATOMIC_LOAD_NAND:
  4078. case ISD::ATOMIC_LOAD_MIN:
  4079. case ISD::ATOMIC_LOAD_MAX:
  4080. case ISD::ATOMIC_LOAD_UMIN:
  4081. case ISD::ATOMIC_LOAD_UMAX:
  4082. case ISD::ATOMIC_LOAD: {
  4083. Tmp = cast<AtomicSDNode>(Op)->getMemoryVT().getScalarSizeInBits();
  4084. // If we are looking at the loaded value.
  4085. if (Op.getResNo() == 0) {
  4086. if (Tmp == VTBits)
  4087. return 1; // early-out
  4088. if (TLI->getExtendForAtomicOps() == ISD::SIGN_EXTEND)
  4089. return VTBits - Tmp + 1;
  4090. if (TLI->getExtendForAtomicOps() == ISD::ZERO_EXTEND)
  4091. return VTBits - Tmp;
  4092. }
  4093. break;
  4094. }
  4095. }
  4096. // If we are looking at the loaded value of the SDNode.
  4097. if (Op.getResNo() == 0) {
  4098. // Handle LOADX separately here. EXTLOAD case will fallthrough.
  4099. if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
  4100. unsigned ExtType = LD->getExtensionType();
  4101. switch (ExtType) {
  4102. default: break;
  4103. case ISD::SEXTLOAD: // e.g. i16->i32 = '17' bits known.
  4104. Tmp = LD->getMemoryVT().getScalarSizeInBits();
  4105. return VTBits - Tmp + 1;
  4106. case ISD::ZEXTLOAD: // e.g. i16->i32 = '16' bits known.
  4107. Tmp = LD->getMemoryVT().getScalarSizeInBits();
  4108. return VTBits - Tmp;
  4109. case ISD::NON_EXTLOAD:
  4110. if (const Constant *Cst = TLI->getTargetConstantFromLoad(LD)) {
  4111. // We only need to handle vectors - computeKnownBits should handle
  4112. // scalar cases.
  4113. Type *CstTy = Cst->getType();
  4114. if (CstTy->isVectorTy() && !VT.isScalableVector() &&
  4115. (NumElts * VTBits) == CstTy->getPrimitiveSizeInBits() &&
  4116. VTBits == CstTy->getScalarSizeInBits()) {
  4117. Tmp = VTBits;
  4118. for (unsigned i = 0; i != NumElts; ++i) {
  4119. if (!DemandedElts[i])
  4120. continue;
  4121. if (Constant *Elt = Cst->getAggregateElement(i)) {
  4122. if (auto *CInt = dyn_cast<ConstantInt>(Elt)) {
  4123. const APInt &Value = CInt->getValue();
  4124. Tmp = std::min(Tmp, Value.getNumSignBits());
  4125. continue;
  4126. }
  4127. if (auto *CFP = dyn_cast<ConstantFP>(Elt)) {
  4128. APInt Value = CFP->getValueAPF().bitcastToAPInt();
  4129. Tmp = std::min(Tmp, Value.getNumSignBits());
  4130. continue;
  4131. }
  4132. }
  4133. // Unknown type. Conservatively assume no bits match sign bit.
  4134. return 1;
  4135. }
  4136. return Tmp;
  4137. }
  4138. }
  4139. break;
  4140. }
  4141. }
  4142. }
  4143. // Allow the target to implement this method for its nodes.
  4144. if (Opcode >= ISD::BUILTIN_OP_END ||
  4145. Opcode == ISD::INTRINSIC_WO_CHAIN ||
  4146. Opcode == ISD::INTRINSIC_W_CHAIN ||
  4147. Opcode == ISD::INTRINSIC_VOID) {
  4148. // TODO: This can probably be removed once target code is audited. This
  4149. // is here purely to reduce patch size and review complexity.
  4150. if (!VT.isScalableVector()) {
  4151. unsigned NumBits =
  4152. TLI->ComputeNumSignBitsForTargetNode(Op, DemandedElts, *this, Depth);
  4153. if (NumBits > 1)
  4154. FirstAnswer = std::max(FirstAnswer, NumBits);
  4155. }
  4156. }
  4157. // Finally, if we can prove that the top bits of the result are 0's or 1's,
  4158. // use this information.
  4159. KnownBits Known = computeKnownBits(Op, DemandedElts, Depth);
  4160. return std::max(FirstAnswer, Known.countMinSignBits());
  4161. }
  4162. unsigned SelectionDAG::ComputeMaxSignificantBits(SDValue Op,
  4163. unsigned Depth) const {
  4164. unsigned SignBits = ComputeNumSignBits(Op, Depth);
  4165. return Op.getScalarValueSizeInBits() - SignBits + 1;
  4166. }
  4167. unsigned SelectionDAG::ComputeMaxSignificantBits(SDValue Op,
  4168. const APInt &DemandedElts,
  4169. unsigned Depth) const {
  4170. unsigned SignBits = ComputeNumSignBits(Op, DemandedElts, Depth);
  4171. return Op.getScalarValueSizeInBits() - SignBits + 1;
  4172. }
  4173. bool SelectionDAG::isGuaranteedNotToBeUndefOrPoison(SDValue Op, bool PoisonOnly,
  4174. unsigned Depth) const {
  4175. // Early out for FREEZE.
  4176. if (Op.getOpcode() == ISD::FREEZE)
  4177. return true;
  4178. // TODO: Assume we don't know anything for now.
  4179. EVT VT = Op.getValueType();
  4180. if (VT.isScalableVector())
  4181. return false;
  4182. APInt DemandedElts = VT.isVector()
  4183. ? APInt::getAllOnes(VT.getVectorNumElements())
  4184. : APInt(1, 1);
  4185. return isGuaranteedNotToBeUndefOrPoison(Op, DemandedElts, PoisonOnly, Depth);
  4186. }
  4187. bool SelectionDAG::isGuaranteedNotToBeUndefOrPoison(SDValue Op,
  4188. const APInt &DemandedElts,
  4189. bool PoisonOnly,
  4190. unsigned Depth) const {
  4191. unsigned Opcode = Op.getOpcode();
  4192. // Early out for FREEZE.
  4193. if (Opcode == ISD::FREEZE)
  4194. return true;
  4195. if (Depth >= MaxRecursionDepth)
  4196. return false; // Limit search depth.
  4197. if (isIntOrFPConstant(Op))
  4198. return true;
  4199. switch (Opcode) {
  4200. case ISD::VALUETYPE:
  4201. case ISD::FrameIndex:
  4202. case ISD::TargetFrameIndex:
  4203. return true;
  4204. case ISD::UNDEF:
  4205. return PoisonOnly;
  4206. case ISD::BUILD_VECTOR:
  4207. // NOTE: BUILD_VECTOR has implicit truncation of wider scalar elements -
  4208. // this shouldn't affect the result.
  4209. for (unsigned i = 0, e = Op.getNumOperands(); i < e; ++i) {
  4210. if (!DemandedElts[i])
  4211. continue;
  4212. if (!isGuaranteedNotToBeUndefOrPoison(Op.getOperand(i), PoisonOnly,
  4213. Depth + 1))
  4214. return false;
  4215. }
  4216. return true;
  4217. // TODO: Search for noundef attributes from library functions.
  4218. // TODO: Pointers dereferenced by ISD::LOAD/STORE ops are noundef.
  4219. default:
  4220. // Allow the target to implement this method for its nodes.
  4221. if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::INTRINSIC_WO_CHAIN ||
  4222. Opcode == ISD::INTRINSIC_W_CHAIN || Opcode == ISD::INTRINSIC_VOID)
  4223. return TLI->isGuaranteedNotToBeUndefOrPoisonForTargetNode(
  4224. Op, DemandedElts, *this, PoisonOnly, Depth);
  4225. break;
  4226. }
  4227. // If Op can't create undef/poison and none of its operands are undef/poison
  4228. // then Op is never undef/poison.
  4229. // NOTE: TargetNodes should handle this in themselves in
  4230. // isGuaranteedNotToBeUndefOrPoisonForTargetNode.
  4231. return !canCreateUndefOrPoison(Op, PoisonOnly, /*ConsiderFlags*/ true,
  4232. Depth) &&
  4233. all_of(Op->ops(), [&](SDValue V) {
  4234. return isGuaranteedNotToBeUndefOrPoison(V, PoisonOnly, Depth + 1);
  4235. });
  4236. }
  4237. bool SelectionDAG::canCreateUndefOrPoison(SDValue Op, bool PoisonOnly,
  4238. bool ConsiderFlags,
  4239. unsigned Depth) const {
  4240. // TODO: Assume we don't know anything for now.
  4241. EVT VT = Op.getValueType();
  4242. if (VT.isScalableVector())
  4243. return true;
  4244. APInt DemandedElts = VT.isVector()
  4245. ? APInt::getAllOnes(VT.getVectorNumElements())
  4246. : APInt(1, 1);
  4247. return canCreateUndefOrPoison(Op, DemandedElts, PoisonOnly, ConsiderFlags,
  4248. Depth);
  4249. }
  4250. bool SelectionDAG::canCreateUndefOrPoison(SDValue Op, const APInt &DemandedElts,
  4251. bool PoisonOnly, bool ConsiderFlags,
  4252. unsigned Depth) const {
  4253. // TODO: Assume we don't know anything for now.
  4254. EVT VT = Op.getValueType();
  4255. if (VT.isScalableVector())
  4256. return true;
  4257. unsigned Opcode = Op.getOpcode();
  4258. switch (Opcode) {
  4259. case ISD::AssertSext:
  4260. case ISD::AssertZext:
  4261. case ISD::FREEZE:
  4262. case ISD::INSERT_SUBVECTOR:
  4263. case ISD::AND:
  4264. case ISD::OR:
  4265. case ISD::XOR:
  4266. case ISD::ROTL:
  4267. case ISD::ROTR:
  4268. case ISD::FSHL:
  4269. case ISD::FSHR:
  4270. case ISD::BSWAP:
  4271. case ISD::CTPOP:
  4272. case ISD::BITREVERSE:
  4273. case ISD::PARITY:
  4274. case ISD::SIGN_EXTEND:
  4275. case ISD::ZERO_EXTEND:
  4276. case ISD::TRUNCATE:
  4277. case ISD::SIGN_EXTEND_INREG:
  4278. case ISD::SIGN_EXTEND_VECTOR_INREG:
  4279. case ISD::ZERO_EXTEND_VECTOR_INREG:
  4280. case ISD::BITCAST:
  4281. case ISD::BUILD_VECTOR:
  4282. return false;
  4283. case ISD::ADD:
  4284. case ISD::SUB:
  4285. case ISD::MUL:
  4286. // Matches hasPoisonGeneratingFlags().
  4287. return ConsiderFlags && (Op->getFlags().hasNoSignedWrap() ||
  4288. Op->getFlags().hasNoUnsignedWrap());
  4289. case ISD::SHL:
  4290. // If the max shift amount isn't in range, then the shift can create poison.
  4291. if (!getValidMaximumShiftAmountConstant(Op, DemandedElts))
  4292. return true;
  4293. // Matches hasPoisonGeneratingFlags().
  4294. return ConsiderFlags && (Op->getFlags().hasNoSignedWrap() ||
  4295. Op->getFlags().hasNoUnsignedWrap());
  4296. default:
  4297. // Allow the target to implement this method for its nodes.
  4298. if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::INTRINSIC_WO_CHAIN ||
  4299. Opcode == ISD::INTRINSIC_W_CHAIN || Opcode == ISD::INTRINSIC_VOID)
  4300. return TLI->canCreateUndefOrPoisonForTargetNode(
  4301. Op, DemandedElts, *this, PoisonOnly, ConsiderFlags, Depth);
  4302. break;
  4303. }
  4304. // Be conservative and return true.
  4305. return true;
  4306. }
  4307. bool SelectionDAG::isBaseWithConstantOffset(SDValue Op) const {
  4308. if ((Op.getOpcode() != ISD::ADD && Op.getOpcode() != ISD::OR) ||
  4309. !isa<ConstantSDNode>(Op.getOperand(1)))
  4310. return false;
  4311. if (Op.getOpcode() == ISD::OR &&
  4312. !MaskedValueIsZero(Op.getOperand(0), Op.getConstantOperandAPInt(1)))
  4313. return false;
  4314. return true;
  4315. }
  4316. bool SelectionDAG::isKnownNeverNaN(SDValue Op, bool SNaN, unsigned Depth) const {
  4317. // If we're told that NaNs won't happen, assume they won't.
  4318. if (getTarget().Options.NoNaNsFPMath || Op->getFlags().hasNoNaNs())
  4319. return true;
  4320. if (Depth >= MaxRecursionDepth)
  4321. return false; // Limit search depth.
  4322. // If the value is a constant, we can obviously see if it is a NaN or not.
  4323. if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) {
  4324. return !C->getValueAPF().isNaN() ||
  4325. (SNaN && !C->getValueAPF().isSignaling());
  4326. }
  4327. unsigned Opcode = Op.getOpcode();
  4328. switch (Opcode) {
  4329. case ISD::FADD:
  4330. case ISD::FSUB:
  4331. case ISD::FMUL:
  4332. case ISD::FDIV:
  4333. case ISD::FREM:
  4334. case ISD::FSIN:
  4335. case ISD::FCOS:
  4336. case ISD::FMA:
  4337. case ISD::FMAD: {
  4338. if (SNaN)
  4339. return true;
  4340. // TODO: Need isKnownNeverInfinity
  4341. return false;
  4342. }
  4343. case ISD::FCANONICALIZE:
  4344. case ISD::FEXP:
  4345. case ISD::FEXP2:
  4346. case ISD::FTRUNC:
  4347. case ISD::FFLOOR:
  4348. case ISD::FCEIL:
  4349. case ISD::FROUND:
  4350. case ISD::FROUNDEVEN:
  4351. case ISD::FRINT:
  4352. case ISD::FNEARBYINT: {
  4353. if (SNaN)
  4354. return true;
  4355. return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
  4356. }
  4357. case ISD::FABS:
  4358. case ISD::FNEG:
  4359. case ISD::FCOPYSIGN: {
  4360. return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
  4361. }
  4362. case ISD::SELECT:
  4363. return isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1) &&
  4364. isKnownNeverNaN(Op.getOperand(2), SNaN, Depth + 1);
  4365. case ISD::FP_EXTEND:
  4366. case ISD::FP_ROUND: {
  4367. if (SNaN)
  4368. return true;
  4369. return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
  4370. }
  4371. case ISD::SINT_TO_FP:
  4372. case ISD::UINT_TO_FP:
  4373. return true;
  4374. case ISD::FSQRT: // Need is known positive
  4375. case ISD::FLOG:
  4376. case ISD::FLOG2:
  4377. case ISD::FLOG10:
  4378. case ISD::FPOWI:
  4379. case ISD::FPOW: {
  4380. if (SNaN)
  4381. return true;
  4382. // TODO: Refine on operand
  4383. return false;
  4384. }
  4385. case ISD::FMINNUM:
  4386. case ISD::FMAXNUM: {
  4387. // Only one needs to be known not-nan, since it will be returned if the
  4388. // other ends up being one.
  4389. return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) ||
  4390. isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1);
  4391. }
  4392. case ISD::FMINNUM_IEEE:
  4393. case ISD::FMAXNUM_IEEE: {
  4394. if (SNaN)
  4395. return true;
  4396. // This can return a NaN if either operand is an sNaN, or if both operands
  4397. // are NaN.
  4398. return (isKnownNeverNaN(Op.getOperand(0), false, Depth + 1) &&
  4399. isKnownNeverSNaN(Op.getOperand(1), Depth + 1)) ||
  4400. (isKnownNeverNaN(Op.getOperand(1), false, Depth + 1) &&
  4401. isKnownNeverSNaN(Op.getOperand(0), Depth + 1));
  4402. }
  4403. case ISD::FMINIMUM:
  4404. case ISD::FMAXIMUM: {
  4405. // TODO: Does this quiet or return the origina NaN as-is?
  4406. return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) &&
  4407. isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1);
  4408. }
  4409. case ISD::EXTRACT_VECTOR_ELT: {
  4410. return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
  4411. }
  4412. case ISD::BUILD_VECTOR: {
  4413. for (const SDValue &Opnd : Op->ops())
  4414. if (!isKnownNeverNaN(Opnd, SNaN, Depth + 1))
  4415. return false;
  4416. return true;
  4417. }
  4418. default:
  4419. if (Opcode >= ISD::BUILTIN_OP_END ||
  4420. Opcode == ISD::INTRINSIC_WO_CHAIN ||
  4421. Opcode == ISD::INTRINSIC_W_CHAIN ||
  4422. Opcode == ISD::INTRINSIC_VOID) {
  4423. return TLI->isKnownNeverNaNForTargetNode(Op, *this, SNaN, Depth);
  4424. }
  4425. return false;
  4426. }
  4427. }
  4428. bool SelectionDAG::isKnownNeverZeroFloat(SDValue Op) const {
  4429. assert(Op.getValueType().isFloatingPoint() &&
  4430. "Floating point type expected");
  4431. // If the value is a constant, we can obviously see if it is a zero or not.
  4432. // TODO: Add BuildVector support.
  4433. if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
  4434. return !C->isZero();
  4435. return false;
  4436. }
  4437. bool SelectionDAG::isKnownNeverZero(SDValue Op) const {
  4438. assert(!Op.getValueType().isFloatingPoint() &&
  4439. "Floating point types unsupported - use isKnownNeverZeroFloat");
  4440. // If the value is a constant, we can obviously see if it is a zero or not.
  4441. if (ISD::matchUnaryPredicate(Op,
  4442. [](ConstantSDNode *C) { return !C->isZero(); }))
  4443. return true;
  4444. // TODO: Recognize more cases here.
  4445. switch (Op.getOpcode()) {
  4446. default: break;
  4447. case ISD::OR:
  4448. if (isKnownNeverZero(Op.getOperand(1)) ||
  4449. isKnownNeverZero(Op.getOperand(0)))
  4450. return true;
  4451. break;
  4452. }
  4453. return false;
  4454. }
  4455. bool SelectionDAG::isEqualTo(SDValue A, SDValue B) const {
  4456. // Check the obvious case.
  4457. if (A == B) return true;
  4458. // For for negative and positive zero.
  4459. if (const ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A))
  4460. if (const ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B))
  4461. if (CA->isZero() && CB->isZero()) return true;
  4462. // Otherwise they may not be equal.
  4463. return false;
  4464. }
  4465. // Only bits set in Mask must be negated, other bits may be arbitrary.
  4466. SDValue llvm::getBitwiseNotOperand(SDValue V, SDValue Mask, bool AllowUndefs) {
  4467. if (isBitwiseNot(V, AllowUndefs))
  4468. return V.getOperand(0);
  4469. // Handle any_extend (not (truncate X)) pattern, where Mask only sets
  4470. // bits in the non-extended part.
  4471. ConstantSDNode *MaskC = isConstOrConstSplat(Mask);
  4472. if (!MaskC || V.getOpcode() != ISD::ANY_EXTEND)
  4473. return SDValue();
  4474. SDValue ExtArg = V.getOperand(0);
  4475. if (ExtArg.getScalarValueSizeInBits() >=
  4476. MaskC->getAPIntValue().getActiveBits() &&
  4477. isBitwiseNot(ExtArg, AllowUndefs) &&
  4478. ExtArg.getOperand(0).getOpcode() == ISD::TRUNCATE &&
  4479. ExtArg.getOperand(0).getOperand(0).getValueType() == V.getValueType())
  4480. return ExtArg.getOperand(0).getOperand(0);
  4481. return SDValue();
  4482. }
  4483. static bool haveNoCommonBitsSetCommutative(SDValue A, SDValue B) {
  4484. // Match masked merge pattern (X & ~M) op (Y & M)
  4485. // Including degenerate case (X & ~M) op M
  4486. auto MatchNoCommonBitsPattern = [&](SDValue Not, SDValue Mask,
  4487. SDValue Other) {
  4488. if (SDValue NotOperand =
  4489. getBitwiseNotOperand(Not, Mask, /* AllowUndefs */ true)) {
  4490. if (Other == NotOperand)
  4491. return true;
  4492. if (Other->getOpcode() == ISD::AND)
  4493. return NotOperand == Other->getOperand(0) ||
  4494. NotOperand == Other->getOperand(1);
  4495. }
  4496. return false;
  4497. };
  4498. if (A->getOpcode() == ISD::AND)
  4499. return MatchNoCommonBitsPattern(A->getOperand(0), A->getOperand(1), B) ||
  4500. MatchNoCommonBitsPattern(A->getOperand(1), A->getOperand(0), B);
  4501. return false;
  4502. }
  4503. // FIXME: unify with llvm::haveNoCommonBitsSet.
  4504. bool SelectionDAG::haveNoCommonBitsSet(SDValue A, SDValue B) const {
  4505. assert(A.getValueType() == B.getValueType() &&
  4506. "Values must have the same type");
  4507. if (haveNoCommonBitsSetCommutative(A, B) ||
  4508. haveNoCommonBitsSetCommutative(B, A))
  4509. return true;
  4510. return KnownBits::haveNoCommonBitsSet(computeKnownBits(A),
  4511. computeKnownBits(B));
  4512. }
  4513. static SDValue FoldSTEP_VECTOR(const SDLoc &DL, EVT VT, SDValue Step,
  4514. SelectionDAG &DAG) {
  4515. if (cast<ConstantSDNode>(Step)->isZero())
  4516. return DAG.getConstant(0, DL, VT);
  4517. return SDValue();
  4518. }
  4519. static SDValue FoldBUILD_VECTOR(const SDLoc &DL, EVT VT,
  4520. ArrayRef<SDValue> Ops,
  4521. SelectionDAG &DAG) {
  4522. int NumOps = Ops.size();
  4523. assert(NumOps != 0 && "Can't build an empty vector!");
  4524. assert(!VT.isScalableVector() &&
  4525. "BUILD_VECTOR cannot be used with scalable types");
  4526. assert(VT.getVectorNumElements() == (unsigned)NumOps &&
  4527. "Incorrect element count in BUILD_VECTOR!");
  4528. // BUILD_VECTOR of UNDEFs is UNDEF.
  4529. if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); }))
  4530. return DAG.getUNDEF(VT);
  4531. // BUILD_VECTOR of seq extract/insert from the same vector + type is Identity.
  4532. SDValue IdentitySrc;
  4533. bool IsIdentity = true;
  4534. for (int i = 0; i != NumOps; ++i) {
  4535. if (Ops[i].getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
  4536. Ops[i].getOperand(0).getValueType() != VT ||
  4537. (IdentitySrc && Ops[i].getOperand(0) != IdentitySrc) ||
  4538. !isa<ConstantSDNode>(Ops[i].getOperand(1)) ||
  4539. cast<ConstantSDNode>(Ops[i].getOperand(1))->getAPIntValue() != i) {
  4540. IsIdentity = false;
  4541. break;
  4542. }
  4543. IdentitySrc = Ops[i].getOperand(0);
  4544. }
  4545. if (IsIdentity)
  4546. return IdentitySrc;
  4547. return SDValue();
  4548. }
  4549. /// Try to simplify vector concatenation to an input value, undef, or build
  4550. /// vector.
  4551. static SDValue foldCONCAT_VECTORS(const SDLoc &DL, EVT VT,
  4552. ArrayRef<SDValue> Ops,
  4553. SelectionDAG &DAG) {
  4554. assert(!Ops.empty() && "Can't concatenate an empty list of vectors!");
  4555. assert(llvm::all_of(Ops,
  4556. [Ops](SDValue Op) {
  4557. return Ops[0].getValueType() == Op.getValueType();
  4558. }) &&
  4559. "Concatenation of vectors with inconsistent value types!");
  4560. assert((Ops[0].getValueType().getVectorElementCount() * Ops.size()) ==
  4561. VT.getVectorElementCount() &&
  4562. "Incorrect element count in vector concatenation!");
  4563. if (Ops.size() == 1)
  4564. return Ops[0];
  4565. // Concat of UNDEFs is UNDEF.
  4566. if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); }))
  4567. return DAG.getUNDEF(VT);
  4568. // Scan the operands and look for extract operations from a single source
  4569. // that correspond to insertion at the same location via this concatenation:
  4570. // concat (extract X, 0*subvec_elts), (extract X, 1*subvec_elts), ...
  4571. SDValue IdentitySrc;
  4572. bool IsIdentity = true;
  4573. for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
  4574. SDValue Op = Ops[i];
  4575. unsigned IdentityIndex = i * Op.getValueType().getVectorMinNumElements();
  4576. if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
  4577. Op.getOperand(0).getValueType() != VT ||
  4578. (IdentitySrc && Op.getOperand(0) != IdentitySrc) ||
  4579. Op.getConstantOperandVal(1) != IdentityIndex) {
  4580. IsIdentity = false;
  4581. break;
  4582. }
  4583. assert((!IdentitySrc || IdentitySrc == Op.getOperand(0)) &&
  4584. "Unexpected identity source vector for concat of extracts");
  4585. IdentitySrc = Op.getOperand(0);
  4586. }
  4587. if (IsIdentity) {
  4588. assert(IdentitySrc && "Failed to set source vector of extracts");
  4589. return IdentitySrc;
  4590. }
  4591. // The code below this point is only designed to work for fixed width
  4592. // vectors, so we bail out for now.
  4593. if (VT.isScalableVector())
  4594. return SDValue();
  4595. // A CONCAT_VECTOR with all UNDEF/BUILD_VECTOR operands can be
  4596. // simplified to one big BUILD_VECTOR.
  4597. // FIXME: Add support for SCALAR_TO_VECTOR as well.
  4598. EVT SVT = VT.getScalarType();
  4599. SmallVector<SDValue, 16> Elts;
  4600. for (SDValue Op : Ops) {
  4601. EVT OpVT = Op.getValueType();
  4602. if (Op.isUndef())
  4603. Elts.append(OpVT.getVectorNumElements(), DAG.getUNDEF(SVT));
  4604. else if (Op.getOpcode() == ISD::BUILD_VECTOR)
  4605. Elts.append(Op->op_begin(), Op->op_end());
  4606. else
  4607. return SDValue();
  4608. }
  4609. // BUILD_VECTOR requires all inputs to be of the same type, find the
  4610. // maximum type and extend them all.
  4611. for (SDValue Op : Elts)
  4612. SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
  4613. if (SVT.bitsGT(VT.getScalarType())) {
  4614. for (SDValue &Op : Elts) {
  4615. if (Op.isUndef())
  4616. Op = DAG.getUNDEF(SVT);
  4617. else
  4618. Op = DAG.getTargetLoweringInfo().isZExtFree(Op.getValueType(), SVT)
  4619. ? DAG.getZExtOrTrunc(Op, DL, SVT)
  4620. : DAG.getSExtOrTrunc(Op, DL, SVT);
  4621. }
  4622. }
  4623. SDValue V = DAG.getBuildVector(VT, DL, Elts);
  4624. NewSDValueDbgMsg(V, "New node fold concat vectors: ", &DAG);
  4625. return V;
  4626. }
  4627. /// Gets or creates the specified node.
  4628. SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT) {
  4629. FoldingSetNodeID ID;
  4630. AddNodeIDNode(ID, Opcode, getVTList(VT), std::nullopt);
  4631. void *IP = nullptr;
  4632. if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
  4633. return SDValue(E, 0);
  4634. auto *N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(),
  4635. getVTList(VT));
  4636. CSEMap.InsertNode(N, IP);
  4637. InsertNode(N);
  4638. SDValue V = SDValue(N, 0);
  4639. NewSDValueDbgMsg(V, "Creating new node: ", this);
  4640. return V;
  4641. }
  4642. SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
  4643. SDValue Operand) {
  4644. SDNodeFlags Flags;
  4645. if (Inserter)
  4646. Flags = Inserter->getFlags();
  4647. return getNode(Opcode, DL, VT, Operand, Flags);
  4648. }
  4649. SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
  4650. SDValue Operand, const SDNodeFlags Flags) {
  4651. assert(Operand.getOpcode() != ISD::DELETED_NODE &&
  4652. "Operand is DELETED_NODE!");
  4653. // Constant fold unary operations with an integer constant operand. Even
  4654. // opaque constant will be folded, because the folding of unary operations
  4655. // doesn't create new constants with different values. Nevertheless, the
  4656. // opaque flag is preserved during folding to prevent future folding with
  4657. // other constants.
  4658. if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Operand)) {
  4659. const APInt &Val = C->getAPIntValue();
  4660. switch (Opcode) {
  4661. default: break;
  4662. case ISD::SIGN_EXTEND:
  4663. return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT,
  4664. C->isTargetOpcode(), C->isOpaque());
  4665. case ISD::TRUNCATE:
  4666. if (C->isOpaque())
  4667. break;
  4668. [[fallthrough]];
  4669. case ISD::ZERO_EXTEND:
  4670. return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT,
  4671. C->isTargetOpcode(), C->isOpaque());
  4672. case ISD::ANY_EXTEND:
  4673. // Some targets like RISCV prefer to sign extend some types.
  4674. if (TLI->isSExtCheaperThanZExt(Operand.getValueType(), VT))
  4675. return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT,
  4676. C->isTargetOpcode(), C->isOpaque());
  4677. return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT,
  4678. C->isTargetOpcode(), C->isOpaque());
  4679. case ISD::UINT_TO_FP:
  4680. case ISD::SINT_TO_FP: {
  4681. APFloat apf(EVTToAPFloatSemantics(VT),
  4682. APInt::getZero(VT.getSizeInBits()));
  4683. (void)apf.convertFromAPInt(Val,
  4684. Opcode==ISD::SINT_TO_FP,
  4685. APFloat::rmNearestTiesToEven);
  4686. return getConstantFP(apf, DL, VT);
  4687. }
  4688. case ISD::BITCAST:
  4689. if (VT == MVT::f16 && C->getValueType(0) == MVT::i16)
  4690. return getConstantFP(APFloat(APFloat::IEEEhalf(), Val), DL, VT);
  4691. if (VT == MVT::f32 && C->getValueType(0) == MVT::i32)
  4692. return getConstantFP(APFloat(APFloat::IEEEsingle(), Val), DL, VT);
  4693. if (VT == MVT::f64 && C->getValueType(0) == MVT::i64)
  4694. return getConstantFP(APFloat(APFloat::IEEEdouble(), Val), DL, VT);
  4695. if (VT == MVT::f128 && C->getValueType(0) == MVT::i128)
  4696. return getConstantFP(APFloat(APFloat::IEEEquad(), Val), DL, VT);
  4697. break;
  4698. case ISD::ABS:
  4699. return getConstant(Val.abs(), DL, VT, C->isTargetOpcode(),
  4700. C->isOpaque());
  4701. case ISD::BITREVERSE:
  4702. return getConstant(Val.reverseBits(), DL, VT, C->isTargetOpcode(),
  4703. C->isOpaque());
  4704. case ISD::BSWAP:
  4705. return getConstant(Val.byteSwap(), DL, VT, C->isTargetOpcode(),
  4706. C->isOpaque());
  4707. case ISD::CTPOP:
  4708. return getConstant(Val.countPopulation(), DL, VT, C->isTargetOpcode(),
  4709. C->isOpaque());
  4710. case ISD::CTLZ:
  4711. case ISD::CTLZ_ZERO_UNDEF:
  4712. return getConstant(Val.countLeadingZeros(), DL, VT, C->isTargetOpcode(),
  4713. C->isOpaque());
  4714. case ISD::CTTZ:
  4715. case ISD::CTTZ_ZERO_UNDEF:
  4716. return getConstant(Val.countTrailingZeros(), DL, VT, C->isTargetOpcode(),
  4717. C->isOpaque());
  4718. case ISD::FP16_TO_FP:
  4719. case ISD::BF16_TO_FP: {
  4720. bool Ignored;
  4721. APFloat FPV(Opcode == ISD::FP16_TO_FP ? APFloat::IEEEhalf()
  4722. : APFloat::BFloat(),
  4723. (Val.getBitWidth() == 16) ? Val : Val.trunc(16));
  4724. // This can return overflow, underflow, or inexact; we don't care.
  4725. // FIXME need to be more flexible about rounding mode.
  4726. (void)FPV.convert(EVTToAPFloatSemantics(VT),
  4727. APFloat::rmNearestTiesToEven, &Ignored);
  4728. return getConstantFP(FPV, DL, VT);
  4729. }
  4730. case ISD::STEP_VECTOR: {
  4731. if (SDValue V = FoldSTEP_VECTOR(DL, VT, Operand, *this))
  4732. return V;
  4733. break;
  4734. }
  4735. }
  4736. }
  4737. // Constant fold unary operations with a floating point constant operand.
  4738. if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Operand)) {
  4739. APFloat V = C->getValueAPF(); // make copy
  4740. switch (Opcode) {
  4741. case ISD::FNEG:
  4742. V.changeSign();
  4743. return getConstantFP(V, DL, VT);
  4744. case ISD::FABS:
  4745. V.clearSign();
  4746. return getConstantFP(V, DL, VT);
  4747. case ISD::FCEIL: {
  4748. APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardPositive);
  4749. if (fs == APFloat::opOK || fs == APFloat::opInexact)
  4750. return getConstantFP(V, DL, VT);
  4751. break;
  4752. }
  4753. case ISD::FTRUNC: {
  4754. APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardZero);
  4755. if (fs == APFloat::opOK || fs == APFloat::opInexact)
  4756. return getConstantFP(V, DL, VT);
  4757. break;
  4758. }
  4759. case ISD::FFLOOR: {
  4760. APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardNegative);
  4761. if (fs == APFloat::opOK || fs == APFloat::opInexact)
  4762. return getConstantFP(V, DL, VT);
  4763. break;
  4764. }
  4765. case ISD::FP_EXTEND: {
  4766. bool ignored;
  4767. // This can return overflow, underflow, or inexact; we don't care.
  4768. // FIXME need to be more flexible about rounding mode.
  4769. (void)V.convert(EVTToAPFloatSemantics(VT),
  4770. APFloat::rmNearestTiesToEven, &ignored);
  4771. return getConstantFP(V, DL, VT);
  4772. }
  4773. case ISD::FP_TO_SINT:
  4774. case ISD::FP_TO_UINT: {
  4775. bool ignored;
  4776. APSInt IntVal(VT.getSizeInBits(), Opcode == ISD::FP_TO_UINT);
  4777. // FIXME need to be more flexible about rounding mode.
  4778. APFloat::opStatus s =
  4779. V.convertToInteger(IntVal, APFloat::rmTowardZero, &ignored);
  4780. if (s == APFloat::opInvalidOp) // inexact is OK, in fact usual
  4781. break;
  4782. return getConstant(IntVal, DL, VT);
  4783. }
  4784. case ISD::BITCAST:
  4785. if (VT == MVT::i16 && C->getValueType(0) == MVT::f16)
  4786. return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL, VT);
  4787. if (VT == MVT::i16 && C->getValueType(0) == MVT::bf16)
  4788. return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL, VT);
  4789. if (VT == MVT::i32 && C->getValueType(0) == MVT::f32)
  4790. return getConstant((uint32_t)V.bitcastToAPInt().getZExtValue(), DL, VT);
  4791. if (VT == MVT::i64 && C->getValueType(0) == MVT::f64)
  4792. return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT);
  4793. break;
  4794. case ISD::FP_TO_FP16:
  4795. case ISD::FP_TO_BF16: {
  4796. bool Ignored;
  4797. // This can return overflow, underflow, or inexact; we don't care.
  4798. // FIXME need to be more flexible about rounding mode.
  4799. (void)V.convert(Opcode == ISD::FP_TO_FP16 ? APFloat::IEEEhalf()
  4800. : APFloat::BFloat(),
  4801. APFloat::rmNearestTiesToEven, &Ignored);
  4802. return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT);
  4803. }
  4804. }
  4805. }
  4806. // Constant fold unary operations with a vector integer or float operand.
  4807. switch (Opcode) {
  4808. default:
  4809. // FIXME: Entirely reasonable to perform folding of other unary
  4810. // operations here as the need arises.
  4811. break;
  4812. case ISD::FNEG:
  4813. case ISD::FABS:
  4814. case ISD::FCEIL:
  4815. case ISD::FTRUNC:
  4816. case ISD::FFLOOR:
  4817. case ISD::FP_EXTEND:
  4818. case ISD::FP_TO_SINT:
  4819. case ISD::FP_TO_UINT:
  4820. case ISD::TRUNCATE:
  4821. case ISD::ANY_EXTEND:
  4822. case ISD::ZERO_EXTEND:
  4823. case ISD::SIGN_EXTEND:
  4824. case ISD::UINT_TO_FP:
  4825. case ISD::SINT_TO_FP:
  4826. case ISD::ABS:
  4827. case ISD::BITREVERSE:
  4828. case ISD::BSWAP:
  4829. case ISD::CTLZ:
  4830. case ISD::CTLZ_ZERO_UNDEF:
  4831. case ISD::CTTZ:
  4832. case ISD::CTTZ_ZERO_UNDEF:
  4833. case ISD::CTPOP: {
  4834. SDValue Ops = {Operand};
  4835. if (SDValue Fold = FoldConstantArithmetic(Opcode, DL, VT, Ops))
  4836. return Fold;
  4837. }
  4838. }
  4839. unsigned OpOpcode = Operand.getNode()->getOpcode();
  4840. switch (Opcode) {
  4841. case ISD::STEP_VECTOR:
  4842. assert(VT.isScalableVector() &&
  4843. "STEP_VECTOR can only be used with scalable types");
  4844. assert(OpOpcode == ISD::TargetConstant &&
  4845. VT.getVectorElementType() == Operand.getValueType() &&
  4846. "Unexpected step operand");
  4847. break;
  4848. case ISD::FREEZE:
  4849. assert(VT == Operand.getValueType() && "Unexpected VT!");
  4850. if (isGuaranteedNotToBeUndefOrPoison(Operand, /*PoisonOnly*/ false,
  4851. /*Depth*/ 1))
  4852. return Operand;
  4853. break;
  4854. case ISD::TokenFactor:
  4855. case ISD::MERGE_VALUES:
  4856. case ISD::CONCAT_VECTORS:
  4857. return Operand; // Factor, merge or concat of one node? No need.
  4858. case ISD::BUILD_VECTOR: {
  4859. // Attempt to simplify BUILD_VECTOR.
  4860. SDValue Ops[] = {Operand};
  4861. if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
  4862. return V;
  4863. break;
  4864. }
  4865. case ISD::FP_ROUND: llvm_unreachable("Invalid method to make FP_ROUND node");
  4866. case ISD::FP_EXTEND:
  4867. assert(VT.isFloatingPoint() &&
  4868. Operand.getValueType().isFloatingPoint() && "Invalid FP cast!");
  4869. if (Operand.getValueType() == VT) return Operand; // noop conversion.
  4870. assert((!VT.isVector() ||
  4871. VT.getVectorElementCount() ==
  4872. Operand.getValueType().getVectorElementCount()) &&
  4873. "Vector element count mismatch!");
  4874. assert(Operand.getValueType().bitsLT(VT) &&
  4875. "Invalid fpext node, dst < src!");
  4876. if (Operand.isUndef())
  4877. return getUNDEF(VT);
  4878. break;
  4879. case ISD::FP_TO_SINT:
  4880. case ISD::FP_TO_UINT:
  4881. if (Operand.isUndef())
  4882. return getUNDEF(VT);
  4883. break;
  4884. case ISD::SINT_TO_FP:
  4885. case ISD::UINT_TO_FP:
  4886. // [us]itofp(undef) = 0, because the result value is bounded.
  4887. if (Operand.isUndef())
  4888. return getConstantFP(0.0, DL, VT);
  4889. break;
  4890. case ISD::SIGN_EXTEND:
  4891. assert(VT.isInteger() && Operand.getValueType().isInteger() &&
  4892. "Invalid SIGN_EXTEND!");
  4893. assert(VT.isVector() == Operand.getValueType().isVector() &&
  4894. "SIGN_EXTEND result type type should be vector iff the operand "
  4895. "type is vector!");
  4896. if (Operand.getValueType() == VT) return Operand; // noop extension
  4897. assert((!VT.isVector() ||
  4898. VT.getVectorElementCount() ==
  4899. Operand.getValueType().getVectorElementCount()) &&
  4900. "Vector element count mismatch!");
  4901. assert(Operand.getValueType().bitsLT(VT) &&
  4902. "Invalid sext node, dst < src!");
  4903. if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND)
  4904. return getNode(OpOpcode, DL, VT, Operand.getOperand(0));
  4905. if (OpOpcode == ISD::UNDEF)
  4906. // sext(undef) = 0, because the top bits will all be the same.
  4907. return getConstant(0, DL, VT);
  4908. break;
  4909. case ISD::ZERO_EXTEND:
  4910. assert(VT.isInteger() && Operand.getValueType().isInteger() &&
  4911. "Invalid ZERO_EXTEND!");
  4912. assert(VT.isVector() == Operand.getValueType().isVector() &&
  4913. "ZERO_EXTEND result type type should be vector iff the operand "
  4914. "type is vector!");
  4915. if (Operand.getValueType() == VT) return Operand; // noop extension
  4916. assert((!VT.isVector() ||
  4917. VT.getVectorElementCount() ==
  4918. Operand.getValueType().getVectorElementCount()) &&
  4919. "Vector element count mismatch!");
  4920. assert(Operand.getValueType().bitsLT(VT) &&
  4921. "Invalid zext node, dst < src!");
  4922. if (OpOpcode == ISD::ZERO_EXTEND) // (zext (zext x)) -> (zext x)
  4923. return getNode(ISD::ZERO_EXTEND, DL, VT, Operand.getOperand(0));
  4924. if (OpOpcode == ISD::UNDEF)
  4925. // zext(undef) = 0, because the top bits will be zero.
  4926. return getConstant(0, DL, VT);
  4927. break;
  4928. case ISD::ANY_EXTEND:
  4929. assert(VT.isInteger() && Operand.getValueType().isInteger() &&
  4930. "Invalid ANY_EXTEND!");
  4931. assert(VT.isVector() == Operand.getValueType().isVector() &&
  4932. "ANY_EXTEND result type type should be vector iff the operand "
  4933. "type is vector!");
  4934. if (Operand.getValueType() == VT) return Operand; // noop extension
  4935. assert((!VT.isVector() ||
  4936. VT.getVectorElementCount() ==
  4937. Operand.getValueType().getVectorElementCount()) &&
  4938. "Vector element count mismatch!");
  4939. assert(Operand.getValueType().bitsLT(VT) &&
  4940. "Invalid anyext node, dst < src!");
  4941. if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
  4942. OpOpcode == ISD::ANY_EXTEND)
  4943. // (ext (zext x)) -> (zext x) and (ext (sext x)) -> (sext x)
  4944. return getNode(OpOpcode, DL, VT, Operand.getOperand(0));
  4945. if (OpOpcode == ISD::UNDEF)
  4946. return getUNDEF(VT);
  4947. // (ext (trunc x)) -> x
  4948. if (OpOpcode == ISD::TRUNCATE) {
  4949. SDValue OpOp = Operand.getOperand(0);
  4950. if (OpOp.getValueType() == VT) {
  4951. transferDbgValues(Operand, OpOp);
  4952. return OpOp;
  4953. }
  4954. }
  4955. break;
  4956. case ISD::TRUNCATE:
  4957. assert(VT.isInteger() && Operand.getValueType().isInteger() &&
  4958. "Invalid TRUNCATE!");
  4959. assert(VT.isVector() == Operand.getValueType().isVector() &&
  4960. "TRUNCATE result type type should be vector iff the operand "
  4961. "type is vector!");
  4962. if (Operand.getValueType() == VT) return Operand; // noop truncate
  4963. assert((!VT.isVector() ||
  4964. VT.getVectorElementCount() ==
  4965. Operand.getValueType().getVectorElementCount()) &&
  4966. "Vector element count mismatch!");
  4967. assert(Operand.getValueType().bitsGT(VT) &&
  4968. "Invalid truncate node, src < dst!");
  4969. if (OpOpcode == ISD::TRUNCATE)
  4970. return getNode(ISD::TRUNCATE, DL, VT, Operand.getOperand(0));
  4971. if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
  4972. OpOpcode == ISD::ANY_EXTEND) {
  4973. // If the source is smaller than the dest, we still need an extend.
  4974. if (Operand.getOperand(0).getValueType().getScalarType()
  4975. .bitsLT(VT.getScalarType()))
  4976. return getNode(OpOpcode, DL, VT, Operand.getOperand(0));
  4977. if (Operand.getOperand(0).getValueType().bitsGT(VT))
  4978. return getNode(ISD::TRUNCATE, DL, VT, Operand.getOperand(0));
  4979. return Operand.getOperand(0);
  4980. }
  4981. if (OpOpcode == ISD::UNDEF)
  4982. return getUNDEF(VT);
  4983. if (OpOpcode == ISD::VSCALE && !NewNodesMustHaveLegalTypes)
  4984. return getVScale(DL, VT, Operand.getConstantOperandAPInt(0));
  4985. break;
  4986. case ISD::ANY_EXTEND_VECTOR_INREG:
  4987. case ISD::ZERO_EXTEND_VECTOR_INREG:
  4988. case ISD::SIGN_EXTEND_VECTOR_INREG:
  4989. assert(VT.isVector() && "This DAG node is restricted to vector types.");
  4990. assert(Operand.getValueType().bitsLE(VT) &&
  4991. "The input must be the same size or smaller than the result.");
  4992. assert(VT.getVectorMinNumElements() <
  4993. Operand.getValueType().getVectorMinNumElements() &&
  4994. "The destination vector type must have fewer lanes than the input.");
  4995. break;
  4996. case ISD::ABS:
  4997. assert(VT.isInteger() && VT == Operand.getValueType() &&
  4998. "Invalid ABS!");
  4999. if (OpOpcode == ISD::UNDEF)
  5000. return getConstant(0, DL, VT);
  5001. break;
  5002. case ISD::BSWAP:
  5003. assert(VT.isInteger() && VT == Operand.getValueType() &&
  5004. "Invalid BSWAP!");
  5005. assert((VT.getScalarSizeInBits() % 16 == 0) &&
  5006. "BSWAP types must be a multiple of 16 bits!");
  5007. if (OpOpcode == ISD::UNDEF)
  5008. return getUNDEF(VT);
  5009. // bswap(bswap(X)) -> X.
  5010. if (OpOpcode == ISD::BSWAP)
  5011. return Operand.getOperand(0);
  5012. break;
  5013. case ISD::BITREVERSE:
  5014. assert(VT.isInteger() && VT == Operand.getValueType() &&
  5015. "Invalid BITREVERSE!");
  5016. if (OpOpcode == ISD::UNDEF)
  5017. return getUNDEF(VT);
  5018. break;
  5019. case ISD::BITCAST:
  5020. assert(VT.getSizeInBits() == Operand.getValueSizeInBits() &&
  5021. "Cannot BITCAST between types of different sizes!");
  5022. if (VT == Operand.getValueType()) return Operand; // noop conversion.
  5023. if (OpOpcode == ISD::BITCAST) // bitconv(bitconv(x)) -> bitconv(x)
  5024. return getNode(ISD::BITCAST, DL, VT, Operand.getOperand(0));
  5025. if (OpOpcode == ISD::UNDEF)
  5026. return getUNDEF(VT);
  5027. break;
  5028. case ISD::SCALAR_TO_VECTOR:
  5029. assert(VT.isVector() && !Operand.getValueType().isVector() &&
  5030. (VT.getVectorElementType() == Operand.getValueType() ||
  5031. (VT.getVectorElementType().isInteger() &&
  5032. Operand.getValueType().isInteger() &&
  5033. VT.getVectorElementType().bitsLE(Operand.getValueType()))) &&
  5034. "Illegal SCALAR_TO_VECTOR node!");
  5035. if (OpOpcode == ISD::UNDEF)
  5036. return getUNDEF(VT);
  5037. // scalar_to_vector(extract_vector_elt V, 0) -> V, top bits are undefined.
  5038. if (OpOpcode == ISD::EXTRACT_VECTOR_ELT &&
  5039. isa<ConstantSDNode>(Operand.getOperand(1)) &&
  5040. Operand.getConstantOperandVal(1) == 0 &&
  5041. Operand.getOperand(0).getValueType() == VT)
  5042. return Operand.getOperand(0);
  5043. break;
  5044. case ISD::FNEG:
  5045. // Negation of an unknown bag of bits is still completely undefined.
  5046. if (OpOpcode == ISD::UNDEF)
  5047. return getUNDEF(VT);
  5048. if (OpOpcode == ISD::FNEG) // --X -> X
  5049. return Operand.getOperand(0);
  5050. break;
  5051. case ISD::FABS:
  5052. if (OpOpcode == ISD::FNEG) // abs(-X) -> abs(X)
  5053. return getNode(ISD::FABS, DL, VT, Operand.getOperand(0));
  5054. break;
  5055. case ISD::VSCALE:
  5056. assert(VT == Operand.getValueType() && "Unexpected VT!");
  5057. break;
  5058. case ISD::CTPOP:
  5059. if (Operand.getValueType().getScalarType() == MVT::i1)
  5060. return Operand;
  5061. break;
  5062. case ISD::CTLZ:
  5063. case ISD::CTTZ:
  5064. if (Operand.getValueType().getScalarType() == MVT::i1)
  5065. return getNOT(DL, Operand, Operand.getValueType());
  5066. break;
  5067. case ISD::VECREDUCE_ADD:
  5068. if (Operand.getValueType().getScalarType() == MVT::i1)
  5069. return getNode(ISD::VECREDUCE_XOR, DL, VT, Operand);
  5070. break;
  5071. case ISD::VECREDUCE_SMIN:
  5072. case ISD::VECREDUCE_UMAX:
  5073. if (Operand.getValueType().getScalarType() == MVT::i1)
  5074. return getNode(ISD::VECREDUCE_OR, DL, VT, Operand);
  5075. break;
  5076. case ISD::VECREDUCE_SMAX:
  5077. case ISD::VECREDUCE_UMIN:
  5078. if (Operand.getValueType().getScalarType() == MVT::i1)
  5079. return getNode(ISD::VECREDUCE_AND, DL, VT, Operand);
  5080. break;
  5081. }
  5082. SDNode *N;
  5083. SDVTList VTs = getVTList(VT);
  5084. SDValue Ops[] = {Operand};
  5085. if (VT != MVT::Glue) { // Don't CSE flag producing nodes
  5086. FoldingSetNodeID ID;
  5087. AddNodeIDNode(ID, Opcode, VTs, Ops);
  5088. void *IP = nullptr;
  5089. if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
  5090. E->intersectFlagsWith(Flags);
  5091. return SDValue(E, 0);
  5092. }
  5093. N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
  5094. N->setFlags(Flags);
  5095. createOperands(N, Ops);
  5096. CSEMap.InsertNode(N, IP);
  5097. } else {
  5098. N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
  5099. createOperands(N, Ops);
  5100. }
  5101. InsertNode(N);
  5102. SDValue V = SDValue(N, 0);
  5103. NewSDValueDbgMsg(V, "Creating new node: ", this);
  5104. return V;
  5105. }
  5106. static std::optional<APInt> FoldValue(unsigned Opcode, const APInt &C1,
  5107. const APInt &C2) {
  5108. switch (Opcode) {
  5109. case ISD::ADD: return C1 + C2;
  5110. case ISD::SUB: return C1 - C2;
  5111. case ISD::MUL: return C1 * C2;
  5112. case ISD::AND: return C1 & C2;
  5113. case ISD::OR: return C1 | C2;
  5114. case ISD::XOR: return C1 ^ C2;
  5115. case ISD::SHL: return C1 << C2;
  5116. case ISD::SRL: return C1.lshr(C2);
  5117. case ISD::SRA: return C1.ashr(C2);
  5118. case ISD::ROTL: return C1.rotl(C2);
  5119. case ISD::ROTR: return C1.rotr(C2);
  5120. case ISD::SMIN: return C1.sle(C2) ? C1 : C2;
  5121. case ISD::SMAX: return C1.sge(C2) ? C1 : C2;
  5122. case ISD::UMIN: return C1.ule(C2) ? C1 : C2;
  5123. case ISD::UMAX: return C1.uge(C2) ? C1 : C2;
  5124. case ISD::SADDSAT: return C1.sadd_sat(C2);
  5125. case ISD::UADDSAT: return C1.uadd_sat(C2);
  5126. case ISD::SSUBSAT: return C1.ssub_sat(C2);
  5127. case ISD::USUBSAT: return C1.usub_sat(C2);
  5128. case ISD::SSHLSAT: return C1.sshl_sat(C2);
  5129. case ISD::USHLSAT: return C1.ushl_sat(C2);
  5130. case ISD::UDIV:
  5131. if (!C2.getBoolValue())
  5132. break;
  5133. return C1.udiv(C2);
  5134. case ISD::UREM:
  5135. if (!C2.getBoolValue())
  5136. break;
  5137. return C1.urem(C2);
  5138. case ISD::SDIV:
  5139. if (!C2.getBoolValue())
  5140. break;
  5141. return C1.sdiv(C2);
  5142. case ISD::SREM:
  5143. if (!C2.getBoolValue())
  5144. break;
  5145. return C1.srem(C2);
  5146. case ISD::MULHS: {
  5147. unsigned FullWidth = C1.getBitWidth() * 2;
  5148. APInt C1Ext = C1.sext(FullWidth);
  5149. APInt C2Ext = C2.sext(FullWidth);
  5150. return (C1Ext * C2Ext).extractBits(C1.getBitWidth(), C1.getBitWidth());
  5151. }
  5152. case ISD::MULHU: {
  5153. unsigned FullWidth = C1.getBitWidth() * 2;
  5154. APInt C1Ext = C1.zext(FullWidth);
  5155. APInt C2Ext = C2.zext(FullWidth);
  5156. return (C1Ext * C2Ext).extractBits(C1.getBitWidth(), C1.getBitWidth());
  5157. }
  5158. case ISD::AVGFLOORS: {
  5159. unsigned FullWidth = C1.getBitWidth() + 1;
  5160. APInt C1Ext = C1.sext(FullWidth);
  5161. APInt C2Ext = C2.sext(FullWidth);
  5162. return (C1Ext + C2Ext).extractBits(C1.getBitWidth(), 1);
  5163. }
  5164. case ISD::AVGFLOORU: {
  5165. unsigned FullWidth = C1.getBitWidth() + 1;
  5166. APInt C1Ext = C1.zext(FullWidth);
  5167. APInt C2Ext = C2.zext(FullWidth);
  5168. return (C1Ext + C2Ext).extractBits(C1.getBitWidth(), 1);
  5169. }
  5170. case ISD::AVGCEILS: {
  5171. unsigned FullWidth = C1.getBitWidth() + 1;
  5172. APInt C1Ext = C1.sext(FullWidth);
  5173. APInt C2Ext = C2.sext(FullWidth);
  5174. return (C1Ext + C2Ext + 1).extractBits(C1.getBitWidth(), 1);
  5175. }
  5176. case ISD::AVGCEILU: {
  5177. unsigned FullWidth = C1.getBitWidth() + 1;
  5178. APInt C1Ext = C1.zext(FullWidth);
  5179. APInt C2Ext = C2.zext(FullWidth);
  5180. return (C1Ext + C2Ext + 1).extractBits(C1.getBitWidth(), 1);
  5181. }
  5182. }
  5183. return std::nullopt;
  5184. }
  5185. // Handle constant folding with UNDEF.
  5186. // TODO: Handle more cases.
  5187. static std::optional<APInt> FoldValueWithUndef(unsigned Opcode, const APInt &C1,
  5188. bool IsUndef1, const APInt &C2,
  5189. bool IsUndef2) {
  5190. if (!(IsUndef1 || IsUndef2))
  5191. return FoldValue(Opcode, C1, C2);
  5192. // Fold and(x, undef) -> 0
  5193. // Fold mul(x, undef) -> 0
  5194. if (Opcode == ISD::AND || Opcode == ISD::MUL)
  5195. return APInt::getZero(C1.getBitWidth());
  5196. return std::nullopt;
  5197. }
  5198. SDValue SelectionDAG::FoldSymbolOffset(unsigned Opcode, EVT VT,
  5199. const GlobalAddressSDNode *GA,
  5200. const SDNode *N2) {
  5201. if (GA->getOpcode() != ISD::GlobalAddress)
  5202. return SDValue();
  5203. if (!TLI->isOffsetFoldingLegal(GA))
  5204. return SDValue();
  5205. auto *C2 = dyn_cast<ConstantSDNode>(N2);
  5206. if (!C2)
  5207. return SDValue();
  5208. int64_t Offset = C2->getSExtValue();
  5209. switch (Opcode) {
  5210. case ISD::ADD: break;
  5211. case ISD::SUB: Offset = -uint64_t(Offset); break;
  5212. default: return SDValue();
  5213. }
  5214. return getGlobalAddress(GA->getGlobal(), SDLoc(C2), VT,
  5215. GA->getOffset() + uint64_t(Offset));
  5216. }
  5217. bool SelectionDAG::isUndef(unsigned Opcode, ArrayRef<SDValue> Ops) {
  5218. switch (Opcode) {
  5219. case ISD::SDIV:
  5220. case ISD::UDIV:
  5221. case ISD::SREM:
  5222. case ISD::UREM: {
  5223. // If a divisor is zero/undef or any element of a divisor vector is
  5224. // zero/undef, the whole op is undef.
  5225. assert(Ops.size() == 2 && "Div/rem should have 2 operands");
  5226. SDValue Divisor = Ops[1];
  5227. if (Divisor.isUndef() || isNullConstant(Divisor))
  5228. return true;
  5229. return ISD::isBuildVectorOfConstantSDNodes(Divisor.getNode()) &&
  5230. llvm::any_of(Divisor->op_values(),
  5231. [](SDValue V) { return V.isUndef() ||
  5232. isNullConstant(V); });
  5233. // TODO: Handle signed overflow.
  5234. }
  5235. // TODO: Handle oversized shifts.
  5236. default:
  5237. return false;
  5238. }
  5239. }
  5240. SDValue SelectionDAG::FoldConstantArithmetic(unsigned Opcode, const SDLoc &DL,
  5241. EVT VT, ArrayRef<SDValue> Ops) {
  5242. // If the opcode is a target-specific ISD node, there's nothing we can
  5243. // do here and the operand rules may not line up with the below, so
  5244. // bail early.
  5245. // We can't create a scalar CONCAT_VECTORS so skip it. It will break
  5246. // for concats involving SPLAT_VECTOR. Concats of BUILD_VECTORS are handled by
  5247. // foldCONCAT_VECTORS in getNode before this is called.
  5248. if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::CONCAT_VECTORS)
  5249. return SDValue();
  5250. unsigned NumOps = Ops.size();
  5251. if (NumOps == 0)
  5252. return SDValue();
  5253. if (isUndef(Opcode, Ops))
  5254. return getUNDEF(VT);
  5255. // Handle binops special cases.
  5256. if (NumOps == 2) {
  5257. if (SDValue CFP = foldConstantFPMath(Opcode, DL, VT, Ops[0], Ops[1]))
  5258. return CFP;
  5259. if (auto *C1 = dyn_cast<ConstantSDNode>(Ops[0])) {
  5260. if (auto *C2 = dyn_cast<ConstantSDNode>(Ops[1])) {
  5261. if (C1->isOpaque() || C2->isOpaque())
  5262. return SDValue();
  5263. std::optional<APInt> FoldAttempt =
  5264. FoldValue(Opcode, C1->getAPIntValue(), C2->getAPIntValue());
  5265. if (!FoldAttempt)
  5266. return SDValue();
  5267. SDValue Folded = getConstant(*FoldAttempt, DL, VT);
  5268. assert((!Folded || !VT.isVector()) &&
  5269. "Can't fold vectors ops with scalar operands");
  5270. return Folded;
  5271. }
  5272. }
  5273. // fold (add Sym, c) -> Sym+c
  5274. if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Ops[0]))
  5275. return FoldSymbolOffset(Opcode, VT, GA, Ops[1].getNode());
  5276. if (TLI->isCommutativeBinOp(Opcode))
  5277. if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Ops[1]))
  5278. return FoldSymbolOffset(Opcode, VT, GA, Ops[0].getNode());
  5279. }
  5280. // This is for vector folding only from here on.
  5281. if (!VT.isVector())
  5282. return SDValue();
  5283. ElementCount NumElts = VT.getVectorElementCount();
  5284. // See if we can fold through bitcasted integer ops.
  5285. if (NumOps == 2 && VT.isFixedLengthVector() && VT.isInteger() &&
  5286. Ops[0].getValueType() == VT && Ops[1].getValueType() == VT &&
  5287. Ops[0].getOpcode() == ISD::BITCAST &&
  5288. Ops[1].getOpcode() == ISD::BITCAST) {
  5289. SDValue N1 = peekThroughBitcasts(Ops[0]);
  5290. SDValue N2 = peekThroughBitcasts(Ops[1]);
  5291. auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
  5292. auto *BV2 = dyn_cast<BuildVectorSDNode>(N2);
  5293. EVT BVVT = N1.getValueType();
  5294. if (BV1 && BV2 && BVVT.isInteger() && BVVT == N2.getValueType()) {
  5295. bool IsLE = getDataLayout().isLittleEndian();
  5296. unsigned EltBits = VT.getScalarSizeInBits();
  5297. SmallVector<APInt> RawBits1, RawBits2;
  5298. BitVector UndefElts1, UndefElts2;
  5299. if (BV1->getConstantRawBits(IsLE, EltBits, RawBits1, UndefElts1) &&
  5300. BV2->getConstantRawBits(IsLE, EltBits, RawBits2, UndefElts2)) {
  5301. SmallVector<APInt> RawBits;
  5302. for (unsigned I = 0, E = NumElts.getFixedValue(); I != E; ++I) {
  5303. std::optional<APInt> Fold = FoldValueWithUndef(
  5304. Opcode, RawBits1[I], UndefElts1[I], RawBits2[I], UndefElts2[I]);
  5305. if (!Fold)
  5306. break;
  5307. RawBits.push_back(*Fold);
  5308. }
  5309. if (RawBits.size() == NumElts.getFixedValue()) {
  5310. // We have constant folded, but we need to cast this again back to
  5311. // the original (possibly legalized) type.
  5312. SmallVector<APInt> DstBits;
  5313. BitVector DstUndefs;
  5314. BuildVectorSDNode::recastRawBits(IsLE, BVVT.getScalarSizeInBits(),
  5315. DstBits, RawBits, DstUndefs,
  5316. BitVector(RawBits.size(), false));
  5317. EVT BVEltVT = BV1->getOperand(0).getValueType();
  5318. unsigned BVEltBits = BVEltVT.getSizeInBits();
  5319. SmallVector<SDValue> Ops(DstBits.size(), getUNDEF(BVEltVT));
  5320. for (unsigned I = 0, E = DstBits.size(); I != E; ++I) {
  5321. if (DstUndefs[I])
  5322. continue;
  5323. Ops[I] = getConstant(DstBits[I].sext(BVEltBits), DL, BVEltVT);
  5324. }
  5325. return getBitcast(VT, getBuildVector(BVVT, DL, Ops));
  5326. }
  5327. }
  5328. }
  5329. }
  5330. // Fold (mul step_vector(C0), C1) to (step_vector(C0 * C1)).
  5331. // (shl step_vector(C0), C1) -> (step_vector(C0 << C1))
  5332. if ((Opcode == ISD::MUL || Opcode == ISD::SHL) &&
  5333. Ops[0].getOpcode() == ISD::STEP_VECTOR) {
  5334. APInt RHSVal;
  5335. if (ISD::isConstantSplatVector(Ops[1].getNode(), RHSVal)) {
  5336. APInt NewStep = Opcode == ISD::MUL
  5337. ? Ops[0].getConstantOperandAPInt(0) * RHSVal
  5338. : Ops[0].getConstantOperandAPInt(0) << RHSVal;
  5339. return getStepVector(DL, VT, NewStep);
  5340. }
  5341. }
  5342. auto IsScalarOrSameVectorSize = [NumElts](const SDValue &Op) {
  5343. return !Op.getValueType().isVector() ||
  5344. Op.getValueType().getVectorElementCount() == NumElts;
  5345. };
  5346. auto IsBuildVectorSplatVectorOrUndef = [](const SDValue &Op) {
  5347. return Op.isUndef() || Op.getOpcode() == ISD::CONDCODE ||
  5348. Op.getOpcode() == ISD::BUILD_VECTOR ||
  5349. Op.getOpcode() == ISD::SPLAT_VECTOR;
  5350. };
  5351. // All operands must be vector types with the same number of elements as
  5352. // the result type and must be either UNDEF or a build/splat vector
  5353. // or UNDEF scalars.
  5354. if (!llvm::all_of(Ops, IsBuildVectorSplatVectorOrUndef) ||
  5355. !llvm::all_of(Ops, IsScalarOrSameVectorSize))
  5356. return SDValue();
  5357. // If we are comparing vectors, then the result needs to be a i1 boolean that
  5358. // is then extended back to the legal result type depending on how booleans
  5359. // are represented.
  5360. EVT SVT = (Opcode == ISD::SETCC ? MVT::i1 : VT.getScalarType());
  5361. ISD::NodeType ExtendCode =
  5362. (Opcode == ISD::SETCC && SVT != VT.getScalarType())
  5363. ? TargetLowering::getExtendForContent(TLI->getBooleanContents(VT))
  5364. : ISD::SIGN_EXTEND;
  5365. // Find legal integer scalar type for constant promotion and
  5366. // ensure that its scalar size is at least as large as source.
  5367. EVT LegalSVT = VT.getScalarType();
  5368. if (NewNodesMustHaveLegalTypes && LegalSVT.isInteger()) {
  5369. LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT);
  5370. if (LegalSVT.bitsLT(VT.getScalarType()))
  5371. return SDValue();
  5372. }
  5373. // For scalable vector types we know we're dealing with SPLAT_VECTORs. We
  5374. // only have one operand to check. For fixed-length vector types we may have
  5375. // a combination of BUILD_VECTOR and SPLAT_VECTOR.
  5376. unsigned NumVectorElts = NumElts.isScalable() ? 1 : NumElts.getFixedValue();
  5377. // Constant fold each scalar lane separately.
  5378. SmallVector<SDValue, 4> ScalarResults;
  5379. for (unsigned I = 0; I != NumVectorElts; I++) {
  5380. SmallVector<SDValue, 4> ScalarOps;
  5381. for (SDValue Op : Ops) {
  5382. EVT InSVT = Op.getValueType().getScalarType();
  5383. if (Op.getOpcode() != ISD::BUILD_VECTOR &&
  5384. Op.getOpcode() != ISD::SPLAT_VECTOR) {
  5385. if (Op.isUndef())
  5386. ScalarOps.push_back(getUNDEF(InSVT));
  5387. else
  5388. ScalarOps.push_back(Op);
  5389. continue;
  5390. }
  5391. SDValue ScalarOp =
  5392. Op.getOperand(Op.getOpcode() == ISD::SPLAT_VECTOR ? 0 : I);
  5393. EVT ScalarVT = ScalarOp.getValueType();
  5394. // Build vector (integer) scalar operands may need implicit
  5395. // truncation - do this before constant folding.
  5396. if (ScalarVT.isInteger() && ScalarVT.bitsGT(InSVT)) {
  5397. // Don't create illegally-typed nodes unless they're constants or undef
  5398. // - if we fail to constant fold we can't guarantee the (dead) nodes
  5399. // we're creating will be cleaned up before being visited for
  5400. // legalization.
  5401. if (NewNodesMustHaveLegalTypes && !ScalarOp.isUndef() &&
  5402. !isa<ConstantSDNode>(ScalarOp) &&
  5403. TLI->getTypeAction(*getContext(), InSVT) !=
  5404. TargetLowering::TypeLegal)
  5405. return SDValue();
  5406. ScalarOp = getNode(ISD::TRUNCATE, DL, InSVT, ScalarOp);
  5407. }
  5408. ScalarOps.push_back(ScalarOp);
  5409. }
  5410. // Constant fold the scalar operands.
  5411. SDValue ScalarResult = getNode(Opcode, DL, SVT, ScalarOps);
  5412. // Legalize the (integer) scalar constant if necessary.
  5413. if (LegalSVT != SVT)
  5414. ScalarResult = getNode(ExtendCode, DL, LegalSVT, ScalarResult);
  5415. // Scalar folding only succeeded if the result is a constant or UNDEF.
  5416. if (!ScalarResult.isUndef() && ScalarResult.getOpcode() != ISD::Constant &&
  5417. ScalarResult.getOpcode() != ISD::ConstantFP)
  5418. return SDValue();
  5419. ScalarResults.push_back(ScalarResult);
  5420. }
  5421. SDValue V = NumElts.isScalable() ? getSplatVector(VT, DL, ScalarResults[0])
  5422. : getBuildVector(VT, DL, ScalarResults);
  5423. NewSDValueDbgMsg(V, "New node fold constant vector: ", this);
  5424. return V;
  5425. }
  5426. SDValue SelectionDAG::foldConstantFPMath(unsigned Opcode, const SDLoc &DL,
  5427. EVT VT, SDValue N1, SDValue N2) {
  5428. // TODO: We don't do any constant folding for strict FP opcodes here, but we
  5429. // should. That will require dealing with a potentially non-default
  5430. // rounding mode, checking the "opStatus" return value from the APFloat
  5431. // math calculations, and possibly other variations.
  5432. ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1, /*AllowUndefs*/ false);
  5433. ConstantFPSDNode *N2CFP = isConstOrConstSplatFP(N2, /*AllowUndefs*/ false);
  5434. if (N1CFP && N2CFP) {
  5435. APFloat C1 = N1CFP->getValueAPF(); // make copy
  5436. const APFloat &C2 = N2CFP->getValueAPF();
  5437. switch (Opcode) {
  5438. case ISD::FADD:
  5439. C1.add(C2, APFloat::rmNearestTiesToEven);
  5440. return getConstantFP(C1, DL, VT);
  5441. case ISD::FSUB:
  5442. C1.subtract(C2, APFloat::rmNearestTiesToEven);
  5443. return getConstantFP(C1, DL, VT);
  5444. case ISD::FMUL:
  5445. C1.multiply(C2, APFloat::rmNearestTiesToEven);
  5446. return getConstantFP(C1, DL, VT);
  5447. case ISD::FDIV:
  5448. C1.divide(C2, APFloat::rmNearestTiesToEven);
  5449. return getConstantFP(C1, DL, VT);
  5450. case ISD::FREM:
  5451. C1.mod(C2);
  5452. return getConstantFP(C1, DL, VT);
  5453. case ISD::FCOPYSIGN:
  5454. C1.copySign(C2);
  5455. return getConstantFP(C1, DL, VT);
  5456. case ISD::FMINNUM:
  5457. return getConstantFP(minnum(C1, C2), DL, VT);
  5458. case ISD::FMAXNUM:
  5459. return getConstantFP(maxnum(C1, C2), DL, VT);
  5460. case ISD::FMINIMUM:
  5461. return getConstantFP(minimum(C1, C2), DL, VT);
  5462. case ISD::FMAXIMUM:
  5463. return getConstantFP(maximum(C1, C2), DL, VT);
  5464. default: break;
  5465. }
  5466. }
  5467. if (N1CFP && Opcode == ISD::FP_ROUND) {
  5468. APFloat C1 = N1CFP->getValueAPF(); // make copy
  5469. bool Unused;
  5470. // This can return overflow, underflow, or inexact; we don't care.
  5471. // FIXME need to be more flexible about rounding mode.
  5472. (void) C1.convert(EVTToAPFloatSemantics(VT), APFloat::rmNearestTiesToEven,
  5473. &Unused);
  5474. return getConstantFP(C1, DL, VT);
  5475. }
  5476. switch (Opcode) {
  5477. case ISD::FSUB:
  5478. // -0.0 - undef --> undef (consistent with "fneg undef")
  5479. if (ConstantFPSDNode *N1C = isConstOrConstSplatFP(N1, /*AllowUndefs*/ true))
  5480. if (N1C && N1C->getValueAPF().isNegZero() && N2.isUndef())
  5481. return getUNDEF(VT);
  5482. [[fallthrough]];
  5483. case ISD::FADD:
  5484. case ISD::FMUL:
  5485. case ISD::FDIV:
  5486. case ISD::FREM:
  5487. // If both operands are undef, the result is undef. If 1 operand is undef,
  5488. // the result is NaN. This should match the behavior of the IR optimizer.
  5489. if (N1.isUndef() && N2.isUndef())
  5490. return getUNDEF(VT);
  5491. if (N1.isUndef() || N2.isUndef())
  5492. return getConstantFP(APFloat::getNaN(EVTToAPFloatSemantics(VT)), DL, VT);
  5493. }
  5494. return SDValue();
  5495. }
  5496. SDValue SelectionDAG::getAssertAlign(const SDLoc &DL, SDValue Val, Align A) {
  5497. assert(Val.getValueType().isInteger() && "Invalid AssertAlign!");
  5498. // There's no need to assert on a byte-aligned pointer. All pointers are at
  5499. // least byte aligned.
  5500. if (A == Align(1))
  5501. return Val;
  5502. FoldingSetNodeID ID;
  5503. AddNodeIDNode(ID, ISD::AssertAlign, getVTList(Val.getValueType()), {Val});
  5504. ID.AddInteger(A.value());
  5505. void *IP = nullptr;
  5506. if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
  5507. return SDValue(E, 0);
  5508. auto *N = newSDNode<AssertAlignSDNode>(DL.getIROrder(), DL.getDebugLoc(),
  5509. Val.getValueType(), A);
  5510. createOperands(N, {Val});
  5511. CSEMap.InsertNode(N, IP);
  5512. InsertNode(N);
  5513. SDValue V(N, 0);
  5514. NewSDValueDbgMsg(V, "Creating new node: ", this);
  5515. return V;
  5516. }
  5517. SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
  5518. SDValue N1, SDValue N2) {
  5519. SDNodeFlags Flags;
  5520. if (Inserter)
  5521. Flags = Inserter->getFlags();
  5522. return getNode(Opcode, DL, VT, N1, N2, Flags);
  5523. }
  5524. void SelectionDAG::canonicalizeCommutativeBinop(unsigned Opcode, SDValue &N1,
  5525. SDValue &N2) const {
  5526. if (!TLI->isCommutativeBinOp(Opcode))
  5527. return;
  5528. // Canonicalize:
  5529. // binop(const, nonconst) -> binop(nonconst, const)
  5530. SDNode *N1C = isConstantIntBuildVectorOrConstantInt(N1);
  5531. SDNode *N2C = isConstantIntBuildVectorOrConstantInt(N2);
  5532. SDNode *N1CFP = isConstantFPBuildVectorOrConstantFP(N1);
  5533. SDNode *N2CFP = isConstantFPBuildVectorOrConstantFP(N2);
  5534. if ((N1C && !N2C) || (N1CFP && !N2CFP))
  5535. std::swap(N1, N2);
  5536. // Canonicalize:
  5537. // binop(splat(x), step_vector) -> binop(step_vector, splat(x))
  5538. else if (N1.getOpcode() == ISD::SPLAT_VECTOR &&
  5539. N2.getOpcode() == ISD::STEP_VECTOR)
  5540. std::swap(N1, N2);
  5541. }
  5542. SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
  5543. SDValue N1, SDValue N2, const SDNodeFlags Flags) {
  5544. assert(N1.getOpcode() != ISD::DELETED_NODE &&
  5545. N2.getOpcode() != ISD::DELETED_NODE &&
  5546. "Operand is DELETED_NODE!");
  5547. canonicalizeCommutativeBinop(Opcode, N1, N2);
  5548. auto *N1C = dyn_cast<ConstantSDNode>(N1);
  5549. auto *N2C = dyn_cast<ConstantSDNode>(N2);
  5550. // Don't allow undefs in vector splats - we might be returning N2 when folding
  5551. // to zero etc.
  5552. ConstantSDNode *N2CV =
  5553. isConstOrConstSplat(N2, /*AllowUndefs*/ false, /*AllowTruncation*/ true);
  5554. switch (Opcode) {
  5555. default: break;
  5556. case ISD::TokenFactor:
  5557. assert(VT == MVT::Other && N1.getValueType() == MVT::Other &&
  5558. N2.getValueType() == MVT::Other && "Invalid token factor!");
  5559. // Fold trivial token factors.
  5560. if (N1.getOpcode() == ISD::EntryToken) return N2;
  5561. if (N2.getOpcode() == ISD::EntryToken) return N1;
  5562. if (N1 == N2) return N1;
  5563. break;
  5564. case ISD::BUILD_VECTOR: {
  5565. // Attempt to simplify BUILD_VECTOR.
  5566. SDValue Ops[] = {N1, N2};
  5567. if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
  5568. return V;
  5569. break;
  5570. }
  5571. case ISD::CONCAT_VECTORS: {
  5572. SDValue Ops[] = {N1, N2};
  5573. if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
  5574. return V;
  5575. break;
  5576. }
  5577. case ISD::AND:
  5578. assert(VT.isInteger() && "This operator does not apply to FP types!");
  5579. assert(N1.getValueType() == N2.getValueType() &&
  5580. N1.getValueType() == VT && "Binary operator types must match!");
  5581. // (X & 0) -> 0. This commonly occurs when legalizing i64 values, so it's
  5582. // worth handling here.
  5583. if (N2CV && N2CV->isZero())
  5584. return N2;
  5585. if (N2CV && N2CV->isAllOnes()) // X & -1 -> X
  5586. return N1;
  5587. break;
  5588. case ISD::OR:
  5589. case ISD::XOR:
  5590. case ISD::ADD:
  5591. case ISD::SUB:
  5592. assert(VT.isInteger() && "This operator does not apply to FP types!");
  5593. assert(N1.getValueType() == N2.getValueType() &&
  5594. N1.getValueType() == VT && "Binary operator types must match!");
  5595. // (X ^|+- 0) -> X. This commonly occurs when legalizing i64 values, so
  5596. // it's worth handling here.
  5597. if (N2CV && N2CV->isZero())
  5598. return N1;
  5599. if ((Opcode == ISD::ADD || Opcode == ISD::SUB) && VT.isVector() &&
  5600. VT.getVectorElementType() == MVT::i1)
  5601. return getNode(ISD::XOR, DL, VT, N1, N2);
  5602. break;
  5603. case ISD::MUL:
  5604. assert(VT.isInteger() && "This operator does not apply to FP types!");
  5605. assert(N1.getValueType() == N2.getValueType() &&
  5606. N1.getValueType() == VT && "Binary operator types must match!");
  5607. if (VT.isVector() && VT.getVectorElementType() == MVT::i1)
  5608. return getNode(ISD::AND, DL, VT, N1, N2);
  5609. if (N2C && (N1.getOpcode() == ISD::VSCALE) && Flags.hasNoSignedWrap()) {
  5610. const APInt &MulImm = N1->getConstantOperandAPInt(0);
  5611. const APInt &N2CImm = N2C->getAPIntValue();
  5612. return getVScale(DL, VT, MulImm * N2CImm);
  5613. }
  5614. break;
  5615. case ISD::UDIV:
  5616. case ISD::UREM:
  5617. case ISD::MULHU:
  5618. case ISD::MULHS:
  5619. case ISD::SDIV:
  5620. case ISD::SREM:
  5621. case ISD::SADDSAT:
  5622. case ISD::SSUBSAT:
  5623. case ISD::UADDSAT:
  5624. case ISD::USUBSAT:
  5625. assert(VT.isInteger() && "This operator does not apply to FP types!");
  5626. assert(N1.getValueType() == N2.getValueType() &&
  5627. N1.getValueType() == VT && "Binary operator types must match!");
  5628. if (VT.isVector() && VT.getVectorElementType() == MVT::i1) {
  5629. // fold (add_sat x, y) -> (or x, y) for bool types.
  5630. if (Opcode == ISD::SADDSAT || Opcode == ISD::UADDSAT)
  5631. return getNode(ISD::OR, DL, VT, N1, N2);
  5632. // fold (sub_sat x, y) -> (and x, ~y) for bool types.
  5633. if (Opcode == ISD::SSUBSAT || Opcode == ISD::USUBSAT)
  5634. return getNode(ISD::AND, DL, VT, N1, getNOT(DL, N2, VT));
  5635. }
  5636. break;
  5637. case ISD::ABDS:
  5638. case ISD::ABDU:
  5639. assert(VT.isInteger() && "This operator does not apply to FP types!");
  5640. assert(N1.getValueType() == N2.getValueType() &&
  5641. N1.getValueType() == VT && "Binary operator types must match!");
  5642. break;
  5643. case ISD::SMIN:
  5644. case ISD::UMAX:
  5645. assert(VT.isInteger() && "This operator does not apply to FP types!");
  5646. assert(N1.getValueType() == N2.getValueType() &&
  5647. N1.getValueType() == VT && "Binary operator types must match!");
  5648. if (VT.isVector() && VT.getVectorElementType() == MVT::i1)
  5649. return getNode(ISD::OR, DL, VT, N1, N2);
  5650. break;
  5651. case ISD::SMAX:
  5652. case ISD::UMIN:
  5653. assert(VT.isInteger() && "This operator does not apply to FP types!");
  5654. assert(N1.getValueType() == N2.getValueType() &&
  5655. N1.getValueType() == VT && "Binary operator types must match!");
  5656. if (VT.isVector() && VT.getVectorElementType() == MVT::i1)
  5657. return getNode(ISD::AND, DL, VT, N1, N2);
  5658. break;
  5659. case ISD::FADD:
  5660. case ISD::FSUB:
  5661. case ISD::FMUL:
  5662. case ISD::FDIV:
  5663. case ISD::FREM:
  5664. assert(VT.isFloatingPoint() && "This operator only applies to FP types!");
  5665. assert(N1.getValueType() == N2.getValueType() &&
  5666. N1.getValueType() == VT && "Binary operator types must match!");
  5667. if (SDValue V = simplifyFPBinop(Opcode, N1, N2, Flags))
  5668. return V;
  5669. break;
  5670. case ISD::FCOPYSIGN: // N1 and result must match. N1/N2 need not match.
  5671. assert(N1.getValueType() == VT &&
  5672. N1.getValueType().isFloatingPoint() &&
  5673. N2.getValueType().isFloatingPoint() &&
  5674. "Invalid FCOPYSIGN!");
  5675. break;
  5676. case ISD::SHL:
  5677. if (N2C && (N1.getOpcode() == ISD::VSCALE) && Flags.hasNoSignedWrap()) {
  5678. const APInt &MulImm = N1->getConstantOperandAPInt(0);
  5679. const APInt &ShiftImm = N2C->getAPIntValue();
  5680. return getVScale(DL, VT, MulImm << ShiftImm);
  5681. }
  5682. [[fallthrough]];
  5683. case ISD::SRA:
  5684. case ISD::SRL:
  5685. if (SDValue V = simplifyShift(N1, N2))
  5686. return V;
  5687. [[fallthrough]];
  5688. case ISD::ROTL:
  5689. case ISD::ROTR:
  5690. assert(VT == N1.getValueType() &&
  5691. "Shift operators return type must be the same as their first arg");
  5692. assert(VT.isInteger() && N2.getValueType().isInteger() &&
  5693. "Shifts only work on integers");
  5694. assert((!VT.isVector() || VT == N2.getValueType()) &&
  5695. "Vector shift amounts must be in the same as their first arg");
  5696. // Verify that the shift amount VT is big enough to hold valid shift
  5697. // amounts. This catches things like trying to shift an i1024 value by an
  5698. // i8, which is easy to fall into in generic code that uses
  5699. // TLI.getShiftAmount().
  5700. assert(N2.getValueType().getScalarSizeInBits() >=
  5701. Log2_32_Ceil(VT.getScalarSizeInBits()) &&
  5702. "Invalid use of small shift amount with oversized value!");
  5703. // Always fold shifts of i1 values so the code generator doesn't need to
  5704. // handle them. Since we know the size of the shift has to be less than the
  5705. // size of the value, the shift/rotate count is guaranteed to be zero.
  5706. if (VT == MVT::i1)
  5707. return N1;
  5708. if (N2CV && N2CV->isZero())
  5709. return N1;
  5710. break;
  5711. case ISD::FP_ROUND:
  5712. assert(VT.isFloatingPoint() &&
  5713. N1.getValueType().isFloatingPoint() &&
  5714. VT.bitsLE(N1.getValueType()) &&
  5715. N2C && (N2C->getZExtValue() == 0 || N2C->getZExtValue() == 1) &&
  5716. "Invalid FP_ROUND!");
  5717. if (N1.getValueType() == VT) return N1; // noop conversion.
  5718. break;
  5719. case ISD::AssertSext:
  5720. case ISD::AssertZext: {
  5721. EVT EVT = cast<VTSDNode>(N2)->getVT();
  5722. assert(VT == N1.getValueType() && "Not an inreg extend!");
  5723. assert(VT.isInteger() && EVT.isInteger() &&
  5724. "Cannot *_EXTEND_INREG FP types");
  5725. assert(!EVT.isVector() &&
  5726. "AssertSExt/AssertZExt type should be the vector element type "
  5727. "rather than the vector type!");
  5728. assert(EVT.bitsLE(VT.getScalarType()) && "Not extending!");
  5729. if (VT.getScalarType() == EVT) return N1; // noop assertion.
  5730. break;
  5731. }
  5732. case ISD::SIGN_EXTEND_INREG: {
  5733. EVT EVT = cast<VTSDNode>(N2)->getVT();
  5734. assert(VT == N1.getValueType() && "Not an inreg extend!");
  5735. assert(VT.isInteger() && EVT.isInteger() &&
  5736. "Cannot *_EXTEND_INREG FP types");
  5737. assert(EVT.isVector() == VT.isVector() &&
  5738. "SIGN_EXTEND_INREG type should be vector iff the operand "
  5739. "type is vector!");
  5740. assert((!EVT.isVector() ||
  5741. EVT.getVectorElementCount() == VT.getVectorElementCount()) &&
  5742. "Vector element counts must match in SIGN_EXTEND_INREG");
  5743. assert(EVT.bitsLE(VT) && "Not extending!");
  5744. if (EVT == VT) return N1; // Not actually extending
  5745. auto SignExtendInReg = [&](APInt Val, llvm::EVT ConstantVT) {
  5746. unsigned FromBits = EVT.getScalarSizeInBits();
  5747. Val <<= Val.getBitWidth() - FromBits;
  5748. Val.ashrInPlace(Val.getBitWidth() - FromBits);
  5749. return getConstant(Val, DL, ConstantVT);
  5750. };
  5751. if (N1C) {
  5752. const APInt &Val = N1C->getAPIntValue();
  5753. return SignExtendInReg(Val, VT);
  5754. }
  5755. if (ISD::isBuildVectorOfConstantSDNodes(N1.getNode())) {
  5756. SmallVector<SDValue, 8> Ops;
  5757. llvm::EVT OpVT = N1.getOperand(0).getValueType();
  5758. for (int i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
  5759. SDValue Op = N1.getOperand(i);
  5760. if (Op.isUndef()) {
  5761. Ops.push_back(getUNDEF(OpVT));
  5762. continue;
  5763. }
  5764. ConstantSDNode *C = cast<ConstantSDNode>(Op);
  5765. APInt Val = C->getAPIntValue();
  5766. Ops.push_back(SignExtendInReg(Val, OpVT));
  5767. }
  5768. return getBuildVector(VT, DL, Ops);
  5769. }
  5770. break;
  5771. }
  5772. case ISD::FP_TO_SINT_SAT:
  5773. case ISD::FP_TO_UINT_SAT: {
  5774. assert(VT.isInteger() && cast<VTSDNode>(N2)->getVT().isInteger() &&
  5775. N1.getValueType().isFloatingPoint() && "Invalid FP_TO_*INT_SAT");
  5776. assert(N1.getValueType().isVector() == VT.isVector() &&
  5777. "FP_TO_*INT_SAT type should be vector iff the operand type is "
  5778. "vector!");
  5779. assert((!VT.isVector() || VT.getVectorElementCount() ==
  5780. N1.getValueType().getVectorElementCount()) &&
  5781. "Vector element counts must match in FP_TO_*INT_SAT");
  5782. assert(!cast<VTSDNode>(N2)->getVT().isVector() &&
  5783. "Type to saturate to must be a scalar.");
  5784. assert(cast<VTSDNode>(N2)->getVT().bitsLE(VT.getScalarType()) &&
  5785. "Not extending!");
  5786. break;
  5787. }
  5788. case ISD::EXTRACT_VECTOR_ELT:
  5789. assert(VT.getSizeInBits() >= N1.getValueType().getScalarSizeInBits() &&
  5790. "The result of EXTRACT_VECTOR_ELT must be at least as wide as the \
  5791. element type of the vector.");
  5792. // Extract from an undefined value or using an undefined index is undefined.
  5793. if (N1.isUndef() || N2.isUndef())
  5794. return getUNDEF(VT);
  5795. // EXTRACT_VECTOR_ELT of out-of-bounds element is an UNDEF for fixed length
  5796. // vectors. For scalable vectors we will provide appropriate support for
  5797. // dealing with arbitrary indices.
  5798. if (N2C && N1.getValueType().isFixedLengthVector() &&
  5799. N2C->getAPIntValue().uge(N1.getValueType().getVectorNumElements()))
  5800. return getUNDEF(VT);
  5801. // EXTRACT_VECTOR_ELT of CONCAT_VECTORS is often formed while lowering is
  5802. // expanding copies of large vectors from registers. This only works for
  5803. // fixed length vectors, since we need to know the exact number of
  5804. // elements.
  5805. if (N2C && N1.getOperand(0).getValueType().isFixedLengthVector() &&
  5806. N1.getOpcode() == ISD::CONCAT_VECTORS && N1.getNumOperands() > 0) {
  5807. unsigned Factor =
  5808. N1.getOperand(0).getValueType().getVectorNumElements();
  5809. return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
  5810. N1.getOperand(N2C->getZExtValue() / Factor),
  5811. getVectorIdxConstant(N2C->getZExtValue() % Factor, DL));
  5812. }
  5813. // EXTRACT_VECTOR_ELT of BUILD_VECTOR or SPLAT_VECTOR is often formed while
  5814. // lowering is expanding large vector constants.
  5815. if (N2C && (N1.getOpcode() == ISD::BUILD_VECTOR ||
  5816. N1.getOpcode() == ISD::SPLAT_VECTOR)) {
  5817. assert((N1.getOpcode() != ISD::BUILD_VECTOR ||
  5818. N1.getValueType().isFixedLengthVector()) &&
  5819. "BUILD_VECTOR used for scalable vectors");
  5820. unsigned Index =
  5821. N1.getOpcode() == ISD::BUILD_VECTOR ? N2C->getZExtValue() : 0;
  5822. SDValue Elt = N1.getOperand(Index);
  5823. if (VT != Elt.getValueType())
  5824. // If the vector element type is not legal, the BUILD_VECTOR operands
  5825. // are promoted and implicitly truncated, and the result implicitly
  5826. // extended. Make that explicit here.
  5827. Elt = getAnyExtOrTrunc(Elt, DL, VT);
  5828. return Elt;
  5829. }
  5830. // EXTRACT_VECTOR_ELT of INSERT_VECTOR_ELT is often formed when vector
  5831. // operations are lowered to scalars.
  5832. if (N1.getOpcode() == ISD::INSERT_VECTOR_ELT) {
  5833. // If the indices are the same, return the inserted element else
  5834. // if the indices are known different, extract the element from
  5835. // the original vector.
  5836. SDValue N1Op2 = N1.getOperand(2);
  5837. ConstantSDNode *N1Op2C = dyn_cast<ConstantSDNode>(N1Op2);
  5838. if (N1Op2C && N2C) {
  5839. if (N1Op2C->getZExtValue() == N2C->getZExtValue()) {
  5840. if (VT == N1.getOperand(1).getValueType())
  5841. return N1.getOperand(1);
  5842. if (VT.isFloatingPoint()) {
  5843. assert(VT.getSizeInBits() > N1.getOperand(1).getValueType().getSizeInBits());
  5844. return getFPExtendOrRound(N1.getOperand(1), DL, VT);
  5845. }
  5846. return getSExtOrTrunc(N1.getOperand(1), DL, VT);
  5847. }
  5848. return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0), N2);
  5849. }
  5850. }
  5851. // EXTRACT_VECTOR_ELT of v1iX EXTRACT_SUBVECTOR could be formed
  5852. // when vector types are scalarized and v1iX is legal.
  5853. // vextract (v1iX extract_subvector(vNiX, Idx)) -> vextract(vNiX,Idx).
  5854. // Here we are completely ignoring the extract element index (N2),
  5855. // which is fine for fixed width vectors, since any index other than 0
  5856. // is undefined anyway. However, this cannot be ignored for scalable
  5857. // vectors - in theory we could support this, but we don't want to do this
  5858. // without a profitability check.
  5859. if (N1.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
  5860. N1.getValueType().isFixedLengthVector() &&
  5861. N1.getValueType().getVectorNumElements() == 1) {
  5862. return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0),
  5863. N1.getOperand(1));
  5864. }
  5865. break;
  5866. case ISD::EXTRACT_ELEMENT:
  5867. assert(N2C && (unsigned)N2C->getZExtValue() < 2 && "Bad EXTRACT_ELEMENT!");
  5868. assert(!N1.getValueType().isVector() && !VT.isVector() &&
  5869. (N1.getValueType().isInteger() == VT.isInteger()) &&
  5870. N1.getValueType() != VT &&
  5871. "Wrong types for EXTRACT_ELEMENT!");
  5872. // EXTRACT_ELEMENT of BUILD_PAIR is often formed while legalize is expanding
  5873. // 64-bit integers into 32-bit parts. Instead of building the extract of
  5874. // the BUILD_PAIR, only to have legalize rip it apart, just do it now.
  5875. if (N1.getOpcode() == ISD::BUILD_PAIR)
  5876. return N1.getOperand(N2C->getZExtValue());
  5877. // EXTRACT_ELEMENT of a constant int is also very common.
  5878. if (N1C) {
  5879. unsigned ElementSize = VT.getSizeInBits();
  5880. unsigned Shift = ElementSize * N2C->getZExtValue();
  5881. const APInt &Val = N1C->getAPIntValue();
  5882. return getConstant(Val.extractBits(ElementSize, Shift), DL, VT);
  5883. }
  5884. break;
  5885. case ISD::EXTRACT_SUBVECTOR: {
  5886. EVT N1VT = N1.getValueType();
  5887. assert(VT.isVector() && N1VT.isVector() &&
  5888. "Extract subvector VTs must be vectors!");
  5889. assert(VT.getVectorElementType() == N1VT.getVectorElementType() &&
  5890. "Extract subvector VTs must have the same element type!");
  5891. assert((VT.isFixedLengthVector() || N1VT.isScalableVector()) &&
  5892. "Cannot extract a scalable vector from a fixed length vector!");
  5893. assert((VT.isScalableVector() != N1VT.isScalableVector() ||
  5894. VT.getVectorMinNumElements() <= N1VT.getVectorMinNumElements()) &&
  5895. "Extract subvector must be from larger vector to smaller vector!");
  5896. assert(N2C && "Extract subvector index must be a constant");
  5897. assert((VT.isScalableVector() != N1VT.isScalableVector() ||
  5898. (VT.getVectorMinNumElements() + N2C->getZExtValue()) <=
  5899. N1VT.getVectorMinNumElements()) &&
  5900. "Extract subvector overflow!");
  5901. assert(N2C->getAPIntValue().getBitWidth() ==
  5902. TLI->getVectorIdxTy(getDataLayout()).getFixedSizeInBits() &&
  5903. "Constant index for EXTRACT_SUBVECTOR has an invalid size");
  5904. // Trivial extraction.
  5905. if (VT == N1VT)
  5906. return N1;
  5907. // EXTRACT_SUBVECTOR of an UNDEF is an UNDEF.
  5908. if (N1.isUndef())
  5909. return getUNDEF(VT);
  5910. // EXTRACT_SUBVECTOR of CONCAT_VECTOR can be simplified if the pieces of
  5911. // the concat have the same type as the extract.
  5912. if (N1.getOpcode() == ISD::CONCAT_VECTORS && N1.getNumOperands() > 0 &&
  5913. VT == N1.getOperand(0).getValueType()) {
  5914. unsigned Factor = VT.getVectorMinNumElements();
  5915. return N1.getOperand(N2C->getZExtValue() / Factor);
  5916. }
  5917. // EXTRACT_SUBVECTOR of INSERT_SUBVECTOR is often created
  5918. // during shuffle legalization.
  5919. if (N1.getOpcode() == ISD::INSERT_SUBVECTOR && N2 == N1.getOperand(2) &&
  5920. VT == N1.getOperand(1).getValueType())
  5921. return N1.getOperand(1);
  5922. break;
  5923. }
  5924. }
  5925. // Perform trivial constant folding.
  5926. if (SDValue SV = FoldConstantArithmetic(Opcode, DL, VT, {N1, N2}))
  5927. return SV;
  5928. // Canonicalize an UNDEF to the RHS, even over a constant.
  5929. if (N1.isUndef()) {
  5930. if (TLI->isCommutativeBinOp(Opcode)) {
  5931. std::swap(N1, N2);
  5932. } else {
  5933. switch (Opcode) {
  5934. case ISD::SUB:
  5935. return getUNDEF(VT); // fold op(undef, arg2) -> undef
  5936. case ISD::SIGN_EXTEND_INREG:
  5937. case ISD::UDIV:
  5938. case ISD::SDIV:
  5939. case ISD::UREM:
  5940. case ISD::SREM:
  5941. case ISD::SSUBSAT:
  5942. case ISD::USUBSAT:
  5943. return getConstant(0, DL, VT); // fold op(undef, arg2) -> 0
  5944. }
  5945. }
  5946. }
  5947. // Fold a bunch of operators when the RHS is undef.
  5948. if (N2.isUndef()) {
  5949. switch (Opcode) {
  5950. case ISD::XOR:
  5951. if (N1.isUndef())
  5952. // Handle undef ^ undef -> 0 special case. This is a common
  5953. // idiom (misuse).
  5954. return getConstant(0, DL, VT);
  5955. [[fallthrough]];
  5956. case ISD::ADD:
  5957. case ISD::SUB:
  5958. case ISD::UDIV:
  5959. case ISD::SDIV:
  5960. case ISD::UREM:
  5961. case ISD::SREM:
  5962. return getUNDEF(VT); // fold op(arg1, undef) -> undef
  5963. case ISD::MUL:
  5964. case ISD::AND:
  5965. case ISD::SSUBSAT:
  5966. case ISD::USUBSAT:
  5967. return getConstant(0, DL, VT); // fold op(arg1, undef) -> 0
  5968. case ISD::OR:
  5969. case ISD::SADDSAT:
  5970. case ISD::UADDSAT:
  5971. return getAllOnesConstant(DL, VT);
  5972. }
  5973. }
  5974. // Memoize this node if possible.
  5975. SDNode *N;
  5976. SDVTList VTs = getVTList(VT);
  5977. SDValue Ops[] = {N1, N2};
  5978. if (VT != MVT::Glue) {
  5979. FoldingSetNodeID ID;
  5980. AddNodeIDNode(ID, Opcode, VTs, Ops);
  5981. void *IP = nullptr;
  5982. if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
  5983. E->intersectFlagsWith(Flags);
  5984. return SDValue(E, 0);
  5985. }
  5986. N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
  5987. N->setFlags(Flags);
  5988. createOperands(N, Ops);
  5989. CSEMap.InsertNode(N, IP);
  5990. } else {
  5991. N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
  5992. createOperands(N, Ops);
  5993. }
  5994. InsertNode(N);
  5995. SDValue V = SDValue(N, 0);
  5996. NewSDValueDbgMsg(V, "Creating new node: ", this);
  5997. return V;
  5998. }
  5999. SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
  6000. SDValue N1, SDValue N2, SDValue N3) {
  6001. SDNodeFlags Flags;
  6002. if (Inserter)
  6003. Flags = Inserter->getFlags();
  6004. return getNode(Opcode, DL, VT, N1, N2, N3, Flags);
  6005. }
  6006. SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
  6007. SDValue N1, SDValue N2, SDValue N3,
  6008. const SDNodeFlags Flags) {
  6009. assert(N1.getOpcode() != ISD::DELETED_NODE &&
  6010. N2.getOpcode() != ISD::DELETED_NODE &&
  6011. N3.getOpcode() != ISD::DELETED_NODE &&
  6012. "Operand is DELETED_NODE!");
  6013. // Perform various simplifications.
  6014. switch (Opcode) {
  6015. case ISD::FMA: {
  6016. assert(VT.isFloatingPoint() && "This operator only applies to FP types!");
  6017. assert(N1.getValueType() == VT && N2.getValueType() == VT &&
  6018. N3.getValueType() == VT && "FMA types must match!");
  6019. ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
  6020. ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2);
  6021. ConstantFPSDNode *N3CFP = dyn_cast<ConstantFPSDNode>(N3);
  6022. if (N1CFP && N2CFP && N3CFP) {
  6023. APFloat V1 = N1CFP->getValueAPF();
  6024. const APFloat &V2 = N2CFP->getValueAPF();
  6025. const APFloat &V3 = N3CFP->getValueAPF();
  6026. V1.fusedMultiplyAdd(V2, V3, APFloat::rmNearestTiesToEven);
  6027. return getConstantFP(V1, DL, VT);
  6028. }
  6029. break;
  6030. }
  6031. case ISD::BUILD_VECTOR: {
  6032. // Attempt to simplify BUILD_VECTOR.
  6033. SDValue Ops[] = {N1, N2, N3};
  6034. if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
  6035. return V;
  6036. break;
  6037. }
  6038. case ISD::CONCAT_VECTORS: {
  6039. SDValue Ops[] = {N1, N2, N3};
  6040. if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
  6041. return V;
  6042. break;
  6043. }
  6044. case ISD::SETCC: {
  6045. assert(VT.isInteger() && "SETCC result type must be an integer!");
  6046. assert(N1.getValueType() == N2.getValueType() &&
  6047. "SETCC operands must have the same type!");
  6048. assert(VT.isVector() == N1.getValueType().isVector() &&
  6049. "SETCC type should be vector iff the operand type is vector!");
  6050. assert((!VT.isVector() || VT.getVectorElementCount() ==
  6051. N1.getValueType().getVectorElementCount()) &&
  6052. "SETCC vector element counts must match!");
  6053. // Use FoldSetCC to simplify SETCC's.
  6054. if (SDValue V = FoldSetCC(VT, N1, N2, cast<CondCodeSDNode>(N3)->get(), DL))
  6055. return V;
  6056. // Vector constant folding.
  6057. SDValue Ops[] = {N1, N2, N3};
  6058. if (SDValue V = FoldConstantArithmetic(Opcode, DL, VT, Ops)) {
  6059. NewSDValueDbgMsg(V, "New node vector constant folding: ", this);
  6060. return V;
  6061. }
  6062. break;
  6063. }
  6064. case ISD::SELECT:
  6065. case ISD::VSELECT:
  6066. if (SDValue V = simplifySelect(N1, N2, N3))
  6067. return V;
  6068. break;
  6069. case ISD::VECTOR_SHUFFLE:
  6070. llvm_unreachable("should use getVectorShuffle constructor!");
  6071. case ISD::VECTOR_SPLICE: {
  6072. if (cast<ConstantSDNode>(N3)->isNullValue())
  6073. return N1;
  6074. break;
  6075. }
  6076. case ISD::INSERT_VECTOR_ELT: {
  6077. ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3);
  6078. // INSERT_VECTOR_ELT into out-of-bounds element is an UNDEF, except
  6079. // for scalable vectors where we will generate appropriate code to
  6080. // deal with out-of-bounds cases correctly.
  6081. if (N3C && N1.getValueType().isFixedLengthVector() &&
  6082. N3C->getZExtValue() >= N1.getValueType().getVectorNumElements())
  6083. return getUNDEF(VT);
  6084. // Undefined index can be assumed out-of-bounds, so that's UNDEF too.
  6085. if (N3.isUndef())
  6086. return getUNDEF(VT);
  6087. // If the inserted element is an UNDEF, just use the input vector.
  6088. if (N2.isUndef())
  6089. return N1;
  6090. break;
  6091. }
  6092. case ISD::INSERT_SUBVECTOR: {
  6093. // Inserting undef into undef is still undef.
  6094. if (N1.isUndef() && N2.isUndef())
  6095. return getUNDEF(VT);
  6096. EVT N2VT = N2.getValueType();
  6097. assert(VT == N1.getValueType() &&
  6098. "Dest and insert subvector source types must match!");
  6099. assert(VT.isVector() && N2VT.isVector() &&
  6100. "Insert subvector VTs must be vectors!");
  6101. assert(VT.getVectorElementType() == N2VT.getVectorElementType() &&
  6102. "Insert subvector VTs must have the same element type!");
  6103. assert((VT.isScalableVector() || N2VT.isFixedLengthVector()) &&
  6104. "Cannot insert a scalable vector into a fixed length vector!");
  6105. assert((VT.isScalableVector() != N2VT.isScalableVector() ||
  6106. VT.getVectorMinNumElements() >= N2VT.getVectorMinNumElements()) &&
  6107. "Insert subvector must be from smaller vector to larger vector!");
  6108. assert(isa<ConstantSDNode>(N3) &&
  6109. "Insert subvector index must be constant");
  6110. assert((VT.isScalableVector() != N2VT.isScalableVector() ||
  6111. (N2VT.getVectorMinNumElements() +
  6112. cast<ConstantSDNode>(N3)->getZExtValue()) <=
  6113. VT.getVectorMinNumElements()) &&
  6114. "Insert subvector overflow!");
  6115. assert(cast<ConstantSDNode>(N3)->getAPIntValue().getBitWidth() ==
  6116. TLI->getVectorIdxTy(getDataLayout()).getFixedSizeInBits() &&
  6117. "Constant index for INSERT_SUBVECTOR has an invalid size");
  6118. // Trivial insertion.
  6119. if (VT == N2VT)
  6120. return N2;
  6121. // If this is an insert of an extracted vector into an undef vector, we
  6122. // can just use the input to the extract.
  6123. if (N1.isUndef() && N2.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
  6124. N2.getOperand(1) == N3 && N2.getOperand(0).getValueType() == VT)
  6125. return N2.getOperand(0);
  6126. break;
  6127. }
  6128. case ISD::BITCAST:
  6129. // Fold bit_convert nodes from a type to themselves.
  6130. if (N1.getValueType() == VT)
  6131. return N1;
  6132. break;
  6133. }
  6134. // Memoize node if it doesn't produce a flag.
  6135. SDNode *N;
  6136. SDVTList VTs = getVTList(VT);
  6137. SDValue Ops[] = {N1, N2, N3};
  6138. if (VT != MVT::Glue) {
  6139. FoldingSetNodeID ID;
  6140. AddNodeIDNode(ID, Opcode, VTs, Ops);
  6141. void *IP = nullptr;
  6142. if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
  6143. E->intersectFlagsWith(Flags);
  6144. return SDValue(E, 0);
  6145. }
  6146. N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
  6147. N->setFlags(Flags);
  6148. createOperands(N, Ops);
  6149. CSEMap.InsertNode(N, IP);
  6150. } else {
  6151. N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
  6152. createOperands(N, Ops);
  6153. }
  6154. InsertNode(N);
  6155. SDValue V = SDValue(N, 0);
  6156. NewSDValueDbgMsg(V, "Creating new node: ", this);
  6157. return V;
  6158. }
  6159. SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
  6160. SDValue N1, SDValue N2, SDValue N3, SDValue N4) {
  6161. SDValue Ops[] = { N1, N2, N3, N4 };
  6162. return getNode(Opcode, DL, VT, Ops);
  6163. }
  6164. SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
  6165. SDValue N1, SDValue N2, SDValue N3, SDValue N4,
  6166. SDValue N5) {
  6167. SDValue Ops[] = { N1, N2, N3, N4, N5 };
  6168. return getNode(Opcode, DL, VT, Ops);
  6169. }
  6170. /// getStackArgumentTokenFactor - Compute a TokenFactor to force all
  6171. /// the incoming stack arguments to be loaded from the stack.
  6172. SDValue SelectionDAG::getStackArgumentTokenFactor(SDValue Chain) {
  6173. SmallVector<SDValue, 8> ArgChains;
  6174. // Include the original chain at the beginning of the list. When this is
  6175. // used by target LowerCall hooks, this helps legalize find the
  6176. // CALLSEQ_BEGIN node.
  6177. ArgChains.push_back(Chain);
  6178. // Add a chain value for each stack argument.
  6179. for (SDNode *U : getEntryNode().getNode()->uses())
  6180. if (LoadSDNode *L = dyn_cast<LoadSDNode>(U))
  6181. if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
  6182. if (FI->getIndex() < 0)
  6183. ArgChains.push_back(SDValue(L, 1));
  6184. // Build a tokenfactor for all the chains.
  6185. return getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
  6186. }
  6187. /// getMemsetValue - Vectorized representation of the memset value
  6188. /// operand.
  6189. static SDValue getMemsetValue(SDValue Value, EVT VT, SelectionDAG &DAG,
  6190. const SDLoc &dl) {
  6191. assert(!Value.isUndef());
  6192. unsigned NumBits = VT.getScalarSizeInBits();
  6193. if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
  6194. assert(C->getAPIntValue().getBitWidth() == 8);
  6195. APInt Val = APInt::getSplat(NumBits, C->getAPIntValue());
  6196. if (VT.isInteger()) {
  6197. bool IsOpaque = VT.getSizeInBits() > 64 ||
  6198. !DAG.getTargetLoweringInfo().isLegalStoreImmediate(C->getSExtValue());
  6199. return DAG.getConstant(Val, dl, VT, false, IsOpaque);
  6200. }
  6201. return DAG.getConstantFP(APFloat(DAG.EVTToAPFloatSemantics(VT), Val), dl,
  6202. VT);
  6203. }
  6204. assert(Value.getValueType() == MVT::i8 && "memset with non-byte fill value?");
  6205. EVT IntVT = VT.getScalarType();
  6206. if (!IntVT.isInteger())
  6207. IntVT = EVT::getIntegerVT(*DAG.getContext(), IntVT.getSizeInBits());
  6208. Value = DAG.getNode(ISD::ZERO_EXTEND, dl, IntVT, Value);
  6209. if (NumBits > 8) {
  6210. // Use a multiplication with 0x010101... to extend the input to the
  6211. // required length.
  6212. APInt Magic = APInt::getSplat(NumBits, APInt(8, 0x01));
  6213. Value = DAG.getNode(ISD::MUL, dl, IntVT, Value,
  6214. DAG.getConstant(Magic, dl, IntVT));
  6215. }
  6216. if (VT != Value.getValueType() && !VT.isInteger())
  6217. Value = DAG.getBitcast(VT.getScalarType(), Value);
  6218. if (VT != Value.getValueType())
  6219. Value = DAG.getSplatBuildVector(VT, dl, Value);
  6220. return Value;
  6221. }
  6222. /// getMemsetStringVal - Similar to getMemsetValue. Except this is only
  6223. /// used when a memcpy is turned into a memset when the source is a constant
  6224. /// string ptr.
  6225. static SDValue getMemsetStringVal(EVT VT, const SDLoc &dl, SelectionDAG &DAG,
  6226. const TargetLowering &TLI,
  6227. const ConstantDataArraySlice &Slice) {
  6228. // Handle vector with all elements zero.
  6229. if (Slice.Array == nullptr) {
  6230. if (VT.isInteger())
  6231. return DAG.getConstant(0, dl, VT);
  6232. if (VT == MVT::f32 || VT == MVT::f64 || VT == MVT::f128)
  6233. return DAG.getConstantFP(0.0, dl, VT);
  6234. if (VT.isVector()) {
  6235. unsigned NumElts = VT.getVectorNumElements();
  6236. MVT EltVT = (VT.getVectorElementType() == MVT::f32) ? MVT::i32 : MVT::i64;
  6237. return DAG.getNode(ISD::BITCAST, dl, VT,
  6238. DAG.getConstant(0, dl,
  6239. EVT::getVectorVT(*DAG.getContext(),
  6240. EltVT, NumElts)));
  6241. }
  6242. llvm_unreachable("Expected type!");
  6243. }
  6244. assert(!VT.isVector() && "Can't handle vector type here!");
  6245. unsigned NumVTBits = VT.getSizeInBits();
  6246. unsigned NumVTBytes = NumVTBits / 8;
  6247. unsigned NumBytes = std::min(NumVTBytes, unsigned(Slice.Length));
  6248. APInt Val(NumVTBits, 0);
  6249. if (DAG.getDataLayout().isLittleEndian()) {
  6250. for (unsigned i = 0; i != NumBytes; ++i)
  6251. Val |= (uint64_t)(unsigned char)Slice[i] << i*8;
  6252. } else {
  6253. for (unsigned i = 0; i != NumBytes; ++i)
  6254. Val |= (uint64_t)(unsigned char)Slice[i] << (NumVTBytes-i-1)*8;
  6255. }
  6256. // If the "cost" of materializing the integer immediate is less than the cost
  6257. // of a load, then it is cost effective to turn the load into the immediate.
  6258. Type *Ty = VT.getTypeForEVT(*DAG.getContext());
  6259. if (TLI.shouldConvertConstantLoadToIntImm(Val, Ty))
  6260. return DAG.getConstant(Val, dl, VT);
  6261. return SDValue();
  6262. }
  6263. SDValue SelectionDAG::getMemBasePlusOffset(SDValue Base, TypeSize Offset,
  6264. const SDLoc &DL,
  6265. const SDNodeFlags Flags) {
  6266. EVT VT = Base.getValueType();
  6267. SDValue Index;
  6268. if (Offset.isScalable())
  6269. Index = getVScale(DL, Base.getValueType(),
  6270. APInt(Base.getValueSizeInBits().getFixedValue(),
  6271. Offset.getKnownMinValue()));
  6272. else
  6273. Index = getConstant(Offset.getFixedValue(), DL, VT);
  6274. return getMemBasePlusOffset(Base, Index, DL, Flags);
  6275. }
  6276. SDValue SelectionDAG::getMemBasePlusOffset(SDValue Ptr, SDValue Offset,
  6277. const SDLoc &DL,
  6278. const SDNodeFlags Flags) {
  6279. assert(Offset.getValueType().isInteger());
  6280. EVT BasePtrVT = Ptr.getValueType();
  6281. return getNode(ISD::ADD, DL, BasePtrVT, Ptr, Offset, Flags);
  6282. }
  6283. /// Returns true if memcpy source is constant data.
  6284. static bool isMemSrcFromConstant(SDValue Src, ConstantDataArraySlice &Slice) {
  6285. uint64_t SrcDelta = 0;
  6286. GlobalAddressSDNode *G = nullptr;
  6287. if (Src.getOpcode() == ISD::GlobalAddress)
  6288. G = cast<GlobalAddressSDNode>(Src);
  6289. else if (Src.getOpcode() == ISD::ADD &&
  6290. Src.getOperand(0).getOpcode() == ISD::GlobalAddress &&
  6291. Src.getOperand(1).getOpcode() == ISD::Constant) {
  6292. G = cast<GlobalAddressSDNode>(Src.getOperand(0));
  6293. SrcDelta = cast<ConstantSDNode>(Src.getOperand(1))->getZExtValue();
  6294. }
  6295. if (!G)
  6296. return false;
  6297. return getConstantDataArrayInfo(G->getGlobal(), Slice, 8,
  6298. SrcDelta + G->getOffset());
  6299. }
  6300. static bool shouldLowerMemFuncForSize(const MachineFunction &MF,
  6301. SelectionDAG &DAG) {
  6302. // On Darwin, -Os means optimize for size without hurting performance, so
  6303. // only really optimize for size when -Oz (MinSize) is used.
  6304. if (MF.getTarget().getTargetTriple().isOSDarwin())
  6305. return MF.getFunction().hasMinSize();
  6306. return DAG.shouldOptForSize();
  6307. }
  6308. static void chainLoadsAndStoresForMemcpy(SelectionDAG &DAG, const SDLoc &dl,
  6309. SmallVector<SDValue, 32> &OutChains, unsigned From,
  6310. unsigned To, SmallVector<SDValue, 16> &OutLoadChains,
  6311. SmallVector<SDValue, 16> &OutStoreChains) {
  6312. assert(OutLoadChains.size() && "Missing loads in memcpy inlining");
  6313. assert(OutStoreChains.size() && "Missing stores in memcpy inlining");
  6314. SmallVector<SDValue, 16> GluedLoadChains;
  6315. for (unsigned i = From; i < To; ++i) {
  6316. OutChains.push_back(OutLoadChains[i]);
  6317. GluedLoadChains.push_back(OutLoadChains[i]);
  6318. }
  6319. // Chain for all loads.
  6320. SDValue LoadToken = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
  6321. GluedLoadChains);
  6322. for (unsigned i = From; i < To; ++i) {
  6323. StoreSDNode *ST = dyn_cast<StoreSDNode>(OutStoreChains[i]);
  6324. SDValue NewStore = DAG.getTruncStore(LoadToken, dl, ST->getValue(),
  6325. ST->getBasePtr(), ST->getMemoryVT(),
  6326. ST->getMemOperand());
  6327. OutChains.push_back(NewStore);
  6328. }
  6329. }
  6330. static SDValue getMemcpyLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl,
  6331. SDValue Chain, SDValue Dst, SDValue Src,
  6332. uint64_t Size, Align Alignment,
  6333. bool isVol, bool AlwaysInline,
  6334. MachinePointerInfo DstPtrInfo,
  6335. MachinePointerInfo SrcPtrInfo,
  6336. const AAMDNodes &AAInfo, AAResults *AA) {
  6337. // Turn a memcpy of undef to nop.
  6338. // FIXME: We need to honor volatile even is Src is undef.
  6339. if (Src.isUndef())
  6340. return Chain;
  6341. // Expand memcpy to a series of load and store ops if the size operand falls
  6342. // below a certain threshold.
  6343. // TODO: In the AlwaysInline case, if the size is big then generate a loop
  6344. // rather than maybe a humongous number of loads and stores.
  6345. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  6346. const DataLayout &DL = DAG.getDataLayout();
  6347. LLVMContext &C = *DAG.getContext();
  6348. std::vector<EVT> MemOps;
  6349. bool DstAlignCanChange = false;
  6350. MachineFunction &MF = DAG.getMachineFunction();
  6351. MachineFrameInfo &MFI = MF.getFrameInfo();
  6352. bool OptSize = shouldLowerMemFuncForSize(MF, DAG);
  6353. FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
  6354. if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
  6355. DstAlignCanChange = true;
  6356. MaybeAlign SrcAlign = DAG.InferPtrAlign(Src);
  6357. if (!SrcAlign || Alignment > *SrcAlign)
  6358. SrcAlign = Alignment;
  6359. assert(SrcAlign && "SrcAlign must be set");
  6360. ConstantDataArraySlice Slice;
  6361. // If marked as volatile, perform a copy even when marked as constant.
  6362. bool CopyFromConstant = !isVol && isMemSrcFromConstant(Src, Slice);
  6363. bool isZeroConstant = CopyFromConstant && Slice.Array == nullptr;
  6364. unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemcpy(OptSize);
  6365. const MemOp Op = isZeroConstant
  6366. ? MemOp::Set(Size, DstAlignCanChange, Alignment,
  6367. /*IsZeroMemset*/ true, isVol)
  6368. : MemOp::Copy(Size, DstAlignCanChange, Alignment,
  6369. *SrcAlign, isVol, CopyFromConstant);
  6370. if (!TLI.findOptimalMemOpLowering(
  6371. MemOps, Limit, Op, DstPtrInfo.getAddrSpace(),
  6372. SrcPtrInfo.getAddrSpace(), MF.getFunction().getAttributes()))
  6373. return SDValue();
  6374. if (DstAlignCanChange) {
  6375. Type *Ty = MemOps[0].getTypeForEVT(C);
  6376. Align NewAlign = DL.getABITypeAlign(Ty);
  6377. // Don't promote to an alignment that would require dynamic stack
  6378. // realignment which may conflict with optimizations such as tail call
  6379. // optimization.
  6380. const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
  6381. if (!TRI->hasStackRealignment(MF))
  6382. while (NewAlign > Alignment && DL.exceedsNaturalStackAlignment(NewAlign))
  6383. NewAlign = NewAlign.previous();
  6384. if (NewAlign > Alignment) {
  6385. // Give the stack frame object a larger alignment if needed.
  6386. if (MFI.getObjectAlign(FI->getIndex()) < NewAlign)
  6387. MFI.setObjectAlignment(FI->getIndex(), NewAlign);
  6388. Alignment = NewAlign;
  6389. }
  6390. }
  6391. // Prepare AAInfo for loads/stores after lowering this memcpy.
  6392. AAMDNodes NewAAInfo = AAInfo;
  6393. NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr;
  6394. const Value *SrcVal = SrcPtrInfo.V.dyn_cast<const Value *>();
  6395. bool isConstant =
  6396. AA && SrcVal &&
  6397. AA->pointsToConstantMemory(MemoryLocation(SrcVal, Size, AAInfo));
  6398. MachineMemOperand::Flags MMOFlags =
  6399. isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone;
  6400. SmallVector<SDValue, 16> OutLoadChains;
  6401. SmallVector<SDValue, 16> OutStoreChains;
  6402. SmallVector<SDValue, 32> OutChains;
  6403. unsigned NumMemOps = MemOps.size();
  6404. uint64_t SrcOff = 0, DstOff = 0;
  6405. for (unsigned i = 0; i != NumMemOps; ++i) {
  6406. EVT VT = MemOps[i];
  6407. unsigned VTSize = VT.getSizeInBits() / 8;
  6408. SDValue Value, Store;
  6409. if (VTSize > Size) {
  6410. // Issuing an unaligned load / store pair that overlaps with the previous
  6411. // pair. Adjust the offset accordingly.
  6412. assert(i == NumMemOps-1 && i != 0);
  6413. SrcOff -= VTSize - Size;
  6414. DstOff -= VTSize - Size;
  6415. }
  6416. if (CopyFromConstant &&
  6417. (isZeroConstant || (VT.isInteger() && !VT.isVector()))) {
  6418. // It's unlikely a store of a vector immediate can be done in a single
  6419. // instruction. It would require a load from a constantpool first.
  6420. // We only handle zero vectors here.
  6421. // FIXME: Handle other cases where store of vector immediate is done in
  6422. // a single instruction.
  6423. ConstantDataArraySlice SubSlice;
  6424. if (SrcOff < Slice.Length) {
  6425. SubSlice = Slice;
  6426. SubSlice.move(SrcOff);
  6427. } else {
  6428. // This is an out-of-bounds access and hence UB. Pretend we read zero.
  6429. SubSlice.Array = nullptr;
  6430. SubSlice.Offset = 0;
  6431. SubSlice.Length = VTSize;
  6432. }
  6433. Value = getMemsetStringVal(VT, dl, DAG, TLI, SubSlice);
  6434. if (Value.getNode()) {
  6435. Store = DAG.getStore(
  6436. Chain, dl, Value,
  6437. DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl),
  6438. DstPtrInfo.getWithOffset(DstOff), Alignment, MMOFlags, NewAAInfo);
  6439. OutChains.push_back(Store);
  6440. }
  6441. }
  6442. if (!Store.getNode()) {
  6443. // The type might not be legal for the target. This should only happen
  6444. // if the type is smaller than a legal type, as on PPC, so the right
  6445. // thing to do is generate a LoadExt/StoreTrunc pair. These simplify
  6446. // to Load/Store if NVT==VT.
  6447. // FIXME does the case above also need this?
  6448. EVT NVT = TLI.getTypeToTransformTo(C, VT);
  6449. assert(NVT.bitsGE(VT));
  6450. bool isDereferenceable =
  6451. SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL);
  6452. MachineMemOperand::Flags SrcMMOFlags = MMOFlags;
  6453. if (isDereferenceable)
  6454. SrcMMOFlags |= MachineMemOperand::MODereferenceable;
  6455. if (isConstant)
  6456. SrcMMOFlags |= MachineMemOperand::MOInvariant;
  6457. Value = DAG.getExtLoad(
  6458. ISD::EXTLOAD, dl, NVT, Chain,
  6459. DAG.getMemBasePlusOffset(Src, TypeSize::Fixed(SrcOff), dl),
  6460. SrcPtrInfo.getWithOffset(SrcOff), VT,
  6461. commonAlignment(*SrcAlign, SrcOff), SrcMMOFlags, NewAAInfo);
  6462. OutLoadChains.push_back(Value.getValue(1));
  6463. Store = DAG.getTruncStore(
  6464. Chain, dl, Value,
  6465. DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl),
  6466. DstPtrInfo.getWithOffset(DstOff), VT, Alignment, MMOFlags, NewAAInfo);
  6467. OutStoreChains.push_back(Store);
  6468. }
  6469. SrcOff += VTSize;
  6470. DstOff += VTSize;
  6471. Size -= VTSize;
  6472. }
  6473. unsigned GluedLdStLimit = MaxLdStGlue == 0 ?
  6474. TLI.getMaxGluedStoresPerMemcpy() : MaxLdStGlue;
  6475. unsigned NumLdStInMemcpy = OutStoreChains.size();
  6476. if (NumLdStInMemcpy) {
  6477. // It may be that memcpy might be converted to memset if it's memcpy
  6478. // of constants. In such a case, we won't have loads and stores, but
  6479. // just stores. In the absence of loads, there is nothing to gang up.
  6480. if ((GluedLdStLimit <= 1) || !EnableMemCpyDAGOpt) {
  6481. // If target does not care, just leave as it.
  6482. for (unsigned i = 0; i < NumLdStInMemcpy; ++i) {
  6483. OutChains.push_back(OutLoadChains[i]);
  6484. OutChains.push_back(OutStoreChains[i]);
  6485. }
  6486. } else {
  6487. // Ld/St less than/equal limit set by target.
  6488. if (NumLdStInMemcpy <= GluedLdStLimit) {
  6489. chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, 0,
  6490. NumLdStInMemcpy, OutLoadChains,
  6491. OutStoreChains);
  6492. } else {
  6493. unsigned NumberLdChain = NumLdStInMemcpy / GluedLdStLimit;
  6494. unsigned RemainingLdStInMemcpy = NumLdStInMemcpy % GluedLdStLimit;
  6495. unsigned GlueIter = 0;
  6496. for (unsigned cnt = 0; cnt < NumberLdChain; ++cnt) {
  6497. unsigned IndexFrom = NumLdStInMemcpy - GlueIter - GluedLdStLimit;
  6498. unsigned IndexTo = NumLdStInMemcpy - GlueIter;
  6499. chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, IndexFrom, IndexTo,
  6500. OutLoadChains, OutStoreChains);
  6501. GlueIter += GluedLdStLimit;
  6502. }
  6503. // Residual ld/st.
  6504. if (RemainingLdStInMemcpy) {
  6505. chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, 0,
  6506. RemainingLdStInMemcpy, OutLoadChains,
  6507. OutStoreChains);
  6508. }
  6509. }
  6510. }
  6511. }
  6512. return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
  6513. }
  6514. static SDValue getMemmoveLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl,
  6515. SDValue Chain, SDValue Dst, SDValue Src,
  6516. uint64_t Size, Align Alignment,
  6517. bool isVol, bool AlwaysInline,
  6518. MachinePointerInfo DstPtrInfo,
  6519. MachinePointerInfo SrcPtrInfo,
  6520. const AAMDNodes &AAInfo) {
  6521. // Turn a memmove of undef to nop.
  6522. // FIXME: We need to honor volatile even is Src is undef.
  6523. if (Src.isUndef())
  6524. return Chain;
  6525. // Expand memmove to a series of load and store ops if the size operand falls
  6526. // below a certain threshold.
  6527. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  6528. const DataLayout &DL = DAG.getDataLayout();
  6529. LLVMContext &C = *DAG.getContext();
  6530. std::vector<EVT> MemOps;
  6531. bool DstAlignCanChange = false;
  6532. MachineFunction &MF = DAG.getMachineFunction();
  6533. MachineFrameInfo &MFI = MF.getFrameInfo();
  6534. bool OptSize = shouldLowerMemFuncForSize(MF, DAG);
  6535. FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
  6536. if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
  6537. DstAlignCanChange = true;
  6538. MaybeAlign SrcAlign = DAG.InferPtrAlign(Src);
  6539. if (!SrcAlign || Alignment > *SrcAlign)
  6540. SrcAlign = Alignment;
  6541. assert(SrcAlign && "SrcAlign must be set");
  6542. unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemmove(OptSize);
  6543. if (!TLI.findOptimalMemOpLowering(
  6544. MemOps, Limit,
  6545. MemOp::Copy(Size, DstAlignCanChange, Alignment, *SrcAlign,
  6546. /*IsVolatile*/ true),
  6547. DstPtrInfo.getAddrSpace(), SrcPtrInfo.getAddrSpace(),
  6548. MF.getFunction().getAttributes()))
  6549. return SDValue();
  6550. if (DstAlignCanChange) {
  6551. Type *Ty = MemOps[0].getTypeForEVT(C);
  6552. Align NewAlign = DL.getABITypeAlign(Ty);
  6553. // Don't promote to an alignment that would require dynamic stack
  6554. // realignment which may conflict with optimizations such as tail call
  6555. // optimization.
  6556. const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
  6557. if (!TRI->hasStackRealignment(MF))
  6558. while (NewAlign > Alignment && DL.exceedsNaturalStackAlignment(NewAlign))
  6559. NewAlign = NewAlign.previous();
  6560. if (NewAlign > Alignment) {
  6561. // Give the stack frame object a larger alignment if needed.
  6562. if (MFI.getObjectAlign(FI->getIndex()) < NewAlign)
  6563. MFI.setObjectAlignment(FI->getIndex(), NewAlign);
  6564. Alignment = NewAlign;
  6565. }
  6566. }
  6567. // Prepare AAInfo for loads/stores after lowering this memmove.
  6568. AAMDNodes NewAAInfo = AAInfo;
  6569. NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr;
  6570. MachineMemOperand::Flags MMOFlags =
  6571. isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone;
  6572. uint64_t SrcOff = 0, DstOff = 0;
  6573. SmallVector<SDValue, 8> LoadValues;
  6574. SmallVector<SDValue, 8> LoadChains;
  6575. SmallVector<SDValue, 8> OutChains;
  6576. unsigned NumMemOps = MemOps.size();
  6577. for (unsigned i = 0; i < NumMemOps; i++) {
  6578. EVT VT = MemOps[i];
  6579. unsigned VTSize = VT.getSizeInBits() / 8;
  6580. SDValue Value;
  6581. bool isDereferenceable =
  6582. SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL);
  6583. MachineMemOperand::Flags SrcMMOFlags = MMOFlags;
  6584. if (isDereferenceable)
  6585. SrcMMOFlags |= MachineMemOperand::MODereferenceable;
  6586. Value = DAG.getLoad(
  6587. VT, dl, Chain,
  6588. DAG.getMemBasePlusOffset(Src, TypeSize::Fixed(SrcOff), dl),
  6589. SrcPtrInfo.getWithOffset(SrcOff), *SrcAlign, SrcMMOFlags, NewAAInfo);
  6590. LoadValues.push_back(Value);
  6591. LoadChains.push_back(Value.getValue(1));
  6592. SrcOff += VTSize;
  6593. }
  6594. Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
  6595. OutChains.clear();
  6596. for (unsigned i = 0; i < NumMemOps; i++) {
  6597. EVT VT = MemOps[i];
  6598. unsigned VTSize = VT.getSizeInBits() / 8;
  6599. SDValue Store;
  6600. Store = DAG.getStore(
  6601. Chain, dl, LoadValues[i],
  6602. DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl),
  6603. DstPtrInfo.getWithOffset(DstOff), Alignment, MMOFlags, NewAAInfo);
  6604. OutChains.push_back(Store);
  6605. DstOff += VTSize;
  6606. }
  6607. return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
  6608. }
  6609. /// Lower the call to 'memset' intrinsic function into a series of store
  6610. /// operations.
  6611. ///
  6612. /// \param DAG Selection DAG where lowered code is placed.
  6613. /// \param dl Link to corresponding IR location.
  6614. /// \param Chain Control flow dependency.
  6615. /// \param Dst Pointer to destination memory location.
  6616. /// \param Src Value of byte to write into the memory.
  6617. /// \param Size Number of bytes to write.
  6618. /// \param Alignment Alignment of the destination in bytes.
  6619. /// \param isVol True if destination is volatile.
  6620. /// \param AlwaysInline Makes sure no function call is generated.
  6621. /// \param DstPtrInfo IR information on the memory pointer.
  6622. /// \returns New head in the control flow, if lowering was successful, empty
  6623. /// SDValue otherwise.
  6624. ///
  6625. /// The function tries to replace 'llvm.memset' intrinsic with several store
  6626. /// operations and value calculation code. This is usually profitable for small
  6627. /// memory size or when the semantic requires inlining.
  6628. static SDValue getMemsetStores(SelectionDAG &DAG, const SDLoc &dl,
  6629. SDValue Chain, SDValue Dst, SDValue Src,
  6630. uint64_t Size, Align Alignment, bool isVol,
  6631. bool AlwaysInline, MachinePointerInfo DstPtrInfo,
  6632. const AAMDNodes &AAInfo) {
  6633. // Turn a memset of undef to nop.
  6634. // FIXME: We need to honor volatile even is Src is undef.
  6635. if (Src.isUndef())
  6636. return Chain;
  6637. // Expand memset to a series of load/store ops if the size operand
  6638. // falls below a certain threshold.
  6639. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  6640. std::vector<EVT> MemOps;
  6641. bool DstAlignCanChange = false;
  6642. MachineFunction &MF = DAG.getMachineFunction();
  6643. MachineFrameInfo &MFI = MF.getFrameInfo();
  6644. bool OptSize = shouldLowerMemFuncForSize(MF, DAG);
  6645. FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
  6646. if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
  6647. DstAlignCanChange = true;
  6648. bool IsZeroVal =
  6649. isa<ConstantSDNode>(Src) && cast<ConstantSDNode>(Src)->isZero();
  6650. unsigned Limit = AlwaysInline ? ~0 : TLI.getMaxStoresPerMemset(OptSize);
  6651. if (!TLI.findOptimalMemOpLowering(
  6652. MemOps, Limit,
  6653. MemOp::Set(Size, DstAlignCanChange, Alignment, IsZeroVal, isVol),
  6654. DstPtrInfo.getAddrSpace(), ~0u, MF.getFunction().getAttributes()))
  6655. return SDValue();
  6656. if (DstAlignCanChange) {
  6657. Type *Ty = MemOps[0].getTypeForEVT(*DAG.getContext());
  6658. const DataLayout &DL = DAG.getDataLayout();
  6659. Align NewAlign = DL.getABITypeAlign(Ty);
  6660. // Don't promote to an alignment that would require dynamic stack
  6661. // realignment which may conflict with optimizations such as tail call
  6662. // optimization.
  6663. const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
  6664. if (!TRI->hasStackRealignment(MF))
  6665. while (NewAlign > Alignment && DL.exceedsNaturalStackAlignment(NewAlign))
  6666. NewAlign = NewAlign.previous();
  6667. if (NewAlign > Alignment) {
  6668. // Give the stack frame object a larger alignment if needed.
  6669. if (MFI.getObjectAlign(FI->getIndex()) < NewAlign)
  6670. MFI.setObjectAlignment(FI->getIndex(), NewAlign);
  6671. Alignment = NewAlign;
  6672. }
  6673. }
  6674. SmallVector<SDValue, 8> OutChains;
  6675. uint64_t DstOff = 0;
  6676. unsigned NumMemOps = MemOps.size();
  6677. // Find the largest store and generate the bit pattern for it.
  6678. EVT LargestVT = MemOps[0];
  6679. for (unsigned i = 1; i < NumMemOps; i++)
  6680. if (MemOps[i].bitsGT(LargestVT))
  6681. LargestVT = MemOps[i];
  6682. SDValue MemSetValue = getMemsetValue(Src, LargestVT, DAG, dl);
  6683. // Prepare AAInfo for loads/stores after lowering this memset.
  6684. AAMDNodes NewAAInfo = AAInfo;
  6685. NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr;
  6686. for (unsigned i = 0; i < NumMemOps; i++) {
  6687. EVT VT = MemOps[i];
  6688. unsigned VTSize = VT.getSizeInBits() / 8;
  6689. if (VTSize > Size) {
  6690. // Issuing an unaligned load / store pair that overlaps with the previous
  6691. // pair. Adjust the offset accordingly.
  6692. assert(i == NumMemOps-1 && i != 0);
  6693. DstOff -= VTSize - Size;
  6694. }
  6695. // If this store is smaller than the largest store see whether we can get
  6696. // the smaller value for free with a truncate.
  6697. SDValue Value = MemSetValue;
  6698. if (VT.bitsLT(LargestVT)) {
  6699. if (!LargestVT.isVector() && !VT.isVector() &&
  6700. TLI.isTruncateFree(LargestVT, VT))
  6701. Value = DAG.getNode(ISD::TRUNCATE, dl, VT, MemSetValue);
  6702. else
  6703. Value = getMemsetValue(Src, VT, DAG, dl);
  6704. }
  6705. assert(Value.getValueType() == VT && "Value with wrong type.");
  6706. SDValue Store = DAG.getStore(
  6707. Chain, dl, Value,
  6708. DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl),
  6709. DstPtrInfo.getWithOffset(DstOff), Alignment,
  6710. isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone,
  6711. NewAAInfo);
  6712. OutChains.push_back(Store);
  6713. DstOff += VT.getSizeInBits() / 8;
  6714. Size -= VTSize;
  6715. }
  6716. return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
  6717. }
  6718. static void checkAddrSpaceIsValidForLibcall(const TargetLowering *TLI,
  6719. unsigned AS) {
  6720. // Lowering memcpy / memset / memmove intrinsics to calls is only valid if all
  6721. // pointer operands can be losslessly bitcasted to pointers of address space 0
  6722. if (AS != 0 && !TLI->getTargetMachine().isNoopAddrSpaceCast(AS, 0)) {
  6723. report_fatal_error("cannot lower memory intrinsic in address space " +
  6724. Twine(AS));
  6725. }
  6726. }
  6727. SDValue SelectionDAG::getMemcpy(SDValue Chain, const SDLoc &dl, SDValue Dst,
  6728. SDValue Src, SDValue Size, Align Alignment,
  6729. bool isVol, bool AlwaysInline, bool isTailCall,
  6730. MachinePointerInfo DstPtrInfo,
  6731. MachinePointerInfo SrcPtrInfo,
  6732. const AAMDNodes &AAInfo, AAResults *AA) {
  6733. // Check to see if we should lower the memcpy to loads and stores first.
  6734. // For cases within the target-specified limits, this is the best choice.
  6735. ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
  6736. if (ConstantSize) {
  6737. // Memcpy with size zero? Just return the original chain.
  6738. if (ConstantSize->isZero())
  6739. return Chain;
  6740. SDValue Result = getMemcpyLoadsAndStores(
  6741. *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), Alignment,
  6742. isVol, false, DstPtrInfo, SrcPtrInfo, AAInfo, AA);
  6743. if (Result.getNode())
  6744. return Result;
  6745. }
  6746. // Then check to see if we should lower the memcpy with target-specific
  6747. // code. If the target chooses to do this, this is the next best.
  6748. if (TSI) {
  6749. SDValue Result = TSI->EmitTargetCodeForMemcpy(
  6750. *this, dl, Chain, Dst, Src, Size, Alignment, isVol, AlwaysInline,
  6751. DstPtrInfo, SrcPtrInfo);
  6752. if (Result.getNode())
  6753. return Result;
  6754. }
  6755. // If we really need inline code and the target declined to provide it,
  6756. // use a (potentially long) sequence of loads and stores.
  6757. if (AlwaysInline) {
  6758. assert(ConstantSize && "AlwaysInline requires a constant size!");
  6759. return getMemcpyLoadsAndStores(
  6760. *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), Alignment,
  6761. isVol, true, DstPtrInfo, SrcPtrInfo, AAInfo, AA);
  6762. }
  6763. checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
  6764. checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace());
  6765. // FIXME: If the memcpy is volatile (isVol), lowering it to a plain libc
  6766. // memcpy is not guaranteed to be safe. libc memcpys aren't required to
  6767. // respect volatile, so they may do things like read or write memory
  6768. // beyond the given memory regions. But fixing this isn't easy, and most
  6769. // people don't care.
  6770. // Emit a library call.
  6771. TargetLowering::ArgListTy Args;
  6772. TargetLowering::ArgListEntry Entry;
  6773. Entry.Ty = Type::getInt8PtrTy(*getContext());
  6774. Entry.Node = Dst; Args.push_back(Entry);
  6775. Entry.Node = Src; Args.push_back(Entry);
  6776. Entry.Ty = getDataLayout().getIntPtrType(*getContext());
  6777. Entry.Node = Size; Args.push_back(Entry);
  6778. // FIXME: pass in SDLoc
  6779. TargetLowering::CallLoweringInfo CLI(*this);
  6780. CLI.setDebugLoc(dl)
  6781. .setChain(Chain)
  6782. .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMCPY),
  6783. Dst.getValueType().getTypeForEVT(*getContext()),
  6784. getExternalSymbol(TLI->getLibcallName(RTLIB::MEMCPY),
  6785. TLI->getPointerTy(getDataLayout())),
  6786. std::move(Args))
  6787. .setDiscardResult()
  6788. .setTailCall(isTailCall);
  6789. std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
  6790. return CallResult.second;
  6791. }
  6792. SDValue SelectionDAG::getAtomicMemcpy(SDValue Chain, const SDLoc &dl,
  6793. SDValue Dst, SDValue Src, SDValue Size,
  6794. Type *SizeTy, unsigned ElemSz,
  6795. bool isTailCall,
  6796. MachinePointerInfo DstPtrInfo,
  6797. MachinePointerInfo SrcPtrInfo) {
  6798. // Emit a library call.
  6799. TargetLowering::ArgListTy Args;
  6800. TargetLowering::ArgListEntry Entry;
  6801. Entry.Ty = getDataLayout().getIntPtrType(*getContext());
  6802. Entry.Node = Dst;
  6803. Args.push_back(Entry);
  6804. Entry.Node = Src;
  6805. Args.push_back(Entry);
  6806. Entry.Ty = SizeTy;
  6807. Entry.Node = Size;
  6808. Args.push_back(Entry);
  6809. RTLIB::Libcall LibraryCall =
  6810. RTLIB::getMEMCPY_ELEMENT_UNORDERED_ATOMIC(ElemSz);
  6811. if (LibraryCall == RTLIB::UNKNOWN_LIBCALL)
  6812. report_fatal_error("Unsupported element size");
  6813. TargetLowering::CallLoweringInfo CLI(*this);
  6814. CLI.setDebugLoc(dl)
  6815. .setChain(Chain)
  6816. .setLibCallee(TLI->getLibcallCallingConv(LibraryCall),
  6817. Type::getVoidTy(*getContext()),
  6818. getExternalSymbol(TLI->getLibcallName(LibraryCall),
  6819. TLI->getPointerTy(getDataLayout())),
  6820. std::move(Args))
  6821. .setDiscardResult()
  6822. .setTailCall(isTailCall);
  6823. std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
  6824. return CallResult.second;
  6825. }
  6826. SDValue SelectionDAG::getMemmove(SDValue Chain, const SDLoc &dl, SDValue Dst,
  6827. SDValue Src, SDValue Size, Align Alignment,
  6828. bool isVol, bool isTailCall,
  6829. MachinePointerInfo DstPtrInfo,
  6830. MachinePointerInfo SrcPtrInfo,
  6831. const AAMDNodes &AAInfo, AAResults *AA) {
  6832. // Check to see if we should lower the memmove to loads and stores first.
  6833. // For cases within the target-specified limits, this is the best choice.
  6834. ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
  6835. if (ConstantSize) {
  6836. // Memmove with size zero? Just return the original chain.
  6837. if (ConstantSize->isZero())
  6838. return Chain;
  6839. SDValue Result = getMemmoveLoadsAndStores(
  6840. *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), Alignment,
  6841. isVol, false, DstPtrInfo, SrcPtrInfo, AAInfo);
  6842. if (Result.getNode())
  6843. return Result;
  6844. }
  6845. // Then check to see if we should lower the memmove with target-specific
  6846. // code. If the target chooses to do this, this is the next best.
  6847. if (TSI) {
  6848. SDValue Result =
  6849. TSI->EmitTargetCodeForMemmove(*this, dl, Chain, Dst, Src, Size,
  6850. Alignment, isVol, DstPtrInfo, SrcPtrInfo);
  6851. if (Result.getNode())
  6852. return Result;
  6853. }
  6854. checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
  6855. checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace());
  6856. // FIXME: If the memmove is volatile, lowering it to plain libc memmove may
  6857. // not be safe. See memcpy above for more details.
  6858. // Emit a library call.
  6859. TargetLowering::ArgListTy Args;
  6860. TargetLowering::ArgListEntry Entry;
  6861. Entry.Ty = Type::getInt8PtrTy(*getContext());
  6862. Entry.Node = Dst; Args.push_back(Entry);
  6863. Entry.Node = Src; Args.push_back(Entry);
  6864. Entry.Ty = getDataLayout().getIntPtrType(*getContext());
  6865. Entry.Node = Size; Args.push_back(Entry);
  6866. // FIXME: pass in SDLoc
  6867. TargetLowering::CallLoweringInfo CLI(*this);
  6868. CLI.setDebugLoc(dl)
  6869. .setChain(Chain)
  6870. .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMMOVE),
  6871. Dst.getValueType().getTypeForEVT(*getContext()),
  6872. getExternalSymbol(TLI->getLibcallName(RTLIB::MEMMOVE),
  6873. TLI->getPointerTy(getDataLayout())),
  6874. std::move(Args))
  6875. .setDiscardResult()
  6876. .setTailCall(isTailCall);
  6877. std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
  6878. return CallResult.second;
  6879. }
  6880. SDValue SelectionDAG::getAtomicMemmove(SDValue Chain, const SDLoc &dl,
  6881. SDValue Dst, SDValue Src, SDValue Size,
  6882. Type *SizeTy, unsigned ElemSz,
  6883. bool isTailCall,
  6884. MachinePointerInfo DstPtrInfo,
  6885. MachinePointerInfo SrcPtrInfo) {
  6886. // Emit a library call.
  6887. TargetLowering::ArgListTy Args;
  6888. TargetLowering::ArgListEntry Entry;
  6889. Entry.Ty = getDataLayout().getIntPtrType(*getContext());
  6890. Entry.Node = Dst;
  6891. Args.push_back(Entry);
  6892. Entry.Node = Src;
  6893. Args.push_back(Entry);
  6894. Entry.Ty = SizeTy;
  6895. Entry.Node = Size;
  6896. Args.push_back(Entry);
  6897. RTLIB::Libcall LibraryCall =
  6898. RTLIB::getMEMMOVE_ELEMENT_UNORDERED_ATOMIC(ElemSz);
  6899. if (LibraryCall == RTLIB::UNKNOWN_LIBCALL)
  6900. report_fatal_error("Unsupported element size");
  6901. TargetLowering::CallLoweringInfo CLI(*this);
  6902. CLI.setDebugLoc(dl)
  6903. .setChain(Chain)
  6904. .setLibCallee(TLI->getLibcallCallingConv(LibraryCall),
  6905. Type::getVoidTy(*getContext()),
  6906. getExternalSymbol(TLI->getLibcallName(LibraryCall),
  6907. TLI->getPointerTy(getDataLayout())),
  6908. std::move(Args))
  6909. .setDiscardResult()
  6910. .setTailCall(isTailCall);
  6911. std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
  6912. return CallResult.second;
  6913. }
  6914. SDValue SelectionDAG::getMemset(SDValue Chain, const SDLoc &dl, SDValue Dst,
  6915. SDValue Src, SDValue Size, Align Alignment,
  6916. bool isVol, bool AlwaysInline, bool isTailCall,
  6917. MachinePointerInfo DstPtrInfo,
  6918. const AAMDNodes &AAInfo) {
  6919. // Check to see if we should lower the memset to stores first.
  6920. // For cases within the target-specified limits, this is the best choice.
  6921. ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
  6922. if (ConstantSize) {
  6923. // Memset with size zero? Just return the original chain.
  6924. if (ConstantSize->isZero())
  6925. return Chain;
  6926. SDValue Result = getMemsetStores(*this, dl, Chain, Dst, Src,
  6927. ConstantSize->getZExtValue(), Alignment,
  6928. isVol, false, DstPtrInfo, AAInfo);
  6929. if (Result.getNode())
  6930. return Result;
  6931. }
  6932. // Then check to see if we should lower the memset with target-specific
  6933. // code. If the target chooses to do this, this is the next best.
  6934. if (TSI) {
  6935. SDValue Result = TSI->EmitTargetCodeForMemset(
  6936. *this, dl, Chain, Dst, Src, Size, Alignment, isVol, AlwaysInline, DstPtrInfo);
  6937. if (Result.getNode())
  6938. return Result;
  6939. }
  6940. // If we really need inline code and the target declined to provide it,
  6941. // use a (potentially long) sequence of loads and stores.
  6942. if (AlwaysInline) {
  6943. assert(ConstantSize && "AlwaysInline requires a constant size!");
  6944. SDValue Result = getMemsetStores(*this, dl, Chain, Dst, Src,
  6945. ConstantSize->getZExtValue(), Alignment,
  6946. isVol, true, DstPtrInfo, AAInfo);
  6947. assert(Result &&
  6948. "getMemsetStores must return a valid sequence when AlwaysInline");
  6949. return Result;
  6950. }
  6951. checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
  6952. // Emit a library call.
  6953. auto &Ctx = *getContext();
  6954. const auto& DL = getDataLayout();
  6955. TargetLowering::CallLoweringInfo CLI(*this);
  6956. // FIXME: pass in SDLoc
  6957. CLI.setDebugLoc(dl).setChain(Chain);
  6958. ConstantSDNode *ConstantSrc = dyn_cast<ConstantSDNode>(Src);
  6959. const bool SrcIsZero = ConstantSrc && ConstantSrc->isZero();
  6960. const char *BzeroName = getTargetLoweringInfo().getLibcallName(RTLIB::BZERO);
  6961. // Helper function to create an Entry from Node and Type.
  6962. const auto CreateEntry = [](SDValue Node, Type *Ty) {
  6963. TargetLowering::ArgListEntry Entry;
  6964. Entry.Node = Node;
  6965. Entry.Ty = Ty;
  6966. return Entry;
  6967. };
  6968. // If zeroing out and bzero is present, use it.
  6969. if (SrcIsZero && BzeroName) {
  6970. TargetLowering::ArgListTy Args;
  6971. Args.push_back(CreateEntry(Dst, Type::getInt8PtrTy(Ctx)));
  6972. Args.push_back(CreateEntry(Size, DL.getIntPtrType(Ctx)));
  6973. CLI.setLibCallee(
  6974. TLI->getLibcallCallingConv(RTLIB::BZERO), Type::getVoidTy(Ctx),
  6975. getExternalSymbol(BzeroName, TLI->getPointerTy(DL)), std::move(Args));
  6976. } else {
  6977. TargetLowering::ArgListTy Args;
  6978. Args.push_back(CreateEntry(Dst, Type::getInt8PtrTy(Ctx)));
  6979. Args.push_back(CreateEntry(Src, Src.getValueType().getTypeForEVT(Ctx)));
  6980. Args.push_back(CreateEntry(Size, DL.getIntPtrType(Ctx)));
  6981. CLI.setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMSET),
  6982. Dst.getValueType().getTypeForEVT(Ctx),
  6983. getExternalSymbol(TLI->getLibcallName(RTLIB::MEMSET),
  6984. TLI->getPointerTy(DL)),
  6985. std::move(Args));
  6986. }
  6987. CLI.setDiscardResult().setTailCall(isTailCall);
  6988. std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
  6989. return CallResult.second;
  6990. }
  6991. SDValue SelectionDAG::getAtomicMemset(SDValue Chain, const SDLoc &dl,
  6992. SDValue Dst, SDValue Value, SDValue Size,
  6993. Type *SizeTy, unsigned ElemSz,
  6994. bool isTailCall,
  6995. MachinePointerInfo DstPtrInfo) {
  6996. // Emit a library call.
  6997. TargetLowering::ArgListTy Args;
  6998. TargetLowering::ArgListEntry Entry;
  6999. Entry.Ty = getDataLayout().getIntPtrType(*getContext());
  7000. Entry.Node = Dst;
  7001. Args.push_back(Entry);
  7002. Entry.Ty = Type::getInt8Ty(*getContext());
  7003. Entry.Node = Value;
  7004. Args.push_back(Entry);
  7005. Entry.Ty = SizeTy;
  7006. Entry.Node = Size;
  7007. Args.push_back(Entry);
  7008. RTLIB::Libcall LibraryCall =
  7009. RTLIB::getMEMSET_ELEMENT_UNORDERED_ATOMIC(ElemSz);
  7010. if (LibraryCall == RTLIB::UNKNOWN_LIBCALL)
  7011. report_fatal_error("Unsupported element size");
  7012. TargetLowering::CallLoweringInfo CLI(*this);
  7013. CLI.setDebugLoc(dl)
  7014. .setChain(Chain)
  7015. .setLibCallee(TLI->getLibcallCallingConv(LibraryCall),
  7016. Type::getVoidTy(*getContext()),
  7017. getExternalSymbol(TLI->getLibcallName(LibraryCall),
  7018. TLI->getPointerTy(getDataLayout())),
  7019. std::move(Args))
  7020. .setDiscardResult()
  7021. .setTailCall(isTailCall);
  7022. std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
  7023. return CallResult.second;
  7024. }
  7025. SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
  7026. SDVTList VTList, ArrayRef<SDValue> Ops,
  7027. MachineMemOperand *MMO) {
  7028. FoldingSetNodeID ID;
  7029. ID.AddInteger(MemVT.getRawBits());
  7030. AddNodeIDNode(ID, Opcode, VTList, Ops);
  7031. ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
  7032. ID.AddInteger(MMO->getFlags());
  7033. void* IP = nullptr;
  7034. if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
  7035. cast<AtomicSDNode>(E)->refineAlignment(MMO);
  7036. return SDValue(E, 0);
  7037. }
  7038. auto *N = newSDNode<AtomicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
  7039. VTList, MemVT, MMO);
  7040. createOperands(N, Ops);
  7041. CSEMap.InsertNode(N, IP);
  7042. InsertNode(N);
  7043. return SDValue(N, 0);
  7044. }
  7045. SDValue SelectionDAG::getAtomicCmpSwap(unsigned Opcode, const SDLoc &dl,
  7046. EVT MemVT, SDVTList VTs, SDValue Chain,
  7047. SDValue Ptr, SDValue Cmp, SDValue Swp,
  7048. MachineMemOperand *MMO) {
  7049. assert(Opcode == ISD::ATOMIC_CMP_SWAP ||
  7050. Opcode == ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
  7051. assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types");
  7052. SDValue Ops[] = {Chain, Ptr, Cmp, Swp};
  7053. return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
  7054. }
  7055. SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
  7056. SDValue Chain, SDValue Ptr, SDValue Val,
  7057. MachineMemOperand *MMO) {
  7058. assert((Opcode == ISD::ATOMIC_LOAD_ADD ||
  7059. Opcode == ISD::ATOMIC_LOAD_SUB ||
  7060. Opcode == ISD::ATOMIC_LOAD_AND ||
  7061. Opcode == ISD::ATOMIC_LOAD_CLR ||
  7062. Opcode == ISD::ATOMIC_LOAD_OR ||
  7063. Opcode == ISD::ATOMIC_LOAD_XOR ||
  7064. Opcode == ISD::ATOMIC_LOAD_NAND ||
  7065. Opcode == ISD::ATOMIC_LOAD_MIN ||
  7066. Opcode == ISD::ATOMIC_LOAD_MAX ||
  7067. Opcode == ISD::ATOMIC_LOAD_UMIN ||
  7068. Opcode == ISD::ATOMIC_LOAD_UMAX ||
  7069. Opcode == ISD::ATOMIC_LOAD_FADD ||
  7070. Opcode == ISD::ATOMIC_LOAD_FSUB ||
  7071. Opcode == ISD::ATOMIC_LOAD_FMAX ||
  7072. Opcode == ISD::ATOMIC_LOAD_FMIN ||
  7073. Opcode == ISD::ATOMIC_LOAD_UINC_WRAP ||
  7074. Opcode == ISD::ATOMIC_LOAD_UDEC_WRAP ||
  7075. Opcode == ISD::ATOMIC_SWAP ||
  7076. Opcode == ISD::ATOMIC_STORE) &&
  7077. "Invalid Atomic Op");
  7078. EVT VT = Val.getValueType();
  7079. SDVTList VTs = Opcode == ISD::ATOMIC_STORE ? getVTList(MVT::Other) :
  7080. getVTList(VT, MVT::Other);
  7081. SDValue Ops[] = {Chain, Ptr, Val};
  7082. return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
  7083. }
  7084. SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
  7085. EVT VT, SDValue Chain, SDValue Ptr,
  7086. MachineMemOperand *MMO) {
  7087. assert(Opcode == ISD::ATOMIC_LOAD && "Invalid Atomic Op");
  7088. SDVTList VTs = getVTList(VT, MVT::Other);
  7089. SDValue Ops[] = {Chain, Ptr};
  7090. return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
  7091. }
  7092. /// getMergeValues - Create a MERGE_VALUES node from the given operands.
  7093. SDValue SelectionDAG::getMergeValues(ArrayRef<SDValue> Ops, const SDLoc &dl) {
  7094. if (Ops.size() == 1)
  7095. return Ops[0];
  7096. SmallVector<EVT, 4> VTs;
  7097. VTs.reserve(Ops.size());
  7098. for (const SDValue &Op : Ops)
  7099. VTs.push_back(Op.getValueType());
  7100. return getNode(ISD::MERGE_VALUES, dl, getVTList(VTs), Ops);
  7101. }
  7102. SDValue SelectionDAG::getMemIntrinsicNode(
  7103. unsigned Opcode, const SDLoc &dl, SDVTList VTList, ArrayRef<SDValue> Ops,
  7104. EVT MemVT, MachinePointerInfo PtrInfo, Align Alignment,
  7105. MachineMemOperand::Flags Flags, uint64_t Size, const AAMDNodes &AAInfo) {
  7106. if (!Size && MemVT.isScalableVector())
  7107. Size = MemoryLocation::UnknownSize;
  7108. else if (!Size)
  7109. Size = MemVT.getStoreSize();
  7110. MachineFunction &MF = getMachineFunction();
  7111. MachineMemOperand *MMO =
  7112. MF.getMachineMemOperand(PtrInfo, Flags, Size, Alignment, AAInfo);
  7113. return getMemIntrinsicNode(Opcode, dl, VTList, Ops, MemVT, MMO);
  7114. }
  7115. SDValue SelectionDAG::getMemIntrinsicNode(unsigned Opcode, const SDLoc &dl,
  7116. SDVTList VTList,
  7117. ArrayRef<SDValue> Ops, EVT MemVT,
  7118. MachineMemOperand *MMO) {
  7119. assert((Opcode == ISD::INTRINSIC_VOID ||
  7120. Opcode == ISD::INTRINSIC_W_CHAIN ||
  7121. Opcode == ISD::PREFETCH ||
  7122. ((int)Opcode <= std::numeric_limits<int>::max() &&
  7123. (int)Opcode >= ISD::FIRST_TARGET_MEMORY_OPCODE)) &&
  7124. "Opcode is not a memory-accessing opcode!");
  7125. // Memoize the node unless it returns a flag.
  7126. MemIntrinsicSDNode *N;
  7127. if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
  7128. FoldingSetNodeID ID;
  7129. AddNodeIDNode(ID, Opcode, VTList, Ops);
  7130. ID.AddInteger(getSyntheticNodeSubclassData<MemIntrinsicSDNode>(
  7131. Opcode, dl.getIROrder(), VTList, MemVT, MMO));
  7132. ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
  7133. ID.AddInteger(MMO->getFlags());
  7134. void *IP = nullptr;
  7135. if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
  7136. cast<MemIntrinsicSDNode>(E)->refineAlignment(MMO);
  7137. return SDValue(E, 0);
  7138. }
  7139. N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
  7140. VTList, MemVT, MMO);
  7141. createOperands(N, Ops);
  7142. CSEMap.InsertNode(N, IP);
  7143. } else {
  7144. N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
  7145. VTList, MemVT, MMO);
  7146. createOperands(N, Ops);
  7147. }
  7148. InsertNode(N);
  7149. SDValue V(N, 0);
  7150. NewSDValueDbgMsg(V, "Creating new node: ", this);
  7151. return V;
  7152. }
  7153. SDValue SelectionDAG::getLifetimeNode(bool IsStart, const SDLoc &dl,
  7154. SDValue Chain, int FrameIndex,
  7155. int64_t Size, int64_t Offset) {
  7156. const unsigned Opcode = IsStart ? ISD::LIFETIME_START : ISD::LIFETIME_END;
  7157. const auto VTs = getVTList(MVT::Other);
  7158. SDValue Ops[2] = {
  7159. Chain,
  7160. getFrameIndex(FrameIndex,
  7161. getTargetLoweringInfo().getFrameIndexTy(getDataLayout()),
  7162. true)};
  7163. FoldingSetNodeID ID;
  7164. AddNodeIDNode(ID, Opcode, VTs, Ops);
  7165. ID.AddInteger(FrameIndex);
  7166. ID.AddInteger(Size);
  7167. ID.AddInteger(Offset);
  7168. void *IP = nullptr;
  7169. if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
  7170. return SDValue(E, 0);
  7171. LifetimeSDNode *N = newSDNode<LifetimeSDNode>(
  7172. Opcode, dl.getIROrder(), dl.getDebugLoc(), VTs, Size, Offset);
  7173. createOperands(N, Ops);
  7174. CSEMap.InsertNode(N, IP);
  7175. InsertNode(N);
  7176. SDValue V(N, 0);
  7177. NewSDValueDbgMsg(V, "Creating new node: ", this);
  7178. return V;
  7179. }
  7180. SDValue SelectionDAG::getPseudoProbeNode(const SDLoc &Dl, SDValue Chain,
  7181. uint64_t Guid, uint64_t Index,
  7182. uint32_t Attr) {
  7183. const unsigned Opcode = ISD::PSEUDO_PROBE;
  7184. const auto VTs = getVTList(MVT::Other);
  7185. SDValue Ops[] = {Chain};
  7186. FoldingSetNodeID ID;
  7187. AddNodeIDNode(ID, Opcode, VTs, Ops);
  7188. ID.AddInteger(Guid);
  7189. ID.AddInteger(Index);
  7190. void *IP = nullptr;
  7191. if (SDNode *E = FindNodeOrInsertPos(ID, Dl, IP))
  7192. return SDValue(E, 0);
  7193. auto *N = newSDNode<PseudoProbeSDNode>(
  7194. Opcode, Dl.getIROrder(), Dl.getDebugLoc(), VTs, Guid, Index, Attr);
  7195. createOperands(N, Ops);
  7196. CSEMap.InsertNode(N, IP);
  7197. InsertNode(N);
  7198. SDValue V(N, 0);
  7199. NewSDValueDbgMsg(V, "Creating new node: ", this);
  7200. return V;
  7201. }
  7202. /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a
  7203. /// MachinePointerInfo record from it. This is particularly useful because the
  7204. /// code generator has many cases where it doesn't bother passing in a
  7205. /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst".
  7206. static MachinePointerInfo InferPointerInfo(const MachinePointerInfo &Info,
  7207. SelectionDAG &DAG, SDValue Ptr,
  7208. int64_t Offset = 0) {
  7209. // If this is FI+Offset, we can model it.
  7210. if (const FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr))
  7211. return MachinePointerInfo::getFixedStack(DAG.getMachineFunction(),
  7212. FI->getIndex(), Offset);
  7213. // If this is (FI+Offset1)+Offset2, we can model it.
  7214. if (Ptr.getOpcode() != ISD::ADD ||
  7215. !isa<ConstantSDNode>(Ptr.getOperand(1)) ||
  7216. !isa<FrameIndexSDNode>(Ptr.getOperand(0)))
  7217. return Info;
  7218. int FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
  7219. return MachinePointerInfo::getFixedStack(
  7220. DAG.getMachineFunction(), FI,
  7221. Offset + cast<ConstantSDNode>(Ptr.getOperand(1))->getSExtValue());
  7222. }
  7223. /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a
  7224. /// MachinePointerInfo record from it. This is particularly useful because the
  7225. /// code generator has many cases where it doesn't bother passing in a
  7226. /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst".
  7227. static MachinePointerInfo InferPointerInfo(const MachinePointerInfo &Info,
  7228. SelectionDAG &DAG, SDValue Ptr,
  7229. SDValue OffsetOp) {
  7230. // If the 'Offset' value isn't a constant, we can't handle this.
  7231. if (ConstantSDNode *OffsetNode = dyn_cast<ConstantSDNode>(OffsetOp))
  7232. return InferPointerInfo(Info, DAG, Ptr, OffsetNode->getSExtValue());
  7233. if (OffsetOp.isUndef())
  7234. return InferPointerInfo(Info, DAG, Ptr);
  7235. return Info;
  7236. }
  7237. SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
  7238. EVT VT, const SDLoc &dl, SDValue Chain,
  7239. SDValue Ptr, SDValue Offset,
  7240. MachinePointerInfo PtrInfo, EVT MemVT,
  7241. Align Alignment,
  7242. MachineMemOperand::Flags MMOFlags,
  7243. const AAMDNodes &AAInfo, const MDNode *Ranges) {
  7244. assert(Chain.getValueType() == MVT::Other &&
  7245. "Invalid chain type");
  7246. MMOFlags |= MachineMemOperand::MOLoad;
  7247. assert((MMOFlags & MachineMemOperand::MOStore) == 0);
  7248. // If we don't have a PtrInfo, infer the trivial frame index case to simplify
  7249. // clients.
  7250. if (PtrInfo.V.isNull())
  7251. PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset);
  7252. uint64_t Size = MemoryLocation::getSizeOrUnknown(MemVT.getStoreSize());
  7253. MachineFunction &MF = getMachineFunction();
  7254. MachineMemOperand *MMO = MF.getMachineMemOperand(PtrInfo, MMOFlags, Size,
  7255. Alignment, AAInfo, Ranges);
  7256. return getLoad(AM, ExtType, VT, dl, Chain, Ptr, Offset, MemVT, MMO);
  7257. }
  7258. SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
  7259. EVT VT, const SDLoc &dl, SDValue Chain,
  7260. SDValue Ptr, SDValue Offset, EVT MemVT,
  7261. MachineMemOperand *MMO) {
  7262. if (VT == MemVT) {
  7263. ExtType = ISD::NON_EXTLOAD;
  7264. } else if (ExtType == ISD::NON_EXTLOAD) {
  7265. assert(VT == MemVT && "Non-extending load from different memory type!");
  7266. } else {
  7267. // Extending load.
  7268. assert(MemVT.getScalarType().bitsLT(VT.getScalarType()) &&
  7269. "Should only be an extending load, not truncating!");
  7270. assert(VT.isInteger() == MemVT.isInteger() &&
  7271. "Cannot convert from FP to Int or Int -> FP!");
  7272. assert(VT.isVector() == MemVT.isVector() &&
  7273. "Cannot use an ext load to convert to or from a vector!");
  7274. assert((!VT.isVector() ||
  7275. VT.getVectorElementCount() == MemVT.getVectorElementCount()) &&
  7276. "Cannot use an ext load to change the number of vector elements!");
  7277. }
  7278. bool Indexed = AM != ISD::UNINDEXED;
  7279. assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!");
  7280. SDVTList VTs = Indexed ?
  7281. getVTList(VT, Ptr.getValueType(), MVT::Other) : getVTList(VT, MVT::Other);
  7282. SDValue Ops[] = { Chain, Ptr, Offset };
  7283. FoldingSetNodeID ID;
  7284. AddNodeIDNode(ID, ISD::LOAD, VTs, Ops);
  7285. ID.AddInteger(MemVT.getRawBits());
  7286. ID.AddInteger(getSyntheticNodeSubclassData<LoadSDNode>(
  7287. dl.getIROrder(), VTs, AM, ExtType, MemVT, MMO));
  7288. ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
  7289. ID.AddInteger(MMO->getFlags());
  7290. void *IP = nullptr;
  7291. if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
  7292. cast<LoadSDNode>(E)->refineAlignment(MMO);
  7293. return SDValue(E, 0);
  7294. }
  7295. auto *N = newSDNode<LoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
  7296. ExtType, MemVT, MMO);
  7297. createOperands(N, Ops);
  7298. CSEMap.InsertNode(N, IP);
  7299. InsertNode(N);
  7300. SDValue V(N, 0);
  7301. NewSDValueDbgMsg(V, "Creating new node: ", this);
  7302. return V;
  7303. }
  7304. SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain,
  7305. SDValue Ptr, MachinePointerInfo PtrInfo,
  7306. MaybeAlign Alignment,
  7307. MachineMemOperand::Flags MMOFlags,
  7308. const AAMDNodes &AAInfo, const MDNode *Ranges) {
  7309. SDValue Undef = getUNDEF(Ptr.getValueType());
  7310. return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
  7311. PtrInfo, VT, Alignment, MMOFlags, AAInfo, Ranges);
  7312. }
  7313. SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain,
  7314. SDValue Ptr, MachineMemOperand *MMO) {
  7315. SDValue Undef = getUNDEF(Ptr.getValueType());
  7316. return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
  7317. VT, MMO);
  7318. }
  7319. SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl,
  7320. EVT VT, SDValue Chain, SDValue Ptr,
  7321. MachinePointerInfo PtrInfo, EVT MemVT,
  7322. MaybeAlign Alignment,
  7323. MachineMemOperand::Flags MMOFlags,
  7324. const AAMDNodes &AAInfo) {
  7325. SDValue Undef = getUNDEF(Ptr.getValueType());
  7326. return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, PtrInfo,
  7327. MemVT, Alignment, MMOFlags, AAInfo);
  7328. }
  7329. SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl,
  7330. EVT VT, SDValue Chain, SDValue Ptr, EVT MemVT,
  7331. MachineMemOperand *MMO) {
  7332. SDValue Undef = getUNDEF(Ptr.getValueType());
  7333. return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef,
  7334. MemVT, MMO);
  7335. }
  7336. SDValue SelectionDAG::getIndexedLoad(SDValue OrigLoad, const SDLoc &dl,
  7337. SDValue Base, SDValue Offset,
  7338. ISD::MemIndexedMode AM) {
  7339. LoadSDNode *LD = cast<LoadSDNode>(OrigLoad);
  7340. assert(LD->getOffset().isUndef() && "Load is already a indexed load!");
  7341. // Don't propagate the invariant or dereferenceable flags.
  7342. auto MMOFlags =
  7343. LD->getMemOperand()->getFlags() &
  7344. ~(MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable);
  7345. return getLoad(AM, LD->getExtensionType(), OrigLoad.getValueType(), dl,
  7346. LD->getChain(), Base, Offset, LD->getPointerInfo(),
  7347. LD->getMemoryVT(), LD->getAlign(), MMOFlags, LD->getAAInfo());
  7348. }
  7349. SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val,
  7350. SDValue Ptr, MachinePointerInfo PtrInfo,
  7351. Align Alignment,
  7352. MachineMemOperand::Flags MMOFlags,
  7353. const AAMDNodes &AAInfo) {
  7354. assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
  7355. MMOFlags |= MachineMemOperand::MOStore;
  7356. assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
  7357. if (PtrInfo.V.isNull())
  7358. PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
  7359. MachineFunction &MF = getMachineFunction();
  7360. uint64_t Size =
  7361. MemoryLocation::getSizeOrUnknown(Val.getValueType().getStoreSize());
  7362. MachineMemOperand *MMO =
  7363. MF.getMachineMemOperand(PtrInfo, MMOFlags, Size, Alignment, AAInfo);
  7364. return getStore(Chain, dl, Val, Ptr, MMO);
  7365. }
  7366. SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val,
  7367. SDValue Ptr, MachineMemOperand *MMO) {
  7368. assert(Chain.getValueType() == MVT::Other &&
  7369. "Invalid chain type");
  7370. EVT VT = Val.getValueType();
  7371. SDVTList VTs = getVTList(MVT::Other);
  7372. SDValue Undef = getUNDEF(Ptr.getValueType());
  7373. SDValue Ops[] = { Chain, Val, Ptr, Undef };
  7374. FoldingSetNodeID ID;
  7375. AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
  7376. ID.AddInteger(VT.getRawBits());
  7377. ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>(
  7378. dl.getIROrder(), VTs, ISD::UNINDEXED, false, VT, MMO));
  7379. ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
  7380. ID.AddInteger(MMO->getFlags());
  7381. void *IP = nullptr;
  7382. if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
  7383. cast<StoreSDNode>(E)->refineAlignment(MMO);
  7384. return SDValue(E, 0);
  7385. }
  7386. auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
  7387. ISD::UNINDEXED, false, VT, MMO);
  7388. createOperands(N, Ops);
  7389. CSEMap.InsertNode(N, IP);
  7390. InsertNode(N);
  7391. SDValue V(N, 0);
  7392. NewSDValueDbgMsg(V, "Creating new node: ", this);
  7393. return V;
  7394. }
  7395. SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val,
  7396. SDValue Ptr, MachinePointerInfo PtrInfo,
  7397. EVT SVT, Align Alignment,
  7398. MachineMemOperand::Flags MMOFlags,
  7399. const AAMDNodes &AAInfo) {
  7400. assert(Chain.getValueType() == MVT::Other &&
  7401. "Invalid chain type");
  7402. MMOFlags |= MachineMemOperand::MOStore;
  7403. assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
  7404. if (PtrInfo.V.isNull())
  7405. PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
  7406. MachineFunction &MF = getMachineFunction();
  7407. MachineMemOperand *MMO = MF.getMachineMemOperand(
  7408. PtrInfo, MMOFlags, MemoryLocation::getSizeOrUnknown(SVT.getStoreSize()),
  7409. Alignment, AAInfo);
  7410. return getTruncStore(Chain, dl, Val, Ptr, SVT, MMO);
  7411. }
  7412. SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val,
  7413. SDValue Ptr, EVT SVT,
  7414. MachineMemOperand *MMO) {
  7415. EVT VT = Val.getValueType();
  7416. assert(Chain.getValueType() == MVT::Other &&
  7417. "Invalid chain type");
  7418. if (VT == SVT)
  7419. return getStore(Chain, dl, Val, Ptr, MMO);
  7420. assert(SVT.getScalarType().bitsLT(VT.getScalarType()) &&
  7421. "Should only be a truncating store, not extending!");
  7422. assert(VT.isInteger() == SVT.isInteger() &&
  7423. "Can't do FP-INT conversion!");
  7424. assert(VT.isVector() == SVT.isVector() &&
  7425. "Cannot use trunc store to convert to or from a vector!");
  7426. assert((!VT.isVector() ||
  7427. VT.getVectorElementCount() == SVT.getVectorElementCount()) &&
  7428. "Cannot use trunc store to change the number of vector elements!");
  7429. SDVTList VTs = getVTList(MVT::Other);
  7430. SDValue Undef = getUNDEF(Ptr.getValueType());
  7431. SDValue Ops[] = { Chain, Val, Ptr, Undef };
  7432. FoldingSetNodeID ID;
  7433. AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
  7434. ID.AddInteger(SVT.getRawBits());
  7435. ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>(
  7436. dl.getIROrder(), VTs, ISD::UNINDEXED, true, SVT, MMO));
  7437. ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
  7438. ID.AddInteger(MMO->getFlags());
  7439. void *IP = nullptr;
  7440. if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
  7441. cast<StoreSDNode>(E)->refineAlignment(MMO);
  7442. return SDValue(E, 0);
  7443. }
  7444. auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
  7445. ISD::UNINDEXED, true, SVT, MMO);
  7446. createOperands(N, Ops);
  7447. CSEMap.InsertNode(N, IP);
  7448. InsertNode(N);
  7449. SDValue V(N, 0);
  7450. NewSDValueDbgMsg(V, "Creating new node: ", this);
  7451. return V;
  7452. }
  7453. SDValue SelectionDAG::getIndexedStore(SDValue OrigStore, const SDLoc &dl,
  7454. SDValue Base, SDValue Offset,
  7455. ISD::MemIndexedMode AM) {
  7456. StoreSDNode *ST = cast<StoreSDNode>(OrigStore);
  7457. assert(ST->getOffset().isUndef() && "Store is already a indexed store!");
  7458. SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
  7459. SDValue Ops[] = { ST->getChain(), ST->getValue(), Base, Offset };
  7460. FoldingSetNodeID ID;
  7461. AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
  7462. ID.AddInteger(ST->getMemoryVT().getRawBits());
  7463. ID.AddInteger(ST->getRawSubclassData());
  7464. ID.AddInteger(ST->getPointerInfo().getAddrSpace());
  7465. ID.AddInteger(ST->getMemOperand()->getFlags());
  7466. void *IP = nullptr;
  7467. if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
  7468. return SDValue(E, 0);
  7469. auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
  7470. ST->isTruncatingStore(), ST->getMemoryVT(),
  7471. ST->getMemOperand());
  7472. createOperands(N, Ops);
  7473. CSEMap.InsertNode(N, IP);
  7474. InsertNode(N);
  7475. SDValue V(N, 0);
  7476. NewSDValueDbgMsg(V, "Creating new node: ", this);
  7477. return V;
  7478. }
  7479. SDValue SelectionDAG::getLoadVP(
  7480. ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, EVT VT, const SDLoc &dl,
  7481. SDValue Chain, SDValue Ptr, SDValue Offset, SDValue Mask, SDValue EVL,
  7482. MachinePointerInfo PtrInfo, EVT MemVT, Align Alignment,
  7483. MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo,
  7484. const MDNode *Ranges, bool IsExpanding) {
  7485. assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
  7486. MMOFlags |= MachineMemOperand::MOLoad;
  7487. assert((MMOFlags & MachineMemOperand::MOStore) == 0);
  7488. // If we don't have a PtrInfo, infer the trivial frame index case to simplify
  7489. // clients.
  7490. if (PtrInfo.V.isNull())
  7491. PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset);
  7492. uint64_t Size = MemoryLocation::getSizeOrUnknown(MemVT.getStoreSize());
  7493. MachineFunction &MF = getMachineFunction();
  7494. MachineMemOperand *MMO = MF.getMachineMemOperand(PtrInfo, MMOFlags, Size,
  7495. Alignment, AAInfo, Ranges);
  7496. return getLoadVP(AM, ExtType, VT, dl, Chain, Ptr, Offset, Mask, EVL, MemVT,
  7497. MMO, IsExpanding);
  7498. }
  7499. SDValue SelectionDAG::getLoadVP(ISD::MemIndexedMode AM,
  7500. ISD::LoadExtType ExtType, EVT VT,
  7501. const SDLoc &dl, SDValue Chain, SDValue Ptr,
  7502. SDValue Offset, SDValue Mask, SDValue EVL,
  7503. EVT MemVT, MachineMemOperand *MMO,
  7504. bool IsExpanding) {
  7505. bool Indexed = AM != ISD::UNINDEXED;
  7506. assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!");
  7507. SDVTList VTs = Indexed ? getVTList(VT, Ptr.getValueType(), MVT::Other)
  7508. : getVTList(VT, MVT::Other);
  7509. SDValue Ops[] = {Chain, Ptr, Offset, Mask, EVL};
  7510. FoldingSetNodeID ID;
  7511. AddNodeIDNode(ID, ISD::VP_LOAD, VTs, Ops);
  7512. ID.AddInteger(VT.getRawBits());
  7513. ID.AddInteger(getSyntheticNodeSubclassData<VPLoadSDNode>(
  7514. dl.getIROrder(), VTs, AM, ExtType, IsExpanding, MemVT, MMO));
  7515. ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
  7516. ID.AddInteger(MMO->getFlags());
  7517. void *IP = nullptr;
  7518. if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
  7519. cast<VPLoadSDNode>(E)->refineAlignment(MMO);
  7520. return SDValue(E, 0);
  7521. }
  7522. auto *N = newSDNode<VPLoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
  7523. ExtType, IsExpanding, MemVT, MMO);
  7524. createOperands(N, Ops);
  7525. CSEMap.InsertNode(N, IP);
  7526. InsertNode(N);
  7527. SDValue V(N, 0);
  7528. NewSDValueDbgMsg(V, "Creating new node: ", this);
  7529. return V;
  7530. }
  7531. SDValue SelectionDAG::getLoadVP(EVT VT, const SDLoc &dl, SDValue Chain,
  7532. SDValue Ptr, SDValue Mask, SDValue EVL,
  7533. MachinePointerInfo PtrInfo,
  7534. MaybeAlign Alignment,
  7535. MachineMemOperand::Flags MMOFlags,
  7536. const AAMDNodes &AAInfo, const MDNode *Ranges,
  7537. bool IsExpanding) {
  7538. SDValue Undef = getUNDEF(Ptr.getValueType());
  7539. return getLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
  7540. Mask, EVL, PtrInfo, VT, Alignment, MMOFlags, AAInfo, Ranges,
  7541. IsExpanding);
  7542. }
  7543. SDValue SelectionDAG::getLoadVP(EVT VT, const SDLoc &dl, SDValue Chain,
  7544. SDValue Ptr, SDValue Mask, SDValue EVL,
  7545. MachineMemOperand *MMO, bool IsExpanding) {
  7546. SDValue Undef = getUNDEF(Ptr.getValueType());
  7547. return getLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
  7548. Mask, EVL, VT, MMO, IsExpanding);
  7549. }
  7550. SDValue SelectionDAG::getExtLoadVP(ISD::LoadExtType ExtType, const SDLoc &dl,
  7551. EVT VT, SDValue Chain, SDValue Ptr,
  7552. SDValue Mask, SDValue EVL,
  7553. MachinePointerInfo PtrInfo, EVT MemVT,
  7554. MaybeAlign Alignment,
  7555. MachineMemOperand::Flags MMOFlags,
  7556. const AAMDNodes &AAInfo, bool IsExpanding) {
  7557. SDValue Undef = getUNDEF(Ptr.getValueType());
  7558. return getLoadVP(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, Mask,
  7559. EVL, PtrInfo, MemVT, Alignment, MMOFlags, AAInfo, nullptr,
  7560. IsExpanding);
  7561. }
  7562. SDValue SelectionDAG::getExtLoadVP(ISD::LoadExtType ExtType, const SDLoc &dl,
  7563. EVT VT, SDValue Chain, SDValue Ptr,
  7564. SDValue Mask, SDValue EVL, EVT MemVT,
  7565. MachineMemOperand *MMO, bool IsExpanding) {
  7566. SDValue Undef = getUNDEF(Ptr.getValueType());
  7567. return getLoadVP(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, Mask,
  7568. EVL, MemVT, MMO, IsExpanding);
  7569. }
  7570. SDValue SelectionDAG::getIndexedLoadVP(SDValue OrigLoad, const SDLoc &dl,
  7571. SDValue Base, SDValue Offset,
  7572. ISD::MemIndexedMode AM) {
  7573. auto *LD = cast<VPLoadSDNode>(OrigLoad);
  7574. assert(LD->getOffset().isUndef() && "Load is already a indexed load!");
  7575. // Don't propagate the invariant or dereferenceable flags.
  7576. auto MMOFlags =
  7577. LD->getMemOperand()->getFlags() &
  7578. ~(MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable);
  7579. return getLoadVP(AM, LD->getExtensionType(), OrigLoad.getValueType(), dl,
  7580. LD->getChain(), Base, Offset, LD->getMask(),
  7581. LD->getVectorLength(), LD->getPointerInfo(),
  7582. LD->getMemoryVT(), LD->getAlign(), MMOFlags, LD->getAAInfo(),
  7583. nullptr, LD->isExpandingLoad());
  7584. }
  7585. SDValue SelectionDAG::getStoreVP(SDValue Chain, const SDLoc &dl, SDValue Val,
  7586. SDValue Ptr, SDValue Offset, SDValue Mask,
  7587. SDValue EVL, EVT MemVT, MachineMemOperand *MMO,
  7588. ISD::MemIndexedMode AM, bool IsTruncating,
  7589. bool IsCompressing) {
  7590. assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
  7591. bool Indexed = AM != ISD::UNINDEXED;
  7592. assert((Indexed || Offset.isUndef()) && "Unindexed vp_store with an offset!");
  7593. SDVTList VTs = Indexed ? getVTList(Ptr.getValueType(), MVT::Other)
  7594. : getVTList(MVT::Other);
  7595. SDValue Ops[] = {Chain, Val, Ptr, Offset, Mask, EVL};
  7596. FoldingSetNodeID ID;
  7597. AddNodeIDNode(ID, ISD::VP_STORE, VTs, Ops);
  7598. ID.AddInteger(MemVT.getRawBits());
  7599. ID.AddInteger(getSyntheticNodeSubclassData<VPStoreSDNode>(
  7600. dl.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO));
  7601. ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
  7602. ID.AddInteger(MMO->getFlags());
  7603. void *IP = nullptr;
  7604. if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
  7605. cast<VPStoreSDNode>(E)->refineAlignment(MMO);
  7606. return SDValue(E, 0);
  7607. }
  7608. auto *N = newSDNode<VPStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
  7609. IsTruncating, IsCompressing, MemVT, MMO);
  7610. createOperands(N, Ops);
  7611. CSEMap.InsertNode(N, IP);
  7612. InsertNode(N);
  7613. SDValue V(N, 0);
  7614. NewSDValueDbgMsg(V, "Creating new node: ", this);
  7615. return V;
  7616. }
  7617. SDValue SelectionDAG::getTruncStoreVP(SDValue Chain, const SDLoc &dl,
  7618. SDValue Val, SDValue Ptr, SDValue Mask,
  7619. SDValue EVL, MachinePointerInfo PtrInfo,
  7620. EVT SVT, Align Alignment,
  7621. MachineMemOperand::Flags MMOFlags,
  7622. const AAMDNodes &AAInfo,
  7623. bool IsCompressing) {
  7624. assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
  7625. MMOFlags |= MachineMemOperand::MOStore;
  7626. assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
  7627. if (PtrInfo.V.isNull())
  7628. PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
  7629. MachineFunction &MF = getMachineFunction();
  7630. MachineMemOperand *MMO = MF.getMachineMemOperand(
  7631. PtrInfo, MMOFlags, MemoryLocation::getSizeOrUnknown(SVT.getStoreSize()),
  7632. Alignment, AAInfo);
  7633. return getTruncStoreVP(Chain, dl, Val, Ptr, Mask, EVL, SVT, MMO,
  7634. IsCompressing);
  7635. }
  7636. SDValue SelectionDAG::getTruncStoreVP(SDValue Chain, const SDLoc &dl,
  7637. SDValue Val, SDValue Ptr, SDValue Mask,
  7638. SDValue EVL, EVT SVT,
  7639. MachineMemOperand *MMO,
  7640. bool IsCompressing) {
  7641. EVT VT = Val.getValueType();
  7642. assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
  7643. if (VT == SVT)
  7644. return getStoreVP(Chain, dl, Val, Ptr, getUNDEF(Ptr.getValueType()), Mask,
  7645. EVL, VT, MMO, ISD::UNINDEXED,
  7646. /*IsTruncating*/ false, IsCompressing);
  7647. assert(SVT.getScalarType().bitsLT(VT.getScalarType()) &&
  7648. "Should only be a truncating store, not extending!");
  7649. assert(VT.isInteger() == SVT.isInteger() && "Can't do FP-INT conversion!");
  7650. assert(VT.isVector() == SVT.isVector() &&
  7651. "Cannot use trunc store to convert to or from a vector!");
  7652. assert((!VT.isVector() ||
  7653. VT.getVectorElementCount() == SVT.getVectorElementCount()) &&
  7654. "Cannot use trunc store to change the number of vector elements!");
  7655. SDVTList VTs = getVTList(MVT::Other);
  7656. SDValue Undef = getUNDEF(Ptr.getValueType());
  7657. SDValue Ops[] = {Chain, Val, Ptr, Undef, Mask, EVL};
  7658. FoldingSetNodeID ID;
  7659. AddNodeIDNode(ID, ISD::VP_STORE, VTs, Ops);
  7660. ID.AddInteger(SVT.getRawBits());
  7661. ID.AddInteger(getSyntheticNodeSubclassData<VPStoreSDNode>(
  7662. dl.getIROrder(), VTs, ISD::UNINDEXED, true, IsCompressing, SVT, MMO));
  7663. ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
  7664. ID.AddInteger(MMO->getFlags());
  7665. void *IP = nullptr;
  7666. if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
  7667. cast<VPStoreSDNode>(E)->refineAlignment(MMO);
  7668. return SDValue(E, 0);
  7669. }
  7670. auto *N =
  7671. newSDNode<VPStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
  7672. ISD::UNINDEXED, true, IsCompressing, SVT, MMO);
  7673. createOperands(N, Ops);
  7674. CSEMap.InsertNode(N, IP);
  7675. InsertNode(N);
  7676. SDValue V(N, 0);
  7677. NewSDValueDbgMsg(V, "Creating new node: ", this);
  7678. return V;
  7679. }
  7680. SDValue SelectionDAG::getIndexedStoreVP(SDValue OrigStore, const SDLoc &dl,
  7681. SDValue Base, SDValue Offset,
  7682. ISD::MemIndexedMode AM) {
  7683. auto *ST = cast<VPStoreSDNode>(OrigStore);
  7684. assert(ST->getOffset().isUndef() && "Store is already an indexed store!");
  7685. SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
  7686. SDValue Ops[] = {ST->getChain(), ST->getValue(), Base,
  7687. Offset, ST->getMask(), ST->getVectorLength()};
  7688. FoldingSetNodeID ID;
  7689. AddNodeIDNode(ID, ISD::VP_STORE, VTs, Ops);
  7690. ID.AddInteger(ST->getMemoryVT().getRawBits());
  7691. ID.AddInteger(ST->getRawSubclassData());
  7692. ID.AddInteger(ST->getPointerInfo().getAddrSpace());
  7693. ID.AddInteger(ST->getMemOperand()->getFlags());
  7694. void *IP = nullptr;
  7695. if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
  7696. return SDValue(E, 0);
  7697. auto *N = newSDNode<VPStoreSDNode>(
  7698. dl.getIROrder(), dl.getDebugLoc(), VTs, AM, ST->isTruncatingStore(),
  7699. ST->isCompressingStore(), ST->getMemoryVT(), ST->getMemOperand());
  7700. createOperands(N, Ops);
  7701. CSEMap.InsertNode(N, IP);
  7702. InsertNode(N);
  7703. SDValue V(N, 0);
  7704. NewSDValueDbgMsg(V, "Creating new node: ", this);
  7705. return V;
  7706. }
  7707. SDValue SelectionDAG::getStridedLoadVP(
  7708. ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, EVT VT, const SDLoc &DL,
  7709. SDValue Chain, SDValue Ptr, SDValue Offset, SDValue Stride, SDValue Mask,
  7710. SDValue EVL, MachinePointerInfo PtrInfo, EVT MemVT, Align Alignment,
  7711. MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo,
  7712. const MDNode *Ranges, bool IsExpanding) {
  7713. assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
  7714. MMOFlags |= MachineMemOperand::MOLoad;
  7715. assert((MMOFlags & MachineMemOperand::MOStore) == 0);
  7716. // If we don't have a PtrInfo, infer the trivial frame index case to simplify
  7717. // clients.
  7718. if (PtrInfo.V.isNull())
  7719. PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset);
  7720. uint64_t Size = MemoryLocation::UnknownSize;
  7721. MachineFunction &MF = getMachineFunction();
  7722. MachineMemOperand *MMO = MF.getMachineMemOperand(PtrInfo, MMOFlags, Size,
  7723. Alignment, AAInfo, Ranges);
  7724. return getStridedLoadVP(AM, ExtType, VT, DL, Chain, Ptr, Offset, Stride, Mask,
  7725. EVL, MemVT, MMO, IsExpanding);
  7726. }
  7727. SDValue SelectionDAG::getStridedLoadVP(
  7728. ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, EVT VT, const SDLoc &DL,
  7729. SDValue Chain, SDValue Ptr, SDValue Offset, SDValue Stride, SDValue Mask,
  7730. SDValue EVL, EVT MemVT, MachineMemOperand *MMO, bool IsExpanding) {
  7731. bool Indexed = AM != ISD::UNINDEXED;
  7732. assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!");
  7733. SDValue Ops[] = {Chain, Ptr, Offset, Stride, Mask, EVL};
  7734. SDVTList VTs = Indexed ? getVTList(VT, Ptr.getValueType(), MVT::Other)
  7735. : getVTList(VT, MVT::Other);
  7736. FoldingSetNodeID ID;
  7737. AddNodeIDNode(ID, ISD::EXPERIMENTAL_VP_STRIDED_LOAD, VTs, Ops);
  7738. ID.AddInteger(VT.getRawBits());
  7739. ID.AddInteger(getSyntheticNodeSubclassData<VPStridedLoadSDNode>(
  7740. DL.getIROrder(), VTs, AM, ExtType, IsExpanding, MemVT, MMO));
  7741. ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
  7742. void *IP = nullptr;
  7743. if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
  7744. cast<VPStridedLoadSDNode>(E)->refineAlignment(MMO);
  7745. return SDValue(E, 0);
  7746. }
  7747. auto *N =
  7748. newSDNode<VPStridedLoadSDNode>(DL.getIROrder(), DL.getDebugLoc(), VTs, AM,
  7749. ExtType, IsExpanding, MemVT, MMO);
  7750. createOperands(N, Ops);
  7751. CSEMap.InsertNode(N, IP);
  7752. InsertNode(N);
  7753. SDValue V(N, 0);
  7754. NewSDValueDbgMsg(V, "Creating new node: ", this);
  7755. return V;
  7756. }
  7757. SDValue SelectionDAG::getStridedLoadVP(
  7758. EVT VT, const SDLoc &DL, SDValue Chain, SDValue Ptr, SDValue Stride,
  7759. SDValue Mask, SDValue EVL, MachinePointerInfo PtrInfo, MaybeAlign Alignment,
  7760. MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo,
  7761. const MDNode *Ranges, bool IsExpanding) {
  7762. SDValue Undef = getUNDEF(Ptr.getValueType());
  7763. return getStridedLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, DL, Chain, Ptr,
  7764. Undef, Stride, Mask, EVL, PtrInfo, VT, Alignment,
  7765. MMOFlags, AAInfo, Ranges, IsExpanding);
  7766. }
  7767. SDValue SelectionDAG::getStridedLoadVP(EVT VT, const SDLoc &DL, SDValue Chain,
  7768. SDValue Ptr, SDValue Stride,
  7769. SDValue Mask, SDValue EVL,
  7770. MachineMemOperand *MMO,
  7771. bool IsExpanding) {
  7772. SDValue Undef = getUNDEF(Ptr.getValueType());
  7773. return getStridedLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, DL, Chain, Ptr,
  7774. Undef, Stride, Mask, EVL, VT, MMO, IsExpanding);
  7775. }
  7776. SDValue SelectionDAG::getExtStridedLoadVP(
  7777. ISD::LoadExtType ExtType, const SDLoc &DL, EVT VT, SDValue Chain,
  7778. SDValue Ptr, SDValue Stride, SDValue Mask, SDValue EVL,
  7779. MachinePointerInfo PtrInfo, EVT MemVT, MaybeAlign Alignment,
  7780. MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo,
  7781. bool IsExpanding) {
  7782. SDValue Undef = getUNDEF(Ptr.getValueType());
  7783. return getStridedLoadVP(ISD::UNINDEXED, ExtType, VT, DL, Chain, Ptr, Undef,
  7784. Stride, Mask, EVL, PtrInfo, MemVT, Alignment,
  7785. MMOFlags, AAInfo, nullptr, IsExpanding);
  7786. }
  7787. SDValue SelectionDAG::getExtStridedLoadVP(
  7788. ISD::LoadExtType ExtType, const SDLoc &DL, EVT VT, SDValue Chain,
  7789. SDValue Ptr, SDValue Stride, SDValue Mask, SDValue EVL, EVT MemVT,
  7790. MachineMemOperand *MMO, bool IsExpanding) {
  7791. SDValue Undef = getUNDEF(Ptr.getValueType());
  7792. return getStridedLoadVP(ISD::UNINDEXED, ExtType, VT, DL, Chain, Ptr, Undef,
  7793. Stride, Mask, EVL, MemVT, MMO, IsExpanding);
  7794. }
  7795. SDValue SelectionDAG::getIndexedStridedLoadVP(SDValue OrigLoad, const SDLoc &DL,
  7796. SDValue Base, SDValue Offset,
  7797. ISD::MemIndexedMode AM) {
  7798. auto *SLD = cast<VPStridedLoadSDNode>(OrigLoad);
  7799. assert(SLD->getOffset().isUndef() &&
  7800. "Strided load is already a indexed load!");
  7801. // Don't propagate the invariant or dereferenceable flags.
  7802. auto MMOFlags =
  7803. SLD->getMemOperand()->getFlags() &
  7804. ~(MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable);
  7805. return getStridedLoadVP(
  7806. AM, SLD->getExtensionType(), OrigLoad.getValueType(), DL, SLD->getChain(),
  7807. Base, Offset, SLD->getStride(), SLD->getMask(), SLD->getVectorLength(),
  7808. SLD->getPointerInfo(), SLD->getMemoryVT(), SLD->getAlign(), MMOFlags,
  7809. SLD->getAAInfo(), nullptr, SLD->isExpandingLoad());
  7810. }
  7811. SDValue SelectionDAG::getStridedStoreVP(SDValue Chain, const SDLoc &DL,
  7812. SDValue Val, SDValue Ptr,
  7813. SDValue Offset, SDValue Stride,
  7814. SDValue Mask, SDValue EVL, EVT MemVT,
  7815. MachineMemOperand *MMO,
  7816. ISD::MemIndexedMode AM,
  7817. bool IsTruncating, bool IsCompressing) {
  7818. assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
  7819. bool Indexed = AM != ISD::UNINDEXED;
  7820. assert((Indexed || Offset.isUndef()) && "Unindexed vp_store with an offset!");
  7821. SDVTList VTs = Indexed ? getVTList(Ptr.getValueType(), MVT::Other)
  7822. : getVTList(MVT::Other);
  7823. SDValue Ops[] = {Chain, Val, Ptr, Offset, Stride, Mask, EVL};
  7824. FoldingSetNodeID ID;
  7825. AddNodeIDNode(ID, ISD::EXPERIMENTAL_VP_STRIDED_STORE, VTs, Ops);
  7826. ID.AddInteger(MemVT.getRawBits());
  7827. ID.AddInteger(getSyntheticNodeSubclassData<VPStridedStoreSDNode>(
  7828. DL.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO));
  7829. ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
  7830. void *IP = nullptr;
  7831. if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
  7832. cast<VPStridedStoreSDNode>(E)->refineAlignment(MMO);
  7833. return SDValue(E, 0);
  7834. }
  7835. auto *N = newSDNode<VPStridedStoreSDNode>(DL.getIROrder(), DL.getDebugLoc(),
  7836. VTs, AM, IsTruncating,
  7837. IsCompressing, MemVT, MMO);
  7838. createOperands(N, Ops);
  7839. CSEMap.InsertNode(N, IP);
  7840. InsertNode(N);
  7841. SDValue V(N, 0);
  7842. NewSDValueDbgMsg(V, "Creating new node: ", this);
  7843. return V;
  7844. }
  7845. SDValue SelectionDAG::getTruncStridedStoreVP(
  7846. SDValue Chain, const SDLoc &DL, SDValue Val, SDValue Ptr, SDValue Stride,
  7847. SDValue Mask, SDValue EVL, MachinePointerInfo PtrInfo, EVT SVT,
  7848. Align Alignment, MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo,
  7849. bool IsCompressing) {
  7850. assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
  7851. MMOFlags |= MachineMemOperand::MOStore;
  7852. assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
  7853. if (PtrInfo.V.isNull())
  7854. PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
  7855. MachineFunction &MF = getMachineFunction();
  7856. MachineMemOperand *MMO = MF.getMachineMemOperand(
  7857. PtrInfo, MMOFlags, MemoryLocation::UnknownSize, Alignment, AAInfo);
  7858. return getTruncStridedStoreVP(Chain, DL, Val, Ptr, Stride, Mask, EVL, SVT,
  7859. MMO, IsCompressing);
  7860. }
  7861. SDValue SelectionDAG::getTruncStridedStoreVP(SDValue Chain, const SDLoc &DL,
  7862. SDValue Val, SDValue Ptr,
  7863. SDValue Stride, SDValue Mask,
  7864. SDValue EVL, EVT SVT,
  7865. MachineMemOperand *MMO,
  7866. bool IsCompressing) {
  7867. EVT VT = Val.getValueType();
  7868. assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
  7869. if (VT == SVT)
  7870. return getStridedStoreVP(Chain, DL, Val, Ptr, getUNDEF(Ptr.getValueType()),
  7871. Stride, Mask, EVL, VT, MMO, ISD::UNINDEXED,
  7872. /*IsTruncating*/ false, IsCompressing);
  7873. assert(SVT.getScalarType().bitsLT(VT.getScalarType()) &&
  7874. "Should only be a truncating store, not extending!");
  7875. assert(VT.isInteger() == SVT.isInteger() && "Can't do FP-INT conversion!");
  7876. assert(VT.isVector() == SVT.isVector() &&
  7877. "Cannot use trunc store to convert to or from a vector!");
  7878. assert((!VT.isVector() ||
  7879. VT.getVectorElementCount() == SVT.getVectorElementCount()) &&
  7880. "Cannot use trunc store to change the number of vector elements!");
  7881. SDVTList VTs = getVTList(MVT::Other);
  7882. SDValue Undef = getUNDEF(Ptr.getValueType());
  7883. SDValue Ops[] = {Chain, Val, Ptr, Undef, Stride, Mask, EVL};
  7884. FoldingSetNodeID ID;
  7885. AddNodeIDNode(ID, ISD::EXPERIMENTAL_VP_STRIDED_STORE, VTs, Ops);
  7886. ID.AddInteger(SVT.getRawBits());
  7887. ID.AddInteger(getSyntheticNodeSubclassData<VPStridedStoreSDNode>(
  7888. DL.getIROrder(), VTs, ISD::UNINDEXED, true, IsCompressing, SVT, MMO));
  7889. ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
  7890. void *IP = nullptr;
  7891. if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
  7892. cast<VPStridedStoreSDNode>(E)->refineAlignment(MMO);
  7893. return SDValue(E, 0);
  7894. }
  7895. auto *N = newSDNode<VPStridedStoreSDNode>(DL.getIROrder(), DL.getDebugLoc(),
  7896. VTs, ISD::UNINDEXED, true,
  7897. IsCompressing, SVT, MMO);
  7898. createOperands(N, Ops);
  7899. CSEMap.InsertNode(N, IP);
  7900. InsertNode(N);
  7901. SDValue V(N, 0);
  7902. NewSDValueDbgMsg(V, "Creating new node: ", this);
  7903. return V;
  7904. }
  7905. SDValue SelectionDAG::getIndexedStridedStoreVP(SDValue OrigStore,
  7906. const SDLoc &DL, SDValue Base,
  7907. SDValue Offset,
  7908. ISD::MemIndexedMode AM) {
  7909. auto *SST = cast<VPStridedStoreSDNode>(OrigStore);
  7910. assert(SST->getOffset().isUndef() &&
  7911. "Strided store is already an indexed store!");
  7912. SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
  7913. SDValue Ops[] = {
  7914. SST->getChain(), SST->getValue(), Base, Offset, SST->getStride(),
  7915. SST->getMask(), SST->getVectorLength()};
  7916. FoldingSetNodeID ID;
  7917. AddNodeIDNode(ID, ISD::EXPERIMENTAL_VP_STRIDED_STORE, VTs, Ops);
  7918. ID.AddInteger(SST->getMemoryVT().getRawBits());
  7919. ID.AddInteger(SST->getRawSubclassData());
  7920. ID.AddInteger(SST->getPointerInfo().getAddrSpace());
  7921. void *IP = nullptr;
  7922. if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
  7923. return SDValue(E, 0);
  7924. auto *N = newSDNode<VPStridedStoreSDNode>(
  7925. DL.getIROrder(), DL.getDebugLoc(), VTs, AM, SST->isTruncatingStore(),
  7926. SST->isCompressingStore(), SST->getMemoryVT(), SST->getMemOperand());
  7927. createOperands(N, Ops);
  7928. CSEMap.InsertNode(N, IP);
  7929. InsertNode(N);
  7930. SDValue V(N, 0);
  7931. NewSDValueDbgMsg(V, "Creating new node: ", this);
  7932. return V;
  7933. }
  7934. SDValue SelectionDAG::getGatherVP(SDVTList VTs, EVT VT, const SDLoc &dl,
  7935. ArrayRef<SDValue> Ops, MachineMemOperand *MMO,
  7936. ISD::MemIndexType IndexType) {
  7937. assert(Ops.size() == 6 && "Incompatible number of operands");
  7938. FoldingSetNodeID ID;
  7939. AddNodeIDNode(ID, ISD::VP_GATHER, VTs, Ops);
  7940. ID.AddInteger(VT.getRawBits());
  7941. ID.AddInteger(getSyntheticNodeSubclassData<VPGatherSDNode>(
  7942. dl.getIROrder(), VTs, VT, MMO, IndexType));
  7943. ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
  7944. ID.AddInteger(MMO->getFlags());
  7945. void *IP = nullptr;
  7946. if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
  7947. cast<VPGatherSDNode>(E)->refineAlignment(MMO);
  7948. return SDValue(E, 0);
  7949. }
  7950. auto *N = newSDNode<VPGatherSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
  7951. VT, MMO, IndexType);
  7952. createOperands(N, Ops);
  7953. assert(N->getMask().getValueType().getVectorElementCount() ==
  7954. N->getValueType(0).getVectorElementCount() &&
  7955. "Vector width mismatch between mask and data");
  7956. assert(N->getIndex().getValueType().getVectorElementCount().isScalable() ==
  7957. N->getValueType(0).getVectorElementCount().isScalable() &&
  7958. "Scalable flags of index and data do not match");
  7959. assert(ElementCount::isKnownGE(
  7960. N->getIndex().getValueType().getVectorElementCount(),
  7961. N->getValueType(0).getVectorElementCount()) &&
  7962. "Vector width mismatch between index and data");
  7963. assert(isa<ConstantSDNode>(N->getScale()) &&
  7964. cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() &&
  7965. "Scale should be a constant power of 2");
  7966. CSEMap.InsertNode(N, IP);
  7967. InsertNode(N);
  7968. SDValue V(N, 0);
  7969. NewSDValueDbgMsg(V, "Creating new node: ", this);
  7970. return V;
  7971. }
  7972. SDValue SelectionDAG::getScatterVP(SDVTList VTs, EVT VT, const SDLoc &dl,
  7973. ArrayRef<SDValue> Ops,
  7974. MachineMemOperand *MMO,
  7975. ISD::MemIndexType IndexType) {
  7976. assert(Ops.size() == 7 && "Incompatible number of operands");
  7977. FoldingSetNodeID ID;
  7978. AddNodeIDNode(ID, ISD::VP_SCATTER, VTs, Ops);
  7979. ID.AddInteger(VT.getRawBits());
  7980. ID.AddInteger(getSyntheticNodeSubclassData<VPScatterSDNode>(
  7981. dl.getIROrder(), VTs, VT, MMO, IndexType));
  7982. ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
  7983. ID.AddInteger(MMO->getFlags());
  7984. void *IP = nullptr;
  7985. if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
  7986. cast<VPScatterSDNode>(E)->refineAlignment(MMO);
  7987. return SDValue(E, 0);
  7988. }
  7989. auto *N = newSDNode<VPScatterSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
  7990. VT, MMO, IndexType);
  7991. createOperands(N, Ops);
  7992. assert(N->getMask().getValueType().getVectorElementCount() ==
  7993. N->getValue().getValueType().getVectorElementCount() &&
  7994. "Vector width mismatch between mask and data");
  7995. assert(
  7996. N->getIndex().getValueType().getVectorElementCount().isScalable() ==
  7997. N->getValue().getValueType().getVectorElementCount().isScalable() &&
  7998. "Scalable flags of index and data do not match");
  7999. assert(ElementCount::isKnownGE(
  8000. N->getIndex().getValueType().getVectorElementCount(),
  8001. N->getValue().getValueType().getVectorElementCount()) &&
  8002. "Vector width mismatch between index and data");
  8003. assert(isa<ConstantSDNode>(N->getScale()) &&
  8004. cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() &&
  8005. "Scale should be a constant power of 2");
  8006. CSEMap.InsertNode(N, IP);
  8007. InsertNode(N);
  8008. SDValue V(N, 0);
  8009. NewSDValueDbgMsg(V, "Creating new node: ", this);
  8010. return V;
  8011. }
  8012. SDValue SelectionDAG::getMaskedLoad(EVT VT, const SDLoc &dl, SDValue Chain,
  8013. SDValue Base, SDValue Offset, SDValue Mask,
  8014. SDValue PassThru, EVT MemVT,
  8015. MachineMemOperand *MMO,
  8016. ISD::MemIndexedMode AM,
  8017. ISD::LoadExtType ExtTy, bool isExpanding) {
  8018. bool Indexed = AM != ISD::UNINDEXED;
  8019. assert((Indexed || Offset.isUndef()) &&
  8020. "Unindexed masked load with an offset!");
  8021. SDVTList VTs = Indexed ? getVTList(VT, Base.getValueType(), MVT::Other)
  8022. : getVTList(VT, MVT::Other);
  8023. SDValue Ops[] = {Chain, Base, Offset, Mask, PassThru};
  8024. FoldingSetNodeID ID;
  8025. AddNodeIDNode(ID, ISD::MLOAD, VTs, Ops);
  8026. ID.AddInteger(MemVT.getRawBits());
  8027. ID.AddInteger(getSyntheticNodeSubclassData<MaskedLoadSDNode>(
  8028. dl.getIROrder(), VTs, AM, ExtTy, isExpanding, MemVT, MMO));
  8029. ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
  8030. ID.AddInteger(MMO->getFlags());
  8031. void *IP = nullptr;
  8032. if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
  8033. cast<MaskedLoadSDNode>(E)->refineAlignment(MMO);
  8034. return SDValue(E, 0);
  8035. }
  8036. auto *N = newSDNode<MaskedLoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
  8037. AM, ExtTy, isExpanding, MemVT, MMO);
  8038. createOperands(N, Ops);
  8039. CSEMap.InsertNode(N, IP);
  8040. InsertNode(N);
  8041. SDValue V(N, 0);
  8042. NewSDValueDbgMsg(V, "Creating new node: ", this);
  8043. return V;
  8044. }
  8045. SDValue SelectionDAG::getIndexedMaskedLoad(SDValue OrigLoad, const SDLoc &dl,
  8046. SDValue Base, SDValue Offset,
  8047. ISD::MemIndexedMode AM) {
  8048. MaskedLoadSDNode *LD = cast<MaskedLoadSDNode>(OrigLoad);
  8049. assert(LD->getOffset().isUndef() && "Masked load is already a indexed load!");
  8050. return getMaskedLoad(OrigLoad.getValueType(), dl, LD->getChain(), Base,
  8051. Offset, LD->getMask(), LD->getPassThru(),
  8052. LD->getMemoryVT(), LD->getMemOperand(), AM,
  8053. LD->getExtensionType(), LD->isExpandingLoad());
  8054. }
  8055. SDValue SelectionDAG::getMaskedStore(SDValue Chain, const SDLoc &dl,
  8056. SDValue Val, SDValue Base, SDValue Offset,
  8057. SDValue Mask, EVT MemVT,
  8058. MachineMemOperand *MMO,
  8059. ISD::MemIndexedMode AM, bool IsTruncating,
  8060. bool IsCompressing) {
  8061. assert(Chain.getValueType() == MVT::Other &&
  8062. "Invalid chain type");
  8063. bool Indexed = AM != ISD::UNINDEXED;
  8064. assert((Indexed || Offset.isUndef()) &&
  8065. "Unindexed masked store with an offset!");
  8066. SDVTList VTs = Indexed ? getVTList(Base.getValueType(), MVT::Other)
  8067. : getVTList(MVT::Other);
  8068. SDValue Ops[] = {Chain, Val, Base, Offset, Mask};
  8069. FoldingSetNodeID ID;
  8070. AddNodeIDNode(ID, ISD::MSTORE, VTs, Ops);
  8071. ID.AddInteger(MemVT.getRawBits());
  8072. ID.AddInteger(getSyntheticNodeSubclassData<MaskedStoreSDNode>(
  8073. dl.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO));
  8074. ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
  8075. ID.AddInteger(MMO->getFlags());
  8076. void *IP = nullptr;
  8077. if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
  8078. cast<MaskedStoreSDNode>(E)->refineAlignment(MMO);
  8079. return SDValue(E, 0);
  8080. }
  8081. auto *N =
  8082. newSDNode<MaskedStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
  8083. IsTruncating, IsCompressing, MemVT, MMO);
  8084. createOperands(N, Ops);
  8085. CSEMap.InsertNode(N, IP);
  8086. InsertNode(N);
  8087. SDValue V(N, 0);
  8088. NewSDValueDbgMsg(V, "Creating new node: ", this);
  8089. return V;
  8090. }
  8091. SDValue SelectionDAG::getIndexedMaskedStore(SDValue OrigStore, const SDLoc &dl,
  8092. SDValue Base, SDValue Offset,
  8093. ISD::MemIndexedMode AM) {
  8094. MaskedStoreSDNode *ST = cast<MaskedStoreSDNode>(OrigStore);
  8095. assert(ST->getOffset().isUndef() &&
  8096. "Masked store is already a indexed store!");
  8097. return getMaskedStore(ST->getChain(), dl, ST->getValue(), Base, Offset,
  8098. ST->getMask(), ST->getMemoryVT(), ST->getMemOperand(),
  8099. AM, ST->isTruncatingStore(), ST->isCompressingStore());
  8100. }
  8101. SDValue SelectionDAG::getMaskedGather(SDVTList VTs, EVT MemVT, const SDLoc &dl,
  8102. ArrayRef<SDValue> Ops,
  8103. MachineMemOperand *MMO,
  8104. ISD::MemIndexType IndexType,
  8105. ISD::LoadExtType ExtTy) {
  8106. assert(Ops.size() == 6 && "Incompatible number of operands");
  8107. FoldingSetNodeID ID;
  8108. AddNodeIDNode(ID, ISD::MGATHER, VTs, Ops);
  8109. ID.AddInteger(MemVT.getRawBits());
  8110. ID.AddInteger(getSyntheticNodeSubclassData<MaskedGatherSDNode>(
  8111. dl.getIROrder(), VTs, MemVT, MMO, IndexType, ExtTy));
  8112. ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
  8113. ID.AddInteger(MMO->getFlags());
  8114. void *IP = nullptr;
  8115. if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
  8116. cast<MaskedGatherSDNode>(E)->refineAlignment(MMO);
  8117. return SDValue(E, 0);
  8118. }
  8119. auto *N = newSDNode<MaskedGatherSDNode>(dl.getIROrder(), dl.getDebugLoc(),
  8120. VTs, MemVT, MMO, IndexType, ExtTy);
  8121. createOperands(N, Ops);
  8122. assert(N->getPassThru().getValueType() == N->getValueType(0) &&
  8123. "Incompatible type of the PassThru value in MaskedGatherSDNode");
  8124. assert(N->getMask().getValueType().getVectorElementCount() ==
  8125. N->getValueType(0).getVectorElementCount() &&
  8126. "Vector width mismatch between mask and data");
  8127. assert(N->getIndex().getValueType().getVectorElementCount().isScalable() ==
  8128. N->getValueType(0).getVectorElementCount().isScalable() &&
  8129. "Scalable flags of index and data do not match");
  8130. assert(ElementCount::isKnownGE(
  8131. N->getIndex().getValueType().getVectorElementCount(),
  8132. N->getValueType(0).getVectorElementCount()) &&
  8133. "Vector width mismatch between index and data");
  8134. assert(isa<ConstantSDNode>(N->getScale()) &&
  8135. cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() &&
  8136. "Scale should be a constant power of 2");
  8137. CSEMap.InsertNode(N, IP);
  8138. InsertNode(N);
  8139. SDValue V(N, 0);
  8140. NewSDValueDbgMsg(V, "Creating new node: ", this);
  8141. return V;
  8142. }
  8143. SDValue SelectionDAG::getMaskedScatter(SDVTList VTs, EVT MemVT, const SDLoc &dl,
  8144. ArrayRef<SDValue> Ops,
  8145. MachineMemOperand *MMO,
  8146. ISD::MemIndexType IndexType,
  8147. bool IsTrunc) {
  8148. assert(Ops.size() == 6 && "Incompatible number of operands");
  8149. FoldingSetNodeID ID;
  8150. AddNodeIDNode(ID, ISD::MSCATTER, VTs, Ops);
  8151. ID.AddInteger(MemVT.getRawBits());
  8152. ID.AddInteger(getSyntheticNodeSubclassData<MaskedScatterSDNode>(
  8153. dl.getIROrder(), VTs, MemVT, MMO, IndexType, IsTrunc));
  8154. ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
  8155. ID.AddInteger(MMO->getFlags());
  8156. void *IP = nullptr;
  8157. if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
  8158. cast<MaskedScatterSDNode>(E)->refineAlignment(MMO);
  8159. return SDValue(E, 0);
  8160. }
  8161. auto *N = newSDNode<MaskedScatterSDNode>(dl.getIROrder(), dl.getDebugLoc(),
  8162. VTs, MemVT, MMO, IndexType, IsTrunc);
  8163. createOperands(N, Ops);
  8164. assert(N->getMask().getValueType().getVectorElementCount() ==
  8165. N->getValue().getValueType().getVectorElementCount() &&
  8166. "Vector width mismatch between mask and data");
  8167. assert(
  8168. N->getIndex().getValueType().getVectorElementCount().isScalable() ==
  8169. N->getValue().getValueType().getVectorElementCount().isScalable() &&
  8170. "Scalable flags of index and data do not match");
  8171. assert(ElementCount::isKnownGE(
  8172. N->getIndex().getValueType().getVectorElementCount(),
  8173. N->getValue().getValueType().getVectorElementCount()) &&
  8174. "Vector width mismatch between index and data");
  8175. assert(isa<ConstantSDNode>(N->getScale()) &&
  8176. cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() &&
  8177. "Scale should be a constant power of 2");
  8178. CSEMap.InsertNode(N, IP);
  8179. InsertNode(N);
  8180. SDValue V(N, 0);
  8181. NewSDValueDbgMsg(V, "Creating new node: ", this);
  8182. return V;
  8183. }
  8184. SDValue SelectionDAG::simplifySelect(SDValue Cond, SDValue T, SDValue F) {
  8185. // select undef, T, F --> T (if T is a constant), otherwise F
  8186. // select, ?, undef, F --> F
  8187. // select, ?, T, undef --> T
  8188. if (Cond.isUndef())
  8189. return isConstantValueOfAnyType(T) ? T : F;
  8190. if (T.isUndef())
  8191. return F;
  8192. if (F.isUndef())
  8193. return T;
  8194. // select true, T, F --> T
  8195. // select false, T, F --> F
  8196. if (auto *CondC = dyn_cast<ConstantSDNode>(Cond))
  8197. return CondC->isZero() ? F : T;
  8198. // TODO: This should simplify VSELECT with non-zero constant condition using
  8199. // something like this (but check boolean contents to be complete?):
  8200. if (ConstantSDNode *CondC = isConstOrConstSplat(Cond, /*AllowUndefs*/ false,
  8201. /*AllowTruncation*/ true))
  8202. if (CondC->isZero())
  8203. return F;
  8204. // select ?, T, T --> T
  8205. if (T == F)
  8206. return T;
  8207. return SDValue();
  8208. }
  8209. SDValue SelectionDAG::simplifyShift(SDValue X, SDValue Y) {
  8210. // shift undef, Y --> 0 (can always assume that the undef value is 0)
  8211. if (X.isUndef())
  8212. return getConstant(0, SDLoc(X.getNode()), X.getValueType());
  8213. // shift X, undef --> undef (because it may shift by the bitwidth)
  8214. if (Y.isUndef())
  8215. return getUNDEF(X.getValueType());
  8216. // shift 0, Y --> 0
  8217. // shift X, 0 --> X
  8218. if (isNullOrNullSplat(X) || isNullOrNullSplat(Y))
  8219. return X;
  8220. // shift X, C >= bitwidth(X) --> undef
  8221. // All vector elements must be too big (or undef) to avoid partial undefs.
  8222. auto isShiftTooBig = [X](ConstantSDNode *Val) {
  8223. return !Val || Val->getAPIntValue().uge(X.getScalarValueSizeInBits());
  8224. };
  8225. if (ISD::matchUnaryPredicate(Y, isShiftTooBig, true))
  8226. return getUNDEF(X.getValueType());
  8227. return SDValue();
  8228. }
  8229. SDValue SelectionDAG::simplifyFPBinop(unsigned Opcode, SDValue X, SDValue Y,
  8230. SDNodeFlags Flags) {
  8231. // If this operation has 'nnan' or 'ninf' and at least 1 disallowed operand
  8232. // (an undef operand can be chosen to be Nan/Inf), then the result of this
  8233. // operation is poison. That result can be relaxed to undef.
  8234. ConstantFPSDNode *XC = isConstOrConstSplatFP(X, /* AllowUndefs */ true);
  8235. ConstantFPSDNode *YC = isConstOrConstSplatFP(Y, /* AllowUndefs */ true);
  8236. bool HasNan = (XC && XC->getValueAPF().isNaN()) ||
  8237. (YC && YC->getValueAPF().isNaN());
  8238. bool HasInf = (XC && XC->getValueAPF().isInfinity()) ||
  8239. (YC && YC->getValueAPF().isInfinity());
  8240. if (Flags.hasNoNaNs() && (HasNan || X.isUndef() || Y.isUndef()))
  8241. return getUNDEF(X.getValueType());
  8242. if (Flags.hasNoInfs() && (HasInf || X.isUndef() || Y.isUndef()))
  8243. return getUNDEF(X.getValueType());
  8244. if (!YC)
  8245. return SDValue();
  8246. // X + -0.0 --> X
  8247. if (Opcode == ISD::FADD)
  8248. if (YC->getValueAPF().isNegZero())
  8249. return X;
  8250. // X - +0.0 --> X
  8251. if (Opcode == ISD::FSUB)
  8252. if (YC->getValueAPF().isPosZero())
  8253. return X;
  8254. // X * 1.0 --> X
  8255. // X / 1.0 --> X
  8256. if (Opcode == ISD::FMUL || Opcode == ISD::FDIV)
  8257. if (YC->getValueAPF().isExactlyValue(1.0))
  8258. return X;
  8259. // X * 0.0 --> 0.0
  8260. if (Opcode == ISD::FMUL && Flags.hasNoNaNs() && Flags.hasNoSignedZeros())
  8261. if (YC->getValueAPF().isZero())
  8262. return getConstantFP(0.0, SDLoc(Y), Y.getValueType());
  8263. return SDValue();
  8264. }
  8265. SDValue SelectionDAG::getVAArg(EVT VT, const SDLoc &dl, SDValue Chain,
  8266. SDValue Ptr, SDValue SV, unsigned Align) {
  8267. SDValue Ops[] = { Chain, Ptr, SV, getTargetConstant(Align, dl, MVT::i32) };
  8268. return getNode(ISD::VAARG, dl, getVTList(VT, MVT::Other), Ops);
  8269. }
  8270. SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
  8271. ArrayRef<SDUse> Ops) {
  8272. switch (Ops.size()) {
  8273. case 0: return getNode(Opcode, DL, VT);
  8274. case 1: return getNode(Opcode, DL, VT, static_cast<const SDValue>(Ops[0]));
  8275. case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1]);
  8276. case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]);
  8277. default: break;
  8278. }
  8279. // Copy from an SDUse array into an SDValue array for use with
  8280. // the regular getNode logic.
  8281. SmallVector<SDValue, 8> NewOps(Ops.begin(), Ops.end());
  8282. return getNode(Opcode, DL, VT, NewOps);
  8283. }
  8284. SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
  8285. ArrayRef<SDValue> Ops) {
  8286. SDNodeFlags Flags;
  8287. if (Inserter)
  8288. Flags = Inserter->getFlags();
  8289. return getNode(Opcode, DL, VT, Ops, Flags);
  8290. }
  8291. SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
  8292. ArrayRef<SDValue> Ops, const SDNodeFlags Flags) {
  8293. unsigned NumOps = Ops.size();
  8294. switch (NumOps) {
  8295. case 0: return getNode(Opcode, DL, VT);
  8296. case 1: return getNode(Opcode, DL, VT, Ops[0], Flags);
  8297. case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Flags);
  8298. case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2], Flags);
  8299. default: break;
  8300. }
  8301. #ifndef NDEBUG
  8302. for (const auto &Op : Ops)
  8303. assert(Op.getOpcode() != ISD::DELETED_NODE &&
  8304. "Operand is DELETED_NODE!");
  8305. #endif
  8306. switch (Opcode) {
  8307. default: break;
  8308. case ISD::BUILD_VECTOR:
  8309. // Attempt to simplify BUILD_VECTOR.
  8310. if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
  8311. return V;
  8312. break;
  8313. case ISD::CONCAT_VECTORS:
  8314. if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
  8315. return V;
  8316. break;
  8317. case ISD::SELECT_CC:
  8318. assert(NumOps == 5 && "SELECT_CC takes 5 operands!");
  8319. assert(Ops[0].getValueType() == Ops[1].getValueType() &&
  8320. "LHS and RHS of condition must have same type!");
  8321. assert(Ops[2].getValueType() == Ops[3].getValueType() &&
  8322. "True and False arms of SelectCC must have same type!");
  8323. assert(Ops[2].getValueType() == VT &&
  8324. "select_cc node must be of same type as true and false value!");
  8325. assert((!Ops[0].getValueType().isVector() ||
  8326. Ops[0].getValueType().getVectorElementCount() ==
  8327. VT.getVectorElementCount()) &&
  8328. "Expected select_cc with vector result to have the same sized "
  8329. "comparison type!");
  8330. break;
  8331. case ISD::BR_CC:
  8332. assert(NumOps == 5 && "BR_CC takes 5 operands!");
  8333. assert(Ops[2].getValueType() == Ops[3].getValueType() &&
  8334. "LHS/RHS of comparison should match types!");
  8335. break;
  8336. case ISD::VP_ADD:
  8337. case ISD::VP_SUB:
  8338. // If it is VP_ADD/VP_SUB mask operation then turn it to VP_XOR
  8339. if (VT.isVector() && VT.getVectorElementType() == MVT::i1)
  8340. Opcode = ISD::VP_XOR;
  8341. break;
  8342. case ISD::VP_MUL:
  8343. // If it is VP_MUL mask operation then turn it to VP_AND
  8344. if (VT.isVector() && VT.getVectorElementType() == MVT::i1)
  8345. Opcode = ISD::VP_AND;
  8346. break;
  8347. case ISD::VP_REDUCE_MUL:
  8348. // If it is VP_REDUCE_MUL mask operation then turn it to VP_REDUCE_AND
  8349. if (VT == MVT::i1)
  8350. Opcode = ISD::VP_REDUCE_AND;
  8351. break;
  8352. case ISD::VP_REDUCE_ADD:
  8353. // If it is VP_REDUCE_ADD mask operation then turn it to VP_REDUCE_XOR
  8354. if (VT == MVT::i1)
  8355. Opcode = ISD::VP_REDUCE_XOR;
  8356. break;
  8357. case ISD::VP_REDUCE_SMAX:
  8358. case ISD::VP_REDUCE_UMIN:
  8359. // If it is VP_REDUCE_SMAX/VP_REDUCE_UMIN mask operation then turn it to
  8360. // VP_REDUCE_AND.
  8361. if (VT == MVT::i1)
  8362. Opcode = ISD::VP_REDUCE_AND;
  8363. break;
  8364. case ISD::VP_REDUCE_SMIN:
  8365. case ISD::VP_REDUCE_UMAX:
  8366. // If it is VP_REDUCE_SMIN/VP_REDUCE_UMAX mask operation then turn it to
  8367. // VP_REDUCE_OR.
  8368. if (VT == MVT::i1)
  8369. Opcode = ISD::VP_REDUCE_OR;
  8370. break;
  8371. }
  8372. // Memoize nodes.
  8373. SDNode *N;
  8374. SDVTList VTs = getVTList(VT);
  8375. if (VT != MVT::Glue) {
  8376. FoldingSetNodeID ID;
  8377. AddNodeIDNode(ID, Opcode, VTs, Ops);
  8378. void *IP = nullptr;
  8379. if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
  8380. return SDValue(E, 0);
  8381. N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
  8382. createOperands(N, Ops);
  8383. CSEMap.InsertNode(N, IP);
  8384. } else {
  8385. N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
  8386. createOperands(N, Ops);
  8387. }
  8388. N->setFlags(Flags);
  8389. InsertNode(N);
  8390. SDValue V(N, 0);
  8391. NewSDValueDbgMsg(V, "Creating new node: ", this);
  8392. return V;
  8393. }
  8394. SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL,
  8395. ArrayRef<EVT> ResultTys, ArrayRef<SDValue> Ops) {
  8396. return getNode(Opcode, DL, getVTList(ResultTys), Ops);
  8397. }
  8398. SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
  8399. ArrayRef<SDValue> Ops) {
  8400. SDNodeFlags Flags;
  8401. if (Inserter)
  8402. Flags = Inserter->getFlags();
  8403. return getNode(Opcode, DL, VTList, Ops, Flags);
  8404. }
  8405. SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
  8406. ArrayRef<SDValue> Ops, const SDNodeFlags Flags) {
  8407. if (VTList.NumVTs == 1)
  8408. return getNode(Opcode, DL, VTList.VTs[0], Ops, Flags);
  8409. #ifndef NDEBUG
  8410. for (const auto &Op : Ops)
  8411. assert(Op.getOpcode() != ISD::DELETED_NODE &&
  8412. "Operand is DELETED_NODE!");
  8413. #endif
  8414. switch (Opcode) {
  8415. case ISD::SADDO:
  8416. case ISD::UADDO:
  8417. case ISD::SSUBO:
  8418. case ISD::USUBO: {
  8419. assert(VTList.NumVTs == 2 && Ops.size() == 2 &&
  8420. "Invalid add/sub overflow op!");
  8421. assert(VTList.VTs[0].isInteger() && VTList.VTs[1].isInteger() &&
  8422. Ops[0].getValueType() == Ops[1].getValueType() &&
  8423. Ops[0].getValueType() == VTList.VTs[0] &&
  8424. "Binary operator types must match!");
  8425. SDValue N1 = Ops[0], N2 = Ops[1];
  8426. canonicalizeCommutativeBinop(Opcode, N1, N2);
  8427. // (X +- 0) -> X with zero-overflow.
  8428. ConstantSDNode *N2CV = isConstOrConstSplat(N2, /*AllowUndefs*/ false,
  8429. /*AllowTruncation*/ true);
  8430. if (N2CV && N2CV->isZero()) {
  8431. SDValue ZeroOverFlow = getConstant(0, DL, VTList.VTs[1]);
  8432. return getNode(ISD::MERGE_VALUES, DL, VTList, {N1, ZeroOverFlow}, Flags);
  8433. }
  8434. break;
  8435. }
  8436. case ISD::SMUL_LOHI:
  8437. case ISD::UMUL_LOHI: {
  8438. assert(VTList.NumVTs == 2 && Ops.size() == 2 && "Invalid mul lo/hi op!");
  8439. assert(VTList.VTs[0].isInteger() && VTList.VTs[0] == VTList.VTs[1] &&
  8440. VTList.VTs[0] == Ops[0].getValueType() &&
  8441. VTList.VTs[0] == Ops[1].getValueType() &&
  8442. "Binary operator types must match!");
  8443. break;
  8444. }
  8445. case ISD::STRICT_FP_EXTEND:
  8446. assert(VTList.NumVTs == 2 && Ops.size() == 2 &&
  8447. "Invalid STRICT_FP_EXTEND!");
  8448. assert(VTList.VTs[0].isFloatingPoint() &&
  8449. Ops[1].getValueType().isFloatingPoint() && "Invalid FP cast!");
  8450. assert(VTList.VTs[0].isVector() == Ops[1].getValueType().isVector() &&
  8451. "STRICT_FP_EXTEND result type should be vector iff the operand "
  8452. "type is vector!");
  8453. assert((!VTList.VTs[0].isVector() ||
  8454. VTList.VTs[0].getVectorNumElements() ==
  8455. Ops[1].getValueType().getVectorNumElements()) &&
  8456. "Vector element count mismatch!");
  8457. assert(Ops[1].getValueType().bitsLT(VTList.VTs[0]) &&
  8458. "Invalid fpext node, dst <= src!");
  8459. break;
  8460. case ISD::STRICT_FP_ROUND:
  8461. assert(VTList.NumVTs == 2 && Ops.size() == 3 && "Invalid STRICT_FP_ROUND!");
  8462. assert(VTList.VTs[0].isVector() == Ops[1].getValueType().isVector() &&
  8463. "STRICT_FP_ROUND result type should be vector iff the operand "
  8464. "type is vector!");
  8465. assert((!VTList.VTs[0].isVector() ||
  8466. VTList.VTs[0].getVectorNumElements() ==
  8467. Ops[1].getValueType().getVectorNumElements()) &&
  8468. "Vector element count mismatch!");
  8469. assert(VTList.VTs[0].isFloatingPoint() &&
  8470. Ops[1].getValueType().isFloatingPoint() &&
  8471. VTList.VTs[0].bitsLT(Ops[1].getValueType()) &&
  8472. isa<ConstantSDNode>(Ops[2]) &&
  8473. (cast<ConstantSDNode>(Ops[2])->getZExtValue() == 0 ||
  8474. cast<ConstantSDNode>(Ops[2])->getZExtValue() == 1) &&
  8475. "Invalid STRICT_FP_ROUND!");
  8476. break;
  8477. #if 0
  8478. // FIXME: figure out how to safely handle things like
  8479. // int foo(int x) { return 1 << (x & 255); }
  8480. // int bar() { return foo(256); }
  8481. case ISD::SRA_PARTS:
  8482. case ISD::SRL_PARTS:
  8483. case ISD::SHL_PARTS:
  8484. if (N3.getOpcode() == ISD::SIGN_EXTEND_INREG &&
  8485. cast<VTSDNode>(N3.getOperand(1))->getVT() != MVT::i1)
  8486. return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0));
  8487. else if (N3.getOpcode() == ISD::AND)
  8488. if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N3.getOperand(1))) {
  8489. // If the and is only masking out bits that cannot effect the shift,
  8490. // eliminate the and.
  8491. unsigned NumBits = VT.getScalarSizeInBits()*2;
  8492. if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1)
  8493. return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0));
  8494. }
  8495. break;
  8496. #endif
  8497. }
  8498. // Memoize the node unless it returns a flag.
  8499. SDNode *N;
  8500. if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
  8501. FoldingSetNodeID ID;
  8502. AddNodeIDNode(ID, Opcode, VTList, Ops);
  8503. void *IP = nullptr;
  8504. if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
  8505. return SDValue(E, 0);
  8506. N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList);
  8507. createOperands(N, Ops);
  8508. CSEMap.InsertNode(N, IP);
  8509. } else {
  8510. N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList);
  8511. createOperands(N, Ops);
  8512. }
  8513. N->setFlags(Flags);
  8514. InsertNode(N);
  8515. SDValue V(N, 0);
  8516. NewSDValueDbgMsg(V, "Creating new node: ", this);
  8517. return V;
  8518. }
  8519. SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL,
  8520. SDVTList VTList) {
  8521. return getNode(Opcode, DL, VTList, std::nullopt);
  8522. }
  8523. SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
  8524. SDValue N1) {
  8525. SDValue Ops[] = { N1 };
  8526. return getNode(Opcode, DL, VTList, Ops);
  8527. }
  8528. SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
  8529. SDValue N1, SDValue N2) {
  8530. SDValue Ops[] = { N1, N2 };
  8531. return getNode(Opcode, DL, VTList, Ops);
  8532. }
  8533. SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
  8534. SDValue N1, SDValue N2, SDValue N3) {
  8535. SDValue Ops[] = { N1, N2, N3 };
  8536. return getNode(Opcode, DL, VTList, Ops);
  8537. }
  8538. SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
  8539. SDValue N1, SDValue N2, SDValue N3, SDValue N4) {
  8540. SDValue Ops[] = { N1, N2, N3, N4 };
  8541. return getNode(Opcode, DL, VTList, Ops);
  8542. }
  8543. SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
  8544. SDValue N1, SDValue N2, SDValue N3, SDValue N4,
  8545. SDValue N5) {
  8546. SDValue Ops[] = { N1, N2, N3, N4, N5 };
  8547. return getNode(Opcode, DL, VTList, Ops);
  8548. }
  8549. SDVTList SelectionDAG::getVTList(EVT VT) {
  8550. return makeVTList(SDNode::getValueTypeList(VT), 1);
  8551. }
  8552. SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2) {
  8553. FoldingSetNodeID ID;
  8554. ID.AddInteger(2U);
  8555. ID.AddInteger(VT1.getRawBits());
  8556. ID.AddInteger(VT2.getRawBits());
  8557. void *IP = nullptr;
  8558. SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
  8559. if (!Result) {
  8560. EVT *Array = Allocator.Allocate<EVT>(2);
  8561. Array[0] = VT1;
  8562. Array[1] = VT2;
  8563. Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 2);
  8564. VTListMap.InsertNode(Result, IP);
  8565. }
  8566. return Result->getSDVTList();
  8567. }
  8568. SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3) {
  8569. FoldingSetNodeID ID;
  8570. ID.AddInteger(3U);
  8571. ID.AddInteger(VT1.getRawBits());
  8572. ID.AddInteger(VT2.getRawBits());
  8573. ID.AddInteger(VT3.getRawBits());
  8574. void *IP = nullptr;
  8575. SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
  8576. if (!Result) {
  8577. EVT *Array = Allocator.Allocate<EVT>(3);
  8578. Array[0] = VT1;
  8579. Array[1] = VT2;
  8580. Array[2] = VT3;
  8581. Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 3);
  8582. VTListMap.InsertNode(Result, IP);
  8583. }
  8584. return Result->getSDVTList();
  8585. }
  8586. SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3, EVT VT4) {
  8587. FoldingSetNodeID ID;
  8588. ID.AddInteger(4U);
  8589. ID.AddInteger(VT1.getRawBits());
  8590. ID.AddInteger(VT2.getRawBits());
  8591. ID.AddInteger(VT3.getRawBits());
  8592. ID.AddInteger(VT4.getRawBits());
  8593. void *IP = nullptr;
  8594. SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
  8595. if (!Result) {
  8596. EVT *Array = Allocator.Allocate<EVT>(4);
  8597. Array[0] = VT1;
  8598. Array[1] = VT2;
  8599. Array[2] = VT3;
  8600. Array[3] = VT4;
  8601. Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 4);
  8602. VTListMap.InsertNode(Result, IP);
  8603. }
  8604. return Result->getSDVTList();
  8605. }
  8606. SDVTList SelectionDAG::getVTList(ArrayRef<EVT> VTs) {
  8607. unsigned NumVTs = VTs.size();
  8608. FoldingSetNodeID ID;
  8609. ID.AddInteger(NumVTs);
  8610. for (unsigned index = 0; index < NumVTs; index++) {
  8611. ID.AddInteger(VTs[index].getRawBits());
  8612. }
  8613. void *IP = nullptr;
  8614. SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
  8615. if (!Result) {
  8616. EVT *Array = Allocator.Allocate<EVT>(NumVTs);
  8617. llvm::copy(VTs, Array);
  8618. Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, NumVTs);
  8619. VTListMap.InsertNode(Result, IP);
  8620. }
  8621. return Result->getSDVTList();
  8622. }
  8623. /// UpdateNodeOperands - *Mutate* the specified node in-place to have the
  8624. /// specified operands. If the resultant node already exists in the DAG,
  8625. /// this does not modify the specified node, instead it returns the node that
  8626. /// already exists. If the resultant node does not exist in the DAG, the
  8627. /// input node is returned. As a degenerate case, if you specify the same
  8628. /// input operands as the node already has, the input node is returned.
  8629. SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op) {
  8630. assert(N->getNumOperands() == 1 && "Update with wrong number of operands");
  8631. // Check to see if there is no change.
  8632. if (Op == N->getOperand(0)) return N;
  8633. // See if the modified node already exists.
  8634. void *InsertPos = nullptr;
  8635. if (SDNode *Existing = FindModifiedNodeSlot(N, Op, InsertPos))
  8636. return Existing;
  8637. // Nope it doesn't. Remove the node from its current place in the maps.
  8638. if (InsertPos)
  8639. if (!RemoveNodeFromCSEMaps(N))
  8640. InsertPos = nullptr;
  8641. // Now we update the operands.
  8642. N->OperandList[0].set(Op);
  8643. updateDivergence(N);
  8644. // If this gets put into a CSE map, add it.
  8645. if (InsertPos) CSEMap.InsertNode(N, InsertPos);
  8646. return N;
  8647. }
  8648. SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2) {
  8649. assert(N->getNumOperands() == 2 && "Update with wrong number of operands");
  8650. // Check to see if there is no change.
  8651. if (Op1 == N->getOperand(0) && Op2 == N->getOperand(1))
  8652. return N; // No operands changed, just return the input node.
  8653. // See if the modified node already exists.
  8654. void *InsertPos = nullptr;
  8655. if (SDNode *Existing = FindModifiedNodeSlot(N, Op1, Op2, InsertPos))
  8656. return Existing;
  8657. // Nope it doesn't. Remove the node from its current place in the maps.
  8658. if (InsertPos)
  8659. if (!RemoveNodeFromCSEMaps(N))
  8660. InsertPos = nullptr;
  8661. // Now we update the operands.
  8662. if (N->OperandList[0] != Op1)
  8663. N->OperandList[0].set(Op1);
  8664. if (N->OperandList[1] != Op2)
  8665. N->OperandList[1].set(Op2);
  8666. updateDivergence(N);
  8667. // If this gets put into a CSE map, add it.
  8668. if (InsertPos) CSEMap.InsertNode(N, InsertPos);
  8669. return N;
  8670. }
  8671. SDNode *SelectionDAG::
  8672. UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2, SDValue Op3) {
  8673. SDValue Ops[] = { Op1, Op2, Op3 };
  8674. return UpdateNodeOperands(N, Ops);
  8675. }
  8676. SDNode *SelectionDAG::
  8677. UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2,
  8678. SDValue Op3, SDValue Op4) {
  8679. SDValue Ops[] = { Op1, Op2, Op3, Op4 };
  8680. return UpdateNodeOperands(N, Ops);
  8681. }
  8682. SDNode *SelectionDAG::
  8683. UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2,
  8684. SDValue Op3, SDValue Op4, SDValue Op5) {
  8685. SDValue Ops[] = { Op1, Op2, Op3, Op4, Op5 };
  8686. return UpdateNodeOperands(N, Ops);
  8687. }
  8688. SDNode *SelectionDAG::
  8689. UpdateNodeOperands(SDNode *N, ArrayRef<SDValue> Ops) {
  8690. unsigned NumOps = Ops.size();
  8691. assert(N->getNumOperands() == NumOps &&
  8692. "Update with wrong number of operands");
  8693. // If no operands changed just return the input node.
  8694. if (std::equal(Ops.begin(), Ops.end(), N->op_begin()))
  8695. return N;
  8696. // See if the modified node already exists.
  8697. void *InsertPos = nullptr;
  8698. if (SDNode *Existing = FindModifiedNodeSlot(N, Ops, InsertPos))
  8699. return Existing;
  8700. // Nope it doesn't. Remove the node from its current place in the maps.
  8701. if (InsertPos)
  8702. if (!RemoveNodeFromCSEMaps(N))
  8703. InsertPos = nullptr;
  8704. // Now we update the operands.
  8705. for (unsigned i = 0; i != NumOps; ++i)
  8706. if (N->OperandList[i] != Ops[i])
  8707. N->OperandList[i].set(Ops[i]);
  8708. updateDivergence(N);
  8709. // If this gets put into a CSE map, add it.
  8710. if (InsertPos) CSEMap.InsertNode(N, InsertPos);
  8711. return N;
  8712. }
  8713. /// DropOperands - Release the operands and set this node to have
  8714. /// zero operands.
  8715. void SDNode::DropOperands() {
  8716. // Unlike the code in MorphNodeTo that does this, we don't need to
  8717. // watch for dead nodes here.
  8718. for (op_iterator I = op_begin(), E = op_end(); I != E; ) {
  8719. SDUse &Use = *I++;
  8720. Use.set(SDValue());
  8721. }
  8722. }
  8723. void SelectionDAG::setNodeMemRefs(MachineSDNode *N,
  8724. ArrayRef<MachineMemOperand *> NewMemRefs) {
  8725. if (NewMemRefs.empty()) {
  8726. N->clearMemRefs();
  8727. return;
  8728. }
  8729. // Check if we can avoid allocating by storing a single reference directly.
  8730. if (NewMemRefs.size() == 1) {
  8731. N->MemRefs = NewMemRefs[0];
  8732. N->NumMemRefs = 1;
  8733. return;
  8734. }
  8735. MachineMemOperand **MemRefsBuffer =
  8736. Allocator.template Allocate<MachineMemOperand *>(NewMemRefs.size());
  8737. llvm::copy(NewMemRefs, MemRefsBuffer);
  8738. N->MemRefs = MemRefsBuffer;
  8739. N->NumMemRefs = static_cast<int>(NewMemRefs.size());
  8740. }
  8741. /// SelectNodeTo - These are wrappers around MorphNodeTo that accept a
  8742. /// machine opcode.
  8743. ///
  8744. SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
  8745. EVT VT) {
  8746. SDVTList VTs = getVTList(VT);
  8747. return SelectNodeTo(N, MachineOpc, VTs, std::nullopt);
  8748. }
  8749. SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
  8750. EVT VT, SDValue Op1) {
  8751. SDVTList VTs = getVTList(VT);
  8752. SDValue Ops[] = { Op1 };
  8753. return SelectNodeTo(N, MachineOpc, VTs, Ops);
  8754. }
  8755. SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
  8756. EVT VT, SDValue Op1,
  8757. SDValue Op2) {
  8758. SDVTList VTs = getVTList(VT);
  8759. SDValue Ops[] = { Op1, Op2 };
  8760. return SelectNodeTo(N, MachineOpc, VTs, Ops);
  8761. }
  8762. SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
  8763. EVT VT, SDValue Op1,
  8764. SDValue Op2, SDValue Op3) {
  8765. SDVTList VTs = getVTList(VT);
  8766. SDValue Ops[] = { Op1, Op2, Op3 };
  8767. return SelectNodeTo(N, MachineOpc, VTs, Ops);
  8768. }
  8769. SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
  8770. EVT VT, ArrayRef<SDValue> Ops) {
  8771. SDVTList VTs = getVTList(VT);
  8772. return SelectNodeTo(N, MachineOpc, VTs, Ops);
  8773. }
  8774. SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
  8775. EVT VT1, EVT VT2, ArrayRef<SDValue> Ops) {
  8776. SDVTList VTs = getVTList(VT1, VT2);
  8777. return SelectNodeTo(N, MachineOpc, VTs, Ops);
  8778. }
  8779. SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
  8780. EVT VT1, EVT VT2) {
  8781. SDVTList VTs = getVTList(VT1, VT2);
  8782. return SelectNodeTo(N, MachineOpc, VTs, std::nullopt);
  8783. }
  8784. SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
  8785. EVT VT1, EVT VT2, EVT VT3,
  8786. ArrayRef<SDValue> Ops) {
  8787. SDVTList VTs = getVTList(VT1, VT2, VT3);
  8788. return SelectNodeTo(N, MachineOpc, VTs, Ops);
  8789. }
  8790. SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
  8791. EVT VT1, EVT VT2,
  8792. SDValue Op1, SDValue Op2) {
  8793. SDVTList VTs = getVTList(VT1, VT2);
  8794. SDValue Ops[] = { Op1, Op2 };
  8795. return SelectNodeTo(N, MachineOpc, VTs, Ops);
  8796. }
  8797. SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
  8798. SDVTList VTs,ArrayRef<SDValue> Ops) {
  8799. SDNode *New = MorphNodeTo(N, ~MachineOpc, VTs, Ops);
  8800. // Reset the NodeID to -1.
  8801. New->setNodeId(-1);
  8802. if (New != N) {
  8803. ReplaceAllUsesWith(N, New);
  8804. RemoveDeadNode(N);
  8805. }
  8806. return New;
  8807. }
  8808. /// UpdateSDLocOnMergeSDNode - If the opt level is -O0 then it throws away
  8809. /// the line number information on the merged node since it is not possible to
  8810. /// preserve the information that operation is associated with multiple lines.
  8811. /// This will make the debugger working better at -O0, were there is a higher
  8812. /// probability having other instructions associated with that line.
  8813. ///
  8814. /// For IROrder, we keep the smaller of the two
  8815. SDNode *SelectionDAG::UpdateSDLocOnMergeSDNode(SDNode *N, const SDLoc &OLoc) {
  8816. DebugLoc NLoc = N->getDebugLoc();
  8817. if (NLoc && OptLevel == CodeGenOpt::None && OLoc.getDebugLoc() != NLoc) {
  8818. N->setDebugLoc(DebugLoc());
  8819. }
  8820. unsigned Order = std::min(N->getIROrder(), OLoc.getIROrder());
  8821. N->setIROrder(Order);
  8822. return N;
  8823. }
  8824. /// MorphNodeTo - This *mutates* the specified node to have the specified
  8825. /// return type, opcode, and operands.
  8826. ///
  8827. /// Note that MorphNodeTo returns the resultant node. If there is already a
  8828. /// node of the specified opcode and operands, it returns that node instead of
  8829. /// the current one. Note that the SDLoc need not be the same.
  8830. ///
  8831. /// Using MorphNodeTo is faster than creating a new node and swapping it in
  8832. /// with ReplaceAllUsesWith both because it often avoids allocating a new
  8833. /// node, and because it doesn't require CSE recalculation for any of
  8834. /// the node's users.
  8835. ///
  8836. /// However, note that MorphNodeTo recursively deletes dead nodes from the DAG.
  8837. /// As a consequence it isn't appropriate to use from within the DAG combiner or
  8838. /// the legalizer which maintain worklists that would need to be updated when
  8839. /// deleting things.
  8840. SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
  8841. SDVTList VTs, ArrayRef<SDValue> Ops) {
  8842. // If an identical node already exists, use it.
  8843. void *IP = nullptr;
  8844. if (VTs.VTs[VTs.NumVTs-1] != MVT::Glue) {
  8845. FoldingSetNodeID ID;
  8846. AddNodeIDNode(ID, Opc, VTs, Ops);
  8847. if (SDNode *ON = FindNodeOrInsertPos(ID, SDLoc(N), IP))
  8848. return UpdateSDLocOnMergeSDNode(ON, SDLoc(N));
  8849. }
  8850. if (!RemoveNodeFromCSEMaps(N))
  8851. IP = nullptr;
  8852. // Start the morphing.
  8853. N->NodeType = Opc;
  8854. N->ValueList = VTs.VTs;
  8855. N->NumValues = VTs.NumVTs;
  8856. // Clear the operands list, updating used nodes to remove this from their
  8857. // use list. Keep track of any operands that become dead as a result.
  8858. SmallPtrSet<SDNode*, 16> DeadNodeSet;
  8859. for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
  8860. SDUse &Use = *I++;
  8861. SDNode *Used = Use.getNode();
  8862. Use.set(SDValue());
  8863. if (Used->use_empty())
  8864. DeadNodeSet.insert(Used);
  8865. }
  8866. // For MachineNode, initialize the memory references information.
  8867. if (MachineSDNode *MN = dyn_cast<MachineSDNode>(N))
  8868. MN->clearMemRefs();
  8869. // Swap for an appropriately sized array from the recycler.
  8870. removeOperands(N);
  8871. createOperands(N, Ops);
  8872. // Delete any nodes that are still dead after adding the uses for the
  8873. // new operands.
  8874. if (!DeadNodeSet.empty()) {
  8875. SmallVector<SDNode *, 16> DeadNodes;
  8876. for (SDNode *N : DeadNodeSet)
  8877. if (N->use_empty())
  8878. DeadNodes.push_back(N);
  8879. RemoveDeadNodes(DeadNodes);
  8880. }
  8881. if (IP)
  8882. CSEMap.InsertNode(N, IP); // Memoize the new node.
  8883. return N;
  8884. }
  8885. SDNode* SelectionDAG::mutateStrictFPToFP(SDNode *Node) {
  8886. unsigned OrigOpc = Node->getOpcode();
  8887. unsigned NewOpc;
  8888. switch (OrigOpc) {
  8889. default:
  8890. llvm_unreachable("mutateStrictFPToFP called with unexpected opcode!");
  8891. #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \
  8892. case ISD::STRICT_##DAGN: NewOpc = ISD::DAGN; break;
  8893. #define CMP_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \
  8894. case ISD::STRICT_##DAGN: NewOpc = ISD::SETCC; break;
  8895. #include "llvm/IR/ConstrainedOps.def"
  8896. }
  8897. assert(Node->getNumValues() == 2 && "Unexpected number of results!");
  8898. // We're taking this node out of the chain, so we need to re-link things.
  8899. SDValue InputChain = Node->getOperand(0);
  8900. SDValue OutputChain = SDValue(Node, 1);
  8901. ReplaceAllUsesOfValueWith(OutputChain, InputChain);
  8902. SmallVector<SDValue, 3> Ops;
  8903. for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i)
  8904. Ops.push_back(Node->getOperand(i));
  8905. SDVTList VTs = getVTList(Node->getValueType(0));
  8906. SDNode *Res = MorphNodeTo(Node, NewOpc, VTs, Ops);
  8907. // MorphNodeTo can operate in two ways: if an existing node with the
  8908. // specified operands exists, it can just return it. Otherwise, it
  8909. // updates the node in place to have the requested operands.
  8910. if (Res == Node) {
  8911. // If we updated the node in place, reset the node ID. To the isel,
  8912. // this should be just like a newly allocated machine node.
  8913. Res->setNodeId(-1);
  8914. } else {
  8915. ReplaceAllUsesWith(Node, Res);
  8916. RemoveDeadNode(Node);
  8917. }
  8918. return Res;
  8919. }
  8920. /// getMachineNode - These are used for target selectors to create a new node
  8921. /// with specified return type(s), MachineInstr opcode, and operands.
  8922. ///
  8923. /// Note that getMachineNode returns the resultant node. If there is already a
  8924. /// node of the specified opcode and operands, it returns that node instead of
  8925. /// the current one.
  8926. MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
  8927. EVT VT) {
  8928. SDVTList VTs = getVTList(VT);
  8929. return getMachineNode(Opcode, dl, VTs, std::nullopt);
  8930. }
  8931. MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
  8932. EVT VT, SDValue Op1) {
  8933. SDVTList VTs = getVTList(VT);
  8934. SDValue Ops[] = { Op1 };
  8935. return getMachineNode(Opcode, dl, VTs, Ops);
  8936. }
  8937. MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
  8938. EVT VT, SDValue Op1, SDValue Op2) {
  8939. SDVTList VTs = getVTList(VT);
  8940. SDValue Ops[] = { Op1, Op2 };
  8941. return getMachineNode(Opcode, dl, VTs, Ops);
  8942. }
  8943. MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
  8944. EVT VT, SDValue Op1, SDValue Op2,
  8945. SDValue Op3) {
  8946. SDVTList VTs = getVTList(VT);
  8947. SDValue Ops[] = { Op1, Op2, Op3 };
  8948. return getMachineNode(Opcode, dl, VTs, Ops);
  8949. }
  8950. MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
  8951. EVT VT, ArrayRef<SDValue> Ops) {
  8952. SDVTList VTs = getVTList(VT);
  8953. return getMachineNode(Opcode, dl, VTs, Ops);
  8954. }
  8955. MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
  8956. EVT VT1, EVT VT2, SDValue Op1,
  8957. SDValue Op2) {
  8958. SDVTList VTs = getVTList(VT1, VT2);
  8959. SDValue Ops[] = { Op1, Op2 };
  8960. return getMachineNode(Opcode, dl, VTs, Ops);
  8961. }
  8962. MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
  8963. EVT VT1, EVT VT2, SDValue Op1,
  8964. SDValue Op2, SDValue Op3) {
  8965. SDVTList VTs = getVTList(VT1, VT2);
  8966. SDValue Ops[] = { Op1, Op2, Op3 };
  8967. return getMachineNode(Opcode, dl, VTs, Ops);
  8968. }
  8969. MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
  8970. EVT VT1, EVT VT2,
  8971. ArrayRef<SDValue> Ops) {
  8972. SDVTList VTs = getVTList(VT1, VT2);
  8973. return getMachineNode(Opcode, dl, VTs, Ops);
  8974. }
  8975. MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
  8976. EVT VT1, EVT VT2, EVT VT3,
  8977. SDValue Op1, SDValue Op2) {
  8978. SDVTList VTs = getVTList(VT1, VT2, VT3);
  8979. SDValue Ops[] = { Op1, Op2 };
  8980. return getMachineNode(Opcode, dl, VTs, Ops);
  8981. }
  8982. MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
  8983. EVT VT1, EVT VT2, EVT VT3,
  8984. SDValue Op1, SDValue Op2,
  8985. SDValue Op3) {
  8986. SDVTList VTs = getVTList(VT1, VT2, VT3);
  8987. SDValue Ops[] = { Op1, Op2, Op3 };
  8988. return getMachineNode(Opcode, dl, VTs, Ops);
  8989. }
  8990. MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
  8991. EVT VT1, EVT VT2, EVT VT3,
  8992. ArrayRef<SDValue> Ops) {
  8993. SDVTList VTs = getVTList(VT1, VT2, VT3);
  8994. return getMachineNode(Opcode, dl, VTs, Ops);
  8995. }
  8996. MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
  8997. ArrayRef<EVT> ResultTys,
  8998. ArrayRef<SDValue> Ops) {
  8999. SDVTList VTs = getVTList(ResultTys);
  9000. return getMachineNode(Opcode, dl, VTs, Ops);
  9001. }
  9002. MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &DL,
  9003. SDVTList VTs,
  9004. ArrayRef<SDValue> Ops) {
  9005. bool DoCSE = VTs.VTs[VTs.NumVTs-1] != MVT::Glue;
  9006. MachineSDNode *N;
  9007. void *IP = nullptr;
  9008. if (DoCSE) {
  9009. FoldingSetNodeID ID;
  9010. AddNodeIDNode(ID, ~Opcode, VTs, Ops);
  9011. IP = nullptr;
  9012. if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
  9013. return cast<MachineSDNode>(UpdateSDLocOnMergeSDNode(E, DL));
  9014. }
  9015. }
  9016. // Allocate a new MachineSDNode.
  9017. N = newSDNode<MachineSDNode>(~Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
  9018. createOperands(N, Ops);
  9019. if (DoCSE)
  9020. CSEMap.InsertNode(N, IP);
  9021. InsertNode(N);
  9022. NewSDValueDbgMsg(SDValue(N, 0), "Creating new machine node: ", this);
  9023. return N;
  9024. }
  9025. /// getTargetExtractSubreg - A convenience function for creating
  9026. /// TargetOpcode::EXTRACT_SUBREG nodes.
  9027. SDValue SelectionDAG::getTargetExtractSubreg(int SRIdx, const SDLoc &DL, EVT VT,
  9028. SDValue Operand) {
  9029. SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32);
  9030. SDNode *Subreg = getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL,
  9031. VT, Operand, SRIdxVal);
  9032. return SDValue(Subreg, 0);
  9033. }
  9034. /// getTargetInsertSubreg - A convenience function for creating
  9035. /// TargetOpcode::INSERT_SUBREG nodes.
  9036. SDValue SelectionDAG::getTargetInsertSubreg(int SRIdx, const SDLoc &DL, EVT VT,
  9037. SDValue Operand, SDValue Subreg) {
  9038. SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32);
  9039. SDNode *Result = getMachineNode(TargetOpcode::INSERT_SUBREG, DL,
  9040. VT, Operand, Subreg, SRIdxVal);
  9041. return SDValue(Result, 0);
  9042. }
  9043. /// getNodeIfExists - Get the specified node if it's already available, or
  9044. /// else return NULL.
  9045. SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList,
  9046. ArrayRef<SDValue> Ops) {
  9047. SDNodeFlags Flags;
  9048. if (Inserter)
  9049. Flags = Inserter->getFlags();
  9050. return getNodeIfExists(Opcode, VTList, Ops, Flags);
  9051. }
  9052. SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList,
  9053. ArrayRef<SDValue> Ops,
  9054. const SDNodeFlags Flags) {
  9055. if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) {
  9056. FoldingSetNodeID ID;
  9057. AddNodeIDNode(ID, Opcode, VTList, Ops);
  9058. void *IP = nullptr;
  9059. if (SDNode *E = FindNodeOrInsertPos(ID, SDLoc(), IP)) {
  9060. E->intersectFlagsWith(Flags);
  9061. return E;
  9062. }
  9063. }
  9064. return nullptr;
  9065. }
  9066. /// doesNodeExist - Check if a node exists without modifying its flags.
  9067. bool SelectionDAG::doesNodeExist(unsigned Opcode, SDVTList VTList,
  9068. ArrayRef<SDValue> Ops) {
  9069. if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) {
  9070. FoldingSetNodeID ID;
  9071. AddNodeIDNode(ID, Opcode, VTList, Ops);
  9072. void *IP = nullptr;
  9073. if (FindNodeOrInsertPos(ID, SDLoc(), IP))
  9074. return true;
  9075. }
  9076. return false;
  9077. }
  9078. /// getDbgValue - Creates a SDDbgValue node.
  9079. ///
  9080. /// SDNode
  9081. SDDbgValue *SelectionDAG::getDbgValue(DIVariable *Var, DIExpression *Expr,
  9082. SDNode *N, unsigned R, bool IsIndirect,
  9083. const DebugLoc &DL, unsigned O) {
  9084. assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
  9085. "Expected inlined-at fields to agree");
  9086. return new (DbgInfo->getAlloc())
  9087. SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromNode(N, R),
  9088. {}, IsIndirect, DL, O,
  9089. /*IsVariadic=*/false);
  9090. }
  9091. /// Constant
  9092. SDDbgValue *SelectionDAG::getConstantDbgValue(DIVariable *Var,
  9093. DIExpression *Expr,
  9094. const Value *C,
  9095. const DebugLoc &DL, unsigned O) {
  9096. assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
  9097. "Expected inlined-at fields to agree");
  9098. return new (DbgInfo->getAlloc())
  9099. SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromConst(C), {},
  9100. /*IsIndirect=*/false, DL, O,
  9101. /*IsVariadic=*/false);
  9102. }
  9103. /// FrameIndex
  9104. SDDbgValue *SelectionDAG::getFrameIndexDbgValue(DIVariable *Var,
  9105. DIExpression *Expr, unsigned FI,
  9106. bool IsIndirect,
  9107. const DebugLoc &DL,
  9108. unsigned O) {
  9109. assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
  9110. "Expected inlined-at fields to agree");
  9111. return getFrameIndexDbgValue(Var, Expr, FI, {}, IsIndirect, DL, O);
  9112. }
  9113. /// FrameIndex with dependencies
  9114. SDDbgValue *SelectionDAG::getFrameIndexDbgValue(DIVariable *Var,
  9115. DIExpression *Expr, unsigned FI,
  9116. ArrayRef<SDNode *> Dependencies,
  9117. bool IsIndirect,
  9118. const DebugLoc &DL,
  9119. unsigned O) {
  9120. assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
  9121. "Expected inlined-at fields to agree");
  9122. return new (DbgInfo->getAlloc())
  9123. SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromFrameIdx(FI),
  9124. Dependencies, IsIndirect, DL, O,
  9125. /*IsVariadic=*/false);
  9126. }
  9127. /// VReg
  9128. SDDbgValue *SelectionDAG::getVRegDbgValue(DIVariable *Var, DIExpression *Expr,
  9129. unsigned VReg, bool IsIndirect,
  9130. const DebugLoc &DL, unsigned O) {
  9131. assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
  9132. "Expected inlined-at fields to agree");
  9133. return new (DbgInfo->getAlloc())
  9134. SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromVReg(VReg),
  9135. {}, IsIndirect, DL, O,
  9136. /*IsVariadic=*/false);
  9137. }
  9138. SDDbgValue *SelectionDAG::getDbgValueList(DIVariable *Var, DIExpression *Expr,
  9139. ArrayRef<SDDbgOperand> Locs,
  9140. ArrayRef<SDNode *> Dependencies,
  9141. bool IsIndirect, const DebugLoc &DL,
  9142. unsigned O, bool IsVariadic) {
  9143. assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
  9144. "Expected inlined-at fields to agree");
  9145. return new (DbgInfo->getAlloc())
  9146. SDDbgValue(DbgInfo->getAlloc(), Var, Expr, Locs, Dependencies, IsIndirect,
  9147. DL, O, IsVariadic);
  9148. }
  9149. void SelectionDAG::transferDbgValues(SDValue From, SDValue To,
  9150. unsigned OffsetInBits, unsigned SizeInBits,
  9151. bool InvalidateDbg) {
  9152. SDNode *FromNode = From.getNode();
  9153. SDNode *ToNode = To.getNode();
  9154. assert(FromNode && ToNode && "Can't modify dbg values");
  9155. // PR35338
  9156. // TODO: assert(From != To && "Redundant dbg value transfer");
  9157. // TODO: assert(FromNode != ToNode && "Intranode dbg value transfer");
  9158. if (From == To || FromNode == ToNode)
  9159. return;
  9160. if (!FromNode->getHasDebugValue())
  9161. return;
  9162. SDDbgOperand FromLocOp =
  9163. SDDbgOperand::fromNode(From.getNode(), From.getResNo());
  9164. SDDbgOperand ToLocOp = SDDbgOperand::fromNode(To.getNode(), To.getResNo());
  9165. SmallVector<SDDbgValue *, 2> ClonedDVs;
  9166. for (SDDbgValue *Dbg : GetDbgValues(FromNode)) {
  9167. if (Dbg->isInvalidated())
  9168. continue;
  9169. // TODO: assert(!Dbg->isInvalidated() && "Transfer of invalid dbg value");
  9170. // Create a new location ops vector that is equal to the old vector, but
  9171. // with each instance of FromLocOp replaced with ToLocOp.
  9172. bool Changed = false;
  9173. auto NewLocOps = Dbg->copyLocationOps();
  9174. std::replace_if(
  9175. NewLocOps.begin(), NewLocOps.end(),
  9176. [&Changed, FromLocOp](const SDDbgOperand &Op) {
  9177. bool Match = Op == FromLocOp;
  9178. Changed |= Match;
  9179. return Match;
  9180. },
  9181. ToLocOp);
  9182. // Ignore this SDDbgValue if we didn't find a matching location.
  9183. if (!Changed)
  9184. continue;
  9185. DIVariable *Var = Dbg->getVariable();
  9186. auto *Expr = Dbg->getExpression();
  9187. // If a fragment is requested, update the expression.
  9188. if (SizeInBits) {
  9189. // When splitting a larger (e.g., sign-extended) value whose
  9190. // lower bits are described with an SDDbgValue, do not attempt
  9191. // to transfer the SDDbgValue to the upper bits.
  9192. if (auto FI = Expr->getFragmentInfo())
  9193. if (OffsetInBits + SizeInBits > FI->SizeInBits)
  9194. continue;
  9195. auto Fragment = DIExpression::createFragmentExpression(Expr, OffsetInBits,
  9196. SizeInBits);
  9197. if (!Fragment)
  9198. continue;
  9199. Expr = *Fragment;
  9200. }
  9201. auto AdditionalDependencies = Dbg->getAdditionalDependencies();
  9202. // Clone the SDDbgValue and move it to To.
  9203. SDDbgValue *Clone = getDbgValueList(
  9204. Var, Expr, NewLocOps, AdditionalDependencies, Dbg->isIndirect(),
  9205. Dbg->getDebugLoc(), std::max(ToNode->getIROrder(), Dbg->getOrder()),
  9206. Dbg->isVariadic());
  9207. ClonedDVs.push_back(Clone);
  9208. if (InvalidateDbg) {
  9209. // Invalidate value and indicate the SDDbgValue should not be emitted.
  9210. Dbg->setIsInvalidated();
  9211. Dbg->setIsEmitted();
  9212. }
  9213. }
  9214. for (SDDbgValue *Dbg : ClonedDVs) {
  9215. assert(is_contained(Dbg->getSDNodes(), ToNode) &&
  9216. "Transferred DbgValues should depend on the new SDNode");
  9217. AddDbgValue(Dbg, false);
  9218. }
  9219. }
  9220. void SelectionDAG::salvageDebugInfo(SDNode &N) {
  9221. if (!N.getHasDebugValue())
  9222. return;
  9223. SmallVector<SDDbgValue *, 2> ClonedDVs;
  9224. for (auto *DV : GetDbgValues(&N)) {
  9225. if (DV->isInvalidated())
  9226. continue;
  9227. switch (N.getOpcode()) {
  9228. default:
  9229. break;
  9230. case ISD::ADD:
  9231. SDValue N0 = N.getOperand(0);
  9232. SDValue N1 = N.getOperand(1);
  9233. if (!isConstantIntBuildVectorOrConstantInt(N0) &&
  9234. isConstantIntBuildVectorOrConstantInt(N1)) {
  9235. uint64_t Offset = N.getConstantOperandVal(1);
  9236. // Rewrite an ADD constant node into a DIExpression. Since we are
  9237. // performing arithmetic to compute the variable's *value* in the
  9238. // DIExpression, we need to mark the expression with a
  9239. // DW_OP_stack_value.
  9240. auto *DIExpr = DV->getExpression();
  9241. auto NewLocOps = DV->copyLocationOps();
  9242. bool Changed = false;
  9243. for (size_t i = 0; i < NewLocOps.size(); ++i) {
  9244. // We're not given a ResNo to compare against because the whole
  9245. // node is going away. We know that any ISD::ADD only has one
  9246. // result, so we can assume any node match is using the result.
  9247. if (NewLocOps[i].getKind() != SDDbgOperand::SDNODE ||
  9248. NewLocOps[i].getSDNode() != &N)
  9249. continue;
  9250. NewLocOps[i] = SDDbgOperand::fromNode(N0.getNode(), N0.getResNo());
  9251. SmallVector<uint64_t, 3> ExprOps;
  9252. DIExpression::appendOffset(ExprOps, Offset);
  9253. DIExpr = DIExpression::appendOpsToArg(DIExpr, ExprOps, i, true);
  9254. Changed = true;
  9255. }
  9256. (void)Changed;
  9257. assert(Changed && "Salvage target doesn't use N");
  9258. auto AdditionalDependencies = DV->getAdditionalDependencies();
  9259. SDDbgValue *Clone = getDbgValueList(DV->getVariable(), DIExpr,
  9260. NewLocOps, AdditionalDependencies,
  9261. DV->isIndirect(), DV->getDebugLoc(),
  9262. DV->getOrder(), DV->isVariadic());
  9263. ClonedDVs.push_back(Clone);
  9264. DV->setIsInvalidated();
  9265. DV->setIsEmitted();
  9266. LLVM_DEBUG(dbgs() << "SALVAGE: Rewriting";
  9267. N0.getNode()->dumprFull(this);
  9268. dbgs() << " into " << *DIExpr << '\n');
  9269. }
  9270. }
  9271. }
  9272. for (SDDbgValue *Dbg : ClonedDVs) {
  9273. assert(!Dbg->getSDNodes().empty() &&
  9274. "Salvaged DbgValue should depend on a new SDNode");
  9275. AddDbgValue(Dbg, false);
  9276. }
  9277. }
  9278. /// Creates a SDDbgLabel node.
  9279. SDDbgLabel *SelectionDAG::getDbgLabel(DILabel *Label,
  9280. const DebugLoc &DL, unsigned O) {
  9281. assert(cast<DILabel>(Label)->isValidLocationForIntrinsic(DL) &&
  9282. "Expected inlined-at fields to agree");
  9283. return new (DbgInfo->getAlloc()) SDDbgLabel(Label, DL, O);
  9284. }
  9285. namespace {
  9286. /// RAUWUpdateListener - Helper for ReplaceAllUsesWith - When the node
  9287. /// pointed to by a use iterator is deleted, increment the use iterator
  9288. /// so that it doesn't dangle.
  9289. ///
  9290. class RAUWUpdateListener : public SelectionDAG::DAGUpdateListener {
  9291. SDNode::use_iterator &UI;
  9292. SDNode::use_iterator &UE;
  9293. void NodeDeleted(SDNode *N, SDNode *E) override {
  9294. // Increment the iterator as needed.
  9295. while (UI != UE && N == *UI)
  9296. ++UI;
  9297. }
  9298. public:
  9299. RAUWUpdateListener(SelectionDAG &d,
  9300. SDNode::use_iterator &ui,
  9301. SDNode::use_iterator &ue)
  9302. : SelectionDAG::DAGUpdateListener(d), UI(ui), UE(ue) {}
  9303. };
  9304. } // end anonymous namespace
  9305. /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
  9306. /// This can cause recursive merging of nodes in the DAG.
  9307. ///
  9308. /// This version assumes From has a single result value.
  9309. ///
  9310. void SelectionDAG::ReplaceAllUsesWith(SDValue FromN, SDValue To) {
  9311. SDNode *From = FromN.getNode();
  9312. assert(From->getNumValues() == 1 && FromN.getResNo() == 0 &&
  9313. "Cannot replace with this method!");
  9314. assert(From != To.getNode() && "Cannot replace uses of with self");
  9315. // Preserve Debug Values
  9316. transferDbgValues(FromN, To);
  9317. // Preserve extra info.
  9318. copyExtraInfo(From, To.getNode());
  9319. // Iterate over all the existing uses of From. New uses will be added
  9320. // to the beginning of the use list, which we avoid visiting.
  9321. // This specifically avoids visiting uses of From that arise while the
  9322. // replacement is happening, because any such uses would be the result
  9323. // of CSE: If an existing node looks like From after one of its operands
  9324. // is replaced by To, we don't want to replace of all its users with To
  9325. // too. See PR3018 for more info.
  9326. SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
  9327. RAUWUpdateListener Listener(*this, UI, UE);
  9328. while (UI != UE) {
  9329. SDNode *User = *UI;
  9330. // This node is about to morph, remove its old self from the CSE maps.
  9331. RemoveNodeFromCSEMaps(User);
  9332. // A user can appear in a use list multiple times, and when this
  9333. // happens the uses are usually next to each other in the list.
  9334. // To help reduce the number of CSE recomputations, process all
  9335. // the uses of this user that we can find this way.
  9336. do {
  9337. SDUse &Use = UI.getUse();
  9338. ++UI;
  9339. Use.set(To);
  9340. if (To->isDivergent() != From->isDivergent())
  9341. updateDivergence(User);
  9342. } while (UI != UE && *UI == User);
  9343. // Now that we have modified User, add it back to the CSE maps. If it
  9344. // already exists there, recursively merge the results together.
  9345. AddModifiedNodeToCSEMaps(User);
  9346. }
  9347. // If we just RAUW'd the root, take note.
  9348. if (FromN == getRoot())
  9349. setRoot(To);
  9350. }
  9351. /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
  9352. /// This can cause recursive merging of nodes in the DAG.
  9353. ///
  9354. /// This version assumes that for each value of From, there is a
  9355. /// corresponding value in To in the same position with the same type.
  9356. ///
  9357. void SelectionDAG::ReplaceAllUsesWith(SDNode *From, SDNode *To) {
  9358. #ifndef NDEBUG
  9359. for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
  9360. assert((!From->hasAnyUseOfValue(i) ||
  9361. From->getValueType(i) == To->getValueType(i)) &&
  9362. "Cannot use this version of ReplaceAllUsesWith!");
  9363. #endif
  9364. // Handle the trivial case.
  9365. if (From == To)
  9366. return;
  9367. // Preserve Debug Info. Only do this if there's a use.
  9368. for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
  9369. if (From->hasAnyUseOfValue(i)) {
  9370. assert((i < To->getNumValues()) && "Invalid To location");
  9371. transferDbgValues(SDValue(From, i), SDValue(To, i));
  9372. }
  9373. // Preserve extra info.
  9374. copyExtraInfo(From, To);
  9375. // Iterate over just the existing users of From. See the comments in
  9376. // the ReplaceAllUsesWith above.
  9377. SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
  9378. RAUWUpdateListener Listener(*this, UI, UE);
  9379. while (UI != UE) {
  9380. SDNode *User = *UI;
  9381. // This node is about to morph, remove its old self from the CSE maps.
  9382. RemoveNodeFromCSEMaps(User);
  9383. // A user can appear in a use list multiple times, and when this
  9384. // happens the uses are usually next to each other in the list.
  9385. // To help reduce the number of CSE recomputations, process all
  9386. // the uses of this user that we can find this way.
  9387. do {
  9388. SDUse &Use = UI.getUse();
  9389. ++UI;
  9390. Use.setNode(To);
  9391. if (To->isDivergent() != From->isDivergent())
  9392. updateDivergence(User);
  9393. } while (UI != UE && *UI == User);
  9394. // Now that we have modified User, add it back to the CSE maps. If it
  9395. // already exists there, recursively merge the results together.
  9396. AddModifiedNodeToCSEMaps(User);
  9397. }
  9398. // If we just RAUW'd the root, take note.
  9399. if (From == getRoot().getNode())
  9400. setRoot(SDValue(To, getRoot().getResNo()));
  9401. }
  9402. /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
  9403. /// This can cause recursive merging of nodes in the DAG.
  9404. ///
  9405. /// This version can replace From with any result values. To must match the
  9406. /// number and types of values returned by From.
  9407. void SelectionDAG::ReplaceAllUsesWith(SDNode *From, const SDValue *To) {
  9408. if (From->getNumValues() == 1) // Handle the simple case efficiently.
  9409. return ReplaceAllUsesWith(SDValue(From, 0), To[0]);
  9410. for (unsigned i = 0, e = From->getNumValues(); i != e; ++i) {
  9411. // Preserve Debug Info.
  9412. transferDbgValues(SDValue(From, i), To[i]);
  9413. // Preserve extra info.
  9414. copyExtraInfo(From, To[i].getNode());
  9415. }
  9416. // Iterate over just the existing users of From. See the comments in
  9417. // the ReplaceAllUsesWith above.
  9418. SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
  9419. RAUWUpdateListener Listener(*this, UI, UE);
  9420. while (UI != UE) {
  9421. SDNode *User = *UI;
  9422. // This node is about to morph, remove its old self from the CSE maps.
  9423. RemoveNodeFromCSEMaps(User);
  9424. // A user can appear in a use list multiple times, and when this happens the
  9425. // uses are usually next to each other in the list. To help reduce the
  9426. // number of CSE and divergence recomputations, process all the uses of this
  9427. // user that we can find this way.
  9428. bool To_IsDivergent = false;
  9429. do {
  9430. SDUse &Use = UI.getUse();
  9431. const SDValue &ToOp = To[Use.getResNo()];
  9432. ++UI;
  9433. Use.set(ToOp);
  9434. To_IsDivergent |= ToOp->isDivergent();
  9435. } while (UI != UE && *UI == User);
  9436. if (To_IsDivergent != From->isDivergent())
  9437. updateDivergence(User);
  9438. // Now that we have modified User, add it back to the CSE maps. If it
  9439. // already exists there, recursively merge the results together.
  9440. AddModifiedNodeToCSEMaps(User);
  9441. }
  9442. // If we just RAUW'd the root, take note.
  9443. if (From == getRoot().getNode())
  9444. setRoot(SDValue(To[getRoot().getResNo()]));
  9445. }
  9446. /// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving
  9447. /// uses of other values produced by From.getNode() alone. The Deleted
  9448. /// vector is handled the same way as for ReplaceAllUsesWith.
  9449. void SelectionDAG::ReplaceAllUsesOfValueWith(SDValue From, SDValue To){
  9450. // Handle the really simple, really trivial case efficiently.
  9451. if (From == To) return;
  9452. // Handle the simple, trivial, case efficiently.
  9453. if (From.getNode()->getNumValues() == 1) {
  9454. ReplaceAllUsesWith(From, To);
  9455. return;
  9456. }
  9457. // Preserve Debug Info.
  9458. transferDbgValues(From, To);
  9459. copyExtraInfo(From.getNode(), To.getNode());
  9460. // Iterate over just the existing users of From. See the comments in
  9461. // the ReplaceAllUsesWith above.
  9462. SDNode::use_iterator UI = From.getNode()->use_begin(),
  9463. UE = From.getNode()->use_end();
  9464. RAUWUpdateListener Listener(*this, UI, UE);
  9465. while (UI != UE) {
  9466. SDNode *User = *UI;
  9467. bool UserRemovedFromCSEMaps = false;
  9468. // A user can appear in a use list multiple times, and when this
  9469. // happens the uses are usually next to each other in the list.
  9470. // To help reduce the number of CSE recomputations, process all
  9471. // the uses of this user that we can find this way.
  9472. do {
  9473. SDUse &Use = UI.getUse();
  9474. // Skip uses of different values from the same node.
  9475. if (Use.getResNo() != From.getResNo()) {
  9476. ++UI;
  9477. continue;
  9478. }
  9479. // If this node hasn't been modified yet, it's still in the CSE maps,
  9480. // so remove its old self from the CSE maps.
  9481. if (!UserRemovedFromCSEMaps) {
  9482. RemoveNodeFromCSEMaps(User);
  9483. UserRemovedFromCSEMaps = true;
  9484. }
  9485. ++UI;
  9486. Use.set(To);
  9487. if (To->isDivergent() != From->isDivergent())
  9488. updateDivergence(User);
  9489. } while (UI != UE && *UI == User);
  9490. // We are iterating over all uses of the From node, so if a use
  9491. // doesn't use the specific value, no changes are made.
  9492. if (!UserRemovedFromCSEMaps)
  9493. continue;
  9494. // Now that we have modified User, add it back to the CSE maps. If it
  9495. // already exists there, recursively merge the results together.
  9496. AddModifiedNodeToCSEMaps(User);
  9497. }
  9498. // If we just RAUW'd the root, take note.
  9499. if (From == getRoot())
  9500. setRoot(To);
  9501. }
  9502. namespace {
  9503. /// UseMemo - This class is used by SelectionDAG::ReplaceAllUsesOfValuesWith
  9504. /// to record information about a use.
  9505. struct UseMemo {
  9506. SDNode *User;
  9507. unsigned Index;
  9508. SDUse *Use;
  9509. };
  9510. /// operator< - Sort Memos by User.
  9511. bool operator<(const UseMemo &L, const UseMemo &R) {
  9512. return (intptr_t)L.User < (intptr_t)R.User;
  9513. }
  9514. /// RAUOVWUpdateListener - Helper for ReplaceAllUsesOfValuesWith - When the node
  9515. /// pointed to by a UseMemo is deleted, set the User to nullptr to indicate that
  9516. /// the node already has been taken care of recursively.
  9517. class RAUOVWUpdateListener : public SelectionDAG::DAGUpdateListener {
  9518. SmallVector<UseMemo, 4> &Uses;
  9519. void NodeDeleted(SDNode *N, SDNode *E) override {
  9520. for (UseMemo &Memo : Uses)
  9521. if (Memo.User == N)
  9522. Memo.User = nullptr;
  9523. }
  9524. public:
  9525. RAUOVWUpdateListener(SelectionDAG &d, SmallVector<UseMemo, 4> &uses)
  9526. : SelectionDAG::DAGUpdateListener(d), Uses(uses) {}
  9527. };
  9528. } // end anonymous namespace
  9529. bool SelectionDAG::calculateDivergence(SDNode *N) {
  9530. if (TLI->isSDNodeAlwaysUniform(N)) {
  9531. assert(!TLI->isSDNodeSourceOfDivergence(N, FLI, DA) &&
  9532. "Conflicting divergence information!");
  9533. return false;
  9534. }
  9535. if (TLI->isSDNodeSourceOfDivergence(N, FLI, DA))
  9536. return true;
  9537. for (const auto &Op : N->ops()) {
  9538. if (Op.Val.getValueType() != MVT::Other && Op.getNode()->isDivergent())
  9539. return true;
  9540. }
  9541. return false;
  9542. }
  9543. void SelectionDAG::updateDivergence(SDNode *N) {
  9544. SmallVector<SDNode *, 16> Worklist(1, N);
  9545. do {
  9546. N = Worklist.pop_back_val();
  9547. bool IsDivergent = calculateDivergence(N);
  9548. if (N->SDNodeBits.IsDivergent != IsDivergent) {
  9549. N->SDNodeBits.IsDivergent = IsDivergent;
  9550. llvm::append_range(Worklist, N->uses());
  9551. }
  9552. } while (!Worklist.empty());
  9553. }
  9554. void SelectionDAG::CreateTopologicalOrder(std::vector<SDNode *> &Order) {
  9555. DenseMap<SDNode *, unsigned> Degree;
  9556. Order.reserve(AllNodes.size());
  9557. for (auto &N : allnodes()) {
  9558. unsigned NOps = N.getNumOperands();
  9559. Degree[&N] = NOps;
  9560. if (0 == NOps)
  9561. Order.push_back(&N);
  9562. }
  9563. for (size_t I = 0; I != Order.size(); ++I) {
  9564. SDNode *N = Order[I];
  9565. for (auto *U : N->uses()) {
  9566. unsigned &UnsortedOps = Degree[U];
  9567. if (0 == --UnsortedOps)
  9568. Order.push_back(U);
  9569. }
  9570. }
  9571. }
  9572. #ifndef NDEBUG
  9573. void SelectionDAG::VerifyDAGDivergence() {
  9574. std::vector<SDNode *> TopoOrder;
  9575. CreateTopologicalOrder(TopoOrder);
  9576. for (auto *N : TopoOrder) {
  9577. assert(calculateDivergence(N) == N->isDivergent() &&
  9578. "Divergence bit inconsistency detected");
  9579. }
  9580. }
  9581. #endif
  9582. /// ReplaceAllUsesOfValuesWith - Replace any uses of From with To, leaving
  9583. /// uses of other values produced by From.getNode() alone. The same value
  9584. /// may appear in both the From and To list. The Deleted vector is
  9585. /// handled the same way as for ReplaceAllUsesWith.
  9586. void SelectionDAG::ReplaceAllUsesOfValuesWith(const SDValue *From,
  9587. const SDValue *To,
  9588. unsigned Num){
  9589. // Handle the simple, trivial case efficiently.
  9590. if (Num == 1)
  9591. return ReplaceAllUsesOfValueWith(*From, *To);
  9592. transferDbgValues(*From, *To);
  9593. copyExtraInfo(From->getNode(), To->getNode());
  9594. // Read up all the uses and make records of them. This helps
  9595. // processing new uses that are introduced during the
  9596. // replacement process.
  9597. SmallVector<UseMemo, 4> Uses;
  9598. for (unsigned i = 0; i != Num; ++i) {
  9599. unsigned FromResNo = From[i].getResNo();
  9600. SDNode *FromNode = From[i].getNode();
  9601. for (SDNode::use_iterator UI = FromNode->use_begin(),
  9602. E = FromNode->use_end(); UI != E; ++UI) {
  9603. SDUse &Use = UI.getUse();
  9604. if (Use.getResNo() == FromResNo) {
  9605. UseMemo Memo = { *UI, i, &Use };
  9606. Uses.push_back(Memo);
  9607. }
  9608. }
  9609. }
  9610. // Sort the uses, so that all the uses from a given User are together.
  9611. llvm::sort(Uses);
  9612. RAUOVWUpdateListener Listener(*this, Uses);
  9613. for (unsigned UseIndex = 0, UseIndexEnd = Uses.size();
  9614. UseIndex != UseIndexEnd; ) {
  9615. // We know that this user uses some value of From. If it is the right
  9616. // value, update it.
  9617. SDNode *User = Uses[UseIndex].User;
  9618. // If the node has been deleted by recursive CSE updates when updating
  9619. // another node, then just skip this entry.
  9620. if (User == nullptr) {
  9621. ++UseIndex;
  9622. continue;
  9623. }
  9624. // This node is about to morph, remove its old self from the CSE maps.
  9625. RemoveNodeFromCSEMaps(User);
  9626. // The Uses array is sorted, so all the uses for a given User
  9627. // are next to each other in the list.
  9628. // To help reduce the number of CSE recomputations, process all
  9629. // the uses of this user that we can find this way.
  9630. do {
  9631. unsigned i = Uses[UseIndex].Index;
  9632. SDUse &Use = *Uses[UseIndex].Use;
  9633. ++UseIndex;
  9634. Use.set(To[i]);
  9635. } while (UseIndex != UseIndexEnd && Uses[UseIndex].User == User);
  9636. // Now that we have modified User, add it back to the CSE maps. If it
  9637. // already exists there, recursively merge the results together.
  9638. AddModifiedNodeToCSEMaps(User);
  9639. }
  9640. }
  9641. /// AssignTopologicalOrder - Assign a unique node id for each node in the DAG
  9642. /// based on their topological order. It returns the maximum id and a vector
  9643. /// of the SDNodes* in assigned order by reference.
  9644. unsigned SelectionDAG::AssignTopologicalOrder() {
  9645. unsigned DAGSize = 0;
  9646. // SortedPos tracks the progress of the algorithm. Nodes before it are
  9647. // sorted, nodes after it are unsorted. When the algorithm completes
  9648. // it is at the end of the list.
  9649. allnodes_iterator SortedPos = allnodes_begin();
  9650. // Visit all the nodes. Move nodes with no operands to the front of
  9651. // the list immediately. Annotate nodes that do have operands with their
  9652. // operand count. Before we do this, the Node Id fields of the nodes
  9653. // may contain arbitrary values. After, the Node Id fields for nodes
  9654. // before SortedPos will contain the topological sort index, and the
  9655. // Node Id fields for nodes At SortedPos and after will contain the
  9656. // count of outstanding operands.
  9657. for (SDNode &N : llvm::make_early_inc_range(allnodes())) {
  9658. checkForCycles(&N, this);
  9659. unsigned Degree = N.getNumOperands();
  9660. if (Degree == 0) {
  9661. // A node with no uses, add it to the result array immediately.
  9662. N.setNodeId(DAGSize++);
  9663. allnodes_iterator Q(&N);
  9664. if (Q != SortedPos)
  9665. SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(Q));
  9666. assert(SortedPos != AllNodes.end() && "Overran node list");
  9667. ++SortedPos;
  9668. } else {
  9669. // Temporarily use the Node Id as scratch space for the degree count.
  9670. N.setNodeId(Degree);
  9671. }
  9672. }
  9673. // Visit all the nodes. As we iterate, move nodes into sorted order,
  9674. // such that by the time the end is reached all nodes will be sorted.
  9675. for (SDNode &Node : allnodes()) {
  9676. SDNode *N = &Node;
  9677. checkForCycles(N, this);
  9678. // N is in sorted position, so all its uses have one less operand
  9679. // that needs to be sorted.
  9680. for (SDNode *P : N->uses()) {
  9681. unsigned Degree = P->getNodeId();
  9682. assert(Degree != 0 && "Invalid node degree");
  9683. --Degree;
  9684. if (Degree == 0) {
  9685. // All of P's operands are sorted, so P may sorted now.
  9686. P->setNodeId(DAGSize++);
  9687. if (P->getIterator() != SortedPos)
  9688. SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(P));
  9689. assert(SortedPos != AllNodes.end() && "Overran node list");
  9690. ++SortedPos;
  9691. } else {
  9692. // Update P's outstanding operand count.
  9693. P->setNodeId(Degree);
  9694. }
  9695. }
  9696. if (Node.getIterator() == SortedPos) {
  9697. #ifndef NDEBUG
  9698. allnodes_iterator I(N);
  9699. SDNode *S = &*++I;
  9700. dbgs() << "Overran sorted position:\n";
  9701. S->dumprFull(this); dbgs() << "\n";
  9702. dbgs() << "Checking if this is due to cycles\n";
  9703. checkForCycles(this, true);
  9704. #endif
  9705. llvm_unreachable(nullptr);
  9706. }
  9707. }
  9708. assert(SortedPos == AllNodes.end() &&
  9709. "Topological sort incomplete!");
  9710. assert(AllNodes.front().getOpcode() == ISD::EntryToken &&
  9711. "First node in topological sort is not the entry token!");
  9712. assert(AllNodes.front().getNodeId() == 0 &&
  9713. "First node in topological sort has non-zero id!");
  9714. assert(AllNodes.front().getNumOperands() == 0 &&
  9715. "First node in topological sort has operands!");
  9716. assert(AllNodes.back().getNodeId() == (int)DAGSize-1 &&
  9717. "Last node in topologic sort has unexpected id!");
  9718. assert(AllNodes.back().use_empty() &&
  9719. "Last node in topologic sort has users!");
  9720. assert(DAGSize == allnodes_size() && "Node count mismatch!");
  9721. return DAGSize;
  9722. }
  9723. /// AddDbgValue - Add a dbg_value SDNode. If SD is non-null that means the
  9724. /// value is produced by SD.
  9725. void SelectionDAG::AddDbgValue(SDDbgValue *DB, bool isParameter) {
  9726. for (SDNode *SD : DB->getSDNodes()) {
  9727. if (!SD)
  9728. continue;
  9729. assert(DbgInfo->getSDDbgValues(SD).empty() || SD->getHasDebugValue());
  9730. SD->setHasDebugValue(true);
  9731. }
  9732. DbgInfo->add(DB, isParameter);
  9733. }
  9734. void SelectionDAG::AddDbgLabel(SDDbgLabel *DB) { DbgInfo->add(DB); }
  9735. SDValue SelectionDAG::makeEquivalentMemoryOrdering(SDValue OldChain,
  9736. SDValue NewMemOpChain) {
  9737. assert(isa<MemSDNode>(NewMemOpChain) && "Expected a memop node");
  9738. assert(NewMemOpChain.getValueType() == MVT::Other && "Expected a token VT");
  9739. // The new memory operation must have the same position as the old load in
  9740. // terms of memory dependency. Create a TokenFactor for the old load and new
  9741. // memory operation and update uses of the old load's output chain to use that
  9742. // TokenFactor.
  9743. if (OldChain == NewMemOpChain || OldChain.use_empty())
  9744. return NewMemOpChain;
  9745. SDValue TokenFactor = getNode(ISD::TokenFactor, SDLoc(OldChain), MVT::Other,
  9746. OldChain, NewMemOpChain);
  9747. ReplaceAllUsesOfValueWith(OldChain, TokenFactor);
  9748. UpdateNodeOperands(TokenFactor.getNode(), OldChain, NewMemOpChain);
  9749. return TokenFactor;
  9750. }
  9751. SDValue SelectionDAG::makeEquivalentMemoryOrdering(LoadSDNode *OldLoad,
  9752. SDValue NewMemOp) {
  9753. assert(isa<MemSDNode>(NewMemOp.getNode()) && "Expected a memop node");
  9754. SDValue OldChain = SDValue(OldLoad, 1);
  9755. SDValue NewMemOpChain = NewMemOp.getValue(1);
  9756. return makeEquivalentMemoryOrdering(OldChain, NewMemOpChain);
  9757. }
  9758. SDValue SelectionDAG::getSymbolFunctionGlobalAddress(SDValue Op,
  9759. Function **OutFunction) {
  9760. assert(isa<ExternalSymbolSDNode>(Op) && "Node should be an ExternalSymbol");
  9761. auto *Symbol = cast<ExternalSymbolSDNode>(Op)->getSymbol();
  9762. auto *Module = MF->getFunction().getParent();
  9763. auto *Function = Module->getFunction(Symbol);
  9764. if (OutFunction != nullptr)
  9765. *OutFunction = Function;
  9766. if (Function != nullptr) {
  9767. auto PtrTy = TLI->getPointerTy(getDataLayout(), Function->getAddressSpace());
  9768. return getGlobalAddress(Function, SDLoc(Op), PtrTy);
  9769. }
  9770. std::string ErrorStr;
  9771. raw_string_ostream ErrorFormatter(ErrorStr);
  9772. ErrorFormatter << "Undefined external symbol ";
  9773. ErrorFormatter << '"' << Symbol << '"';
  9774. report_fatal_error(Twine(ErrorFormatter.str()));
  9775. }
  9776. //===----------------------------------------------------------------------===//
  9777. // SDNode Class
  9778. //===----------------------------------------------------------------------===//
  9779. bool llvm::isNullConstant(SDValue V) {
  9780. ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
  9781. return Const != nullptr && Const->isZero();
  9782. }
  9783. bool llvm::isNullFPConstant(SDValue V) {
  9784. ConstantFPSDNode *Const = dyn_cast<ConstantFPSDNode>(V);
  9785. return Const != nullptr && Const->isZero() && !Const->isNegative();
  9786. }
  9787. bool llvm::isAllOnesConstant(SDValue V) {
  9788. ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
  9789. return Const != nullptr && Const->isAllOnes();
  9790. }
  9791. bool llvm::isOneConstant(SDValue V) {
  9792. ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
  9793. return Const != nullptr && Const->isOne();
  9794. }
  9795. bool llvm::isMinSignedConstant(SDValue V) {
  9796. ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
  9797. return Const != nullptr && Const->isMinSignedValue();
  9798. }
  9799. bool llvm::isNeutralConstant(unsigned Opcode, SDNodeFlags Flags, SDValue V,
  9800. unsigned OperandNo) {
  9801. // NOTE: The cases should match with IR's ConstantExpr::getBinOpIdentity().
  9802. // TODO: Target-specific opcodes could be added.
  9803. if (auto *Const = isConstOrConstSplat(V)) {
  9804. switch (Opcode) {
  9805. case ISD::ADD:
  9806. case ISD::OR:
  9807. case ISD::XOR:
  9808. case ISD::UMAX:
  9809. return Const->isZero();
  9810. case ISD::MUL:
  9811. return Const->isOne();
  9812. case ISD::AND:
  9813. case ISD::UMIN:
  9814. return Const->isAllOnes();
  9815. case ISD::SMAX:
  9816. return Const->isMinSignedValue();
  9817. case ISD::SMIN:
  9818. return Const->isMaxSignedValue();
  9819. case ISD::SUB:
  9820. case ISD::SHL:
  9821. case ISD::SRA:
  9822. case ISD::SRL:
  9823. return OperandNo == 1 && Const->isZero();
  9824. case ISD::UDIV:
  9825. case ISD::SDIV:
  9826. return OperandNo == 1 && Const->isOne();
  9827. }
  9828. } else if (auto *ConstFP = isConstOrConstSplatFP(V)) {
  9829. switch (Opcode) {
  9830. case ISD::FADD:
  9831. return ConstFP->isZero() &&
  9832. (Flags.hasNoSignedZeros() || ConstFP->isNegative());
  9833. case ISD::FSUB:
  9834. return OperandNo == 1 && ConstFP->isZero() &&
  9835. (Flags.hasNoSignedZeros() || !ConstFP->isNegative());
  9836. case ISD::FMUL:
  9837. return ConstFP->isExactlyValue(1.0);
  9838. case ISD::FDIV:
  9839. return OperandNo == 1 && ConstFP->isExactlyValue(1.0);
  9840. case ISD::FMINNUM:
  9841. case ISD::FMAXNUM: {
  9842. // Neutral element for fminnum is NaN, Inf or FLT_MAX, depending on FMF.
  9843. EVT VT = V.getValueType();
  9844. const fltSemantics &Semantics = SelectionDAG::EVTToAPFloatSemantics(VT);
  9845. APFloat NeutralAF = !Flags.hasNoNaNs()
  9846. ? APFloat::getQNaN(Semantics)
  9847. : !Flags.hasNoInfs()
  9848. ? APFloat::getInf(Semantics)
  9849. : APFloat::getLargest(Semantics);
  9850. if (Opcode == ISD::FMAXNUM)
  9851. NeutralAF.changeSign();
  9852. return ConstFP->isExactlyValue(NeutralAF);
  9853. }
  9854. }
  9855. }
  9856. return false;
  9857. }
  9858. SDValue llvm::peekThroughBitcasts(SDValue V) {
  9859. while (V.getOpcode() == ISD::BITCAST)
  9860. V = V.getOperand(0);
  9861. return V;
  9862. }
  9863. SDValue llvm::peekThroughOneUseBitcasts(SDValue V) {
  9864. while (V.getOpcode() == ISD::BITCAST && V.getOperand(0).hasOneUse())
  9865. V = V.getOperand(0);
  9866. return V;
  9867. }
  9868. SDValue llvm::peekThroughExtractSubvectors(SDValue V) {
  9869. while (V.getOpcode() == ISD::EXTRACT_SUBVECTOR)
  9870. V = V.getOperand(0);
  9871. return V;
  9872. }
  9873. bool llvm::isBitwiseNot(SDValue V, bool AllowUndefs) {
  9874. if (V.getOpcode() != ISD::XOR)
  9875. return false;
  9876. V = peekThroughBitcasts(V.getOperand(1));
  9877. unsigned NumBits = V.getScalarValueSizeInBits();
  9878. ConstantSDNode *C =
  9879. isConstOrConstSplat(V, AllowUndefs, /*AllowTruncation*/ true);
  9880. return C && (C->getAPIntValue().countTrailingOnes() >= NumBits);
  9881. }
  9882. ConstantSDNode *llvm::isConstOrConstSplat(SDValue N, bool AllowUndefs,
  9883. bool AllowTruncation) {
  9884. EVT VT = N.getValueType();
  9885. APInt DemandedElts = VT.isFixedLengthVector()
  9886. ? APInt::getAllOnes(VT.getVectorMinNumElements())
  9887. : APInt(1, 1);
  9888. return isConstOrConstSplat(N, DemandedElts, AllowUndefs, AllowTruncation);
  9889. }
  9890. ConstantSDNode *llvm::isConstOrConstSplat(SDValue N, const APInt &DemandedElts,
  9891. bool AllowUndefs,
  9892. bool AllowTruncation) {
  9893. if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
  9894. return CN;
  9895. // SplatVectors can truncate their operands. Ignore that case here unless
  9896. // AllowTruncation is set.
  9897. if (N->getOpcode() == ISD::SPLAT_VECTOR) {
  9898. EVT VecEltVT = N->getValueType(0).getVectorElementType();
  9899. if (auto *CN = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
  9900. EVT CVT = CN->getValueType(0);
  9901. assert(CVT.bitsGE(VecEltVT) && "Illegal splat_vector element extension");
  9902. if (AllowTruncation || CVT == VecEltVT)
  9903. return CN;
  9904. }
  9905. }
  9906. if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
  9907. BitVector UndefElements;
  9908. ConstantSDNode *CN = BV->getConstantSplatNode(DemandedElts, &UndefElements);
  9909. // BuildVectors can truncate their operands. Ignore that case here unless
  9910. // AllowTruncation is set.
  9911. // TODO: Look into whether we should allow UndefElements in non-DemandedElts
  9912. if (CN && (UndefElements.none() || AllowUndefs)) {
  9913. EVT CVT = CN->getValueType(0);
  9914. EVT NSVT = N.getValueType().getScalarType();
  9915. assert(CVT.bitsGE(NSVT) && "Illegal build vector element extension");
  9916. if (AllowTruncation || (CVT == NSVT))
  9917. return CN;
  9918. }
  9919. }
  9920. return nullptr;
  9921. }
  9922. ConstantFPSDNode *llvm::isConstOrConstSplatFP(SDValue N, bool AllowUndefs) {
  9923. EVT VT = N.getValueType();
  9924. APInt DemandedElts = VT.isFixedLengthVector()
  9925. ? APInt::getAllOnes(VT.getVectorMinNumElements())
  9926. : APInt(1, 1);
  9927. return isConstOrConstSplatFP(N, DemandedElts, AllowUndefs);
  9928. }
  9929. ConstantFPSDNode *llvm::isConstOrConstSplatFP(SDValue N,
  9930. const APInt &DemandedElts,
  9931. bool AllowUndefs) {
  9932. if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
  9933. return CN;
  9934. if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
  9935. BitVector UndefElements;
  9936. ConstantFPSDNode *CN =
  9937. BV->getConstantFPSplatNode(DemandedElts, &UndefElements);
  9938. // TODO: Look into whether we should allow UndefElements in non-DemandedElts
  9939. if (CN && (UndefElements.none() || AllowUndefs))
  9940. return CN;
  9941. }
  9942. if (N.getOpcode() == ISD::SPLAT_VECTOR)
  9943. if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N.getOperand(0)))
  9944. return CN;
  9945. return nullptr;
  9946. }
  9947. bool llvm::isNullOrNullSplat(SDValue N, bool AllowUndefs) {
  9948. // TODO: may want to use peekThroughBitcast() here.
  9949. ConstantSDNode *C =
  9950. isConstOrConstSplat(N, AllowUndefs, /*AllowTruncation=*/true);
  9951. return C && C->isZero();
  9952. }
  9953. bool llvm::isOneOrOneSplat(SDValue N, bool AllowUndefs) {
  9954. ConstantSDNode *C =
  9955. isConstOrConstSplat(N, AllowUndefs, /*AllowTruncation*/ true);
  9956. return C && C->isOne();
  9957. }
  9958. bool llvm::isAllOnesOrAllOnesSplat(SDValue N, bool AllowUndefs) {
  9959. N = peekThroughBitcasts(N);
  9960. unsigned BitWidth = N.getScalarValueSizeInBits();
  9961. ConstantSDNode *C = isConstOrConstSplat(N, AllowUndefs);
  9962. return C && C->isAllOnes() && C->getValueSizeInBits(0) == BitWidth;
  9963. }
  9964. HandleSDNode::~HandleSDNode() {
  9965. DropOperands();
  9966. }
  9967. GlobalAddressSDNode::GlobalAddressSDNode(unsigned Opc, unsigned Order,
  9968. const DebugLoc &DL,
  9969. const GlobalValue *GA, EVT VT,
  9970. int64_t o, unsigned TF)
  9971. : SDNode(Opc, Order, DL, getSDVTList(VT)), Offset(o), TargetFlags(TF) {
  9972. TheGlobal = GA;
  9973. }
  9974. AddrSpaceCastSDNode::AddrSpaceCastSDNode(unsigned Order, const DebugLoc &dl,
  9975. EVT VT, unsigned SrcAS,
  9976. unsigned DestAS)
  9977. : SDNode(ISD::ADDRSPACECAST, Order, dl, getSDVTList(VT)),
  9978. SrcAddrSpace(SrcAS), DestAddrSpace(DestAS) {}
  9979. MemSDNode::MemSDNode(unsigned Opc, unsigned Order, const DebugLoc &dl,
  9980. SDVTList VTs, EVT memvt, MachineMemOperand *mmo)
  9981. : SDNode(Opc, Order, dl, VTs), MemoryVT(memvt), MMO(mmo) {
  9982. MemSDNodeBits.IsVolatile = MMO->isVolatile();
  9983. MemSDNodeBits.IsNonTemporal = MMO->isNonTemporal();
  9984. MemSDNodeBits.IsDereferenceable = MMO->isDereferenceable();
  9985. MemSDNodeBits.IsInvariant = MMO->isInvariant();
  9986. // We check here that the size of the memory operand fits within the size of
  9987. // the MMO. This is because the MMO might indicate only a possible address
  9988. // range instead of specifying the affected memory addresses precisely.
  9989. // TODO: Make MachineMemOperands aware of scalable vectors.
  9990. assert(memvt.getStoreSize().getKnownMinValue() <= MMO->getSize() &&
  9991. "Size mismatch!");
  9992. }
  9993. /// Profile - Gather unique data for the node.
  9994. ///
  9995. void SDNode::Profile(FoldingSetNodeID &ID) const {
  9996. AddNodeIDNode(ID, this);
  9997. }
  9998. namespace {
  9999. struct EVTArray {
  10000. std::vector<EVT> VTs;
  10001. EVTArray() {
  10002. VTs.reserve(MVT::VALUETYPE_SIZE);
  10003. for (unsigned i = 0; i < MVT::VALUETYPE_SIZE; ++i)
  10004. VTs.push_back(MVT((MVT::SimpleValueType)i));
  10005. }
  10006. };
  10007. } // end anonymous namespace
  10008. /// getValueTypeList - Return a pointer to the specified value type.
  10009. ///
  10010. const EVT *SDNode::getValueTypeList(EVT VT) {
  10011. static std::set<EVT, EVT::compareRawBits> EVTs;
  10012. static EVTArray SimpleVTArray;
  10013. static sys::SmartMutex<true> VTMutex;
  10014. if (VT.isExtended()) {
  10015. sys::SmartScopedLock<true> Lock(VTMutex);
  10016. return &(*EVTs.insert(VT).first);
  10017. }
  10018. assert(VT.getSimpleVT() < MVT::VALUETYPE_SIZE && "Value type out of range!");
  10019. return &SimpleVTArray.VTs[VT.getSimpleVT().SimpleTy];
  10020. }
  10021. /// hasNUsesOfValue - Return true if there are exactly NUSES uses of the
  10022. /// indicated value. This method ignores uses of other values defined by this
  10023. /// operation.
  10024. bool SDNode::hasNUsesOfValue(unsigned NUses, unsigned Value) const {
  10025. assert(Value < getNumValues() && "Bad value!");
  10026. // TODO: Only iterate over uses of a given value of the node
  10027. for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) {
  10028. if (UI.getUse().getResNo() == Value) {
  10029. if (NUses == 0)
  10030. return false;
  10031. --NUses;
  10032. }
  10033. }
  10034. // Found exactly the right number of uses?
  10035. return NUses == 0;
  10036. }
  10037. /// hasAnyUseOfValue - Return true if there are any use of the indicated
  10038. /// value. This method ignores uses of other values defined by this operation.
  10039. bool SDNode::hasAnyUseOfValue(unsigned Value) const {
  10040. assert(Value < getNumValues() && "Bad value!");
  10041. for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI)
  10042. if (UI.getUse().getResNo() == Value)
  10043. return true;
  10044. return false;
  10045. }
  10046. /// isOnlyUserOf - Return true if this node is the only use of N.
  10047. bool SDNode::isOnlyUserOf(const SDNode *N) const {
  10048. bool Seen = false;
  10049. for (const SDNode *User : N->uses()) {
  10050. if (User == this)
  10051. Seen = true;
  10052. else
  10053. return false;
  10054. }
  10055. return Seen;
  10056. }
  10057. /// Return true if the only users of N are contained in Nodes.
  10058. bool SDNode::areOnlyUsersOf(ArrayRef<const SDNode *> Nodes, const SDNode *N) {
  10059. bool Seen = false;
  10060. for (const SDNode *User : N->uses()) {
  10061. if (llvm::is_contained(Nodes, User))
  10062. Seen = true;
  10063. else
  10064. return false;
  10065. }
  10066. return Seen;
  10067. }
  10068. /// isOperand - Return true if this node is an operand of N.
  10069. bool SDValue::isOperandOf(const SDNode *N) const {
  10070. return is_contained(N->op_values(), *this);
  10071. }
  10072. bool SDNode::isOperandOf(const SDNode *N) const {
  10073. return any_of(N->op_values(),
  10074. [this](SDValue Op) { return this == Op.getNode(); });
  10075. }
  10076. /// reachesChainWithoutSideEffects - Return true if this operand (which must
  10077. /// be a chain) reaches the specified operand without crossing any
  10078. /// side-effecting instructions on any chain path. In practice, this looks
  10079. /// through token factors and non-volatile loads. In order to remain efficient,
  10080. /// this only looks a couple of nodes in, it does not do an exhaustive search.
  10081. ///
  10082. /// Note that we only need to examine chains when we're searching for
  10083. /// side-effects; SelectionDAG requires that all side-effects are represented
  10084. /// by chains, even if another operand would force a specific ordering. This
  10085. /// constraint is necessary to allow transformations like splitting loads.
  10086. bool SDValue::reachesChainWithoutSideEffects(SDValue Dest,
  10087. unsigned Depth) const {
  10088. if (*this == Dest) return true;
  10089. // Don't search too deeply, we just want to be able to see through
  10090. // TokenFactor's etc.
  10091. if (Depth == 0) return false;
  10092. // If this is a token factor, all inputs to the TF happen in parallel.
  10093. if (getOpcode() == ISD::TokenFactor) {
  10094. // First, try a shallow search.
  10095. if (is_contained((*this)->ops(), Dest)) {
  10096. // We found the chain we want as an operand of this TokenFactor.
  10097. // Essentially, we reach the chain without side-effects if we could
  10098. // serialize the TokenFactor into a simple chain of operations with
  10099. // Dest as the last operation. This is automatically true if the
  10100. // chain has one use: there are no other ordering constraints.
  10101. // If the chain has more than one use, we give up: some other
  10102. // use of Dest might force a side-effect between Dest and the current
  10103. // node.
  10104. if (Dest.hasOneUse())
  10105. return true;
  10106. }
  10107. // Next, try a deep search: check whether every operand of the TokenFactor
  10108. // reaches Dest.
  10109. return llvm::all_of((*this)->ops(), [=](SDValue Op) {
  10110. return Op.reachesChainWithoutSideEffects(Dest, Depth - 1);
  10111. });
  10112. }
  10113. // Loads don't have side effects, look through them.
  10114. if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(*this)) {
  10115. if (Ld->isUnordered())
  10116. return Ld->getChain().reachesChainWithoutSideEffects(Dest, Depth-1);
  10117. }
  10118. return false;
  10119. }
  10120. bool SDNode::hasPredecessor(const SDNode *N) const {
  10121. SmallPtrSet<const SDNode *, 32> Visited;
  10122. SmallVector<const SDNode *, 16> Worklist;
  10123. Worklist.push_back(this);
  10124. return hasPredecessorHelper(N, Visited, Worklist);
  10125. }
  10126. void SDNode::intersectFlagsWith(const SDNodeFlags Flags) {
  10127. this->Flags.intersectWith(Flags);
  10128. }
  10129. SDValue
  10130. SelectionDAG::matchBinOpReduction(SDNode *Extract, ISD::NodeType &BinOp,
  10131. ArrayRef<ISD::NodeType> CandidateBinOps,
  10132. bool AllowPartials) {
  10133. // The pattern must end in an extract from index 0.
  10134. if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
  10135. !isNullConstant(Extract->getOperand(1)))
  10136. return SDValue();
  10137. // Match against one of the candidate binary ops.
  10138. SDValue Op = Extract->getOperand(0);
  10139. if (llvm::none_of(CandidateBinOps, [Op](ISD::NodeType BinOp) {
  10140. return Op.getOpcode() == unsigned(BinOp);
  10141. }))
  10142. return SDValue();
  10143. // Floating-point reductions may require relaxed constraints on the final step
  10144. // of the reduction because they may reorder intermediate operations.
  10145. unsigned CandidateBinOp = Op.getOpcode();
  10146. if (Op.getValueType().isFloatingPoint()) {
  10147. SDNodeFlags Flags = Op->getFlags();
  10148. switch (CandidateBinOp) {
  10149. case ISD::FADD:
  10150. if (!Flags.hasNoSignedZeros() || !Flags.hasAllowReassociation())
  10151. return SDValue();
  10152. break;
  10153. default:
  10154. llvm_unreachable("Unhandled FP opcode for binop reduction");
  10155. }
  10156. }
  10157. // Matching failed - attempt to see if we did enough stages that a partial
  10158. // reduction from a subvector is possible.
  10159. auto PartialReduction = [&](SDValue Op, unsigned NumSubElts) {
  10160. if (!AllowPartials || !Op)
  10161. return SDValue();
  10162. EVT OpVT = Op.getValueType();
  10163. EVT OpSVT = OpVT.getScalarType();
  10164. EVT SubVT = EVT::getVectorVT(*getContext(), OpSVT, NumSubElts);
  10165. if (!TLI->isExtractSubvectorCheap(SubVT, OpVT, 0))
  10166. return SDValue();
  10167. BinOp = (ISD::NodeType)CandidateBinOp;
  10168. return getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(Op), SubVT, Op,
  10169. getVectorIdxConstant(0, SDLoc(Op)));
  10170. };
  10171. // At each stage, we're looking for something that looks like:
  10172. // %s = shufflevector <8 x i32> %op, <8 x i32> undef,
  10173. // <8 x i32> <i32 2, i32 3, i32 undef, i32 undef,
  10174. // i32 undef, i32 undef, i32 undef, i32 undef>
  10175. // %a = binop <8 x i32> %op, %s
  10176. // Where the mask changes according to the stage. E.g. for a 3-stage pyramid,
  10177. // we expect something like:
  10178. // <4,5,6,7,u,u,u,u>
  10179. // <2,3,u,u,u,u,u,u>
  10180. // <1,u,u,u,u,u,u,u>
  10181. // While a partial reduction match would be:
  10182. // <2,3,u,u,u,u,u,u>
  10183. // <1,u,u,u,u,u,u,u>
  10184. unsigned Stages = Log2_32(Op.getValueType().getVectorNumElements());
  10185. SDValue PrevOp;
  10186. for (unsigned i = 0; i < Stages; ++i) {
  10187. unsigned MaskEnd = (1 << i);
  10188. if (Op.getOpcode() != CandidateBinOp)
  10189. return PartialReduction(PrevOp, MaskEnd);
  10190. SDValue Op0 = Op.getOperand(0);
  10191. SDValue Op1 = Op.getOperand(1);
  10192. ShuffleVectorSDNode *Shuffle = dyn_cast<ShuffleVectorSDNode>(Op0);
  10193. if (Shuffle) {
  10194. Op = Op1;
  10195. } else {
  10196. Shuffle = dyn_cast<ShuffleVectorSDNode>(Op1);
  10197. Op = Op0;
  10198. }
  10199. // The first operand of the shuffle should be the same as the other operand
  10200. // of the binop.
  10201. if (!Shuffle || Shuffle->getOperand(0) != Op)
  10202. return PartialReduction(PrevOp, MaskEnd);
  10203. // Verify the shuffle has the expected (at this stage of the pyramid) mask.
  10204. for (int Index = 0; Index < (int)MaskEnd; ++Index)
  10205. if (Shuffle->getMaskElt(Index) != (int)(MaskEnd + Index))
  10206. return PartialReduction(PrevOp, MaskEnd);
  10207. PrevOp = Op;
  10208. }
  10209. // Handle subvector reductions, which tend to appear after the shuffle
  10210. // reduction stages.
  10211. while (Op.getOpcode() == CandidateBinOp) {
  10212. unsigned NumElts = Op.getValueType().getVectorNumElements();
  10213. SDValue Op0 = Op.getOperand(0);
  10214. SDValue Op1 = Op.getOperand(1);
  10215. if (Op0.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
  10216. Op1.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
  10217. Op0.getOperand(0) != Op1.getOperand(0))
  10218. break;
  10219. SDValue Src = Op0.getOperand(0);
  10220. unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
  10221. if (NumSrcElts != (2 * NumElts))
  10222. break;
  10223. if (!(Op0.getConstantOperandAPInt(1) == 0 &&
  10224. Op1.getConstantOperandAPInt(1) == NumElts) &&
  10225. !(Op1.getConstantOperandAPInt(1) == 0 &&
  10226. Op0.getConstantOperandAPInt(1) == NumElts))
  10227. break;
  10228. Op = Src;
  10229. }
  10230. BinOp = (ISD::NodeType)CandidateBinOp;
  10231. return Op;
  10232. }
  10233. SDValue SelectionDAG::UnrollVectorOp(SDNode *N, unsigned ResNE) {
  10234. assert(N->getNumValues() == 1 &&
  10235. "Can't unroll a vector with multiple results!");
  10236. EVT VT = N->getValueType(0);
  10237. unsigned NE = VT.getVectorNumElements();
  10238. EVT EltVT = VT.getVectorElementType();
  10239. SDLoc dl(N);
  10240. SmallVector<SDValue, 8> Scalars;
  10241. SmallVector<SDValue, 4> Operands(N->getNumOperands());
  10242. // If ResNE is 0, fully unroll the vector op.
  10243. if (ResNE == 0)
  10244. ResNE = NE;
  10245. else if (NE > ResNE)
  10246. NE = ResNE;
  10247. unsigned i;
  10248. for (i= 0; i != NE; ++i) {
  10249. for (unsigned j = 0, e = N->getNumOperands(); j != e; ++j) {
  10250. SDValue Operand = N->getOperand(j);
  10251. EVT OperandVT = Operand.getValueType();
  10252. if (OperandVT.isVector()) {
  10253. // A vector operand; extract a single element.
  10254. EVT OperandEltVT = OperandVT.getVectorElementType();
  10255. Operands[j] = getNode(ISD::EXTRACT_VECTOR_ELT, dl, OperandEltVT,
  10256. Operand, getVectorIdxConstant(i, dl));
  10257. } else {
  10258. // A scalar operand; just use it as is.
  10259. Operands[j] = Operand;
  10260. }
  10261. }
  10262. switch (N->getOpcode()) {
  10263. default: {
  10264. Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands,
  10265. N->getFlags()));
  10266. break;
  10267. }
  10268. case ISD::VSELECT:
  10269. Scalars.push_back(getNode(ISD::SELECT, dl, EltVT, Operands));
  10270. break;
  10271. case ISD::SHL:
  10272. case ISD::SRA:
  10273. case ISD::SRL:
  10274. case ISD::ROTL:
  10275. case ISD::ROTR:
  10276. Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands[0],
  10277. getShiftAmountOperand(Operands[0].getValueType(),
  10278. Operands[1])));
  10279. break;
  10280. case ISD::SIGN_EXTEND_INREG: {
  10281. EVT ExtVT = cast<VTSDNode>(Operands[1])->getVT().getVectorElementType();
  10282. Scalars.push_back(getNode(N->getOpcode(), dl, EltVT,
  10283. Operands[0],
  10284. getValueType(ExtVT)));
  10285. }
  10286. }
  10287. }
  10288. for (; i < ResNE; ++i)
  10289. Scalars.push_back(getUNDEF(EltVT));
  10290. EVT VecVT = EVT::getVectorVT(*getContext(), EltVT, ResNE);
  10291. return getBuildVector(VecVT, dl, Scalars);
  10292. }
  10293. std::pair<SDValue, SDValue> SelectionDAG::UnrollVectorOverflowOp(
  10294. SDNode *N, unsigned ResNE) {
  10295. unsigned Opcode = N->getOpcode();
  10296. assert((Opcode == ISD::UADDO || Opcode == ISD::SADDO ||
  10297. Opcode == ISD::USUBO || Opcode == ISD::SSUBO ||
  10298. Opcode == ISD::UMULO || Opcode == ISD::SMULO) &&
  10299. "Expected an overflow opcode");
  10300. EVT ResVT = N->getValueType(0);
  10301. EVT OvVT = N->getValueType(1);
  10302. EVT ResEltVT = ResVT.getVectorElementType();
  10303. EVT OvEltVT = OvVT.getVectorElementType();
  10304. SDLoc dl(N);
  10305. // If ResNE is 0, fully unroll the vector op.
  10306. unsigned NE = ResVT.getVectorNumElements();
  10307. if (ResNE == 0)
  10308. ResNE = NE;
  10309. else if (NE > ResNE)
  10310. NE = ResNE;
  10311. SmallVector<SDValue, 8> LHSScalars;
  10312. SmallVector<SDValue, 8> RHSScalars;
  10313. ExtractVectorElements(N->getOperand(0), LHSScalars, 0, NE);
  10314. ExtractVectorElements(N->getOperand(1), RHSScalars, 0, NE);
  10315. EVT SVT = TLI->getSetCCResultType(getDataLayout(), *getContext(), ResEltVT);
  10316. SDVTList VTs = getVTList(ResEltVT, SVT);
  10317. SmallVector<SDValue, 8> ResScalars;
  10318. SmallVector<SDValue, 8> OvScalars;
  10319. for (unsigned i = 0; i < NE; ++i) {
  10320. SDValue Res = getNode(Opcode, dl, VTs, LHSScalars[i], RHSScalars[i]);
  10321. SDValue Ov =
  10322. getSelect(dl, OvEltVT, Res.getValue(1),
  10323. getBoolConstant(true, dl, OvEltVT, ResVT),
  10324. getConstant(0, dl, OvEltVT));
  10325. ResScalars.push_back(Res);
  10326. OvScalars.push_back(Ov);
  10327. }
  10328. ResScalars.append(ResNE - NE, getUNDEF(ResEltVT));
  10329. OvScalars.append(ResNE - NE, getUNDEF(OvEltVT));
  10330. EVT NewResVT = EVT::getVectorVT(*getContext(), ResEltVT, ResNE);
  10331. EVT NewOvVT = EVT::getVectorVT(*getContext(), OvEltVT, ResNE);
  10332. return std::make_pair(getBuildVector(NewResVT, dl, ResScalars),
  10333. getBuildVector(NewOvVT, dl, OvScalars));
  10334. }
  10335. bool SelectionDAG::areNonVolatileConsecutiveLoads(LoadSDNode *LD,
  10336. LoadSDNode *Base,
  10337. unsigned Bytes,
  10338. int Dist) const {
  10339. if (LD->isVolatile() || Base->isVolatile())
  10340. return false;
  10341. // TODO: probably too restrictive for atomics, revisit
  10342. if (!LD->isSimple())
  10343. return false;
  10344. if (LD->isIndexed() || Base->isIndexed())
  10345. return false;
  10346. if (LD->getChain() != Base->getChain())
  10347. return false;
  10348. EVT VT = LD->getMemoryVT();
  10349. if (VT.getSizeInBits() / 8 != Bytes)
  10350. return false;
  10351. auto BaseLocDecomp = BaseIndexOffset::match(Base, *this);
  10352. auto LocDecomp = BaseIndexOffset::match(LD, *this);
  10353. int64_t Offset = 0;
  10354. if (BaseLocDecomp.equalBaseIndex(LocDecomp, *this, Offset))
  10355. return (Dist * Bytes == Offset);
  10356. return false;
  10357. }
  10358. /// InferPtrAlignment - Infer alignment of a load / store address. Return
  10359. /// std::nullopt if it cannot be inferred.
  10360. MaybeAlign SelectionDAG::InferPtrAlign(SDValue Ptr) const {
  10361. // If this is a GlobalAddress + cst, return the alignment.
  10362. const GlobalValue *GV = nullptr;
  10363. int64_t GVOffset = 0;
  10364. if (TLI->isGAPlusOffset(Ptr.getNode(), GV, GVOffset)) {
  10365. unsigned PtrWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType());
  10366. KnownBits Known(PtrWidth);
  10367. llvm::computeKnownBits(GV, Known, getDataLayout());
  10368. unsigned AlignBits = Known.countMinTrailingZeros();
  10369. if (AlignBits)
  10370. return commonAlignment(Align(1ull << std::min(31U, AlignBits)), GVOffset);
  10371. }
  10372. // If this is a direct reference to a stack slot, use information about the
  10373. // stack slot's alignment.
  10374. int FrameIdx = INT_MIN;
  10375. int64_t FrameOffset = 0;
  10376. if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr)) {
  10377. FrameIdx = FI->getIndex();
  10378. } else if (isBaseWithConstantOffset(Ptr) &&
  10379. isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
  10380. // Handle FI+Cst
  10381. FrameIdx = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
  10382. FrameOffset = Ptr.getConstantOperandVal(1);
  10383. }
  10384. if (FrameIdx != INT_MIN) {
  10385. const MachineFrameInfo &MFI = getMachineFunction().getFrameInfo();
  10386. return commonAlignment(MFI.getObjectAlign(FrameIdx), FrameOffset);
  10387. }
  10388. return std::nullopt;
  10389. }
  10390. /// GetSplitDestVTs - Compute the VTs needed for the low/hi parts of a type
  10391. /// which is split (or expanded) into two not necessarily identical pieces.
  10392. std::pair<EVT, EVT> SelectionDAG::GetSplitDestVTs(const EVT &VT) const {
  10393. // Currently all types are split in half.
  10394. EVT LoVT, HiVT;
  10395. if (!VT.isVector())
  10396. LoVT = HiVT = TLI->getTypeToTransformTo(*getContext(), VT);
  10397. else
  10398. LoVT = HiVT = VT.getHalfNumVectorElementsVT(*getContext());
  10399. return std::make_pair(LoVT, HiVT);
  10400. }
  10401. /// GetDependentSplitDestVTs - Compute the VTs needed for the low/hi parts of a
  10402. /// type, dependent on an enveloping VT that has been split into two identical
  10403. /// pieces. Sets the HiIsEmpty flag when hi type has zero storage size.
  10404. std::pair<EVT, EVT>
  10405. SelectionDAG::GetDependentSplitDestVTs(const EVT &VT, const EVT &EnvVT,
  10406. bool *HiIsEmpty) const {
  10407. EVT EltTp = VT.getVectorElementType();
  10408. // Examples:
  10409. // custom VL=8 with enveloping VL=8/8 yields 8/0 (hi empty)
  10410. // custom VL=9 with enveloping VL=8/8 yields 8/1
  10411. // custom VL=10 with enveloping VL=8/8 yields 8/2
  10412. // etc.
  10413. ElementCount VTNumElts = VT.getVectorElementCount();
  10414. ElementCount EnvNumElts = EnvVT.getVectorElementCount();
  10415. assert(VTNumElts.isScalable() == EnvNumElts.isScalable() &&
  10416. "Mixing fixed width and scalable vectors when enveloping a type");
  10417. EVT LoVT, HiVT;
  10418. if (VTNumElts.getKnownMinValue() > EnvNumElts.getKnownMinValue()) {
  10419. LoVT = EVT::getVectorVT(*getContext(), EltTp, EnvNumElts);
  10420. HiVT = EVT::getVectorVT(*getContext(), EltTp, VTNumElts - EnvNumElts);
  10421. *HiIsEmpty = false;
  10422. } else {
  10423. // Flag that hi type has zero storage size, but return split envelop type
  10424. // (this would be easier if vector types with zero elements were allowed).
  10425. LoVT = EVT::getVectorVT(*getContext(), EltTp, VTNumElts);
  10426. HiVT = EVT::getVectorVT(*getContext(), EltTp, EnvNumElts);
  10427. *HiIsEmpty = true;
  10428. }
  10429. return std::make_pair(LoVT, HiVT);
  10430. }
  10431. /// SplitVector - Split the vector with EXTRACT_SUBVECTOR and return the
  10432. /// low/high part.
  10433. std::pair<SDValue, SDValue>
  10434. SelectionDAG::SplitVector(const SDValue &N, const SDLoc &DL, const EVT &LoVT,
  10435. const EVT &HiVT) {
  10436. assert(LoVT.isScalableVector() == HiVT.isScalableVector() &&
  10437. LoVT.isScalableVector() == N.getValueType().isScalableVector() &&
  10438. "Splitting vector with an invalid mixture of fixed and scalable "
  10439. "vector types");
  10440. assert(LoVT.getVectorMinNumElements() + HiVT.getVectorMinNumElements() <=
  10441. N.getValueType().getVectorMinNumElements() &&
  10442. "More vector elements requested than available!");
  10443. SDValue Lo, Hi;
  10444. Lo =
  10445. getNode(ISD::EXTRACT_SUBVECTOR, DL, LoVT, N, getVectorIdxConstant(0, DL));
  10446. // For scalable vectors it is safe to use LoVT.getVectorMinNumElements()
  10447. // (rather than having to use ElementCount), because EXTRACT_SUBVECTOR scales
  10448. // IDX with the runtime scaling factor of the result vector type. For
  10449. // fixed-width result vectors, that runtime scaling factor is 1.
  10450. Hi = getNode(ISD::EXTRACT_SUBVECTOR, DL, HiVT, N,
  10451. getVectorIdxConstant(LoVT.getVectorMinNumElements(), DL));
  10452. return std::make_pair(Lo, Hi);
  10453. }
  10454. std::pair<SDValue, SDValue> SelectionDAG::SplitEVL(SDValue N, EVT VecVT,
  10455. const SDLoc &DL) {
  10456. // Split the vector length parameter.
  10457. // %evl -> umin(%evl, %halfnumelts) and usubsat(%evl - %halfnumelts).
  10458. EVT VT = N.getValueType();
  10459. assert(VecVT.getVectorElementCount().isKnownEven() &&
  10460. "Expecting the mask to be an evenly-sized vector");
  10461. unsigned HalfMinNumElts = VecVT.getVectorMinNumElements() / 2;
  10462. SDValue HalfNumElts =
  10463. VecVT.isFixedLengthVector()
  10464. ? getConstant(HalfMinNumElts, DL, VT)
  10465. : getVScale(DL, VT, APInt(VT.getScalarSizeInBits(), HalfMinNumElts));
  10466. SDValue Lo = getNode(ISD::UMIN, DL, VT, N, HalfNumElts);
  10467. SDValue Hi = getNode(ISD::USUBSAT, DL, VT, N, HalfNumElts);
  10468. return std::make_pair(Lo, Hi);
  10469. }
  10470. /// Widen the vector up to the next power of two using INSERT_SUBVECTOR.
  10471. SDValue SelectionDAG::WidenVector(const SDValue &N, const SDLoc &DL) {
  10472. EVT VT = N.getValueType();
  10473. EVT WideVT = EVT::getVectorVT(*getContext(), VT.getVectorElementType(),
  10474. NextPowerOf2(VT.getVectorNumElements()));
  10475. return getNode(ISD::INSERT_SUBVECTOR, DL, WideVT, getUNDEF(WideVT), N,
  10476. getVectorIdxConstant(0, DL));
  10477. }
  10478. void SelectionDAG::ExtractVectorElements(SDValue Op,
  10479. SmallVectorImpl<SDValue> &Args,
  10480. unsigned Start, unsigned Count,
  10481. EVT EltVT) {
  10482. EVT VT = Op.getValueType();
  10483. if (Count == 0)
  10484. Count = VT.getVectorNumElements();
  10485. if (EltVT == EVT())
  10486. EltVT = VT.getVectorElementType();
  10487. SDLoc SL(Op);
  10488. for (unsigned i = Start, e = Start + Count; i != e; ++i) {
  10489. Args.push_back(getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Op,
  10490. getVectorIdxConstant(i, SL)));
  10491. }
  10492. }
  10493. // getAddressSpace - Return the address space this GlobalAddress belongs to.
  10494. unsigned GlobalAddressSDNode::getAddressSpace() const {
  10495. return getGlobal()->getType()->getAddressSpace();
  10496. }
  10497. Type *ConstantPoolSDNode::getType() const {
  10498. if (isMachineConstantPoolEntry())
  10499. return Val.MachineCPVal->getType();
  10500. return Val.ConstVal->getType();
  10501. }
  10502. bool BuildVectorSDNode::isConstantSplat(APInt &SplatValue, APInt &SplatUndef,
  10503. unsigned &SplatBitSize,
  10504. bool &HasAnyUndefs,
  10505. unsigned MinSplatBits,
  10506. bool IsBigEndian) const {
  10507. EVT VT = getValueType(0);
  10508. assert(VT.isVector() && "Expected a vector type");
  10509. unsigned VecWidth = VT.getSizeInBits();
  10510. if (MinSplatBits > VecWidth)
  10511. return false;
  10512. // FIXME: The widths are based on this node's type, but build vectors can
  10513. // truncate their operands.
  10514. SplatValue = APInt(VecWidth, 0);
  10515. SplatUndef = APInt(VecWidth, 0);
  10516. // Get the bits. Bits with undefined values (when the corresponding element
  10517. // of the vector is an ISD::UNDEF value) are set in SplatUndef and cleared
  10518. // in SplatValue. If any of the values are not constant, give up and return
  10519. // false.
  10520. unsigned int NumOps = getNumOperands();
  10521. assert(NumOps > 0 && "isConstantSplat has 0-size build vector");
  10522. unsigned EltWidth = VT.getScalarSizeInBits();
  10523. for (unsigned j = 0; j < NumOps; ++j) {
  10524. unsigned i = IsBigEndian ? NumOps - 1 - j : j;
  10525. SDValue OpVal = getOperand(i);
  10526. unsigned BitPos = j * EltWidth;
  10527. if (OpVal.isUndef())
  10528. SplatUndef.setBits(BitPos, BitPos + EltWidth);
  10529. else if (auto *CN = dyn_cast<ConstantSDNode>(OpVal))
  10530. SplatValue.insertBits(CN->getAPIntValue().zextOrTrunc(EltWidth), BitPos);
  10531. else if (auto *CN = dyn_cast<ConstantFPSDNode>(OpVal))
  10532. SplatValue.insertBits(CN->getValueAPF().bitcastToAPInt(), BitPos);
  10533. else
  10534. return false;
  10535. }
  10536. // The build_vector is all constants or undefs. Find the smallest element
  10537. // size that splats the vector.
  10538. HasAnyUndefs = (SplatUndef != 0);
  10539. // FIXME: This does not work for vectors with elements less than 8 bits.
  10540. while (VecWidth > 8) {
  10541. unsigned HalfSize = VecWidth / 2;
  10542. APInt HighValue = SplatValue.extractBits(HalfSize, HalfSize);
  10543. APInt LowValue = SplatValue.extractBits(HalfSize, 0);
  10544. APInt HighUndef = SplatUndef.extractBits(HalfSize, HalfSize);
  10545. APInt LowUndef = SplatUndef.extractBits(HalfSize, 0);
  10546. // If the two halves do not match (ignoring undef bits), stop here.
  10547. if ((HighValue & ~LowUndef) != (LowValue & ~HighUndef) ||
  10548. MinSplatBits > HalfSize)
  10549. break;
  10550. SplatValue = HighValue | LowValue;
  10551. SplatUndef = HighUndef & LowUndef;
  10552. VecWidth = HalfSize;
  10553. }
  10554. SplatBitSize = VecWidth;
  10555. return true;
  10556. }
  10557. SDValue BuildVectorSDNode::getSplatValue(const APInt &DemandedElts,
  10558. BitVector *UndefElements) const {
  10559. unsigned NumOps = getNumOperands();
  10560. if (UndefElements) {
  10561. UndefElements->clear();
  10562. UndefElements->resize(NumOps);
  10563. }
  10564. assert(NumOps == DemandedElts.getBitWidth() && "Unexpected vector size");
  10565. if (!DemandedElts)
  10566. return SDValue();
  10567. SDValue Splatted;
  10568. for (unsigned i = 0; i != NumOps; ++i) {
  10569. if (!DemandedElts[i])
  10570. continue;
  10571. SDValue Op = getOperand(i);
  10572. if (Op.isUndef()) {
  10573. if (UndefElements)
  10574. (*UndefElements)[i] = true;
  10575. } else if (!Splatted) {
  10576. Splatted = Op;
  10577. } else if (Splatted != Op) {
  10578. return SDValue();
  10579. }
  10580. }
  10581. if (!Splatted) {
  10582. unsigned FirstDemandedIdx = DemandedElts.countTrailingZeros();
  10583. assert(getOperand(FirstDemandedIdx).isUndef() &&
  10584. "Can only have a splat without a constant for all undefs.");
  10585. return getOperand(FirstDemandedIdx);
  10586. }
  10587. return Splatted;
  10588. }
  10589. SDValue BuildVectorSDNode::getSplatValue(BitVector *UndefElements) const {
  10590. APInt DemandedElts = APInt::getAllOnes(getNumOperands());
  10591. return getSplatValue(DemandedElts, UndefElements);
  10592. }
  10593. bool BuildVectorSDNode::getRepeatedSequence(const APInt &DemandedElts,
  10594. SmallVectorImpl<SDValue> &Sequence,
  10595. BitVector *UndefElements) const {
  10596. unsigned NumOps = getNumOperands();
  10597. Sequence.clear();
  10598. if (UndefElements) {
  10599. UndefElements->clear();
  10600. UndefElements->resize(NumOps);
  10601. }
  10602. assert(NumOps == DemandedElts.getBitWidth() && "Unexpected vector size");
  10603. if (!DemandedElts || NumOps < 2 || !isPowerOf2_32(NumOps))
  10604. return false;
  10605. // Set the undefs even if we don't find a sequence (like getSplatValue).
  10606. if (UndefElements)
  10607. for (unsigned I = 0; I != NumOps; ++I)
  10608. if (DemandedElts[I] && getOperand(I).isUndef())
  10609. (*UndefElements)[I] = true;
  10610. // Iteratively widen the sequence length looking for repetitions.
  10611. for (unsigned SeqLen = 1; SeqLen < NumOps; SeqLen *= 2) {
  10612. Sequence.append(SeqLen, SDValue());
  10613. for (unsigned I = 0; I != NumOps; ++I) {
  10614. if (!DemandedElts[I])
  10615. continue;
  10616. SDValue &SeqOp = Sequence[I % SeqLen];
  10617. SDValue Op = getOperand(I);
  10618. if (Op.isUndef()) {
  10619. if (!SeqOp)
  10620. SeqOp = Op;
  10621. continue;
  10622. }
  10623. if (SeqOp && !SeqOp.isUndef() && SeqOp != Op) {
  10624. Sequence.clear();
  10625. break;
  10626. }
  10627. SeqOp = Op;
  10628. }
  10629. if (!Sequence.empty())
  10630. return true;
  10631. }
  10632. assert(Sequence.empty() && "Failed to empty non-repeating sequence pattern");
  10633. return false;
  10634. }
  10635. bool BuildVectorSDNode::getRepeatedSequence(SmallVectorImpl<SDValue> &Sequence,
  10636. BitVector *UndefElements) const {
  10637. APInt DemandedElts = APInt::getAllOnes(getNumOperands());
  10638. return getRepeatedSequence(DemandedElts, Sequence, UndefElements);
  10639. }
  10640. ConstantSDNode *
  10641. BuildVectorSDNode::getConstantSplatNode(const APInt &DemandedElts,
  10642. BitVector *UndefElements) const {
  10643. return dyn_cast_or_null<ConstantSDNode>(
  10644. getSplatValue(DemandedElts, UndefElements));
  10645. }
  10646. ConstantSDNode *
  10647. BuildVectorSDNode::getConstantSplatNode(BitVector *UndefElements) const {
  10648. return dyn_cast_or_null<ConstantSDNode>(getSplatValue(UndefElements));
  10649. }
  10650. ConstantFPSDNode *
  10651. BuildVectorSDNode::getConstantFPSplatNode(const APInt &DemandedElts,
  10652. BitVector *UndefElements) const {
  10653. return dyn_cast_or_null<ConstantFPSDNode>(
  10654. getSplatValue(DemandedElts, UndefElements));
  10655. }
  10656. ConstantFPSDNode *
  10657. BuildVectorSDNode::getConstantFPSplatNode(BitVector *UndefElements) const {
  10658. return dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements));
  10659. }
  10660. int32_t
  10661. BuildVectorSDNode::getConstantFPSplatPow2ToLog2Int(BitVector *UndefElements,
  10662. uint32_t BitWidth) const {
  10663. if (ConstantFPSDNode *CN =
  10664. dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements))) {
  10665. bool IsExact;
  10666. APSInt IntVal(BitWidth);
  10667. const APFloat &APF = CN->getValueAPF();
  10668. if (APF.convertToInteger(IntVal, APFloat::rmTowardZero, &IsExact) !=
  10669. APFloat::opOK ||
  10670. !IsExact)
  10671. return -1;
  10672. return IntVal.exactLogBase2();
  10673. }
  10674. return -1;
  10675. }
  10676. bool BuildVectorSDNode::getConstantRawBits(
  10677. bool IsLittleEndian, unsigned DstEltSizeInBits,
  10678. SmallVectorImpl<APInt> &RawBitElements, BitVector &UndefElements) const {
  10679. // Early-out if this contains anything but Undef/Constant/ConstantFP.
  10680. if (!isConstant())
  10681. return false;
  10682. unsigned NumSrcOps = getNumOperands();
  10683. unsigned SrcEltSizeInBits = getValueType(0).getScalarSizeInBits();
  10684. assert(((NumSrcOps * SrcEltSizeInBits) % DstEltSizeInBits) == 0 &&
  10685. "Invalid bitcast scale");
  10686. // Extract raw src bits.
  10687. SmallVector<APInt> SrcBitElements(NumSrcOps,
  10688. APInt::getNullValue(SrcEltSizeInBits));
  10689. BitVector SrcUndeElements(NumSrcOps, false);
  10690. for (unsigned I = 0; I != NumSrcOps; ++I) {
  10691. SDValue Op = getOperand(I);
  10692. if (Op.isUndef()) {
  10693. SrcUndeElements.set(I);
  10694. continue;
  10695. }
  10696. auto *CInt = dyn_cast<ConstantSDNode>(Op);
  10697. auto *CFP = dyn_cast<ConstantFPSDNode>(Op);
  10698. assert((CInt || CFP) && "Unknown constant");
  10699. SrcBitElements[I] = CInt ? CInt->getAPIntValue().trunc(SrcEltSizeInBits)
  10700. : CFP->getValueAPF().bitcastToAPInt();
  10701. }
  10702. // Recast to dst width.
  10703. recastRawBits(IsLittleEndian, DstEltSizeInBits, RawBitElements,
  10704. SrcBitElements, UndefElements, SrcUndeElements);
  10705. return true;
  10706. }
  10707. void BuildVectorSDNode::recastRawBits(bool IsLittleEndian,
  10708. unsigned DstEltSizeInBits,
  10709. SmallVectorImpl<APInt> &DstBitElements,
  10710. ArrayRef<APInt> SrcBitElements,
  10711. BitVector &DstUndefElements,
  10712. const BitVector &SrcUndefElements) {
  10713. unsigned NumSrcOps = SrcBitElements.size();
  10714. unsigned SrcEltSizeInBits = SrcBitElements[0].getBitWidth();
  10715. assert(((NumSrcOps * SrcEltSizeInBits) % DstEltSizeInBits) == 0 &&
  10716. "Invalid bitcast scale");
  10717. assert(NumSrcOps == SrcUndefElements.size() &&
  10718. "Vector size mismatch");
  10719. unsigned NumDstOps = (NumSrcOps * SrcEltSizeInBits) / DstEltSizeInBits;
  10720. DstUndefElements.clear();
  10721. DstUndefElements.resize(NumDstOps, false);
  10722. DstBitElements.assign(NumDstOps, APInt::getNullValue(DstEltSizeInBits));
  10723. // Concatenate src elements constant bits together into dst element.
  10724. if (SrcEltSizeInBits <= DstEltSizeInBits) {
  10725. unsigned Scale = DstEltSizeInBits / SrcEltSizeInBits;
  10726. for (unsigned I = 0; I != NumDstOps; ++I) {
  10727. DstUndefElements.set(I);
  10728. APInt &DstBits = DstBitElements[I];
  10729. for (unsigned J = 0; J != Scale; ++J) {
  10730. unsigned Idx = (I * Scale) + (IsLittleEndian ? J : (Scale - J - 1));
  10731. if (SrcUndefElements[Idx])
  10732. continue;
  10733. DstUndefElements.reset(I);
  10734. const APInt &SrcBits = SrcBitElements[Idx];
  10735. assert(SrcBits.getBitWidth() == SrcEltSizeInBits &&
  10736. "Illegal constant bitwidths");
  10737. DstBits.insertBits(SrcBits, J * SrcEltSizeInBits);
  10738. }
  10739. }
  10740. return;
  10741. }
  10742. // Split src element constant bits into dst elements.
  10743. unsigned Scale = SrcEltSizeInBits / DstEltSizeInBits;
  10744. for (unsigned I = 0; I != NumSrcOps; ++I) {
  10745. if (SrcUndefElements[I]) {
  10746. DstUndefElements.set(I * Scale, (I + 1) * Scale);
  10747. continue;
  10748. }
  10749. const APInt &SrcBits = SrcBitElements[I];
  10750. for (unsigned J = 0; J != Scale; ++J) {
  10751. unsigned Idx = (I * Scale) + (IsLittleEndian ? J : (Scale - J - 1));
  10752. APInt &DstBits = DstBitElements[Idx];
  10753. DstBits = SrcBits.extractBits(DstEltSizeInBits, J * DstEltSizeInBits);
  10754. }
  10755. }
  10756. }
  10757. bool BuildVectorSDNode::isConstant() const {
  10758. for (const SDValue &Op : op_values()) {
  10759. unsigned Opc = Op.getOpcode();
  10760. if (Opc != ISD::UNDEF && Opc != ISD::Constant && Opc != ISD::ConstantFP)
  10761. return false;
  10762. }
  10763. return true;
  10764. }
  10765. std::optional<std::pair<APInt, APInt>>
  10766. BuildVectorSDNode::isConstantSequence() const {
  10767. unsigned NumOps = getNumOperands();
  10768. if (NumOps < 2)
  10769. return std::nullopt;
  10770. if (!isa<ConstantSDNode>(getOperand(0)) ||
  10771. !isa<ConstantSDNode>(getOperand(1)))
  10772. return std::nullopt;
  10773. unsigned EltSize = getValueType(0).getScalarSizeInBits();
  10774. APInt Start = getConstantOperandAPInt(0).trunc(EltSize);
  10775. APInt Stride = getConstantOperandAPInt(1).trunc(EltSize) - Start;
  10776. if (Stride.isZero())
  10777. return std::nullopt;
  10778. for (unsigned i = 2; i < NumOps; ++i) {
  10779. if (!isa<ConstantSDNode>(getOperand(i)))
  10780. return std::nullopt;
  10781. APInt Val = getConstantOperandAPInt(i).trunc(EltSize);
  10782. if (Val != (Start + (Stride * i)))
  10783. return std::nullopt;
  10784. }
  10785. return std::make_pair(Start, Stride);
  10786. }
  10787. bool ShuffleVectorSDNode::isSplatMask(const int *Mask, EVT VT) {
  10788. // Find the first non-undef value in the shuffle mask.
  10789. unsigned i, e;
  10790. for (i = 0, e = VT.getVectorNumElements(); i != e && Mask[i] < 0; ++i)
  10791. /* search */;
  10792. // If all elements are undefined, this shuffle can be considered a splat
  10793. // (although it should eventually get simplified away completely).
  10794. if (i == e)
  10795. return true;
  10796. // Make sure all remaining elements are either undef or the same as the first
  10797. // non-undef value.
  10798. for (int Idx = Mask[i]; i != e; ++i)
  10799. if (Mask[i] >= 0 && Mask[i] != Idx)
  10800. return false;
  10801. return true;
  10802. }
  10803. // Returns the SDNode if it is a constant integer BuildVector
  10804. // or constant integer.
  10805. SDNode *SelectionDAG::isConstantIntBuildVectorOrConstantInt(SDValue N) const {
  10806. if (isa<ConstantSDNode>(N))
  10807. return N.getNode();
  10808. if (ISD::isBuildVectorOfConstantSDNodes(N.getNode()))
  10809. return N.getNode();
  10810. // Treat a GlobalAddress supporting constant offset folding as a
  10811. // constant integer.
  10812. if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N))
  10813. if (GA->getOpcode() == ISD::GlobalAddress &&
  10814. TLI->isOffsetFoldingLegal(GA))
  10815. return GA;
  10816. if ((N.getOpcode() == ISD::SPLAT_VECTOR) &&
  10817. isa<ConstantSDNode>(N.getOperand(0)))
  10818. return N.getNode();
  10819. return nullptr;
  10820. }
  10821. // Returns the SDNode if it is a constant float BuildVector
  10822. // or constant float.
  10823. SDNode *SelectionDAG::isConstantFPBuildVectorOrConstantFP(SDValue N) const {
  10824. if (isa<ConstantFPSDNode>(N))
  10825. return N.getNode();
  10826. if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode()))
  10827. return N.getNode();
  10828. if ((N.getOpcode() == ISD::SPLAT_VECTOR) &&
  10829. isa<ConstantFPSDNode>(N.getOperand(0)))
  10830. return N.getNode();
  10831. return nullptr;
  10832. }
  10833. void SelectionDAG::createOperands(SDNode *Node, ArrayRef<SDValue> Vals) {
  10834. assert(!Node->OperandList && "Node already has operands");
  10835. assert(SDNode::getMaxNumOperands() >= Vals.size() &&
  10836. "too many operands to fit into SDNode");
  10837. SDUse *Ops = OperandRecycler.allocate(
  10838. ArrayRecycler<SDUse>::Capacity::get(Vals.size()), OperandAllocator);
  10839. bool IsDivergent = false;
  10840. for (unsigned I = 0; I != Vals.size(); ++I) {
  10841. Ops[I].setUser(Node);
  10842. Ops[I].setInitial(Vals[I]);
  10843. if (Ops[I].Val.getValueType() != MVT::Other) // Skip Chain. It does not carry divergence.
  10844. IsDivergent |= Ops[I].getNode()->isDivergent();
  10845. }
  10846. Node->NumOperands = Vals.size();
  10847. Node->OperandList = Ops;
  10848. if (!TLI->isSDNodeAlwaysUniform(Node)) {
  10849. IsDivergent |= TLI->isSDNodeSourceOfDivergence(Node, FLI, DA);
  10850. Node->SDNodeBits.IsDivergent = IsDivergent;
  10851. }
  10852. checkForCycles(Node);
  10853. }
  10854. SDValue SelectionDAG::getTokenFactor(const SDLoc &DL,
  10855. SmallVectorImpl<SDValue> &Vals) {
  10856. size_t Limit = SDNode::getMaxNumOperands();
  10857. while (Vals.size() > Limit) {
  10858. unsigned SliceIdx = Vals.size() - Limit;
  10859. auto ExtractedTFs = ArrayRef<SDValue>(Vals).slice(SliceIdx, Limit);
  10860. SDValue NewTF = getNode(ISD::TokenFactor, DL, MVT::Other, ExtractedTFs);
  10861. Vals.erase(Vals.begin() + SliceIdx, Vals.end());
  10862. Vals.emplace_back(NewTF);
  10863. }
  10864. return getNode(ISD::TokenFactor, DL, MVT::Other, Vals);
  10865. }
  10866. SDValue SelectionDAG::getNeutralElement(unsigned Opcode, const SDLoc &DL,
  10867. EVT VT, SDNodeFlags Flags) {
  10868. switch (Opcode) {
  10869. default:
  10870. return SDValue();
  10871. case ISD::ADD:
  10872. case ISD::OR:
  10873. case ISD::XOR:
  10874. case ISD::UMAX:
  10875. return getConstant(0, DL, VT);
  10876. case ISD::MUL:
  10877. return getConstant(1, DL, VT);
  10878. case ISD::AND:
  10879. case ISD::UMIN:
  10880. return getAllOnesConstant(DL, VT);
  10881. case ISD::SMAX:
  10882. return getConstant(APInt::getSignedMinValue(VT.getSizeInBits()), DL, VT);
  10883. case ISD::SMIN:
  10884. return getConstant(APInt::getSignedMaxValue(VT.getSizeInBits()), DL, VT);
  10885. case ISD::FADD:
  10886. return getConstantFP(-0.0, DL, VT);
  10887. case ISD::FMUL:
  10888. return getConstantFP(1.0, DL, VT);
  10889. case ISD::FMINNUM:
  10890. case ISD::FMAXNUM: {
  10891. // Neutral element for fminnum is NaN, Inf or FLT_MAX, depending on FMF.
  10892. const fltSemantics &Semantics = EVTToAPFloatSemantics(VT);
  10893. APFloat NeutralAF = !Flags.hasNoNaNs() ? APFloat::getQNaN(Semantics) :
  10894. !Flags.hasNoInfs() ? APFloat::getInf(Semantics) :
  10895. APFloat::getLargest(Semantics);
  10896. if (Opcode == ISD::FMAXNUM)
  10897. NeutralAF.changeSign();
  10898. return getConstantFP(NeutralAF, DL, VT);
  10899. }
  10900. }
  10901. }
  10902. void SelectionDAG::copyExtraInfo(SDNode *From, SDNode *To) {
  10903. assert(From && To && "Invalid SDNode; empty source SDValue?");
  10904. auto I = SDEI.find(From);
  10905. if (I == SDEI.end())
  10906. return;
  10907. // Use of operator[] on the DenseMap may cause an insertion, which invalidates
  10908. // the iterator, hence the need to make a copy to prevent a use-after-free.
  10909. NodeExtraInfo Copy = I->second;
  10910. SDEI[To] = std::move(Copy);
  10911. }
  10912. #ifndef NDEBUG
  10913. static void checkForCyclesHelper(const SDNode *N,
  10914. SmallPtrSetImpl<const SDNode*> &Visited,
  10915. SmallPtrSetImpl<const SDNode*> &Checked,
  10916. const llvm::SelectionDAG *DAG) {
  10917. // If this node has already been checked, don't check it again.
  10918. if (Checked.count(N))
  10919. return;
  10920. // If a node has already been visited on this depth-first walk, reject it as
  10921. // a cycle.
  10922. if (!Visited.insert(N).second) {
  10923. errs() << "Detected cycle in SelectionDAG\n";
  10924. dbgs() << "Offending node:\n";
  10925. N->dumprFull(DAG); dbgs() << "\n";
  10926. abort();
  10927. }
  10928. for (const SDValue &Op : N->op_values())
  10929. checkForCyclesHelper(Op.getNode(), Visited, Checked, DAG);
  10930. Checked.insert(N);
  10931. Visited.erase(N);
  10932. }
  10933. #endif
  10934. void llvm::checkForCycles(const llvm::SDNode *N,
  10935. const llvm::SelectionDAG *DAG,
  10936. bool force) {
  10937. #ifndef NDEBUG
  10938. bool check = force;
  10939. #ifdef EXPENSIVE_CHECKS
  10940. check = true;
  10941. #endif // EXPENSIVE_CHECKS
  10942. if (check) {
  10943. assert(N && "Checking nonexistent SDNode");
  10944. SmallPtrSet<const SDNode*, 32> visited;
  10945. SmallPtrSet<const SDNode*, 32> checked;
  10946. checkForCyclesHelper(N, visited, checked, DAG);
  10947. }
  10948. #endif // !NDEBUG
  10949. }
  10950. void llvm::checkForCycles(const llvm::SelectionDAG *DAG, bool force) {
  10951. checkForCycles(DAG->getRoot().getNode(), DAG, force);
  10952. }