SelectionDAG.cpp 345 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498
  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/None.h"
  21. #include "llvm/ADT/STLExtras.h"
  22. #include "llvm/ADT/SmallPtrSet.h"
  23. #include "llvm/ADT/SmallVector.h"
  24. #include "llvm/ADT/Triple.h"
  25. #include "llvm/ADT/Twine.h"
  26. #include "llvm/Analysis/ValueTracking.h"
  27. #include "llvm/CodeGen/ISDOpcodes.h"
  28. #include "llvm/CodeGen/MachineBasicBlock.h"
  29. #include "llvm/CodeGen/MachineConstantPool.h"
  30. #include "llvm/CodeGen/MachineFrameInfo.h"
  31. #include "llvm/CodeGen/MachineFunction.h"
  32. #include "llvm/CodeGen/MachineMemOperand.h"
  33. #include "llvm/CodeGen/RuntimeLibcalls.h"
  34. #include "llvm/CodeGen/SelectionDAGAddressAnalysis.h"
  35. #include "llvm/CodeGen/SelectionDAGNodes.h"
  36. #include "llvm/CodeGen/SelectionDAGTargetInfo.h"
  37. #include "llvm/CodeGen/TargetLowering.h"
  38. #include "llvm/CodeGen/TargetRegisterInfo.h"
  39. #include "llvm/CodeGen/TargetSubtargetInfo.h"
  40. #include "llvm/CodeGen/ValueTypes.h"
  41. #include "llvm/IR/Constant.h"
  42. #include "llvm/IR/Constants.h"
  43. #include "llvm/IR/DataLayout.h"
  44. #include "llvm/IR/DebugInfoMetadata.h"
  45. #include "llvm/IR/DebugLoc.h"
  46. #include "llvm/IR/DerivedTypes.h"
  47. #include "llvm/IR/Function.h"
  48. #include "llvm/IR/GlobalValue.h"
  49. #include "llvm/IR/Metadata.h"
  50. #include "llvm/IR/Type.h"
  51. #include "llvm/IR/Value.h"
  52. #include "llvm/Support/Casting.h"
  53. #include "llvm/Support/CodeGen.h"
  54. #include "llvm/Support/Compiler.h"
  55. #include "llvm/Support/Debug.h"
  56. #include "llvm/Support/ErrorHandling.h"
  57. #include "llvm/Support/KnownBits.h"
  58. #include "llvm/Support/MachineValueType.h"
  59. #include "llvm/Support/ManagedStatic.h"
  60. #include "llvm/Support/MathExtras.h"
  61. #include "llvm/Support/Mutex.h"
  62. #include "llvm/Support/raw_ostream.h"
  63. #include "llvm/Target/TargetMachine.h"
  64. #include "llvm/Target/TargetOptions.h"
  65. #include <algorithm>
  66. #include <cassert>
  67. #include <cstdint>
  68. #include <cstdlib>
  69. #include <limits>
  70. #include <set>
  71. #include <string>
  72. #include <utility>
  73. #include <vector>
  74. using namespace llvm;
  75. /// makeVTList - Return an instance of the SDVTList struct initialized with the
  76. /// specified members.
  77. static SDVTList makeVTList(const EVT *VTs, unsigned NumVTs) {
  78. SDVTList Res = {VTs, NumVTs};
  79. return Res;
  80. }
  81. // Default null implementations of the callbacks.
  82. void SelectionDAG::DAGUpdateListener::NodeDeleted(SDNode*, SDNode*) {}
  83. void SelectionDAG::DAGUpdateListener::NodeUpdated(SDNode*) {}
  84. void SelectionDAG::DAGUpdateListener::NodeInserted(SDNode *) {}
  85. void SelectionDAG::DAGNodeDeletedListener::anchor() {}
  86. #define DEBUG_TYPE "selectiondag"
  87. static cl::opt<bool> EnableMemCpyDAGOpt("enable-memcpy-dag-opt",
  88. cl::Hidden, cl::init(true),
  89. cl::desc("Gang up loads and stores generated by inlining of memcpy"));
  90. static cl::opt<int> MaxLdStGlue("ldstmemcpy-glue-max",
  91. cl::desc("Number limit for gluing ld/st of memcpy."),
  92. cl::Hidden, cl::init(0));
  93. static void NewSDValueDbgMsg(SDValue V, StringRef Msg, SelectionDAG *G) {
  94. LLVM_DEBUG(dbgs() << Msg; V.getNode()->dump(G););
  95. }
  96. //===----------------------------------------------------------------------===//
  97. // ConstantFPSDNode Class
  98. //===----------------------------------------------------------------------===//
  99. /// isExactlyValue - We don't rely on operator== working on double values, as
  100. /// it returns true for things that are clearly not equal, like -0.0 and 0.0.
  101. /// As such, this method can be used to do an exact bit-for-bit comparison of
  102. /// two floating point values.
  103. bool ConstantFPSDNode::isExactlyValue(const APFloat& V) const {
  104. return getValueAPF().bitwiseIsEqual(V);
  105. }
  106. bool ConstantFPSDNode::isValueValidForType(EVT VT,
  107. const APFloat& Val) {
  108. assert(VT.isFloatingPoint() && "Can only convert between FP types");
  109. // convert modifies in place, so make a copy.
  110. APFloat Val2 = APFloat(Val);
  111. bool losesInfo;
  112. (void) Val2.convert(SelectionDAG::EVTToAPFloatSemantics(VT),
  113. APFloat::rmNearestTiesToEven,
  114. &losesInfo);
  115. return !losesInfo;
  116. }
  117. //===----------------------------------------------------------------------===//
  118. // ISD Namespace
  119. //===----------------------------------------------------------------------===//
  120. bool ISD::isConstantSplatVector(const SDNode *N, APInt &SplatVal) {
  121. auto *BV = dyn_cast<BuildVectorSDNode>(N);
  122. if (!BV)
  123. return false;
  124. APInt SplatUndef;
  125. unsigned SplatBitSize;
  126. bool HasUndefs;
  127. unsigned EltSize = N->getValueType(0).getVectorElementType().getSizeInBits();
  128. return BV->isConstantSplat(SplatVal, SplatUndef, SplatBitSize, HasUndefs,
  129. EltSize) &&
  130. EltSize == SplatBitSize;
  131. }
  132. // FIXME: AllOnes and AllZeros duplicate a lot of code. Could these be
  133. // specializations of the more general isConstantSplatVector()?
  134. bool ISD::isBuildVectorAllOnes(const SDNode *N) {
  135. // Look through a bit convert.
  136. while (N->getOpcode() == ISD::BITCAST)
  137. N = N->getOperand(0).getNode();
  138. if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
  139. unsigned i = 0, e = N->getNumOperands();
  140. // Skip over all of the undef values.
  141. while (i != e && N->getOperand(i).isUndef())
  142. ++i;
  143. // Do not accept an all-undef vector.
  144. if (i == e) return false;
  145. // Do not accept build_vectors that aren't all constants or which have non-~0
  146. // elements. We have to be a bit careful here, as the type of the constant
  147. // may not be the same as the type of the vector elements due to type
  148. // legalization (the elements are promoted to a legal type for the target and
  149. // a vector of a type may be legal when the base element type is not).
  150. // We only want to check enough bits to cover the vector elements, because
  151. // we care if the resultant vector is all ones, not whether the individual
  152. // constants are.
  153. SDValue NotZero = N->getOperand(i);
  154. unsigned EltSize = N->getValueType(0).getScalarSizeInBits();
  155. if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(NotZero)) {
  156. if (CN->getAPIntValue().countTrailingOnes() < EltSize)
  157. return false;
  158. } else if (ConstantFPSDNode *CFPN = dyn_cast<ConstantFPSDNode>(NotZero)) {
  159. if (CFPN->getValueAPF().bitcastToAPInt().countTrailingOnes() < EltSize)
  160. return false;
  161. } else
  162. return false;
  163. // Okay, we have at least one ~0 value, check to see if the rest match or are
  164. // undefs. Even with the above element type twiddling, this should be OK, as
  165. // the same type legalization should have applied to all the elements.
  166. for (++i; i != e; ++i)
  167. if (N->getOperand(i) != NotZero && !N->getOperand(i).isUndef())
  168. return false;
  169. return true;
  170. }
  171. bool ISD::isBuildVectorAllZeros(const SDNode *N) {
  172. // Look through a bit convert.
  173. while (N->getOpcode() == ISD::BITCAST)
  174. N = N->getOperand(0).getNode();
  175. if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
  176. bool IsAllUndef = true;
  177. for (const SDValue &Op : N->op_values()) {
  178. if (Op.isUndef())
  179. continue;
  180. IsAllUndef = false;
  181. // Do not accept build_vectors that aren't all constants or which have non-0
  182. // elements. We have to be a bit careful here, as the type of the constant
  183. // may not be the same as the type of the vector elements due to type
  184. // legalization (the elements are promoted to a legal type for the target
  185. // and a vector of a type may be legal when the base element type is not).
  186. // We only want to check enough bits to cover the vector elements, because
  187. // we care if the resultant vector is all zeros, not whether the individual
  188. // constants are.
  189. unsigned EltSize = N->getValueType(0).getScalarSizeInBits();
  190. if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Op)) {
  191. if (CN->getAPIntValue().countTrailingZeros() < EltSize)
  192. return false;
  193. } else if (ConstantFPSDNode *CFPN = dyn_cast<ConstantFPSDNode>(Op)) {
  194. if (CFPN->getValueAPF().bitcastToAPInt().countTrailingZeros() < EltSize)
  195. return false;
  196. } else
  197. return false;
  198. }
  199. // Do not accept an all-undef vector.
  200. if (IsAllUndef)
  201. return false;
  202. return true;
  203. }
  204. bool ISD::isBuildVectorOfConstantSDNodes(const SDNode *N) {
  205. if (N->getOpcode() != ISD::BUILD_VECTOR)
  206. return false;
  207. for (const SDValue &Op : N->op_values()) {
  208. if (Op.isUndef())
  209. continue;
  210. if (!isa<ConstantSDNode>(Op))
  211. return false;
  212. }
  213. return true;
  214. }
  215. bool ISD::isBuildVectorOfConstantFPSDNodes(const SDNode *N) {
  216. if (N->getOpcode() != ISD::BUILD_VECTOR)
  217. return false;
  218. for (const SDValue &Op : N->op_values()) {
  219. if (Op.isUndef())
  220. continue;
  221. if (!isa<ConstantFPSDNode>(Op))
  222. return false;
  223. }
  224. return true;
  225. }
  226. bool ISD::allOperandsUndef(const SDNode *N) {
  227. // Return false if the node has no operands.
  228. // This is "logically inconsistent" with the definition of "all" but
  229. // is probably the desired behavior.
  230. if (N->getNumOperands() == 0)
  231. return false;
  232. for (const SDValue &Op : N->op_values())
  233. if (!Op.isUndef())
  234. return false;
  235. return true;
  236. }
  237. bool ISD::matchUnaryPredicate(SDValue Op,
  238. std::function<bool(ConstantSDNode *)> Match,
  239. bool AllowUndefs) {
  240. // FIXME: Add support for scalar UNDEF cases?
  241. if (auto *Cst = dyn_cast<ConstantSDNode>(Op))
  242. return Match(Cst);
  243. // FIXME: Add support for vector UNDEF cases?
  244. if (ISD::BUILD_VECTOR != Op.getOpcode())
  245. return false;
  246. EVT SVT = Op.getValueType().getScalarType();
  247. for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
  248. if (AllowUndefs && Op.getOperand(i).isUndef()) {
  249. if (!Match(nullptr))
  250. return false;
  251. continue;
  252. }
  253. auto *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(i));
  254. if (!Cst || Cst->getValueType(0) != SVT || !Match(Cst))
  255. return false;
  256. }
  257. return true;
  258. }
  259. bool ISD::matchBinaryPredicate(
  260. SDValue LHS, SDValue RHS,
  261. std::function<bool(ConstantSDNode *, ConstantSDNode *)> Match,
  262. bool AllowUndefs) {
  263. if (LHS.getValueType() != RHS.getValueType())
  264. return false;
  265. // TODO: Add support for scalar UNDEF cases?
  266. if (auto *LHSCst = dyn_cast<ConstantSDNode>(LHS))
  267. if (auto *RHSCst = dyn_cast<ConstantSDNode>(RHS))
  268. return Match(LHSCst, RHSCst);
  269. // TODO: Add support for vector UNDEF cases?
  270. if (ISD::BUILD_VECTOR != LHS.getOpcode() ||
  271. ISD::BUILD_VECTOR != RHS.getOpcode())
  272. return false;
  273. EVT SVT = LHS.getValueType().getScalarType();
  274. for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
  275. SDValue LHSOp = LHS.getOperand(i);
  276. SDValue RHSOp = RHS.getOperand(i);
  277. bool LHSUndef = AllowUndefs && LHSOp.isUndef();
  278. bool RHSUndef = AllowUndefs && RHSOp.isUndef();
  279. auto *LHSCst = dyn_cast<ConstantSDNode>(LHSOp);
  280. auto *RHSCst = dyn_cast<ConstantSDNode>(RHSOp);
  281. if ((!LHSCst && !LHSUndef) || (!RHSCst && !RHSUndef))
  282. return false;
  283. if (LHSOp.getValueType() != SVT ||
  284. LHSOp.getValueType() != RHSOp.getValueType())
  285. return false;
  286. if (!Match(LHSCst, RHSCst))
  287. return false;
  288. }
  289. return true;
  290. }
  291. ISD::NodeType ISD::getExtForLoadExtType(bool IsFP, ISD::LoadExtType ExtType) {
  292. switch (ExtType) {
  293. case ISD::EXTLOAD:
  294. return IsFP ? ISD::FP_EXTEND : ISD::ANY_EXTEND;
  295. case ISD::SEXTLOAD:
  296. return ISD::SIGN_EXTEND;
  297. case ISD::ZEXTLOAD:
  298. return ISD::ZERO_EXTEND;
  299. default:
  300. break;
  301. }
  302. llvm_unreachable("Invalid LoadExtType");
  303. }
  304. ISD::CondCode ISD::getSetCCSwappedOperands(ISD::CondCode Operation) {
  305. // To perform this operation, we just need to swap the L and G bits of the
  306. // operation.
  307. unsigned OldL = (Operation >> 2) & 1;
  308. unsigned OldG = (Operation >> 1) & 1;
  309. return ISD::CondCode((Operation & ~6) | // Keep the N, U, E bits
  310. (OldL << 1) | // New G bit
  311. (OldG << 2)); // New L bit.
  312. }
  313. ISD::CondCode ISD::getSetCCInverse(ISD::CondCode Op, bool isInteger) {
  314. unsigned Operation = Op;
  315. if (isInteger)
  316. Operation ^= 7; // Flip L, G, E bits, but not U.
  317. else
  318. Operation ^= 15; // Flip all of the condition bits.
  319. if (Operation > ISD::SETTRUE2)
  320. Operation &= ~8; // Don't let N and U bits get set.
  321. return ISD::CondCode(Operation);
  322. }
  323. /// For an integer comparison, return 1 if the comparison is a signed operation
  324. /// and 2 if the result is an unsigned comparison. Return zero if the operation
  325. /// does not depend on the sign of the input (setne and seteq).
  326. static int isSignedOp(ISD::CondCode Opcode) {
  327. switch (Opcode) {
  328. default: llvm_unreachable("Illegal integer setcc operation!");
  329. case ISD::SETEQ:
  330. case ISD::SETNE: return 0;
  331. case ISD::SETLT:
  332. case ISD::SETLE:
  333. case ISD::SETGT:
  334. case ISD::SETGE: return 1;
  335. case ISD::SETULT:
  336. case ISD::SETULE:
  337. case ISD::SETUGT:
  338. case ISD::SETUGE: return 2;
  339. }
  340. }
  341. ISD::CondCode ISD::getSetCCOrOperation(ISD::CondCode Op1, ISD::CondCode Op2,
  342. bool IsInteger) {
  343. if (IsInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
  344. // Cannot fold a signed integer setcc with an unsigned integer setcc.
  345. return ISD::SETCC_INVALID;
  346. unsigned Op = Op1 | Op2; // Combine all of the condition bits.
  347. // If the N and U bits get set, then the resultant comparison DOES suddenly
  348. // care about orderedness, and it is true when ordered.
  349. if (Op > ISD::SETTRUE2)
  350. Op &= ~16; // Clear the U bit if the N bit is set.
  351. // Canonicalize illegal integer setcc's.
  352. if (IsInteger && Op == ISD::SETUNE) // e.g. SETUGT | SETULT
  353. Op = ISD::SETNE;
  354. return ISD::CondCode(Op);
  355. }
  356. ISD::CondCode ISD::getSetCCAndOperation(ISD::CondCode Op1, ISD::CondCode Op2,
  357. bool IsInteger) {
  358. if (IsInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
  359. // Cannot fold a signed setcc with an unsigned setcc.
  360. return ISD::SETCC_INVALID;
  361. // Combine all of the condition bits.
  362. ISD::CondCode Result = ISD::CondCode(Op1 & Op2);
  363. // Canonicalize illegal integer setcc's.
  364. if (IsInteger) {
  365. switch (Result) {
  366. default: break;
  367. case ISD::SETUO : Result = ISD::SETFALSE; break; // SETUGT & SETULT
  368. case ISD::SETOEQ: // SETEQ & SETU[LG]E
  369. case ISD::SETUEQ: Result = ISD::SETEQ ; break; // SETUGE & SETULE
  370. case ISD::SETOLT: Result = ISD::SETULT ; break; // SETULT & SETNE
  371. case ISD::SETOGT: Result = ISD::SETUGT ; break; // SETUGT & SETNE
  372. }
  373. }
  374. return Result;
  375. }
  376. //===----------------------------------------------------------------------===//
  377. // SDNode Profile Support
  378. //===----------------------------------------------------------------------===//
  379. /// AddNodeIDOpcode - Add the node opcode to the NodeID data.
  380. static void AddNodeIDOpcode(FoldingSetNodeID &ID, unsigned OpC) {
  381. ID.AddInteger(OpC);
  382. }
  383. /// AddNodeIDValueTypes - Value type lists are intern'd so we can represent them
  384. /// solely with their pointer.
  385. static void AddNodeIDValueTypes(FoldingSetNodeID &ID, SDVTList VTList) {
  386. ID.AddPointer(VTList.VTs);
  387. }
  388. /// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
  389. static void AddNodeIDOperands(FoldingSetNodeID &ID,
  390. ArrayRef<SDValue> Ops) {
  391. for (auto& Op : Ops) {
  392. ID.AddPointer(Op.getNode());
  393. ID.AddInteger(Op.getResNo());
  394. }
  395. }
  396. /// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
  397. static void AddNodeIDOperands(FoldingSetNodeID &ID,
  398. ArrayRef<SDUse> Ops) {
  399. for (auto& Op : Ops) {
  400. ID.AddPointer(Op.getNode());
  401. ID.AddInteger(Op.getResNo());
  402. }
  403. }
  404. static void AddNodeIDNode(FoldingSetNodeID &ID, unsigned short OpC,
  405. SDVTList VTList, ArrayRef<SDValue> OpList) {
  406. AddNodeIDOpcode(ID, OpC);
  407. AddNodeIDValueTypes(ID, VTList);
  408. AddNodeIDOperands(ID, OpList);
  409. }
  410. /// If this is an SDNode with special info, add this info to the NodeID data.
  411. static void AddNodeIDCustom(FoldingSetNodeID &ID, const SDNode *N) {
  412. switch (N->getOpcode()) {
  413. case ISD::TargetExternalSymbol:
  414. case ISD::ExternalSymbol:
  415. case ISD::MCSymbol:
  416. llvm_unreachable("Should only be used on nodes with operands");
  417. default: break; // Normal nodes don't need extra info.
  418. case ISD::TargetConstant:
  419. case ISD::Constant: {
  420. const ConstantSDNode *C = cast<ConstantSDNode>(N);
  421. ID.AddPointer(C->getConstantIntValue());
  422. ID.AddBoolean(C->isOpaque());
  423. break;
  424. }
  425. case ISD::TargetConstantFP:
  426. case ISD::ConstantFP:
  427. ID.AddPointer(cast<ConstantFPSDNode>(N)->getConstantFPValue());
  428. break;
  429. case ISD::TargetGlobalAddress:
  430. case ISD::GlobalAddress:
  431. case ISD::TargetGlobalTLSAddress:
  432. case ISD::GlobalTLSAddress: {
  433. const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(N);
  434. ID.AddPointer(GA->getGlobal());
  435. ID.AddInteger(GA->getOffset());
  436. ID.AddInteger(GA->getTargetFlags());
  437. break;
  438. }
  439. case ISD::BasicBlock:
  440. ID.AddPointer(cast<BasicBlockSDNode>(N)->getBasicBlock());
  441. break;
  442. case ISD::Register:
  443. ID.AddInteger(cast<RegisterSDNode>(N)->getReg());
  444. break;
  445. case ISD::RegisterMask:
  446. ID.AddPointer(cast<RegisterMaskSDNode>(N)->getRegMask());
  447. break;
  448. case ISD::SRCVALUE:
  449. ID.AddPointer(cast<SrcValueSDNode>(N)->getValue());
  450. break;
  451. case ISD::FrameIndex:
  452. case ISD::TargetFrameIndex:
  453. ID.AddInteger(cast<FrameIndexSDNode>(N)->getIndex());
  454. break;
  455. case ISD::LIFETIME_START:
  456. case ISD::LIFETIME_END:
  457. if (cast<LifetimeSDNode>(N)->hasOffset()) {
  458. ID.AddInteger(cast<LifetimeSDNode>(N)->getSize());
  459. ID.AddInteger(cast<LifetimeSDNode>(N)->getOffset());
  460. }
  461. break;
  462. case ISD::JumpTable:
  463. case ISD::TargetJumpTable:
  464. ID.AddInteger(cast<JumpTableSDNode>(N)->getIndex());
  465. ID.AddInteger(cast<JumpTableSDNode>(N)->getTargetFlags());
  466. break;
  467. case ISD::ConstantPool:
  468. case ISD::TargetConstantPool: {
  469. const ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(N);
  470. ID.AddInteger(CP->getAlignment());
  471. ID.AddInteger(CP->getOffset());
  472. if (CP->isMachineConstantPoolEntry())
  473. CP->getMachineCPVal()->addSelectionDAGCSEId(ID);
  474. else
  475. ID.AddPointer(CP->getConstVal());
  476. ID.AddInteger(CP->getTargetFlags());
  477. break;
  478. }
  479. case ISD::TargetIndex: {
  480. const TargetIndexSDNode *TI = cast<TargetIndexSDNode>(N);
  481. ID.AddInteger(TI->getIndex());
  482. ID.AddInteger(TI->getOffset());
  483. ID.AddInteger(TI->getTargetFlags());
  484. break;
  485. }
  486. case ISD::LOAD: {
  487. const LoadSDNode *LD = cast<LoadSDNode>(N);
  488. ID.AddInteger(LD->getMemoryVT().getRawBits());
  489. ID.AddInteger(LD->getRawSubclassData());
  490. ID.AddInteger(LD->getPointerInfo().getAddrSpace());
  491. break;
  492. }
  493. case ISD::STORE: {
  494. const StoreSDNode *ST = cast<StoreSDNode>(N);
  495. ID.AddInteger(ST->getMemoryVT().getRawBits());
  496. ID.AddInteger(ST->getRawSubclassData());
  497. ID.AddInteger(ST->getPointerInfo().getAddrSpace());
  498. break;
  499. }
  500. case ISD::MLOAD: {
  501. const MaskedLoadSDNode *MLD = cast<MaskedLoadSDNode>(N);
  502. ID.AddInteger(MLD->getMemoryVT().getRawBits());
  503. ID.AddInteger(MLD->getRawSubclassData());
  504. ID.AddInteger(MLD->getPointerInfo().getAddrSpace());
  505. break;
  506. }
  507. case ISD::MSTORE: {
  508. const MaskedStoreSDNode *MST = cast<MaskedStoreSDNode>(N);
  509. ID.AddInteger(MST->getMemoryVT().getRawBits());
  510. ID.AddInteger(MST->getRawSubclassData());
  511. ID.AddInteger(MST->getPointerInfo().getAddrSpace());
  512. break;
  513. }
  514. case ISD::MGATHER: {
  515. const MaskedGatherSDNode *MG = cast<MaskedGatherSDNode>(N);
  516. ID.AddInteger(MG->getMemoryVT().getRawBits());
  517. ID.AddInteger(MG->getRawSubclassData());
  518. ID.AddInteger(MG->getPointerInfo().getAddrSpace());
  519. break;
  520. }
  521. case ISD::MSCATTER: {
  522. const MaskedScatterSDNode *MS = cast<MaskedScatterSDNode>(N);
  523. ID.AddInteger(MS->getMemoryVT().getRawBits());
  524. ID.AddInteger(MS->getRawSubclassData());
  525. ID.AddInteger(MS->getPointerInfo().getAddrSpace());
  526. break;
  527. }
  528. case ISD::ATOMIC_CMP_SWAP:
  529. case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
  530. case ISD::ATOMIC_SWAP:
  531. case ISD::ATOMIC_LOAD_ADD:
  532. case ISD::ATOMIC_LOAD_SUB:
  533. case ISD::ATOMIC_LOAD_AND:
  534. case ISD::ATOMIC_LOAD_CLR:
  535. case ISD::ATOMIC_LOAD_OR:
  536. case ISD::ATOMIC_LOAD_XOR:
  537. case ISD::ATOMIC_LOAD_NAND:
  538. case ISD::ATOMIC_LOAD_MIN:
  539. case ISD::ATOMIC_LOAD_MAX:
  540. case ISD::ATOMIC_LOAD_UMIN:
  541. case ISD::ATOMIC_LOAD_UMAX:
  542. case ISD::ATOMIC_LOAD:
  543. case ISD::ATOMIC_STORE: {
  544. const AtomicSDNode *AT = cast<AtomicSDNode>(N);
  545. ID.AddInteger(AT->getMemoryVT().getRawBits());
  546. ID.AddInteger(AT->getRawSubclassData());
  547. ID.AddInteger(AT->getPointerInfo().getAddrSpace());
  548. break;
  549. }
  550. case ISD::PREFETCH: {
  551. const MemSDNode *PF = cast<MemSDNode>(N);
  552. ID.AddInteger(PF->getPointerInfo().getAddrSpace());
  553. break;
  554. }
  555. case ISD::VECTOR_SHUFFLE: {
  556. const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
  557. for (unsigned i = 0, e = N->getValueType(0).getVectorNumElements();
  558. i != e; ++i)
  559. ID.AddInteger(SVN->getMaskElt(i));
  560. break;
  561. }
  562. case ISD::TargetBlockAddress:
  563. case ISD::BlockAddress: {
  564. const BlockAddressSDNode *BA = cast<BlockAddressSDNode>(N);
  565. ID.AddPointer(BA->getBlockAddress());
  566. ID.AddInteger(BA->getOffset());
  567. ID.AddInteger(BA->getTargetFlags());
  568. break;
  569. }
  570. } // end switch (N->getOpcode())
  571. // Target specific memory nodes could also have address spaces to check.
  572. if (N->isTargetMemoryOpcode())
  573. ID.AddInteger(cast<MemSDNode>(N)->getPointerInfo().getAddrSpace());
  574. }
  575. /// AddNodeIDNode - Generic routine for adding a nodes info to the NodeID
  576. /// data.
  577. static void AddNodeIDNode(FoldingSetNodeID &ID, const SDNode *N) {
  578. AddNodeIDOpcode(ID, N->getOpcode());
  579. // Add the return value info.
  580. AddNodeIDValueTypes(ID, N->getVTList());
  581. // Add the operand info.
  582. AddNodeIDOperands(ID, N->ops());
  583. // Handle SDNode leafs with special info.
  584. AddNodeIDCustom(ID, N);
  585. }
  586. //===----------------------------------------------------------------------===//
  587. // SelectionDAG Class
  588. //===----------------------------------------------------------------------===//
  589. /// doNotCSE - Return true if CSE should not be performed for this node.
  590. static bool doNotCSE(SDNode *N) {
  591. if (N->getValueType(0) == MVT::Glue)
  592. return true; // Never CSE anything that produces a flag.
  593. switch (N->getOpcode()) {
  594. default: break;
  595. case ISD::HANDLENODE:
  596. case ISD::EH_LABEL:
  597. return true; // Never CSE these nodes.
  598. }
  599. // Check that remaining values produced are not flags.
  600. for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
  601. if (N->getValueType(i) == MVT::Glue)
  602. return true; // Never CSE anything that produces a flag.
  603. return false;
  604. }
  605. /// RemoveDeadNodes - This method deletes all unreachable nodes in the
  606. /// SelectionDAG.
  607. void SelectionDAG::RemoveDeadNodes() {
  608. // Create a dummy node (which is not added to allnodes), that adds a reference
  609. // to the root node, preventing it from being deleted.
  610. HandleSDNode Dummy(getRoot());
  611. SmallVector<SDNode*, 128> DeadNodes;
  612. // Add all obviously-dead nodes to the DeadNodes worklist.
  613. for (SDNode &Node : allnodes())
  614. if (Node.use_empty())
  615. DeadNodes.push_back(&Node);
  616. RemoveDeadNodes(DeadNodes);
  617. // If the root changed (e.g. it was a dead load, update the root).
  618. setRoot(Dummy.getValue());
  619. }
  620. /// RemoveDeadNodes - This method deletes the unreachable nodes in the
  621. /// given list, and any nodes that become unreachable as a result.
  622. void SelectionDAG::RemoveDeadNodes(SmallVectorImpl<SDNode *> &DeadNodes) {
  623. // Process the worklist, deleting the nodes and adding their uses to the
  624. // worklist.
  625. while (!DeadNodes.empty()) {
  626. SDNode *N = DeadNodes.pop_back_val();
  627. // Skip to next node if we've already managed to delete the node. This could
  628. // happen if replacing a node causes a node previously added to the node to
  629. // be deleted.
  630. if (N->getOpcode() == ISD::DELETED_NODE)
  631. continue;
  632. for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
  633. DUL->NodeDeleted(N, nullptr);
  634. // Take the node out of the appropriate CSE map.
  635. RemoveNodeFromCSEMaps(N);
  636. // Next, brutally remove the operand list. This is safe to do, as there are
  637. // no cycles in the graph.
  638. for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
  639. SDUse &Use = *I++;
  640. SDNode *Operand = Use.getNode();
  641. Use.set(SDValue());
  642. // Now that we removed this operand, see if there are no uses of it left.
  643. if (Operand->use_empty())
  644. DeadNodes.push_back(Operand);
  645. }
  646. DeallocateNode(N);
  647. }
  648. }
  649. void SelectionDAG::RemoveDeadNode(SDNode *N){
  650. SmallVector<SDNode*, 16> DeadNodes(1, N);
  651. // Create a dummy node that adds a reference to the root node, preventing
  652. // it from being deleted. (This matters if the root is an operand of the
  653. // dead node.)
  654. HandleSDNode Dummy(getRoot());
  655. RemoveDeadNodes(DeadNodes);
  656. }
  657. void SelectionDAG::DeleteNode(SDNode *N) {
  658. // First take this out of the appropriate CSE map.
  659. RemoveNodeFromCSEMaps(N);
  660. // Finally, remove uses due to operands of this node, remove from the
  661. // AllNodes list, and delete the node.
  662. DeleteNodeNotInCSEMaps(N);
  663. }
  664. void SelectionDAG::DeleteNodeNotInCSEMaps(SDNode *N) {
  665. assert(N->getIterator() != AllNodes.begin() &&
  666. "Cannot delete the entry node!");
  667. assert(N->use_empty() && "Cannot delete a node that is not dead!");
  668. // Drop all of the operands and decrement used node's use counts.
  669. N->DropOperands();
  670. DeallocateNode(N);
  671. }
  672. void SDDbgInfo::erase(const SDNode *Node) {
  673. DbgValMapType::iterator I = DbgValMap.find(Node);
  674. if (I == DbgValMap.end())
  675. return;
  676. for (auto &Val: I->second)
  677. Val->setIsInvalidated();
  678. DbgValMap.erase(I);
  679. }
  680. void SelectionDAG::DeallocateNode(SDNode *N) {
  681. // If we have operands, deallocate them.
  682. removeOperands(N);
  683. NodeAllocator.Deallocate(AllNodes.remove(N));
  684. // Set the opcode to DELETED_NODE to help catch bugs when node
  685. // memory is reallocated.
  686. // FIXME: There are places in SDag that have grown a dependency on the opcode
  687. // value in the released node.
  688. __asan_unpoison_memory_region(&N->NodeType, sizeof(N->NodeType));
  689. N->NodeType = ISD::DELETED_NODE;
  690. // If any of the SDDbgValue nodes refer to this SDNode, invalidate
  691. // them and forget about that node.
  692. DbgInfo->erase(N);
  693. }
  694. #ifndef NDEBUG
  695. /// VerifySDNode - Sanity check the given SDNode. Aborts if it is invalid.
  696. static void VerifySDNode(SDNode *N) {
  697. switch (N->getOpcode()) {
  698. default:
  699. break;
  700. case ISD::BUILD_PAIR: {
  701. EVT VT = N->getValueType(0);
  702. assert(N->getNumValues() == 1 && "Too many results!");
  703. assert(!VT.isVector() && (VT.isInteger() || VT.isFloatingPoint()) &&
  704. "Wrong return type!");
  705. assert(N->getNumOperands() == 2 && "Wrong number of operands!");
  706. assert(N->getOperand(0).getValueType() == N->getOperand(1).getValueType() &&
  707. "Mismatched operand types!");
  708. assert(N->getOperand(0).getValueType().isInteger() == VT.isInteger() &&
  709. "Wrong operand type!");
  710. assert(VT.getSizeInBits() == 2 * N->getOperand(0).getValueSizeInBits() &&
  711. "Wrong return type size");
  712. break;
  713. }
  714. case ISD::BUILD_VECTOR: {
  715. assert(N->getNumValues() == 1 && "Too many results!");
  716. assert(N->getValueType(0).isVector() && "Wrong return type!");
  717. assert(N->getNumOperands() == N->getValueType(0).getVectorNumElements() &&
  718. "Wrong number of operands!");
  719. EVT EltVT = N->getValueType(0).getVectorElementType();
  720. for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ++I) {
  721. assert((I->getValueType() == EltVT ||
  722. (EltVT.isInteger() && I->getValueType().isInteger() &&
  723. EltVT.bitsLE(I->getValueType()))) &&
  724. "Wrong operand type!");
  725. assert(I->getValueType() == N->getOperand(0).getValueType() &&
  726. "Operands must all have the same type");
  727. }
  728. break;
  729. }
  730. }
  731. }
  732. #endif // NDEBUG
  733. /// Insert a newly allocated node into the DAG.
  734. ///
  735. /// Handles insertion into the all nodes list and CSE map, as well as
  736. /// verification and other common operations when a new node is allocated.
  737. void SelectionDAG::InsertNode(SDNode *N) {
  738. AllNodes.push_back(N);
  739. #ifndef NDEBUG
  740. N->PersistentId = NextPersistentId++;
  741. VerifySDNode(N);
  742. #endif
  743. for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
  744. DUL->NodeInserted(N);
  745. }
  746. /// RemoveNodeFromCSEMaps - Take the specified node out of the CSE map that
  747. /// correspond to it. This is useful when we're about to delete or repurpose
  748. /// the node. We don't want future request for structurally identical nodes
  749. /// to return N anymore.
  750. bool SelectionDAG::RemoveNodeFromCSEMaps(SDNode *N) {
  751. bool Erased = false;
  752. switch (N->getOpcode()) {
  753. case ISD::HANDLENODE: return false; // noop.
  754. case ISD::CONDCODE:
  755. assert(CondCodeNodes[cast<CondCodeSDNode>(N)->get()] &&
  756. "Cond code doesn't exist!");
  757. Erased = CondCodeNodes[cast<CondCodeSDNode>(N)->get()] != nullptr;
  758. CondCodeNodes[cast<CondCodeSDNode>(N)->get()] = nullptr;
  759. break;
  760. case ISD::ExternalSymbol:
  761. Erased = ExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol());
  762. break;
  763. case ISD::TargetExternalSymbol: {
  764. ExternalSymbolSDNode *ESN = cast<ExternalSymbolSDNode>(N);
  765. Erased = TargetExternalSymbols.erase(
  766. std::pair<std::string,unsigned char>(ESN->getSymbol(),
  767. ESN->getTargetFlags()));
  768. break;
  769. }
  770. case ISD::MCSymbol: {
  771. auto *MCSN = cast<MCSymbolSDNode>(N);
  772. Erased = MCSymbols.erase(MCSN->getMCSymbol());
  773. break;
  774. }
  775. case ISD::VALUETYPE: {
  776. EVT VT = cast<VTSDNode>(N)->getVT();
  777. if (VT.isExtended()) {
  778. Erased = ExtendedValueTypeNodes.erase(VT);
  779. } else {
  780. Erased = ValueTypeNodes[VT.getSimpleVT().SimpleTy] != nullptr;
  781. ValueTypeNodes[VT.getSimpleVT().SimpleTy] = nullptr;
  782. }
  783. break;
  784. }
  785. default:
  786. // Remove it from the CSE Map.
  787. assert(N->getOpcode() != ISD::DELETED_NODE && "DELETED_NODE in CSEMap!");
  788. assert(N->getOpcode() != ISD::EntryToken && "EntryToken in CSEMap!");
  789. Erased = CSEMap.RemoveNode(N);
  790. break;
  791. }
  792. #ifndef NDEBUG
  793. // Verify that the node was actually in one of the CSE maps, unless it has a
  794. // flag result (which cannot be CSE'd) or is one of the special cases that are
  795. // not subject to CSE.
  796. if (!Erased && N->getValueType(N->getNumValues()-1) != MVT::Glue &&
  797. !N->isMachineOpcode() && !doNotCSE(N)) {
  798. N->dump(this);
  799. dbgs() << "\n";
  800. llvm_unreachable("Node is not in map!");
  801. }
  802. #endif
  803. return Erased;
  804. }
  805. /// AddModifiedNodeToCSEMaps - The specified node has been removed from the CSE
  806. /// maps and modified in place. Add it back to the CSE maps, unless an identical
  807. /// node already exists, in which case transfer all its users to the existing
  808. /// node. This transfer can potentially trigger recursive merging.
  809. void
  810. SelectionDAG::AddModifiedNodeToCSEMaps(SDNode *N) {
  811. // For node types that aren't CSE'd, just act as if no identical node
  812. // already exists.
  813. if (!doNotCSE(N)) {
  814. SDNode *Existing = CSEMap.GetOrInsertNode(N);
  815. if (Existing != N) {
  816. // If there was already an existing matching node, use ReplaceAllUsesWith
  817. // to replace the dead one with the existing one. This can cause
  818. // recursive merging of other unrelated nodes down the line.
  819. ReplaceAllUsesWith(N, Existing);
  820. // N is now dead. Inform the listeners and delete it.
  821. for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
  822. DUL->NodeDeleted(N, Existing);
  823. DeleteNodeNotInCSEMaps(N);
  824. return;
  825. }
  826. }
  827. // If the node doesn't already exist, we updated it. Inform listeners.
  828. for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
  829. DUL->NodeUpdated(N);
  830. }
  831. /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
  832. /// were replaced with those specified. If this node is never memoized,
  833. /// return null, otherwise return a pointer to the slot it would take. If a
  834. /// node already exists with these operands, the slot will be non-null.
  835. SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, SDValue Op,
  836. void *&InsertPos) {
  837. if (doNotCSE(N))
  838. return nullptr;
  839. SDValue Ops[] = { Op };
  840. FoldingSetNodeID ID;
  841. AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
  842. AddNodeIDCustom(ID, N);
  843. SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
  844. if (Node)
  845. Node->intersectFlagsWith(N->getFlags());
  846. return Node;
  847. }
  848. /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
  849. /// were replaced with those specified. If this node is never memoized,
  850. /// return null, otherwise return a pointer to the slot it would take. If a
  851. /// node already exists with these operands, the slot will be non-null.
  852. SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N,
  853. SDValue Op1, SDValue Op2,
  854. void *&InsertPos) {
  855. if (doNotCSE(N))
  856. return nullptr;
  857. SDValue Ops[] = { Op1, Op2 };
  858. FoldingSetNodeID ID;
  859. AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
  860. AddNodeIDCustom(ID, N);
  861. SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
  862. if (Node)
  863. Node->intersectFlagsWith(N->getFlags());
  864. return Node;
  865. }
  866. /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
  867. /// were replaced with those specified. If this node is never memoized,
  868. /// return null, otherwise return a pointer to the slot it would take. If a
  869. /// node already exists with these operands, the slot will be non-null.
  870. SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, ArrayRef<SDValue> Ops,
  871. void *&InsertPos) {
  872. if (doNotCSE(N))
  873. return nullptr;
  874. FoldingSetNodeID ID;
  875. AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
  876. AddNodeIDCustom(ID, N);
  877. SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
  878. if (Node)
  879. Node->intersectFlagsWith(N->getFlags());
  880. return Node;
  881. }
  882. unsigned SelectionDAG::getEVTAlignment(EVT VT) const {
  883. Type *Ty = VT == MVT::iPTR ?
  884. PointerType::get(Type::getInt8Ty(*getContext()), 0) :
  885. VT.getTypeForEVT(*getContext());
  886. return getDataLayout().getABITypeAlignment(Ty);
  887. }
  888. // EntryNode could meaningfully have debug info if we can find it...
  889. SelectionDAG::SelectionDAG(const TargetMachine &tm, CodeGenOpt::Level OL)
  890. : TM(tm), OptLevel(OL),
  891. EntryNode(ISD::EntryToken, 0, DebugLoc(), getVTList(MVT::Other)),
  892. Root(getEntryNode()) {
  893. InsertNode(&EntryNode);
  894. DbgInfo = new SDDbgInfo();
  895. }
  896. void SelectionDAG::init(MachineFunction &NewMF,
  897. OptimizationRemarkEmitter &NewORE,
  898. Pass *PassPtr, const TargetLibraryInfo *LibraryInfo,
  899. LegacyDivergenceAnalysis * Divergence) {
  900. MF = &NewMF;
  901. SDAGISelPass = PassPtr;
  902. ORE = &NewORE;
  903. TLI = getSubtarget().getTargetLowering();
  904. TSI = getSubtarget().getSelectionDAGInfo();
  905. LibInfo = LibraryInfo;
  906. Context = &MF->getFunction().getContext();
  907. DA = Divergence;
  908. }
  909. SelectionDAG::~SelectionDAG() {
  910. assert(!UpdateListeners && "Dangling registered DAGUpdateListeners");
  911. allnodes_clear();
  912. OperandRecycler.clear(OperandAllocator);
  913. delete DbgInfo;
  914. }
  915. void SelectionDAG::allnodes_clear() {
  916. assert(&*AllNodes.begin() == &EntryNode);
  917. AllNodes.remove(AllNodes.begin());
  918. while (!AllNodes.empty())
  919. DeallocateNode(&AllNodes.front());
  920. #ifndef NDEBUG
  921. NextPersistentId = 0;
  922. #endif
  923. }
  924. SDNode *SelectionDAG::FindNodeOrInsertPos(const FoldingSetNodeID &ID,
  925. void *&InsertPos) {
  926. SDNode *N = CSEMap.FindNodeOrInsertPos(ID, InsertPos);
  927. if (N) {
  928. switch (N->getOpcode()) {
  929. default: break;
  930. case ISD::Constant:
  931. case ISD::ConstantFP:
  932. llvm_unreachable("Querying for Constant and ConstantFP nodes requires "
  933. "debug location. Use another overload.");
  934. }
  935. }
  936. return N;
  937. }
  938. SDNode *SelectionDAG::FindNodeOrInsertPos(const FoldingSetNodeID &ID,
  939. const SDLoc &DL, void *&InsertPos) {
  940. SDNode *N = CSEMap.FindNodeOrInsertPos(ID, InsertPos);
  941. if (N) {
  942. switch (N->getOpcode()) {
  943. case ISD::Constant:
  944. case ISD::ConstantFP:
  945. // Erase debug location from the node if the node is used at several
  946. // different places. Do not propagate one location to all uses as it
  947. // will cause a worse single stepping debugging experience.
  948. if (N->getDebugLoc() != DL.getDebugLoc())
  949. N->setDebugLoc(DebugLoc());
  950. break;
  951. default:
  952. // When the node's point of use is located earlier in the instruction
  953. // sequence than its prior point of use, update its debug info to the
  954. // earlier location.
  955. if (DL.getIROrder() && DL.getIROrder() < N->getIROrder())
  956. N->setDebugLoc(DL.getDebugLoc());
  957. break;
  958. }
  959. }
  960. return N;
  961. }
  962. void SelectionDAG::clear() {
  963. allnodes_clear();
  964. OperandRecycler.clear(OperandAllocator);
  965. OperandAllocator.Reset();
  966. CSEMap.clear();
  967. ExtendedValueTypeNodes.clear();
  968. ExternalSymbols.clear();
  969. TargetExternalSymbols.clear();
  970. MCSymbols.clear();
  971. std::fill(CondCodeNodes.begin(), CondCodeNodes.end(),
  972. static_cast<CondCodeSDNode*>(nullptr));
  973. std::fill(ValueTypeNodes.begin(), ValueTypeNodes.end(),
  974. static_cast<SDNode*>(nullptr));
  975. EntryNode.UseList = nullptr;
  976. InsertNode(&EntryNode);
  977. Root = getEntryNode();
  978. DbgInfo->clear();
  979. }
  980. SDValue SelectionDAG::getFPExtendOrRound(SDValue Op, const SDLoc &DL, EVT VT) {
  981. return VT.bitsGT(Op.getValueType())
  982. ? getNode(ISD::FP_EXTEND, DL, VT, Op)
  983. : getNode(ISD::FP_ROUND, DL, VT, Op, getIntPtrConstant(0, DL));
  984. }
  985. SDValue SelectionDAG::getAnyExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
  986. return VT.bitsGT(Op.getValueType()) ?
  987. getNode(ISD::ANY_EXTEND, DL, VT, Op) :
  988. getNode(ISD::TRUNCATE, DL, VT, Op);
  989. }
  990. SDValue SelectionDAG::getSExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
  991. return VT.bitsGT(Op.getValueType()) ?
  992. getNode(ISD::SIGN_EXTEND, DL, VT, Op) :
  993. getNode(ISD::TRUNCATE, DL, VT, Op);
  994. }
  995. SDValue SelectionDAG::getZExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
  996. return VT.bitsGT(Op.getValueType()) ?
  997. getNode(ISD::ZERO_EXTEND, DL, VT, Op) :
  998. getNode(ISD::TRUNCATE, DL, VT, Op);
  999. }
  1000. SDValue SelectionDAG::getBoolExtOrTrunc(SDValue Op, const SDLoc &SL, EVT VT,
  1001. EVT OpVT) {
  1002. if (VT.bitsLE(Op.getValueType()))
  1003. return getNode(ISD::TRUNCATE, SL, VT, Op);
  1004. TargetLowering::BooleanContent BType = TLI->getBooleanContents(OpVT);
  1005. return getNode(TLI->getExtendForContent(BType), SL, VT, Op);
  1006. }
  1007. SDValue SelectionDAG::getZeroExtendInReg(SDValue Op, const SDLoc &DL, EVT VT) {
  1008. assert(!VT.isVector() &&
  1009. "getZeroExtendInReg should use the vector element type instead of "
  1010. "the vector type!");
  1011. if (Op.getValueType().getScalarType() == VT) return Op;
  1012. unsigned BitWidth = Op.getScalarValueSizeInBits();
  1013. APInt Imm = APInt::getLowBitsSet(BitWidth,
  1014. VT.getSizeInBits());
  1015. return getNode(ISD::AND, DL, Op.getValueType(), Op,
  1016. getConstant(Imm, DL, Op.getValueType()));
  1017. }
  1018. /// getNOT - Create a bitwise NOT operation as (XOR Val, -1).
  1019. SDValue SelectionDAG::getNOT(const SDLoc &DL, SDValue Val, EVT VT) {
  1020. EVT EltVT = VT.getScalarType();
  1021. SDValue NegOne =
  1022. getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), DL, VT);
  1023. return getNode(ISD::XOR, DL, VT, Val, NegOne);
  1024. }
  1025. SDValue SelectionDAG::getLogicalNOT(const SDLoc &DL, SDValue Val, EVT VT) {
  1026. SDValue TrueValue = getBoolConstant(true, DL, VT, VT);
  1027. return getNode(ISD::XOR, DL, VT, Val, TrueValue);
  1028. }
  1029. SDValue SelectionDAG::getBoolConstant(bool V, const SDLoc &DL, EVT VT,
  1030. EVT OpVT) {
  1031. if (!V)
  1032. return getConstant(0, DL, VT);
  1033. switch (TLI->getBooleanContents(OpVT)) {
  1034. case TargetLowering::ZeroOrOneBooleanContent:
  1035. case TargetLowering::UndefinedBooleanContent:
  1036. return getConstant(1, DL, VT);
  1037. case TargetLowering::ZeroOrNegativeOneBooleanContent:
  1038. return getAllOnesConstant(DL, VT);
  1039. }
  1040. llvm_unreachable("Unexpected boolean content enum!");
  1041. }
  1042. SDValue SelectionDAG::getConstant(uint64_t Val, const SDLoc &DL, EVT VT,
  1043. bool isT, bool isO) {
  1044. EVT EltVT = VT.getScalarType();
  1045. assert((EltVT.getSizeInBits() >= 64 ||
  1046. (uint64_t)((int64_t)Val >> EltVT.getSizeInBits()) + 1 < 2) &&
  1047. "getConstant with a uint64_t value that doesn't fit in the type!");
  1048. return getConstant(APInt(EltVT.getSizeInBits(), Val), DL, VT, isT, isO);
  1049. }
  1050. SDValue SelectionDAG::getConstant(const APInt &Val, const SDLoc &DL, EVT VT,
  1051. bool isT, bool isO) {
  1052. return getConstant(*ConstantInt::get(*Context, Val), DL, VT, isT, isO);
  1053. }
  1054. SDValue SelectionDAG::getConstant(const ConstantInt &Val, const SDLoc &DL,
  1055. EVT VT, bool isT, bool isO) {
  1056. assert(VT.isInteger() && "Cannot create FP integer constant!");
  1057. EVT EltVT = VT.getScalarType();
  1058. const ConstantInt *Elt = &Val;
  1059. // In some cases the vector type is legal but the element type is illegal and
  1060. // needs to be promoted, for example v8i8 on ARM. In this case, promote the
  1061. // inserted value (the type does not need to match the vector element type).
  1062. // Any extra bits introduced will be truncated away.
  1063. if (VT.isVector() && TLI->getTypeAction(*getContext(), EltVT) ==
  1064. TargetLowering::TypePromoteInteger) {
  1065. EltVT = TLI->getTypeToTransformTo(*getContext(), EltVT);
  1066. APInt NewVal = Elt->getValue().zextOrTrunc(EltVT.getSizeInBits());
  1067. Elt = ConstantInt::get(*getContext(), NewVal);
  1068. }
  1069. // In other cases the element type is illegal and needs to be expanded, for
  1070. // example v2i64 on MIPS32. In this case, find the nearest legal type, split
  1071. // the value into n parts and use a vector type with n-times the elements.
  1072. // Then bitcast to the type requested.
  1073. // Legalizing constants too early makes the DAGCombiner's job harder so we
  1074. // only legalize if the DAG tells us we must produce legal types.
  1075. else if (NewNodesMustHaveLegalTypes && VT.isVector() &&
  1076. TLI->getTypeAction(*getContext(), EltVT) ==
  1077. TargetLowering::TypeExpandInteger) {
  1078. const APInt &NewVal = Elt->getValue();
  1079. EVT ViaEltVT = TLI->getTypeToTransformTo(*getContext(), EltVT);
  1080. unsigned ViaEltSizeInBits = ViaEltVT.getSizeInBits();
  1081. unsigned ViaVecNumElts = VT.getSizeInBits() / ViaEltSizeInBits;
  1082. EVT ViaVecVT = EVT::getVectorVT(*getContext(), ViaEltVT, ViaVecNumElts);
  1083. // Check the temporary vector is the correct size. If this fails then
  1084. // getTypeToTransformTo() probably returned a type whose size (in bits)
  1085. // isn't a power-of-2 factor of the requested type size.
  1086. assert(ViaVecVT.getSizeInBits() == VT.getSizeInBits());
  1087. SmallVector<SDValue, 2> EltParts;
  1088. for (unsigned i = 0; i < ViaVecNumElts / VT.getVectorNumElements(); ++i) {
  1089. EltParts.push_back(getConstant(NewVal.lshr(i * ViaEltSizeInBits)
  1090. .zextOrTrunc(ViaEltSizeInBits), DL,
  1091. ViaEltVT, isT, isO));
  1092. }
  1093. // EltParts is currently in little endian order. If we actually want
  1094. // big-endian order then reverse it now.
  1095. if (getDataLayout().isBigEndian())
  1096. std::reverse(EltParts.begin(), EltParts.end());
  1097. // The elements must be reversed when the element order is different
  1098. // to the endianness of the elements (because the BITCAST is itself a
  1099. // vector shuffle in this situation). However, we do not need any code to
  1100. // perform this reversal because getConstant() is producing a vector
  1101. // splat.
  1102. // This situation occurs in MIPS MSA.
  1103. SmallVector<SDValue, 8> Ops;
  1104. for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
  1105. Ops.insert(Ops.end(), EltParts.begin(), EltParts.end());
  1106. SDValue V = getNode(ISD::BITCAST, DL, VT, getBuildVector(ViaVecVT, DL, Ops));
  1107. return V;
  1108. }
  1109. assert(Elt->getBitWidth() == EltVT.getSizeInBits() &&
  1110. "APInt size does not match type size!");
  1111. unsigned Opc = isT ? ISD::TargetConstant : ISD::Constant;
  1112. FoldingSetNodeID ID;
  1113. AddNodeIDNode(ID, Opc, getVTList(EltVT), None);
  1114. ID.AddPointer(Elt);
  1115. ID.AddBoolean(isO);
  1116. void *IP = nullptr;
  1117. SDNode *N = nullptr;
  1118. if ((N = FindNodeOrInsertPos(ID, DL, IP)))
  1119. if (!VT.isVector())
  1120. return SDValue(N, 0);
  1121. if (!N) {
  1122. N = newSDNode<ConstantSDNode>(isT, isO, Elt, EltVT);
  1123. CSEMap.InsertNode(N, IP);
  1124. InsertNode(N);
  1125. NewSDValueDbgMsg(SDValue(N, 0), "Creating constant: ", this);
  1126. }
  1127. SDValue Result(N, 0);
  1128. if (VT.isVector())
  1129. Result = getSplatBuildVector(VT, DL, Result);
  1130. return Result;
  1131. }
  1132. SDValue SelectionDAG::getIntPtrConstant(uint64_t Val, const SDLoc &DL,
  1133. bool isTarget) {
  1134. return getConstant(Val, DL, TLI->getPointerTy(getDataLayout()), isTarget);
  1135. }
  1136. SDValue SelectionDAG::getShiftAmountConstant(uint64_t Val, EVT VT,
  1137. const SDLoc &DL, bool LegalTypes) {
  1138. EVT ShiftVT = TLI->getShiftAmountTy(VT, getDataLayout(), LegalTypes);
  1139. return getConstant(Val, DL, ShiftVT);
  1140. }
  1141. SDValue SelectionDAG::getConstantFP(const APFloat &V, const SDLoc &DL, EVT VT,
  1142. bool isTarget) {
  1143. return getConstantFP(*ConstantFP::get(*getContext(), V), DL, VT, isTarget);
  1144. }
  1145. SDValue SelectionDAG::getConstantFP(const ConstantFP &V, const SDLoc &DL,
  1146. EVT VT, bool isTarget) {
  1147. assert(VT.isFloatingPoint() && "Cannot create integer FP constant!");
  1148. EVT EltVT = VT.getScalarType();
  1149. // Do the map lookup using the actual bit pattern for the floating point
  1150. // value, so that we don't have problems with 0.0 comparing equal to -0.0, and
  1151. // we don't have issues with SNANs.
  1152. unsigned Opc = isTarget ? ISD::TargetConstantFP : ISD::ConstantFP;
  1153. FoldingSetNodeID ID;
  1154. AddNodeIDNode(ID, Opc, getVTList(EltVT), None);
  1155. ID.AddPointer(&V);
  1156. void *IP = nullptr;
  1157. SDNode *N = nullptr;
  1158. if ((N = FindNodeOrInsertPos(ID, DL, IP)))
  1159. if (!VT.isVector())
  1160. return SDValue(N, 0);
  1161. if (!N) {
  1162. N = newSDNode<ConstantFPSDNode>(isTarget, &V, EltVT);
  1163. CSEMap.InsertNode(N, IP);
  1164. InsertNode(N);
  1165. }
  1166. SDValue Result(N, 0);
  1167. if (VT.isVector())
  1168. Result = getSplatBuildVector(VT, DL, Result);
  1169. NewSDValueDbgMsg(Result, "Creating fp constant: ", this);
  1170. return Result;
  1171. }
  1172. SDValue SelectionDAG::getConstantFP(double Val, const SDLoc &DL, EVT VT,
  1173. bool isTarget) {
  1174. EVT EltVT = VT.getScalarType();
  1175. if (EltVT == MVT::f32)
  1176. return getConstantFP(APFloat((float)Val), DL, VT, isTarget);
  1177. else if (EltVT == MVT::f64)
  1178. return getConstantFP(APFloat(Val), DL, VT, isTarget);
  1179. else if (EltVT == MVT::f80 || EltVT == MVT::f128 || EltVT == MVT::ppcf128 ||
  1180. EltVT == MVT::f16) {
  1181. bool Ignored;
  1182. APFloat APF = APFloat(Val);
  1183. APF.convert(EVTToAPFloatSemantics(EltVT), APFloat::rmNearestTiesToEven,
  1184. &Ignored);
  1185. return getConstantFP(APF, DL, VT, isTarget);
  1186. } else
  1187. llvm_unreachable("Unsupported type in getConstantFP");
  1188. }
  1189. SDValue SelectionDAG::getGlobalAddress(const GlobalValue *GV, const SDLoc &DL,
  1190. EVT VT, int64_t Offset, bool isTargetGA,
  1191. unsigned char TargetFlags) {
  1192. assert((TargetFlags == 0 || isTargetGA) &&
  1193. "Cannot set target flags on target-independent globals");
  1194. // Truncate (with sign-extension) the offset value to the pointer size.
  1195. unsigned BitWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType());
  1196. if (BitWidth < 64)
  1197. Offset = SignExtend64(Offset, BitWidth);
  1198. unsigned Opc;
  1199. if (GV->isThreadLocal())
  1200. Opc = isTargetGA ? ISD::TargetGlobalTLSAddress : ISD::GlobalTLSAddress;
  1201. else
  1202. Opc = isTargetGA ? ISD::TargetGlobalAddress : ISD::GlobalAddress;
  1203. FoldingSetNodeID ID;
  1204. AddNodeIDNode(ID, Opc, getVTList(VT), None);
  1205. ID.AddPointer(GV);
  1206. ID.AddInteger(Offset);
  1207. ID.AddInteger(TargetFlags);
  1208. void *IP = nullptr;
  1209. if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
  1210. return SDValue(E, 0);
  1211. auto *N = newSDNode<GlobalAddressSDNode>(
  1212. Opc, DL.getIROrder(), DL.getDebugLoc(), GV, VT, Offset, TargetFlags);
  1213. CSEMap.InsertNode(N, IP);
  1214. InsertNode(N);
  1215. return SDValue(N, 0);
  1216. }
  1217. SDValue SelectionDAG::getFrameIndex(int FI, EVT VT, bool isTarget) {
  1218. unsigned Opc = isTarget ? ISD::TargetFrameIndex : ISD::FrameIndex;
  1219. FoldingSetNodeID ID;
  1220. AddNodeIDNode(ID, Opc, getVTList(VT), None);
  1221. ID.AddInteger(FI);
  1222. void *IP = nullptr;
  1223. if (SDNode *E = FindNodeOrInsertPos(ID, IP))
  1224. return SDValue(E, 0);
  1225. auto *N = newSDNode<FrameIndexSDNode>(FI, VT, isTarget);
  1226. CSEMap.InsertNode(N, IP);
  1227. InsertNode(N);
  1228. return SDValue(N, 0);
  1229. }
  1230. SDValue SelectionDAG::getJumpTable(int JTI, EVT VT, bool isTarget,
  1231. unsigned char TargetFlags) {
  1232. assert((TargetFlags == 0 || isTarget) &&
  1233. "Cannot set target flags on target-independent jump tables");
  1234. unsigned Opc = isTarget ? ISD::TargetJumpTable : ISD::JumpTable;
  1235. FoldingSetNodeID ID;
  1236. AddNodeIDNode(ID, Opc, getVTList(VT), None);
  1237. ID.AddInteger(JTI);
  1238. ID.AddInteger(TargetFlags);
  1239. void *IP = nullptr;
  1240. if (SDNode *E = FindNodeOrInsertPos(ID, IP))
  1241. return SDValue(E, 0);
  1242. auto *N = newSDNode<JumpTableSDNode>(JTI, VT, isTarget, TargetFlags);
  1243. CSEMap.InsertNode(N, IP);
  1244. InsertNode(N);
  1245. return SDValue(N, 0);
  1246. }
  1247. SDValue SelectionDAG::getConstantPool(const Constant *C, EVT VT,
  1248. unsigned Alignment, int Offset,
  1249. bool isTarget,
  1250. unsigned char TargetFlags) {
  1251. assert((TargetFlags == 0 || isTarget) &&
  1252. "Cannot set target flags on target-independent globals");
  1253. if (Alignment == 0)
  1254. Alignment = MF->getFunction().hasOptSize()
  1255. ? getDataLayout().getABITypeAlignment(C->getType())
  1256. : getDataLayout().getPrefTypeAlignment(C->getType());
  1257. unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
  1258. FoldingSetNodeID ID;
  1259. AddNodeIDNode(ID, Opc, getVTList(VT), None);
  1260. ID.AddInteger(Alignment);
  1261. ID.AddInteger(Offset);
  1262. ID.AddPointer(C);
  1263. ID.AddInteger(TargetFlags);
  1264. void *IP = nullptr;
  1265. if (SDNode *E = FindNodeOrInsertPos(ID, IP))
  1266. return SDValue(E, 0);
  1267. auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VT, Offset, Alignment,
  1268. TargetFlags);
  1269. CSEMap.InsertNode(N, IP);
  1270. InsertNode(N);
  1271. return SDValue(N, 0);
  1272. }
  1273. SDValue SelectionDAG::getConstantPool(MachineConstantPoolValue *C, EVT VT,
  1274. unsigned Alignment, int Offset,
  1275. bool isTarget,
  1276. unsigned char TargetFlags) {
  1277. assert((TargetFlags == 0 || isTarget) &&
  1278. "Cannot set target flags on target-independent globals");
  1279. if (Alignment == 0)
  1280. Alignment = getDataLayout().getPrefTypeAlignment(C->getType());
  1281. unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
  1282. FoldingSetNodeID ID;
  1283. AddNodeIDNode(ID, Opc, getVTList(VT), None);
  1284. ID.AddInteger(Alignment);
  1285. ID.AddInteger(Offset);
  1286. C->addSelectionDAGCSEId(ID);
  1287. ID.AddInteger(TargetFlags);
  1288. void *IP = nullptr;
  1289. if (SDNode *E = FindNodeOrInsertPos(ID, IP))
  1290. return SDValue(E, 0);
  1291. auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VT, Offset, Alignment,
  1292. TargetFlags);
  1293. CSEMap.InsertNode(N, IP);
  1294. InsertNode(N);
  1295. return SDValue(N, 0);
  1296. }
  1297. SDValue SelectionDAG::getTargetIndex(int Index, EVT VT, int64_t Offset,
  1298. unsigned char TargetFlags) {
  1299. FoldingSetNodeID ID;
  1300. AddNodeIDNode(ID, ISD::TargetIndex, getVTList(VT), None);
  1301. ID.AddInteger(Index);
  1302. ID.AddInteger(Offset);
  1303. ID.AddInteger(TargetFlags);
  1304. void *IP = nullptr;
  1305. if (SDNode *E = FindNodeOrInsertPos(ID, IP))
  1306. return SDValue(E, 0);
  1307. auto *N = newSDNode<TargetIndexSDNode>(Index, VT, Offset, TargetFlags);
  1308. CSEMap.InsertNode(N, IP);
  1309. InsertNode(N);
  1310. return SDValue(N, 0);
  1311. }
  1312. SDValue SelectionDAG::getBasicBlock(MachineBasicBlock *MBB) {
  1313. FoldingSetNodeID ID;
  1314. AddNodeIDNode(ID, ISD::BasicBlock, getVTList(MVT::Other), None);
  1315. ID.AddPointer(MBB);
  1316. void *IP = nullptr;
  1317. if (SDNode *E = FindNodeOrInsertPos(ID, IP))
  1318. return SDValue(E, 0);
  1319. auto *N = newSDNode<BasicBlockSDNode>(MBB);
  1320. CSEMap.InsertNode(N, IP);
  1321. InsertNode(N);
  1322. return SDValue(N, 0);
  1323. }
  1324. SDValue SelectionDAG::getValueType(EVT VT) {
  1325. if (VT.isSimple() && (unsigned)VT.getSimpleVT().SimpleTy >=
  1326. ValueTypeNodes.size())
  1327. ValueTypeNodes.resize(VT.getSimpleVT().SimpleTy+1);
  1328. SDNode *&N = VT.isExtended() ?
  1329. ExtendedValueTypeNodes[VT] : ValueTypeNodes[VT.getSimpleVT().SimpleTy];
  1330. if (N) return SDValue(N, 0);
  1331. N = newSDNode<VTSDNode>(VT);
  1332. InsertNode(N);
  1333. return SDValue(N, 0);
  1334. }
  1335. SDValue SelectionDAG::getExternalSymbol(const char *Sym, EVT VT) {
  1336. SDNode *&N = ExternalSymbols[Sym];
  1337. if (N) return SDValue(N, 0);
  1338. N = newSDNode<ExternalSymbolSDNode>(false, Sym, 0, VT);
  1339. InsertNode(N);
  1340. return SDValue(N, 0);
  1341. }
  1342. SDValue SelectionDAG::getMCSymbol(MCSymbol *Sym, EVT VT) {
  1343. SDNode *&N = MCSymbols[Sym];
  1344. if (N)
  1345. return SDValue(N, 0);
  1346. N = newSDNode<MCSymbolSDNode>(Sym, VT);
  1347. InsertNode(N);
  1348. return SDValue(N, 0);
  1349. }
  1350. SDValue SelectionDAG::getTargetExternalSymbol(const char *Sym, EVT VT,
  1351. unsigned char TargetFlags) {
  1352. SDNode *&N =
  1353. TargetExternalSymbols[std::pair<std::string,unsigned char>(Sym,
  1354. TargetFlags)];
  1355. if (N) return SDValue(N, 0);
  1356. N = newSDNode<ExternalSymbolSDNode>(true, Sym, TargetFlags, VT);
  1357. InsertNode(N);
  1358. return SDValue(N, 0);
  1359. }
  1360. SDValue SelectionDAG::getCondCode(ISD::CondCode Cond) {
  1361. if ((unsigned)Cond >= CondCodeNodes.size())
  1362. CondCodeNodes.resize(Cond+1);
  1363. if (!CondCodeNodes[Cond]) {
  1364. auto *N = newSDNode<CondCodeSDNode>(Cond);
  1365. CondCodeNodes[Cond] = N;
  1366. InsertNode(N);
  1367. }
  1368. return SDValue(CondCodeNodes[Cond], 0);
  1369. }
  1370. /// Swaps the values of N1 and N2. Swaps all indices in the shuffle mask M that
  1371. /// point at N1 to point at N2 and indices that point at N2 to point at N1.
  1372. static void commuteShuffle(SDValue &N1, SDValue &N2, MutableArrayRef<int> M) {
  1373. std::swap(N1, N2);
  1374. ShuffleVectorSDNode::commuteMask(M);
  1375. }
  1376. SDValue SelectionDAG::getVectorShuffle(EVT VT, const SDLoc &dl, SDValue N1,
  1377. SDValue N2, ArrayRef<int> Mask) {
  1378. assert(VT.getVectorNumElements() == Mask.size() &&
  1379. "Must have the same number of vector elements as mask elements!");
  1380. assert(VT == N1.getValueType() && VT == N2.getValueType() &&
  1381. "Invalid VECTOR_SHUFFLE");
  1382. // Canonicalize shuffle undef, undef -> undef
  1383. if (N1.isUndef() && N2.isUndef())
  1384. return getUNDEF(VT);
  1385. // Validate that all indices in Mask are within the range of the elements
  1386. // input to the shuffle.
  1387. int NElts = Mask.size();
  1388. assert(llvm::all_of(Mask,
  1389. [&](int M) { return M < (NElts * 2) && M >= -1; }) &&
  1390. "Index out of range");
  1391. // Copy the mask so we can do any needed cleanup.
  1392. SmallVector<int, 8> MaskVec(Mask.begin(), Mask.end());
  1393. // Canonicalize shuffle v, v -> v, undef
  1394. if (N1 == N2) {
  1395. N2 = getUNDEF(VT);
  1396. for (int i = 0; i != NElts; ++i)
  1397. if (MaskVec[i] >= NElts) MaskVec[i] -= NElts;
  1398. }
  1399. // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
  1400. if (N1.isUndef())
  1401. commuteShuffle(N1, N2, MaskVec);
  1402. if (TLI->hasVectorBlend()) {
  1403. // If shuffling a splat, try to blend the splat instead. We do this here so
  1404. // that even when this arises during lowering we don't have to re-handle it.
  1405. auto BlendSplat = [&](BuildVectorSDNode *BV, int Offset) {
  1406. BitVector UndefElements;
  1407. SDValue Splat = BV->getSplatValue(&UndefElements);
  1408. if (!Splat)
  1409. return;
  1410. for (int i = 0; i < NElts; ++i) {
  1411. if (MaskVec[i] < Offset || MaskVec[i] >= (Offset + NElts))
  1412. continue;
  1413. // If this input comes from undef, mark it as such.
  1414. if (UndefElements[MaskVec[i] - Offset]) {
  1415. MaskVec[i] = -1;
  1416. continue;
  1417. }
  1418. // If we can blend a non-undef lane, use that instead.
  1419. if (!UndefElements[i])
  1420. MaskVec[i] = i + Offset;
  1421. }
  1422. };
  1423. if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
  1424. BlendSplat(N1BV, 0);
  1425. if (auto *N2BV = dyn_cast<BuildVectorSDNode>(N2))
  1426. BlendSplat(N2BV, NElts);
  1427. }
  1428. // Canonicalize all index into lhs, -> shuffle lhs, undef
  1429. // Canonicalize all index into rhs, -> shuffle rhs, undef
  1430. bool AllLHS = true, AllRHS = true;
  1431. bool N2Undef = N2.isUndef();
  1432. for (int i = 0; i != NElts; ++i) {
  1433. if (MaskVec[i] >= NElts) {
  1434. if (N2Undef)
  1435. MaskVec[i] = -1;
  1436. else
  1437. AllLHS = false;
  1438. } else if (MaskVec[i] >= 0) {
  1439. AllRHS = false;
  1440. }
  1441. }
  1442. if (AllLHS && AllRHS)
  1443. return getUNDEF(VT);
  1444. if (AllLHS && !N2Undef)
  1445. N2 = getUNDEF(VT);
  1446. if (AllRHS) {
  1447. N1 = getUNDEF(VT);
  1448. commuteShuffle(N1, N2, MaskVec);
  1449. }
  1450. // Reset our undef status after accounting for the mask.
  1451. N2Undef = N2.isUndef();
  1452. // Re-check whether both sides ended up undef.
  1453. if (N1.isUndef() && N2Undef)
  1454. return getUNDEF(VT);
  1455. // If Identity shuffle return that node.
  1456. bool Identity = true, AllSame = true;
  1457. for (int i = 0; i != NElts; ++i) {
  1458. if (MaskVec[i] >= 0 && MaskVec[i] != i) Identity = false;
  1459. if (MaskVec[i] != MaskVec[0]) AllSame = false;
  1460. }
  1461. if (Identity && NElts)
  1462. return N1;
  1463. // Shuffling a constant splat doesn't change the result.
  1464. if (N2Undef) {
  1465. SDValue V = N1;
  1466. // Look through any bitcasts. We check that these don't change the number
  1467. // (and size) of elements and just changes their types.
  1468. while (V.getOpcode() == ISD::BITCAST)
  1469. V = V->getOperand(0);
  1470. // A splat should always show up as a build vector node.
  1471. if (auto *BV = dyn_cast<BuildVectorSDNode>(V)) {
  1472. BitVector UndefElements;
  1473. SDValue Splat = BV->getSplatValue(&UndefElements);
  1474. // If this is a splat of an undef, shuffling it is also undef.
  1475. if (Splat && Splat.isUndef())
  1476. return getUNDEF(VT);
  1477. bool SameNumElts =
  1478. V.getValueType().getVectorNumElements() == VT.getVectorNumElements();
  1479. // We only have a splat which can skip shuffles if there is a splatted
  1480. // value and no undef lanes rearranged by the shuffle.
  1481. if (Splat && UndefElements.none()) {
  1482. // Splat of <x, x, ..., x>, return <x, x, ..., x>, provided that the
  1483. // number of elements match or the value splatted is a zero constant.
  1484. if (SameNumElts)
  1485. return N1;
  1486. if (auto *C = dyn_cast<ConstantSDNode>(Splat))
  1487. if (C->isNullValue())
  1488. return N1;
  1489. }
  1490. // If the shuffle itself creates a splat, build the vector directly.
  1491. if (AllSame && SameNumElts) {
  1492. EVT BuildVT = BV->getValueType(0);
  1493. const SDValue &Splatted = BV->getOperand(MaskVec[0]);
  1494. SDValue NewBV = getSplatBuildVector(BuildVT, dl, Splatted);
  1495. // We may have jumped through bitcasts, so the type of the
  1496. // BUILD_VECTOR may not match the type of the shuffle.
  1497. if (BuildVT != VT)
  1498. NewBV = getNode(ISD::BITCAST, dl, VT, NewBV);
  1499. return NewBV;
  1500. }
  1501. }
  1502. }
  1503. FoldingSetNodeID ID;
  1504. SDValue Ops[2] = { N1, N2 };
  1505. AddNodeIDNode(ID, ISD::VECTOR_SHUFFLE, getVTList(VT), Ops);
  1506. for (int i = 0; i != NElts; ++i)
  1507. ID.AddInteger(MaskVec[i]);
  1508. void* IP = nullptr;
  1509. if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
  1510. return SDValue(E, 0);
  1511. // Allocate the mask array for the node out of the BumpPtrAllocator, since
  1512. // SDNode doesn't have access to it. This memory will be "leaked" when
  1513. // the node is deallocated, but recovered when the NodeAllocator is released.
  1514. int *MaskAlloc = OperandAllocator.Allocate<int>(NElts);
  1515. llvm::copy(MaskVec, MaskAlloc);
  1516. auto *N = newSDNode<ShuffleVectorSDNode>(VT, dl.getIROrder(),
  1517. dl.getDebugLoc(), MaskAlloc);
  1518. createOperands(N, Ops);
  1519. CSEMap.InsertNode(N, IP);
  1520. InsertNode(N);
  1521. SDValue V = SDValue(N, 0);
  1522. NewSDValueDbgMsg(V, "Creating new node: ", this);
  1523. return V;
  1524. }
  1525. SDValue SelectionDAG::getCommutedVectorShuffle(const ShuffleVectorSDNode &SV) {
  1526. EVT VT = SV.getValueType(0);
  1527. SmallVector<int, 8> MaskVec(SV.getMask().begin(), SV.getMask().end());
  1528. ShuffleVectorSDNode::commuteMask(MaskVec);
  1529. SDValue Op0 = SV.getOperand(0);
  1530. SDValue Op1 = SV.getOperand(1);
  1531. return getVectorShuffle(VT, SDLoc(&SV), Op1, Op0, MaskVec);
  1532. }
  1533. SDValue SelectionDAG::getRegister(unsigned RegNo, EVT VT) {
  1534. FoldingSetNodeID ID;
  1535. AddNodeIDNode(ID, ISD::Register, getVTList(VT), None);
  1536. ID.AddInteger(RegNo);
  1537. void *IP = nullptr;
  1538. if (SDNode *E = FindNodeOrInsertPos(ID, IP))
  1539. return SDValue(E, 0);
  1540. auto *N = newSDNode<RegisterSDNode>(RegNo, VT);
  1541. N->SDNodeBits.IsDivergent = TLI->isSDNodeSourceOfDivergence(N, FLI, DA);
  1542. CSEMap.InsertNode(N, IP);
  1543. InsertNode(N);
  1544. return SDValue(N, 0);
  1545. }
  1546. SDValue SelectionDAG::getRegisterMask(const uint32_t *RegMask) {
  1547. FoldingSetNodeID ID;
  1548. AddNodeIDNode(ID, ISD::RegisterMask, getVTList(MVT::Untyped), None);
  1549. ID.AddPointer(RegMask);
  1550. void *IP = nullptr;
  1551. if (SDNode *E = FindNodeOrInsertPos(ID, IP))
  1552. return SDValue(E, 0);
  1553. auto *N = newSDNode<RegisterMaskSDNode>(RegMask);
  1554. CSEMap.InsertNode(N, IP);
  1555. InsertNode(N);
  1556. return SDValue(N, 0);
  1557. }
  1558. SDValue SelectionDAG::getEHLabel(const SDLoc &dl, SDValue Root,
  1559. MCSymbol *Label) {
  1560. return getLabelNode(ISD::EH_LABEL, dl, Root, Label);
  1561. }
  1562. SDValue SelectionDAG::getLabelNode(unsigned Opcode, const SDLoc &dl,
  1563. SDValue Root, MCSymbol *Label) {
  1564. FoldingSetNodeID ID;
  1565. SDValue Ops[] = { Root };
  1566. AddNodeIDNode(ID, Opcode, getVTList(MVT::Other), Ops);
  1567. ID.AddPointer(Label);
  1568. void *IP = nullptr;
  1569. if (SDNode *E = FindNodeOrInsertPos(ID, IP))
  1570. return SDValue(E, 0);
  1571. auto *N = newSDNode<LabelSDNode>(dl.getIROrder(), dl.getDebugLoc(), Label);
  1572. createOperands(N, Ops);
  1573. CSEMap.InsertNode(N, IP);
  1574. InsertNode(N);
  1575. return SDValue(N, 0);
  1576. }
  1577. SDValue SelectionDAG::getBlockAddress(const BlockAddress *BA, EVT VT,
  1578. int64_t Offset,
  1579. bool isTarget,
  1580. unsigned char TargetFlags) {
  1581. unsigned Opc = isTarget ? ISD::TargetBlockAddress : ISD::BlockAddress;
  1582. FoldingSetNodeID ID;
  1583. AddNodeIDNode(ID, Opc, getVTList(VT), None);
  1584. ID.AddPointer(BA);
  1585. ID.AddInteger(Offset);
  1586. ID.AddInteger(TargetFlags);
  1587. void *IP = nullptr;
  1588. if (SDNode *E = FindNodeOrInsertPos(ID, IP))
  1589. return SDValue(E, 0);
  1590. auto *N = newSDNode<BlockAddressSDNode>(Opc, VT, BA, Offset, TargetFlags);
  1591. CSEMap.InsertNode(N, IP);
  1592. InsertNode(N);
  1593. return SDValue(N, 0);
  1594. }
  1595. SDValue SelectionDAG::getSrcValue(const Value *V) {
  1596. assert((!V || V->getType()->isPointerTy()) &&
  1597. "SrcValue is not a pointer?");
  1598. FoldingSetNodeID ID;
  1599. AddNodeIDNode(ID, ISD::SRCVALUE, getVTList(MVT::Other), None);
  1600. ID.AddPointer(V);
  1601. void *IP = nullptr;
  1602. if (SDNode *E = FindNodeOrInsertPos(ID, IP))
  1603. return SDValue(E, 0);
  1604. auto *N = newSDNode<SrcValueSDNode>(V);
  1605. CSEMap.InsertNode(N, IP);
  1606. InsertNode(N);
  1607. return SDValue(N, 0);
  1608. }
  1609. SDValue SelectionDAG::getMDNode(const MDNode *MD) {
  1610. FoldingSetNodeID ID;
  1611. AddNodeIDNode(ID, ISD::MDNODE_SDNODE, getVTList(MVT::Other), None);
  1612. ID.AddPointer(MD);
  1613. void *IP = nullptr;
  1614. if (SDNode *E = FindNodeOrInsertPos(ID, IP))
  1615. return SDValue(E, 0);
  1616. auto *N = newSDNode<MDNodeSDNode>(MD);
  1617. CSEMap.InsertNode(N, IP);
  1618. InsertNode(N);
  1619. return SDValue(N, 0);
  1620. }
  1621. SDValue SelectionDAG::getBitcast(EVT VT, SDValue V) {
  1622. if (VT == V.getValueType())
  1623. return V;
  1624. return getNode(ISD::BITCAST, SDLoc(V), VT, V);
  1625. }
  1626. SDValue SelectionDAG::getAddrSpaceCast(const SDLoc &dl, EVT VT, SDValue Ptr,
  1627. unsigned SrcAS, unsigned DestAS) {
  1628. SDValue Ops[] = {Ptr};
  1629. FoldingSetNodeID ID;
  1630. AddNodeIDNode(ID, ISD::ADDRSPACECAST, getVTList(VT), Ops);
  1631. ID.AddInteger(SrcAS);
  1632. ID.AddInteger(DestAS);
  1633. void *IP = nullptr;
  1634. if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
  1635. return SDValue(E, 0);
  1636. auto *N = newSDNode<AddrSpaceCastSDNode>(dl.getIROrder(), dl.getDebugLoc(),
  1637. VT, SrcAS, DestAS);
  1638. createOperands(N, Ops);
  1639. CSEMap.InsertNode(N, IP);
  1640. InsertNode(N);
  1641. return SDValue(N, 0);
  1642. }
  1643. /// getShiftAmountOperand - Return the specified value casted to
  1644. /// the target's desired shift amount type.
  1645. SDValue SelectionDAG::getShiftAmountOperand(EVT LHSTy, SDValue Op) {
  1646. EVT OpTy = Op.getValueType();
  1647. EVT ShTy = TLI->getShiftAmountTy(LHSTy, getDataLayout());
  1648. if (OpTy == ShTy || OpTy.isVector()) return Op;
  1649. return getZExtOrTrunc(Op, SDLoc(Op), ShTy);
  1650. }
  1651. SDValue SelectionDAG::expandVAArg(SDNode *Node) {
  1652. SDLoc dl(Node);
  1653. const TargetLowering &TLI = getTargetLoweringInfo();
  1654. const Value *V = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
  1655. EVT VT = Node->getValueType(0);
  1656. SDValue Tmp1 = Node->getOperand(0);
  1657. SDValue Tmp2 = Node->getOperand(1);
  1658. unsigned Align = Node->getConstantOperandVal(3);
  1659. SDValue VAListLoad = getLoad(TLI.getPointerTy(getDataLayout()), dl, Tmp1,
  1660. Tmp2, MachinePointerInfo(V));
  1661. SDValue VAList = VAListLoad;
  1662. if (Align > TLI.getMinStackArgumentAlignment()) {
  1663. assert(((Align & (Align-1)) == 0) && "Expected Align to be a power of 2");
  1664. VAList = getNode(ISD::ADD, dl, VAList.getValueType(), VAList,
  1665. getConstant(Align - 1, dl, VAList.getValueType()));
  1666. VAList = getNode(ISD::AND, dl, VAList.getValueType(), VAList,
  1667. getConstant(-(int64_t)Align, dl, VAList.getValueType()));
  1668. }
  1669. // Increment the pointer, VAList, to the next vaarg
  1670. Tmp1 = getNode(ISD::ADD, dl, VAList.getValueType(), VAList,
  1671. getConstant(getDataLayout().getTypeAllocSize(
  1672. VT.getTypeForEVT(*getContext())),
  1673. dl, VAList.getValueType()));
  1674. // Store the incremented VAList to the legalized pointer
  1675. Tmp1 =
  1676. getStore(VAListLoad.getValue(1), dl, Tmp1, Tmp2, MachinePointerInfo(V));
  1677. // Load the actual argument out of the pointer VAList
  1678. return getLoad(VT, dl, Tmp1, VAList, MachinePointerInfo());
  1679. }
  1680. SDValue SelectionDAG::expandVACopy(SDNode *Node) {
  1681. SDLoc dl(Node);
  1682. const TargetLowering &TLI = getTargetLoweringInfo();
  1683. // This defaults to loading a pointer from the input and storing it to the
  1684. // output, returning the chain.
  1685. const Value *VD = cast<SrcValueSDNode>(Node->getOperand(3))->getValue();
  1686. const Value *VS = cast<SrcValueSDNode>(Node->getOperand(4))->getValue();
  1687. SDValue Tmp1 =
  1688. getLoad(TLI.getPointerTy(getDataLayout()), dl, Node->getOperand(0),
  1689. Node->getOperand(2), MachinePointerInfo(VS));
  1690. return getStore(Tmp1.getValue(1), dl, Tmp1, Node->getOperand(1),
  1691. MachinePointerInfo(VD));
  1692. }
  1693. SDValue SelectionDAG::CreateStackTemporary(EVT VT, unsigned minAlign) {
  1694. MachineFrameInfo &MFI = getMachineFunction().getFrameInfo();
  1695. unsigned ByteSize = VT.getStoreSize();
  1696. Type *Ty = VT.getTypeForEVT(*getContext());
  1697. unsigned StackAlign =
  1698. std::max((unsigned)getDataLayout().getPrefTypeAlignment(Ty), minAlign);
  1699. int FrameIdx = MFI.CreateStackObject(ByteSize, StackAlign, false);
  1700. return getFrameIndex(FrameIdx, TLI->getFrameIndexTy(getDataLayout()));
  1701. }
  1702. SDValue SelectionDAG::CreateStackTemporary(EVT VT1, EVT VT2) {
  1703. unsigned Bytes = std::max(VT1.getStoreSize(), VT2.getStoreSize());
  1704. Type *Ty1 = VT1.getTypeForEVT(*getContext());
  1705. Type *Ty2 = VT2.getTypeForEVT(*getContext());
  1706. const DataLayout &DL = getDataLayout();
  1707. unsigned Align =
  1708. std::max(DL.getPrefTypeAlignment(Ty1), DL.getPrefTypeAlignment(Ty2));
  1709. MachineFrameInfo &MFI = getMachineFunction().getFrameInfo();
  1710. int FrameIdx = MFI.CreateStackObject(Bytes, Align, false);
  1711. return getFrameIndex(FrameIdx, TLI->getFrameIndexTy(getDataLayout()));
  1712. }
  1713. SDValue SelectionDAG::FoldSetCC(EVT VT, SDValue N1, SDValue N2,
  1714. ISD::CondCode Cond, const SDLoc &dl) {
  1715. EVT OpVT = N1.getValueType();
  1716. // These setcc operations always fold.
  1717. switch (Cond) {
  1718. default: break;
  1719. case ISD::SETFALSE:
  1720. case ISD::SETFALSE2: return getBoolConstant(false, dl, VT, OpVT);
  1721. case ISD::SETTRUE:
  1722. case ISD::SETTRUE2: return getBoolConstant(true, dl, VT, OpVT);
  1723. case ISD::SETOEQ:
  1724. case ISD::SETOGT:
  1725. case ISD::SETOGE:
  1726. case ISD::SETOLT:
  1727. case ISD::SETOLE:
  1728. case ISD::SETONE:
  1729. case ISD::SETO:
  1730. case ISD::SETUO:
  1731. case ISD::SETUEQ:
  1732. case ISD::SETUNE:
  1733. assert(!OpVT.isInteger() && "Illegal setcc for integer!");
  1734. break;
  1735. }
  1736. if (OpVT.isInteger()) {
  1737. // For EQ and NE, we can always pick a value for the undef to make the
  1738. // predicate pass or fail, so we can return undef.
  1739. // Matches behavior in llvm::ConstantFoldCompareInstruction.
  1740. // icmp eq/ne X, undef -> undef.
  1741. if ((N1.isUndef() || N2.isUndef()) &&
  1742. (Cond == ISD::SETEQ || Cond == ISD::SETNE))
  1743. return getUNDEF(VT);
  1744. // If both operands are undef, we can return undef for int comparison.
  1745. // icmp undef, undef -> undef.
  1746. if (N1.isUndef() && N2.isUndef())
  1747. return getUNDEF(VT);
  1748. // icmp X, X -> true/false
  1749. // icmp X, undef -> true/false because undef could be X.
  1750. if (N1 == N2)
  1751. return getBoolConstant(ISD::isTrueWhenEqual(Cond), dl, VT, OpVT);
  1752. }
  1753. if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2)) {
  1754. const APInt &C2 = N2C->getAPIntValue();
  1755. if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1)) {
  1756. const APInt &C1 = N1C->getAPIntValue();
  1757. switch (Cond) {
  1758. default: llvm_unreachable("Unknown integer setcc!");
  1759. case ISD::SETEQ: return getBoolConstant(C1 == C2, dl, VT, OpVT);
  1760. case ISD::SETNE: return getBoolConstant(C1 != C2, dl, VT, OpVT);
  1761. case ISD::SETULT: return getBoolConstant(C1.ult(C2), dl, VT, OpVT);
  1762. case ISD::SETUGT: return getBoolConstant(C1.ugt(C2), dl, VT, OpVT);
  1763. case ISD::SETULE: return getBoolConstant(C1.ule(C2), dl, VT, OpVT);
  1764. case ISD::SETUGE: return getBoolConstant(C1.uge(C2), dl, VT, OpVT);
  1765. case ISD::SETLT: return getBoolConstant(C1.slt(C2), dl, VT, OpVT);
  1766. case ISD::SETGT: return getBoolConstant(C1.sgt(C2), dl, VT, OpVT);
  1767. case ISD::SETLE: return getBoolConstant(C1.sle(C2), dl, VT, OpVT);
  1768. case ISD::SETGE: return getBoolConstant(C1.sge(C2), dl, VT, OpVT);
  1769. }
  1770. }
  1771. }
  1772. auto *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
  1773. auto *N2CFP = dyn_cast<ConstantFPSDNode>(N2);
  1774. if (N1CFP && N2CFP) {
  1775. APFloat::cmpResult R = N1CFP->getValueAPF().compare(N2CFP->getValueAPF());
  1776. switch (Cond) {
  1777. default: break;
  1778. case ISD::SETEQ: if (R==APFloat::cmpUnordered)
  1779. return getUNDEF(VT);
  1780. LLVM_FALLTHROUGH;
  1781. case ISD::SETOEQ: return getBoolConstant(R==APFloat::cmpEqual, dl, VT,
  1782. OpVT);
  1783. case ISD::SETNE: if (R==APFloat::cmpUnordered)
  1784. return getUNDEF(VT);
  1785. LLVM_FALLTHROUGH;
  1786. case ISD::SETONE: return getBoolConstant(R==APFloat::cmpGreaterThan ||
  1787. R==APFloat::cmpLessThan, dl, VT,
  1788. OpVT);
  1789. case ISD::SETLT: if (R==APFloat::cmpUnordered)
  1790. return getUNDEF(VT);
  1791. LLVM_FALLTHROUGH;
  1792. case ISD::SETOLT: return getBoolConstant(R==APFloat::cmpLessThan, dl, VT,
  1793. OpVT);
  1794. case ISD::SETGT: if (R==APFloat::cmpUnordered)
  1795. return getUNDEF(VT);
  1796. LLVM_FALLTHROUGH;
  1797. case ISD::SETOGT: return getBoolConstant(R==APFloat::cmpGreaterThan, dl,
  1798. VT, OpVT);
  1799. case ISD::SETLE: if (R==APFloat::cmpUnordered)
  1800. return getUNDEF(VT);
  1801. LLVM_FALLTHROUGH;
  1802. case ISD::SETOLE: return getBoolConstant(R==APFloat::cmpLessThan ||
  1803. R==APFloat::cmpEqual, dl, VT,
  1804. OpVT);
  1805. case ISD::SETGE: if (R==APFloat::cmpUnordered)
  1806. return getUNDEF(VT);
  1807. LLVM_FALLTHROUGH;
  1808. case ISD::SETOGE: return getBoolConstant(R==APFloat::cmpGreaterThan ||
  1809. R==APFloat::cmpEqual, dl, VT, OpVT);
  1810. case ISD::SETO: return getBoolConstant(R!=APFloat::cmpUnordered, dl, VT,
  1811. OpVT);
  1812. case ISD::SETUO: return getBoolConstant(R==APFloat::cmpUnordered, dl, VT,
  1813. OpVT);
  1814. case ISD::SETUEQ: return getBoolConstant(R==APFloat::cmpUnordered ||
  1815. R==APFloat::cmpEqual, dl, VT,
  1816. OpVT);
  1817. case ISD::SETUNE: return getBoolConstant(R!=APFloat::cmpEqual, dl, VT,
  1818. OpVT);
  1819. case ISD::SETULT: return getBoolConstant(R==APFloat::cmpUnordered ||
  1820. R==APFloat::cmpLessThan, dl, VT,
  1821. OpVT);
  1822. case ISD::SETUGT: return getBoolConstant(R==APFloat::cmpGreaterThan ||
  1823. R==APFloat::cmpUnordered, dl, VT,
  1824. OpVT);
  1825. case ISD::SETULE: return getBoolConstant(R!=APFloat::cmpGreaterThan, dl,
  1826. VT, OpVT);
  1827. case ISD::SETUGE: return getBoolConstant(R!=APFloat::cmpLessThan, dl, VT,
  1828. OpVT);
  1829. }
  1830. } else if (N1CFP && OpVT.isSimple()) {
  1831. // Ensure that the constant occurs on the RHS.
  1832. ISD::CondCode SwappedCond = ISD::getSetCCSwappedOperands(Cond);
  1833. if (!TLI->isCondCodeLegal(SwappedCond, OpVT.getSimpleVT()))
  1834. return SDValue();
  1835. return getSetCC(dl, VT, N2, N1, SwappedCond);
  1836. } else if (N2CFP && N2CFP->getValueAPF().isNaN()) {
  1837. // If an operand is known to be a nan, we can fold it.
  1838. switch (ISD::getUnorderedFlavor(Cond)) {
  1839. default:
  1840. llvm_unreachable("Unknown flavor!");
  1841. case 0: // Known false.
  1842. return getBoolConstant(false, dl, VT, OpVT);
  1843. case 1: // Known true.
  1844. return getBoolConstant(true, dl, VT, OpVT);
  1845. case 2: // Undefined.
  1846. return getUNDEF(VT);
  1847. }
  1848. }
  1849. // Could not fold it.
  1850. return SDValue();
  1851. }
  1852. /// See if the specified operand can be simplified with the knowledge that only
  1853. /// the bits specified by Mask are used.
  1854. SDValue SelectionDAG::GetDemandedBits(SDValue V, const APInt &Mask) {
  1855. switch (V.getOpcode()) {
  1856. default:
  1857. break;
  1858. case ISD::Constant: {
  1859. const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
  1860. assert(CV && "Const value should be ConstSDNode.");
  1861. const APInt &CVal = CV->getAPIntValue();
  1862. APInt NewVal = CVal & Mask;
  1863. if (NewVal != CVal)
  1864. return getConstant(NewVal, SDLoc(V), V.getValueType());
  1865. break;
  1866. }
  1867. case ISD::OR:
  1868. case ISD::XOR:
  1869. // If the LHS or RHS don't contribute bits to the or, drop them.
  1870. if (MaskedValueIsZero(V.getOperand(0), Mask))
  1871. return V.getOperand(1);
  1872. if (MaskedValueIsZero(V.getOperand(1), Mask))
  1873. return V.getOperand(0);
  1874. break;
  1875. case ISD::SRL:
  1876. // Only look at single-use SRLs.
  1877. if (!V.getNode()->hasOneUse())
  1878. break;
  1879. if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
  1880. // See if we can recursively simplify the LHS.
  1881. unsigned Amt = RHSC->getZExtValue();
  1882. // Watch out for shift count overflow though.
  1883. if (Amt >= Mask.getBitWidth())
  1884. break;
  1885. APInt NewMask = Mask << Amt;
  1886. if (SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask))
  1887. return getNode(ISD::SRL, SDLoc(V), V.getValueType(), SimplifyLHS,
  1888. V.getOperand(1));
  1889. }
  1890. break;
  1891. case ISD::AND: {
  1892. // X & -1 -> X (ignoring bits which aren't demanded).
  1893. // Also handle the case where masked out bits in X are known to be zero.
  1894. if (ConstantSDNode *RHSC = isConstOrConstSplat(V.getOperand(1))) {
  1895. const APInt &AndVal = RHSC->getAPIntValue();
  1896. if (Mask.isSubsetOf(AndVal) ||
  1897. Mask.isSubsetOf(computeKnownBits(V.getOperand(0)).Zero | AndVal))
  1898. return V.getOperand(0);
  1899. }
  1900. break;
  1901. }
  1902. case ISD::ANY_EXTEND: {
  1903. SDValue Src = V.getOperand(0);
  1904. unsigned SrcBitWidth = Src.getScalarValueSizeInBits();
  1905. // Being conservative here - only peek through if we only demand bits in the
  1906. // non-extended source (even though the extended bits are technically undef).
  1907. if (Mask.getActiveBits() > SrcBitWidth)
  1908. break;
  1909. APInt SrcMask = Mask.trunc(SrcBitWidth);
  1910. if (SDValue DemandedSrc = GetDemandedBits(Src, SrcMask))
  1911. return getNode(ISD::ANY_EXTEND, SDLoc(V), V.getValueType(), DemandedSrc);
  1912. break;
  1913. }
  1914. case ISD::SIGN_EXTEND_INREG:
  1915. EVT ExVT = cast<VTSDNode>(V.getOperand(1))->getVT();
  1916. unsigned ExVTBits = ExVT.getScalarSizeInBits();
  1917. // If none of the extended bits are demanded, eliminate the sextinreg.
  1918. if (Mask.getActiveBits() <= ExVTBits)
  1919. return V.getOperand(0);
  1920. break;
  1921. }
  1922. return SDValue();
  1923. }
  1924. /// SignBitIsZero - Return true if the sign bit of Op is known to be zero. We
  1925. /// use this predicate to simplify operations downstream.
  1926. bool SelectionDAG::SignBitIsZero(SDValue Op, unsigned Depth) const {
  1927. unsigned BitWidth = Op.getScalarValueSizeInBits();
  1928. return MaskedValueIsZero(Op, APInt::getSignMask(BitWidth), Depth);
  1929. }
  1930. /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
  1931. /// this predicate to simplify operations downstream. Mask is known to be zero
  1932. /// for bits that V cannot have.
  1933. bool SelectionDAG::MaskedValueIsZero(SDValue Op, const APInt &Mask,
  1934. unsigned Depth) const {
  1935. return Mask.isSubsetOf(computeKnownBits(Op, Depth).Zero);
  1936. }
  1937. /// isSplatValue - Return true if the vector V has the same value
  1938. /// across all DemandedElts.
  1939. bool SelectionDAG::isSplatValue(SDValue V, const APInt &DemandedElts,
  1940. APInt &UndefElts) {
  1941. if (!DemandedElts)
  1942. return false; // No demanded elts, better to assume we don't know anything.
  1943. EVT VT = V.getValueType();
  1944. assert(VT.isVector() && "Vector type expected");
  1945. unsigned NumElts = VT.getVectorNumElements();
  1946. assert(NumElts == DemandedElts.getBitWidth() && "Vector size mismatch");
  1947. UndefElts = APInt::getNullValue(NumElts);
  1948. switch (V.getOpcode()) {
  1949. case ISD::BUILD_VECTOR: {
  1950. SDValue Scl;
  1951. for (unsigned i = 0; i != NumElts; ++i) {
  1952. SDValue Op = V.getOperand(i);
  1953. if (Op.isUndef()) {
  1954. UndefElts.setBit(i);
  1955. continue;
  1956. }
  1957. if (!DemandedElts[i])
  1958. continue;
  1959. if (Scl && Scl != Op)
  1960. return false;
  1961. Scl = Op;
  1962. }
  1963. return true;
  1964. }
  1965. case ISD::VECTOR_SHUFFLE: {
  1966. // Check if this is a shuffle node doing a splat.
  1967. // TODO: Do we need to handle shuffle(splat, undef, mask)?
  1968. int SplatIndex = -1;
  1969. ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(V)->getMask();
  1970. for (int i = 0; i != (int)NumElts; ++i) {
  1971. int M = Mask[i];
  1972. if (M < 0) {
  1973. UndefElts.setBit(i);
  1974. continue;
  1975. }
  1976. if (!DemandedElts[i])
  1977. continue;
  1978. if (0 <= SplatIndex && SplatIndex != M)
  1979. return false;
  1980. SplatIndex = M;
  1981. }
  1982. return true;
  1983. }
  1984. case ISD::EXTRACT_SUBVECTOR: {
  1985. SDValue Src = V.getOperand(0);
  1986. ConstantSDNode *SubIdx = dyn_cast<ConstantSDNode>(V.getOperand(1));
  1987. unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
  1988. if (SubIdx && SubIdx->getAPIntValue().ule(NumSrcElts - NumElts)) {
  1989. // Offset the demanded elts by the subvector index.
  1990. uint64_t Idx = SubIdx->getZExtValue();
  1991. APInt UndefSrcElts;
  1992. APInt DemandedSrc = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx);
  1993. if (isSplatValue(Src, DemandedSrc, UndefSrcElts)) {
  1994. UndefElts = UndefSrcElts.extractBits(NumElts, Idx);
  1995. return true;
  1996. }
  1997. }
  1998. break;
  1999. }
  2000. case ISD::ADD:
  2001. case ISD::SUB:
  2002. case ISD::AND: {
  2003. APInt UndefLHS, UndefRHS;
  2004. SDValue LHS = V.getOperand(0);
  2005. SDValue RHS = V.getOperand(1);
  2006. if (isSplatValue(LHS, DemandedElts, UndefLHS) &&
  2007. isSplatValue(RHS, DemandedElts, UndefRHS)) {
  2008. UndefElts = UndefLHS | UndefRHS;
  2009. return true;
  2010. }
  2011. break;
  2012. }
  2013. }
  2014. return false;
  2015. }
  2016. /// Helper wrapper to main isSplatValue function.
  2017. bool SelectionDAG::isSplatValue(SDValue V, bool AllowUndefs) {
  2018. EVT VT = V.getValueType();
  2019. assert(VT.isVector() && "Vector type expected");
  2020. unsigned NumElts = VT.getVectorNumElements();
  2021. APInt UndefElts;
  2022. APInt DemandedElts = APInt::getAllOnesValue(NumElts);
  2023. return isSplatValue(V, DemandedElts, UndefElts) &&
  2024. (AllowUndefs || !UndefElts);
  2025. }
  2026. /// If a SHL/SRA/SRL node has a constant or splat constant shift amount that
  2027. /// is less than the element bit-width of the shift node, return it.
  2028. static const APInt *getValidShiftAmountConstant(SDValue V) {
  2029. if (ConstantSDNode *SA = isConstOrConstSplat(V.getOperand(1))) {
  2030. // Shifting more than the bitwidth is not valid.
  2031. const APInt &ShAmt = SA->getAPIntValue();
  2032. if (ShAmt.ult(V.getScalarValueSizeInBits()))
  2033. return &ShAmt;
  2034. }
  2035. return nullptr;
  2036. }
  2037. /// Determine which bits of Op are known to be either zero or one and return
  2038. /// them in Known. For vectors, the known bits are those that are shared by
  2039. /// every vector element.
  2040. KnownBits SelectionDAG::computeKnownBits(SDValue Op, unsigned Depth) const {
  2041. EVT VT = Op.getValueType();
  2042. APInt DemandedElts = VT.isVector()
  2043. ? APInt::getAllOnesValue(VT.getVectorNumElements())
  2044. : APInt(1, 1);
  2045. return computeKnownBits(Op, DemandedElts, Depth);
  2046. }
  2047. /// Determine which bits of Op are known to be either zero or one and return
  2048. /// them in Known. The DemandedElts argument allows us to only collect the known
  2049. /// bits that are shared by the requested vector elements.
  2050. KnownBits SelectionDAG::computeKnownBits(SDValue Op, const APInt &DemandedElts,
  2051. unsigned Depth) const {
  2052. unsigned BitWidth = Op.getScalarValueSizeInBits();
  2053. KnownBits Known(BitWidth); // Don't know anything.
  2054. if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
  2055. // We know all of the bits for a constant!
  2056. Known.One = C->getAPIntValue();
  2057. Known.Zero = ~Known.One;
  2058. return Known;
  2059. }
  2060. if (auto *C = dyn_cast<ConstantFPSDNode>(Op)) {
  2061. // We know all of the bits for a constant fp!
  2062. Known.One = C->getValueAPF().bitcastToAPInt();
  2063. Known.Zero = ~Known.One;
  2064. return Known;
  2065. }
  2066. if (Depth == 6)
  2067. return Known; // Limit search depth.
  2068. KnownBits Known2;
  2069. unsigned NumElts = DemandedElts.getBitWidth();
  2070. assert((!Op.getValueType().isVector() ||
  2071. NumElts == Op.getValueType().getVectorNumElements()) &&
  2072. "Unexpected vector size");
  2073. if (!DemandedElts)
  2074. return Known; // No demanded elts, better to assume we don't know anything.
  2075. unsigned Opcode = Op.getOpcode();
  2076. switch (Opcode) {
  2077. case ISD::BUILD_VECTOR:
  2078. // Collect the known bits that are shared by every demanded vector element.
  2079. Known.Zero.setAllBits(); Known.One.setAllBits();
  2080. for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
  2081. if (!DemandedElts[i])
  2082. continue;
  2083. SDValue SrcOp = Op.getOperand(i);
  2084. Known2 = computeKnownBits(SrcOp, Depth + 1);
  2085. // BUILD_VECTOR can implicitly truncate sources, we must handle this.
  2086. if (SrcOp.getValueSizeInBits() != BitWidth) {
  2087. assert(SrcOp.getValueSizeInBits() > BitWidth &&
  2088. "Expected BUILD_VECTOR implicit truncation");
  2089. Known2 = Known2.trunc(BitWidth);
  2090. }
  2091. // Known bits are the values that are shared by every demanded element.
  2092. Known.One &= Known2.One;
  2093. Known.Zero &= Known2.Zero;
  2094. // If we don't know any bits, early out.
  2095. if (Known.isUnknown())
  2096. break;
  2097. }
  2098. break;
  2099. case ISD::VECTOR_SHUFFLE: {
  2100. // Collect the known bits that are shared by every vector element referenced
  2101. // by the shuffle.
  2102. APInt DemandedLHS(NumElts, 0), DemandedRHS(NumElts, 0);
  2103. Known.Zero.setAllBits(); Known.One.setAllBits();
  2104. const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
  2105. assert(NumElts == SVN->getMask().size() && "Unexpected vector size");
  2106. for (unsigned i = 0; i != NumElts; ++i) {
  2107. if (!DemandedElts[i])
  2108. continue;
  2109. int M = SVN->getMaskElt(i);
  2110. if (M < 0) {
  2111. // For UNDEF elements, we don't know anything about the common state of
  2112. // the shuffle result.
  2113. Known.resetAll();
  2114. DemandedLHS.clearAllBits();
  2115. DemandedRHS.clearAllBits();
  2116. break;
  2117. }
  2118. if ((unsigned)M < NumElts)
  2119. DemandedLHS.setBit((unsigned)M % NumElts);
  2120. else
  2121. DemandedRHS.setBit((unsigned)M % NumElts);
  2122. }
  2123. // Known bits are the values that are shared by every demanded element.
  2124. if (!!DemandedLHS) {
  2125. SDValue LHS = Op.getOperand(0);
  2126. Known2 = computeKnownBits(LHS, DemandedLHS, Depth + 1);
  2127. Known.One &= Known2.One;
  2128. Known.Zero &= Known2.Zero;
  2129. }
  2130. // If we don't know any bits, early out.
  2131. if (Known.isUnknown())
  2132. break;
  2133. if (!!DemandedRHS) {
  2134. SDValue RHS = Op.getOperand(1);
  2135. Known2 = computeKnownBits(RHS, DemandedRHS, Depth + 1);
  2136. Known.One &= Known2.One;
  2137. Known.Zero &= Known2.Zero;
  2138. }
  2139. break;
  2140. }
  2141. case ISD::CONCAT_VECTORS: {
  2142. // Split DemandedElts and test each of the demanded subvectors.
  2143. Known.Zero.setAllBits(); Known.One.setAllBits();
  2144. EVT SubVectorVT = Op.getOperand(0).getValueType();
  2145. unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements();
  2146. unsigned NumSubVectors = Op.getNumOperands();
  2147. for (unsigned i = 0; i != NumSubVectors; ++i) {
  2148. APInt DemandedSub = DemandedElts.lshr(i * NumSubVectorElts);
  2149. DemandedSub = DemandedSub.trunc(NumSubVectorElts);
  2150. if (!!DemandedSub) {
  2151. SDValue Sub = Op.getOperand(i);
  2152. Known2 = computeKnownBits(Sub, DemandedSub, Depth + 1);
  2153. Known.One &= Known2.One;
  2154. Known.Zero &= Known2.Zero;
  2155. }
  2156. // If we don't know any bits, early out.
  2157. if (Known.isUnknown())
  2158. break;
  2159. }
  2160. break;
  2161. }
  2162. case ISD::INSERT_SUBVECTOR: {
  2163. // If we know the element index, demand any elements from the subvector and
  2164. // the remainder from the src its inserted into, otherwise demand them all.
  2165. SDValue Src = Op.getOperand(0);
  2166. SDValue Sub = Op.getOperand(1);
  2167. ConstantSDNode *SubIdx = dyn_cast<ConstantSDNode>(Op.getOperand(2));
  2168. unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
  2169. if (SubIdx && SubIdx->getAPIntValue().ule(NumElts - NumSubElts)) {
  2170. Known.One.setAllBits();
  2171. Known.Zero.setAllBits();
  2172. uint64_t Idx = SubIdx->getZExtValue();
  2173. APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
  2174. if (!!DemandedSubElts) {
  2175. Known = computeKnownBits(Sub, DemandedSubElts, Depth + 1);
  2176. if (Known.isUnknown())
  2177. break; // early-out.
  2178. }
  2179. APInt SubMask = APInt::getBitsSet(NumElts, Idx, Idx + NumSubElts);
  2180. APInt DemandedSrcElts = DemandedElts & ~SubMask;
  2181. if (!!DemandedSrcElts) {
  2182. Known2 = computeKnownBits(Src, DemandedSrcElts, Depth + 1);
  2183. Known.One &= Known2.One;
  2184. Known.Zero &= Known2.Zero;
  2185. }
  2186. } else {
  2187. Known = computeKnownBits(Sub, Depth + 1);
  2188. if (Known.isUnknown())
  2189. break; // early-out.
  2190. Known2 = computeKnownBits(Src, Depth + 1);
  2191. Known.One &= Known2.One;
  2192. Known.Zero &= Known2.Zero;
  2193. }
  2194. break;
  2195. }
  2196. case ISD::EXTRACT_SUBVECTOR: {
  2197. // If we know the element index, just demand that subvector elements,
  2198. // otherwise demand them all.
  2199. SDValue Src = Op.getOperand(0);
  2200. ConstantSDNode *SubIdx = dyn_cast<ConstantSDNode>(Op.getOperand(1));
  2201. unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
  2202. if (SubIdx && SubIdx->getAPIntValue().ule(NumSrcElts - NumElts)) {
  2203. // Offset the demanded elts by the subvector index.
  2204. uint64_t Idx = SubIdx->getZExtValue();
  2205. APInt DemandedSrc = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx);
  2206. Known = computeKnownBits(Src, DemandedSrc, Depth + 1);
  2207. } else {
  2208. Known = computeKnownBits(Src, Depth + 1);
  2209. }
  2210. break;
  2211. }
  2212. case ISD::SCALAR_TO_VECTOR: {
  2213. // We know about scalar_to_vector as much as we know about it source,
  2214. // which becomes the first element of otherwise unknown vector.
  2215. if (DemandedElts != 1)
  2216. break;
  2217. SDValue N0 = Op.getOperand(0);
  2218. Known = computeKnownBits(N0, Depth + 1);
  2219. if (N0.getValueSizeInBits() != BitWidth)
  2220. Known = Known.trunc(BitWidth);
  2221. break;
  2222. }
  2223. case ISD::BITCAST: {
  2224. SDValue N0 = Op.getOperand(0);
  2225. EVT SubVT = N0.getValueType();
  2226. unsigned SubBitWidth = SubVT.getScalarSizeInBits();
  2227. // Ignore bitcasts from unsupported types.
  2228. if (!(SubVT.isInteger() || SubVT.isFloatingPoint()))
  2229. break;
  2230. // Fast handling of 'identity' bitcasts.
  2231. if (BitWidth == SubBitWidth) {
  2232. Known = computeKnownBits(N0, DemandedElts, Depth + 1);
  2233. break;
  2234. }
  2235. bool IsLE = getDataLayout().isLittleEndian();
  2236. // Bitcast 'small element' vector to 'large element' scalar/vector.
  2237. if ((BitWidth % SubBitWidth) == 0) {
  2238. assert(N0.getValueType().isVector() && "Expected bitcast from vector");
  2239. // Collect known bits for the (larger) output by collecting the known
  2240. // bits from each set of sub elements and shift these into place.
  2241. // We need to separately call computeKnownBits for each set of
  2242. // sub elements as the knownbits for each is likely to be different.
  2243. unsigned SubScale = BitWidth / SubBitWidth;
  2244. APInt SubDemandedElts(NumElts * SubScale, 0);
  2245. for (unsigned i = 0; i != NumElts; ++i)
  2246. if (DemandedElts[i])
  2247. SubDemandedElts.setBit(i * SubScale);
  2248. for (unsigned i = 0; i != SubScale; ++i) {
  2249. Known2 = computeKnownBits(N0, SubDemandedElts.shl(i),
  2250. Depth + 1);
  2251. unsigned Shifts = IsLE ? i : SubScale - 1 - i;
  2252. Known.One |= Known2.One.zext(BitWidth).shl(SubBitWidth * Shifts);
  2253. Known.Zero |= Known2.Zero.zext(BitWidth).shl(SubBitWidth * Shifts);
  2254. }
  2255. }
  2256. // Bitcast 'large element' scalar/vector to 'small element' vector.
  2257. if ((SubBitWidth % BitWidth) == 0) {
  2258. assert(Op.getValueType().isVector() && "Expected bitcast to vector");
  2259. // Collect known bits for the (smaller) output by collecting the known
  2260. // bits from the overlapping larger input elements and extracting the
  2261. // sub sections we actually care about.
  2262. unsigned SubScale = SubBitWidth / BitWidth;
  2263. APInt SubDemandedElts(NumElts / SubScale, 0);
  2264. for (unsigned i = 0; i != NumElts; ++i)
  2265. if (DemandedElts[i])
  2266. SubDemandedElts.setBit(i / SubScale);
  2267. Known2 = computeKnownBits(N0, SubDemandedElts, Depth + 1);
  2268. Known.Zero.setAllBits(); Known.One.setAllBits();
  2269. for (unsigned i = 0; i != NumElts; ++i)
  2270. if (DemandedElts[i]) {
  2271. unsigned Shifts = IsLE ? i : NumElts - 1 - i;
  2272. unsigned Offset = (Shifts % SubScale) * BitWidth;
  2273. Known.One &= Known2.One.lshr(Offset).trunc(BitWidth);
  2274. Known.Zero &= Known2.Zero.lshr(Offset).trunc(BitWidth);
  2275. // If we don't know any bits, early out.
  2276. if (Known.isUnknown())
  2277. break;
  2278. }
  2279. }
  2280. break;
  2281. }
  2282. case ISD::AND:
  2283. // If either the LHS or the RHS are Zero, the result is zero.
  2284. Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
  2285. Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
  2286. // Output known-1 bits are only known if set in both the LHS & RHS.
  2287. Known.One &= Known2.One;
  2288. // Output known-0 are known to be clear if zero in either the LHS | RHS.
  2289. Known.Zero |= Known2.Zero;
  2290. break;
  2291. case ISD::OR:
  2292. Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
  2293. Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
  2294. // Output known-0 bits are only known if clear in both the LHS & RHS.
  2295. Known.Zero &= Known2.Zero;
  2296. // Output known-1 are known to be set if set in either the LHS | RHS.
  2297. Known.One |= Known2.One;
  2298. break;
  2299. case ISD::XOR: {
  2300. Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
  2301. Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
  2302. // Output known-0 bits are known if clear or set in both the LHS & RHS.
  2303. APInt KnownZeroOut = (Known.Zero & Known2.Zero) | (Known.One & Known2.One);
  2304. // Output known-1 are known to be set if set in only one of the LHS, RHS.
  2305. Known.One = (Known.Zero & Known2.One) | (Known.One & Known2.Zero);
  2306. Known.Zero = KnownZeroOut;
  2307. break;
  2308. }
  2309. case ISD::MUL: {
  2310. Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
  2311. Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
  2312. // If low bits are zero in either operand, output low known-0 bits.
  2313. // Also compute a conservative estimate for high known-0 bits.
  2314. // More trickiness is possible, but this is sufficient for the
  2315. // interesting case of alignment computation.
  2316. unsigned TrailZ = Known.countMinTrailingZeros() +
  2317. Known2.countMinTrailingZeros();
  2318. unsigned LeadZ = std::max(Known.countMinLeadingZeros() +
  2319. Known2.countMinLeadingZeros(),
  2320. BitWidth) - BitWidth;
  2321. Known.resetAll();
  2322. Known.Zero.setLowBits(std::min(TrailZ, BitWidth));
  2323. Known.Zero.setHighBits(std::min(LeadZ, BitWidth));
  2324. break;
  2325. }
  2326. case ISD::UDIV: {
  2327. // For the purposes of computing leading zeros we can conservatively
  2328. // treat a udiv as a logical right shift by the power of 2 known to
  2329. // be less than the denominator.
  2330. Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
  2331. unsigned LeadZ = Known2.countMinLeadingZeros();
  2332. Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
  2333. unsigned RHSMaxLeadingZeros = Known2.countMaxLeadingZeros();
  2334. if (RHSMaxLeadingZeros != BitWidth)
  2335. LeadZ = std::min(BitWidth, LeadZ + BitWidth - RHSMaxLeadingZeros - 1);
  2336. Known.Zero.setHighBits(LeadZ);
  2337. break;
  2338. }
  2339. case ISD::SELECT:
  2340. case ISD::VSELECT:
  2341. Known = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1);
  2342. // If we don't know any bits, early out.
  2343. if (Known.isUnknown())
  2344. break;
  2345. Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth+1);
  2346. // Only known if known in both the LHS and RHS.
  2347. Known.One &= Known2.One;
  2348. Known.Zero &= Known2.Zero;
  2349. break;
  2350. case ISD::SELECT_CC:
  2351. Known = computeKnownBits(Op.getOperand(3), DemandedElts, Depth+1);
  2352. // If we don't know any bits, early out.
  2353. if (Known.isUnknown())
  2354. break;
  2355. Known2 = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1);
  2356. // Only known if known in both the LHS and RHS.
  2357. Known.One &= Known2.One;
  2358. Known.Zero &= Known2.Zero;
  2359. break;
  2360. case ISD::SMULO:
  2361. case ISD::UMULO:
  2362. case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
  2363. if (Op.getResNo() != 1)
  2364. break;
  2365. // The boolean result conforms to getBooleanContents.
  2366. // If we know the result of a setcc has the top bits zero, use this info.
  2367. // We know that we have an integer-based boolean since these operations
  2368. // are only available for integer.
  2369. if (TLI->getBooleanContents(Op.getValueType().isVector(), false) ==
  2370. TargetLowering::ZeroOrOneBooleanContent &&
  2371. BitWidth > 1)
  2372. Known.Zero.setBitsFrom(1);
  2373. break;
  2374. case ISD::SETCC:
  2375. // If we know the result of a setcc has the top bits zero, use this info.
  2376. if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
  2377. TargetLowering::ZeroOrOneBooleanContent &&
  2378. BitWidth > 1)
  2379. Known.Zero.setBitsFrom(1);
  2380. break;
  2381. case ISD::SHL:
  2382. if (const APInt *ShAmt = getValidShiftAmountConstant(Op)) {
  2383. Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
  2384. unsigned Shift = ShAmt->getZExtValue();
  2385. Known.Zero <<= Shift;
  2386. Known.One <<= Shift;
  2387. // Low bits are known zero.
  2388. Known.Zero.setLowBits(Shift);
  2389. }
  2390. break;
  2391. case ISD::SRL:
  2392. if (const APInt *ShAmt = getValidShiftAmountConstant(Op)) {
  2393. Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
  2394. unsigned Shift = ShAmt->getZExtValue();
  2395. Known.Zero.lshrInPlace(Shift);
  2396. Known.One.lshrInPlace(Shift);
  2397. // High bits are known zero.
  2398. Known.Zero.setHighBits(Shift);
  2399. } else if (auto *BV = dyn_cast<BuildVectorSDNode>(Op.getOperand(1))) {
  2400. // If the shift amount is a vector of constants see if we can bound
  2401. // the number of upper zero bits.
  2402. unsigned ShiftAmountMin = BitWidth;
  2403. for (unsigned i = 0; i != BV->getNumOperands(); ++i) {
  2404. if (auto *C = dyn_cast<ConstantSDNode>(BV->getOperand(i))) {
  2405. const APInt &ShAmt = C->getAPIntValue();
  2406. if (ShAmt.ult(BitWidth)) {
  2407. ShiftAmountMin = std::min<unsigned>(ShiftAmountMin,
  2408. ShAmt.getZExtValue());
  2409. continue;
  2410. }
  2411. }
  2412. // Don't know anything.
  2413. ShiftAmountMin = 0;
  2414. break;
  2415. }
  2416. Known.Zero.setHighBits(ShiftAmountMin);
  2417. }
  2418. break;
  2419. case ISD::SRA:
  2420. if (const APInt *ShAmt = getValidShiftAmountConstant(Op)) {
  2421. Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
  2422. unsigned Shift = ShAmt->getZExtValue();
  2423. // Sign extend known zero/one bit (else is unknown).
  2424. Known.Zero.ashrInPlace(Shift);
  2425. Known.One.ashrInPlace(Shift);
  2426. }
  2427. break;
  2428. case ISD::FSHL:
  2429. case ISD::FSHR:
  2430. if (ConstantSDNode *C = isConstOrConstSplat(Op.getOperand(2), DemandedElts)) {
  2431. unsigned Amt = C->getAPIntValue().urem(BitWidth);
  2432. // For fshl, 0-shift returns the 1st arg.
  2433. // For fshr, 0-shift returns the 2nd arg.
  2434. if (Amt == 0) {
  2435. Known = computeKnownBits(Op.getOperand(Opcode == ISD::FSHL ? 0 : 1),
  2436. DemandedElts, Depth + 1);
  2437. break;
  2438. }
  2439. // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW)))
  2440. // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW))
  2441. Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
  2442. Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
  2443. if (Opcode == ISD::FSHL) {
  2444. Known.One <<= Amt;
  2445. Known.Zero <<= Amt;
  2446. Known2.One.lshrInPlace(BitWidth - Amt);
  2447. Known2.Zero.lshrInPlace(BitWidth - Amt);
  2448. } else {
  2449. Known.One <<= BitWidth - Amt;
  2450. Known.Zero <<= BitWidth - Amt;
  2451. Known2.One.lshrInPlace(Amt);
  2452. Known2.Zero.lshrInPlace(Amt);
  2453. }
  2454. Known.One |= Known2.One;
  2455. Known.Zero |= Known2.Zero;
  2456. }
  2457. break;
  2458. case ISD::SIGN_EXTEND_INREG: {
  2459. EVT EVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
  2460. unsigned EBits = EVT.getScalarSizeInBits();
  2461. // Sign extension. Compute the demanded bits in the result that are not
  2462. // present in the input.
  2463. APInt NewBits = APInt::getHighBitsSet(BitWidth, BitWidth - EBits);
  2464. APInt InSignMask = APInt::getSignMask(EBits);
  2465. APInt InputDemandedBits = APInt::getLowBitsSet(BitWidth, EBits);
  2466. // If the sign extended bits are demanded, we know that the sign
  2467. // bit is demanded.
  2468. InSignMask = InSignMask.zext(BitWidth);
  2469. if (NewBits.getBoolValue())
  2470. InputDemandedBits |= InSignMask;
  2471. Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
  2472. Known.One &= InputDemandedBits;
  2473. Known.Zero &= InputDemandedBits;
  2474. // If the sign bit of the input is known set or clear, then we know the
  2475. // top bits of the result.
  2476. if (Known.Zero.intersects(InSignMask)) { // Input sign bit known clear
  2477. Known.Zero |= NewBits;
  2478. Known.One &= ~NewBits;
  2479. } else if (Known.One.intersects(InSignMask)) { // Input sign bit known set
  2480. Known.One |= NewBits;
  2481. Known.Zero &= ~NewBits;
  2482. } else { // Input sign bit unknown
  2483. Known.Zero &= ~NewBits;
  2484. Known.One &= ~NewBits;
  2485. }
  2486. break;
  2487. }
  2488. case ISD::CTTZ:
  2489. case ISD::CTTZ_ZERO_UNDEF: {
  2490. Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
  2491. // If we have a known 1, its position is our upper bound.
  2492. unsigned PossibleTZ = Known2.countMaxTrailingZeros();
  2493. unsigned LowBits = Log2_32(PossibleTZ) + 1;
  2494. Known.Zero.setBitsFrom(LowBits);
  2495. break;
  2496. }
  2497. case ISD::CTLZ:
  2498. case ISD::CTLZ_ZERO_UNDEF: {
  2499. Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
  2500. // If we have a known 1, its position is our upper bound.
  2501. unsigned PossibleLZ = Known2.countMaxLeadingZeros();
  2502. unsigned LowBits = Log2_32(PossibleLZ) + 1;
  2503. Known.Zero.setBitsFrom(LowBits);
  2504. break;
  2505. }
  2506. case ISD::CTPOP: {
  2507. Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
  2508. // If we know some of the bits are zero, they can't be one.
  2509. unsigned PossibleOnes = Known2.countMaxPopulation();
  2510. Known.Zero.setBitsFrom(Log2_32(PossibleOnes) + 1);
  2511. break;
  2512. }
  2513. case ISD::LOAD: {
  2514. LoadSDNode *LD = cast<LoadSDNode>(Op);
  2515. // If this is a ZEXTLoad and we are looking at the loaded value.
  2516. if (ISD::isZEXTLoad(Op.getNode()) && Op.getResNo() == 0) {
  2517. EVT VT = LD->getMemoryVT();
  2518. unsigned MemBits = VT.getScalarSizeInBits();
  2519. Known.Zero.setBitsFrom(MemBits);
  2520. } else if (const MDNode *Ranges = LD->getRanges()) {
  2521. if (LD->getExtensionType() == ISD::NON_EXTLOAD)
  2522. computeKnownBitsFromRangeMetadata(*Ranges, Known);
  2523. }
  2524. break;
  2525. }
  2526. case ISD::ZERO_EXTEND_VECTOR_INREG: {
  2527. EVT InVT = Op.getOperand(0).getValueType();
  2528. APInt InDemandedElts = DemandedElts.zextOrSelf(InVT.getVectorNumElements());
  2529. Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
  2530. Known = Known.zext(BitWidth, true /* ExtendedBitsAreKnownZero */);
  2531. break;
  2532. }
  2533. case ISD::ZERO_EXTEND: {
  2534. Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
  2535. Known = Known.zext(BitWidth, true /* ExtendedBitsAreKnownZero */);
  2536. break;
  2537. }
  2538. case ISD::SIGN_EXTEND_VECTOR_INREG: {
  2539. EVT InVT = Op.getOperand(0).getValueType();
  2540. APInt InDemandedElts = DemandedElts.zextOrSelf(InVT.getVectorNumElements());
  2541. Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
  2542. // If the sign bit is known to be zero or one, then sext will extend
  2543. // it to the top bits, else it will just zext.
  2544. Known = Known.sext(BitWidth);
  2545. break;
  2546. }
  2547. case ISD::SIGN_EXTEND: {
  2548. Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
  2549. // If the sign bit is known to be zero or one, then sext will extend
  2550. // it to the top bits, else it will just zext.
  2551. Known = Known.sext(BitWidth);
  2552. break;
  2553. }
  2554. case ISD::ANY_EXTEND: {
  2555. Known = computeKnownBits(Op.getOperand(0), Depth+1);
  2556. Known = Known.zext(BitWidth, false /* ExtendedBitsAreKnownZero */);
  2557. break;
  2558. }
  2559. case ISD::TRUNCATE: {
  2560. Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
  2561. Known = Known.trunc(BitWidth);
  2562. break;
  2563. }
  2564. case ISD::AssertZext: {
  2565. EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
  2566. APInt InMask = APInt::getLowBitsSet(BitWidth, VT.getSizeInBits());
  2567. Known = computeKnownBits(Op.getOperand(0), Depth+1);
  2568. Known.Zero |= (~InMask);
  2569. Known.One &= (~Known.Zero);
  2570. break;
  2571. }
  2572. case ISD::FGETSIGN:
  2573. // All bits are zero except the low bit.
  2574. Known.Zero.setBitsFrom(1);
  2575. break;
  2576. case ISD::USUBO:
  2577. case ISD::SSUBO:
  2578. if (Op.getResNo() == 1) {
  2579. // If we know the result of a setcc has the top bits zero, use this info.
  2580. if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
  2581. TargetLowering::ZeroOrOneBooleanContent &&
  2582. BitWidth > 1)
  2583. Known.Zero.setBitsFrom(1);
  2584. break;
  2585. }
  2586. LLVM_FALLTHROUGH;
  2587. case ISD::SUB:
  2588. case ISD::SUBC: {
  2589. if (ConstantSDNode *CLHS = isConstOrConstSplat(Op.getOperand(0))) {
  2590. // We know that the top bits of C-X are clear if X contains less bits
  2591. // than C (i.e. no wrap-around can happen). For example, 20-X is
  2592. // positive if we can prove that X is >= 0 and < 16.
  2593. if (CLHS->getAPIntValue().isNonNegative()) {
  2594. unsigned NLZ = (CLHS->getAPIntValue()+1).countLeadingZeros();
  2595. // NLZ can't be BitWidth with no sign bit
  2596. APInt MaskV = APInt::getHighBitsSet(BitWidth, NLZ+1);
  2597. Known2 = computeKnownBits(Op.getOperand(1), DemandedElts,
  2598. Depth + 1);
  2599. // If all of the MaskV bits are known to be zero, then we know the
  2600. // output top bits are zero, because we now know that the output is
  2601. // from [0-C].
  2602. if ((Known2.Zero & MaskV) == MaskV) {
  2603. unsigned NLZ2 = CLHS->getAPIntValue().countLeadingZeros();
  2604. // Top bits known zero.
  2605. Known.Zero.setHighBits(NLZ2);
  2606. }
  2607. }
  2608. }
  2609. // If low bits are know to be zero in both operands, then we know they are
  2610. // going to be 0 in the result. Both addition and complement operations
  2611. // preserve the low zero bits.
  2612. Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
  2613. unsigned KnownZeroLow = Known2.countMinTrailingZeros();
  2614. if (KnownZeroLow == 0)
  2615. break;
  2616. Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
  2617. KnownZeroLow = std::min(KnownZeroLow, Known2.countMinTrailingZeros());
  2618. Known.Zero.setLowBits(KnownZeroLow);
  2619. break;
  2620. }
  2621. case ISD::UADDO:
  2622. case ISD::SADDO:
  2623. case ISD::ADDCARRY:
  2624. if (Op.getResNo() == 1) {
  2625. // If we know the result of a setcc has the top bits zero, use this info.
  2626. if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
  2627. TargetLowering::ZeroOrOneBooleanContent &&
  2628. BitWidth > 1)
  2629. Known.Zero.setBitsFrom(1);
  2630. break;
  2631. }
  2632. LLVM_FALLTHROUGH;
  2633. case ISD::ADD:
  2634. case ISD::ADDC:
  2635. case ISD::ADDE: {
  2636. // Output known-0 bits are known if clear or set in both the low clear bits
  2637. // common to both LHS & RHS. For example, 8+(X<<3) is known to have the
  2638. // low 3 bits clear.
  2639. // Output known-0 bits are also known if the top bits of each input are
  2640. // known to be clear. For example, if one input has the top 10 bits clear
  2641. // and the other has the top 8 bits clear, we know the top 7 bits of the
  2642. // output must be clear.
  2643. Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
  2644. unsigned KnownZeroHigh = Known2.countMinLeadingZeros();
  2645. unsigned KnownZeroLow = Known2.countMinTrailingZeros();
  2646. Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
  2647. KnownZeroHigh = std::min(KnownZeroHigh, Known2.countMinLeadingZeros());
  2648. KnownZeroLow = std::min(KnownZeroLow, Known2.countMinTrailingZeros());
  2649. if (Opcode == ISD::ADDE || Opcode == ISD::ADDCARRY) {
  2650. // With ADDE and ADDCARRY, a carry bit may be added in, so we can only
  2651. // use this information if we know (at least) that the low two bits are
  2652. // clear. We then return to the caller that the low bit is unknown but
  2653. // that other bits are known zero.
  2654. if (KnownZeroLow >= 2)
  2655. Known.Zero.setBits(1, KnownZeroLow);
  2656. break;
  2657. }
  2658. Known.Zero.setLowBits(KnownZeroLow);
  2659. if (KnownZeroHigh > 1)
  2660. Known.Zero.setHighBits(KnownZeroHigh - 1);
  2661. break;
  2662. }
  2663. case ISD::SREM:
  2664. if (ConstantSDNode *Rem = isConstOrConstSplat(Op.getOperand(1))) {
  2665. const APInt &RA = Rem->getAPIntValue().abs();
  2666. if (RA.isPowerOf2()) {
  2667. APInt LowBits = RA - 1;
  2668. Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
  2669. // The low bits of the first operand are unchanged by the srem.
  2670. Known.Zero = Known2.Zero & LowBits;
  2671. Known.One = Known2.One & LowBits;
  2672. // If the first operand is non-negative or has all low bits zero, then
  2673. // the upper bits are all zero.
  2674. if (Known2.Zero[BitWidth-1] || ((Known2.Zero & LowBits) == LowBits))
  2675. Known.Zero |= ~LowBits;
  2676. // If the first operand is negative and not all low bits are zero, then
  2677. // the upper bits are all one.
  2678. if (Known2.One[BitWidth-1] && ((Known2.One & LowBits) != 0))
  2679. Known.One |= ~LowBits;
  2680. assert((Known.Zero & Known.One) == 0&&"Bits known to be one AND zero?");
  2681. }
  2682. }
  2683. break;
  2684. case ISD::UREM: {
  2685. if (ConstantSDNode *Rem = isConstOrConstSplat(Op.getOperand(1))) {
  2686. const APInt &RA = Rem->getAPIntValue();
  2687. if (RA.isPowerOf2()) {
  2688. APInt LowBits = (RA - 1);
  2689. Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
  2690. // The upper bits are all zero, the lower ones are unchanged.
  2691. Known.Zero = Known2.Zero | ~LowBits;
  2692. Known.One = Known2.One & LowBits;
  2693. break;
  2694. }
  2695. }
  2696. // Since the result is less than or equal to either operand, any leading
  2697. // zero bits in either operand must also exist in the result.
  2698. Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
  2699. Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
  2700. uint32_t Leaders =
  2701. std::max(Known.countMinLeadingZeros(), Known2.countMinLeadingZeros());
  2702. Known.resetAll();
  2703. Known.Zero.setHighBits(Leaders);
  2704. break;
  2705. }
  2706. case ISD::EXTRACT_ELEMENT: {
  2707. Known = computeKnownBits(Op.getOperand(0), Depth+1);
  2708. const unsigned Index = Op.getConstantOperandVal(1);
  2709. const unsigned BitWidth = Op.getValueSizeInBits();
  2710. // Remove low part of known bits mask
  2711. Known.Zero = Known.Zero.getHiBits(Known.Zero.getBitWidth() - Index * BitWidth);
  2712. Known.One = Known.One.getHiBits(Known.One.getBitWidth() - Index * BitWidth);
  2713. // Remove high part of known bit mask
  2714. Known = Known.trunc(BitWidth);
  2715. break;
  2716. }
  2717. case ISD::EXTRACT_VECTOR_ELT: {
  2718. SDValue InVec = Op.getOperand(0);
  2719. SDValue EltNo = Op.getOperand(1);
  2720. EVT VecVT = InVec.getValueType();
  2721. const unsigned BitWidth = Op.getValueSizeInBits();
  2722. const unsigned EltBitWidth = VecVT.getScalarSizeInBits();
  2723. const unsigned NumSrcElts = VecVT.getVectorNumElements();
  2724. // If BitWidth > EltBitWidth the value is anyext:ed. So we do not know
  2725. // anything about the extended bits.
  2726. if (BitWidth > EltBitWidth)
  2727. Known = Known.trunc(EltBitWidth);
  2728. ConstantSDNode *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
  2729. if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts)) {
  2730. // If we know the element index, just demand that vector element.
  2731. unsigned Idx = ConstEltNo->getZExtValue();
  2732. APInt DemandedElt = APInt::getOneBitSet(NumSrcElts, Idx);
  2733. Known = computeKnownBits(InVec, DemandedElt, Depth + 1);
  2734. } else {
  2735. // Unknown element index, so ignore DemandedElts and demand them all.
  2736. Known = computeKnownBits(InVec, Depth + 1);
  2737. }
  2738. if (BitWidth > EltBitWidth)
  2739. Known = Known.zext(BitWidth, false /* => any extend */);
  2740. break;
  2741. }
  2742. case ISD::INSERT_VECTOR_ELT: {
  2743. SDValue InVec = Op.getOperand(0);
  2744. SDValue InVal = Op.getOperand(1);
  2745. SDValue EltNo = Op.getOperand(2);
  2746. ConstantSDNode *CEltNo = dyn_cast<ConstantSDNode>(EltNo);
  2747. if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) {
  2748. // If we know the element index, split the demand between the
  2749. // source vector and the inserted element.
  2750. Known.Zero = Known.One = APInt::getAllOnesValue(BitWidth);
  2751. unsigned EltIdx = CEltNo->getZExtValue();
  2752. // If we demand the inserted element then add its common known bits.
  2753. if (DemandedElts[EltIdx]) {
  2754. Known2 = computeKnownBits(InVal, Depth + 1);
  2755. Known.One &= Known2.One.zextOrTrunc(Known.One.getBitWidth());
  2756. Known.Zero &= Known2.Zero.zextOrTrunc(Known.Zero.getBitWidth());
  2757. }
  2758. // If we demand the source vector then add its common known bits, ensuring
  2759. // that we don't demand the inserted element.
  2760. APInt VectorElts = DemandedElts & ~(APInt::getOneBitSet(NumElts, EltIdx));
  2761. if (!!VectorElts) {
  2762. Known2 = computeKnownBits(InVec, VectorElts, Depth + 1);
  2763. Known.One &= Known2.One;
  2764. Known.Zero &= Known2.Zero;
  2765. }
  2766. } else {
  2767. // Unknown element index, so ignore DemandedElts and demand them all.
  2768. Known = computeKnownBits(InVec, Depth + 1);
  2769. Known2 = computeKnownBits(InVal, Depth + 1);
  2770. Known.One &= Known2.One.zextOrTrunc(Known.One.getBitWidth());
  2771. Known.Zero &= Known2.Zero.zextOrTrunc(Known.Zero.getBitWidth());
  2772. }
  2773. break;
  2774. }
  2775. case ISD::BITREVERSE: {
  2776. Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
  2777. Known.Zero = Known2.Zero.reverseBits();
  2778. Known.One = Known2.One.reverseBits();
  2779. break;
  2780. }
  2781. case ISD::BSWAP: {
  2782. Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
  2783. Known.Zero = Known2.Zero.byteSwap();
  2784. Known.One = Known2.One.byteSwap();
  2785. break;
  2786. }
  2787. case ISD::ABS: {
  2788. Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
  2789. // If the source's MSB is zero then we know the rest of the bits already.
  2790. if (Known2.isNonNegative()) {
  2791. Known.Zero = Known2.Zero;
  2792. Known.One = Known2.One;
  2793. break;
  2794. }
  2795. // We only know that the absolute values's MSB will be zero iff there is
  2796. // a set bit that isn't the sign bit (otherwise it could be INT_MIN).
  2797. Known2.One.clearSignBit();
  2798. if (Known2.One.getBoolValue()) {
  2799. Known.Zero = APInt::getSignMask(BitWidth);
  2800. break;
  2801. }
  2802. break;
  2803. }
  2804. case ISD::UMIN: {
  2805. Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
  2806. Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
  2807. // UMIN - we know that the result will have the maximum of the
  2808. // known zero leading bits of the inputs.
  2809. unsigned LeadZero = Known.countMinLeadingZeros();
  2810. LeadZero = std::max(LeadZero, Known2.countMinLeadingZeros());
  2811. Known.Zero &= Known2.Zero;
  2812. Known.One &= Known2.One;
  2813. Known.Zero.setHighBits(LeadZero);
  2814. break;
  2815. }
  2816. case ISD::UMAX: {
  2817. Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
  2818. Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
  2819. // UMAX - we know that the result will have the maximum of the
  2820. // known one leading bits of the inputs.
  2821. unsigned LeadOne = Known.countMinLeadingOnes();
  2822. LeadOne = std::max(LeadOne, Known2.countMinLeadingOnes());
  2823. Known.Zero &= Known2.Zero;
  2824. Known.One &= Known2.One;
  2825. Known.One.setHighBits(LeadOne);
  2826. break;
  2827. }
  2828. case ISD::SMIN:
  2829. case ISD::SMAX: {
  2830. // If we have a clamp pattern, we know that the number of sign bits will be
  2831. // the minimum of the clamp min/max range.
  2832. bool IsMax = (Opcode == ISD::SMAX);
  2833. ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr;
  2834. if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts)))
  2835. if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX))
  2836. CstHigh =
  2837. isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts);
  2838. if (CstLow && CstHigh) {
  2839. if (!IsMax)
  2840. std::swap(CstLow, CstHigh);
  2841. const APInt &ValueLow = CstLow->getAPIntValue();
  2842. const APInt &ValueHigh = CstHigh->getAPIntValue();
  2843. if (ValueLow.sle(ValueHigh)) {
  2844. unsigned LowSignBits = ValueLow.getNumSignBits();
  2845. unsigned HighSignBits = ValueHigh.getNumSignBits();
  2846. unsigned MinSignBits = std::min(LowSignBits, HighSignBits);
  2847. if (ValueLow.isNegative() && ValueHigh.isNegative()) {
  2848. Known.One.setHighBits(MinSignBits);
  2849. break;
  2850. }
  2851. if (ValueLow.isNonNegative() && ValueHigh.isNonNegative()) {
  2852. Known.Zero.setHighBits(MinSignBits);
  2853. break;
  2854. }
  2855. }
  2856. }
  2857. // Fallback - just get the shared known bits of the operands.
  2858. Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
  2859. if (Known.isUnknown()) break; // Early-out
  2860. Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
  2861. Known.Zero &= Known2.Zero;
  2862. Known.One &= Known2.One;
  2863. break;
  2864. }
  2865. case ISD::FrameIndex:
  2866. case ISD::TargetFrameIndex:
  2867. TLI->computeKnownBitsForFrameIndex(Op, Known, DemandedElts, *this, Depth);
  2868. break;
  2869. default:
  2870. if (Opcode < ISD::BUILTIN_OP_END)
  2871. break;
  2872. LLVM_FALLTHROUGH;
  2873. case ISD::INTRINSIC_WO_CHAIN:
  2874. case ISD::INTRINSIC_W_CHAIN:
  2875. case ISD::INTRINSIC_VOID:
  2876. // Allow the target to implement this method for its nodes.
  2877. TLI->computeKnownBitsForTargetNode(Op, Known, DemandedElts, *this, Depth);
  2878. break;
  2879. }
  2880. assert(!Known.hasConflict() && "Bits known to be one AND zero?");
  2881. return Known;
  2882. }
  2883. SelectionDAG::OverflowKind SelectionDAG::computeOverflowKind(SDValue N0,
  2884. SDValue N1) const {
  2885. // X + 0 never overflow
  2886. if (isNullConstant(N1))
  2887. return OFK_Never;
  2888. KnownBits N1Known = computeKnownBits(N1);
  2889. if (N1Known.Zero.getBoolValue()) {
  2890. KnownBits N0Known = computeKnownBits(N0);
  2891. bool overflow;
  2892. (void)(~N0Known.Zero).uadd_ov(~N1Known.Zero, overflow);
  2893. if (!overflow)
  2894. return OFK_Never;
  2895. }
  2896. // mulhi + 1 never overflow
  2897. if (N0.getOpcode() == ISD::UMUL_LOHI && N0.getResNo() == 1 &&
  2898. (~N1Known.Zero & 0x01) == ~N1Known.Zero)
  2899. return OFK_Never;
  2900. if (N1.getOpcode() == ISD::UMUL_LOHI && N1.getResNo() == 1) {
  2901. KnownBits N0Known = computeKnownBits(N0);
  2902. if ((~N0Known.Zero & 0x01) == ~N0Known.Zero)
  2903. return OFK_Never;
  2904. }
  2905. return OFK_Sometime;
  2906. }
  2907. bool SelectionDAG::isKnownToBeAPowerOfTwo(SDValue Val) const {
  2908. EVT OpVT = Val.getValueType();
  2909. unsigned BitWidth = OpVT.getScalarSizeInBits();
  2910. // Is the constant a known power of 2?
  2911. if (ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Val))
  2912. return Const->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2();
  2913. // A left-shift of a constant one will have exactly one bit set because
  2914. // shifting the bit off the end is undefined.
  2915. if (Val.getOpcode() == ISD::SHL) {
  2916. auto *C = isConstOrConstSplat(Val.getOperand(0));
  2917. if (C && C->getAPIntValue() == 1)
  2918. return true;
  2919. }
  2920. // Similarly, a logical right-shift of a constant sign-bit will have exactly
  2921. // one bit set.
  2922. if (Val.getOpcode() == ISD::SRL) {
  2923. auto *C = isConstOrConstSplat(Val.getOperand(0));
  2924. if (C && C->getAPIntValue().isSignMask())
  2925. return true;
  2926. }
  2927. // Are all operands of a build vector constant powers of two?
  2928. if (Val.getOpcode() == ISD::BUILD_VECTOR)
  2929. if (llvm::all_of(Val->ops(), [BitWidth](SDValue E) {
  2930. if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(E))
  2931. return C->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2();
  2932. return false;
  2933. }))
  2934. return true;
  2935. // More could be done here, though the above checks are enough
  2936. // to handle some common cases.
  2937. // Fall back to computeKnownBits to catch other known cases.
  2938. KnownBits Known = computeKnownBits(Val);
  2939. return (Known.countMaxPopulation() == 1) && (Known.countMinPopulation() == 1);
  2940. }
  2941. unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, unsigned Depth) const {
  2942. EVT VT = Op.getValueType();
  2943. APInt DemandedElts = VT.isVector()
  2944. ? APInt::getAllOnesValue(VT.getVectorNumElements())
  2945. : APInt(1, 1);
  2946. return ComputeNumSignBits(Op, DemandedElts, Depth);
  2947. }
  2948. unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, const APInt &DemandedElts,
  2949. unsigned Depth) const {
  2950. EVT VT = Op.getValueType();
  2951. assert((VT.isInteger() || VT.isFloatingPoint()) && "Invalid VT!");
  2952. unsigned VTBits = VT.getScalarSizeInBits();
  2953. unsigned NumElts = DemandedElts.getBitWidth();
  2954. unsigned Tmp, Tmp2;
  2955. unsigned FirstAnswer = 1;
  2956. if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
  2957. const APInt &Val = C->getAPIntValue();
  2958. return Val.getNumSignBits();
  2959. }
  2960. if (Depth == 6)
  2961. return 1; // Limit search depth.
  2962. if (!DemandedElts)
  2963. return 1; // No demanded elts, better to assume we don't know anything.
  2964. unsigned Opcode = Op.getOpcode();
  2965. switch (Opcode) {
  2966. default: break;
  2967. case ISD::AssertSext:
  2968. Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
  2969. return VTBits-Tmp+1;
  2970. case ISD::AssertZext:
  2971. Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
  2972. return VTBits-Tmp;
  2973. case ISD::BUILD_VECTOR:
  2974. Tmp = VTBits;
  2975. for (unsigned i = 0, e = Op.getNumOperands(); (i < e) && (Tmp > 1); ++i) {
  2976. if (!DemandedElts[i])
  2977. continue;
  2978. SDValue SrcOp = Op.getOperand(i);
  2979. Tmp2 = ComputeNumSignBits(Op.getOperand(i), Depth + 1);
  2980. // BUILD_VECTOR can implicitly truncate sources, we must handle this.
  2981. if (SrcOp.getValueSizeInBits() != VTBits) {
  2982. assert(SrcOp.getValueSizeInBits() > VTBits &&
  2983. "Expected BUILD_VECTOR implicit truncation");
  2984. unsigned ExtraBits = SrcOp.getValueSizeInBits() - VTBits;
  2985. Tmp2 = (Tmp2 > ExtraBits ? Tmp2 - ExtraBits : 1);
  2986. }
  2987. Tmp = std::min(Tmp, Tmp2);
  2988. }
  2989. return Tmp;
  2990. case ISD::VECTOR_SHUFFLE: {
  2991. // Collect the minimum number of sign bits that are shared by every vector
  2992. // element referenced by the shuffle.
  2993. APInt DemandedLHS(NumElts, 0), DemandedRHS(NumElts, 0);
  2994. const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
  2995. assert(NumElts == SVN->getMask().size() && "Unexpected vector size");
  2996. for (unsigned i = 0; i != NumElts; ++i) {
  2997. int M = SVN->getMaskElt(i);
  2998. if (!DemandedElts[i])
  2999. continue;
  3000. // For UNDEF elements, we don't know anything about the common state of
  3001. // the shuffle result.
  3002. if (M < 0)
  3003. return 1;
  3004. if ((unsigned)M < NumElts)
  3005. DemandedLHS.setBit((unsigned)M % NumElts);
  3006. else
  3007. DemandedRHS.setBit((unsigned)M % NumElts);
  3008. }
  3009. Tmp = std::numeric_limits<unsigned>::max();
  3010. if (!!DemandedLHS)
  3011. Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedLHS, Depth + 1);
  3012. if (!!DemandedRHS) {
  3013. Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedRHS, Depth + 1);
  3014. Tmp = std::min(Tmp, Tmp2);
  3015. }
  3016. // If we don't know anything, early out and try computeKnownBits fall-back.
  3017. if (Tmp == 1)
  3018. break;
  3019. assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
  3020. return Tmp;
  3021. }
  3022. case ISD::BITCAST: {
  3023. SDValue N0 = Op.getOperand(0);
  3024. EVT SrcVT = N0.getValueType();
  3025. unsigned SrcBits = SrcVT.getScalarSizeInBits();
  3026. // Ignore bitcasts from unsupported types..
  3027. if (!(SrcVT.isInteger() || SrcVT.isFloatingPoint()))
  3028. break;
  3029. // Fast handling of 'identity' bitcasts.
  3030. if (VTBits == SrcBits)
  3031. return ComputeNumSignBits(N0, DemandedElts, Depth + 1);
  3032. bool IsLE = getDataLayout().isLittleEndian();
  3033. // Bitcast 'large element' scalar/vector to 'small element' vector.
  3034. if ((SrcBits % VTBits) == 0) {
  3035. assert(VT.isVector() && "Expected bitcast to vector");
  3036. unsigned Scale = SrcBits / VTBits;
  3037. APInt SrcDemandedElts(NumElts / Scale, 0);
  3038. for (unsigned i = 0; i != NumElts; ++i)
  3039. if (DemandedElts[i])
  3040. SrcDemandedElts.setBit(i / Scale);
  3041. // Fast case - sign splat can be simply split across the small elements.
  3042. Tmp = ComputeNumSignBits(N0, SrcDemandedElts, Depth + 1);
  3043. if (Tmp == SrcBits)
  3044. return VTBits;
  3045. // Slow case - determine how far the sign extends into each sub-element.
  3046. Tmp2 = VTBits;
  3047. for (unsigned i = 0; i != NumElts; ++i)
  3048. if (DemandedElts[i]) {
  3049. unsigned SubOffset = i % Scale;
  3050. SubOffset = (IsLE ? ((Scale - 1) - SubOffset) : SubOffset);
  3051. SubOffset = SubOffset * VTBits;
  3052. if (Tmp <= SubOffset)
  3053. return 1;
  3054. Tmp2 = std::min(Tmp2, Tmp - SubOffset);
  3055. }
  3056. return Tmp2;
  3057. }
  3058. break;
  3059. }
  3060. case ISD::SIGN_EXTEND:
  3061. Tmp = VTBits - Op.getOperand(0).getScalarValueSizeInBits();
  3062. return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1) + Tmp;
  3063. case ISD::SIGN_EXTEND_INREG:
  3064. // Max of the input and what this extends.
  3065. Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getScalarSizeInBits();
  3066. Tmp = VTBits-Tmp+1;
  3067. Tmp2 = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1);
  3068. return std::max(Tmp, Tmp2);
  3069. case ISD::SIGN_EXTEND_VECTOR_INREG: {
  3070. SDValue Src = Op.getOperand(0);
  3071. EVT SrcVT = Src.getValueType();
  3072. APInt DemandedSrcElts = DemandedElts.zextOrSelf(SrcVT.getVectorNumElements());
  3073. Tmp = VTBits - SrcVT.getScalarSizeInBits();
  3074. return ComputeNumSignBits(Src, DemandedSrcElts, Depth+1) + Tmp;
  3075. }
  3076. case ISD::SRA:
  3077. Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1);
  3078. // SRA X, C -> adds C sign bits.
  3079. if (ConstantSDNode *C =
  3080. isConstOrConstSplat(Op.getOperand(1), DemandedElts)) {
  3081. APInt ShiftVal = C->getAPIntValue();
  3082. ShiftVal += Tmp;
  3083. Tmp = ShiftVal.uge(VTBits) ? VTBits : ShiftVal.getZExtValue();
  3084. }
  3085. return Tmp;
  3086. case ISD::SHL:
  3087. if (ConstantSDNode *C =
  3088. isConstOrConstSplat(Op.getOperand(1), DemandedElts)) {
  3089. // shl destroys sign bits.
  3090. Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1);
  3091. if (C->getAPIntValue().uge(VTBits) || // Bad shift.
  3092. C->getAPIntValue().uge(Tmp)) break; // Shifted all sign bits out.
  3093. return Tmp - C->getZExtValue();
  3094. }
  3095. break;
  3096. case ISD::AND:
  3097. case ISD::OR:
  3098. case ISD::XOR: // NOT is handled here.
  3099. // Logical binary ops preserve the number of sign bits at the worst.
  3100. Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1);
  3101. if (Tmp != 1) {
  3102. Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1);
  3103. FirstAnswer = std::min(Tmp, Tmp2);
  3104. // We computed what we know about the sign bits as our first
  3105. // answer. Now proceed to the generic code that uses
  3106. // computeKnownBits, and pick whichever answer is better.
  3107. }
  3108. break;
  3109. case ISD::SELECT:
  3110. case ISD::VSELECT:
  3111. Tmp = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1);
  3112. if (Tmp == 1) return 1; // Early out.
  3113. Tmp2 = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1);
  3114. return std::min(Tmp, Tmp2);
  3115. case ISD::SELECT_CC:
  3116. Tmp = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1);
  3117. if (Tmp == 1) return 1; // Early out.
  3118. Tmp2 = ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth+1);
  3119. return std::min(Tmp, Tmp2);
  3120. case ISD::SMIN:
  3121. case ISD::SMAX: {
  3122. // If we have a clamp pattern, we know that the number of sign bits will be
  3123. // the minimum of the clamp min/max range.
  3124. bool IsMax = (Opcode == ISD::SMAX);
  3125. ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr;
  3126. if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts)))
  3127. if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX))
  3128. CstHigh =
  3129. isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts);
  3130. if (CstLow && CstHigh) {
  3131. if (!IsMax)
  3132. std::swap(CstLow, CstHigh);
  3133. if (CstLow->getAPIntValue().sle(CstHigh->getAPIntValue())) {
  3134. Tmp = CstLow->getAPIntValue().getNumSignBits();
  3135. Tmp2 = CstHigh->getAPIntValue().getNumSignBits();
  3136. return std::min(Tmp, Tmp2);
  3137. }
  3138. }
  3139. // Fallback - just get the minimum number of sign bits of the operands.
  3140. Tmp = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
  3141. if (Tmp == 1)
  3142. return 1; // Early out.
  3143. Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth + 1);
  3144. return std::min(Tmp, Tmp2);
  3145. }
  3146. case ISD::UMIN:
  3147. case ISD::UMAX:
  3148. Tmp = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
  3149. if (Tmp == 1)
  3150. return 1; // Early out.
  3151. Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth + 1);
  3152. return std::min(Tmp, Tmp2);
  3153. case ISD::SADDO:
  3154. case ISD::UADDO:
  3155. case ISD::SSUBO:
  3156. case ISD::USUBO:
  3157. case ISD::SMULO:
  3158. case ISD::UMULO:
  3159. if (Op.getResNo() != 1)
  3160. break;
  3161. // The boolean result conforms to getBooleanContents. Fall through.
  3162. // If setcc returns 0/-1, all bits are sign bits.
  3163. // We know that we have an integer-based boolean since these operations
  3164. // are only available for integer.
  3165. if (TLI->getBooleanContents(VT.isVector(), false) ==
  3166. TargetLowering::ZeroOrNegativeOneBooleanContent)
  3167. return VTBits;
  3168. break;
  3169. case ISD::SETCC:
  3170. // If setcc returns 0/-1, all bits are sign bits.
  3171. if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
  3172. TargetLowering::ZeroOrNegativeOneBooleanContent)
  3173. return VTBits;
  3174. break;
  3175. case ISD::ROTL:
  3176. case ISD::ROTR:
  3177. if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
  3178. unsigned RotAmt = C->getAPIntValue().urem(VTBits);
  3179. // Handle rotate right by N like a rotate left by 32-N.
  3180. if (Opcode == ISD::ROTR)
  3181. RotAmt = (VTBits - RotAmt) % VTBits;
  3182. // If we aren't rotating out all of the known-in sign bits, return the
  3183. // number that are left. This handles rotl(sext(x), 1) for example.
  3184. Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
  3185. if (Tmp > (RotAmt + 1)) return (Tmp - RotAmt);
  3186. }
  3187. break;
  3188. case ISD::ADD:
  3189. case ISD::ADDC:
  3190. // Add can have at most one carry bit. Thus we know that the output
  3191. // is, at worst, one more bit than the inputs.
  3192. Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
  3193. if (Tmp == 1) return 1; // Early out.
  3194. // Special case decrementing a value (ADD X, -1):
  3195. if (ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
  3196. if (CRHS->isAllOnesValue()) {
  3197. KnownBits Known = computeKnownBits(Op.getOperand(0), Depth+1);
  3198. // If the input is known to be 0 or 1, the output is 0/-1, which is all
  3199. // sign bits set.
  3200. if ((Known.Zero | 1).isAllOnesValue())
  3201. return VTBits;
  3202. // If we are subtracting one from a positive number, there is no carry
  3203. // out of the result.
  3204. if (Known.isNonNegative())
  3205. return Tmp;
  3206. }
  3207. Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
  3208. if (Tmp2 == 1) return 1;
  3209. return std::min(Tmp, Tmp2)-1;
  3210. case ISD::SUB:
  3211. Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
  3212. if (Tmp2 == 1) return 1;
  3213. // Handle NEG.
  3214. if (ConstantSDNode *CLHS = isConstOrConstSplat(Op.getOperand(0)))
  3215. if (CLHS->isNullValue()) {
  3216. KnownBits Known = computeKnownBits(Op.getOperand(1), Depth+1);
  3217. // If the input is known to be 0 or 1, the output is 0/-1, which is all
  3218. // sign bits set.
  3219. if ((Known.Zero | 1).isAllOnesValue())
  3220. return VTBits;
  3221. // If the input is known to be positive (the sign bit is known clear),
  3222. // the output of the NEG has the same number of sign bits as the input.
  3223. if (Known.isNonNegative())
  3224. return Tmp2;
  3225. // Otherwise, we treat this like a SUB.
  3226. }
  3227. // Sub can have at most one carry bit. Thus we know that the output
  3228. // is, at worst, one more bit than the inputs.
  3229. Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
  3230. if (Tmp == 1) return 1; // Early out.
  3231. return std::min(Tmp, Tmp2)-1;
  3232. case ISD::TRUNCATE: {
  3233. // Check if the sign bits of source go down as far as the truncated value.
  3234. unsigned NumSrcBits = Op.getOperand(0).getScalarValueSizeInBits();
  3235. unsigned NumSrcSignBits = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
  3236. if (NumSrcSignBits > (NumSrcBits - VTBits))
  3237. return NumSrcSignBits - (NumSrcBits - VTBits);
  3238. break;
  3239. }
  3240. case ISD::EXTRACT_ELEMENT: {
  3241. const int KnownSign = ComputeNumSignBits(Op.getOperand(0), Depth+1);
  3242. const int BitWidth = Op.getValueSizeInBits();
  3243. const int Items = Op.getOperand(0).getValueSizeInBits() / BitWidth;
  3244. // Get reverse index (starting from 1), Op1 value indexes elements from
  3245. // little end. Sign starts at big end.
  3246. const int rIndex = Items - 1 - Op.getConstantOperandVal(1);
  3247. // If the sign portion ends in our element the subtraction gives correct
  3248. // result. Otherwise it gives either negative or > bitwidth result
  3249. return std::max(std::min(KnownSign - rIndex * BitWidth, BitWidth), 0);
  3250. }
  3251. case ISD::INSERT_VECTOR_ELT: {
  3252. SDValue InVec = Op.getOperand(0);
  3253. SDValue InVal = Op.getOperand(1);
  3254. SDValue EltNo = Op.getOperand(2);
  3255. unsigned NumElts = InVec.getValueType().getVectorNumElements();
  3256. ConstantSDNode *CEltNo = dyn_cast<ConstantSDNode>(EltNo);
  3257. if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) {
  3258. // If we know the element index, split the demand between the
  3259. // source vector and the inserted element.
  3260. unsigned EltIdx = CEltNo->getZExtValue();
  3261. // If we demand the inserted element then get its sign bits.
  3262. Tmp = std::numeric_limits<unsigned>::max();
  3263. if (DemandedElts[EltIdx]) {
  3264. // TODO - handle implicit truncation of inserted elements.
  3265. if (InVal.getScalarValueSizeInBits() != VTBits)
  3266. break;
  3267. Tmp = ComputeNumSignBits(InVal, Depth + 1);
  3268. }
  3269. // If we demand the source vector then get its sign bits, and determine
  3270. // the minimum.
  3271. APInt VectorElts = DemandedElts;
  3272. VectorElts.clearBit(EltIdx);
  3273. if (!!VectorElts) {
  3274. Tmp2 = ComputeNumSignBits(InVec, VectorElts, Depth + 1);
  3275. Tmp = std::min(Tmp, Tmp2);
  3276. }
  3277. } else {
  3278. // Unknown element index, so ignore DemandedElts and demand them all.
  3279. Tmp = ComputeNumSignBits(InVec, Depth + 1);
  3280. Tmp2 = ComputeNumSignBits(InVal, Depth + 1);
  3281. Tmp = std::min(Tmp, Tmp2);
  3282. }
  3283. assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
  3284. return Tmp;
  3285. }
  3286. case ISD::EXTRACT_VECTOR_ELT: {
  3287. SDValue InVec = Op.getOperand(0);
  3288. SDValue EltNo = Op.getOperand(1);
  3289. EVT VecVT = InVec.getValueType();
  3290. const unsigned BitWidth = Op.getValueSizeInBits();
  3291. const unsigned EltBitWidth = Op.getOperand(0).getScalarValueSizeInBits();
  3292. const unsigned NumSrcElts = VecVT.getVectorNumElements();
  3293. // If BitWidth > EltBitWidth the value is anyext:ed, and we do not know
  3294. // anything about sign bits. But if the sizes match we can derive knowledge
  3295. // about sign bits from the vector operand.
  3296. if (BitWidth != EltBitWidth)
  3297. break;
  3298. // If we know the element index, just demand that vector element, else for
  3299. // an unknown element index, ignore DemandedElts and demand them all.
  3300. APInt DemandedSrcElts = APInt::getAllOnesValue(NumSrcElts);
  3301. ConstantSDNode *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
  3302. if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts))
  3303. DemandedSrcElts =
  3304. APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue());
  3305. return ComputeNumSignBits(InVec, DemandedSrcElts, Depth + 1);
  3306. }
  3307. case ISD::EXTRACT_SUBVECTOR: {
  3308. // If we know the element index, just demand that subvector elements,
  3309. // otherwise demand them all.
  3310. SDValue Src = Op.getOperand(0);
  3311. ConstantSDNode *SubIdx = dyn_cast<ConstantSDNode>(Op.getOperand(1));
  3312. unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
  3313. if (SubIdx && SubIdx->getAPIntValue().ule(NumSrcElts - NumElts)) {
  3314. // Offset the demanded elts by the subvector index.
  3315. uint64_t Idx = SubIdx->getZExtValue();
  3316. APInt DemandedSrc = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx);
  3317. return ComputeNumSignBits(Src, DemandedSrc, Depth + 1);
  3318. }
  3319. return ComputeNumSignBits(Src, Depth + 1);
  3320. }
  3321. case ISD::CONCAT_VECTORS: {
  3322. // Determine the minimum number of sign bits across all demanded
  3323. // elts of the input vectors. Early out if the result is already 1.
  3324. Tmp = std::numeric_limits<unsigned>::max();
  3325. EVT SubVectorVT = Op.getOperand(0).getValueType();
  3326. unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements();
  3327. unsigned NumSubVectors = Op.getNumOperands();
  3328. for (unsigned i = 0; (i < NumSubVectors) && (Tmp > 1); ++i) {
  3329. APInt DemandedSub = DemandedElts.lshr(i * NumSubVectorElts);
  3330. DemandedSub = DemandedSub.trunc(NumSubVectorElts);
  3331. if (!DemandedSub)
  3332. continue;
  3333. Tmp2 = ComputeNumSignBits(Op.getOperand(i), DemandedSub, Depth + 1);
  3334. Tmp = std::min(Tmp, Tmp2);
  3335. }
  3336. assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
  3337. return Tmp;
  3338. }
  3339. case ISD::INSERT_SUBVECTOR: {
  3340. // If we know the element index, demand any elements from the subvector and
  3341. // the remainder from the src its inserted into, otherwise demand them all.
  3342. SDValue Src = Op.getOperand(0);
  3343. SDValue Sub = Op.getOperand(1);
  3344. auto *SubIdx = dyn_cast<ConstantSDNode>(Op.getOperand(2));
  3345. unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
  3346. if (SubIdx && SubIdx->getAPIntValue().ule(NumElts - NumSubElts)) {
  3347. Tmp = std::numeric_limits<unsigned>::max();
  3348. uint64_t Idx = SubIdx->getZExtValue();
  3349. APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
  3350. if (!!DemandedSubElts) {
  3351. Tmp = ComputeNumSignBits(Sub, DemandedSubElts, Depth + 1);
  3352. if (Tmp == 1) return 1; // early-out
  3353. }
  3354. APInt SubMask = APInt::getBitsSet(NumElts, Idx, Idx + NumSubElts);
  3355. APInt DemandedSrcElts = DemandedElts & ~SubMask;
  3356. if (!!DemandedSrcElts) {
  3357. Tmp2 = ComputeNumSignBits(Src, DemandedSrcElts, Depth + 1);
  3358. Tmp = std::min(Tmp, Tmp2);
  3359. }
  3360. assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
  3361. return Tmp;
  3362. }
  3363. // Not able to determine the index so just assume worst case.
  3364. Tmp = ComputeNumSignBits(Sub, Depth + 1);
  3365. if (Tmp == 1) return 1; // early-out
  3366. Tmp2 = ComputeNumSignBits(Src, Depth + 1);
  3367. Tmp = std::min(Tmp, Tmp2);
  3368. assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
  3369. return Tmp;
  3370. }
  3371. }
  3372. // If we are looking at the loaded value of the SDNode.
  3373. if (Op.getResNo() == 0) {
  3374. // Handle LOADX separately here. EXTLOAD case will fallthrough.
  3375. if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
  3376. unsigned ExtType = LD->getExtensionType();
  3377. switch (ExtType) {
  3378. default: break;
  3379. case ISD::SEXTLOAD: // '17' bits known
  3380. Tmp = LD->getMemoryVT().getScalarSizeInBits();
  3381. return VTBits-Tmp+1;
  3382. case ISD::ZEXTLOAD: // '16' bits known
  3383. Tmp = LD->getMemoryVT().getScalarSizeInBits();
  3384. return VTBits-Tmp;
  3385. }
  3386. }
  3387. }
  3388. // Allow the target to implement this method for its nodes.
  3389. if (Opcode >= ISD::BUILTIN_OP_END ||
  3390. Opcode == ISD::INTRINSIC_WO_CHAIN ||
  3391. Opcode == ISD::INTRINSIC_W_CHAIN ||
  3392. Opcode == ISD::INTRINSIC_VOID) {
  3393. unsigned NumBits =
  3394. TLI->ComputeNumSignBitsForTargetNode(Op, DemandedElts, *this, Depth);
  3395. if (NumBits > 1)
  3396. FirstAnswer = std::max(FirstAnswer, NumBits);
  3397. }
  3398. // Finally, if we can prove that the top bits of the result are 0's or 1's,
  3399. // use this information.
  3400. KnownBits Known = computeKnownBits(Op, DemandedElts, Depth);
  3401. APInt Mask;
  3402. if (Known.isNonNegative()) { // sign bit is 0
  3403. Mask = Known.Zero;
  3404. } else if (Known.isNegative()) { // sign bit is 1;
  3405. Mask = Known.One;
  3406. } else {
  3407. // Nothing known.
  3408. return FirstAnswer;
  3409. }
  3410. // Okay, we know that the sign bit in Mask is set. Use CLZ to determine
  3411. // the number of identical bits in the top of the input value.
  3412. Mask = ~Mask;
  3413. Mask <<= Mask.getBitWidth()-VTBits;
  3414. // Return # leading zeros. We use 'min' here in case Val was zero before
  3415. // shifting. We don't want to return '64' as for an i32 "0".
  3416. return std::max(FirstAnswer, std::min(VTBits, Mask.countLeadingZeros()));
  3417. }
  3418. bool SelectionDAG::isBaseWithConstantOffset(SDValue Op) const {
  3419. if ((Op.getOpcode() != ISD::ADD && Op.getOpcode() != ISD::OR) ||
  3420. !isa<ConstantSDNode>(Op.getOperand(1)))
  3421. return false;
  3422. if (Op.getOpcode() == ISD::OR &&
  3423. !MaskedValueIsZero(Op.getOperand(0), Op.getConstantOperandAPInt(1)))
  3424. return false;
  3425. return true;
  3426. }
  3427. bool SelectionDAG::isKnownNeverNaN(SDValue Op, bool SNaN, unsigned Depth) const {
  3428. // If we're told that NaNs won't happen, assume they won't.
  3429. if (getTarget().Options.NoNaNsFPMath || Op->getFlags().hasNoNaNs())
  3430. return true;
  3431. if (Depth == 6)
  3432. return false; // Limit search depth.
  3433. // TODO: Handle vectors.
  3434. // If the value is a constant, we can obviously see if it is a NaN or not.
  3435. if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) {
  3436. return !C->getValueAPF().isNaN() ||
  3437. (SNaN && !C->getValueAPF().isSignaling());
  3438. }
  3439. unsigned Opcode = Op.getOpcode();
  3440. switch (Opcode) {
  3441. case ISD::FADD:
  3442. case ISD::FSUB:
  3443. case ISD::FMUL:
  3444. case ISD::FDIV:
  3445. case ISD::FREM:
  3446. case ISD::FSIN:
  3447. case ISD::FCOS: {
  3448. if (SNaN)
  3449. return true;
  3450. // TODO: Need isKnownNeverInfinity
  3451. return false;
  3452. }
  3453. case ISD::FCANONICALIZE:
  3454. case ISD::FEXP:
  3455. case ISD::FEXP2:
  3456. case ISD::FTRUNC:
  3457. case ISD::FFLOOR:
  3458. case ISD::FCEIL:
  3459. case ISD::FROUND:
  3460. case ISD::FRINT:
  3461. case ISD::FNEARBYINT: {
  3462. if (SNaN)
  3463. return true;
  3464. return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
  3465. }
  3466. case ISD::FABS:
  3467. case ISD::FNEG:
  3468. case ISD::FCOPYSIGN: {
  3469. return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
  3470. }
  3471. case ISD::SELECT:
  3472. return isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1) &&
  3473. isKnownNeverNaN(Op.getOperand(2), SNaN, Depth + 1);
  3474. case ISD::FP_EXTEND:
  3475. case ISD::FP_ROUND: {
  3476. if (SNaN)
  3477. return true;
  3478. return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
  3479. }
  3480. case ISD::SINT_TO_FP:
  3481. case ISD::UINT_TO_FP:
  3482. return true;
  3483. case ISD::FMA:
  3484. case ISD::FMAD: {
  3485. if (SNaN)
  3486. return true;
  3487. return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) &&
  3488. isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1) &&
  3489. isKnownNeverNaN(Op.getOperand(2), SNaN, Depth + 1);
  3490. }
  3491. case ISD::FSQRT: // Need is known positive
  3492. case ISD::FLOG:
  3493. case ISD::FLOG2:
  3494. case ISD::FLOG10:
  3495. case ISD::FPOWI:
  3496. case ISD::FPOW: {
  3497. if (SNaN)
  3498. return true;
  3499. // TODO: Refine on operand
  3500. return false;
  3501. }
  3502. case ISD::FMINNUM:
  3503. case ISD::FMAXNUM: {
  3504. // Only one needs to be known not-nan, since it will be returned if the
  3505. // other ends up being one.
  3506. return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) ||
  3507. isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1);
  3508. }
  3509. case ISD::FMINNUM_IEEE:
  3510. case ISD::FMAXNUM_IEEE: {
  3511. if (SNaN)
  3512. return true;
  3513. // This can return a NaN if either operand is an sNaN, or if both operands
  3514. // are NaN.
  3515. return (isKnownNeverNaN(Op.getOperand(0), false, Depth + 1) &&
  3516. isKnownNeverSNaN(Op.getOperand(1), Depth + 1)) ||
  3517. (isKnownNeverNaN(Op.getOperand(1), false, Depth + 1) &&
  3518. isKnownNeverSNaN(Op.getOperand(0), Depth + 1));
  3519. }
  3520. case ISD::FMINIMUM:
  3521. case ISD::FMAXIMUM: {
  3522. // TODO: Does this quiet or return the origina NaN as-is?
  3523. return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) &&
  3524. isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1);
  3525. }
  3526. case ISD::EXTRACT_VECTOR_ELT: {
  3527. return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
  3528. }
  3529. default:
  3530. if (Opcode >= ISD::BUILTIN_OP_END ||
  3531. Opcode == ISD::INTRINSIC_WO_CHAIN ||
  3532. Opcode == ISD::INTRINSIC_W_CHAIN ||
  3533. Opcode == ISD::INTRINSIC_VOID) {
  3534. return TLI->isKnownNeverNaNForTargetNode(Op, *this, SNaN, Depth);
  3535. }
  3536. return false;
  3537. }
  3538. }
  3539. bool SelectionDAG::isKnownNeverZeroFloat(SDValue Op) const {
  3540. assert(Op.getValueType().isFloatingPoint() &&
  3541. "Floating point type expected");
  3542. // If the value is a constant, we can obviously see if it is a zero or not.
  3543. // TODO: Add BuildVector support.
  3544. if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
  3545. return !C->isZero();
  3546. return false;
  3547. }
  3548. bool SelectionDAG::isKnownNeverZero(SDValue Op) const {
  3549. assert(!Op.getValueType().isFloatingPoint() &&
  3550. "Floating point types unsupported - use isKnownNeverZeroFloat");
  3551. // If the value is a constant, we can obviously see if it is a zero or not.
  3552. if (ISD::matchUnaryPredicate(
  3553. Op, [](ConstantSDNode *C) { return !C->isNullValue(); }))
  3554. return true;
  3555. // TODO: Recognize more cases here.
  3556. switch (Op.getOpcode()) {
  3557. default: break;
  3558. case ISD::OR:
  3559. if (isKnownNeverZero(Op.getOperand(1)) ||
  3560. isKnownNeverZero(Op.getOperand(0)))
  3561. return true;
  3562. break;
  3563. }
  3564. return false;
  3565. }
  3566. bool SelectionDAG::isEqualTo(SDValue A, SDValue B) const {
  3567. // Check the obvious case.
  3568. if (A == B) return true;
  3569. // For for negative and positive zero.
  3570. if (const ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A))
  3571. if (const ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B))
  3572. if (CA->isZero() && CB->isZero()) return true;
  3573. // Otherwise they may not be equal.
  3574. return false;
  3575. }
  3576. // FIXME: unify with llvm::haveNoCommonBitsSet.
  3577. // FIXME: could also handle masked merge pattern (X & ~M) op (Y & M)
  3578. bool SelectionDAG::haveNoCommonBitsSet(SDValue A, SDValue B) const {
  3579. assert(A.getValueType() == B.getValueType() &&
  3580. "Values must have the same type");
  3581. return (computeKnownBits(A).Zero | computeKnownBits(B).Zero).isAllOnesValue();
  3582. }
  3583. static SDValue FoldBUILD_VECTOR(const SDLoc &DL, EVT VT,
  3584. ArrayRef<SDValue> Ops,
  3585. SelectionDAG &DAG) {
  3586. int NumOps = Ops.size();
  3587. assert(NumOps != 0 && "Can't build an empty vector!");
  3588. assert(VT.getVectorNumElements() == (unsigned)NumOps &&
  3589. "Incorrect element count in BUILD_VECTOR!");
  3590. // BUILD_VECTOR of UNDEFs is UNDEF.
  3591. if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); }))
  3592. return DAG.getUNDEF(VT);
  3593. // BUILD_VECTOR of seq extract/insert from the same vector + type is Identity.
  3594. SDValue IdentitySrc;
  3595. bool IsIdentity = true;
  3596. for (int i = 0; i != NumOps; ++i) {
  3597. if (Ops[i].getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
  3598. Ops[i].getOperand(0).getValueType() != VT ||
  3599. (IdentitySrc && Ops[i].getOperand(0) != IdentitySrc) ||
  3600. !isa<ConstantSDNode>(Ops[i].getOperand(1)) ||
  3601. cast<ConstantSDNode>(Ops[i].getOperand(1))->getAPIntValue() != i) {
  3602. IsIdentity = false;
  3603. break;
  3604. }
  3605. IdentitySrc = Ops[i].getOperand(0);
  3606. }
  3607. if (IsIdentity)
  3608. return IdentitySrc;
  3609. return SDValue();
  3610. }
  3611. static SDValue FoldCONCAT_VECTORS(const SDLoc &DL, EVT VT,
  3612. ArrayRef<SDValue> Ops,
  3613. SelectionDAG &DAG) {
  3614. assert(!Ops.empty() && "Can't concatenate an empty list of vectors!");
  3615. assert(llvm::all_of(Ops,
  3616. [Ops](SDValue Op) {
  3617. return Ops[0].getValueType() == Op.getValueType();
  3618. }) &&
  3619. "Concatenation of vectors with inconsistent value types!");
  3620. assert((Ops.size() * Ops[0].getValueType().getVectorNumElements()) ==
  3621. VT.getVectorNumElements() &&
  3622. "Incorrect element count in vector concatenation!");
  3623. if (Ops.size() == 1)
  3624. return Ops[0];
  3625. // Concat of UNDEFs is UNDEF.
  3626. if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); }))
  3627. return DAG.getUNDEF(VT);
  3628. // A CONCAT_VECTOR with all UNDEF/BUILD_VECTOR operands can be
  3629. // simplified to one big BUILD_VECTOR.
  3630. // FIXME: Add support for SCALAR_TO_VECTOR as well.
  3631. EVT SVT = VT.getScalarType();
  3632. SmallVector<SDValue, 16> Elts;
  3633. for (SDValue Op : Ops) {
  3634. EVT OpVT = Op.getValueType();
  3635. if (Op.isUndef())
  3636. Elts.append(OpVT.getVectorNumElements(), DAG.getUNDEF(SVT));
  3637. else if (Op.getOpcode() == ISD::BUILD_VECTOR)
  3638. Elts.append(Op->op_begin(), Op->op_end());
  3639. else
  3640. return SDValue();
  3641. }
  3642. // BUILD_VECTOR requires all inputs to be of the same type, find the
  3643. // maximum type and extend them all.
  3644. for (SDValue Op : Elts)
  3645. SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
  3646. if (SVT.bitsGT(VT.getScalarType()))
  3647. for (SDValue &Op : Elts)
  3648. Op = DAG.getTargetLoweringInfo().isZExtFree(Op.getValueType(), SVT)
  3649. ? DAG.getZExtOrTrunc(Op, DL, SVT)
  3650. : DAG.getSExtOrTrunc(Op, DL, SVT);
  3651. SDValue V = DAG.getBuildVector(VT, DL, Elts);
  3652. NewSDValueDbgMsg(V, "New node fold concat vectors: ", &DAG);
  3653. return V;
  3654. }
  3655. /// Gets or creates the specified node.
  3656. SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT) {
  3657. FoldingSetNodeID ID;
  3658. AddNodeIDNode(ID, Opcode, getVTList(VT), None);
  3659. void *IP = nullptr;
  3660. if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
  3661. return SDValue(E, 0);
  3662. auto *N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(),
  3663. getVTList(VT));
  3664. CSEMap.InsertNode(N, IP);
  3665. InsertNode(N);
  3666. SDValue V = SDValue(N, 0);
  3667. NewSDValueDbgMsg(V, "Creating new node: ", this);
  3668. return V;
  3669. }
  3670. SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
  3671. SDValue Operand, const SDNodeFlags Flags) {
  3672. // Constant fold unary operations with an integer constant operand. Even
  3673. // opaque constant will be folded, because the folding of unary operations
  3674. // doesn't create new constants with different values. Nevertheless, the
  3675. // opaque flag is preserved during folding to prevent future folding with
  3676. // other constants.
  3677. if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Operand)) {
  3678. const APInt &Val = C->getAPIntValue();
  3679. switch (Opcode) {
  3680. default: break;
  3681. case ISD::SIGN_EXTEND:
  3682. return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT,
  3683. C->isTargetOpcode(), C->isOpaque());
  3684. case ISD::TRUNCATE:
  3685. if (C->isOpaque())
  3686. break;
  3687. LLVM_FALLTHROUGH;
  3688. case ISD::ANY_EXTEND:
  3689. case ISD::ZERO_EXTEND:
  3690. return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT,
  3691. C->isTargetOpcode(), C->isOpaque());
  3692. case ISD::UINT_TO_FP:
  3693. case ISD::SINT_TO_FP: {
  3694. APFloat apf(EVTToAPFloatSemantics(VT),
  3695. APInt::getNullValue(VT.getSizeInBits()));
  3696. (void)apf.convertFromAPInt(Val,
  3697. Opcode==ISD::SINT_TO_FP,
  3698. APFloat::rmNearestTiesToEven);
  3699. return getConstantFP(apf, DL, VT);
  3700. }
  3701. case ISD::BITCAST:
  3702. if (VT == MVT::f16 && C->getValueType(0) == MVT::i16)
  3703. return getConstantFP(APFloat(APFloat::IEEEhalf(), Val), DL, VT);
  3704. if (VT == MVT::f32 && C->getValueType(0) == MVT::i32)
  3705. return getConstantFP(APFloat(APFloat::IEEEsingle(), Val), DL, VT);
  3706. if (VT == MVT::f64 && C->getValueType(0) == MVT::i64)
  3707. return getConstantFP(APFloat(APFloat::IEEEdouble(), Val), DL, VT);
  3708. if (VT == MVT::f128 && C->getValueType(0) == MVT::i128)
  3709. return getConstantFP(APFloat(APFloat::IEEEquad(), Val), DL, VT);
  3710. break;
  3711. case ISD::ABS:
  3712. return getConstant(Val.abs(), DL, VT, C->isTargetOpcode(),
  3713. C->isOpaque());
  3714. case ISD::BITREVERSE:
  3715. return getConstant(Val.reverseBits(), DL, VT, C->isTargetOpcode(),
  3716. C->isOpaque());
  3717. case ISD::BSWAP:
  3718. return getConstant(Val.byteSwap(), DL, VT, C->isTargetOpcode(),
  3719. C->isOpaque());
  3720. case ISD::CTPOP:
  3721. return getConstant(Val.countPopulation(), DL, VT, C->isTargetOpcode(),
  3722. C->isOpaque());
  3723. case ISD::CTLZ:
  3724. case ISD::CTLZ_ZERO_UNDEF:
  3725. return getConstant(Val.countLeadingZeros(), DL, VT, C->isTargetOpcode(),
  3726. C->isOpaque());
  3727. case ISD::CTTZ:
  3728. case ISD::CTTZ_ZERO_UNDEF:
  3729. return getConstant(Val.countTrailingZeros(), DL, VT, C->isTargetOpcode(),
  3730. C->isOpaque());
  3731. case ISD::FP16_TO_FP: {
  3732. bool Ignored;
  3733. APFloat FPV(APFloat::IEEEhalf(),
  3734. (Val.getBitWidth() == 16) ? Val : Val.trunc(16));
  3735. // This can return overflow, underflow, or inexact; we don't care.
  3736. // FIXME need to be more flexible about rounding mode.
  3737. (void)FPV.convert(EVTToAPFloatSemantics(VT),
  3738. APFloat::rmNearestTiesToEven, &Ignored);
  3739. return getConstantFP(FPV, DL, VT);
  3740. }
  3741. }
  3742. }
  3743. // Constant fold unary operations with a floating point constant operand.
  3744. if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Operand)) {
  3745. APFloat V = C->getValueAPF(); // make copy
  3746. switch (Opcode) {
  3747. case ISD::FNEG:
  3748. V.changeSign();
  3749. return getConstantFP(V, DL, VT);
  3750. case ISD::FABS:
  3751. V.clearSign();
  3752. return getConstantFP(V, DL, VT);
  3753. case ISD::FCEIL: {
  3754. APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardPositive);
  3755. if (fs == APFloat::opOK || fs == APFloat::opInexact)
  3756. return getConstantFP(V, DL, VT);
  3757. break;
  3758. }
  3759. case ISD::FTRUNC: {
  3760. APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardZero);
  3761. if (fs == APFloat::opOK || fs == APFloat::opInexact)
  3762. return getConstantFP(V, DL, VT);
  3763. break;
  3764. }
  3765. case ISD::FFLOOR: {
  3766. APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardNegative);
  3767. if (fs == APFloat::opOK || fs == APFloat::opInexact)
  3768. return getConstantFP(V, DL, VT);
  3769. break;
  3770. }
  3771. case ISD::FP_EXTEND: {
  3772. bool ignored;
  3773. // This can return overflow, underflow, or inexact; we don't care.
  3774. // FIXME need to be more flexible about rounding mode.
  3775. (void)V.convert(EVTToAPFloatSemantics(VT),
  3776. APFloat::rmNearestTiesToEven, &ignored);
  3777. return getConstantFP(V, DL, VT);
  3778. }
  3779. case ISD::FP_TO_SINT:
  3780. case ISD::FP_TO_UINT: {
  3781. bool ignored;
  3782. APSInt IntVal(VT.getSizeInBits(), Opcode == ISD::FP_TO_UINT);
  3783. // FIXME need to be more flexible about rounding mode.
  3784. APFloat::opStatus s =
  3785. V.convertToInteger(IntVal, APFloat::rmTowardZero, &ignored);
  3786. if (s == APFloat::opInvalidOp) // inexact is OK, in fact usual
  3787. break;
  3788. return getConstant(IntVal, DL, VT);
  3789. }
  3790. case ISD::BITCAST:
  3791. if (VT == MVT::i16 && C->getValueType(0) == MVT::f16)
  3792. return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL, VT);
  3793. else if (VT == MVT::i32 && C->getValueType(0) == MVT::f32)
  3794. return getConstant((uint32_t)V.bitcastToAPInt().getZExtValue(), DL, VT);
  3795. else if (VT == MVT::i64 && C->getValueType(0) == MVT::f64)
  3796. return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT);
  3797. break;
  3798. case ISD::FP_TO_FP16: {
  3799. bool Ignored;
  3800. // This can return overflow, underflow, or inexact; we don't care.
  3801. // FIXME need to be more flexible about rounding mode.
  3802. (void)V.convert(APFloat::IEEEhalf(),
  3803. APFloat::rmNearestTiesToEven, &Ignored);
  3804. return getConstant(V.bitcastToAPInt(), DL, VT);
  3805. }
  3806. }
  3807. }
  3808. // Constant fold unary operations with a vector integer or float operand.
  3809. if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Operand)) {
  3810. if (BV->isConstant()) {
  3811. switch (Opcode) {
  3812. default:
  3813. // FIXME: Entirely reasonable to perform folding of other unary
  3814. // operations here as the need arises.
  3815. break;
  3816. case ISD::FNEG:
  3817. case ISD::FABS:
  3818. case ISD::FCEIL:
  3819. case ISD::FTRUNC:
  3820. case ISD::FFLOOR:
  3821. case ISD::FP_EXTEND:
  3822. case ISD::FP_TO_SINT:
  3823. case ISD::FP_TO_UINT:
  3824. case ISD::TRUNCATE:
  3825. case ISD::ANY_EXTEND:
  3826. case ISD::ZERO_EXTEND:
  3827. case ISD::SIGN_EXTEND:
  3828. case ISD::UINT_TO_FP:
  3829. case ISD::SINT_TO_FP:
  3830. case ISD::ABS:
  3831. case ISD::BITREVERSE:
  3832. case ISD::BSWAP:
  3833. case ISD::CTLZ:
  3834. case ISD::CTLZ_ZERO_UNDEF:
  3835. case ISD::CTTZ:
  3836. case ISD::CTTZ_ZERO_UNDEF:
  3837. case ISD::CTPOP: {
  3838. SDValue Ops = { Operand };
  3839. if (SDValue Fold = FoldConstantVectorArithmetic(Opcode, DL, VT, Ops))
  3840. return Fold;
  3841. }
  3842. }
  3843. }
  3844. }
  3845. unsigned OpOpcode = Operand.getNode()->getOpcode();
  3846. switch (Opcode) {
  3847. case ISD::TokenFactor:
  3848. case ISD::MERGE_VALUES:
  3849. case ISD::CONCAT_VECTORS:
  3850. return Operand; // Factor, merge or concat of one node? No need.
  3851. case ISD::BUILD_VECTOR: {
  3852. // Attempt to simplify BUILD_VECTOR.
  3853. SDValue Ops[] = {Operand};
  3854. if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
  3855. return V;
  3856. break;
  3857. }
  3858. case ISD::FP_ROUND: llvm_unreachable("Invalid method to make FP_ROUND node");
  3859. case ISD::FP_EXTEND:
  3860. assert(VT.isFloatingPoint() &&
  3861. Operand.getValueType().isFloatingPoint() && "Invalid FP cast!");
  3862. if (Operand.getValueType() == VT) return Operand; // noop conversion.
  3863. assert((!VT.isVector() ||
  3864. VT.getVectorNumElements() ==
  3865. Operand.getValueType().getVectorNumElements()) &&
  3866. "Vector element count mismatch!");
  3867. assert(Operand.getValueType().bitsLT(VT) &&
  3868. "Invalid fpext node, dst < src!");
  3869. if (Operand.isUndef())
  3870. return getUNDEF(VT);
  3871. break;
  3872. case ISD::SIGN_EXTEND:
  3873. assert(VT.isInteger() && Operand.getValueType().isInteger() &&
  3874. "Invalid SIGN_EXTEND!");
  3875. if (Operand.getValueType() == VT) return Operand; // noop extension
  3876. assert((!VT.isVector() ||
  3877. VT.getVectorNumElements() ==
  3878. Operand.getValueType().getVectorNumElements()) &&
  3879. "Vector element count mismatch!");
  3880. assert(Operand.getValueType().bitsLT(VT) &&
  3881. "Invalid sext node, dst < src!");
  3882. if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND)
  3883. return getNode(OpOpcode, DL, VT, Operand.getOperand(0));
  3884. else if (OpOpcode == ISD::UNDEF)
  3885. // sext(undef) = 0, because the top bits will all be the same.
  3886. return getConstant(0, DL, VT);
  3887. break;
  3888. case ISD::ZERO_EXTEND:
  3889. assert(VT.isInteger() && Operand.getValueType().isInteger() &&
  3890. "Invalid ZERO_EXTEND!");
  3891. if (Operand.getValueType() == VT) return Operand; // noop extension
  3892. assert((!VT.isVector() ||
  3893. VT.getVectorNumElements() ==
  3894. Operand.getValueType().getVectorNumElements()) &&
  3895. "Vector element count mismatch!");
  3896. assert(Operand.getValueType().bitsLT(VT) &&
  3897. "Invalid zext node, dst < src!");
  3898. if (OpOpcode == ISD::ZERO_EXTEND) // (zext (zext x)) -> (zext x)
  3899. return getNode(ISD::ZERO_EXTEND, DL, VT, Operand.getOperand(0));
  3900. else if (OpOpcode == ISD::UNDEF)
  3901. // zext(undef) = 0, because the top bits will be zero.
  3902. return getConstant(0, DL, VT);
  3903. break;
  3904. case ISD::ANY_EXTEND:
  3905. assert(VT.isInteger() && Operand.getValueType().isInteger() &&
  3906. "Invalid ANY_EXTEND!");
  3907. if (Operand.getValueType() == VT) return Operand; // noop extension
  3908. assert((!VT.isVector() ||
  3909. VT.getVectorNumElements() ==
  3910. Operand.getValueType().getVectorNumElements()) &&
  3911. "Vector element count mismatch!");
  3912. assert(Operand.getValueType().bitsLT(VT) &&
  3913. "Invalid anyext node, dst < src!");
  3914. if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
  3915. OpOpcode == ISD::ANY_EXTEND)
  3916. // (ext (zext x)) -> (zext x) and (ext (sext x)) -> (sext x)
  3917. return getNode(OpOpcode, DL, VT, Operand.getOperand(0));
  3918. else if (OpOpcode == ISD::UNDEF)
  3919. return getUNDEF(VT);
  3920. // (ext (trunc x)) -> x
  3921. if (OpOpcode == ISD::TRUNCATE) {
  3922. SDValue OpOp = Operand.getOperand(0);
  3923. if (OpOp.getValueType() == VT) {
  3924. transferDbgValues(Operand, OpOp);
  3925. return OpOp;
  3926. }
  3927. }
  3928. break;
  3929. case ISD::TRUNCATE:
  3930. assert(VT.isInteger() && Operand.getValueType().isInteger() &&
  3931. "Invalid TRUNCATE!");
  3932. if (Operand.getValueType() == VT) return Operand; // noop truncate
  3933. assert((!VT.isVector() ||
  3934. VT.getVectorNumElements() ==
  3935. Operand.getValueType().getVectorNumElements()) &&
  3936. "Vector element count mismatch!");
  3937. assert(Operand.getValueType().bitsGT(VT) &&
  3938. "Invalid truncate node, src < dst!");
  3939. if (OpOpcode == ISD::TRUNCATE)
  3940. return getNode(ISD::TRUNCATE, DL, VT, Operand.getOperand(0));
  3941. if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
  3942. OpOpcode == ISD::ANY_EXTEND) {
  3943. // If the source is smaller than the dest, we still need an extend.
  3944. if (Operand.getOperand(0).getValueType().getScalarType()
  3945. .bitsLT(VT.getScalarType()))
  3946. return getNode(OpOpcode, DL, VT, Operand.getOperand(0));
  3947. if (Operand.getOperand(0).getValueType().bitsGT(VT))
  3948. return getNode(ISD::TRUNCATE, DL, VT, Operand.getOperand(0));
  3949. return Operand.getOperand(0);
  3950. }
  3951. if (OpOpcode == ISD::UNDEF)
  3952. return getUNDEF(VT);
  3953. break;
  3954. case ISD::ANY_EXTEND_VECTOR_INREG:
  3955. case ISD::ZERO_EXTEND_VECTOR_INREG:
  3956. case ISD::SIGN_EXTEND_VECTOR_INREG:
  3957. assert(VT.isVector() && "This DAG node is restricted to vector types.");
  3958. assert(Operand.getValueType().bitsLE(VT) &&
  3959. "The input must be the same size or smaller than the result.");
  3960. assert(VT.getVectorNumElements() <
  3961. Operand.getValueType().getVectorNumElements() &&
  3962. "The destination vector type must have fewer lanes than the input.");
  3963. break;
  3964. case ISD::ABS:
  3965. assert(VT.isInteger() && VT == Operand.getValueType() &&
  3966. "Invalid ABS!");
  3967. if (OpOpcode == ISD::UNDEF)
  3968. return getUNDEF(VT);
  3969. break;
  3970. case ISD::BSWAP:
  3971. assert(VT.isInteger() && VT == Operand.getValueType() &&
  3972. "Invalid BSWAP!");
  3973. assert((VT.getScalarSizeInBits() % 16 == 0) &&
  3974. "BSWAP types must be a multiple of 16 bits!");
  3975. if (OpOpcode == ISD::UNDEF)
  3976. return getUNDEF(VT);
  3977. break;
  3978. case ISD::BITREVERSE:
  3979. assert(VT.isInteger() && VT == Operand.getValueType() &&
  3980. "Invalid BITREVERSE!");
  3981. if (OpOpcode == ISD::UNDEF)
  3982. return getUNDEF(VT);
  3983. break;
  3984. case ISD::BITCAST:
  3985. // Basic sanity checking.
  3986. assert(VT.getSizeInBits() == Operand.getValueSizeInBits() &&
  3987. "Cannot BITCAST between types of different sizes!");
  3988. if (VT == Operand.getValueType()) return Operand; // noop conversion.
  3989. if (OpOpcode == ISD::BITCAST) // bitconv(bitconv(x)) -> bitconv(x)
  3990. return getNode(ISD::BITCAST, DL, VT, Operand.getOperand(0));
  3991. if (OpOpcode == ISD::UNDEF)
  3992. return getUNDEF(VT);
  3993. break;
  3994. case ISD::SCALAR_TO_VECTOR:
  3995. assert(VT.isVector() && !Operand.getValueType().isVector() &&
  3996. (VT.getVectorElementType() == Operand.getValueType() ||
  3997. (VT.getVectorElementType().isInteger() &&
  3998. Operand.getValueType().isInteger() &&
  3999. VT.getVectorElementType().bitsLE(Operand.getValueType()))) &&
  4000. "Illegal SCALAR_TO_VECTOR node!");
  4001. if (OpOpcode == ISD::UNDEF)
  4002. return getUNDEF(VT);
  4003. // scalar_to_vector(extract_vector_elt V, 0) -> V, top bits are undefined.
  4004. if (OpOpcode == ISD::EXTRACT_VECTOR_ELT &&
  4005. isa<ConstantSDNode>(Operand.getOperand(1)) &&
  4006. Operand.getConstantOperandVal(1) == 0 &&
  4007. Operand.getOperand(0).getValueType() == VT)
  4008. return Operand.getOperand(0);
  4009. break;
  4010. case ISD::FNEG:
  4011. // -(X-Y) -> (Y-X) is unsafe because when X==Y, -0.0 != +0.0
  4012. if ((getTarget().Options.UnsafeFPMath || Flags.hasNoSignedZeros()) &&
  4013. OpOpcode == ISD::FSUB)
  4014. return getNode(ISD::FSUB, DL, VT, Operand.getOperand(1),
  4015. Operand.getOperand(0), Flags);
  4016. if (OpOpcode == ISD::FNEG) // --X -> X
  4017. return Operand.getOperand(0);
  4018. break;
  4019. case ISD::FABS:
  4020. if (OpOpcode == ISD::FNEG) // abs(-X) -> abs(X)
  4021. return getNode(ISD::FABS, DL, VT, Operand.getOperand(0));
  4022. break;
  4023. }
  4024. SDNode *N;
  4025. SDVTList VTs = getVTList(VT);
  4026. SDValue Ops[] = {Operand};
  4027. if (VT != MVT::Glue) { // Don't CSE flag producing nodes
  4028. FoldingSetNodeID ID;
  4029. AddNodeIDNode(ID, Opcode, VTs, Ops);
  4030. void *IP = nullptr;
  4031. if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
  4032. E->intersectFlagsWith(Flags);
  4033. return SDValue(E, 0);
  4034. }
  4035. N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
  4036. N->setFlags(Flags);
  4037. createOperands(N, Ops);
  4038. CSEMap.InsertNode(N, IP);
  4039. } else {
  4040. N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
  4041. createOperands(N, Ops);
  4042. }
  4043. InsertNode(N);
  4044. SDValue V = SDValue(N, 0);
  4045. NewSDValueDbgMsg(V, "Creating new node: ", this);
  4046. return V;
  4047. }
  4048. static std::pair<APInt, bool> FoldValue(unsigned Opcode, const APInt &C1,
  4049. const APInt &C2) {
  4050. switch (Opcode) {
  4051. case ISD::ADD: return std::make_pair(C1 + C2, true);
  4052. case ISD::SUB: return std::make_pair(C1 - C2, true);
  4053. case ISD::MUL: return std::make_pair(C1 * C2, true);
  4054. case ISD::AND: return std::make_pair(C1 & C2, true);
  4055. case ISD::OR: return std::make_pair(C1 | C2, true);
  4056. case ISD::XOR: return std::make_pair(C1 ^ C2, true);
  4057. case ISD::SHL: return std::make_pair(C1 << C2, true);
  4058. case ISD::SRL: return std::make_pair(C1.lshr(C2), true);
  4059. case ISD::SRA: return std::make_pair(C1.ashr(C2), true);
  4060. case ISD::ROTL: return std::make_pair(C1.rotl(C2), true);
  4061. case ISD::ROTR: return std::make_pair(C1.rotr(C2), true);
  4062. case ISD::SMIN: return std::make_pair(C1.sle(C2) ? C1 : C2, true);
  4063. case ISD::SMAX: return std::make_pair(C1.sge(C2) ? C1 : C2, true);
  4064. case ISD::UMIN: return std::make_pair(C1.ule(C2) ? C1 : C2, true);
  4065. case ISD::UMAX: return std::make_pair(C1.uge(C2) ? C1 : C2, true);
  4066. case ISD::SADDSAT: return std::make_pair(C1.sadd_sat(C2), true);
  4067. case ISD::UADDSAT: return std::make_pair(C1.uadd_sat(C2), true);
  4068. case ISD::SSUBSAT: return std::make_pair(C1.ssub_sat(C2), true);
  4069. case ISD::USUBSAT: return std::make_pair(C1.usub_sat(C2), true);
  4070. case ISD::UDIV:
  4071. if (!C2.getBoolValue())
  4072. break;
  4073. return std::make_pair(C1.udiv(C2), true);
  4074. case ISD::UREM:
  4075. if (!C2.getBoolValue())
  4076. break;
  4077. return std::make_pair(C1.urem(C2), true);
  4078. case ISD::SDIV:
  4079. if (!C2.getBoolValue())
  4080. break;
  4081. return std::make_pair(C1.sdiv(C2), true);
  4082. case ISD::SREM:
  4083. if (!C2.getBoolValue())
  4084. break;
  4085. return std::make_pair(C1.srem(C2), true);
  4086. }
  4087. return std::make_pair(APInt(1, 0), false);
  4088. }
  4089. SDValue SelectionDAG::FoldConstantArithmetic(unsigned Opcode, const SDLoc &DL,
  4090. EVT VT, const ConstantSDNode *C1,
  4091. const ConstantSDNode *C2) {
  4092. if (C1->isOpaque() || C2->isOpaque())
  4093. return SDValue();
  4094. std::pair<APInt, bool> Folded = FoldValue(Opcode, C1->getAPIntValue(),
  4095. C2->getAPIntValue());
  4096. if (!Folded.second)
  4097. return SDValue();
  4098. return getConstant(Folded.first, DL, VT);
  4099. }
  4100. SDValue SelectionDAG::FoldSymbolOffset(unsigned Opcode, EVT VT,
  4101. const GlobalAddressSDNode *GA,
  4102. const SDNode *N2) {
  4103. if (GA->getOpcode() != ISD::GlobalAddress)
  4104. return SDValue();
  4105. if (!TLI->isOffsetFoldingLegal(GA))
  4106. return SDValue();
  4107. auto *C2 = dyn_cast<ConstantSDNode>(N2);
  4108. if (!C2)
  4109. return SDValue();
  4110. int64_t Offset = C2->getSExtValue();
  4111. switch (Opcode) {
  4112. case ISD::ADD: break;
  4113. case ISD::SUB: Offset = -uint64_t(Offset); break;
  4114. default: return SDValue();
  4115. }
  4116. return getGlobalAddress(GA->getGlobal(), SDLoc(C2), VT,
  4117. GA->getOffset() + uint64_t(Offset));
  4118. }
  4119. bool SelectionDAG::isUndef(unsigned Opcode, ArrayRef<SDValue> Ops) {
  4120. switch (Opcode) {
  4121. case ISD::SDIV:
  4122. case ISD::UDIV:
  4123. case ISD::SREM:
  4124. case ISD::UREM: {
  4125. // If a divisor is zero/undef or any element of a divisor vector is
  4126. // zero/undef, the whole op is undef.
  4127. assert(Ops.size() == 2 && "Div/rem should have 2 operands");
  4128. SDValue Divisor = Ops[1];
  4129. if (Divisor.isUndef() || isNullConstant(Divisor))
  4130. return true;
  4131. return ISD::isBuildVectorOfConstantSDNodes(Divisor.getNode()) &&
  4132. llvm::any_of(Divisor->op_values(),
  4133. [](SDValue V) { return V.isUndef() ||
  4134. isNullConstant(V); });
  4135. // TODO: Handle signed overflow.
  4136. }
  4137. // TODO: Handle oversized shifts.
  4138. default:
  4139. return false;
  4140. }
  4141. }
  4142. SDValue SelectionDAG::FoldConstantArithmetic(unsigned Opcode, const SDLoc &DL,
  4143. EVT VT, SDNode *N1, SDNode *N2) {
  4144. // If the opcode is a target-specific ISD node, there's nothing we can
  4145. // do here and the operand rules may not line up with the below, so
  4146. // bail early.
  4147. if (Opcode >= ISD::BUILTIN_OP_END)
  4148. return SDValue();
  4149. if (isUndef(Opcode, {SDValue(N1, 0), SDValue(N2, 0)}))
  4150. return getUNDEF(VT);
  4151. // Handle the case of two scalars.
  4152. if (auto *C1 = dyn_cast<ConstantSDNode>(N1)) {
  4153. if (auto *C2 = dyn_cast<ConstantSDNode>(N2)) {
  4154. SDValue Folded = FoldConstantArithmetic(Opcode, DL, VT, C1, C2);
  4155. assert((!Folded || !VT.isVector()) &&
  4156. "Can't fold vectors ops with scalar operands");
  4157. return Folded;
  4158. }
  4159. }
  4160. // fold (add Sym, c) -> Sym+c
  4161. if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N1))
  4162. return FoldSymbolOffset(Opcode, VT, GA, N2);
  4163. if (TLI->isCommutativeBinOp(Opcode))
  4164. if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N2))
  4165. return FoldSymbolOffset(Opcode, VT, GA, N1);
  4166. // For vectors, extract each constant element and fold them individually.
  4167. // Either input may be an undef value.
  4168. auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
  4169. if (!BV1 && !N1->isUndef())
  4170. return SDValue();
  4171. auto *BV2 = dyn_cast<BuildVectorSDNode>(N2);
  4172. if (!BV2 && !N2->isUndef())
  4173. return SDValue();
  4174. // If both operands are undef, that's handled the same way as scalars.
  4175. if (!BV1 && !BV2)
  4176. return SDValue();
  4177. assert((!BV1 || !BV2 || BV1->getNumOperands() == BV2->getNumOperands()) &&
  4178. "Vector binop with different number of elements in operands?");
  4179. EVT SVT = VT.getScalarType();
  4180. EVT LegalSVT = SVT;
  4181. if (NewNodesMustHaveLegalTypes && LegalSVT.isInteger()) {
  4182. LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT);
  4183. if (LegalSVT.bitsLT(SVT))
  4184. return SDValue();
  4185. }
  4186. SmallVector<SDValue, 4> Outputs;
  4187. unsigned NumOps = BV1 ? BV1->getNumOperands() : BV2->getNumOperands();
  4188. for (unsigned I = 0; I != NumOps; ++I) {
  4189. SDValue V1 = BV1 ? BV1->getOperand(I) : getUNDEF(SVT);
  4190. SDValue V2 = BV2 ? BV2->getOperand(I) : getUNDEF(SVT);
  4191. if (SVT.isInteger()) {
  4192. if (V1->getValueType(0).bitsGT(SVT))
  4193. V1 = getNode(ISD::TRUNCATE, DL, SVT, V1);
  4194. if (V2->getValueType(0).bitsGT(SVT))
  4195. V2 = getNode(ISD::TRUNCATE, DL, SVT, V2);
  4196. }
  4197. if (V1->getValueType(0) != SVT || V2->getValueType(0) != SVT)
  4198. return SDValue();
  4199. // Fold one vector element.
  4200. SDValue ScalarResult = getNode(Opcode, DL, SVT, V1, V2);
  4201. if (LegalSVT != SVT)
  4202. ScalarResult = getNode(ISD::SIGN_EXTEND, DL, LegalSVT, ScalarResult);
  4203. // Scalar folding only succeeded if the result is a constant or UNDEF.
  4204. if (!ScalarResult.isUndef() && ScalarResult.getOpcode() != ISD::Constant &&
  4205. ScalarResult.getOpcode() != ISD::ConstantFP)
  4206. return SDValue();
  4207. Outputs.push_back(ScalarResult);
  4208. }
  4209. assert(VT.getVectorNumElements() == Outputs.size() &&
  4210. "Vector size mismatch!");
  4211. // We may have a vector type but a scalar result. Create a splat.
  4212. Outputs.resize(VT.getVectorNumElements(), Outputs.back());
  4213. // Build a big vector out of the scalar elements we generated.
  4214. return getBuildVector(VT, SDLoc(), Outputs);
  4215. }
  4216. // TODO: Merge with FoldConstantArithmetic
  4217. SDValue SelectionDAG::FoldConstantVectorArithmetic(unsigned Opcode,
  4218. const SDLoc &DL, EVT VT,
  4219. ArrayRef<SDValue> Ops,
  4220. const SDNodeFlags Flags) {
  4221. // If the opcode is a target-specific ISD node, there's nothing we can
  4222. // do here and the operand rules may not line up with the below, so
  4223. // bail early.
  4224. if (Opcode >= ISD::BUILTIN_OP_END)
  4225. return SDValue();
  4226. if (isUndef(Opcode, Ops))
  4227. return getUNDEF(VT);
  4228. // We can only fold vectors - maybe merge with FoldConstantArithmetic someday?
  4229. if (!VT.isVector())
  4230. return SDValue();
  4231. unsigned NumElts = VT.getVectorNumElements();
  4232. auto IsScalarOrSameVectorSize = [&](const SDValue &Op) {
  4233. return !Op.getValueType().isVector() ||
  4234. Op.getValueType().getVectorNumElements() == NumElts;
  4235. };
  4236. auto IsConstantBuildVectorOrUndef = [&](const SDValue &Op) {
  4237. BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op);
  4238. return (Op.isUndef()) || (Op.getOpcode() == ISD::CONDCODE) ||
  4239. (BV && BV->isConstant());
  4240. };
  4241. // All operands must be vector types with the same number of elements as
  4242. // the result type and must be either UNDEF or a build vector of constant
  4243. // or UNDEF scalars.
  4244. if (!llvm::all_of(Ops, IsConstantBuildVectorOrUndef) ||
  4245. !llvm::all_of(Ops, IsScalarOrSameVectorSize))
  4246. return SDValue();
  4247. // If we are comparing vectors, then the result needs to be a i1 boolean
  4248. // that is then sign-extended back to the legal result type.
  4249. EVT SVT = (Opcode == ISD::SETCC ? MVT::i1 : VT.getScalarType());
  4250. // Find legal integer scalar type for constant promotion and
  4251. // ensure that its scalar size is at least as large as source.
  4252. EVT LegalSVT = VT.getScalarType();
  4253. if (NewNodesMustHaveLegalTypes && LegalSVT.isInteger()) {
  4254. LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT);
  4255. if (LegalSVT.bitsLT(VT.getScalarType()))
  4256. return SDValue();
  4257. }
  4258. // Constant fold each scalar lane separately.
  4259. SmallVector<SDValue, 4> ScalarResults;
  4260. for (unsigned i = 0; i != NumElts; i++) {
  4261. SmallVector<SDValue, 4> ScalarOps;
  4262. for (SDValue Op : Ops) {
  4263. EVT InSVT = Op.getValueType().getScalarType();
  4264. BuildVectorSDNode *InBV = dyn_cast<BuildVectorSDNode>(Op);
  4265. if (!InBV) {
  4266. // We've checked that this is UNDEF or a constant of some kind.
  4267. if (Op.isUndef())
  4268. ScalarOps.push_back(getUNDEF(InSVT));
  4269. else
  4270. ScalarOps.push_back(Op);
  4271. continue;
  4272. }
  4273. SDValue ScalarOp = InBV->getOperand(i);
  4274. EVT ScalarVT = ScalarOp.getValueType();
  4275. // Build vector (integer) scalar operands may need implicit
  4276. // truncation - do this before constant folding.
  4277. if (ScalarVT.isInteger() && ScalarVT.bitsGT(InSVT))
  4278. ScalarOp = getNode(ISD::TRUNCATE, DL, InSVT, ScalarOp);
  4279. ScalarOps.push_back(ScalarOp);
  4280. }
  4281. // Constant fold the scalar operands.
  4282. SDValue ScalarResult = getNode(Opcode, DL, SVT, ScalarOps, Flags);
  4283. // Legalize the (integer) scalar constant if necessary.
  4284. if (LegalSVT != SVT)
  4285. ScalarResult = getNode(ISD::SIGN_EXTEND, DL, LegalSVT, ScalarResult);
  4286. // Scalar folding only succeeded if the result is a constant or UNDEF.
  4287. if (!ScalarResult.isUndef() && ScalarResult.getOpcode() != ISD::Constant &&
  4288. ScalarResult.getOpcode() != ISD::ConstantFP)
  4289. return SDValue();
  4290. ScalarResults.push_back(ScalarResult);
  4291. }
  4292. SDValue V = getBuildVector(VT, DL, ScalarResults);
  4293. NewSDValueDbgMsg(V, "New node fold constant vector: ", this);
  4294. return V;
  4295. }
  4296. SDValue SelectionDAG::foldConstantFPMath(unsigned Opcode, const SDLoc &DL,
  4297. EVT VT, SDValue N1, SDValue N2) {
  4298. auto *N1CFP = dyn_cast<ConstantFPSDNode>(N1.getNode());
  4299. auto *N2CFP = dyn_cast<ConstantFPSDNode>(N2.getNode());
  4300. bool HasFPExceptions = TLI->hasFloatingPointExceptions();
  4301. if (N1CFP && N2CFP) {
  4302. APFloat C1 = N1CFP->getValueAPF(), C2 = N2CFP->getValueAPF();
  4303. APFloat::opStatus Status;
  4304. switch (Opcode) {
  4305. case ISD::FADD:
  4306. Status = C1.add(C2, APFloat::rmNearestTiesToEven);
  4307. if (!HasFPExceptions || Status != APFloat::opInvalidOp)
  4308. return getConstantFP(C1, DL, VT);
  4309. break;
  4310. case ISD::FSUB:
  4311. Status = C1.subtract(C2, APFloat::rmNearestTiesToEven);
  4312. if (!HasFPExceptions || Status != APFloat::opInvalidOp)
  4313. return getConstantFP(C1, DL, VT);
  4314. break;
  4315. case ISD::FMUL:
  4316. Status = C1.multiply(C2, APFloat::rmNearestTiesToEven);
  4317. if (!HasFPExceptions || Status != APFloat::opInvalidOp)
  4318. return getConstantFP(C1, DL, VT);
  4319. break;
  4320. case ISD::FDIV:
  4321. Status = C1.divide(C2, APFloat::rmNearestTiesToEven);
  4322. if (!HasFPExceptions || (Status != APFloat::opInvalidOp &&
  4323. Status != APFloat::opDivByZero)) {
  4324. return getConstantFP(C1, DL, VT);
  4325. }
  4326. break;
  4327. case ISD::FREM:
  4328. Status = C1.mod(C2);
  4329. if (!HasFPExceptions || (Status != APFloat::opInvalidOp &&
  4330. Status != APFloat::opDivByZero)) {
  4331. return getConstantFP(C1, DL, VT);
  4332. }
  4333. break;
  4334. case ISD::FCOPYSIGN:
  4335. C1.copySign(C2);
  4336. return getConstantFP(C1, DL, VT);
  4337. default: break;
  4338. }
  4339. }
  4340. if (N1CFP && Opcode == ISD::FP_ROUND) {
  4341. APFloat C1 = N1CFP->getValueAPF(); // make copy
  4342. bool Unused;
  4343. // This can return overflow, underflow, or inexact; we don't care.
  4344. // FIXME need to be more flexible about rounding mode.
  4345. (void) C1.convert(EVTToAPFloatSemantics(VT), APFloat::rmNearestTiesToEven,
  4346. &Unused);
  4347. return getConstantFP(C1, DL, VT);
  4348. }
  4349. switch (Opcode) {
  4350. case ISD::FADD:
  4351. case ISD::FSUB:
  4352. case ISD::FMUL:
  4353. case ISD::FDIV:
  4354. case ISD::FREM:
  4355. // If both operands are undef, the result is undef. If 1 operand is undef,
  4356. // the result is NaN. This should match the behavior of the IR optimizer.
  4357. if (N1.isUndef() && N2.isUndef())
  4358. return getUNDEF(VT);
  4359. if (N1.isUndef() || N2.isUndef())
  4360. return getConstantFP(APFloat::getNaN(EVTToAPFloatSemantics(VT)), DL, VT);
  4361. }
  4362. return SDValue();
  4363. }
  4364. SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
  4365. SDValue N1, SDValue N2, const SDNodeFlags Flags) {
  4366. ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
  4367. ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
  4368. ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
  4369. ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2);
  4370. // Canonicalize constant to RHS if commutative.
  4371. if (TLI->isCommutativeBinOp(Opcode)) {
  4372. if (N1C && !N2C) {
  4373. std::swap(N1C, N2C);
  4374. std::swap(N1, N2);
  4375. } else if (N1CFP && !N2CFP) {
  4376. std::swap(N1CFP, N2CFP);
  4377. std::swap(N1, N2);
  4378. }
  4379. }
  4380. switch (Opcode) {
  4381. default: break;
  4382. case ISD::TokenFactor:
  4383. assert(VT == MVT::Other && N1.getValueType() == MVT::Other &&
  4384. N2.getValueType() == MVT::Other && "Invalid token factor!");
  4385. // Fold trivial token factors.
  4386. if (N1.getOpcode() == ISD::EntryToken) return N2;
  4387. if (N2.getOpcode() == ISD::EntryToken) return N1;
  4388. if (N1 == N2) return N1;
  4389. break;
  4390. case ISD::BUILD_VECTOR: {
  4391. // Attempt to simplify BUILD_VECTOR.
  4392. SDValue Ops[] = {N1, N2};
  4393. if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
  4394. return V;
  4395. break;
  4396. }
  4397. case ISD::CONCAT_VECTORS: {
  4398. // Attempt to fold CONCAT_VECTORS into BUILD_VECTOR or UNDEF.
  4399. SDValue Ops[] = {N1, N2};
  4400. if (SDValue V = FoldCONCAT_VECTORS(DL, VT, Ops, *this))
  4401. return V;
  4402. break;
  4403. }
  4404. case ISD::AND:
  4405. assert(VT.isInteger() && "This operator does not apply to FP types!");
  4406. assert(N1.getValueType() == N2.getValueType() &&
  4407. N1.getValueType() == VT && "Binary operator types must match!");
  4408. // (X & 0) -> 0. This commonly occurs when legalizing i64 values, so it's
  4409. // worth handling here.
  4410. if (N2C && N2C->isNullValue())
  4411. return N2;
  4412. if (N2C && N2C->isAllOnesValue()) // X & -1 -> X
  4413. return N1;
  4414. break;
  4415. case ISD::OR:
  4416. case ISD::XOR:
  4417. case ISD::ADD:
  4418. case ISD::SUB:
  4419. assert(VT.isInteger() && "This operator does not apply to FP types!");
  4420. assert(N1.getValueType() == N2.getValueType() &&
  4421. N1.getValueType() == VT && "Binary operator types must match!");
  4422. // (X ^|+- 0) -> X. This commonly occurs when legalizing i64 values, so
  4423. // it's worth handling here.
  4424. if (N2C && N2C->isNullValue())
  4425. return N1;
  4426. break;
  4427. case ISD::UDIV:
  4428. case ISD::UREM:
  4429. case ISD::MULHU:
  4430. case ISD::MULHS:
  4431. case ISD::MUL:
  4432. case ISD::SDIV:
  4433. case ISD::SREM:
  4434. case ISD::SMIN:
  4435. case ISD::SMAX:
  4436. case ISD::UMIN:
  4437. case ISD::UMAX:
  4438. case ISD::SADDSAT:
  4439. case ISD::SSUBSAT:
  4440. case ISD::UADDSAT:
  4441. case ISD::USUBSAT:
  4442. assert(VT.isInteger() && "This operator does not apply to FP types!");
  4443. assert(N1.getValueType() == N2.getValueType() &&
  4444. N1.getValueType() == VT && "Binary operator types must match!");
  4445. break;
  4446. case ISD::FADD:
  4447. case ISD::FSUB:
  4448. case ISD::FMUL:
  4449. case ISD::FDIV:
  4450. case ISD::FREM:
  4451. assert(VT.isFloatingPoint() && "This operator only applies to FP types!");
  4452. assert(N1.getValueType() == N2.getValueType() &&
  4453. N1.getValueType() == VT && "Binary operator types must match!");
  4454. if (SDValue V = simplifyFPBinop(Opcode, N1, N2))
  4455. return V;
  4456. break;
  4457. case ISD::FCOPYSIGN: // N1 and result must match. N1/N2 need not match.
  4458. assert(N1.getValueType() == VT &&
  4459. N1.getValueType().isFloatingPoint() &&
  4460. N2.getValueType().isFloatingPoint() &&
  4461. "Invalid FCOPYSIGN!");
  4462. break;
  4463. case ISD::SHL:
  4464. case ISD::SRA:
  4465. case ISD::SRL:
  4466. if (SDValue V = simplifyShift(N1, N2))
  4467. return V;
  4468. LLVM_FALLTHROUGH;
  4469. case ISD::ROTL:
  4470. case ISD::ROTR:
  4471. assert(VT == N1.getValueType() &&
  4472. "Shift operators return type must be the same as their first arg");
  4473. assert(VT.isInteger() && N2.getValueType().isInteger() &&
  4474. "Shifts only work on integers");
  4475. assert((!VT.isVector() || VT == N2.getValueType()) &&
  4476. "Vector shift amounts must be in the same as their first arg");
  4477. // Verify that the shift amount VT is big enough to hold valid shift
  4478. // amounts. This catches things like trying to shift an i1024 value by an
  4479. // i8, which is easy to fall into in generic code that uses
  4480. // TLI.getShiftAmount().
  4481. assert(N2.getValueSizeInBits() >= Log2_32_Ceil(N1.getValueSizeInBits()) &&
  4482. "Invalid use of small shift amount with oversized value!");
  4483. // Always fold shifts of i1 values so the code generator doesn't need to
  4484. // handle them. Since we know the size of the shift has to be less than the
  4485. // size of the value, the shift/rotate count is guaranteed to be zero.
  4486. if (VT == MVT::i1)
  4487. return N1;
  4488. if (N2C && N2C->isNullValue())
  4489. return N1;
  4490. break;
  4491. case ISD::FP_ROUND_INREG: {
  4492. EVT EVT = cast<VTSDNode>(N2)->getVT();
  4493. assert(VT == N1.getValueType() && "Not an inreg round!");
  4494. assert(VT.isFloatingPoint() && EVT.isFloatingPoint() &&
  4495. "Cannot FP_ROUND_INREG integer types");
  4496. assert(EVT.isVector() == VT.isVector() &&
  4497. "FP_ROUND_INREG type should be vector iff the operand "
  4498. "type is vector!");
  4499. assert((!EVT.isVector() ||
  4500. EVT.getVectorNumElements() == VT.getVectorNumElements()) &&
  4501. "Vector element counts must match in FP_ROUND_INREG");
  4502. assert(EVT.bitsLE(VT) && "Not rounding down!");
  4503. (void)EVT;
  4504. if (cast<VTSDNode>(N2)->getVT() == VT) return N1; // Not actually rounding.
  4505. break;
  4506. }
  4507. case ISD::FP_ROUND:
  4508. assert(VT.isFloatingPoint() &&
  4509. N1.getValueType().isFloatingPoint() &&
  4510. VT.bitsLE(N1.getValueType()) &&
  4511. N2C && (N2C->getZExtValue() == 0 || N2C->getZExtValue() == 1) &&
  4512. "Invalid FP_ROUND!");
  4513. if (N1.getValueType() == VT) return N1; // noop conversion.
  4514. break;
  4515. case ISD::AssertSext:
  4516. case ISD::AssertZext: {
  4517. EVT EVT = cast<VTSDNode>(N2)->getVT();
  4518. assert(VT == N1.getValueType() && "Not an inreg extend!");
  4519. assert(VT.isInteger() && EVT.isInteger() &&
  4520. "Cannot *_EXTEND_INREG FP types");
  4521. assert(!EVT.isVector() &&
  4522. "AssertSExt/AssertZExt type should be the vector element type "
  4523. "rather than the vector type!");
  4524. assert(EVT.bitsLE(VT.getScalarType()) && "Not extending!");
  4525. if (VT.getScalarType() == EVT) return N1; // noop assertion.
  4526. break;
  4527. }
  4528. case ISD::SIGN_EXTEND_INREG: {
  4529. EVT EVT = cast<VTSDNode>(N2)->getVT();
  4530. assert(VT == N1.getValueType() && "Not an inreg extend!");
  4531. assert(VT.isInteger() && EVT.isInteger() &&
  4532. "Cannot *_EXTEND_INREG FP types");
  4533. assert(EVT.isVector() == VT.isVector() &&
  4534. "SIGN_EXTEND_INREG type should be vector iff the operand "
  4535. "type is vector!");
  4536. assert((!EVT.isVector() ||
  4537. EVT.getVectorNumElements() == VT.getVectorNumElements()) &&
  4538. "Vector element counts must match in SIGN_EXTEND_INREG");
  4539. assert(EVT.bitsLE(VT) && "Not extending!");
  4540. if (EVT == VT) return N1; // Not actually extending
  4541. auto SignExtendInReg = [&](APInt Val, llvm::EVT ConstantVT) {
  4542. unsigned FromBits = EVT.getScalarSizeInBits();
  4543. Val <<= Val.getBitWidth() - FromBits;
  4544. Val.ashrInPlace(Val.getBitWidth() - FromBits);
  4545. return getConstant(Val, DL, ConstantVT);
  4546. };
  4547. if (N1C) {
  4548. const APInt &Val = N1C->getAPIntValue();
  4549. return SignExtendInReg(Val, VT);
  4550. }
  4551. if (ISD::isBuildVectorOfConstantSDNodes(N1.getNode())) {
  4552. SmallVector<SDValue, 8> Ops;
  4553. llvm::EVT OpVT = N1.getOperand(0).getValueType();
  4554. for (int i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
  4555. SDValue Op = N1.getOperand(i);
  4556. if (Op.isUndef()) {
  4557. Ops.push_back(getUNDEF(OpVT));
  4558. continue;
  4559. }
  4560. ConstantSDNode *C = cast<ConstantSDNode>(Op);
  4561. APInt Val = C->getAPIntValue();
  4562. Ops.push_back(SignExtendInReg(Val, OpVT));
  4563. }
  4564. return getBuildVector(VT, DL, Ops);
  4565. }
  4566. break;
  4567. }
  4568. case ISD::EXTRACT_VECTOR_ELT:
  4569. assert(VT.getSizeInBits() >= N1.getValueType().getScalarSizeInBits() &&
  4570. "The result of EXTRACT_VECTOR_ELT must be at least as wide as the \
  4571. element type of the vector.");
  4572. // EXTRACT_VECTOR_ELT of an UNDEF is an UNDEF.
  4573. if (N1.isUndef())
  4574. return getUNDEF(VT);
  4575. // EXTRACT_VECTOR_ELT of out-of-bounds element is an UNDEF
  4576. if (N2C && N2C->getAPIntValue().uge(N1.getValueType().getVectorNumElements()))
  4577. return getUNDEF(VT);
  4578. // EXTRACT_VECTOR_ELT of CONCAT_VECTORS is often formed while lowering is
  4579. // expanding copies of large vectors from registers.
  4580. if (N2C &&
  4581. N1.getOpcode() == ISD::CONCAT_VECTORS &&
  4582. N1.getNumOperands() > 0) {
  4583. unsigned Factor =
  4584. N1.getOperand(0).getValueType().getVectorNumElements();
  4585. return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
  4586. N1.getOperand(N2C->getZExtValue() / Factor),
  4587. getConstant(N2C->getZExtValue() % Factor, DL,
  4588. N2.getValueType()));
  4589. }
  4590. // EXTRACT_VECTOR_ELT of BUILD_VECTOR is often formed while lowering is
  4591. // expanding large vector constants.
  4592. if (N2C && N1.getOpcode() == ISD::BUILD_VECTOR) {
  4593. SDValue Elt = N1.getOperand(N2C->getZExtValue());
  4594. if (VT != Elt.getValueType())
  4595. // If the vector element type is not legal, the BUILD_VECTOR operands
  4596. // are promoted and implicitly truncated, and the result implicitly
  4597. // extended. Make that explicit here.
  4598. Elt = getAnyExtOrTrunc(Elt, DL, VT);
  4599. return Elt;
  4600. }
  4601. // EXTRACT_VECTOR_ELT of INSERT_VECTOR_ELT is often formed when vector
  4602. // operations are lowered to scalars.
  4603. if (N1.getOpcode() == ISD::INSERT_VECTOR_ELT) {
  4604. // If the indices are the same, return the inserted element else
  4605. // if the indices are known different, extract the element from
  4606. // the original vector.
  4607. SDValue N1Op2 = N1.getOperand(2);
  4608. ConstantSDNode *N1Op2C = dyn_cast<ConstantSDNode>(N1Op2);
  4609. if (N1Op2C && N2C) {
  4610. if (N1Op2C->getZExtValue() == N2C->getZExtValue()) {
  4611. if (VT == N1.getOperand(1).getValueType())
  4612. return N1.getOperand(1);
  4613. else
  4614. return getSExtOrTrunc(N1.getOperand(1), DL, VT);
  4615. }
  4616. return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0), N2);
  4617. }
  4618. }
  4619. // EXTRACT_VECTOR_ELT of v1iX EXTRACT_SUBVECTOR could be formed
  4620. // when vector types are scalarized and v1iX is legal.
  4621. // vextract (v1iX extract_subvector(vNiX, Idx)) -> vextract(vNiX,Idx)
  4622. if (N1.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
  4623. N1.getValueType().getVectorNumElements() == 1) {
  4624. return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0),
  4625. N1.getOperand(1));
  4626. }
  4627. break;
  4628. case ISD::EXTRACT_ELEMENT:
  4629. assert(N2C && (unsigned)N2C->getZExtValue() < 2 && "Bad EXTRACT_ELEMENT!");
  4630. assert(!N1.getValueType().isVector() && !VT.isVector() &&
  4631. (N1.getValueType().isInteger() == VT.isInteger()) &&
  4632. N1.getValueType() != VT &&
  4633. "Wrong types for EXTRACT_ELEMENT!");
  4634. // EXTRACT_ELEMENT of BUILD_PAIR is often formed while legalize is expanding
  4635. // 64-bit integers into 32-bit parts. Instead of building the extract of
  4636. // the BUILD_PAIR, only to have legalize rip it apart, just do it now.
  4637. if (N1.getOpcode() == ISD::BUILD_PAIR)
  4638. return N1.getOperand(N2C->getZExtValue());
  4639. // EXTRACT_ELEMENT of a constant int is also very common.
  4640. if (N1C) {
  4641. unsigned ElementSize = VT.getSizeInBits();
  4642. unsigned Shift = ElementSize * N2C->getZExtValue();
  4643. APInt ShiftedVal = N1C->getAPIntValue().lshr(Shift);
  4644. return getConstant(ShiftedVal.trunc(ElementSize), DL, VT);
  4645. }
  4646. break;
  4647. case ISD::EXTRACT_SUBVECTOR:
  4648. if (VT.isSimple() && N1.getValueType().isSimple()) {
  4649. assert(VT.isVector() && N1.getValueType().isVector() &&
  4650. "Extract subvector VTs must be a vectors!");
  4651. assert(VT.getVectorElementType() ==
  4652. N1.getValueType().getVectorElementType() &&
  4653. "Extract subvector VTs must have the same element type!");
  4654. assert(VT.getSimpleVT() <= N1.getSimpleValueType() &&
  4655. "Extract subvector must be from larger vector to smaller vector!");
  4656. if (N2C) {
  4657. assert((VT.getVectorNumElements() + N2C->getZExtValue()
  4658. <= N1.getValueType().getVectorNumElements())
  4659. && "Extract subvector overflow!");
  4660. }
  4661. // Trivial extraction.
  4662. if (VT.getSimpleVT() == N1.getSimpleValueType())
  4663. return N1;
  4664. // EXTRACT_SUBVECTOR of an UNDEF is an UNDEF.
  4665. if (N1.isUndef())
  4666. return getUNDEF(VT);
  4667. // EXTRACT_SUBVECTOR of CONCAT_VECTOR can be simplified if the pieces of
  4668. // the concat have the same type as the extract.
  4669. if (N2C && N1.getOpcode() == ISD::CONCAT_VECTORS &&
  4670. N1.getNumOperands() > 0 &&
  4671. VT == N1.getOperand(0).getValueType()) {
  4672. unsigned Factor = VT.getVectorNumElements();
  4673. return N1.getOperand(N2C->getZExtValue() / Factor);
  4674. }
  4675. // EXTRACT_SUBVECTOR of INSERT_SUBVECTOR is often created
  4676. // during shuffle legalization.
  4677. if (N1.getOpcode() == ISD::INSERT_SUBVECTOR && N2 == N1.getOperand(2) &&
  4678. VT == N1.getOperand(1).getValueType())
  4679. return N1.getOperand(1);
  4680. }
  4681. break;
  4682. }
  4683. // Perform trivial constant folding.
  4684. if (SDValue SV =
  4685. FoldConstantArithmetic(Opcode, DL, VT, N1.getNode(), N2.getNode()))
  4686. return SV;
  4687. if (SDValue V = foldConstantFPMath(Opcode, DL, VT, N1, N2))
  4688. return V;
  4689. // Canonicalize an UNDEF to the RHS, even over a constant.
  4690. if (N1.isUndef()) {
  4691. if (TLI->isCommutativeBinOp(Opcode)) {
  4692. std::swap(N1, N2);
  4693. } else {
  4694. switch (Opcode) {
  4695. case ISD::FP_ROUND_INREG:
  4696. case ISD::SIGN_EXTEND_INREG:
  4697. case ISD::SUB:
  4698. return getUNDEF(VT); // fold op(undef, arg2) -> undef
  4699. case ISD::UDIV:
  4700. case ISD::SDIV:
  4701. case ISD::UREM:
  4702. case ISD::SREM:
  4703. case ISD::SSUBSAT:
  4704. case ISD::USUBSAT:
  4705. return getConstant(0, DL, VT); // fold op(undef, arg2) -> 0
  4706. }
  4707. }
  4708. }
  4709. // Fold a bunch of operators when the RHS is undef.
  4710. if (N2.isUndef()) {
  4711. switch (Opcode) {
  4712. case ISD::XOR:
  4713. if (N1.isUndef())
  4714. // Handle undef ^ undef -> 0 special case. This is a common
  4715. // idiom (misuse).
  4716. return getConstant(0, DL, VT);
  4717. LLVM_FALLTHROUGH;
  4718. case ISD::ADD:
  4719. case ISD::SUB:
  4720. case ISD::UDIV:
  4721. case ISD::SDIV:
  4722. case ISD::UREM:
  4723. case ISD::SREM:
  4724. return getUNDEF(VT); // fold op(arg1, undef) -> undef
  4725. case ISD::MUL:
  4726. case ISD::AND:
  4727. case ISD::SSUBSAT:
  4728. case ISD::USUBSAT:
  4729. return getConstant(0, DL, VT); // fold op(arg1, undef) -> 0
  4730. case ISD::OR:
  4731. case ISD::SADDSAT:
  4732. case ISD::UADDSAT:
  4733. return getAllOnesConstant(DL, VT);
  4734. }
  4735. }
  4736. // Memoize this node if possible.
  4737. SDNode *N;
  4738. SDVTList VTs = getVTList(VT);
  4739. SDValue Ops[] = {N1, N2};
  4740. if (VT != MVT::Glue) {
  4741. FoldingSetNodeID ID;
  4742. AddNodeIDNode(ID, Opcode, VTs, Ops);
  4743. void *IP = nullptr;
  4744. if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
  4745. E->intersectFlagsWith(Flags);
  4746. return SDValue(E, 0);
  4747. }
  4748. N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
  4749. N->setFlags(Flags);
  4750. createOperands(N, Ops);
  4751. CSEMap.InsertNode(N, IP);
  4752. } else {
  4753. N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
  4754. createOperands(N, Ops);
  4755. }
  4756. InsertNode(N);
  4757. SDValue V = SDValue(N, 0);
  4758. NewSDValueDbgMsg(V, "Creating new node: ", this);
  4759. return V;
  4760. }
  4761. SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
  4762. SDValue N1, SDValue N2, SDValue N3,
  4763. const SDNodeFlags Flags) {
  4764. // Perform various simplifications.
  4765. switch (Opcode) {
  4766. case ISD::FMA: {
  4767. assert(VT.isFloatingPoint() && "This operator only applies to FP types!");
  4768. assert(N1.getValueType() == VT && N2.getValueType() == VT &&
  4769. N3.getValueType() == VT && "FMA types must match!");
  4770. ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
  4771. ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2);
  4772. ConstantFPSDNode *N3CFP = dyn_cast<ConstantFPSDNode>(N3);
  4773. if (N1CFP && N2CFP && N3CFP) {
  4774. APFloat V1 = N1CFP->getValueAPF();
  4775. const APFloat &V2 = N2CFP->getValueAPF();
  4776. const APFloat &V3 = N3CFP->getValueAPF();
  4777. APFloat::opStatus s =
  4778. V1.fusedMultiplyAdd(V2, V3, APFloat::rmNearestTiesToEven);
  4779. if (!TLI->hasFloatingPointExceptions() || s != APFloat::opInvalidOp)
  4780. return getConstantFP(V1, DL, VT);
  4781. }
  4782. break;
  4783. }
  4784. case ISD::BUILD_VECTOR: {
  4785. // Attempt to simplify BUILD_VECTOR.
  4786. SDValue Ops[] = {N1, N2, N3};
  4787. if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
  4788. return V;
  4789. break;
  4790. }
  4791. case ISD::CONCAT_VECTORS: {
  4792. // Attempt to fold CONCAT_VECTORS into BUILD_VECTOR or UNDEF.
  4793. SDValue Ops[] = {N1, N2, N3};
  4794. if (SDValue V = FoldCONCAT_VECTORS(DL, VT, Ops, *this))
  4795. return V;
  4796. break;
  4797. }
  4798. case ISD::SETCC: {
  4799. assert(VT.isInteger() && "SETCC result type must be an integer!");
  4800. assert(N1.getValueType() == N2.getValueType() &&
  4801. "SETCC operands must have the same type!");
  4802. assert(VT.isVector() == N1.getValueType().isVector() &&
  4803. "SETCC type should be vector iff the operand type is vector!");
  4804. assert((!VT.isVector() ||
  4805. VT.getVectorNumElements() == N1.getValueType().getVectorNumElements()) &&
  4806. "SETCC vector element counts must match!");
  4807. // Use FoldSetCC to simplify SETCC's.
  4808. if (SDValue V = FoldSetCC(VT, N1, N2, cast<CondCodeSDNode>(N3)->get(), DL))
  4809. return V;
  4810. // Vector constant folding.
  4811. SDValue Ops[] = {N1, N2, N3};
  4812. if (SDValue V = FoldConstantVectorArithmetic(Opcode, DL, VT, Ops)) {
  4813. NewSDValueDbgMsg(V, "New node vector constant folding: ", this);
  4814. return V;
  4815. }
  4816. break;
  4817. }
  4818. case ISD::SELECT:
  4819. case ISD::VSELECT:
  4820. if (SDValue V = simplifySelect(N1, N2, N3))
  4821. return V;
  4822. break;
  4823. case ISD::VECTOR_SHUFFLE:
  4824. llvm_unreachable("should use getVectorShuffle constructor!");
  4825. case ISD::INSERT_VECTOR_ELT: {
  4826. ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3);
  4827. // INSERT_VECTOR_ELT into out-of-bounds element is an UNDEF
  4828. if (N3C && N3C->getZExtValue() >= N1.getValueType().getVectorNumElements())
  4829. return getUNDEF(VT);
  4830. break;
  4831. }
  4832. case ISD::INSERT_SUBVECTOR: {
  4833. SDValue Index = N3;
  4834. if (VT.isSimple() && N1.getValueType().isSimple()
  4835. && N2.getValueType().isSimple()) {
  4836. assert(VT.isVector() && N1.getValueType().isVector() &&
  4837. N2.getValueType().isVector() &&
  4838. "Insert subvector VTs must be a vectors");
  4839. assert(VT == N1.getValueType() &&
  4840. "Dest and insert subvector source types must match!");
  4841. assert(N2.getSimpleValueType() <= N1.getSimpleValueType() &&
  4842. "Insert subvector must be from smaller vector to larger vector!");
  4843. if (isa<ConstantSDNode>(Index)) {
  4844. assert((N2.getValueType().getVectorNumElements() +
  4845. cast<ConstantSDNode>(Index)->getZExtValue()
  4846. <= VT.getVectorNumElements())
  4847. && "Insert subvector overflow!");
  4848. }
  4849. // Trivial insertion.
  4850. if (VT.getSimpleVT() == N2.getSimpleValueType())
  4851. return N2;
  4852. }
  4853. break;
  4854. }
  4855. case ISD::BITCAST:
  4856. // Fold bit_convert nodes from a type to themselves.
  4857. if (N1.getValueType() == VT)
  4858. return N1;
  4859. break;
  4860. }
  4861. // Memoize node if it doesn't produce a flag.
  4862. SDNode *N;
  4863. SDVTList VTs = getVTList(VT);
  4864. SDValue Ops[] = {N1, N2, N3};
  4865. if (VT != MVT::Glue) {
  4866. FoldingSetNodeID ID;
  4867. AddNodeIDNode(ID, Opcode, VTs, Ops);
  4868. void *IP = nullptr;
  4869. if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
  4870. E->intersectFlagsWith(Flags);
  4871. return SDValue(E, 0);
  4872. }
  4873. N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
  4874. N->setFlags(Flags);
  4875. createOperands(N, Ops);
  4876. CSEMap.InsertNode(N, IP);
  4877. } else {
  4878. N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
  4879. createOperands(N, Ops);
  4880. }
  4881. InsertNode(N);
  4882. SDValue V = SDValue(N, 0);
  4883. NewSDValueDbgMsg(V, "Creating new node: ", this);
  4884. return V;
  4885. }
  4886. SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
  4887. SDValue N1, SDValue N2, SDValue N3, SDValue N4) {
  4888. SDValue Ops[] = { N1, N2, N3, N4 };
  4889. return getNode(Opcode, DL, VT, Ops);
  4890. }
  4891. SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
  4892. SDValue N1, SDValue N2, SDValue N3, SDValue N4,
  4893. SDValue N5) {
  4894. SDValue Ops[] = { N1, N2, N3, N4, N5 };
  4895. return getNode(Opcode, DL, VT, Ops);
  4896. }
  4897. /// getStackArgumentTokenFactor - Compute a TokenFactor to force all
  4898. /// the incoming stack arguments to be loaded from the stack.
  4899. SDValue SelectionDAG::getStackArgumentTokenFactor(SDValue Chain) {
  4900. SmallVector<SDValue, 8> ArgChains;
  4901. // Include the original chain at the beginning of the list. When this is
  4902. // used by target LowerCall hooks, this helps legalize find the
  4903. // CALLSEQ_BEGIN node.
  4904. ArgChains.push_back(Chain);
  4905. // Add a chain value for each stack argument.
  4906. for (SDNode::use_iterator U = getEntryNode().getNode()->use_begin(),
  4907. UE = getEntryNode().getNode()->use_end(); U != UE; ++U)
  4908. if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U))
  4909. if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
  4910. if (FI->getIndex() < 0)
  4911. ArgChains.push_back(SDValue(L, 1));
  4912. // Build a tokenfactor for all the chains.
  4913. return getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
  4914. }
  4915. /// getMemsetValue - Vectorized representation of the memset value
  4916. /// operand.
  4917. static SDValue getMemsetValue(SDValue Value, EVT VT, SelectionDAG &DAG,
  4918. const SDLoc &dl) {
  4919. assert(!Value.isUndef());
  4920. unsigned NumBits = VT.getScalarSizeInBits();
  4921. if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
  4922. assert(C->getAPIntValue().getBitWidth() == 8);
  4923. APInt Val = APInt::getSplat(NumBits, C->getAPIntValue());
  4924. if (VT.isInteger()) {
  4925. bool IsOpaque = VT.getSizeInBits() > 64 ||
  4926. !DAG.getTargetLoweringInfo().isLegalStoreImmediate(C->getSExtValue());
  4927. return DAG.getConstant(Val, dl, VT, false, IsOpaque);
  4928. }
  4929. return DAG.getConstantFP(APFloat(DAG.EVTToAPFloatSemantics(VT), Val), dl,
  4930. VT);
  4931. }
  4932. assert(Value.getValueType() == MVT::i8 && "memset with non-byte fill value?");
  4933. EVT IntVT = VT.getScalarType();
  4934. if (!IntVT.isInteger())
  4935. IntVT = EVT::getIntegerVT(*DAG.getContext(), IntVT.getSizeInBits());
  4936. Value = DAG.getNode(ISD::ZERO_EXTEND, dl, IntVT, Value);
  4937. if (NumBits > 8) {
  4938. // Use a multiplication with 0x010101... to extend the input to the
  4939. // required length.
  4940. APInt Magic = APInt::getSplat(NumBits, APInt(8, 0x01));
  4941. Value = DAG.getNode(ISD::MUL, dl, IntVT, Value,
  4942. DAG.getConstant(Magic, dl, IntVT));
  4943. }
  4944. if (VT != Value.getValueType() && !VT.isInteger())
  4945. Value = DAG.getBitcast(VT.getScalarType(), Value);
  4946. if (VT != Value.getValueType())
  4947. Value = DAG.getSplatBuildVector(VT, dl, Value);
  4948. return Value;
  4949. }
  4950. /// getMemsetStringVal - Similar to getMemsetValue. Except this is only
  4951. /// used when a memcpy is turned into a memset when the source is a constant
  4952. /// string ptr.
  4953. static SDValue getMemsetStringVal(EVT VT, const SDLoc &dl, SelectionDAG &DAG,
  4954. const TargetLowering &TLI,
  4955. const ConstantDataArraySlice &Slice) {
  4956. // Handle vector with all elements zero.
  4957. if (Slice.Array == nullptr) {
  4958. if (VT.isInteger())
  4959. return DAG.getConstant(0, dl, VT);
  4960. else if (VT == MVT::f32 || VT == MVT::f64 || VT == MVT::f128)
  4961. return DAG.getConstantFP(0.0, dl, VT);
  4962. else if (VT.isVector()) {
  4963. unsigned NumElts = VT.getVectorNumElements();
  4964. MVT EltVT = (VT.getVectorElementType() == MVT::f32) ? MVT::i32 : MVT::i64;
  4965. return DAG.getNode(ISD::BITCAST, dl, VT,
  4966. DAG.getConstant(0, dl,
  4967. EVT::getVectorVT(*DAG.getContext(),
  4968. EltVT, NumElts)));
  4969. } else
  4970. llvm_unreachable("Expected type!");
  4971. }
  4972. assert(!VT.isVector() && "Can't handle vector type here!");
  4973. unsigned NumVTBits = VT.getSizeInBits();
  4974. unsigned NumVTBytes = NumVTBits / 8;
  4975. unsigned NumBytes = std::min(NumVTBytes, unsigned(Slice.Length));
  4976. APInt Val(NumVTBits, 0);
  4977. if (DAG.getDataLayout().isLittleEndian()) {
  4978. for (unsigned i = 0; i != NumBytes; ++i)
  4979. Val |= (uint64_t)(unsigned char)Slice[i] << i*8;
  4980. } else {
  4981. for (unsigned i = 0; i != NumBytes; ++i)
  4982. Val |= (uint64_t)(unsigned char)Slice[i] << (NumVTBytes-i-1)*8;
  4983. }
  4984. // If the "cost" of materializing the integer immediate is less than the cost
  4985. // of a load, then it is cost effective to turn the load into the immediate.
  4986. Type *Ty = VT.getTypeForEVT(*DAG.getContext());
  4987. if (TLI.shouldConvertConstantLoadToIntImm(Val, Ty))
  4988. return DAG.getConstant(Val, dl, VT);
  4989. return SDValue(nullptr, 0);
  4990. }
  4991. SDValue SelectionDAG::getMemBasePlusOffset(SDValue Base, unsigned Offset,
  4992. const SDLoc &DL) {
  4993. EVT VT = Base.getValueType();
  4994. return getNode(ISD::ADD, DL, VT, Base, getConstant(Offset, DL, VT));
  4995. }
  4996. /// Returns true if memcpy source is constant data.
  4997. static bool isMemSrcFromConstant(SDValue Src, ConstantDataArraySlice &Slice) {
  4998. uint64_t SrcDelta = 0;
  4999. GlobalAddressSDNode *G = nullptr;
  5000. if (Src.getOpcode() == ISD::GlobalAddress)
  5001. G = cast<GlobalAddressSDNode>(Src);
  5002. else if (Src.getOpcode() == ISD::ADD &&
  5003. Src.getOperand(0).getOpcode() == ISD::GlobalAddress &&
  5004. Src.getOperand(1).getOpcode() == ISD::Constant) {
  5005. G = cast<GlobalAddressSDNode>(Src.getOperand(0));
  5006. SrcDelta = cast<ConstantSDNode>(Src.getOperand(1))->getZExtValue();
  5007. }
  5008. if (!G)
  5009. return false;
  5010. return getConstantDataArrayInfo(G->getGlobal(), Slice, 8,
  5011. SrcDelta + G->getOffset());
  5012. }
  5013. /// Determines the optimal series of memory ops to replace the memset / memcpy.
  5014. /// Return true if the number of memory ops is below the threshold (Limit).
  5015. /// It returns the types of the sequence of memory ops to perform
  5016. /// memset / memcpy by reference.
  5017. static bool FindOptimalMemOpLowering(std::vector<EVT> &MemOps,
  5018. unsigned Limit, uint64_t Size,
  5019. unsigned DstAlign, unsigned SrcAlign,
  5020. bool IsMemset,
  5021. bool ZeroMemset,
  5022. bool MemcpyStrSrc,
  5023. bool AllowOverlap,
  5024. unsigned DstAS, unsigned SrcAS,
  5025. SelectionDAG &DAG,
  5026. const TargetLowering &TLI) {
  5027. assert((SrcAlign == 0 || SrcAlign >= DstAlign) &&
  5028. "Expecting memcpy / memset source to meet alignment requirement!");
  5029. // If 'SrcAlign' is zero, that means the memory operation does not need to
  5030. // load the value, i.e. memset or memcpy from constant string. Otherwise,
  5031. // it's the inferred alignment of the source. 'DstAlign', on the other hand,
  5032. // is the specified alignment of the memory operation. If it is zero, that
  5033. // means it's possible to change the alignment of the destination.
  5034. // 'MemcpyStrSrc' indicates whether the memcpy source is constant so it does
  5035. // not need to be loaded.
  5036. EVT VT = TLI.getOptimalMemOpType(Size, DstAlign, SrcAlign,
  5037. IsMemset, ZeroMemset, MemcpyStrSrc,
  5038. DAG.getMachineFunction());
  5039. if (VT == MVT::Other) {
  5040. // Use the largest integer type whose alignment constraints are satisfied.
  5041. // We only need to check DstAlign here as SrcAlign is always greater or
  5042. // equal to DstAlign (or zero).
  5043. VT = MVT::i64;
  5044. while (DstAlign && DstAlign < VT.getSizeInBits() / 8 &&
  5045. !TLI.allowsMisalignedMemoryAccesses(VT, DstAS, DstAlign))
  5046. VT = (MVT::SimpleValueType)(VT.getSimpleVT().SimpleTy - 1);
  5047. assert(VT.isInteger());
  5048. // Find the largest legal integer type.
  5049. MVT LVT = MVT::i64;
  5050. while (!TLI.isTypeLegal(LVT))
  5051. LVT = (MVT::SimpleValueType)(LVT.SimpleTy - 1);
  5052. assert(LVT.isInteger());
  5053. // If the type we've chosen is larger than the largest legal integer type
  5054. // then use that instead.
  5055. if (VT.bitsGT(LVT))
  5056. VT = LVT;
  5057. }
  5058. unsigned NumMemOps = 0;
  5059. while (Size != 0) {
  5060. unsigned VTSize = VT.getSizeInBits() / 8;
  5061. while (VTSize > Size) {
  5062. // For now, only use non-vector load / store's for the left-over pieces.
  5063. EVT NewVT = VT;
  5064. unsigned NewVTSize;
  5065. bool Found = false;
  5066. if (VT.isVector() || VT.isFloatingPoint()) {
  5067. NewVT = (VT.getSizeInBits() > 64) ? MVT::i64 : MVT::i32;
  5068. if (TLI.isOperationLegalOrCustom(ISD::STORE, NewVT) &&
  5069. TLI.isSafeMemOpType(NewVT.getSimpleVT()))
  5070. Found = true;
  5071. else if (NewVT == MVT::i64 &&
  5072. TLI.isOperationLegalOrCustom(ISD::STORE, MVT::f64) &&
  5073. TLI.isSafeMemOpType(MVT::f64)) {
  5074. // i64 is usually not legal on 32-bit targets, but f64 may be.
  5075. NewVT = MVT::f64;
  5076. Found = true;
  5077. }
  5078. }
  5079. if (!Found) {
  5080. do {
  5081. NewVT = (MVT::SimpleValueType)(NewVT.getSimpleVT().SimpleTy - 1);
  5082. if (NewVT == MVT::i8)
  5083. break;
  5084. } while (!TLI.isSafeMemOpType(NewVT.getSimpleVT()));
  5085. }
  5086. NewVTSize = NewVT.getSizeInBits() / 8;
  5087. // If the new VT cannot cover all of the remaining bits, then consider
  5088. // issuing a (or a pair of) unaligned and overlapping load / store.
  5089. bool Fast;
  5090. if (NumMemOps && AllowOverlap && NewVTSize < Size &&
  5091. TLI.allowsMisalignedMemoryAccesses(VT, DstAS, DstAlign, &Fast) &&
  5092. Fast)
  5093. VTSize = Size;
  5094. else {
  5095. VT = NewVT;
  5096. VTSize = NewVTSize;
  5097. }
  5098. }
  5099. if (++NumMemOps > Limit)
  5100. return false;
  5101. MemOps.push_back(VT);
  5102. Size -= VTSize;
  5103. }
  5104. return true;
  5105. }
  5106. static bool shouldLowerMemFuncForSize(const MachineFunction &MF) {
  5107. // On Darwin, -Os means optimize for size without hurting performance, so
  5108. // only really optimize for size when -Oz (MinSize) is used.
  5109. if (MF.getTarget().getTargetTriple().isOSDarwin())
  5110. return MF.getFunction().hasMinSize();
  5111. return MF.getFunction().hasOptSize();
  5112. }
  5113. static void chainLoadsAndStoresForMemcpy(SelectionDAG &DAG, const SDLoc &dl,
  5114. SmallVector<SDValue, 32> &OutChains, unsigned From,
  5115. unsigned To, SmallVector<SDValue, 16> &OutLoadChains,
  5116. SmallVector<SDValue, 16> &OutStoreChains) {
  5117. assert(OutLoadChains.size() && "Missing loads in memcpy inlining");
  5118. assert(OutStoreChains.size() && "Missing stores in memcpy inlining");
  5119. SmallVector<SDValue, 16> GluedLoadChains;
  5120. for (unsigned i = From; i < To; ++i) {
  5121. OutChains.push_back(OutLoadChains[i]);
  5122. GluedLoadChains.push_back(OutLoadChains[i]);
  5123. }
  5124. // Chain for all loads.
  5125. SDValue LoadToken = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
  5126. GluedLoadChains);
  5127. for (unsigned i = From; i < To; ++i) {
  5128. StoreSDNode *ST = dyn_cast<StoreSDNode>(OutStoreChains[i]);
  5129. SDValue NewStore = DAG.getTruncStore(LoadToken, dl, ST->getValue(),
  5130. ST->getBasePtr(), ST->getMemoryVT(),
  5131. ST->getMemOperand());
  5132. OutChains.push_back(NewStore);
  5133. }
  5134. }
  5135. static SDValue getMemcpyLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl,
  5136. SDValue Chain, SDValue Dst, SDValue Src,
  5137. uint64_t Size, unsigned Align,
  5138. bool isVol, bool AlwaysInline,
  5139. MachinePointerInfo DstPtrInfo,
  5140. MachinePointerInfo SrcPtrInfo) {
  5141. // Turn a memcpy of undef to nop.
  5142. if (Src.isUndef())
  5143. return Chain;
  5144. // Expand memcpy to a series of load and store ops if the size operand falls
  5145. // below a certain threshold.
  5146. // TODO: In the AlwaysInline case, if the size is big then generate a loop
  5147. // rather than maybe a humongous number of loads and stores.
  5148. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  5149. const DataLayout &DL = DAG.getDataLayout();
  5150. LLVMContext &C = *DAG.getContext();
  5151. std::vector<EVT> MemOps;
  5152. bool DstAlignCanChange = false;
  5153. MachineFunction &MF = DAG.getMachineFunction();
  5154. MachineFrameInfo &MFI = MF.getFrameInfo();
  5155. bool OptSize = shouldLowerMemFuncForSize(MF);
  5156. FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
  5157. if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
  5158. DstAlignCanChange = true;
  5159. unsigned SrcAlign = DAG.InferPtrAlignment(Src);
  5160. if (Align > SrcAlign)
  5161. SrcAlign = Align;
  5162. ConstantDataArraySlice Slice;
  5163. bool CopyFromConstant = isMemSrcFromConstant(Src, Slice);
  5164. bool isZeroConstant = CopyFromConstant && Slice.Array == nullptr;
  5165. unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemcpy(OptSize);
  5166. if (!FindOptimalMemOpLowering(MemOps, Limit, Size,
  5167. (DstAlignCanChange ? 0 : Align),
  5168. (isZeroConstant ? 0 : SrcAlign),
  5169. false, false, CopyFromConstant, true,
  5170. DstPtrInfo.getAddrSpace(),
  5171. SrcPtrInfo.getAddrSpace(),
  5172. DAG, TLI))
  5173. return SDValue();
  5174. if (DstAlignCanChange) {
  5175. Type *Ty = MemOps[0].getTypeForEVT(C);
  5176. unsigned NewAlign = (unsigned)DL.getABITypeAlignment(Ty);
  5177. // Don't promote to an alignment that would require dynamic stack
  5178. // realignment.
  5179. const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
  5180. if (!TRI->needsStackRealignment(MF))
  5181. while (NewAlign > Align &&
  5182. DL.exceedsNaturalStackAlignment(NewAlign))
  5183. NewAlign /= 2;
  5184. if (NewAlign > Align) {
  5185. // Give the stack frame object a larger alignment if needed.
  5186. if (MFI.getObjectAlignment(FI->getIndex()) < NewAlign)
  5187. MFI.setObjectAlignment(FI->getIndex(), NewAlign);
  5188. Align = NewAlign;
  5189. }
  5190. }
  5191. MachineMemOperand::Flags MMOFlags =
  5192. isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone;
  5193. SmallVector<SDValue, 16> OutLoadChains;
  5194. SmallVector<SDValue, 16> OutStoreChains;
  5195. SmallVector<SDValue, 32> OutChains;
  5196. unsigned NumMemOps = MemOps.size();
  5197. uint64_t SrcOff = 0, DstOff = 0;
  5198. for (unsigned i = 0; i != NumMemOps; ++i) {
  5199. EVT VT = MemOps[i];
  5200. unsigned VTSize = VT.getSizeInBits() / 8;
  5201. SDValue Value, Store;
  5202. if (VTSize > Size) {
  5203. // Issuing an unaligned load / store pair that overlaps with the previous
  5204. // pair. Adjust the offset accordingly.
  5205. assert(i == NumMemOps-1 && i != 0);
  5206. SrcOff -= VTSize - Size;
  5207. DstOff -= VTSize - Size;
  5208. }
  5209. if (CopyFromConstant &&
  5210. (isZeroConstant || (VT.isInteger() && !VT.isVector()))) {
  5211. // It's unlikely a store of a vector immediate can be done in a single
  5212. // instruction. It would require a load from a constantpool first.
  5213. // We only handle zero vectors here.
  5214. // FIXME: Handle other cases where store of vector immediate is done in
  5215. // a single instruction.
  5216. ConstantDataArraySlice SubSlice;
  5217. if (SrcOff < Slice.Length) {
  5218. SubSlice = Slice;
  5219. SubSlice.move(SrcOff);
  5220. } else {
  5221. // This is an out-of-bounds access and hence UB. Pretend we read zero.
  5222. SubSlice.Array = nullptr;
  5223. SubSlice.Offset = 0;
  5224. SubSlice.Length = VTSize;
  5225. }
  5226. Value = getMemsetStringVal(VT, dl, DAG, TLI, SubSlice);
  5227. if (Value.getNode()) {
  5228. Store = DAG.getStore(Chain, dl, Value,
  5229. DAG.getMemBasePlusOffset(Dst, DstOff, dl),
  5230. DstPtrInfo.getWithOffset(DstOff), Align,
  5231. MMOFlags);
  5232. OutChains.push_back(Store);
  5233. }
  5234. }
  5235. if (!Store.getNode()) {
  5236. // The type might not be legal for the target. This should only happen
  5237. // if the type is smaller than a legal type, as on PPC, so the right
  5238. // thing to do is generate a LoadExt/StoreTrunc pair. These simplify
  5239. // to Load/Store if NVT==VT.
  5240. // FIXME does the case above also need this?
  5241. EVT NVT = TLI.getTypeToTransformTo(C, VT);
  5242. assert(NVT.bitsGE(VT));
  5243. bool isDereferenceable =
  5244. SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL);
  5245. MachineMemOperand::Flags SrcMMOFlags = MMOFlags;
  5246. if (isDereferenceable)
  5247. SrcMMOFlags |= MachineMemOperand::MODereferenceable;
  5248. Value = DAG.getExtLoad(ISD::EXTLOAD, dl, NVT, Chain,
  5249. DAG.getMemBasePlusOffset(Src, SrcOff, dl),
  5250. SrcPtrInfo.getWithOffset(SrcOff), VT,
  5251. MinAlign(SrcAlign, SrcOff), SrcMMOFlags);
  5252. OutLoadChains.push_back(Value.getValue(1));
  5253. Store = DAG.getTruncStore(
  5254. Chain, dl, Value, DAG.getMemBasePlusOffset(Dst, DstOff, dl),
  5255. DstPtrInfo.getWithOffset(DstOff), VT, Align, MMOFlags);
  5256. OutStoreChains.push_back(Store);
  5257. }
  5258. SrcOff += VTSize;
  5259. DstOff += VTSize;
  5260. Size -= VTSize;
  5261. }
  5262. unsigned GluedLdStLimit = MaxLdStGlue == 0 ?
  5263. TLI.getMaxGluedStoresPerMemcpy() : MaxLdStGlue;
  5264. unsigned NumLdStInMemcpy = OutStoreChains.size();
  5265. if (NumLdStInMemcpy) {
  5266. // It may be that memcpy might be converted to memset if it's memcpy
  5267. // of constants. In such a case, we won't have loads and stores, but
  5268. // just stores. In the absence of loads, there is nothing to gang up.
  5269. if ((GluedLdStLimit <= 1) || !EnableMemCpyDAGOpt) {
  5270. // If target does not care, just leave as it.
  5271. for (unsigned i = 0; i < NumLdStInMemcpy; ++i) {
  5272. OutChains.push_back(OutLoadChains[i]);
  5273. OutChains.push_back(OutStoreChains[i]);
  5274. }
  5275. } else {
  5276. // Ld/St less than/equal limit set by target.
  5277. if (NumLdStInMemcpy <= GluedLdStLimit) {
  5278. chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, 0,
  5279. NumLdStInMemcpy, OutLoadChains,
  5280. OutStoreChains);
  5281. } else {
  5282. unsigned NumberLdChain = NumLdStInMemcpy / GluedLdStLimit;
  5283. unsigned RemainingLdStInMemcpy = NumLdStInMemcpy % GluedLdStLimit;
  5284. unsigned GlueIter = 0;
  5285. for (unsigned cnt = 0; cnt < NumberLdChain; ++cnt) {
  5286. unsigned IndexFrom = NumLdStInMemcpy - GlueIter - GluedLdStLimit;
  5287. unsigned IndexTo = NumLdStInMemcpy - GlueIter;
  5288. chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, IndexFrom, IndexTo,
  5289. OutLoadChains, OutStoreChains);
  5290. GlueIter += GluedLdStLimit;
  5291. }
  5292. // Residual ld/st.
  5293. if (RemainingLdStInMemcpy) {
  5294. chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, 0,
  5295. RemainingLdStInMemcpy, OutLoadChains,
  5296. OutStoreChains);
  5297. }
  5298. }
  5299. }
  5300. }
  5301. return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
  5302. }
  5303. static SDValue getMemmoveLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl,
  5304. SDValue Chain, SDValue Dst, SDValue Src,
  5305. uint64_t Size, unsigned Align,
  5306. bool isVol, bool AlwaysInline,
  5307. MachinePointerInfo DstPtrInfo,
  5308. MachinePointerInfo SrcPtrInfo) {
  5309. // Turn a memmove of undef to nop.
  5310. if (Src.isUndef())
  5311. return Chain;
  5312. // Expand memmove to a series of load and store ops if the size operand falls
  5313. // below a certain threshold.
  5314. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  5315. const DataLayout &DL = DAG.getDataLayout();
  5316. LLVMContext &C = *DAG.getContext();
  5317. std::vector<EVT> MemOps;
  5318. bool DstAlignCanChange = false;
  5319. MachineFunction &MF = DAG.getMachineFunction();
  5320. MachineFrameInfo &MFI = MF.getFrameInfo();
  5321. bool OptSize = shouldLowerMemFuncForSize(MF);
  5322. FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
  5323. if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
  5324. DstAlignCanChange = true;
  5325. unsigned SrcAlign = DAG.InferPtrAlignment(Src);
  5326. if (Align > SrcAlign)
  5327. SrcAlign = Align;
  5328. unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemmove(OptSize);
  5329. if (!FindOptimalMemOpLowering(MemOps, Limit, Size,
  5330. (DstAlignCanChange ? 0 : Align), SrcAlign,
  5331. false, false, false, false,
  5332. DstPtrInfo.getAddrSpace(),
  5333. SrcPtrInfo.getAddrSpace(),
  5334. DAG, TLI))
  5335. return SDValue();
  5336. if (DstAlignCanChange) {
  5337. Type *Ty = MemOps[0].getTypeForEVT(C);
  5338. unsigned NewAlign = (unsigned)DL.getABITypeAlignment(Ty);
  5339. if (NewAlign > Align) {
  5340. // Give the stack frame object a larger alignment if needed.
  5341. if (MFI.getObjectAlignment(FI->getIndex()) < NewAlign)
  5342. MFI.setObjectAlignment(FI->getIndex(), NewAlign);
  5343. Align = NewAlign;
  5344. }
  5345. }
  5346. MachineMemOperand::Flags MMOFlags =
  5347. isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone;
  5348. uint64_t SrcOff = 0, DstOff = 0;
  5349. SmallVector<SDValue, 8> LoadValues;
  5350. SmallVector<SDValue, 8> LoadChains;
  5351. SmallVector<SDValue, 8> OutChains;
  5352. unsigned NumMemOps = MemOps.size();
  5353. for (unsigned i = 0; i < NumMemOps; i++) {
  5354. EVT VT = MemOps[i];
  5355. unsigned VTSize = VT.getSizeInBits() / 8;
  5356. SDValue Value;
  5357. bool isDereferenceable =
  5358. SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL);
  5359. MachineMemOperand::Flags SrcMMOFlags = MMOFlags;
  5360. if (isDereferenceable)
  5361. SrcMMOFlags |= MachineMemOperand::MODereferenceable;
  5362. Value =
  5363. DAG.getLoad(VT, dl, Chain, DAG.getMemBasePlusOffset(Src, SrcOff, dl),
  5364. SrcPtrInfo.getWithOffset(SrcOff), SrcAlign, SrcMMOFlags);
  5365. LoadValues.push_back(Value);
  5366. LoadChains.push_back(Value.getValue(1));
  5367. SrcOff += VTSize;
  5368. }
  5369. Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
  5370. OutChains.clear();
  5371. for (unsigned i = 0; i < NumMemOps; i++) {
  5372. EVT VT = MemOps[i];
  5373. unsigned VTSize = VT.getSizeInBits() / 8;
  5374. SDValue Store;
  5375. Store = DAG.getStore(Chain, dl, LoadValues[i],
  5376. DAG.getMemBasePlusOffset(Dst, DstOff, dl),
  5377. DstPtrInfo.getWithOffset(DstOff), Align, MMOFlags);
  5378. OutChains.push_back(Store);
  5379. DstOff += VTSize;
  5380. }
  5381. return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
  5382. }
  5383. /// Lower the call to 'memset' intrinsic function into a series of store
  5384. /// operations.
  5385. ///
  5386. /// \param DAG Selection DAG where lowered code is placed.
  5387. /// \param dl Link to corresponding IR location.
  5388. /// \param Chain Control flow dependency.
  5389. /// \param Dst Pointer to destination memory location.
  5390. /// \param Src Value of byte to write into the memory.
  5391. /// \param Size Number of bytes to write.
  5392. /// \param Align Alignment of the destination in bytes.
  5393. /// \param isVol True if destination is volatile.
  5394. /// \param DstPtrInfo IR information on the memory pointer.
  5395. /// \returns New head in the control flow, if lowering was successful, empty
  5396. /// SDValue otherwise.
  5397. ///
  5398. /// The function tries to replace 'llvm.memset' intrinsic with several store
  5399. /// operations and value calculation code. This is usually profitable for small
  5400. /// memory size.
  5401. static SDValue getMemsetStores(SelectionDAG &DAG, const SDLoc &dl,
  5402. SDValue Chain, SDValue Dst, SDValue Src,
  5403. uint64_t Size, unsigned Align, bool isVol,
  5404. MachinePointerInfo DstPtrInfo) {
  5405. // Turn a memset of undef to nop.
  5406. if (Src.isUndef())
  5407. return Chain;
  5408. // Expand memset to a series of load/store ops if the size operand
  5409. // falls below a certain threshold.
  5410. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  5411. std::vector<EVT> MemOps;
  5412. bool DstAlignCanChange = false;
  5413. MachineFunction &MF = DAG.getMachineFunction();
  5414. MachineFrameInfo &MFI = MF.getFrameInfo();
  5415. bool OptSize = shouldLowerMemFuncForSize(MF);
  5416. FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
  5417. if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
  5418. DstAlignCanChange = true;
  5419. bool IsZeroVal =
  5420. isa<ConstantSDNode>(Src) && cast<ConstantSDNode>(Src)->isNullValue();
  5421. if (!FindOptimalMemOpLowering(MemOps, TLI.getMaxStoresPerMemset(OptSize),
  5422. Size, (DstAlignCanChange ? 0 : Align), 0,
  5423. true, IsZeroVal, false, true,
  5424. DstPtrInfo.getAddrSpace(), ~0u,
  5425. DAG, TLI))
  5426. return SDValue();
  5427. if (DstAlignCanChange) {
  5428. Type *Ty = MemOps[0].getTypeForEVT(*DAG.getContext());
  5429. unsigned NewAlign = (unsigned)DAG.getDataLayout().getABITypeAlignment(Ty);
  5430. if (NewAlign > Align) {
  5431. // Give the stack frame object a larger alignment if needed.
  5432. if (MFI.getObjectAlignment(FI->getIndex()) < NewAlign)
  5433. MFI.setObjectAlignment(FI->getIndex(), NewAlign);
  5434. Align = NewAlign;
  5435. }
  5436. }
  5437. SmallVector<SDValue, 8> OutChains;
  5438. uint64_t DstOff = 0;
  5439. unsigned NumMemOps = MemOps.size();
  5440. // Find the largest store and generate the bit pattern for it.
  5441. EVT LargestVT = MemOps[0];
  5442. for (unsigned i = 1; i < NumMemOps; i++)
  5443. if (MemOps[i].bitsGT(LargestVT))
  5444. LargestVT = MemOps[i];
  5445. SDValue MemSetValue = getMemsetValue(Src, LargestVT, DAG, dl);
  5446. for (unsigned i = 0; i < NumMemOps; i++) {
  5447. EVT VT = MemOps[i];
  5448. unsigned VTSize = VT.getSizeInBits() / 8;
  5449. if (VTSize > Size) {
  5450. // Issuing an unaligned load / store pair that overlaps with the previous
  5451. // pair. Adjust the offset accordingly.
  5452. assert(i == NumMemOps-1 && i != 0);
  5453. DstOff -= VTSize - Size;
  5454. }
  5455. // If this store is smaller than the largest store see whether we can get
  5456. // the smaller value for free with a truncate.
  5457. SDValue Value = MemSetValue;
  5458. if (VT.bitsLT(LargestVT)) {
  5459. if (!LargestVT.isVector() && !VT.isVector() &&
  5460. TLI.isTruncateFree(LargestVT, VT))
  5461. Value = DAG.getNode(ISD::TRUNCATE, dl, VT, MemSetValue);
  5462. else
  5463. Value = getMemsetValue(Src, VT, DAG, dl);
  5464. }
  5465. assert(Value.getValueType() == VT && "Value with wrong type.");
  5466. SDValue Store = DAG.getStore(
  5467. Chain, dl, Value, DAG.getMemBasePlusOffset(Dst, DstOff, dl),
  5468. DstPtrInfo.getWithOffset(DstOff), Align,
  5469. isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone);
  5470. OutChains.push_back(Store);
  5471. DstOff += VT.getSizeInBits() / 8;
  5472. Size -= VTSize;
  5473. }
  5474. return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
  5475. }
  5476. static void checkAddrSpaceIsValidForLibcall(const TargetLowering *TLI,
  5477. unsigned AS) {
  5478. // Lowering memcpy / memset / memmove intrinsics to calls is only valid if all
  5479. // pointer operands can be losslessly bitcasted to pointers of address space 0
  5480. if (AS != 0 && !TLI->isNoopAddrSpaceCast(AS, 0)) {
  5481. report_fatal_error("cannot lower memory intrinsic in address space " +
  5482. Twine(AS));
  5483. }
  5484. }
  5485. SDValue SelectionDAG::getMemcpy(SDValue Chain, const SDLoc &dl, SDValue Dst,
  5486. SDValue Src, SDValue Size, unsigned Align,
  5487. bool isVol, bool AlwaysInline, bool isTailCall,
  5488. MachinePointerInfo DstPtrInfo,
  5489. MachinePointerInfo SrcPtrInfo) {
  5490. assert(Align && "The SDAG layer expects explicit alignment and reserves 0");
  5491. // Check to see if we should lower the memcpy to loads and stores first.
  5492. // For cases within the target-specified limits, this is the best choice.
  5493. ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
  5494. if (ConstantSize) {
  5495. // Memcpy with size zero? Just return the original chain.
  5496. if (ConstantSize->isNullValue())
  5497. return Chain;
  5498. SDValue Result = getMemcpyLoadsAndStores(*this, dl, Chain, Dst, Src,
  5499. ConstantSize->getZExtValue(),Align,
  5500. isVol, false, DstPtrInfo, SrcPtrInfo);
  5501. if (Result.getNode())
  5502. return Result;
  5503. }
  5504. // Then check to see if we should lower the memcpy with target-specific
  5505. // code. If the target chooses to do this, this is the next best.
  5506. if (TSI) {
  5507. SDValue Result = TSI->EmitTargetCodeForMemcpy(
  5508. *this, dl, Chain, Dst, Src, Size, Align, isVol, AlwaysInline,
  5509. DstPtrInfo, SrcPtrInfo);
  5510. if (Result.getNode())
  5511. return Result;
  5512. }
  5513. // If we really need inline code and the target declined to provide it,
  5514. // use a (potentially long) sequence of loads and stores.
  5515. if (AlwaysInline) {
  5516. assert(ConstantSize && "AlwaysInline requires a constant size!");
  5517. return getMemcpyLoadsAndStores(*this, dl, Chain, Dst, Src,
  5518. ConstantSize->getZExtValue(), Align, isVol,
  5519. true, DstPtrInfo, SrcPtrInfo);
  5520. }
  5521. checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
  5522. checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace());
  5523. // FIXME: If the memcpy is volatile (isVol), lowering it to a plain libc
  5524. // memcpy is not guaranteed to be safe. libc memcpys aren't required to
  5525. // respect volatile, so they may do things like read or write memory
  5526. // beyond the given memory regions. But fixing this isn't easy, and most
  5527. // people don't care.
  5528. // Emit a library call.
  5529. TargetLowering::ArgListTy Args;
  5530. TargetLowering::ArgListEntry Entry;
  5531. Entry.Ty = getDataLayout().getIntPtrType(*getContext());
  5532. Entry.Node = Dst; Args.push_back(Entry);
  5533. Entry.Node = Src; Args.push_back(Entry);
  5534. Entry.Node = Size; Args.push_back(Entry);
  5535. // FIXME: pass in SDLoc
  5536. TargetLowering::CallLoweringInfo CLI(*this);
  5537. CLI.setDebugLoc(dl)
  5538. .setChain(Chain)
  5539. .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMCPY),
  5540. Dst.getValueType().getTypeForEVT(*getContext()),
  5541. getExternalSymbol(TLI->getLibcallName(RTLIB::MEMCPY),
  5542. TLI->getPointerTy(getDataLayout())),
  5543. std::move(Args))
  5544. .setDiscardResult()
  5545. .setTailCall(isTailCall);
  5546. std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
  5547. return CallResult.second;
  5548. }
  5549. SDValue SelectionDAG::getAtomicMemcpy(SDValue Chain, const SDLoc &dl,
  5550. SDValue Dst, unsigned DstAlign,
  5551. SDValue Src, unsigned SrcAlign,
  5552. SDValue Size, Type *SizeTy,
  5553. unsigned ElemSz, bool isTailCall,
  5554. MachinePointerInfo DstPtrInfo,
  5555. MachinePointerInfo SrcPtrInfo) {
  5556. // Emit a library call.
  5557. TargetLowering::ArgListTy Args;
  5558. TargetLowering::ArgListEntry Entry;
  5559. Entry.Ty = getDataLayout().getIntPtrType(*getContext());
  5560. Entry.Node = Dst;
  5561. Args.push_back(Entry);
  5562. Entry.Node = Src;
  5563. Args.push_back(Entry);
  5564. Entry.Ty = SizeTy;
  5565. Entry.Node = Size;
  5566. Args.push_back(Entry);
  5567. RTLIB::Libcall LibraryCall =
  5568. RTLIB::getMEMCPY_ELEMENT_UNORDERED_ATOMIC(ElemSz);
  5569. if (LibraryCall == RTLIB::UNKNOWN_LIBCALL)
  5570. report_fatal_error("Unsupported element size");
  5571. TargetLowering::CallLoweringInfo CLI(*this);
  5572. CLI.setDebugLoc(dl)
  5573. .setChain(Chain)
  5574. .setLibCallee(TLI->getLibcallCallingConv(LibraryCall),
  5575. Type::getVoidTy(*getContext()),
  5576. getExternalSymbol(TLI->getLibcallName(LibraryCall),
  5577. TLI->getPointerTy(getDataLayout())),
  5578. std::move(Args))
  5579. .setDiscardResult()
  5580. .setTailCall(isTailCall);
  5581. std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
  5582. return CallResult.second;
  5583. }
  5584. SDValue SelectionDAG::getMemmove(SDValue Chain, const SDLoc &dl, SDValue Dst,
  5585. SDValue Src, SDValue Size, unsigned Align,
  5586. bool isVol, bool isTailCall,
  5587. MachinePointerInfo DstPtrInfo,
  5588. MachinePointerInfo SrcPtrInfo) {
  5589. assert(Align && "The SDAG layer expects explicit alignment and reserves 0");
  5590. // Check to see if we should lower the memmove to loads and stores first.
  5591. // For cases within the target-specified limits, this is the best choice.
  5592. ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
  5593. if (ConstantSize) {
  5594. // Memmove with size zero? Just return the original chain.
  5595. if (ConstantSize->isNullValue())
  5596. return Chain;
  5597. SDValue Result =
  5598. getMemmoveLoadsAndStores(*this, dl, Chain, Dst, Src,
  5599. ConstantSize->getZExtValue(), Align, isVol,
  5600. false, DstPtrInfo, SrcPtrInfo);
  5601. if (Result.getNode())
  5602. return Result;
  5603. }
  5604. // Then check to see if we should lower the memmove with target-specific
  5605. // code. If the target chooses to do this, this is the next best.
  5606. if (TSI) {
  5607. SDValue Result = TSI->EmitTargetCodeForMemmove(
  5608. *this, dl, Chain, Dst, Src, Size, Align, isVol, DstPtrInfo, SrcPtrInfo);
  5609. if (Result.getNode())
  5610. return Result;
  5611. }
  5612. checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
  5613. checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace());
  5614. // FIXME: If the memmove is volatile, lowering it to plain libc memmove may
  5615. // not be safe. See memcpy above for more details.
  5616. // Emit a library call.
  5617. TargetLowering::ArgListTy Args;
  5618. TargetLowering::ArgListEntry Entry;
  5619. Entry.Ty = getDataLayout().getIntPtrType(*getContext());
  5620. Entry.Node = Dst; Args.push_back(Entry);
  5621. Entry.Node = Src; Args.push_back(Entry);
  5622. Entry.Node = Size; Args.push_back(Entry);
  5623. // FIXME: pass in SDLoc
  5624. TargetLowering::CallLoweringInfo CLI(*this);
  5625. CLI.setDebugLoc(dl)
  5626. .setChain(Chain)
  5627. .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMMOVE),
  5628. Dst.getValueType().getTypeForEVT(*getContext()),
  5629. getExternalSymbol(TLI->getLibcallName(RTLIB::MEMMOVE),
  5630. TLI->getPointerTy(getDataLayout())),
  5631. std::move(Args))
  5632. .setDiscardResult()
  5633. .setTailCall(isTailCall);
  5634. std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
  5635. return CallResult.second;
  5636. }
  5637. SDValue SelectionDAG::getAtomicMemmove(SDValue Chain, const SDLoc &dl,
  5638. SDValue Dst, unsigned DstAlign,
  5639. SDValue Src, unsigned SrcAlign,
  5640. SDValue Size, Type *SizeTy,
  5641. unsigned ElemSz, bool isTailCall,
  5642. MachinePointerInfo DstPtrInfo,
  5643. MachinePointerInfo SrcPtrInfo) {
  5644. // Emit a library call.
  5645. TargetLowering::ArgListTy Args;
  5646. TargetLowering::ArgListEntry Entry;
  5647. Entry.Ty = getDataLayout().getIntPtrType(*getContext());
  5648. Entry.Node = Dst;
  5649. Args.push_back(Entry);
  5650. Entry.Node = Src;
  5651. Args.push_back(Entry);
  5652. Entry.Ty = SizeTy;
  5653. Entry.Node = Size;
  5654. Args.push_back(Entry);
  5655. RTLIB::Libcall LibraryCall =
  5656. RTLIB::getMEMMOVE_ELEMENT_UNORDERED_ATOMIC(ElemSz);
  5657. if (LibraryCall == RTLIB::UNKNOWN_LIBCALL)
  5658. report_fatal_error("Unsupported element size");
  5659. TargetLowering::CallLoweringInfo CLI(*this);
  5660. CLI.setDebugLoc(dl)
  5661. .setChain(Chain)
  5662. .setLibCallee(TLI->getLibcallCallingConv(LibraryCall),
  5663. Type::getVoidTy(*getContext()),
  5664. getExternalSymbol(TLI->getLibcallName(LibraryCall),
  5665. TLI->getPointerTy(getDataLayout())),
  5666. std::move(Args))
  5667. .setDiscardResult()
  5668. .setTailCall(isTailCall);
  5669. std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
  5670. return CallResult.second;
  5671. }
  5672. SDValue SelectionDAG::getMemset(SDValue Chain, const SDLoc &dl, SDValue Dst,
  5673. SDValue Src, SDValue Size, unsigned Align,
  5674. bool isVol, bool isTailCall,
  5675. MachinePointerInfo DstPtrInfo) {
  5676. assert(Align && "The SDAG layer expects explicit alignment and reserves 0");
  5677. // Check to see if we should lower the memset to stores first.
  5678. // For cases within the target-specified limits, this is the best choice.
  5679. ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
  5680. if (ConstantSize) {
  5681. // Memset with size zero? Just return the original chain.
  5682. if (ConstantSize->isNullValue())
  5683. return Chain;
  5684. SDValue Result =
  5685. getMemsetStores(*this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(),
  5686. Align, isVol, DstPtrInfo);
  5687. if (Result.getNode())
  5688. return Result;
  5689. }
  5690. // Then check to see if we should lower the memset with target-specific
  5691. // code. If the target chooses to do this, this is the next best.
  5692. if (TSI) {
  5693. SDValue Result = TSI->EmitTargetCodeForMemset(
  5694. *this, dl, Chain, Dst, Src, Size, Align, isVol, DstPtrInfo);
  5695. if (Result.getNode())
  5696. return Result;
  5697. }
  5698. checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
  5699. // Emit a library call.
  5700. Type *IntPtrTy = getDataLayout().getIntPtrType(*getContext());
  5701. TargetLowering::ArgListTy Args;
  5702. TargetLowering::ArgListEntry Entry;
  5703. Entry.Node = Dst; Entry.Ty = IntPtrTy;
  5704. Args.push_back(Entry);
  5705. Entry.Node = Src;
  5706. Entry.Ty = Src.getValueType().getTypeForEVT(*getContext());
  5707. Args.push_back(Entry);
  5708. Entry.Node = Size;
  5709. Entry.Ty = IntPtrTy;
  5710. Args.push_back(Entry);
  5711. // FIXME: pass in SDLoc
  5712. TargetLowering::CallLoweringInfo CLI(*this);
  5713. CLI.setDebugLoc(dl)
  5714. .setChain(Chain)
  5715. .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMSET),
  5716. Dst.getValueType().getTypeForEVT(*getContext()),
  5717. getExternalSymbol(TLI->getLibcallName(RTLIB::MEMSET),
  5718. TLI->getPointerTy(getDataLayout())),
  5719. std::move(Args))
  5720. .setDiscardResult()
  5721. .setTailCall(isTailCall);
  5722. std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
  5723. return CallResult.second;
  5724. }
  5725. SDValue SelectionDAG::getAtomicMemset(SDValue Chain, const SDLoc &dl,
  5726. SDValue Dst, unsigned DstAlign,
  5727. SDValue Value, SDValue Size, Type *SizeTy,
  5728. unsigned ElemSz, bool isTailCall,
  5729. MachinePointerInfo DstPtrInfo) {
  5730. // Emit a library call.
  5731. TargetLowering::ArgListTy Args;
  5732. TargetLowering::ArgListEntry Entry;
  5733. Entry.Ty = getDataLayout().getIntPtrType(*getContext());
  5734. Entry.Node = Dst;
  5735. Args.push_back(Entry);
  5736. Entry.Ty = Type::getInt8Ty(*getContext());
  5737. Entry.Node = Value;
  5738. Args.push_back(Entry);
  5739. Entry.Ty = SizeTy;
  5740. Entry.Node = Size;
  5741. Args.push_back(Entry);
  5742. RTLIB::Libcall LibraryCall =
  5743. RTLIB::getMEMSET_ELEMENT_UNORDERED_ATOMIC(ElemSz);
  5744. if (LibraryCall == RTLIB::UNKNOWN_LIBCALL)
  5745. report_fatal_error("Unsupported element size");
  5746. TargetLowering::CallLoweringInfo CLI(*this);
  5747. CLI.setDebugLoc(dl)
  5748. .setChain(Chain)
  5749. .setLibCallee(TLI->getLibcallCallingConv(LibraryCall),
  5750. Type::getVoidTy(*getContext()),
  5751. getExternalSymbol(TLI->getLibcallName(LibraryCall),
  5752. TLI->getPointerTy(getDataLayout())),
  5753. std::move(Args))
  5754. .setDiscardResult()
  5755. .setTailCall(isTailCall);
  5756. std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
  5757. return CallResult.second;
  5758. }
  5759. SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
  5760. SDVTList VTList, ArrayRef<SDValue> Ops,
  5761. MachineMemOperand *MMO) {
  5762. FoldingSetNodeID ID;
  5763. ID.AddInteger(MemVT.getRawBits());
  5764. AddNodeIDNode(ID, Opcode, VTList, Ops);
  5765. ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
  5766. void* IP = nullptr;
  5767. if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
  5768. cast<AtomicSDNode>(E)->refineAlignment(MMO);
  5769. return SDValue(E, 0);
  5770. }
  5771. auto *N = newSDNode<AtomicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
  5772. VTList, MemVT, MMO);
  5773. createOperands(N, Ops);
  5774. CSEMap.InsertNode(N, IP);
  5775. InsertNode(N);
  5776. return SDValue(N, 0);
  5777. }
  5778. SDValue SelectionDAG::getAtomicCmpSwap(unsigned Opcode, const SDLoc &dl,
  5779. EVT MemVT, SDVTList VTs, SDValue Chain,
  5780. SDValue Ptr, SDValue Cmp, SDValue Swp,
  5781. MachineMemOperand *MMO) {
  5782. assert(Opcode == ISD::ATOMIC_CMP_SWAP ||
  5783. Opcode == ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
  5784. assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types");
  5785. SDValue Ops[] = {Chain, Ptr, Cmp, Swp};
  5786. return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
  5787. }
  5788. SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
  5789. SDValue Chain, SDValue Ptr, SDValue Val,
  5790. MachineMemOperand *MMO) {
  5791. assert((Opcode == ISD::ATOMIC_LOAD_ADD ||
  5792. Opcode == ISD::ATOMIC_LOAD_SUB ||
  5793. Opcode == ISD::ATOMIC_LOAD_AND ||
  5794. Opcode == ISD::ATOMIC_LOAD_CLR ||
  5795. Opcode == ISD::ATOMIC_LOAD_OR ||
  5796. Opcode == ISD::ATOMIC_LOAD_XOR ||
  5797. Opcode == ISD::ATOMIC_LOAD_NAND ||
  5798. Opcode == ISD::ATOMIC_LOAD_MIN ||
  5799. Opcode == ISD::ATOMIC_LOAD_MAX ||
  5800. Opcode == ISD::ATOMIC_LOAD_UMIN ||
  5801. Opcode == ISD::ATOMIC_LOAD_UMAX ||
  5802. Opcode == ISD::ATOMIC_LOAD_FADD ||
  5803. Opcode == ISD::ATOMIC_LOAD_FSUB ||
  5804. Opcode == ISD::ATOMIC_SWAP ||
  5805. Opcode == ISD::ATOMIC_STORE) &&
  5806. "Invalid Atomic Op");
  5807. EVT VT = Val.getValueType();
  5808. SDVTList VTs = Opcode == ISD::ATOMIC_STORE ? getVTList(MVT::Other) :
  5809. getVTList(VT, MVT::Other);
  5810. SDValue Ops[] = {Chain, Ptr, Val};
  5811. return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
  5812. }
  5813. SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
  5814. EVT VT, SDValue Chain, SDValue Ptr,
  5815. MachineMemOperand *MMO) {
  5816. assert(Opcode == ISD::ATOMIC_LOAD && "Invalid Atomic Op");
  5817. SDVTList VTs = getVTList(VT, MVT::Other);
  5818. SDValue Ops[] = {Chain, Ptr};
  5819. return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
  5820. }
  5821. /// getMergeValues - Create a MERGE_VALUES node from the given operands.
  5822. SDValue SelectionDAG::getMergeValues(ArrayRef<SDValue> Ops, const SDLoc &dl) {
  5823. if (Ops.size() == 1)
  5824. return Ops[0];
  5825. SmallVector<EVT, 4> VTs;
  5826. VTs.reserve(Ops.size());
  5827. for (unsigned i = 0; i < Ops.size(); ++i)
  5828. VTs.push_back(Ops[i].getValueType());
  5829. return getNode(ISD::MERGE_VALUES, dl, getVTList(VTs), Ops);
  5830. }
  5831. SDValue SelectionDAG::getMemIntrinsicNode(
  5832. unsigned Opcode, const SDLoc &dl, SDVTList VTList, ArrayRef<SDValue> Ops,
  5833. EVT MemVT, MachinePointerInfo PtrInfo, unsigned Align,
  5834. MachineMemOperand::Flags Flags, unsigned Size) {
  5835. if (Align == 0) // Ensure that codegen never sees alignment 0
  5836. Align = getEVTAlignment(MemVT);
  5837. if (!Size)
  5838. Size = MemVT.getStoreSize();
  5839. MachineFunction &MF = getMachineFunction();
  5840. MachineMemOperand *MMO =
  5841. MF.getMachineMemOperand(PtrInfo, Flags, Size, Align);
  5842. return getMemIntrinsicNode(Opcode, dl, VTList, Ops, MemVT, MMO);
  5843. }
  5844. SDValue SelectionDAG::getMemIntrinsicNode(unsigned Opcode, const SDLoc &dl,
  5845. SDVTList VTList,
  5846. ArrayRef<SDValue> Ops, EVT MemVT,
  5847. MachineMemOperand *MMO) {
  5848. assert((Opcode == ISD::INTRINSIC_VOID ||
  5849. Opcode == ISD::INTRINSIC_W_CHAIN ||
  5850. Opcode == ISD::PREFETCH ||
  5851. Opcode == ISD::LIFETIME_START ||
  5852. Opcode == ISD::LIFETIME_END ||
  5853. ((int)Opcode <= std::numeric_limits<int>::max() &&
  5854. (int)Opcode >= ISD::FIRST_TARGET_MEMORY_OPCODE)) &&
  5855. "Opcode is not a memory-accessing opcode!");
  5856. // Memoize the node unless it returns a flag.
  5857. MemIntrinsicSDNode *N;
  5858. if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
  5859. FoldingSetNodeID ID;
  5860. AddNodeIDNode(ID, Opcode, VTList, Ops);
  5861. ID.AddInteger(getSyntheticNodeSubclassData<MemIntrinsicSDNode>(
  5862. Opcode, dl.getIROrder(), VTList, MemVT, MMO));
  5863. ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
  5864. void *IP = nullptr;
  5865. if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
  5866. cast<MemIntrinsicSDNode>(E)->refineAlignment(MMO);
  5867. return SDValue(E, 0);
  5868. }
  5869. N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
  5870. VTList, MemVT, MMO);
  5871. createOperands(N, Ops);
  5872. CSEMap.InsertNode(N, IP);
  5873. } else {
  5874. N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
  5875. VTList, MemVT, MMO);
  5876. createOperands(N, Ops);
  5877. }
  5878. InsertNode(N);
  5879. return SDValue(N, 0);
  5880. }
  5881. SDValue SelectionDAG::getLifetimeNode(bool IsStart, const SDLoc &dl,
  5882. SDValue Chain, int FrameIndex,
  5883. int64_t Size, int64_t Offset) {
  5884. const unsigned Opcode = IsStart ? ISD::LIFETIME_START : ISD::LIFETIME_END;
  5885. const auto VTs = getVTList(MVT::Other);
  5886. SDValue Ops[2] = {
  5887. Chain,
  5888. getFrameIndex(FrameIndex,
  5889. getTargetLoweringInfo().getFrameIndexTy(getDataLayout()),
  5890. true)};
  5891. FoldingSetNodeID ID;
  5892. AddNodeIDNode(ID, Opcode, VTs, Ops);
  5893. ID.AddInteger(FrameIndex);
  5894. ID.AddInteger(Size);
  5895. ID.AddInteger(Offset);
  5896. void *IP = nullptr;
  5897. if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
  5898. return SDValue(E, 0);
  5899. LifetimeSDNode *N = newSDNode<LifetimeSDNode>(
  5900. Opcode, dl.getIROrder(), dl.getDebugLoc(), VTs, Size, Offset);
  5901. createOperands(N, Ops);
  5902. CSEMap.InsertNode(N, IP);
  5903. InsertNode(N);
  5904. SDValue V(N, 0);
  5905. NewSDValueDbgMsg(V, "Creating new node: ", this);
  5906. return V;
  5907. }
  5908. /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a
  5909. /// MachinePointerInfo record from it. This is particularly useful because the
  5910. /// code generator has many cases where it doesn't bother passing in a
  5911. /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst".
  5912. static MachinePointerInfo InferPointerInfo(const MachinePointerInfo &Info,
  5913. SelectionDAG &DAG, SDValue Ptr,
  5914. int64_t Offset = 0) {
  5915. // If this is FI+Offset, we can model it.
  5916. if (const FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr))
  5917. return MachinePointerInfo::getFixedStack(DAG.getMachineFunction(),
  5918. FI->getIndex(), Offset);
  5919. // If this is (FI+Offset1)+Offset2, we can model it.
  5920. if (Ptr.getOpcode() != ISD::ADD ||
  5921. !isa<ConstantSDNode>(Ptr.getOperand(1)) ||
  5922. !isa<FrameIndexSDNode>(Ptr.getOperand(0)))
  5923. return Info;
  5924. int FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
  5925. return MachinePointerInfo::getFixedStack(
  5926. DAG.getMachineFunction(), FI,
  5927. Offset + cast<ConstantSDNode>(Ptr.getOperand(1))->getSExtValue());
  5928. }
  5929. /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a
  5930. /// MachinePointerInfo record from it. This is particularly useful because the
  5931. /// code generator has many cases where it doesn't bother passing in a
  5932. /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst".
  5933. static MachinePointerInfo InferPointerInfo(const MachinePointerInfo &Info,
  5934. SelectionDAG &DAG, SDValue Ptr,
  5935. SDValue OffsetOp) {
  5936. // If the 'Offset' value isn't a constant, we can't handle this.
  5937. if (ConstantSDNode *OffsetNode = dyn_cast<ConstantSDNode>(OffsetOp))
  5938. return InferPointerInfo(Info, DAG, Ptr, OffsetNode->getSExtValue());
  5939. if (OffsetOp.isUndef())
  5940. return InferPointerInfo(Info, DAG, Ptr);
  5941. return Info;
  5942. }
  5943. SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
  5944. EVT VT, const SDLoc &dl, SDValue Chain,
  5945. SDValue Ptr, SDValue Offset,
  5946. MachinePointerInfo PtrInfo, EVT MemVT,
  5947. unsigned Alignment,
  5948. MachineMemOperand::Flags MMOFlags,
  5949. const AAMDNodes &AAInfo, const MDNode *Ranges) {
  5950. assert(Chain.getValueType() == MVT::Other &&
  5951. "Invalid chain type");
  5952. if (Alignment == 0) // Ensure that codegen never sees alignment 0
  5953. Alignment = getEVTAlignment(MemVT);
  5954. MMOFlags |= MachineMemOperand::MOLoad;
  5955. assert((MMOFlags & MachineMemOperand::MOStore) == 0);
  5956. // If we don't have a PtrInfo, infer the trivial frame index case to simplify
  5957. // clients.
  5958. if (PtrInfo.V.isNull())
  5959. PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset);
  5960. MachineFunction &MF = getMachineFunction();
  5961. MachineMemOperand *MMO = MF.getMachineMemOperand(
  5962. PtrInfo, MMOFlags, MemVT.getStoreSize(), Alignment, AAInfo, Ranges);
  5963. return getLoad(AM, ExtType, VT, dl, Chain, Ptr, Offset, MemVT, MMO);
  5964. }
  5965. SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
  5966. EVT VT, const SDLoc &dl, SDValue Chain,
  5967. SDValue Ptr, SDValue Offset, EVT MemVT,
  5968. MachineMemOperand *MMO) {
  5969. if (VT == MemVT) {
  5970. ExtType = ISD::NON_EXTLOAD;
  5971. } else if (ExtType == ISD::NON_EXTLOAD) {
  5972. assert(VT == MemVT && "Non-extending load from different memory type!");
  5973. } else {
  5974. // Extending load.
  5975. assert(MemVT.getScalarType().bitsLT(VT.getScalarType()) &&
  5976. "Should only be an extending load, not truncating!");
  5977. assert(VT.isInteger() == MemVT.isInteger() &&
  5978. "Cannot convert from FP to Int or Int -> FP!");
  5979. assert(VT.isVector() == MemVT.isVector() &&
  5980. "Cannot use an ext load to convert to or from a vector!");
  5981. assert((!VT.isVector() ||
  5982. VT.getVectorNumElements() == MemVT.getVectorNumElements()) &&
  5983. "Cannot use an ext load to change the number of vector elements!");
  5984. }
  5985. bool Indexed = AM != ISD::UNINDEXED;
  5986. assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!");
  5987. SDVTList VTs = Indexed ?
  5988. getVTList(VT, Ptr.getValueType(), MVT::Other) : getVTList(VT, MVT::Other);
  5989. SDValue Ops[] = { Chain, Ptr, Offset };
  5990. FoldingSetNodeID ID;
  5991. AddNodeIDNode(ID, ISD::LOAD, VTs, Ops);
  5992. ID.AddInteger(MemVT.getRawBits());
  5993. ID.AddInteger(getSyntheticNodeSubclassData<LoadSDNode>(
  5994. dl.getIROrder(), VTs, AM, ExtType, MemVT, MMO));
  5995. ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
  5996. void *IP = nullptr;
  5997. if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
  5998. cast<LoadSDNode>(E)->refineAlignment(MMO);
  5999. return SDValue(E, 0);
  6000. }
  6001. auto *N = newSDNode<LoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
  6002. ExtType, MemVT, MMO);
  6003. createOperands(N, Ops);
  6004. CSEMap.InsertNode(N, IP);
  6005. InsertNode(N);
  6006. SDValue V(N, 0);
  6007. NewSDValueDbgMsg(V, "Creating new node: ", this);
  6008. return V;
  6009. }
  6010. SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain,
  6011. SDValue Ptr, MachinePointerInfo PtrInfo,
  6012. unsigned Alignment,
  6013. MachineMemOperand::Flags MMOFlags,
  6014. const AAMDNodes &AAInfo, const MDNode *Ranges) {
  6015. SDValue Undef = getUNDEF(Ptr.getValueType());
  6016. return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
  6017. PtrInfo, VT, Alignment, MMOFlags, AAInfo, Ranges);
  6018. }
  6019. SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain,
  6020. SDValue Ptr, MachineMemOperand *MMO) {
  6021. SDValue Undef = getUNDEF(Ptr.getValueType());
  6022. return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
  6023. VT, MMO);
  6024. }
  6025. SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl,
  6026. EVT VT, SDValue Chain, SDValue Ptr,
  6027. MachinePointerInfo PtrInfo, EVT MemVT,
  6028. unsigned Alignment,
  6029. MachineMemOperand::Flags MMOFlags,
  6030. const AAMDNodes &AAInfo) {
  6031. SDValue Undef = getUNDEF(Ptr.getValueType());
  6032. return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, PtrInfo,
  6033. MemVT, Alignment, MMOFlags, AAInfo);
  6034. }
  6035. SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl,
  6036. EVT VT, SDValue Chain, SDValue Ptr, EVT MemVT,
  6037. MachineMemOperand *MMO) {
  6038. SDValue Undef = getUNDEF(Ptr.getValueType());
  6039. return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef,
  6040. MemVT, MMO);
  6041. }
  6042. SDValue SelectionDAG::getIndexedLoad(SDValue OrigLoad, const SDLoc &dl,
  6043. SDValue Base, SDValue Offset,
  6044. ISD::MemIndexedMode AM) {
  6045. LoadSDNode *LD = cast<LoadSDNode>(OrigLoad);
  6046. assert(LD->getOffset().isUndef() && "Load is already a indexed load!");
  6047. // Don't propagate the invariant or dereferenceable flags.
  6048. auto MMOFlags =
  6049. LD->getMemOperand()->getFlags() &
  6050. ~(MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable);
  6051. return getLoad(AM, LD->getExtensionType(), OrigLoad.getValueType(), dl,
  6052. LD->getChain(), Base, Offset, LD->getPointerInfo(),
  6053. LD->getMemoryVT(), LD->getAlignment(), MMOFlags,
  6054. LD->getAAInfo());
  6055. }
  6056. SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val,
  6057. SDValue Ptr, MachinePointerInfo PtrInfo,
  6058. unsigned Alignment,
  6059. MachineMemOperand::Flags MMOFlags,
  6060. const AAMDNodes &AAInfo) {
  6061. assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
  6062. if (Alignment == 0) // Ensure that codegen never sees alignment 0
  6063. Alignment = getEVTAlignment(Val.getValueType());
  6064. MMOFlags |= MachineMemOperand::MOStore;
  6065. assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
  6066. if (PtrInfo.V.isNull())
  6067. PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
  6068. MachineFunction &MF = getMachineFunction();
  6069. MachineMemOperand *MMO = MF.getMachineMemOperand(
  6070. PtrInfo, MMOFlags, Val.getValueType().getStoreSize(), Alignment, AAInfo);
  6071. return getStore(Chain, dl, Val, Ptr, MMO);
  6072. }
  6073. SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val,
  6074. SDValue Ptr, MachineMemOperand *MMO) {
  6075. assert(Chain.getValueType() == MVT::Other &&
  6076. "Invalid chain type");
  6077. EVT VT = Val.getValueType();
  6078. SDVTList VTs = getVTList(MVT::Other);
  6079. SDValue Undef = getUNDEF(Ptr.getValueType());
  6080. SDValue Ops[] = { Chain, Val, Ptr, Undef };
  6081. FoldingSetNodeID ID;
  6082. AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
  6083. ID.AddInteger(VT.getRawBits());
  6084. ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>(
  6085. dl.getIROrder(), VTs, ISD::UNINDEXED, false, VT, MMO));
  6086. ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
  6087. void *IP = nullptr;
  6088. if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
  6089. cast<StoreSDNode>(E)->refineAlignment(MMO);
  6090. return SDValue(E, 0);
  6091. }
  6092. auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
  6093. ISD::UNINDEXED, false, VT, MMO);
  6094. createOperands(N, Ops);
  6095. CSEMap.InsertNode(N, IP);
  6096. InsertNode(N);
  6097. SDValue V(N, 0);
  6098. NewSDValueDbgMsg(V, "Creating new node: ", this);
  6099. return V;
  6100. }
  6101. SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val,
  6102. SDValue Ptr, MachinePointerInfo PtrInfo,
  6103. EVT SVT, unsigned Alignment,
  6104. MachineMemOperand::Flags MMOFlags,
  6105. const AAMDNodes &AAInfo) {
  6106. assert(Chain.getValueType() == MVT::Other &&
  6107. "Invalid chain type");
  6108. if (Alignment == 0) // Ensure that codegen never sees alignment 0
  6109. Alignment = getEVTAlignment(SVT);
  6110. MMOFlags |= MachineMemOperand::MOStore;
  6111. assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
  6112. if (PtrInfo.V.isNull())
  6113. PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
  6114. MachineFunction &MF = getMachineFunction();
  6115. MachineMemOperand *MMO = MF.getMachineMemOperand(
  6116. PtrInfo, MMOFlags, SVT.getStoreSize(), Alignment, AAInfo);
  6117. return getTruncStore(Chain, dl, Val, Ptr, SVT, MMO);
  6118. }
  6119. SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val,
  6120. SDValue Ptr, EVT SVT,
  6121. MachineMemOperand *MMO) {
  6122. EVT VT = Val.getValueType();
  6123. assert(Chain.getValueType() == MVT::Other &&
  6124. "Invalid chain type");
  6125. if (VT == SVT)
  6126. return getStore(Chain, dl, Val, Ptr, MMO);
  6127. assert(SVT.getScalarType().bitsLT(VT.getScalarType()) &&
  6128. "Should only be a truncating store, not extending!");
  6129. assert(VT.isInteger() == SVT.isInteger() &&
  6130. "Can't do FP-INT conversion!");
  6131. assert(VT.isVector() == SVT.isVector() &&
  6132. "Cannot use trunc store to convert to or from a vector!");
  6133. assert((!VT.isVector() ||
  6134. VT.getVectorNumElements() == SVT.getVectorNumElements()) &&
  6135. "Cannot use trunc store to change the number of vector elements!");
  6136. SDVTList VTs = getVTList(MVT::Other);
  6137. SDValue Undef = getUNDEF(Ptr.getValueType());
  6138. SDValue Ops[] = { Chain, Val, Ptr, Undef };
  6139. FoldingSetNodeID ID;
  6140. AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
  6141. ID.AddInteger(SVT.getRawBits());
  6142. ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>(
  6143. dl.getIROrder(), VTs, ISD::UNINDEXED, true, SVT, MMO));
  6144. ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
  6145. void *IP = nullptr;
  6146. if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
  6147. cast<StoreSDNode>(E)->refineAlignment(MMO);
  6148. return SDValue(E, 0);
  6149. }
  6150. auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
  6151. ISD::UNINDEXED, true, SVT, MMO);
  6152. createOperands(N, Ops);
  6153. CSEMap.InsertNode(N, IP);
  6154. InsertNode(N);
  6155. SDValue V(N, 0);
  6156. NewSDValueDbgMsg(V, "Creating new node: ", this);
  6157. return V;
  6158. }
  6159. SDValue SelectionDAG::getIndexedStore(SDValue OrigStore, const SDLoc &dl,
  6160. SDValue Base, SDValue Offset,
  6161. ISD::MemIndexedMode AM) {
  6162. StoreSDNode *ST = cast<StoreSDNode>(OrigStore);
  6163. assert(ST->getOffset().isUndef() && "Store is already a indexed store!");
  6164. SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
  6165. SDValue Ops[] = { ST->getChain(), ST->getValue(), Base, Offset };
  6166. FoldingSetNodeID ID;
  6167. AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
  6168. ID.AddInteger(ST->getMemoryVT().getRawBits());
  6169. ID.AddInteger(ST->getRawSubclassData());
  6170. ID.AddInteger(ST->getPointerInfo().getAddrSpace());
  6171. void *IP = nullptr;
  6172. if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
  6173. return SDValue(E, 0);
  6174. auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
  6175. ST->isTruncatingStore(), ST->getMemoryVT(),
  6176. ST->getMemOperand());
  6177. createOperands(N, Ops);
  6178. CSEMap.InsertNode(N, IP);
  6179. InsertNode(N);
  6180. SDValue V(N, 0);
  6181. NewSDValueDbgMsg(V, "Creating new node: ", this);
  6182. return V;
  6183. }
  6184. SDValue SelectionDAG::getMaskedLoad(EVT VT, const SDLoc &dl, SDValue Chain,
  6185. SDValue Ptr, SDValue Mask, SDValue PassThru,
  6186. EVT MemVT, MachineMemOperand *MMO,
  6187. ISD::LoadExtType ExtTy, bool isExpanding) {
  6188. SDVTList VTs = getVTList(VT, MVT::Other);
  6189. SDValue Ops[] = { Chain, Ptr, Mask, PassThru };
  6190. FoldingSetNodeID ID;
  6191. AddNodeIDNode(ID, ISD::MLOAD, VTs, Ops);
  6192. ID.AddInteger(VT.getRawBits());
  6193. ID.AddInteger(getSyntheticNodeSubclassData<MaskedLoadSDNode>(
  6194. dl.getIROrder(), VTs, ExtTy, isExpanding, MemVT, MMO));
  6195. ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
  6196. void *IP = nullptr;
  6197. if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
  6198. cast<MaskedLoadSDNode>(E)->refineAlignment(MMO);
  6199. return SDValue(E, 0);
  6200. }
  6201. auto *N = newSDNode<MaskedLoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
  6202. ExtTy, isExpanding, MemVT, MMO);
  6203. createOperands(N, Ops);
  6204. CSEMap.InsertNode(N, IP);
  6205. InsertNode(N);
  6206. SDValue V(N, 0);
  6207. NewSDValueDbgMsg(V, "Creating new node: ", this);
  6208. return V;
  6209. }
  6210. SDValue SelectionDAG::getMaskedStore(SDValue Chain, const SDLoc &dl,
  6211. SDValue Val, SDValue Ptr, SDValue Mask,
  6212. EVT MemVT, MachineMemOperand *MMO,
  6213. bool IsTruncating, bool IsCompressing) {
  6214. assert(Chain.getValueType() == MVT::Other &&
  6215. "Invalid chain type");
  6216. EVT VT = Val.getValueType();
  6217. SDVTList VTs = getVTList(MVT::Other);
  6218. SDValue Ops[] = { Chain, Val, Ptr, Mask };
  6219. FoldingSetNodeID ID;
  6220. AddNodeIDNode(ID, ISD::MSTORE, VTs, Ops);
  6221. ID.AddInteger(VT.getRawBits());
  6222. ID.AddInteger(getSyntheticNodeSubclassData<MaskedStoreSDNode>(
  6223. dl.getIROrder(), VTs, IsTruncating, IsCompressing, MemVT, MMO));
  6224. ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
  6225. void *IP = nullptr;
  6226. if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
  6227. cast<MaskedStoreSDNode>(E)->refineAlignment(MMO);
  6228. return SDValue(E, 0);
  6229. }
  6230. auto *N = newSDNode<MaskedStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
  6231. IsTruncating, IsCompressing, MemVT, MMO);
  6232. createOperands(N, Ops);
  6233. CSEMap.InsertNode(N, IP);
  6234. InsertNode(N);
  6235. SDValue V(N, 0);
  6236. NewSDValueDbgMsg(V, "Creating new node: ", this);
  6237. return V;
  6238. }
  6239. SDValue SelectionDAG::getMaskedGather(SDVTList VTs, EVT VT, const SDLoc &dl,
  6240. ArrayRef<SDValue> Ops,
  6241. MachineMemOperand *MMO) {
  6242. assert(Ops.size() == 6 && "Incompatible number of operands");
  6243. FoldingSetNodeID ID;
  6244. AddNodeIDNode(ID, ISD::MGATHER, VTs, Ops);
  6245. ID.AddInteger(VT.getRawBits());
  6246. ID.AddInteger(getSyntheticNodeSubclassData<MaskedGatherSDNode>(
  6247. dl.getIROrder(), VTs, VT, MMO));
  6248. ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
  6249. void *IP = nullptr;
  6250. if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
  6251. cast<MaskedGatherSDNode>(E)->refineAlignment(MMO);
  6252. return SDValue(E, 0);
  6253. }
  6254. auto *N = newSDNode<MaskedGatherSDNode>(dl.getIROrder(), dl.getDebugLoc(),
  6255. VTs, VT, MMO);
  6256. createOperands(N, Ops);
  6257. assert(N->getPassThru().getValueType() == N->getValueType(0) &&
  6258. "Incompatible type of the PassThru value in MaskedGatherSDNode");
  6259. assert(N->getMask().getValueType().getVectorNumElements() ==
  6260. N->getValueType(0).getVectorNumElements() &&
  6261. "Vector width mismatch between mask and data");
  6262. assert(N->getIndex().getValueType().getVectorNumElements() >=
  6263. N->getValueType(0).getVectorNumElements() &&
  6264. "Vector width mismatch between index and data");
  6265. assert(isa<ConstantSDNode>(N->getScale()) &&
  6266. cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() &&
  6267. "Scale should be a constant power of 2");
  6268. CSEMap.InsertNode(N, IP);
  6269. InsertNode(N);
  6270. SDValue V(N, 0);
  6271. NewSDValueDbgMsg(V, "Creating new node: ", this);
  6272. return V;
  6273. }
  6274. SDValue SelectionDAG::getMaskedScatter(SDVTList VTs, EVT VT, const SDLoc &dl,
  6275. ArrayRef<SDValue> Ops,
  6276. MachineMemOperand *MMO) {
  6277. assert(Ops.size() == 6 && "Incompatible number of operands");
  6278. FoldingSetNodeID ID;
  6279. AddNodeIDNode(ID, ISD::MSCATTER, VTs, Ops);
  6280. ID.AddInteger(VT.getRawBits());
  6281. ID.AddInteger(getSyntheticNodeSubclassData<MaskedScatterSDNode>(
  6282. dl.getIROrder(), VTs, VT, MMO));
  6283. ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
  6284. void *IP = nullptr;
  6285. if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
  6286. cast<MaskedScatterSDNode>(E)->refineAlignment(MMO);
  6287. return SDValue(E, 0);
  6288. }
  6289. auto *N = newSDNode<MaskedScatterSDNode>(dl.getIROrder(), dl.getDebugLoc(),
  6290. VTs, VT, MMO);
  6291. createOperands(N, Ops);
  6292. assert(N->getMask().getValueType().getVectorNumElements() ==
  6293. N->getValue().getValueType().getVectorNumElements() &&
  6294. "Vector width mismatch between mask and data");
  6295. assert(N->getIndex().getValueType().getVectorNumElements() >=
  6296. N->getValue().getValueType().getVectorNumElements() &&
  6297. "Vector width mismatch between index and data");
  6298. assert(isa<ConstantSDNode>(N->getScale()) &&
  6299. cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() &&
  6300. "Scale should be a constant power of 2");
  6301. CSEMap.InsertNode(N, IP);
  6302. InsertNode(N);
  6303. SDValue V(N, 0);
  6304. NewSDValueDbgMsg(V, "Creating new node: ", this);
  6305. return V;
  6306. }
  6307. SDValue SelectionDAG::simplifySelect(SDValue Cond, SDValue T, SDValue F) {
  6308. // select undef, T, F --> T (if T is a constant), otherwise F
  6309. // select, ?, undef, F --> F
  6310. // select, ?, T, undef --> T
  6311. if (Cond.isUndef())
  6312. return isConstantValueOfAnyType(T) ? T : F;
  6313. if (T.isUndef())
  6314. return F;
  6315. if (F.isUndef())
  6316. return T;
  6317. // select true, T, F --> T
  6318. // select false, T, F --> F
  6319. if (auto *CondC = dyn_cast<ConstantSDNode>(Cond))
  6320. return CondC->isNullValue() ? F : T;
  6321. // TODO: This should simplify VSELECT with constant condition using something
  6322. // like this (but check boolean contents to be complete?):
  6323. // if (ISD::isBuildVectorAllOnes(Cond.getNode()))
  6324. // return T;
  6325. // if (ISD::isBuildVectorAllZeros(Cond.getNode()))
  6326. // return F;
  6327. // select ?, T, T --> T
  6328. if (T == F)
  6329. return T;
  6330. return SDValue();
  6331. }
  6332. SDValue SelectionDAG::simplifyShift(SDValue X, SDValue Y) {
  6333. // shift undef, Y --> 0 (can always assume that the undef value is 0)
  6334. if (X.isUndef())
  6335. return getConstant(0, SDLoc(X.getNode()), X.getValueType());
  6336. // shift X, undef --> undef (because it may shift by the bitwidth)
  6337. if (Y.isUndef())
  6338. return getUNDEF(X.getValueType());
  6339. // shift 0, Y --> 0
  6340. // shift X, 0 --> X
  6341. if (isNullOrNullSplat(X) || isNullOrNullSplat(Y))
  6342. return X;
  6343. // shift X, C >= bitwidth(X) --> undef
  6344. // All vector elements must be too big (or undef) to avoid partial undefs.
  6345. auto isShiftTooBig = [X](ConstantSDNode *Val) {
  6346. return !Val || Val->getAPIntValue().uge(X.getScalarValueSizeInBits());
  6347. };
  6348. if (ISD::matchUnaryPredicate(Y, isShiftTooBig, true))
  6349. return getUNDEF(X.getValueType());
  6350. return SDValue();
  6351. }
  6352. // TODO: Use fast-math-flags to enable more simplifications.
  6353. SDValue SelectionDAG::simplifyFPBinop(unsigned Opcode, SDValue X, SDValue Y) {
  6354. ConstantFPSDNode *YC = isConstOrConstSplatFP(Y, /* AllowUndefs */ true);
  6355. if (!YC)
  6356. return SDValue();
  6357. // X + -0.0 --> X
  6358. if (Opcode == ISD::FADD)
  6359. if (YC->getValueAPF().isNegZero())
  6360. return X;
  6361. // X - +0.0 --> X
  6362. if (Opcode == ISD::FSUB)
  6363. if (YC->getValueAPF().isPosZero())
  6364. return X;
  6365. // X * 1.0 --> X
  6366. // X / 1.0 --> X
  6367. if (Opcode == ISD::FMUL || Opcode == ISD::FDIV)
  6368. if (YC->getValueAPF().isExactlyValue(1.0))
  6369. return X;
  6370. return SDValue();
  6371. }
  6372. SDValue SelectionDAG::getVAArg(EVT VT, const SDLoc &dl, SDValue Chain,
  6373. SDValue Ptr, SDValue SV, unsigned Align) {
  6374. SDValue Ops[] = { Chain, Ptr, SV, getTargetConstant(Align, dl, MVT::i32) };
  6375. return getNode(ISD::VAARG, dl, getVTList(VT, MVT::Other), Ops);
  6376. }
  6377. SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
  6378. ArrayRef<SDUse> Ops) {
  6379. switch (Ops.size()) {
  6380. case 0: return getNode(Opcode, DL, VT);
  6381. case 1: return getNode(Opcode, DL, VT, static_cast<const SDValue>(Ops[0]));
  6382. case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1]);
  6383. case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]);
  6384. default: break;
  6385. }
  6386. // Copy from an SDUse array into an SDValue array for use with
  6387. // the regular getNode logic.
  6388. SmallVector<SDValue, 8> NewOps(Ops.begin(), Ops.end());
  6389. return getNode(Opcode, DL, VT, NewOps);
  6390. }
  6391. SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
  6392. ArrayRef<SDValue> Ops, const SDNodeFlags Flags) {
  6393. unsigned NumOps = Ops.size();
  6394. switch (NumOps) {
  6395. case 0: return getNode(Opcode, DL, VT);
  6396. case 1: return getNode(Opcode, DL, VT, Ops[0], Flags);
  6397. case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Flags);
  6398. case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2], Flags);
  6399. default: break;
  6400. }
  6401. switch (Opcode) {
  6402. default: break;
  6403. case ISD::BUILD_VECTOR:
  6404. // Attempt to simplify BUILD_VECTOR.
  6405. if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
  6406. return V;
  6407. break;
  6408. case ISD::CONCAT_VECTORS:
  6409. // Attempt to fold CONCAT_VECTORS into BUILD_VECTOR or UNDEF.
  6410. if (SDValue V = FoldCONCAT_VECTORS(DL, VT, Ops, *this))
  6411. return V;
  6412. break;
  6413. case ISD::SELECT_CC:
  6414. assert(NumOps == 5 && "SELECT_CC takes 5 operands!");
  6415. assert(Ops[0].getValueType() == Ops[1].getValueType() &&
  6416. "LHS and RHS of condition must have same type!");
  6417. assert(Ops[2].getValueType() == Ops[3].getValueType() &&
  6418. "True and False arms of SelectCC must have same type!");
  6419. assert(Ops[2].getValueType() == VT &&
  6420. "select_cc node must be of same type as true and false value!");
  6421. break;
  6422. case ISD::BR_CC:
  6423. assert(NumOps == 5 && "BR_CC takes 5 operands!");
  6424. assert(Ops[2].getValueType() == Ops[3].getValueType() &&
  6425. "LHS/RHS of comparison should match types!");
  6426. break;
  6427. }
  6428. // Memoize nodes.
  6429. SDNode *N;
  6430. SDVTList VTs = getVTList(VT);
  6431. if (VT != MVT::Glue) {
  6432. FoldingSetNodeID ID;
  6433. AddNodeIDNode(ID, Opcode, VTs, Ops);
  6434. void *IP = nullptr;
  6435. if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
  6436. return SDValue(E, 0);
  6437. N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
  6438. createOperands(N, Ops);
  6439. CSEMap.InsertNode(N, IP);
  6440. } else {
  6441. N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
  6442. createOperands(N, Ops);
  6443. }
  6444. InsertNode(N);
  6445. SDValue V(N, 0);
  6446. NewSDValueDbgMsg(V, "Creating new node: ", this);
  6447. return V;
  6448. }
  6449. SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL,
  6450. ArrayRef<EVT> ResultTys, ArrayRef<SDValue> Ops) {
  6451. return getNode(Opcode, DL, getVTList(ResultTys), Ops);
  6452. }
  6453. SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
  6454. ArrayRef<SDValue> Ops) {
  6455. if (VTList.NumVTs == 1)
  6456. return getNode(Opcode, DL, VTList.VTs[0], Ops);
  6457. #if 0
  6458. switch (Opcode) {
  6459. // FIXME: figure out how to safely handle things like
  6460. // int foo(int x) { return 1 << (x & 255); }
  6461. // int bar() { return foo(256); }
  6462. case ISD::SRA_PARTS:
  6463. case ISD::SRL_PARTS:
  6464. case ISD::SHL_PARTS:
  6465. if (N3.getOpcode() == ISD::SIGN_EXTEND_INREG &&
  6466. cast<VTSDNode>(N3.getOperand(1))->getVT() != MVT::i1)
  6467. return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0));
  6468. else if (N3.getOpcode() == ISD::AND)
  6469. if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N3.getOperand(1))) {
  6470. // If the and is only masking out bits that cannot effect the shift,
  6471. // eliminate the and.
  6472. unsigned NumBits = VT.getScalarSizeInBits()*2;
  6473. if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1)
  6474. return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0));
  6475. }
  6476. break;
  6477. }
  6478. #endif
  6479. // Memoize the node unless it returns a flag.
  6480. SDNode *N;
  6481. if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
  6482. FoldingSetNodeID ID;
  6483. AddNodeIDNode(ID, Opcode, VTList, Ops);
  6484. void *IP = nullptr;
  6485. if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
  6486. return SDValue(E, 0);
  6487. N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList);
  6488. createOperands(N, Ops);
  6489. CSEMap.InsertNode(N, IP);
  6490. } else {
  6491. N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList);
  6492. createOperands(N, Ops);
  6493. }
  6494. InsertNode(N);
  6495. SDValue V(N, 0);
  6496. NewSDValueDbgMsg(V, "Creating new node: ", this);
  6497. return V;
  6498. }
  6499. SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL,
  6500. SDVTList VTList) {
  6501. return getNode(Opcode, DL, VTList, None);
  6502. }
  6503. SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
  6504. SDValue N1) {
  6505. SDValue Ops[] = { N1 };
  6506. return getNode(Opcode, DL, VTList, Ops);
  6507. }
  6508. SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
  6509. SDValue N1, SDValue N2) {
  6510. SDValue Ops[] = { N1, N2 };
  6511. return getNode(Opcode, DL, VTList, Ops);
  6512. }
  6513. SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
  6514. SDValue N1, SDValue N2, SDValue N3) {
  6515. SDValue Ops[] = { N1, N2, N3 };
  6516. return getNode(Opcode, DL, VTList, Ops);
  6517. }
  6518. SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
  6519. SDValue N1, SDValue N2, SDValue N3, SDValue N4) {
  6520. SDValue Ops[] = { N1, N2, N3, N4 };
  6521. return getNode(Opcode, DL, VTList, Ops);
  6522. }
  6523. SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
  6524. SDValue N1, SDValue N2, SDValue N3, SDValue N4,
  6525. SDValue N5) {
  6526. SDValue Ops[] = { N1, N2, N3, N4, N5 };
  6527. return getNode(Opcode, DL, VTList, Ops);
  6528. }
  6529. SDVTList SelectionDAG::getVTList(EVT VT) {
  6530. return makeVTList(SDNode::getValueTypeList(VT), 1);
  6531. }
  6532. SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2) {
  6533. FoldingSetNodeID ID;
  6534. ID.AddInteger(2U);
  6535. ID.AddInteger(VT1.getRawBits());
  6536. ID.AddInteger(VT2.getRawBits());
  6537. void *IP = nullptr;
  6538. SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
  6539. if (!Result) {
  6540. EVT *Array = Allocator.Allocate<EVT>(2);
  6541. Array[0] = VT1;
  6542. Array[1] = VT2;
  6543. Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 2);
  6544. VTListMap.InsertNode(Result, IP);
  6545. }
  6546. return Result->getSDVTList();
  6547. }
  6548. SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3) {
  6549. FoldingSetNodeID ID;
  6550. ID.AddInteger(3U);
  6551. ID.AddInteger(VT1.getRawBits());
  6552. ID.AddInteger(VT2.getRawBits());
  6553. ID.AddInteger(VT3.getRawBits());
  6554. void *IP = nullptr;
  6555. SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
  6556. if (!Result) {
  6557. EVT *Array = Allocator.Allocate<EVT>(3);
  6558. Array[0] = VT1;
  6559. Array[1] = VT2;
  6560. Array[2] = VT3;
  6561. Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 3);
  6562. VTListMap.InsertNode(Result, IP);
  6563. }
  6564. return Result->getSDVTList();
  6565. }
  6566. SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3, EVT VT4) {
  6567. FoldingSetNodeID ID;
  6568. ID.AddInteger(4U);
  6569. ID.AddInteger(VT1.getRawBits());
  6570. ID.AddInteger(VT2.getRawBits());
  6571. ID.AddInteger(VT3.getRawBits());
  6572. ID.AddInteger(VT4.getRawBits());
  6573. void *IP = nullptr;
  6574. SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
  6575. if (!Result) {
  6576. EVT *Array = Allocator.Allocate<EVT>(4);
  6577. Array[0] = VT1;
  6578. Array[1] = VT2;
  6579. Array[2] = VT3;
  6580. Array[3] = VT4;
  6581. Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 4);
  6582. VTListMap.InsertNode(Result, IP);
  6583. }
  6584. return Result->getSDVTList();
  6585. }
  6586. SDVTList SelectionDAG::getVTList(ArrayRef<EVT> VTs) {
  6587. unsigned NumVTs = VTs.size();
  6588. FoldingSetNodeID ID;
  6589. ID.AddInteger(NumVTs);
  6590. for (unsigned index = 0; index < NumVTs; index++) {
  6591. ID.AddInteger(VTs[index].getRawBits());
  6592. }
  6593. void *IP = nullptr;
  6594. SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
  6595. if (!Result) {
  6596. EVT *Array = Allocator.Allocate<EVT>(NumVTs);
  6597. llvm::copy(VTs, Array);
  6598. Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, NumVTs);
  6599. VTListMap.InsertNode(Result, IP);
  6600. }
  6601. return Result->getSDVTList();
  6602. }
  6603. /// UpdateNodeOperands - *Mutate* the specified node in-place to have the
  6604. /// specified operands. If the resultant node already exists in the DAG,
  6605. /// this does not modify the specified node, instead it returns the node that
  6606. /// already exists. If the resultant node does not exist in the DAG, the
  6607. /// input node is returned. As a degenerate case, if you specify the same
  6608. /// input operands as the node already has, the input node is returned.
  6609. SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op) {
  6610. assert(N->getNumOperands() == 1 && "Update with wrong number of operands");
  6611. // Check to see if there is no change.
  6612. if (Op == N->getOperand(0)) return N;
  6613. // See if the modified node already exists.
  6614. void *InsertPos = nullptr;
  6615. if (SDNode *Existing = FindModifiedNodeSlot(N, Op, InsertPos))
  6616. return Existing;
  6617. // Nope it doesn't. Remove the node from its current place in the maps.
  6618. if (InsertPos)
  6619. if (!RemoveNodeFromCSEMaps(N))
  6620. InsertPos = nullptr;
  6621. // Now we update the operands.
  6622. N->OperandList[0].set(Op);
  6623. updateDivergence(N);
  6624. // If this gets put into a CSE map, add it.
  6625. if (InsertPos) CSEMap.InsertNode(N, InsertPos);
  6626. return N;
  6627. }
  6628. SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2) {
  6629. assert(N->getNumOperands() == 2 && "Update with wrong number of operands");
  6630. // Check to see if there is no change.
  6631. if (Op1 == N->getOperand(0) && Op2 == N->getOperand(1))
  6632. return N; // No operands changed, just return the input node.
  6633. // See if the modified node already exists.
  6634. void *InsertPos = nullptr;
  6635. if (SDNode *Existing = FindModifiedNodeSlot(N, Op1, Op2, InsertPos))
  6636. return Existing;
  6637. // Nope it doesn't. Remove the node from its current place in the maps.
  6638. if (InsertPos)
  6639. if (!RemoveNodeFromCSEMaps(N))
  6640. InsertPos = nullptr;
  6641. // Now we update the operands.
  6642. if (N->OperandList[0] != Op1)
  6643. N->OperandList[0].set(Op1);
  6644. if (N->OperandList[1] != Op2)
  6645. N->OperandList[1].set(Op2);
  6646. updateDivergence(N);
  6647. // If this gets put into a CSE map, add it.
  6648. if (InsertPos) CSEMap.InsertNode(N, InsertPos);
  6649. return N;
  6650. }
  6651. SDNode *SelectionDAG::
  6652. UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2, SDValue Op3) {
  6653. SDValue Ops[] = { Op1, Op2, Op3 };
  6654. return UpdateNodeOperands(N, Ops);
  6655. }
  6656. SDNode *SelectionDAG::
  6657. UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2,
  6658. SDValue Op3, SDValue Op4) {
  6659. SDValue Ops[] = { Op1, Op2, Op3, Op4 };
  6660. return UpdateNodeOperands(N, Ops);
  6661. }
  6662. SDNode *SelectionDAG::
  6663. UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2,
  6664. SDValue Op3, SDValue Op4, SDValue Op5) {
  6665. SDValue Ops[] = { Op1, Op2, Op3, Op4, Op5 };
  6666. return UpdateNodeOperands(N, Ops);
  6667. }
  6668. SDNode *SelectionDAG::
  6669. UpdateNodeOperands(SDNode *N, ArrayRef<SDValue> Ops) {
  6670. unsigned NumOps = Ops.size();
  6671. assert(N->getNumOperands() == NumOps &&
  6672. "Update with wrong number of operands");
  6673. // If no operands changed just return the input node.
  6674. if (std::equal(Ops.begin(), Ops.end(), N->op_begin()))
  6675. return N;
  6676. // See if the modified node already exists.
  6677. void *InsertPos = nullptr;
  6678. if (SDNode *Existing = FindModifiedNodeSlot(N, Ops, InsertPos))
  6679. return Existing;
  6680. // Nope it doesn't. Remove the node from its current place in the maps.
  6681. if (InsertPos)
  6682. if (!RemoveNodeFromCSEMaps(N))
  6683. InsertPos = nullptr;
  6684. // Now we update the operands.
  6685. for (unsigned i = 0; i != NumOps; ++i)
  6686. if (N->OperandList[i] != Ops[i])
  6687. N->OperandList[i].set(Ops[i]);
  6688. updateDivergence(N);
  6689. // If this gets put into a CSE map, add it.
  6690. if (InsertPos) CSEMap.InsertNode(N, InsertPos);
  6691. return N;
  6692. }
  6693. /// DropOperands - Release the operands and set this node to have
  6694. /// zero operands.
  6695. void SDNode::DropOperands() {
  6696. // Unlike the code in MorphNodeTo that does this, we don't need to
  6697. // watch for dead nodes here.
  6698. for (op_iterator I = op_begin(), E = op_end(); I != E; ) {
  6699. SDUse &Use = *I++;
  6700. Use.set(SDValue());
  6701. }
  6702. }
  6703. void SelectionDAG::setNodeMemRefs(MachineSDNode *N,
  6704. ArrayRef<MachineMemOperand *> NewMemRefs) {
  6705. if (NewMemRefs.empty()) {
  6706. N->clearMemRefs();
  6707. return;
  6708. }
  6709. // Check if we can avoid allocating by storing a single reference directly.
  6710. if (NewMemRefs.size() == 1) {
  6711. N->MemRefs = NewMemRefs[0];
  6712. N->NumMemRefs = 1;
  6713. return;
  6714. }
  6715. MachineMemOperand **MemRefsBuffer =
  6716. Allocator.template Allocate<MachineMemOperand *>(NewMemRefs.size());
  6717. llvm::copy(NewMemRefs, MemRefsBuffer);
  6718. N->MemRefs = MemRefsBuffer;
  6719. N->NumMemRefs = static_cast<int>(NewMemRefs.size());
  6720. }
  6721. /// SelectNodeTo - These are wrappers around MorphNodeTo that accept a
  6722. /// machine opcode.
  6723. ///
  6724. SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
  6725. EVT VT) {
  6726. SDVTList VTs = getVTList(VT);
  6727. return SelectNodeTo(N, MachineOpc, VTs, None);
  6728. }
  6729. SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
  6730. EVT VT, SDValue Op1) {
  6731. SDVTList VTs = getVTList(VT);
  6732. SDValue Ops[] = { Op1 };
  6733. return SelectNodeTo(N, MachineOpc, VTs, Ops);
  6734. }
  6735. SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
  6736. EVT VT, SDValue Op1,
  6737. SDValue Op2) {
  6738. SDVTList VTs = getVTList(VT);
  6739. SDValue Ops[] = { Op1, Op2 };
  6740. return SelectNodeTo(N, MachineOpc, VTs, Ops);
  6741. }
  6742. SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
  6743. EVT VT, SDValue Op1,
  6744. SDValue Op2, SDValue Op3) {
  6745. SDVTList VTs = getVTList(VT);
  6746. SDValue Ops[] = { Op1, Op2, Op3 };
  6747. return SelectNodeTo(N, MachineOpc, VTs, Ops);
  6748. }
  6749. SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
  6750. EVT VT, ArrayRef<SDValue> Ops) {
  6751. SDVTList VTs = getVTList(VT);
  6752. return SelectNodeTo(N, MachineOpc, VTs, Ops);
  6753. }
  6754. SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
  6755. EVT VT1, EVT VT2, ArrayRef<SDValue> Ops) {
  6756. SDVTList VTs = getVTList(VT1, VT2);
  6757. return SelectNodeTo(N, MachineOpc, VTs, Ops);
  6758. }
  6759. SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
  6760. EVT VT1, EVT VT2) {
  6761. SDVTList VTs = getVTList(VT1, VT2);
  6762. return SelectNodeTo(N, MachineOpc, VTs, None);
  6763. }
  6764. SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
  6765. EVT VT1, EVT VT2, EVT VT3,
  6766. ArrayRef<SDValue> Ops) {
  6767. SDVTList VTs = getVTList(VT1, VT2, VT3);
  6768. return SelectNodeTo(N, MachineOpc, VTs, Ops);
  6769. }
  6770. SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
  6771. EVT VT1, EVT VT2,
  6772. SDValue Op1, SDValue Op2) {
  6773. SDVTList VTs = getVTList(VT1, VT2);
  6774. SDValue Ops[] = { Op1, Op2 };
  6775. return SelectNodeTo(N, MachineOpc, VTs, Ops);
  6776. }
  6777. SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
  6778. SDVTList VTs,ArrayRef<SDValue> Ops) {
  6779. SDNode *New = MorphNodeTo(N, ~MachineOpc, VTs, Ops);
  6780. // Reset the NodeID to -1.
  6781. New->setNodeId(-1);
  6782. if (New != N) {
  6783. ReplaceAllUsesWith(N, New);
  6784. RemoveDeadNode(N);
  6785. }
  6786. return New;
  6787. }
  6788. /// UpdateSDLocOnMergeSDNode - If the opt level is -O0 then it throws away
  6789. /// the line number information on the merged node since it is not possible to
  6790. /// preserve the information that operation is associated with multiple lines.
  6791. /// This will make the debugger working better at -O0, were there is a higher
  6792. /// probability having other instructions associated with that line.
  6793. ///
  6794. /// For IROrder, we keep the smaller of the two
  6795. SDNode *SelectionDAG::UpdateSDLocOnMergeSDNode(SDNode *N, const SDLoc &OLoc) {
  6796. DebugLoc NLoc = N->getDebugLoc();
  6797. if (NLoc && OptLevel == CodeGenOpt::None && OLoc.getDebugLoc() != NLoc) {
  6798. N->setDebugLoc(DebugLoc());
  6799. }
  6800. unsigned Order = std::min(N->getIROrder(), OLoc.getIROrder());
  6801. N->setIROrder(Order);
  6802. return N;
  6803. }
  6804. /// MorphNodeTo - This *mutates* the specified node to have the specified
  6805. /// return type, opcode, and operands.
  6806. ///
  6807. /// Note that MorphNodeTo returns the resultant node. If there is already a
  6808. /// node of the specified opcode and operands, it returns that node instead of
  6809. /// the current one. Note that the SDLoc need not be the same.
  6810. ///
  6811. /// Using MorphNodeTo is faster than creating a new node and swapping it in
  6812. /// with ReplaceAllUsesWith both because it often avoids allocating a new
  6813. /// node, and because it doesn't require CSE recalculation for any of
  6814. /// the node's users.
  6815. ///
  6816. /// However, note that MorphNodeTo recursively deletes dead nodes from the DAG.
  6817. /// As a consequence it isn't appropriate to use from within the DAG combiner or
  6818. /// the legalizer which maintain worklists that would need to be updated when
  6819. /// deleting things.
  6820. SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
  6821. SDVTList VTs, ArrayRef<SDValue> Ops) {
  6822. // If an identical node already exists, use it.
  6823. void *IP = nullptr;
  6824. if (VTs.VTs[VTs.NumVTs-1] != MVT::Glue) {
  6825. FoldingSetNodeID ID;
  6826. AddNodeIDNode(ID, Opc, VTs, Ops);
  6827. if (SDNode *ON = FindNodeOrInsertPos(ID, SDLoc(N), IP))
  6828. return UpdateSDLocOnMergeSDNode(ON, SDLoc(N));
  6829. }
  6830. if (!RemoveNodeFromCSEMaps(N))
  6831. IP = nullptr;
  6832. // Start the morphing.
  6833. N->NodeType = Opc;
  6834. N->ValueList = VTs.VTs;
  6835. N->NumValues = VTs.NumVTs;
  6836. // Clear the operands list, updating used nodes to remove this from their
  6837. // use list. Keep track of any operands that become dead as a result.
  6838. SmallPtrSet<SDNode*, 16> DeadNodeSet;
  6839. for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
  6840. SDUse &Use = *I++;
  6841. SDNode *Used = Use.getNode();
  6842. Use.set(SDValue());
  6843. if (Used->use_empty())
  6844. DeadNodeSet.insert(Used);
  6845. }
  6846. // For MachineNode, initialize the memory references information.
  6847. if (MachineSDNode *MN = dyn_cast<MachineSDNode>(N))
  6848. MN->clearMemRefs();
  6849. // Swap for an appropriately sized array from the recycler.
  6850. removeOperands(N);
  6851. createOperands(N, Ops);
  6852. // Delete any nodes that are still dead after adding the uses for the
  6853. // new operands.
  6854. if (!DeadNodeSet.empty()) {
  6855. SmallVector<SDNode *, 16> DeadNodes;
  6856. for (SDNode *N : DeadNodeSet)
  6857. if (N->use_empty())
  6858. DeadNodes.push_back(N);
  6859. RemoveDeadNodes(DeadNodes);
  6860. }
  6861. if (IP)
  6862. CSEMap.InsertNode(N, IP); // Memoize the new node.
  6863. return N;
  6864. }
  6865. SDNode* SelectionDAG::mutateStrictFPToFP(SDNode *Node) {
  6866. unsigned OrigOpc = Node->getOpcode();
  6867. unsigned NewOpc;
  6868. bool IsUnary = false;
  6869. bool IsTernary = false;
  6870. switch (OrigOpc) {
  6871. default:
  6872. llvm_unreachable("mutateStrictFPToFP called with unexpected opcode!");
  6873. case ISD::STRICT_FADD: NewOpc = ISD::FADD; break;
  6874. case ISD::STRICT_FSUB: NewOpc = ISD::FSUB; break;
  6875. case ISD::STRICT_FMUL: NewOpc = ISD::FMUL; break;
  6876. case ISD::STRICT_FDIV: NewOpc = ISD::FDIV; break;
  6877. case ISD::STRICT_FREM: NewOpc = ISD::FREM; break;
  6878. case ISD::STRICT_FMA: NewOpc = ISD::FMA; IsTernary = true; break;
  6879. case ISD::STRICT_FSQRT: NewOpc = ISD::FSQRT; IsUnary = true; break;
  6880. case ISD::STRICT_FPOW: NewOpc = ISD::FPOW; break;
  6881. case ISD::STRICT_FPOWI: NewOpc = ISD::FPOWI; break;
  6882. case ISD::STRICT_FSIN: NewOpc = ISD::FSIN; IsUnary = true; break;
  6883. case ISD::STRICT_FCOS: NewOpc = ISD::FCOS; IsUnary = true; break;
  6884. case ISD::STRICT_FEXP: NewOpc = ISD::FEXP; IsUnary = true; break;
  6885. case ISD::STRICT_FEXP2: NewOpc = ISD::FEXP2; IsUnary = true; break;
  6886. case ISD::STRICT_FLOG: NewOpc = ISD::FLOG; IsUnary = true; break;
  6887. case ISD::STRICT_FLOG10: NewOpc = ISD::FLOG10; IsUnary = true; break;
  6888. case ISD::STRICT_FLOG2: NewOpc = ISD::FLOG2; IsUnary = true; break;
  6889. case ISD::STRICT_FRINT: NewOpc = ISD::FRINT; IsUnary = true; break;
  6890. case ISD::STRICT_FNEARBYINT:
  6891. NewOpc = ISD::FNEARBYINT;
  6892. IsUnary = true;
  6893. break;
  6894. case ISD::STRICT_FMAXNUM: NewOpc = ISD::FMAXNUM; break;
  6895. case ISD::STRICT_FMINNUM: NewOpc = ISD::FMINNUM; break;
  6896. case ISD::STRICT_FCEIL: NewOpc = ISD::FCEIL; IsUnary = true; break;
  6897. case ISD::STRICT_FFLOOR: NewOpc = ISD::FFLOOR; IsUnary = true; break;
  6898. case ISD::STRICT_FROUND: NewOpc = ISD::FROUND; IsUnary = true; break;
  6899. case ISD::STRICT_FTRUNC: NewOpc = ISD::FTRUNC; IsUnary = true; break;
  6900. }
  6901. // We're taking this node out of the chain, so we need to re-link things.
  6902. SDValue InputChain = Node->getOperand(0);
  6903. SDValue OutputChain = SDValue(Node, 1);
  6904. ReplaceAllUsesOfValueWith(OutputChain, InputChain);
  6905. SDVTList VTs = getVTList(Node->getOperand(1).getValueType());
  6906. SDNode *Res = nullptr;
  6907. if (IsUnary)
  6908. Res = MorphNodeTo(Node, NewOpc, VTs, { Node->getOperand(1) });
  6909. else if (IsTernary)
  6910. Res = MorphNodeTo(Node, NewOpc, VTs, { Node->getOperand(1),
  6911. Node->getOperand(2),
  6912. Node->getOperand(3)});
  6913. else
  6914. Res = MorphNodeTo(Node, NewOpc, VTs, { Node->getOperand(1),
  6915. Node->getOperand(2) });
  6916. // MorphNodeTo can operate in two ways: if an existing node with the
  6917. // specified operands exists, it can just return it. Otherwise, it
  6918. // updates the node in place to have the requested operands.
  6919. if (Res == Node) {
  6920. // If we updated the node in place, reset the node ID. To the isel,
  6921. // this should be just like a newly allocated machine node.
  6922. Res->setNodeId(-1);
  6923. } else {
  6924. ReplaceAllUsesWith(Node, Res);
  6925. RemoveDeadNode(Node);
  6926. }
  6927. return Res;
  6928. }
  6929. /// getMachineNode - These are used for target selectors to create a new node
  6930. /// with specified return type(s), MachineInstr opcode, and operands.
  6931. ///
  6932. /// Note that getMachineNode returns the resultant node. If there is already a
  6933. /// node of the specified opcode and operands, it returns that node instead of
  6934. /// the current one.
  6935. MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
  6936. EVT VT) {
  6937. SDVTList VTs = getVTList(VT);
  6938. return getMachineNode(Opcode, dl, VTs, None);
  6939. }
  6940. MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
  6941. EVT VT, SDValue Op1) {
  6942. SDVTList VTs = getVTList(VT);
  6943. SDValue Ops[] = { Op1 };
  6944. return getMachineNode(Opcode, dl, VTs, Ops);
  6945. }
  6946. MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
  6947. EVT VT, SDValue Op1, SDValue Op2) {
  6948. SDVTList VTs = getVTList(VT);
  6949. SDValue Ops[] = { Op1, Op2 };
  6950. return getMachineNode(Opcode, dl, VTs, Ops);
  6951. }
  6952. MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
  6953. EVT VT, SDValue Op1, SDValue Op2,
  6954. SDValue Op3) {
  6955. SDVTList VTs = getVTList(VT);
  6956. SDValue Ops[] = { Op1, Op2, Op3 };
  6957. return getMachineNode(Opcode, dl, VTs, Ops);
  6958. }
  6959. MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
  6960. EVT VT, ArrayRef<SDValue> Ops) {
  6961. SDVTList VTs = getVTList(VT);
  6962. return getMachineNode(Opcode, dl, VTs, Ops);
  6963. }
  6964. MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
  6965. EVT VT1, EVT VT2, SDValue Op1,
  6966. SDValue Op2) {
  6967. SDVTList VTs = getVTList(VT1, VT2);
  6968. SDValue Ops[] = { Op1, Op2 };
  6969. return getMachineNode(Opcode, dl, VTs, Ops);
  6970. }
  6971. MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
  6972. EVT VT1, EVT VT2, SDValue Op1,
  6973. SDValue Op2, SDValue Op3) {
  6974. SDVTList VTs = getVTList(VT1, VT2);
  6975. SDValue Ops[] = { Op1, Op2, Op3 };
  6976. return getMachineNode(Opcode, dl, VTs, Ops);
  6977. }
  6978. MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
  6979. EVT VT1, EVT VT2,
  6980. ArrayRef<SDValue> Ops) {
  6981. SDVTList VTs = getVTList(VT1, VT2);
  6982. return getMachineNode(Opcode, dl, VTs, Ops);
  6983. }
  6984. MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
  6985. EVT VT1, EVT VT2, EVT VT3,
  6986. SDValue Op1, SDValue Op2) {
  6987. SDVTList VTs = getVTList(VT1, VT2, VT3);
  6988. SDValue Ops[] = { Op1, Op2 };
  6989. return getMachineNode(Opcode, dl, VTs, Ops);
  6990. }
  6991. MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
  6992. EVT VT1, EVT VT2, EVT VT3,
  6993. SDValue Op1, SDValue Op2,
  6994. SDValue Op3) {
  6995. SDVTList VTs = getVTList(VT1, VT2, VT3);
  6996. SDValue Ops[] = { Op1, Op2, Op3 };
  6997. return getMachineNode(Opcode, dl, VTs, Ops);
  6998. }
  6999. MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
  7000. EVT VT1, EVT VT2, EVT VT3,
  7001. ArrayRef<SDValue> Ops) {
  7002. SDVTList VTs = getVTList(VT1, VT2, VT3);
  7003. return getMachineNode(Opcode, dl, VTs, Ops);
  7004. }
  7005. MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
  7006. ArrayRef<EVT> ResultTys,
  7007. ArrayRef<SDValue> Ops) {
  7008. SDVTList VTs = getVTList(ResultTys);
  7009. return getMachineNode(Opcode, dl, VTs, Ops);
  7010. }
  7011. MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &DL,
  7012. SDVTList VTs,
  7013. ArrayRef<SDValue> Ops) {
  7014. bool DoCSE = VTs.VTs[VTs.NumVTs-1] != MVT::Glue;
  7015. MachineSDNode *N;
  7016. void *IP = nullptr;
  7017. if (DoCSE) {
  7018. FoldingSetNodeID ID;
  7019. AddNodeIDNode(ID, ~Opcode, VTs, Ops);
  7020. IP = nullptr;
  7021. if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
  7022. return cast<MachineSDNode>(UpdateSDLocOnMergeSDNode(E, DL));
  7023. }
  7024. }
  7025. // Allocate a new MachineSDNode.
  7026. N = newSDNode<MachineSDNode>(~Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
  7027. createOperands(N, Ops);
  7028. if (DoCSE)
  7029. CSEMap.InsertNode(N, IP);
  7030. InsertNode(N);
  7031. return N;
  7032. }
  7033. /// getTargetExtractSubreg - A convenience function for creating
  7034. /// TargetOpcode::EXTRACT_SUBREG nodes.
  7035. SDValue SelectionDAG::getTargetExtractSubreg(int SRIdx, const SDLoc &DL, EVT VT,
  7036. SDValue Operand) {
  7037. SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32);
  7038. SDNode *Subreg = getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL,
  7039. VT, Operand, SRIdxVal);
  7040. return SDValue(Subreg, 0);
  7041. }
  7042. /// getTargetInsertSubreg - A convenience function for creating
  7043. /// TargetOpcode::INSERT_SUBREG nodes.
  7044. SDValue SelectionDAG::getTargetInsertSubreg(int SRIdx, const SDLoc &DL, EVT VT,
  7045. SDValue Operand, SDValue Subreg) {
  7046. SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32);
  7047. SDNode *Result = getMachineNode(TargetOpcode::INSERT_SUBREG, DL,
  7048. VT, Operand, Subreg, SRIdxVal);
  7049. return SDValue(Result, 0);
  7050. }
  7051. /// getNodeIfExists - Get the specified node if it's already available, or
  7052. /// else return NULL.
  7053. SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList,
  7054. ArrayRef<SDValue> Ops,
  7055. const SDNodeFlags Flags) {
  7056. if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) {
  7057. FoldingSetNodeID ID;
  7058. AddNodeIDNode(ID, Opcode, VTList, Ops);
  7059. void *IP = nullptr;
  7060. if (SDNode *E = FindNodeOrInsertPos(ID, SDLoc(), IP)) {
  7061. E->intersectFlagsWith(Flags);
  7062. return E;
  7063. }
  7064. }
  7065. return nullptr;
  7066. }
  7067. /// getDbgValue - Creates a SDDbgValue node.
  7068. ///
  7069. /// SDNode
  7070. SDDbgValue *SelectionDAG::getDbgValue(DIVariable *Var, DIExpression *Expr,
  7071. SDNode *N, unsigned R, bool IsIndirect,
  7072. const DebugLoc &DL, unsigned O) {
  7073. assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
  7074. "Expected inlined-at fields to agree");
  7075. return new (DbgInfo->getAlloc())
  7076. SDDbgValue(Var, Expr, N, R, IsIndirect, DL, O);
  7077. }
  7078. /// Constant
  7079. SDDbgValue *SelectionDAG::getConstantDbgValue(DIVariable *Var,
  7080. DIExpression *Expr,
  7081. const Value *C,
  7082. const DebugLoc &DL, unsigned O) {
  7083. assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
  7084. "Expected inlined-at fields to agree");
  7085. return new (DbgInfo->getAlloc()) SDDbgValue(Var, Expr, C, DL, O);
  7086. }
  7087. /// FrameIndex
  7088. SDDbgValue *SelectionDAG::getFrameIndexDbgValue(DIVariable *Var,
  7089. DIExpression *Expr, unsigned FI,
  7090. bool IsIndirect,
  7091. const DebugLoc &DL,
  7092. unsigned O) {
  7093. assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
  7094. "Expected inlined-at fields to agree");
  7095. return new (DbgInfo->getAlloc())
  7096. SDDbgValue(Var, Expr, FI, IsIndirect, DL, O, SDDbgValue::FRAMEIX);
  7097. }
  7098. /// VReg
  7099. SDDbgValue *SelectionDAG::getVRegDbgValue(DIVariable *Var,
  7100. DIExpression *Expr,
  7101. unsigned VReg, bool IsIndirect,
  7102. const DebugLoc &DL, unsigned O) {
  7103. assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
  7104. "Expected inlined-at fields to agree");
  7105. return new (DbgInfo->getAlloc())
  7106. SDDbgValue(Var, Expr, VReg, IsIndirect, DL, O, SDDbgValue::VREG);
  7107. }
  7108. void SelectionDAG::transferDbgValues(SDValue From, SDValue To,
  7109. unsigned OffsetInBits, unsigned SizeInBits,
  7110. bool InvalidateDbg) {
  7111. SDNode *FromNode = From.getNode();
  7112. SDNode *ToNode = To.getNode();
  7113. assert(FromNode && ToNode && "Can't modify dbg values");
  7114. // PR35338
  7115. // TODO: assert(From != To && "Redundant dbg value transfer");
  7116. // TODO: assert(FromNode != ToNode && "Intranode dbg value transfer");
  7117. if (From == To || FromNode == ToNode)
  7118. return;
  7119. if (!FromNode->getHasDebugValue())
  7120. return;
  7121. SmallVector<SDDbgValue *, 2> ClonedDVs;
  7122. for (SDDbgValue *Dbg : GetDbgValues(FromNode)) {
  7123. if (Dbg->getKind() != SDDbgValue::SDNODE || Dbg->isInvalidated())
  7124. continue;
  7125. // TODO: assert(!Dbg->isInvalidated() && "Transfer of invalid dbg value");
  7126. // Just transfer the dbg value attached to From.
  7127. if (Dbg->getResNo() != From.getResNo())
  7128. continue;
  7129. DIVariable *Var = Dbg->getVariable();
  7130. auto *Expr = Dbg->getExpression();
  7131. // If a fragment is requested, update the expression.
  7132. if (SizeInBits) {
  7133. // When splitting a larger (e.g., sign-extended) value whose
  7134. // lower bits are described with an SDDbgValue, do not attempt
  7135. // to transfer the SDDbgValue to the upper bits.
  7136. if (auto FI = Expr->getFragmentInfo())
  7137. if (OffsetInBits + SizeInBits > FI->SizeInBits)
  7138. continue;
  7139. auto Fragment = DIExpression::createFragmentExpression(Expr, OffsetInBits,
  7140. SizeInBits);
  7141. if (!Fragment)
  7142. continue;
  7143. Expr = *Fragment;
  7144. }
  7145. // Clone the SDDbgValue and move it to To.
  7146. SDDbgValue *Clone =
  7147. getDbgValue(Var, Expr, ToNode, To.getResNo(), Dbg->isIndirect(),
  7148. Dbg->getDebugLoc(), Dbg->getOrder());
  7149. ClonedDVs.push_back(Clone);
  7150. if (InvalidateDbg) {
  7151. // Invalidate value and indicate the SDDbgValue should not be emitted.
  7152. Dbg->setIsInvalidated();
  7153. Dbg->setIsEmitted();
  7154. }
  7155. }
  7156. for (SDDbgValue *Dbg : ClonedDVs)
  7157. AddDbgValue(Dbg, ToNode, false);
  7158. }
  7159. void SelectionDAG::salvageDebugInfo(SDNode &N) {
  7160. if (!N.getHasDebugValue())
  7161. return;
  7162. SmallVector<SDDbgValue *, 2> ClonedDVs;
  7163. for (auto DV : GetDbgValues(&N)) {
  7164. if (DV->isInvalidated())
  7165. continue;
  7166. switch (N.getOpcode()) {
  7167. default:
  7168. break;
  7169. case ISD::ADD:
  7170. SDValue N0 = N.getOperand(0);
  7171. SDValue N1 = N.getOperand(1);
  7172. if (!isConstantIntBuildVectorOrConstantInt(N0) &&
  7173. isConstantIntBuildVectorOrConstantInt(N1)) {
  7174. uint64_t Offset = N.getConstantOperandVal(1);
  7175. // Rewrite an ADD constant node into a DIExpression. Since we are
  7176. // performing arithmetic to compute the variable's *value* in the
  7177. // DIExpression, we need to mark the expression with a
  7178. // DW_OP_stack_value.
  7179. auto *DIExpr = DV->getExpression();
  7180. DIExpr = DIExpression::prepend(DIExpr, DIExpression::NoDeref, Offset,
  7181. DIExpression::NoDeref,
  7182. DIExpression::WithStackValue);
  7183. SDDbgValue *Clone =
  7184. getDbgValue(DV->getVariable(), DIExpr, N0.getNode(), N0.getResNo(),
  7185. DV->isIndirect(), DV->getDebugLoc(), DV->getOrder());
  7186. ClonedDVs.push_back(Clone);
  7187. DV->setIsInvalidated();
  7188. DV->setIsEmitted();
  7189. LLVM_DEBUG(dbgs() << "SALVAGE: Rewriting";
  7190. N0.getNode()->dumprFull(this);
  7191. dbgs() << " into " << *DIExpr << '\n');
  7192. }
  7193. }
  7194. }
  7195. for (SDDbgValue *Dbg : ClonedDVs)
  7196. AddDbgValue(Dbg, Dbg->getSDNode(), false);
  7197. }
  7198. /// Creates a SDDbgLabel node.
  7199. SDDbgLabel *SelectionDAG::getDbgLabel(DILabel *Label,
  7200. const DebugLoc &DL, unsigned O) {
  7201. assert(cast<DILabel>(Label)->isValidLocationForIntrinsic(DL) &&
  7202. "Expected inlined-at fields to agree");
  7203. return new (DbgInfo->getAlloc()) SDDbgLabel(Label, DL, O);
  7204. }
  7205. namespace {
  7206. /// RAUWUpdateListener - Helper for ReplaceAllUsesWith - When the node
  7207. /// pointed to by a use iterator is deleted, increment the use iterator
  7208. /// so that it doesn't dangle.
  7209. ///
  7210. class RAUWUpdateListener : public SelectionDAG::DAGUpdateListener {
  7211. SDNode::use_iterator &UI;
  7212. SDNode::use_iterator &UE;
  7213. void NodeDeleted(SDNode *N, SDNode *E) override {
  7214. // Increment the iterator as needed.
  7215. while (UI != UE && N == *UI)
  7216. ++UI;
  7217. }
  7218. public:
  7219. RAUWUpdateListener(SelectionDAG &d,
  7220. SDNode::use_iterator &ui,
  7221. SDNode::use_iterator &ue)
  7222. : SelectionDAG::DAGUpdateListener(d), UI(ui), UE(ue) {}
  7223. };
  7224. } // end anonymous namespace
  7225. /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
  7226. /// This can cause recursive merging of nodes in the DAG.
  7227. ///
  7228. /// This version assumes From has a single result value.
  7229. ///
  7230. void SelectionDAG::ReplaceAllUsesWith(SDValue FromN, SDValue To) {
  7231. SDNode *From = FromN.getNode();
  7232. assert(From->getNumValues() == 1 && FromN.getResNo() == 0 &&
  7233. "Cannot replace with this method!");
  7234. assert(From != To.getNode() && "Cannot replace uses of with self");
  7235. // Preserve Debug Values
  7236. transferDbgValues(FromN, To);
  7237. // Iterate over all the existing uses of From. New uses will be added
  7238. // to the beginning of the use list, which we avoid visiting.
  7239. // This specifically avoids visiting uses of From that arise while the
  7240. // replacement is happening, because any such uses would be the result
  7241. // of CSE: If an existing node looks like From after one of its operands
  7242. // is replaced by To, we don't want to replace of all its users with To
  7243. // too. See PR3018 for more info.
  7244. SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
  7245. RAUWUpdateListener Listener(*this, UI, UE);
  7246. while (UI != UE) {
  7247. SDNode *User = *UI;
  7248. // This node is about to morph, remove its old self from the CSE maps.
  7249. RemoveNodeFromCSEMaps(User);
  7250. // A user can appear in a use list multiple times, and when this
  7251. // happens the uses are usually next to each other in the list.
  7252. // To help reduce the number of CSE recomputations, process all
  7253. // the uses of this user that we can find this way.
  7254. do {
  7255. SDUse &Use = UI.getUse();
  7256. ++UI;
  7257. Use.set(To);
  7258. if (To->isDivergent() != From->isDivergent())
  7259. updateDivergence(User);
  7260. } while (UI != UE && *UI == User);
  7261. // Now that we have modified User, add it back to the CSE maps. If it
  7262. // already exists there, recursively merge the results together.
  7263. AddModifiedNodeToCSEMaps(User);
  7264. }
  7265. // If we just RAUW'd the root, take note.
  7266. if (FromN == getRoot())
  7267. setRoot(To);
  7268. }
  7269. /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
  7270. /// This can cause recursive merging of nodes in the DAG.
  7271. ///
  7272. /// This version assumes that for each value of From, there is a
  7273. /// corresponding value in To in the same position with the same type.
  7274. ///
  7275. void SelectionDAG::ReplaceAllUsesWith(SDNode *From, SDNode *To) {
  7276. #ifndef NDEBUG
  7277. for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
  7278. assert((!From->hasAnyUseOfValue(i) ||
  7279. From->getValueType(i) == To->getValueType(i)) &&
  7280. "Cannot use this version of ReplaceAllUsesWith!");
  7281. #endif
  7282. // Handle the trivial case.
  7283. if (From == To)
  7284. return;
  7285. // Preserve Debug Info. Only do this if there's a use.
  7286. for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
  7287. if (From->hasAnyUseOfValue(i)) {
  7288. assert((i < To->getNumValues()) && "Invalid To location");
  7289. transferDbgValues(SDValue(From, i), SDValue(To, i));
  7290. }
  7291. // Iterate over just the existing users of From. See the comments in
  7292. // the ReplaceAllUsesWith above.
  7293. SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
  7294. RAUWUpdateListener Listener(*this, UI, UE);
  7295. while (UI != UE) {
  7296. SDNode *User = *UI;
  7297. // This node is about to morph, remove its old self from the CSE maps.
  7298. RemoveNodeFromCSEMaps(User);
  7299. // A user can appear in a use list multiple times, and when this
  7300. // happens the uses are usually next to each other in the list.
  7301. // To help reduce the number of CSE recomputations, process all
  7302. // the uses of this user that we can find this way.
  7303. do {
  7304. SDUse &Use = UI.getUse();
  7305. ++UI;
  7306. Use.setNode(To);
  7307. if (To->isDivergent() != From->isDivergent())
  7308. updateDivergence(User);
  7309. } while (UI != UE && *UI == User);
  7310. // Now that we have modified User, add it back to the CSE maps. If it
  7311. // already exists there, recursively merge the results together.
  7312. AddModifiedNodeToCSEMaps(User);
  7313. }
  7314. // If we just RAUW'd the root, take note.
  7315. if (From == getRoot().getNode())
  7316. setRoot(SDValue(To, getRoot().getResNo()));
  7317. }
  7318. /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
  7319. /// This can cause recursive merging of nodes in the DAG.
  7320. ///
  7321. /// This version can replace From with any result values. To must match the
  7322. /// number and types of values returned by From.
  7323. void SelectionDAG::ReplaceAllUsesWith(SDNode *From, const SDValue *To) {
  7324. if (From->getNumValues() == 1) // Handle the simple case efficiently.
  7325. return ReplaceAllUsesWith(SDValue(From, 0), To[0]);
  7326. // Preserve Debug Info.
  7327. for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
  7328. transferDbgValues(SDValue(From, i), To[i]);
  7329. // Iterate over just the existing users of From. See the comments in
  7330. // the ReplaceAllUsesWith above.
  7331. SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
  7332. RAUWUpdateListener Listener(*this, UI, UE);
  7333. while (UI != UE) {
  7334. SDNode *User = *UI;
  7335. // This node is about to morph, remove its old self from the CSE maps.
  7336. RemoveNodeFromCSEMaps(User);
  7337. // A user can appear in a use list multiple times, and when this happens the
  7338. // uses are usually next to each other in the list. To help reduce the
  7339. // number of CSE and divergence recomputations, process all the uses of this
  7340. // user that we can find this way.
  7341. bool To_IsDivergent = false;
  7342. do {
  7343. SDUse &Use = UI.getUse();
  7344. const SDValue &ToOp = To[Use.getResNo()];
  7345. ++UI;
  7346. Use.set(ToOp);
  7347. To_IsDivergent |= ToOp->isDivergent();
  7348. } while (UI != UE && *UI == User);
  7349. if (To_IsDivergent != From->isDivergent())
  7350. updateDivergence(User);
  7351. // Now that we have modified User, add it back to the CSE maps. If it
  7352. // already exists there, recursively merge the results together.
  7353. AddModifiedNodeToCSEMaps(User);
  7354. }
  7355. // If we just RAUW'd the root, take note.
  7356. if (From == getRoot().getNode())
  7357. setRoot(SDValue(To[getRoot().getResNo()]));
  7358. }
  7359. /// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving
  7360. /// uses of other values produced by From.getNode() alone. The Deleted
  7361. /// vector is handled the same way as for ReplaceAllUsesWith.
  7362. void SelectionDAG::ReplaceAllUsesOfValueWith(SDValue From, SDValue To){
  7363. // Handle the really simple, really trivial case efficiently.
  7364. if (From == To) return;
  7365. // Handle the simple, trivial, case efficiently.
  7366. if (From.getNode()->getNumValues() == 1) {
  7367. ReplaceAllUsesWith(From, To);
  7368. return;
  7369. }
  7370. // Preserve Debug Info.
  7371. transferDbgValues(From, To);
  7372. // Iterate over just the existing users of From. See the comments in
  7373. // the ReplaceAllUsesWith above.
  7374. SDNode::use_iterator UI = From.getNode()->use_begin(),
  7375. UE = From.getNode()->use_end();
  7376. RAUWUpdateListener Listener(*this, UI, UE);
  7377. while (UI != UE) {
  7378. SDNode *User = *UI;
  7379. bool UserRemovedFromCSEMaps = false;
  7380. // A user can appear in a use list multiple times, and when this
  7381. // happens the uses are usually next to each other in the list.
  7382. // To help reduce the number of CSE recomputations, process all
  7383. // the uses of this user that we can find this way.
  7384. do {
  7385. SDUse &Use = UI.getUse();
  7386. // Skip uses of different values from the same node.
  7387. if (Use.getResNo() != From.getResNo()) {
  7388. ++UI;
  7389. continue;
  7390. }
  7391. // If this node hasn't been modified yet, it's still in the CSE maps,
  7392. // so remove its old self from the CSE maps.
  7393. if (!UserRemovedFromCSEMaps) {
  7394. RemoveNodeFromCSEMaps(User);
  7395. UserRemovedFromCSEMaps = true;
  7396. }
  7397. ++UI;
  7398. Use.set(To);
  7399. if (To->isDivergent() != From->isDivergent())
  7400. updateDivergence(User);
  7401. } while (UI != UE && *UI == User);
  7402. // We are iterating over all uses of the From node, so if a use
  7403. // doesn't use the specific value, no changes are made.
  7404. if (!UserRemovedFromCSEMaps)
  7405. continue;
  7406. // Now that we have modified User, add it back to the CSE maps. If it
  7407. // already exists there, recursively merge the results together.
  7408. AddModifiedNodeToCSEMaps(User);
  7409. }
  7410. // If we just RAUW'd the root, take note.
  7411. if (From == getRoot())
  7412. setRoot(To);
  7413. }
  7414. namespace {
  7415. /// UseMemo - This class is used by SelectionDAG::ReplaceAllUsesOfValuesWith
  7416. /// to record information about a use.
  7417. struct UseMemo {
  7418. SDNode *User;
  7419. unsigned Index;
  7420. SDUse *Use;
  7421. };
  7422. /// operator< - Sort Memos by User.
  7423. bool operator<(const UseMemo &L, const UseMemo &R) {
  7424. return (intptr_t)L.User < (intptr_t)R.User;
  7425. }
  7426. } // end anonymous namespace
  7427. void SelectionDAG::updateDivergence(SDNode * N)
  7428. {
  7429. if (TLI->isSDNodeAlwaysUniform(N))
  7430. return;
  7431. bool IsDivergent = TLI->isSDNodeSourceOfDivergence(N, FLI, DA);
  7432. for (auto &Op : N->ops()) {
  7433. if (Op.Val.getValueType() != MVT::Other)
  7434. IsDivergent |= Op.getNode()->isDivergent();
  7435. }
  7436. if (N->SDNodeBits.IsDivergent != IsDivergent) {
  7437. N->SDNodeBits.IsDivergent = IsDivergent;
  7438. for (auto U : N->uses()) {
  7439. updateDivergence(U);
  7440. }
  7441. }
  7442. }
  7443. void SelectionDAG::CreateTopologicalOrder(std::vector<SDNode*>& Order) {
  7444. DenseMap<SDNode *, unsigned> Degree;
  7445. Order.reserve(AllNodes.size());
  7446. for (auto & N : allnodes()) {
  7447. unsigned NOps = N.getNumOperands();
  7448. Degree[&N] = NOps;
  7449. if (0 == NOps)
  7450. Order.push_back(&N);
  7451. }
  7452. for (std::vector<SDNode *>::iterator I = Order.begin();
  7453. I!=Order.end();++I) {
  7454. SDNode * N = *I;
  7455. for (auto U : N->uses()) {
  7456. unsigned &UnsortedOps = Degree[U];
  7457. if (0 == --UnsortedOps)
  7458. Order.push_back(U);
  7459. }
  7460. }
  7461. }
  7462. #ifndef NDEBUG
  7463. void SelectionDAG::VerifyDAGDiverence()
  7464. {
  7465. std::vector<SDNode*> TopoOrder;
  7466. CreateTopologicalOrder(TopoOrder);
  7467. const TargetLowering &TLI = getTargetLoweringInfo();
  7468. DenseMap<const SDNode *, bool> DivergenceMap;
  7469. for (auto &N : allnodes()) {
  7470. DivergenceMap[&N] = false;
  7471. }
  7472. for (auto N : TopoOrder) {
  7473. bool IsDivergent = DivergenceMap[N];
  7474. bool IsSDNodeDivergent = TLI.isSDNodeSourceOfDivergence(N, FLI, DA);
  7475. for (auto &Op : N->ops()) {
  7476. if (Op.Val.getValueType() != MVT::Other)
  7477. IsSDNodeDivergent |= DivergenceMap[Op.getNode()];
  7478. }
  7479. if (!IsDivergent && IsSDNodeDivergent && !TLI.isSDNodeAlwaysUniform(N)) {
  7480. DivergenceMap[N] = true;
  7481. }
  7482. }
  7483. for (auto &N : allnodes()) {
  7484. (void)N;
  7485. assert(DivergenceMap[&N] == N.isDivergent() &&
  7486. "Divergence bit inconsistency detected\n");
  7487. }
  7488. }
  7489. #endif
  7490. /// ReplaceAllUsesOfValuesWith - Replace any uses of From with To, leaving
  7491. /// uses of other values produced by From.getNode() alone. The same value
  7492. /// may appear in both the From and To list. The Deleted vector is
  7493. /// handled the same way as for ReplaceAllUsesWith.
  7494. void SelectionDAG::ReplaceAllUsesOfValuesWith(const SDValue *From,
  7495. const SDValue *To,
  7496. unsigned Num){
  7497. // Handle the simple, trivial case efficiently.
  7498. if (Num == 1)
  7499. return ReplaceAllUsesOfValueWith(*From, *To);
  7500. transferDbgValues(*From, *To);
  7501. // Read up all the uses and make records of them. This helps
  7502. // processing new uses that are introduced during the
  7503. // replacement process.
  7504. SmallVector<UseMemo, 4> Uses;
  7505. for (unsigned i = 0; i != Num; ++i) {
  7506. unsigned FromResNo = From[i].getResNo();
  7507. SDNode *FromNode = From[i].getNode();
  7508. for (SDNode::use_iterator UI = FromNode->use_begin(),
  7509. E = FromNode->use_end(); UI != E; ++UI) {
  7510. SDUse &Use = UI.getUse();
  7511. if (Use.getResNo() == FromResNo) {
  7512. UseMemo Memo = { *UI, i, &Use };
  7513. Uses.push_back(Memo);
  7514. }
  7515. }
  7516. }
  7517. // Sort the uses, so that all the uses from a given User are together.
  7518. llvm::sort(Uses);
  7519. for (unsigned UseIndex = 0, UseIndexEnd = Uses.size();
  7520. UseIndex != UseIndexEnd; ) {
  7521. // We know that this user uses some value of From. If it is the right
  7522. // value, update it.
  7523. SDNode *User = Uses[UseIndex].User;
  7524. // This node is about to morph, remove its old self from the CSE maps.
  7525. RemoveNodeFromCSEMaps(User);
  7526. // The Uses array is sorted, so all the uses for a given User
  7527. // are next to each other in the list.
  7528. // To help reduce the number of CSE recomputations, process all
  7529. // the uses of this user that we can find this way.
  7530. do {
  7531. unsigned i = Uses[UseIndex].Index;
  7532. SDUse &Use = *Uses[UseIndex].Use;
  7533. ++UseIndex;
  7534. Use.set(To[i]);
  7535. } while (UseIndex != UseIndexEnd && Uses[UseIndex].User == User);
  7536. // Now that we have modified User, add it back to the CSE maps. If it
  7537. // already exists there, recursively merge the results together.
  7538. AddModifiedNodeToCSEMaps(User);
  7539. }
  7540. }
  7541. /// AssignTopologicalOrder - Assign a unique node id for each node in the DAG
  7542. /// based on their topological order. It returns the maximum id and a vector
  7543. /// of the SDNodes* in assigned order by reference.
  7544. unsigned SelectionDAG::AssignTopologicalOrder() {
  7545. unsigned DAGSize = 0;
  7546. // SortedPos tracks the progress of the algorithm. Nodes before it are
  7547. // sorted, nodes after it are unsorted. When the algorithm completes
  7548. // it is at the end of the list.
  7549. allnodes_iterator SortedPos = allnodes_begin();
  7550. // Visit all the nodes. Move nodes with no operands to the front of
  7551. // the list immediately. Annotate nodes that do have operands with their
  7552. // operand count. Before we do this, the Node Id fields of the nodes
  7553. // may contain arbitrary values. After, the Node Id fields for nodes
  7554. // before SortedPos will contain the topological sort index, and the
  7555. // Node Id fields for nodes At SortedPos and after will contain the
  7556. // count of outstanding operands.
  7557. for (allnodes_iterator I = allnodes_begin(),E = allnodes_end(); I != E; ) {
  7558. SDNode *N = &*I++;
  7559. checkForCycles(N, this);
  7560. unsigned Degree = N->getNumOperands();
  7561. if (Degree == 0) {
  7562. // A node with no uses, add it to the result array immediately.
  7563. N->setNodeId(DAGSize++);
  7564. allnodes_iterator Q(N);
  7565. if (Q != SortedPos)
  7566. SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(Q));
  7567. assert(SortedPos != AllNodes.end() && "Overran node list");
  7568. ++SortedPos;
  7569. } else {
  7570. // Temporarily use the Node Id as scratch space for the degree count.
  7571. N->setNodeId(Degree);
  7572. }
  7573. }
  7574. // Visit all the nodes. As we iterate, move nodes into sorted order,
  7575. // such that by the time the end is reached all nodes will be sorted.
  7576. for (SDNode &Node : allnodes()) {
  7577. SDNode *N = &Node;
  7578. checkForCycles(N, this);
  7579. // N is in sorted position, so all its uses have one less operand
  7580. // that needs to be sorted.
  7581. for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
  7582. UI != UE; ++UI) {
  7583. SDNode *P = *UI;
  7584. unsigned Degree = P->getNodeId();
  7585. assert(Degree != 0 && "Invalid node degree");
  7586. --Degree;
  7587. if (Degree == 0) {
  7588. // All of P's operands are sorted, so P may sorted now.
  7589. P->setNodeId(DAGSize++);
  7590. if (P->getIterator() != SortedPos)
  7591. SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(P));
  7592. assert(SortedPos != AllNodes.end() && "Overran node list");
  7593. ++SortedPos;
  7594. } else {
  7595. // Update P's outstanding operand count.
  7596. P->setNodeId(Degree);
  7597. }
  7598. }
  7599. if (Node.getIterator() == SortedPos) {
  7600. #ifndef NDEBUG
  7601. allnodes_iterator I(N);
  7602. SDNode *S = &*++I;
  7603. dbgs() << "Overran sorted position:\n";
  7604. S->dumprFull(this); dbgs() << "\n";
  7605. dbgs() << "Checking if this is due to cycles\n";
  7606. checkForCycles(this, true);
  7607. #endif
  7608. llvm_unreachable(nullptr);
  7609. }
  7610. }
  7611. assert(SortedPos == AllNodes.end() &&
  7612. "Topological sort incomplete!");
  7613. assert(AllNodes.front().getOpcode() == ISD::EntryToken &&
  7614. "First node in topological sort is not the entry token!");
  7615. assert(AllNodes.front().getNodeId() == 0 &&
  7616. "First node in topological sort has non-zero id!");
  7617. assert(AllNodes.front().getNumOperands() == 0 &&
  7618. "First node in topological sort has operands!");
  7619. assert(AllNodes.back().getNodeId() == (int)DAGSize-1 &&
  7620. "Last node in topologic sort has unexpected id!");
  7621. assert(AllNodes.back().use_empty() &&
  7622. "Last node in topologic sort has users!");
  7623. assert(DAGSize == allnodes_size() && "Node count mismatch!");
  7624. return DAGSize;
  7625. }
  7626. /// AddDbgValue - Add a dbg_value SDNode. If SD is non-null that means the
  7627. /// value is produced by SD.
  7628. void SelectionDAG::AddDbgValue(SDDbgValue *DB, SDNode *SD, bool isParameter) {
  7629. if (SD) {
  7630. assert(DbgInfo->getSDDbgValues(SD).empty() || SD->getHasDebugValue());
  7631. SD->setHasDebugValue(true);
  7632. }
  7633. DbgInfo->add(DB, SD, isParameter);
  7634. }
  7635. void SelectionDAG::AddDbgLabel(SDDbgLabel *DB) {
  7636. DbgInfo->add(DB);
  7637. }
  7638. SDValue SelectionDAG::makeEquivalentMemoryOrdering(LoadSDNode *OldLoad,
  7639. SDValue NewMemOp) {
  7640. assert(isa<MemSDNode>(NewMemOp.getNode()) && "Expected a memop node");
  7641. // The new memory operation must have the same position as the old load in
  7642. // terms of memory dependency. Create a TokenFactor for the old load and new
  7643. // memory operation and update uses of the old load's output chain to use that
  7644. // TokenFactor.
  7645. SDValue OldChain = SDValue(OldLoad, 1);
  7646. SDValue NewChain = SDValue(NewMemOp.getNode(), 1);
  7647. if (!OldLoad->hasAnyUseOfValue(1))
  7648. return NewChain;
  7649. SDValue TokenFactor =
  7650. getNode(ISD::TokenFactor, SDLoc(OldLoad), MVT::Other, OldChain, NewChain);
  7651. ReplaceAllUsesOfValueWith(OldChain, TokenFactor);
  7652. UpdateNodeOperands(TokenFactor.getNode(), OldChain, NewChain);
  7653. return TokenFactor;
  7654. }
  7655. SDValue SelectionDAG::getSymbolFunctionGlobalAddress(SDValue Op,
  7656. Function **OutFunction) {
  7657. assert(isa<ExternalSymbolSDNode>(Op) && "Node should be an ExternalSymbol");
  7658. auto *Symbol = cast<ExternalSymbolSDNode>(Op)->getSymbol();
  7659. auto *Module = MF->getFunction().getParent();
  7660. auto *Function = Module->getFunction(Symbol);
  7661. if (OutFunction != nullptr)
  7662. *OutFunction = Function;
  7663. if (Function != nullptr) {
  7664. auto PtrTy = TLI->getPointerTy(getDataLayout(), Function->getAddressSpace());
  7665. return getGlobalAddress(Function, SDLoc(Op), PtrTy);
  7666. }
  7667. std::string ErrorStr;
  7668. raw_string_ostream ErrorFormatter(ErrorStr);
  7669. ErrorFormatter << "Undefined external symbol ";
  7670. ErrorFormatter << '"' << Symbol << '"';
  7671. ErrorFormatter.flush();
  7672. report_fatal_error(ErrorStr);
  7673. }
  7674. //===----------------------------------------------------------------------===//
  7675. // SDNode Class
  7676. //===----------------------------------------------------------------------===//
  7677. bool llvm::isNullConstant(SDValue V) {
  7678. ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
  7679. return Const != nullptr && Const->isNullValue();
  7680. }
  7681. bool llvm::isNullFPConstant(SDValue V) {
  7682. ConstantFPSDNode *Const = dyn_cast<ConstantFPSDNode>(V);
  7683. return Const != nullptr && Const->isZero() && !Const->isNegative();
  7684. }
  7685. bool llvm::isAllOnesConstant(SDValue V) {
  7686. ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
  7687. return Const != nullptr && Const->isAllOnesValue();
  7688. }
  7689. bool llvm::isOneConstant(SDValue V) {
  7690. ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
  7691. return Const != nullptr && Const->isOne();
  7692. }
  7693. SDValue llvm::peekThroughBitcasts(SDValue V) {
  7694. while (V.getOpcode() == ISD::BITCAST)
  7695. V = V.getOperand(0);
  7696. return V;
  7697. }
  7698. SDValue llvm::peekThroughOneUseBitcasts(SDValue V) {
  7699. while (V.getOpcode() == ISD::BITCAST && V.getOperand(0).hasOneUse())
  7700. V = V.getOperand(0);
  7701. return V;
  7702. }
  7703. bool llvm::isBitwiseNot(SDValue V) {
  7704. if (V.getOpcode() != ISD::XOR)
  7705. return false;
  7706. ConstantSDNode *C = isConstOrConstSplat(peekThroughBitcasts(V.getOperand(1)));
  7707. return C && C->isAllOnesValue();
  7708. }
  7709. ConstantSDNode *llvm::isConstOrConstSplat(SDValue N, bool AllowUndefs) {
  7710. if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
  7711. return CN;
  7712. if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
  7713. BitVector UndefElements;
  7714. ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
  7715. // BuildVectors can truncate their operands. Ignore that case here.
  7716. if (CN && (UndefElements.none() || AllowUndefs) &&
  7717. CN->getValueType(0) == N.getValueType().getScalarType())
  7718. return CN;
  7719. }
  7720. return nullptr;
  7721. }
  7722. ConstantSDNode *llvm::isConstOrConstSplat(SDValue N, const APInt &DemandedElts,
  7723. bool AllowUndefs) {
  7724. if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
  7725. return CN;
  7726. if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
  7727. BitVector UndefElements;
  7728. ConstantSDNode *CN = BV->getConstantSplatNode(DemandedElts, &UndefElements);
  7729. // BuildVectors can truncate their operands. Ignore that case here.
  7730. if (CN && (UndefElements.none() || AllowUndefs) &&
  7731. CN->getValueType(0) == N.getValueType().getScalarType())
  7732. return CN;
  7733. }
  7734. return nullptr;
  7735. }
  7736. ConstantFPSDNode *llvm::isConstOrConstSplatFP(SDValue N, bool AllowUndefs) {
  7737. if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
  7738. return CN;
  7739. if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
  7740. BitVector UndefElements;
  7741. ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
  7742. if (CN && (UndefElements.none() || AllowUndefs))
  7743. return CN;
  7744. }
  7745. return nullptr;
  7746. }
  7747. ConstantFPSDNode *llvm::isConstOrConstSplatFP(SDValue N,
  7748. const APInt &DemandedElts,
  7749. bool AllowUndefs) {
  7750. if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
  7751. return CN;
  7752. if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
  7753. BitVector UndefElements;
  7754. ConstantFPSDNode *CN =
  7755. BV->getConstantFPSplatNode(DemandedElts, &UndefElements);
  7756. if (CN && (UndefElements.none() || AllowUndefs))
  7757. return CN;
  7758. }
  7759. return nullptr;
  7760. }
  7761. bool llvm::isNullOrNullSplat(SDValue N, bool AllowUndefs) {
  7762. // TODO: may want to use peekThroughBitcast() here.
  7763. ConstantSDNode *C = isConstOrConstSplat(N, AllowUndefs);
  7764. return C && C->isNullValue();
  7765. }
  7766. bool llvm::isOneOrOneSplat(SDValue N) {
  7767. // TODO: may want to use peekThroughBitcast() here.
  7768. unsigned BitWidth = N.getScalarValueSizeInBits();
  7769. ConstantSDNode *C = isConstOrConstSplat(N);
  7770. return C && C->isOne() && C->getValueSizeInBits(0) == BitWidth;
  7771. }
  7772. bool llvm::isAllOnesOrAllOnesSplat(SDValue N) {
  7773. N = peekThroughBitcasts(N);
  7774. unsigned BitWidth = N.getScalarValueSizeInBits();
  7775. ConstantSDNode *C = isConstOrConstSplat(N);
  7776. return C && C->isAllOnesValue() && C->getValueSizeInBits(0) == BitWidth;
  7777. }
  7778. HandleSDNode::~HandleSDNode() {
  7779. DropOperands();
  7780. }
  7781. GlobalAddressSDNode::GlobalAddressSDNode(unsigned Opc, unsigned Order,
  7782. const DebugLoc &DL,
  7783. const GlobalValue *GA, EVT VT,
  7784. int64_t o, unsigned char TF)
  7785. : SDNode(Opc, Order, DL, getSDVTList(VT)), Offset(o), TargetFlags(TF) {
  7786. TheGlobal = GA;
  7787. }
  7788. AddrSpaceCastSDNode::AddrSpaceCastSDNode(unsigned Order, const DebugLoc &dl,
  7789. EVT VT, unsigned SrcAS,
  7790. unsigned DestAS)
  7791. : SDNode(ISD::ADDRSPACECAST, Order, dl, getSDVTList(VT)),
  7792. SrcAddrSpace(SrcAS), DestAddrSpace(DestAS) {}
  7793. MemSDNode::MemSDNode(unsigned Opc, unsigned Order, const DebugLoc &dl,
  7794. SDVTList VTs, EVT memvt, MachineMemOperand *mmo)
  7795. : SDNode(Opc, Order, dl, VTs), MemoryVT(memvt), MMO(mmo) {
  7796. MemSDNodeBits.IsVolatile = MMO->isVolatile();
  7797. MemSDNodeBits.IsNonTemporal = MMO->isNonTemporal();
  7798. MemSDNodeBits.IsDereferenceable = MMO->isDereferenceable();
  7799. MemSDNodeBits.IsInvariant = MMO->isInvariant();
  7800. // We check here that the size of the memory operand fits within the size of
  7801. // the MMO. This is because the MMO might indicate only a possible address
  7802. // range instead of specifying the affected memory addresses precisely.
  7803. assert(memvt.getStoreSize() <= MMO->getSize() && "Size mismatch!");
  7804. }
  7805. /// Profile - Gather unique data for the node.
  7806. ///
  7807. void SDNode::Profile(FoldingSetNodeID &ID) const {
  7808. AddNodeIDNode(ID, this);
  7809. }
  7810. namespace {
  7811. struct EVTArray {
  7812. std::vector<EVT> VTs;
  7813. EVTArray() {
  7814. VTs.reserve(MVT::LAST_VALUETYPE);
  7815. for (unsigned i = 0; i < MVT::LAST_VALUETYPE; ++i)
  7816. VTs.push_back(MVT((MVT::SimpleValueType)i));
  7817. }
  7818. };
  7819. } // end anonymous namespace
  7820. static ManagedStatic<std::set<EVT, EVT::compareRawBits>> EVTs;
  7821. static ManagedStatic<EVTArray> SimpleVTArray;
  7822. static ManagedStatic<sys::SmartMutex<true>> VTMutex;
  7823. /// getValueTypeList - Return a pointer to the specified value type.
  7824. ///
  7825. const EVT *SDNode::getValueTypeList(EVT VT) {
  7826. if (VT.isExtended()) {
  7827. sys::SmartScopedLock<true> Lock(*VTMutex);
  7828. return &(*EVTs->insert(VT).first);
  7829. } else {
  7830. assert(VT.getSimpleVT() < MVT::LAST_VALUETYPE &&
  7831. "Value type out of range!");
  7832. return &SimpleVTArray->VTs[VT.getSimpleVT().SimpleTy];
  7833. }
  7834. }
  7835. /// hasNUsesOfValue - Return true if there are exactly NUSES uses of the
  7836. /// indicated value. This method ignores uses of other values defined by this
  7837. /// operation.
  7838. bool SDNode::hasNUsesOfValue(unsigned NUses, unsigned Value) const {
  7839. assert(Value < getNumValues() && "Bad value!");
  7840. // TODO: Only iterate over uses of a given value of the node
  7841. for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) {
  7842. if (UI.getUse().getResNo() == Value) {
  7843. if (NUses == 0)
  7844. return false;
  7845. --NUses;
  7846. }
  7847. }
  7848. // Found exactly the right number of uses?
  7849. return NUses == 0;
  7850. }
  7851. /// hasAnyUseOfValue - Return true if there are any use of the indicated
  7852. /// value. This method ignores uses of other values defined by this operation.
  7853. bool SDNode::hasAnyUseOfValue(unsigned Value) const {
  7854. assert(Value < getNumValues() && "Bad value!");
  7855. for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI)
  7856. if (UI.getUse().getResNo() == Value)
  7857. return true;
  7858. return false;
  7859. }
  7860. /// isOnlyUserOf - Return true if this node is the only use of N.
  7861. bool SDNode::isOnlyUserOf(const SDNode *N) const {
  7862. bool Seen = false;
  7863. for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
  7864. SDNode *User = *I;
  7865. if (User == this)
  7866. Seen = true;
  7867. else
  7868. return false;
  7869. }
  7870. return Seen;
  7871. }
  7872. /// Return true if the only users of N are contained in Nodes.
  7873. bool SDNode::areOnlyUsersOf(ArrayRef<const SDNode *> Nodes, const SDNode *N) {
  7874. bool Seen = false;
  7875. for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
  7876. SDNode *User = *I;
  7877. if (llvm::any_of(Nodes,
  7878. [&User](const SDNode *Node) { return User == Node; }))
  7879. Seen = true;
  7880. else
  7881. return false;
  7882. }
  7883. return Seen;
  7884. }
  7885. /// isOperand - Return true if this node is an operand of N.
  7886. bool SDValue::isOperandOf(const SDNode *N) const {
  7887. for (const SDValue &Op : N->op_values())
  7888. if (*this == Op)
  7889. return true;
  7890. return false;
  7891. }
  7892. bool SDNode::isOperandOf(const SDNode *N) const {
  7893. for (const SDValue &Op : N->op_values())
  7894. if (this == Op.getNode())
  7895. return true;
  7896. return false;
  7897. }
  7898. /// reachesChainWithoutSideEffects - Return true if this operand (which must
  7899. /// be a chain) reaches the specified operand without crossing any
  7900. /// side-effecting instructions on any chain path. In practice, this looks
  7901. /// through token factors and non-volatile loads. In order to remain efficient,
  7902. /// this only looks a couple of nodes in, it does not do an exhaustive search.
  7903. ///
  7904. /// Note that we only need to examine chains when we're searching for
  7905. /// side-effects; SelectionDAG requires that all side-effects are represented
  7906. /// by chains, even if another operand would force a specific ordering. This
  7907. /// constraint is necessary to allow transformations like splitting loads.
  7908. bool SDValue::reachesChainWithoutSideEffects(SDValue Dest,
  7909. unsigned Depth) const {
  7910. if (*this == Dest) return true;
  7911. // Don't search too deeply, we just want to be able to see through
  7912. // TokenFactor's etc.
  7913. if (Depth == 0) return false;
  7914. // If this is a token factor, all inputs to the TF happen in parallel.
  7915. if (getOpcode() == ISD::TokenFactor) {
  7916. // First, try a shallow search.
  7917. if (is_contained((*this)->ops(), Dest)) {
  7918. // We found the chain we want as an operand of this TokenFactor.
  7919. // Essentially, we reach the chain without side-effects if we could
  7920. // serialize the TokenFactor into a simple chain of operations with
  7921. // Dest as the last operation. This is automatically true if the
  7922. // chain has one use: there are no other ordering constraints.
  7923. // If the chain has more than one use, we give up: some other
  7924. // use of Dest might force a side-effect between Dest and the current
  7925. // node.
  7926. if (Dest.hasOneUse())
  7927. return true;
  7928. }
  7929. // Next, try a deep search: check whether every operand of the TokenFactor
  7930. // reaches Dest.
  7931. return llvm::all_of((*this)->ops(), [=](SDValue Op) {
  7932. return Op.reachesChainWithoutSideEffects(Dest, Depth - 1);
  7933. });
  7934. }
  7935. // Loads don't have side effects, look through them.
  7936. if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(*this)) {
  7937. if (!Ld->isVolatile())
  7938. return Ld->getChain().reachesChainWithoutSideEffects(Dest, Depth-1);
  7939. }
  7940. return false;
  7941. }
  7942. bool SDNode::hasPredecessor(const SDNode *N) const {
  7943. SmallPtrSet<const SDNode *, 32> Visited;
  7944. SmallVector<const SDNode *, 16> Worklist;
  7945. Worklist.push_back(this);
  7946. return hasPredecessorHelper(N, Visited, Worklist);
  7947. }
  7948. void SDNode::intersectFlagsWith(const SDNodeFlags Flags) {
  7949. this->Flags.intersectWith(Flags);
  7950. }
  7951. SDValue
  7952. SelectionDAG::matchBinOpReduction(SDNode *Extract, ISD::NodeType &BinOp,
  7953. ArrayRef<ISD::NodeType> CandidateBinOps) {
  7954. // The pattern must end in an extract from index 0.
  7955. if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
  7956. !isNullConstant(Extract->getOperand(1)))
  7957. return SDValue();
  7958. SDValue Op = Extract->getOperand(0);
  7959. unsigned Stages = Log2_32(Op.getValueType().getVectorNumElements());
  7960. // Match against one of the candidate binary ops.
  7961. if (llvm::none_of(CandidateBinOps, [Op](ISD::NodeType BinOp) {
  7962. return Op.getOpcode() == unsigned(BinOp);
  7963. }))
  7964. return SDValue();
  7965. // At each stage, we're looking for something that looks like:
  7966. // %s = shufflevector <8 x i32> %op, <8 x i32> undef,
  7967. // <8 x i32> <i32 2, i32 3, i32 undef, i32 undef,
  7968. // i32 undef, i32 undef, i32 undef, i32 undef>
  7969. // %a = binop <8 x i32> %op, %s
  7970. // Where the mask changes according to the stage. E.g. for a 3-stage pyramid,
  7971. // we expect something like:
  7972. // <4,5,6,7,u,u,u,u>
  7973. // <2,3,u,u,u,u,u,u>
  7974. // <1,u,u,u,u,u,u,u>
  7975. unsigned CandidateBinOp = Op.getOpcode();
  7976. for (unsigned i = 0; i < Stages; ++i) {
  7977. if (Op.getOpcode() != CandidateBinOp)
  7978. return SDValue();
  7979. SDValue Op0 = Op.getOperand(0);
  7980. SDValue Op1 = Op.getOperand(1);
  7981. ShuffleVectorSDNode *Shuffle = dyn_cast<ShuffleVectorSDNode>(Op0);
  7982. if (Shuffle) {
  7983. Op = Op1;
  7984. } else {
  7985. Shuffle = dyn_cast<ShuffleVectorSDNode>(Op1);
  7986. Op = Op0;
  7987. }
  7988. // The first operand of the shuffle should be the same as the other operand
  7989. // of the binop.
  7990. if (!Shuffle || Shuffle->getOperand(0) != Op)
  7991. return SDValue();
  7992. // Verify the shuffle has the expected (at this stage of the pyramid) mask.
  7993. for (int Index = 0, MaskEnd = 1 << i; Index < MaskEnd; ++Index)
  7994. if (Shuffle->getMaskElt(Index) != MaskEnd + Index)
  7995. return SDValue();
  7996. }
  7997. BinOp = (ISD::NodeType)CandidateBinOp;
  7998. return Op;
  7999. }
  8000. SDValue SelectionDAG::UnrollVectorOp(SDNode *N, unsigned ResNE) {
  8001. assert(N->getNumValues() == 1 &&
  8002. "Can't unroll a vector with multiple results!");
  8003. EVT VT = N->getValueType(0);
  8004. unsigned NE = VT.getVectorNumElements();
  8005. EVT EltVT = VT.getVectorElementType();
  8006. SDLoc dl(N);
  8007. SmallVector<SDValue, 8> Scalars;
  8008. SmallVector<SDValue, 4> Operands(N->getNumOperands());
  8009. // If ResNE is 0, fully unroll the vector op.
  8010. if (ResNE == 0)
  8011. ResNE = NE;
  8012. else if (NE > ResNE)
  8013. NE = ResNE;
  8014. unsigned i;
  8015. for (i= 0; i != NE; ++i) {
  8016. for (unsigned j = 0, e = N->getNumOperands(); j != e; ++j) {
  8017. SDValue Operand = N->getOperand(j);
  8018. EVT OperandVT = Operand.getValueType();
  8019. if (OperandVT.isVector()) {
  8020. // A vector operand; extract a single element.
  8021. EVT OperandEltVT = OperandVT.getVectorElementType();
  8022. Operands[j] =
  8023. getNode(ISD::EXTRACT_VECTOR_ELT, dl, OperandEltVT, Operand,
  8024. getConstant(i, dl, TLI->getVectorIdxTy(getDataLayout())));
  8025. } else {
  8026. // A scalar operand; just use it as is.
  8027. Operands[j] = Operand;
  8028. }
  8029. }
  8030. switch (N->getOpcode()) {
  8031. default: {
  8032. Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands,
  8033. N->getFlags()));
  8034. break;
  8035. }
  8036. case ISD::VSELECT:
  8037. Scalars.push_back(getNode(ISD::SELECT, dl, EltVT, Operands));
  8038. break;
  8039. case ISD::SHL:
  8040. case ISD::SRA:
  8041. case ISD::SRL:
  8042. case ISD::ROTL:
  8043. case ISD::ROTR:
  8044. Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands[0],
  8045. getShiftAmountOperand(Operands[0].getValueType(),
  8046. Operands[1])));
  8047. break;
  8048. case ISD::SIGN_EXTEND_INREG:
  8049. case ISD::FP_ROUND_INREG: {
  8050. EVT ExtVT = cast<VTSDNode>(Operands[1])->getVT().getVectorElementType();
  8051. Scalars.push_back(getNode(N->getOpcode(), dl, EltVT,
  8052. Operands[0],
  8053. getValueType(ExtVT)));
  8054. }
  8055. }
  8056. }
  8057. for (; i < ResNE; ++i)
  8058. Scalars.push_back(getUNDEF(EltVT));
  8059. EVT VecVT = EVT::getVectorVT(*getContext(), EltVT, ResNE);
  8060. return getBuildVector(VecVT, dl, Scalars);
  8061. }
  8062. std::pair<SDValue, SDValue> SelectionDAG::UnrollVectorOverflowOp(
  8063. SDNode *N, unsigned ResNE) {
  8064. unsigned Opcode = N->getOpcode();
  8065. assert((Opcode == ISD::UADDO || Opcode == ISD::SADDO ||
  8066. Opcode == ISD::USUBO || Opcode == ISD::SSUBO ||
  8067. Opcode == ISD::UMULO || Opcode == ISD::SMULO) &&
  8068. "Expected an overflow opcode");
  8069. EVT ResVT = N->getValueType(0);
  8070. EVT OvVT = N->getValueType(1);
  8071. EVT ResEltVT = ResVT.getVectorElementType();
  8072. EVT OvEltVT = OvVT.getVectorElementType();
  8073. SDLoc dl(N);
  8074. // If ResNE is 0, fully unroll the vector op.
  8075. unsigned NE = ResVT.getVectorNumElements();
  8076. if (ResNE == 0)
  8077. ResNE = NE;
  8078. else if (NE > ResNE)
  8079. NE = ResNE;
  8080. SmallVector<SDValue, 8> LHSScalars;
  8081. SmallVector<SDValue, 8> RHSScalars;
  8082. ExtractVectorElements(N->getOperand(0), LHSScalars, 0, NE);
  8083. ExtractVectorElements(N->getOperand(1), RHSScalars, 0, NE);
  8084. EVT SVT = TLI->getSetCCResultType(getDataLayout(), *getContext(), ResEltVT);
  8085. SDVTList VTs = getVTList(ResEltVT, SVT);
  8086. SmallVector<SDValue, 8> ResScalars;
  8087. SmallVector<SDValue, 8> OvScalars;
  8088. for (unsigned i = 0; i < NE; ++i) {
  8089. SDValue Res = getNode(Opcode, dl, VTs, LHSScalars[i], RHSScalars[i]);
  8090. SDValue Ov =
  8091. getSelect(dl, OvEltVT, Res.getValue(1),
  8092. getBoolConstant(true, dl, OvEltVT, ResVT),
  8093. getConstant(0, dl, OvEltVT));
  8094. ResScalars.push_back(Res);
  8095. OvScalars.push_back(Ov);
  8096. }
  8097. ResScalars.append(ResNE - NE, getUNDEF(ResEltVT));
  8098. OvScalars.append(ResNE - NE, getUNDEF(OvEltVT));
  8099. EVT NewResVT = EVT::getVectorVT(*getContext(), ResEltVT, ResNE);
  8100. EVT NewOvVT = EVT::getVectorVT(*getContext(), OvEltVT, ResNE);
  8101. return std::make_pair(getBuildVector(NewResVT, dl, ResScalars),
  8102. getBuildVector(NewOvVT, dl, OvScalars));
  8103. }
  8104. bool SelectionDAG::areNonVolatileConsecutiveLoads(LoadSDNode *LD,
  8105. LoadSDNode *Base,
  8106. unsigned Bytes,
  8107. int Dist) const {
  8108. if (LD->isVolatile() || Base->isVolatile())
  8109. return false;
  8110. if (LD->isIndexed() || Base->isIndexed())
  8111. return false;
  8112. if (LD->getChain() != Base->getChain())
  8113. return false;
  8114. EVT VT = LD->getValueType(0);
  8115. if (VT.getSizeInBits() / 8 != Bytes)
  8116. return false;
  8117. auto BaseLocDecomp = BaseIndexOffset::match(Base, *this);
  8118. auto LocDecomp = BaseIndexOffset::match(LD, *this);
  8119. int64_t Offset = 0;
  8120. if (BaseLocDecomp.equalBaseIndex(LocDecomp, *this, Offset))
  8121. return (Dist * Bytes == Offset);
  8122. return false;
  8123. }
  8124. /// InferPtrAlignment - Infer alignment of a load / store address. Return 0 if
  8125. /// it cannot be inferred.
  8126. unsigned SelectionDAG::InferPtrAlignment(SDValue Ptr) const {
  8127. // If this is a GlobalAddress + cst, return the alignment.
  8128. const GlobalValue *GV;
  8129. int64_t GVOffset = 0;
  8130. if (TLI->isGAPlusOffset(Ptr.getNode(), GV, GVOffset)) {
  8131. unsigned IdxWidth = getDataLayout().getIndexTypeSizeInBits(GV->getType());
  8132. KnownBits Known(IdxWidth);
  8133. llvm::computeKnownBits(GV, Known, getDataLayout());
  8134. unsigned AlignBits = Known.countMinTrailingZeros();
  8135. unsigned Align = AlignBits ? 1 << std::min(31U, AlignBits) : 0;
  8136. if (Align)
  8137. return MinAlign(Align, GVOffset);
  8138. }
  8139. // If this is a direct reference to a stack slot, use information about the
  8140. // stack slot's alignment.
  8141. int FrameIdx = 1 << 31;
  8142. int64_t FrameOffset = 0;
  8143. if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr)) {
  8144. FrameIdx = FI->getIndex();
  8145. } else if (isBaseWithConstantOffset(Ptr) &&
  8146. isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
  8147. // Handle FI+Cst
  8148. FrameIdx = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
  8149. FrameOffset = Ptr.getConstantOperandVal(1);
  8150. }
  8151. if (FrameIdx != (1 << 31)) {
  8152. const MachineFrameInfo &MFI = getMachineFunction().getFrameInfo();
  8153. unsigned FIInfoAlign = MinAlign(MFI.getObjectAlignment(FrameIdx),
  8154. FrameOffset);
  8155. return FIInfoAlign;
  8156. }
  8157. return 0;
  8158. }
  8159. /// GetSplitDestVTs - Compute the VTs needed for the low/hi parts of a type
  8160. /// which is split (or expanded) into two not necessarily identical pieces.
  8161. std::pair<EVT, EVT> SelectionDAG::GetSplitDestVTs(const EVT &VT) const {
  8162. // Currently all types are split in half.
  8163. EVT LoVT, HiVT;
  8164. if (!VT.isVector())
  8165. LoVT = HiVT = TLI->getTypeToTransformTo(*getContext(), VT);
  8166. else
  8167. LoVT = HiVT = VT.getHalfNumVectorElementsVT(*getContext());
  8168. return std::make_pair(LoVT, HiVT);
  8169. }
  8170. /// SplitVector - Split the vector with EXTRACT_SUBVECTOR and return the
  8171. /// low/high part.
  8172. std::pair<SDValue, SDValue>
  8173. SelectionDAG::SplitVector(const SDValue &N, const SDLoc &DL, const EVT &LoVT,
  8174. const EVT &HiVT) {
  8175. assert(LoVT.getVectorNumElements() + HiVT.getVectorNumElements() <=
  8176. N.getValueType().getVectorNumElements() &&
  8177. "More vector elements requested than available!");
  8178. SDValue Lo, Hi;
  8179. Lo = getNode(ISD::EXTRACT_SUBVECTOR, DL, LoVT, N,
  8180. getConstant(0, DL, TLI->getVectorIdxTy(getDataLayout())));
  8181. Hi = getNode(ISD::EXTRACT_SUBVECTOR, DL, HiVT, N,
  8182. getConstant(LoVT.getVectorNumElements(), DL,
  8183. TLI->getVectorIdxTy(getDataLayout())));
  8184. return std::make_pair(Lo, Hi);
  8185. }
  8186. /// Widen the vector up to the next power of two using INSERT_SUBVECTOR.
  8187. SDValue SelectionDAG::WidenVector(const SDValue &N, const SDLoc &DL) {
  8188. EVT VT = N.getValueType();
  8189. EVT WideVT = EVT::getVectorVT(*getContext(), VT.getVectorElementType(),
  8190. NextPowerOf2(VT.getVectorNumElements()));
  8191. return getNode(ISD::INSERT_SUBVECTOR, DL, WideVT, getUNDEF(WideVT), N,
  8192. getConstant(0, DL, TLI->getVectorIdxTy(getDataLayout())));
  8193. }
  8194. void SelectionDAG::ExtractVectorElements(SDValue Op,
  8195. SmallVectorImpl<SDValue> &Args,
  8196. unsigned Start, unsigned Count) {
  8197. EVT VT = Op.getValueType();
  8198. if (Count == 0)
  8199. Count = VT.getVectorNumElements();
  8200. EVT EltVT = VT.getVectorElementType();
  8201. EVT IdxTy = TLI->getVectorIdxTy(getDataLayout());
  8202. SDLoc SL(Op);
  8203. for (unsigned i = Start, e = Start + Count; i != e; ++i) {
  8204. Args.push_back(getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
  8205. Op, getConstant(i, SL, IdxTy)));
  8206. }
  8207. }
  8208. // getAddressSpace - Return the address space this GlobalAddress belongs to.
  8209. unsigned GlobalAddressSDNode::getAddressSpace() const {
  8210. return getGlobal()->getType()->getAddressSpace();
  8211. }
  8212. Type *ConstantPoolSDNode::getType() const {
  8213. if (isMachineConstantPoolEntry())
  8214. return Val.MachineCPVal->getType();
  8215. return Val.ConstVal->getType();
  8216. }
  8217. bool BuildVectorSDNode::isConstantSplat(APInt &SplatValue, APInt &SplatUndef,
  8218. unsigned &SplatBitSize,
  8219. bool &HasAnyUndefs,
  8220. unsigned MinSplatBits,
  8221. bool IsBigEndian) const {
  8222. EVT VT = getValueType(0);
  8223. assert(VT.isVector() && "Expected a vector type");
  8224. unsigned VecWidth = VT.getSizeInBits();
  8225. if (MinSplatBits > VecWidth)
  8226. return false;
  8227. // FIXME: The widths are based on this node's type, but build vectors can
  8228. // truncate their operands.
  8229. SplatValue = APInt(VecWidth, 0);
  8230. SplatUndef = APInt(VecWidth, 0);
  8231. // Get the bits. Bits with undefined values (when the corresponding element
  8232. // of the vector is an ISD::UNDEF value) are set in SplatUndef and cleared
  8233. // in SplatValue. If any of the values are not constant, give up and return
  8234. // false.
  8235. unsigned int NumOps = getNumOperands();
  8236. assert(NumOps > 0 && "isConstantSplat has 0-size build vector");
  8237. unsigned EltWidth = VT.getScalarSizeInBits();
  8238. for (unsigned j = 0; j < NumOps; ++j) {
  8239. unsigned i = IsBigEndian ? NumOps - 1 - j : j;
  8240. SDValue OpVal = getOperand(i);
  8241. unsigned BitPos = j * EltWidth;
  8242. if (OpVal.isUndef())
  8243. SplatUndef.setBits(BitPos, BitPos + EltWidth);
  8244. else if (auto *CN = dyn_cast<ConstantSDNode>(OpVal))
  8245. SplatValue.insertBits(CN->getAPIntValue().zextOrTrunc(EltWidth), BitPos);
  8246. else if (auto *CN = dyn_cast<ConstantFPSDNode>(OpVal))
  8247. SplatValue.insertBits(CN->getValueAPF().bitcastToAPInt(), BitPos);
  8248. else
  8249. return false;
  8250. }
  8251. // The build_vector is all constants or undefs. Find the smallest element
  8252. // size that splats the vector.
  8253. HasAnyUndefs = (SplatUndef != 0);
  8254. // FIXME: This does not work for vectors with elements less than 8 bits.
  8255. while (VecWidth > 8) {
  8256. unsigned HalfSize = VecWidth / 2;
  8257. APInt HighValue = SplatValue.lshr(HalfSize).trunc(HalfSize);
  8258. APInt LowValue = SplatValue.trunc(HalfSize);
  8259. APInt HighUndef = SplatUndef.lshr(HalfSize).trunc(HalfSize);
  8260. APInt LowUndef = SplatUndef.trunc(HalfSize);
  8261. // If the two halves do not match (ignoring undef bits), stop here.
  8262. if ((HighValue & ~LowUndef) != (LowValue & ~HighUndef) ||
  8263. MinSplatBits > HalfSize)
  8264. break;
  8265. SplatValue = HighValue | LowValue;
  8266. SplatUndef = HighUndef & LowUndef;
  8267. VecWidth = HalfSize;
  8268. }
  8269. SplatBitSize = VecWidth;
  8270. return true;
  8271. }
  8272. SDValue BuildVectorSDNode::getSplatValue(const APInt &DemandedElts,
  8273. BitVector *UndefElements) const {
  8274. if (UndefElements) {
  8275. UndefElements->clear();
  8276. UndefElements->resize(getNumOperands());
  8277. }
  8278. assert(getNumOperands() == DemandedElts.getBitWidth() &&
  8279. "Unexpected vector size");
  8280. if (!DemandedElts)
  8281. return SDValue();
  8282. SDValue Splatted;
  8283. for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
  8284. if (!DemandedElts[i])
  8285. continue;
  8286. SDValue Op = getOperand(i);
  8287. if (Op.isUndef()) {
  8288. if (UndefElements)
  8289. (*UndefElements)[i] = true;
  8290. } else if (!Splatted) {
  8291. Splatted = Op;
  8292. } else if (Splatted != Op) {
  8293. return SDValue();
  8294. }
  8295. }
  8296. if (!Splatted) {
  8297. unsigned FirstDemandedIdx = DemandedElts.countTrailingZeros();
  8298. assert(getOperand(FirstDemandedIdx).isUndef() &&
  8299. "Can only have a splat without a constant for all undefs.");
  8300. return getOperand(FirstDemandedIdx);
  8301. }
  8302. return Splatted;
  8303. }
  8304. SDValue BuildVectorSDNode::getSplatValue(BitVector *UndefElements) const {
  8305. APInt DemandedElts = APInt::getAllOnesValue(getNumOperands());
  8306. return getSplatValue(DemandedElts, UndefElements);
  8307. }
  8308. ConstantSDNode *
  8309. BuildVectorSDNode::getConstantSplatNode(const APInt &DemandedElts,
  8310. BitVector *UndefElements) const {
  8311. return dyn_cast_or_null<ConstantSDNode>(
  8312. getSplatValue(DemandedElts, UndefElements));
  8313. }
  8314. ConstantSDNode *
  8315. BuildVectorSDNode::getConstantSplatNode(BitVector *UndefElements) const {
  8316. return dyn_cast_or_null<ConstantSDNode>(getSplatValue(UndefElements));
  8317. }
  8318. ConstantFPSDNode *
  8319. BuildVectorSDNode::getConstantFPSplatNode(const APInt &DemandedElts,
  8320. BitVector *UndefElements) const {
  8321. return dyn_cast_or_null<ConstantFPSDNode>(
  8322. getSplatValue(DemandedElts, UndefElements));
  8323. }
  8324. ConstantFPSDNode *
  8325. BuildVectorSDNode::getConstantFPSplatNode(BitVector *UndefElements) const {
  8326. return dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements));
  8327. }
  8328. int32_t
  8329. BuildVectorSDNode::getConstantFPSplatPow2ToLog2Int(BitVector *UndefElements,
  8330. uint32_t BitWidth) const {
  8331. if (ConstantFPSDNode *CN =
  8332. dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements))) {
  8333. bool IsExact;
  8334. APSInt IntVal(BitWidth);
  8335. const APFloat &APF = CN->getValueAPF();
  8336. if (APF.convertToInteger(IntVal, APFloat::rmTowardZero, &IsExact) !=
  8337. APFloat::opOK ||
  8338. !IsExact)
  8339. return -1;
  8340. return IntVal.exactLogBase2();
  8341. }
  8342. return -1;
  8343. }
  8344. bool BuildVectorSDNode::isConstant() const {
  8345. for (const SDValue &Op : op_values()) {
  8346. unsigned Opc = Op.getOpcode();
  8347. if (Opc != ISD::UNDEF && Opc != ISD::Constant && Opc != ISD::ConstantFP)
  8348. return false;
  8349. }
  8350. return true;
  8351. }
  8352. bool ShuffleVectorSDNode::isSplatMask(const int *Mask, EVT VT) {
  8353. // Find the first non-undef value in the shuffle mask.
  8354. unsigned i, e;
  8355. for (i = 0, e = VT.getVectorNumElements(); i != e && Mask[i] < 0; ++i)
  8356. /* search */;
  8357. assert(i != e && "VECTOR_SHUFFLE node with all undef indices!");
  8358. // Make sure all remaining elements are either undef or the same as the first
  8359. // non-undef value.
  8360. for (int Idx = Mask[i]; i != e; ++i)
  8361. if (Mask[i] >= 0 && Mask[i] != Idx)
  8362. return false;
  8363. return true;
  8364. }
  8365. // Returns the SDNode if it is a constant integer BuildVector
  8366. // or constant integer.
  8367. SDNode *SelectionDAG::isConstantIntBuildVectorOrConstantInt(SDValue N) {
  8368. if (isa<ConstantSDNode>(N))
  8369. return N.getNode();
  8370. if (ISD::isBuildVectorOfConstantSDNodes(N.getNode()))
  8371. return N.getNode();
  8372. // Treat a GlobalAddress supporting constant offset folding as a
  8373. // constant integer.
  8374. if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N))
  8375. if (GA->getOpcode() == ISD::GlobalAddress &&
  8376. TLI->isOffsetFoldingLegal(GA))
  8377. return GA;
  8378. return nullptr;
  8379. }
  8380. SDNode *SelectionDAG::isConstantFPBuildVectorOrConstantFP(SDValue N) {
  8381. if (isa<ConstantFPSDNode>(N))
  8382. return N.getNode();
  8383. if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode()))
  8384. return N.getNode();
  8385. return nullptr;
  8386. }
  8387. void SelectionDAG::createOperands(SDNode *Node, ArrayRef<SDValue> Vals) {
  8388. assert(!Node->OperandList && "Node already has operands");
  8389. assert(SDNode::getMaxNumOperands() >= Vals.size() &&
  8390. "too many operands to fit into SDNode");
  8391. SDUse *Ops = OperandRecycler.allocate(
  8392. ArrayRecycler<SDUse>::Capacity::get(Vals.size()), OperandAllocator);
  8393. bool IsDivergent = false;
  8394. for (unsigned I = 0; I != Vals.size(); ++I) {
  8395. Ops[I].setUser(Node);
  8396. Ops[I].setInitial(Vals[I]);
  8397. if (Ops[I].Val.getValueType() != MVT::Other) // Skip Chain. It does not carry divergence.
  8398. IsDivergent = IsDivergent || Ops[I].getNode()->isDivergent();
  8399. }
  8400. Node->NumOperands = Vals.size();
  8401. Node->OperandList = Ops;
  8402. IsDivergent |= TLI->isSDNodeSourceOfDivergence(Node, FLI, DA);
  8403. if (!TLI->isSDNodeAlwaysUniform(Node))
  8404. Node->SDNodeBits.IsDivergent = IsDivergent;
  8405. checkForCycles(Node);
  8406. }
  8407. SDValue SelectionDAG::getTokenFactor(const SDLoc &DL,
  8408. SmallVectorImpl<SDValue> &Vals) {
  8409. size_t Limit = SDNode::getMaxNumOperands();
  8410. while (Vals.size() > Limit) {
  8411. unsigned SliceIdx = Vals.size() - Limit;
  8412. auto ExtractedTFs = ArrayRef<SDValue>(Vals).slice(SliceIdx, Limit);
  8413. SDValue NewTF = getNode(ISD::TokenFactor, DL, MVT::Other, ExtractedTFs);
  8414. Vals.erase(Vals.begin() + SliceIdx, Vals.end());
  8415. Vals.emplace_back(NewTF);
  8416. }
  8417. return getNode(ISD::TokenFactor, DL, MVT::Other, Vals);
  8418. }
  8419. #ifndef NDEBUG
  8420. static void checkForCyclesHelper(const SDNode *N,
  8421. SmallPtrSetImpl<const SDNode*> &Visited,
  8422. SmallPtrSetImpl<const SDNode*> &Checked,
  8423. const llvm::SelectionDAG *DAG) {
  8424. // If this node has already been checked, don't check it again.
  8425. if (Checked.count(N))
  8426. return;
  8427. // If a node has already been visited on this depth-first walk, reject it as
  8428. // a cycle.
  8429. if (!Visited.insert(N).second) {
  8430. errs() << "Detected cycle in SelectionDAG\n";
  8431. dbgs() << "Offending node:\n";
  8432. N->dumprFull(DAG); dbgs() << "\n";
  8433. abort();
  8434. }
  8435. for (const SDValue &Op : N->op_values())
  8436. checkForCyclesHelper(Op.getNode(), Visited, Checked, DAG);
  8437. Checked.insert(N);
  8438. Visited.erase(N);
  8439. }
  8440. #endif
  8441. void llvm::checkForCycles(const llvm::SDNode *N,
  8442. const llvm::SelectionDAG *DAG,
  8443. bool force) {
  8444. #ifndef NDEBUG
  8445. bool check = force;
  8446. #ifdef EXPENSIVE_CHECKS
  8447. check = true;
  8448. #endif // EXPENSIVE_CHECKS
  8449. if (check) {
  8450. assert(N && "Checking nonexistent SDNode");
  8451. SmallPtrSet<const SDNode*, 32> visited;
  8452. SmallPtrSet<const SDNode*, 32> checked;
  8453. checkForCyclesHelper(N, visited, checked, DAG);
  8454. }
  8455. #endif // !NDEBUG
  8456. }
  8457. void llvm::checkForCycles(const llvm::SelectionDAG *DAG, bool force) {
  8458. checkForCycles(DAG->getRoot().getNode(), DAG, force);
  8459. }